单位测试__init_subclass__ in Python 3.x

发布于 2025-02-02 23:39:29 字数 1116 浏览 4 评论 0原文

我正在尝试单元测试其基类实施__init_subclass __方法的继承类。代码如下:

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()

问题是我什至无法达到测试案例,因为child> childnoprop定义呼叫__ initi> __ init_subclass __ __ < /代码>在基类中,并提出例外。

有什么方法可以通过当前实现来对此进行单位测试,或者我应该在__ init_subclass __中废除升级错误?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一花一树开 2025-02-09 23:39:29

您可以在assertraises块中创建类。

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

如果方法内部的声明使您感到不舒服,则可以直接使用type构造函数。

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

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,), {})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文