jde*_*son 8 python testing pytest
Pytest的默认发现规则将从所有Test不带的Class导入__init__()。我遇到这种情况,导致导入了错误的类。
我正在测试使用Factory Boy的django项目。http://factoryboy.readthedocs.org/en/latest/构建一个名为的Django模型Testimonial。
像这样:
class TestimonialFactory(factory.Factory):
class Meta:
model = models.Testimonial
Run Code Online (Sandbox Code Playgroud)
这个问题是factory.Factory没有__init__()。因此,py.test看到了Testimonials并尝试运行。依次尝试在pytest发现阶段将记录插入数据库(随之而来的是热闹和失败)。
我通过更改pytest.ini来寻找一种以Check而不是Test开头的Test类来解决问题:
[pytest]
python_classes=Check
Run Code Online (Sandbox Code Playgroud)
这不是我真正想要的。有什么方法可以明确告诉py.test忽略特定名称的测试?
小智 15
这是我使用的一个简单解决方案,但有一些开销。
class DisablePyTestCollectionMixin(object):
__test__ = False
class TestimonialFactory(DisablePyTestCollectionMixin):
pass
Run Code Online (Sandbox Code Playgroud)
基于:https : //github.com/pytest-dev/pytest/issues/1879
这是一个较旧的问题,但它似乎是 stackoverflow 上唯一相关的问题,所以我想我会在这里留下一个替代答案以供后代使用。
另一种解决方法是禁用所有基于类名的发现并仅依赖于子类发现。换句话说:
在您的配置文件中:(setup.cfg或pytest.ini):
[pytest]
python_classes =
Run Code Online (Sandbox Code Playgroud)
在您的测试文件中:
class TestWillNotBeRun(object):
# Not a subclass of unittest.TestCase, so not collected regardless of name
class TestWillBeRun(unittest.TestCase):
# Still okay to use TestName convention for readability
# It just doesn't actually do anything.
class StillGoingToBeRun(unittest.TestCase):
# Relying on subclassing means *all* subclasses will be picked up, regardless of name
Run Code Online (Sandbox Code Playgroud)
这样做的优点之一是它不需要更改您的非测试类名称。对于向用户公开这些类的库,可能有充分的理由不重命名。此外,它不需要大量重命名测试类(因为它们现在实际上可以是任何东西)。最后,与基于名称的发现不同,非测试代码不太可能以某种方式成为 unittest.TestCase 的子类。(我敢肯定有人是个例外。)
缺点是您必须确保所有测试类都必须是unittest.TestCase. 对于我的所有代码,这已经是正确的,所以没有成本。不过,这不一定是普遍正确的。
将所有测试放入以以下开头的文件中,test_并将其添加到您的pytest.ini:
[pytest]
python_files=test_*.py
Run Code Online (Sandbox Code Playgroud)
这将指示 pytest 仅发现test_*.py文件中的测试。
| 归档时间: |
|
| 查看次数: |
3191 次 |
| 最近记录: |