Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Testing an abstract base class

I am looking for ways / best practices on testing methods defined in an abstract base class. One thing I can think of directly is performing the test on all concrete subclasses of the base class, but that seems excessive at some times.

Consider this example:

import abc  class Abstract(object):      __metaclass__ = abc.ABCMeta      @abc.abstractproperty     def id(self):         return         @abc.abstractmethod     def foo(self):         print "foo"      def bar(self):         print "bar" 

Is it possible to test bar without doing any subclassing?

like image 214
bow Avatar asked Mar 18 '12 09:03

bow


People also ask

Can abstract classes be tested?

The answer is: always test only concrete classes; don't test abstract classes directly . The reason is that abstract classes are implementation details. From the client perspective, it doesn't matter how Student or Professor implement their GetSignature() methods.

How do you access the abstract method in Python?

A class is called an Abstract class if it contains one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and its abstract methods must be implemented by its subclasses.

What is abstract base class in Python?

In Python, abstract base classes provide a blueprint for concrete classes. They don't contain implementation. Instead, they provide an interface and make sure that derived concrete classes are properly implemented. Abstract base classes cannot be instantiated.

Can we inherit abstract class in Python?

Introduction to Python Abstract Classes In object-oriented programming, an abstract class is a class that cannot be instantiated. However, you can create classes that inherit from an abstract class.


1 Answers

In newer versions of Python you can use unittest.mock.patch()

class MyAbcClassTest(unittest.TestCase):      @patch.multiple(MyAbcClass, __abstractmethods__=set())     def test(self):          self.instance = MyAbcClass() # Ha! 
like image 51
Mariusz Jamro Avatar answered Sep 21 '22 05:09

Mariusz Jamro