3

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)

maheshakya
  • 2,198
  • 7
  • 28
  • 43

1 Answers1

4

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Forgot that metaclass.Edited. I thought wanted test the abstract class it self. Seems like there's no way other than creating a sub class of that. – maheshakya Aug 31 '13 at 14:34