Home > Software engineering >  unit testing __init_subclass__ method in python 3.x
unit testing __init_subclass__ method in python 3.x

Time:05-31

I am trying to unit test an inherited class for which its base class implements __init_subclass__ method. Code is the following:

quick_test.py

import unittest
from unittest.mock import create_autospec

class Parent():

    PROPERTY = NotImplemented

    def __init_subclass__(cls, **kwargs):
        if cls.PROPERTY is NotImplemented:
            raise NotImplementedError("Please implement the `PROPERTY`.")
        super().__init_subclass__(**kwargs)

    def __init__(self, connection_type="default"):
        self.connection_type = connection_type


class Child(Parent):

    PROPERTY = "has value"


class ChildNoProp(Parent):
    pass


class TestClass(unittest.TestCase):

    def test_required_params(self):
        mock = create_autospec(Child)
        self.assertRaises(NotImplementedError, mock)


if __name__ == '__main__':
    unittest.main()

The problem is I can't even reach the test case because ChildNoProp definition calls __init_subclass__ in base class and raises exception.

Is there a way I can unit test this with current implementation, or should I scrap the error raising in __init_subclass__?

CodePudding user response:

You can create the class inside the assertRaises block.

with self.assertRaises(NotImplementedError):
    class ChildNoProp(Parent):
        pass

If the class declaration inside of a method makes you uncomfortable, you can use the type constructor directly.

with self.assertRaises(NotImplementedError):
    type("ChildNoProp", (Parent,), {})
  • Related