Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 434
pretend I have a cool name Avatar asked Jan 20 '26 15:01

pretend I have a cool name


1 Answers

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.

like image 177
dmjy Avatar answered Jan 22 '26 12:01

dmjy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!