Python abc 模块,abstractmethod() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用abc.abstractmethod()

项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def setUpClass(cls):
        FinalABCMeta = final_meta_factory(ABCMeta)

        class ABCWithFinal(with_metaclass(FinalABCMeta, object)):
            a = final('ABCWithFinal: a')
            b = 'ABCWithFinal: b'

            @final
            def f(self):
                return 'ABCWithFinal: f'

            def g(self):
                return 'ABCWithFinal: g'

            @abstractmethod
            def h(self):
                raise NotImplementedError('h')

        cls.class_ = ABCWithFinal
项目:sketchbook    作者:futursolo    | 项目源码 | 文件源码
def _find_abs_path(
        self, skt_path: str,
            origin_path: Optional[str]=None) -> str:  # pragma: no cover
        """
        This is an :func:`abc.abstractmethod`.

        Override this method to customize sketch discovery.

        Solve the absolute path(starting with :code:`/`) of the sketch from
        the skt_path based on the origin_path(if applicable).

        .. important::

            If no matched file is found, it should raise a
            :class:`.SketchNotFoundError`.
        """
        raise NotImplementedError
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def setUpClass(cls):
        FinalABCMeta = compose_types(FinalMeta, ABCMeta)

        class ABCWithFinal(with_metaclass(FinalABCMeta, object)):
            a = final('ABCWithFinal: a')
            b = 'ABCWithFinal: b'

            @final
            def f(self):
                return 'ABCWithFinal: f'

            def g(self):
                return 'ABCWithFinal: g'

            @abstractmethod
            def h(self):
                raise NotImplementedError('h')

        cls.class_ = ABCWithFinal
项目:qiime2    作者:qiime2    | 项目源码 | 文件源码
def validate(self, level='max'):
        _check_validation_level(level)

        if not self.path.is_file():
            raise ValidationError("%s is not a file." % self.path)

        if hasattr(self, '_validate_'):
            try:
                self._validate_(level)
            except ValidationError as e:
                raise ValidationError(
                    "%s is not a(n) %s file:\n\n%s"
                    % (self.path, self.__class__.__name__, str(e))
                    ) from e
        # TODO: remove this branch
        elif hasattr(self, 'sniff'):
            if not self.sniff():
                raise ValidationError("%s is not a(n) %s file"
                                      % (self.path, self.__class__.__name__))

        # TODO: define an abc.abstractmethod for `validate` when sniff is
        # removed instead of this
        else:
            raise NotImplementedError("%r does not implement validate."
                                      % type(self))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_cache_leak(self):
        # See issue #2521.
        class A(object):
            __metaclass__ = abc.ABCMeta
            @abc.abstractmethod
            def f(self):
                pass
        class C(A):
            def f(self):
                A.f(self)
        r = weakref.ref(C)
        # Trigger cache.
        C().f()
        del C
        test_support.gc_collect()
        self.assertEqual(r(), None)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_cache_leak(self):
        # See issue #2521.
        class A(object):
            __metaclass__ = abc.ABCMeta
            @abc.abstractmethod
            def f(self):
                pass
        class C(A):
            def f(self):
                A.f(self)
        r = weakref.ref(C)
        # Trigger cache.
        C().f()
        del C
        test_support.gc_collect()
        self.assertEqual(r(), None)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_abstractproperty_basics(self):
        @property
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @property
            @abc.abstractmethod
            def foo(self): return 3
        self.assertRaises(TypeError, C)
        class D(C):
            @C.foo.getter
            def foo(self): return super().foo
        self.assertEqual(D().foo, 3)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_abstractclassmethod_basics(self):
        @classmethod
        @abc.abstractmethod
        def foo(cls): pass
        self.assertTrue(foo.__isabstractmethod__)
        @classmethod
        def bar(cls): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D')
        self.assertEqual(D().foo(), 'D')
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_abstractstaticmethod_basics(self):
        @staticmethod
        @abc.abstractmethod
        def foo(): pass
        self.assertTrue(foo.__isabstractmethod__)
        @staticmethod
        def bar(): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @staticmethod
            @abc.abstractmethod
            def foo(): return 3
        self.assertRaises(TypeError, C)
        class D(C):
            @staticmethod
            def foo(): return 4
        self.assertEqual(D.foo(), 4)
        self.assertEqual(D().foo(), 4)
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_cache_leak(self):
        # See issue #2521.
        class A(object):
            __metaclass__ = abc.ABCMeta
            @abc.abstractmethod
            def f(self):
                pass
        class C(A):
            def f(self):
                A.f(self)
        r = weakref.ref(C)
        # Trigger cache.
        C().f()
        del C
        test_support.gc_collect()
        self.assertEqual(r(), None)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_abstractproperty_basics(self):
        @property
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @property
            @abc.abstractmethod
            def foo(self): return 3
        self.assertRaises(TypeError, C)
        class D(C):
            @C.foo.getter
            def foo(self): return super().foo
        self.assertEqual(D().foo, 3)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_abstractclassmethod_basics(self):
        @classmethod
        @abc.abstractmethod
        def foo(cls): pass
        self.assertTrue(foo.__isabstractmethod__)
        @classmethod
        def bar(cls): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D')
        self.assertEqual(D().foo(), 'D')
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_abstractstaticmethod_basics(self):
        @staticmethod
        @abc.abstractmethod
        def foo(): pass
        self.assertTrue(foo.__isabstractmethod__)
        @staticmethod
        def bar(): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @staticmethod
            @abc.abstractmethod
            def foo(): return 3
        self.assertRaises(TypeError, C)
        class D(C):
            @staticmethod
            def foo(): return 4
        self.assertEqual(D.foo(), 4)
        self.assertEqual(D().foo(), 4)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_cache_leak(self):
        # See issue #2521.
        class A(object):
            __metaclass__ = abc.ABCMeta
            @abc.abstractmethod
            def f(self):
                pass
        class C(A):
            def f(self):
                A.f(self)
        r = weakref.ref(C)
        # Trigger cache.
        C().f()
        del C
        test_support.gc_collect()
        self.assertEqual(r(), None)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_abstractproperty_basics(self):
        @property
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @property
            @abc.abstractmethod
            def foo(self): return 3
        self.assertRaises(TypeError, C)
        class D(C):
            @C.foo.getter
            def foo(self): return super().foo
        self.assertEqual(D().foo, 3)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_abstractclassmethod_basics(self):
        @classmethod
        @abc.abstractmethod
        def foo(cls): pass
        self.assertTrue(foo.__isabstractmethod__)
        @classmethod
        def bar(cls): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D')
        self.assertEqual(D().foo(), 'D')
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_abstractstaticmethod_basics(self):
        @staticmethod
        @abc.abstractmethod
        def foo(): pass
        self.assertTrue(foo.__isabstractmethod__)
        @staticmethod
        def bar(): pass
        self.assertFalse(getattr(bar, "__isabstractmethod__", False))

        class C(metaclass=abc.ABCMeta):
            @staticmethod
            @abc.abstractmethod
            def foo(): return 3
        self.assertRaises(TypeError, C)
        class D(C):
            @staticmethod
            def foo(): return 4
        self.assertEqual(D.foo(), 4)
        self.assertEqual(D().foo(), 4)
项目:multimedia_crawler    作者:JFluo2011    | 项目源码 | 文件源码
def __init__(self, logger, page_url, *args, **kwargs):
        self.json_data = None
        self.media_urls = None
        self.file_name = ''
        self.logger = logger
        self.page_url = page_url
        self.args = args
        self.kwargs = kwargs

    # @abc.abstractmethod
    # def get_params(self):
    #     pass
    #
    # @abc.abstractmethod
    # def get_video_info(self, response):
    #     pass
项目:aws-encryption-sdk-python    作者:awslabs    | 项目源码 | 文件源码
def __new__(cls, **kwargs):
        """Patch for abstractmethod-like enforcement in io.IOBase grandchildren."""
        if (
                not (hasattr(cls, '_read_bytes') and callable(cls._read_bytes))
                or not (hasattr(cls, '_prep_message') and callable(cls._read_bytes))
                or not hasattr(cls, '_config_class')
        ):
            raise TypeError("Can't instantiate abstract class {}".format(cls.__name__))

        instance = super(_EncryptionStream, cls).__new__(cls)

        config = kwargs.pop('config', None)
        if not isinstance(config, instance._config_class):  # pylint: disable=protected-access
            config = instance._config_class(**kwargs)  # pylint: disable=protected-access
        instance.config = config

        instance.bytes_read = 0
        instance.output_buffer = b''
        instance._message_prepped = False  # pylint: disable=protected-access
        instance.source_stream = instance.config.source
        instance._stream_length = instance.config.source_length  # pylint: disable=protected-access

        return instance
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def test_cannot_instantiate_subclass(self):
        """
        Tests that you cannot create an instance of a subclass
        that does not implement the abstractmethod h.
        """
        class AbstractSubClass(self.class_):
            pass

        with self.assertRaises(TypeError):
            AbstractSubClass()
项目:Leics    作者:LeicsFrameWork    | 项目源码 | 文件源码
def test_abstract_subclasses(self):
            AbstractSubclass = ABCMeta(
                'AbstractSubclass',
                (greenlet,),
                {'run': abstractmethod(lambda self: None)})

            class BadSubclass(AbstractSubclass):
                pass

            class GoodSubclass(AbstractSubclass):
                def run(self):
                    pass

            GoodSubclass() # should not raise
            self.assertRaises(TypeError, BadSubclass)
项目:arclib    作者:kirbyfan64    | 项目源码 | 文件源码
def _uabstractmethod(f):
    @_wraps(f)
    def func(*args): raise NotImplementedError()
    return _abstractmethod(func)
项目:sketchbook    作者:futursolo    | 项目源码 | 文件源码
def _load_sketch_content(
            self, skt_path: str) -> Union[str, bytes]:  # pragma: no cover
        """
        This is an :func:`abc.abstractmethod`.

        Override this method to customize sketch loading.

        Load the sketch content as string or bytestring.

        .. important::

            If no matched file is found, it should raise a
            :class:`.SketchNotFoundError`.
        """
        raise NotImplementedError
项目:exchangelib    作者:ecederstrand    | 项目源码 | 文件源码
def __init__(self, protocol):
        self.protocol = protocol

    # The following two methods are the minimum required to be implemented by subclasses, but the name and number of
    # kwargs differs between services. Therefore, we cannot make these methods abstract.

    # @abc.abstractmethod
    # def call(self, **kwargs):
    #     raise NotImplementedError()

    # @abc.abstractmethod
    # def get_payload(self, **kwargs):
    #     raise NotImplementedError()
项目:creator-system-test-framework    作者:CreatorDev    | 项目源码 | 文件源码
def GetResourceType(self, resourceDefinition):
        return

#     @abc.abstractmethod
#     def GetResourceSupportedOperations(self, resourceDefinition):
#         return
#
项目:creator-system-test-framework    作者:CreatorDev    | 项目源码 | 文件源码
def DefineWithSession(self, session, objectDefinitionSettings, resourceDefinitionSettingsCollection):
        return

#     @abc.abstractmethod
#     def CreateObjectDefinitionIterator(self, session):
#         return
#
#     @abc.abstractmethod
#     def GetNextObjectDefinitionFromIterator(self, iterator):
#         return
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def test_cannot_instantiate_subclass(self):
        """
        Tests that you cannot create an instance of a subclass
        that does not implement the abstractmethod h.
        """
        class AbstractSubClass(self.class_):
            pass

        with self.assertRaises(TypeError):
            AbstractSubClass()
项目:myautotest    作者:auuppp    | 项目源码 | 文件源码
def clear_auth(self):
        """Clear access cache

        Can be called to clear the access cache so that next request
        will fetch a new token and base_url.
        """
        self.cache = None
        self.credentials.reset()

    #@abc.abstractmethod
    #ef is_expired(self, auth_data):
    #    return
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_abstractmethod_basics(self):
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_abstractmethod_integration(self):
        for abstractthing in [abc.abstractmethod, abc.abstractproperty,
                              abc.abstractclassmethod,
                              abc.abstractstaticmethod]:
            class C(metaclass=abc.ABCMeta):
                @abstractthing
                def foo(self): pass  # abstract
                def bar(self): pass  # concrete
            self.assertEqual(C.__abstractmethods__, {"foo"})
            self.assertRaises(TypeError, C)  # because foo is abstract
            self.assertTrue(isabstract(C))
            class D(C):
                def bar(self): pass  # concrete override of concrete
            self.assertEqual(D.__abstractmethods__, {"foo"})
            self.assertRaises(TypeError, D)  # because foo is still abstract
            self.assertTrue(isabstract(D))
            class E(D):
                def foo(self): pass
            self.assertEqual(E.__abstractmethods__, set())
            E()  # now foo is concrete, too
            self.assertFalse(isabstract(E))
            class F(E):
                @abstractthing
                def bar(self): pass  # abstract override of concrete
            self.assertEqual(F.__abstractmethods__, {"bar"})
            self.assertRaises(TypeError, F)  # because bar is abstract now
            self.assertTrue(isabstract(F))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_metaclass_abc(self):
        # Metaclasses can be ABCs, too.
        class A(metaclass=abc.ABCMeta):
            @abc.abstractmethod
            def x(self):
                pass
        self.assertEqual(A.__abstractmethods__, {"x"})
        class meta(type, A):
            def x(self):
                return 1
        class C(metaclass=meta):
            pass
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_abstractmethod_basics(self):
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_abstractmethod_integration(self):
        for abstractthing in [abc.abstractmethod, abc.abstractproperty]:
            class C:
                __metaclass__ = abc.ABCMeta
                @abstractthing
                def foo(self): pass  # abstract
                def bar(self): pass  # concrete
            self.assertEqual(C.__abstractmethods__, set(["foo"]))
            self.assertRaises(TypeError, C)  # because foo is abstract
            self.assertTrue(isabstract(C))
            class D(C):
                def bar(self): pass  # concrete override of concrete
            self.assertEqual(D.__abstractmethods__, set(["foo"]))
            self.assertRaises(TypeError, D)  # because foo is still abstract
            self.assertTrue(isabstract(D))
            class E(D):
                def foo(self): pass
            self.assertEqual(E.__abstractmethods__, set())
            E()  # now foo is concrete, too
            self.assertFalse(isabstract(E))
            class F(E):
                @abstractthing
                def bar(self): pass  # abstract override of concrete
            self.assertEqual(F.__abstractmethods__, set(["bar"]))
            self.assertRaises(TypeError, F)  # because bar is abstract now
            self.assertTrue(isabstract(F))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_abstractmethod_basics(self):
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_abstractmethod_integration(self):
        for abstractthing in [abc.abstractmethod, abc.abstractproperty]:
            class C:
                __metaclass__ = abc.ABCMeta
                @abstractthing
                def foo(self): pass  # abstract
                def bar(self): pass  # concrete
            self.assertEqual(C.__abstractmethods__, set(["foo"]))
            self.assertRaises(TypeError, C)  # because foo is abstract
            self.assertTrue(isabstract(C))
            class D(C):
                def bar(self): pass  # concrete override of concrete
            self.assertEqual(D.__abstractmethods__, set(["foo"]))
            self.assertRaises(TypeError, D)  # because foo is still abstract
            self.assertTrue(isabstract(D))
            class E(D):
                def foo(self): pass
            self.assertEqual(E.__abstractmethods__, set())
            E()  # now foo is concrete, too
            self.assertFalse(isabstract(E))
            class F(E):
                @abstractthing
                def bar(self): pass  # abstract override of concrete
            self.assertEqual(F.__abstractmethods__, set(["bar"]))
            self.assertRaises(TypeError, F)  # because bar is abstract now
            self.assertTrue(isabstract(F))
项目:Callandtext    作者:iaora    | 项目源码 | 文件源码
def abstractmethod(func):
        return func
#    def abstractproperty():
#        return None
项目:ProsperWarehouse    作者:EVEprosper    | 项目源码 | 文件源码
def _set_info(self):
        '''save useful info about table/datasource'''
        pass

    #@abc.abstractmethod
    #def get_connection(self):
    #    '''get con[nection] for database handles'''
    #    pass
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def abstractmethod(self):
    return self

### ONE-TRICK PONIES ###


#class Iterable(metaclass=ABCMeta):
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_abstractmethod_basics(self):
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_descriptors_with_abstractmethod(self):
        class C(metaclass=abc.ABCMeta):
            @property
            @abc.abstractmethod
            def foo(self): return 3
            @foo.setter
            @abc.abstractmethod
            def foo(self, val): pass
        self.assertRaises(TypeError, C)
        class D(C):
            @C.foo.getter
            def foo(self): return super().foo
        self.assertRaises(TypeError, D)
        class E(D):
            @D.foo.setter
            def foo(self, val): pass
        self.assertEqual(E().foo, 3)
        # check that the property's __isabstractmethod__ descriptor does the
        # right thing when presented with a value that fails truth testing:
        class NotBool(object):
            def __nonzero__(self):
                raise ValueError()
            __len__ = __nonzero__
        with self.assertRaises(ValueError):
            class F(C):
                def bar(self):
                    pass
                bar.__isabstractmethod__ = NotBool()
                foo = property(bar)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_customdescriptors_with_abstractmethod(self):
        class Descriptor:
            def __init__(self, fget, fset=None):
                self._fget = fget
                self._fset = fset
            def getter(self, callable):
                return Descriptor(callable, self._fget)
            def setter(self, callable):
                return Descriptor(self._fget, callable)
            @property
            def __isabstractmethod__(self):
                return (getattr(self._fget, '__isabstractmethod__', False)
                        or getattr(self._fset, '__isabstractmethod__', False))
        class C(metaclass=abc.ABCMeta):
            @Descriptor
            @abc.abstractmethod
            def foo(self): return 3
            @foo.setter
            @abc.abstractmethod
            def foo(self, val): pass
        self.assertRaises(TypeError, C)
        class D(C):
            @C.foo.getter
            def foo(self): return super().foo
        self.assertRaises(TypeError, D)
        class E(D):
            @D.foo.setter
            def foo(self, val): pass
        self.assertFalse(E.foo.__isabstractmethod__)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_metaclass_abc(self):
        # Metaclasses can be ABCs, too.
        class A(metaclass=abc.ABCMeta):
            @abc.abstractmethod
            def x(self):
                pass
        self.assertEqual(A.__abstractmethods__, {"x"})
        class meta(type, A):
            def x(self):
                return 1
        class C(metaclass=meta):
            pass
项目:pman    作者:FNNDSC    | 项目源码 | 文件源码
def __iter__(self):
        yield('Feed', dict(self._stree.snode_root))

    # @abc.abstractmethod
    # def create(self, **kwargs):
    #     """Create a new tree
    #
    #     """
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_abstractmethod_basics(self):
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_abstractmethod_integration(self):
        for abstractthing in [abc.abstractmethod, abc.abstractproperty]:
            class C:
                __metaclass__ = abc.ABCMeta
                @abstractthing
                def foo(self): pass  # abstract
                def bar(self): pass  # concrete
            self.assertEqual(C.__abstractmethods__, set(["foo"]))
            self.assertRaises(TypeError, C)  # because foo is abstract
            self.assertTrue(isabstract(C))
            class D(C):
                def bar(self): pass  # concrete override of concrete
            self.assertEqual(D.__abstractmethods__, set(["foo"]))
            self.assertRaises(TypeError, D)  # because foo is still abstract
            self.assertTrue(isabstract(D))
            class E(D):
                def foo(self): pass
            self.assertEqual(E.__abstractmethods__, set())
            E()  # now foo is concrete, too
            self.assertFalse(isabstract(E))
            class F(E):
                @abstractthing
                def bar(self): pass  # abstract override of concrete
            self.assertEqual(F.__abstractmethods__, set(["bar"]))
            self.assertRaises(TypeError, F)  # because bar is abstract now
            self.assertTrue(isabstract(F))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_ABC_helper(self):
        # create an ABC using the helper class and perform basic checks
        class C(abc.ABC):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertEqual(type(C), abc.ABCMeta)
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D')
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_abstractmethod_basics(self):
        @abc.abstractmethod
        def foo(self): pass
        self.assertTrue(foo.__isabstractmethod__)
        def bar(self): pass
        self.assertFalse(hasattr(bar, "__isabstractmethod__"))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_descriptors_with_abstractmethod(self):
        class C(metaclass=abc.ABCMeta):
            @property
            @abc.abstractmethod
            def foo(self): return 3
            @foo.setter
            @abc.abstractmethod
            def foo(self, val): pass
        self.assertRaises(TypeError, C)
        class D(C):
            @C.foo.getter
            def foo(self): return super().foo
        self.assertRaises(TypeError, D)
        class E(D):
            @D.foo.setter
            def foo(self, val): pass
        self.assertEqual(E().foo, 3)
        # check that the property's __isabstractmethod__ descriptor does the
        # right thing when presented with a value that fails truth testing:
        class NotBool(object):
            def __bool__(self):
                raise ValueError()
            __len__ = __bool__
        with self.assertRaises(ValueError):
            class F(C):
                def bar(self):
                    pass
                bar.__isabstractmethod__ = NotBool()
                foo = property(bar)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_customdescriptors_with_abstractmethod(self):
        class Descriptor:
            def __init__(self, fget, fset=None):
                self._fget = fget
                self._fset = fset
            def getter(self, callable):
                return Descriptor(callable, self._fget)
            def setter(self, callable):
                return Descriptor(self._fget, callable)
            @property
            def __isabstractmethod__(self):
                return (getattr(self._fget, '__isabstractmethod__', False)
                        or getattr(self._fset, '__isabstractmethod__', False))
        class C(metaclass=abc.ABCMeta):
            @Descriptor
            @abc.abstractmethod
            def foo(self): return 3
            @foo.setter
            @abc.abstractmethod
            def foo(self, val): pass
        self.assertRaises(TypeError, C)
        class D(C):
            @C.foo.getter
            def foo(self): return super().foo
        self.assertRaises(TypeError, D)
        class E(D):
            @D.foo.setter
            def foo(self, val): pass
        self.assertFalse(E.foo.__isabstractmethod__)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_metaclass_abc(self):
        # Metaclasses can be ABCs, too.
        class A(metaclass=abc.ABCMeta):
            @abc.abstractmethod
            def x(self):
                pass
        self.assertEqual(A.__abstractmethods__, {"x"})
        class meta(type, A):
            def x(self):
                return 1
        class C(metaclass=meta):
            pass