Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unit testing __init_subclass__ method in python 3.x

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__?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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,), {})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading