Search code examples
pythonunit-testingpython-2.7nosetestspython-unittest

Testing abstract classes in Python


Consider the following scenario.

import six
from abc import ABCMeta, abstractmethod


class ThisIsAnAbstractClass(six.with_metaclass(ABCMeta)):
    @abstractmethod
    def __init__(self,parameter):
        self.parameter = parameter

    def do_something():
        """do something"""

There is a class extended form ABCMeta (an abstract class) with an abstract method in it. This class cannot be initialized because of that abstract init() method. Is there a way to test this class? (at least using any testing framework)


Solution

  • Make a subclass of the abstract class, then test the subclass.

    from abc import ABCMeta, abstractmethod
    
    class ThisIsAnAbstractClass(object):
        __metaclass__ = ABCMeta # <--
    
        @abstractmethod
        def __init__(self, parameter):
            self.parameter = parameter
    
        def do_something():
            """do something"""
    
    class ConcreteClass(ThisIsAnAbstractClass):
        def __init__(self, parameter):
            super(ConcreteClass, self).__init__(parameter)
    
    try:
        ThisIsAnAbstractClass('test')
        assert False, 'Abstract class instance created!'
    except TypeError:
        pass
    
    assert ConcreteClass('test').parameter == 'test'
    

    NOTE: You should use abc.ABCMeta as a metaclass.