Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

aroundthecode / zope.interface   python

Repository URL to install this package:

Version: 4.6.0 

/ interface / tests / test_interface.py

##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Test Interface implementation
"""
# pylint:disable=protected-access
import unittest

from zope.interface._compat import _skip_under_py3k

_marker = object()


class Test_invariant(unittest.TestCase):

    def test_w_single(self):
        from zope.interface.interface import invariant
        from zope.interface.interface import TAGGED_DATA

        def _check(*args, **kw):
            raise NotImplementedError()

        class Foo(object):
            invariant(_check)

        self.assertEqual(getattr(Foo, TAGGED_DATA, None),
                         {'invariants': [_check]})

    def test_w_multiple(self):
        from zope.interface.interface import invariant
        from zope.interface.interface import TAGGED_DATA

        def _check(*args, **kw):
            raise NotImplementedError()

        def _another_check(*args, **kw):
            raise NotImplementedError()

        class Foo(object):
            invariant(_check)
            invariant(_another_check)

        self.assertEqual(getattr(Foo, TAGGED_DATA, None),
                         {'invariants': [_check, _another_check]})


class Test_taggedValue(unittest.TestCase):

    def test_w_single(self):
        from zope.interface.interface import taggedValue
        from zope.interface.interface import TAGGED_DATA

        class Foo(object):
            taggedValue('bar', ['baz'])

        self.assertEqual(getattr(Foo, TAGGED_DATA, None),
                         {'bar': ['baz']})

    def test_w_multiple(self):
        from zope.interface.interface import taggedValue
        from zope.interface.interface import TAGGED_DATA

        class Foo(object):
            taggedValue('bar', ['baz'])
            taggedValue('qux', 'spam')

        self.assertEqual(getattr(Foo, TAGGED_DATA, None),
                         {'bar': ['baz'], 'qux': 'spam'})

    def test_w_multiple_overwriting(self):
        from zope.interface.interface import taggedValue
        from zope.interface.interface import TAGGED_DATA

        class Foo(object):
            taggedValue('bar', ['baz'])
            taggedValue('qux', 'spam')
            taggedValue('bar', 'frob')

        self.assertEqual(getattr(Foo, TAGGED_DATA, None),
                         {'bar': 'frob', 'qux': 'spam'})


class ElementTests(unittest.TestCase):

    DEFAULT_NAME = 'AnElement'

    def _getTargetClass(self):
        from zope.interface.interface import Element
        return Element

    def _makeOne(self,  name=None):
        if name is None:
            name = self.DEFAULT_NAME
        return self._getTargetClass()(name)

    def test_ctor_defaults(self):
        element = self._makeOne()
        self.assertEqual(element.__name__, self.DEFAULT_NAME)
        self.assertEqual(element.getName(), self.DEFAULT_NAME)
        self.assertEqual(element.__doc__, '')
        self.assertEqual(element.getDoc(), '')
        self.assertEqual(list(element.getTaggedValueTags()), [])

    def test_ctor_no_doc_space_in_name(self):
        element = self._makeOne('An Element')
        self.assertEqual(element.__name__, None)
        self.assertEqual(element.__doc__, 'An Element')

    def test_getTaggedValue_miss(self):
        element = self._makeOne()
        self.assertRaises(KeyError, element.getTaggedValue, 'nonesuch')

    def test_queryTaggedValue_miss(self):
        element = self._makeOne()
        self.assertEqual(element.queryTaggedValue('nonesuch'), None)

    def test_queryTaggedValue_miss_w_default(self):
        element = self._makeOne()
        self.assertEqual(element.queryTaggedValue('nonesuch', 'bar'), 'bar')

    def test_setTaggedValue(self):
        element = self._makeOne()
        element.setTaggedValue('foo', 'bar')
        self.assertEqual(list(element.getTaggedValueTags()), ['foo'])
        self.assertEqual(element.getTaggedValue('foo'), 'bar')
        self.assertEqual(element.queryTaggedValue('foo'), 'bar')


class SpecificationBasePyTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.interface import SpecificationBasePy
        return SpecificationBasePy

    def _makeOne(self):
        return self._getTargetClass()()

    def test_providedBy_miss(self):
        from zope.interface import interface
        from zope.interface.declarations import _empty
        sb = self._makeOne()
        def _providedBy(obj):
            return _empty
        with _Monkey(interface, providedBy=_providedBy):
            self.assertFalse(sb.providedBy(object()))

    def test_providedBy_hit(self):
        from zope.interface import interface
        sb = self._makeOne()
        class _Decl(object):
            _implied = {sb: {},}
        def _providedBy(obj):
            return _Decl()
        with _Monkey(interface, providedBy=_providedBy):
            self.assertTrue(sb.providedBy(object()))

    def test_implementedBy_miss(self):
        from zope.interface import interface
        from zope.interface.declarations import _empty
        sb = self._makeOne()
        def _implementedBy(obj):
            return _empty
        with _Monkey(interface, implementedBy=_implementedBy):
            self.assertFalse(sb.implementedBy(object()))

    def test_implementedBy_hit(self):
        from zope.interface import interface
        sb = self._makeOne()
        class _Decl(object):
            _implied = {sb: {},}
        def _implementedBy(obj):
            return _Decl()
        with _Monkey(interface, implementedBy=_implementedBy):
            self.assertTrue(sb.implementedBy(object()))

    def test_isOrExtends_miss(self):
        sb = self._makeOne()
        sb._implied = {}  # not defined by SpecificationBasePy
        self.assertFalse(sb.isOrExtends(object()))

    def test_isOrExtends_hit(self):
        sb = self._makeOne()
        testing = object()
        sb._implied = {testing: {}}  # not defined by SpecificationBasePy
        self.assertTrue(sb(testing))

    def test___call___miss(self):
        sb = self._makeOne()
        sb._implied = {}  # not defined by SpecificationBasePy
        self.assertFalse(sb.isOrExtends(object()))

    def test___call___hit(self):
        sb = self._makeOne()
        testing = object()
        sb._implied = {testing: {}}  # not defined by SpecificationBasePy
        self.assertTrue(sb(testing))


class SpecificationBaseTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.interface import SpecificationBase
        return SpecificationBase

    def test_optimizations(self):
        from zope.interface.interface import SpecificationBasePy
        try:
            import zope.interface._zope_interface_coptimizations
        except ImportError:
            self.assertIs(self._getTargetClass(), SpecificationBasePy)
        else:
            self.assertIsNot(self._getTargetClass(), SpecificationBasePy)


class InterfaceBasePyTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.interface import InterfaceBasePy
        return InterfaceBasePy

    def _makeOne(self, object_should_provide):
        class IB(self._getTargetClass()):
            def _call_conform(self, conform):
                return conform(self)
            def providedBy(self, obj):
                return object_should_provide
        return IB()

    def test___call___w___conform___returning_value(self):
        ib = self._makeOne(False)
        conformed = object()
        class _Adapted(object):
            def __conform__(self, iface):
                return conformed
        self.assertTrue(ib(_Adapted()) is conformed)

    def test___call___w___conform___miss_ob_provides(self):
        ib = self._makeOne(True)
        class _Adapted(object):
            def __conform__(self, iface):
                return None
        adapted = _Adapted()
        self.assertTrue(ib(adapted) is adapted)

    def test___call___wo___conform___ob_no_provides_w_alternate(self):
        ib = self._makeOne(False)
        adapted = object()
        alternate = object()
        self.assertTrue(ib(adapted, alternate) is alternate)

    def test___call___w___conform___ob_no_provides_wo_alternate(self):
        ib = self._makeOne(False)
        adapted = object()
        self.assertRaises(TypeError, ib, adapted)

    def test___adapt___ob_provides(self):
        ib = self._makeOne(True)
        adapted = object()
        self.assertTrue(ib.__adapt__(adapted) is adapted)

    def test___adapt___ob_no_provides_uses_hooks(self):
        from zope.interface import interface
        ib = self._makeOne(False)
        adapted = object()
        _missed = []
        def _hook_miss(iface, obj):
            _missed.append((iface, obj))
            return None
        def _hook_hit(iface, obj):
            return obj
        with _Monkey(interface, adapter_hooks=[_hook_miss, _hook_hit]):
            self.assertTrue(ib.__adapt__(adapted) is adapted)
            self.assertEqual(_missed, [(ib, adapted)])


class InterfaceBaseTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.interface import InterfaceBase
        return InterfaceBase

    def test_optimizations(self):
        from zope.interface.interface import InterfaceBasePy
        try:
            import zope.interface._zope_interface_coptimizations
        except ImportError:
            self.assertIs(self._getTargetClass(), InterfaceBasePy)
        else:
            self.assertIsNot(self._getTargetClass(), InterfaceBasePy)


class SpecificationTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.interface import Specification
        return Specification

    def _makeOne(self, bases=_marker):
        if bases is _marker:
            return self._getTargetClass()()
        return self._getTargetClass()(bases)

    def test_ctor(self):
        from zope.interface.interface import Interface
        spec = self._makeOne()
        self.assertEqual(spec.__bases__, ())
        self.assertEqual(len(spec._implied), 2)
        self.assertTrue(spec in spec._implied)
        self.assertTrue(Interface in spec._implied)
        self.assertEqual(len(spec.dependents), 0)

    def test_subscribe_first_time(self):
        spec = self._makeOne()
        dep = DummyDependent()
        spec.subscribe(dep)
        self.assertEqual(len(spec.dependents), 1)
        self.assertEqual(spec.dependents[dep], 1)

    def test_subscribe_again(self):
        spec = self._makeOne()
        dep = DummyDependent()
        spec.subscribe(dep)
        spec.subscribe(dep)
        self.assertEqual(spec.dependents[dep], 2)

    def test_unsubscribe_miss(self):
        spec = self._makeOne()
        dep = DummyDependent()
        self.assertRaises(KeyError, spec.unsubscribe, dep)

    def test_unsubscribe(self):
        spec = self._makeOne()
        dep = DummyDependent()
        spec.subscribe(dep)
        spec.subscribe(dep)
Loading ...