Search code examples
pytestabstract-methods

Pytest test is method abstract


I have an abstract basis class with an abstract method.

from abc import ABC, abstractmethod

class MyClass(ABC):

    @abstractmethod
    def my_method():
        pass

I want to test if I get an error if I create a Child of my abstract basis class without creating that method.

My first approach was to see if the error occurs if I create the Child within a function. But I get no error at all.

from abstract_method import MyClass

def test_my_class_without_my_method_error():
    class MyChildClass(MyClass):
        def my_method_with_spelling_error():
            print("do something")

is there a way to test if an method is abstract?


Solution

  • You can check this example.

    myabc.py

    from abc import ABC, abstractmethod
    
    class MyABC(ABC):
        @abstractmethod
        def my_method():
            pass
    

    test.py

    from myabc import *
    
    def test_function():
        class MyChild(MyABC):
            def my_method_new():
                pass
        c = MyChild()
    

    This raises an error (TypeError: Can't instantiate abstract class MyChild with abstract methods my_method) at c = MyChild(). This means you don't get an error until you instantiate the class.