我有以下通过 py.test 运行的单元测试代码。 构造函数的存在会使整个类在运行时跳过 py.test -v -s
已收集 0 件 / 已跳过 1 件
任何人都可以向我解释 py.test 的这种行为吗?
我有兴趣了解 py.test 行为,我知道不需要构造函数。
谢谢, 兹德内克
class TestClassName(object):
def __init__(self):
pass
def setup_method(self, method):
print "setup_method called"
def teardown_method(self, method):
print "teardown_method called"
def test_a(self):
print "test_a called"
assert 1 == 1
def test_b(self):
print "test_b called"
assert 1 == 1
正如 Matti Lyra 的答案中已经提到的,py.test 故意跳过具有构造函数的类。这样做的原因是,类仅在 py.test 中出于结构原因而使用,并且没有任何固有行为,而在实际编写代码时,情况恰恰相反,并且类没有
.__init__()
方法的情况要少得多。因此,在实践中,跳过带有构造函数的类可能是所期望的,通常它只是一个碰巧具有冲突名称的类。
最后 py.test 需要实例化该类才能执行测试。如果构造函数接受任何参数,它无法实例化它,所以再次跳过是正确的做法。
以上所有答案都清楚地解释了根本原因,我只是想分享我的经验并解决警告。
通过为导入的类添加别名,我的测试可以在没有警告的情况下工作
from app.core.utils import model_from_meta
from app.core.models import Panel, TestType as _TestType
from app.core.serializers import PanelSerializer, TestType as _TestTypeSerializer
def test_model_from_meta():
assert isinstance(Panel, model_from_meta(PanelSerializer)
assert isinstance(_TestType, model_from_meta(_TestTypeSerializer)
使用别名导入类后,不再打印警告
我希望这对某人有帮助。