Search code examples
pythonpython-3.xunit-testingabstract

Python: Testing abstract class with concrete implementation details


I have a class containing a mixture of @abstractmethods and normal implementation methods, and I'm wondering how I should go about testing the normal implementations.

Quick Example: I'd like to test the zoo_str method, even though it depends on the abstract description method. If I have 100 animals, it seems like overkill to write a test in the Lion class, the Antelope class, the Hippo class, etc. What's the best way to do this -- my intuition says I should try to mock description, but I can't instatntiate the class and this falls apart if the abstract method is private (_description).

class Animal:
    @abstractmethod
    def description(self) -> str:
        pass

    def zoo_str(self) -> str:
         return self.description() + "Get more info at zoo.com!"

Solution

  • Just create a subclass.

    class TestAnimal(Animal):
        def description(self):
            return "foo"
    
    
    assert TestAnimal().zoo_str() == "fooGet more info at zoo.com!"