单位测试__init_subclass__ in Python 3.x
我正在尝试单元测试其基类实施__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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在
assertraises
块中创建类。如果方法内部的
类
声明使您感到不舒服,则可以直接使用type
构造函数。You can create the class inside the
assertRaises
block.If the
class
declaration inside of a method makes you uncomfortable, you can use thetype
constructor directly.