配置 Pytest 发现以忽略类名 [英] Configure Pytest discovery to ignore class name
问题描述
Pytest 的默认发现规则将导入所有以 Test
开头且没有 __init__()
的类.我有一种情况,这会导致导入错误的类.
Pytest's default discovery rules will import all Class starting with Test
that do not have an __init__()
. I have a situation where this causes an incorrect class to be imported.
我正在测试一个使用 Factory Boy 的 django 项目.http://factoryboy.readthedocs.org/en/latest/ 构建 Django 模型名为 Testimonial
.
I am testing a django project that uses Factory Boy. http://factoryboy.readthedocs.org/en/latest/ to build out a Django model named Testimonial
.
像这样:
class TestimonialFactory(factory.Factory):
class Meta:
model = models.Testimonial
这个问题是 factory.Factory
没有 __init__()
.所以 py.test 看到 Test
imonials 并尝试运行.这反过来又会尝试在 pytest 发现阶段将记录插入到数据库中(随之而来的是欢笑和失败).
This issue is that factory.Factory
does not have an __init__()
. So py.test sees Test
imonials and tries to run. Which in turn tries to insert a record into the database within the pytest discovery phase (hilarity and failures ensue).
我通过更改 pytest.ini 来查找测试类以从 Check 而不是 Test 开始,从而破解了一种解决方法:
I have hacked a workaround by changing the pytest.ini to look for Test classes to start with Check instead of Test:
[pytest]
python_classes=Check
这不是我真正想要的.有没有办法明确告诉 py.test 忽略某个名称的测试?
This is not really what I want. Is there any way to explicitly tell py.test to ignore a test of a certain name?
推荐答案
这是我使用的一个简单的解决方案,但有一些开销.
Here is a simple solution that I use, but has some overhead.
class DisablePyTestCollectionMixin(object):
__test__ = False
class TestimonialFactory(DisablePyTestCollectionMixin):
pass
基于:https://github.com/pytest-dev/pytest/issues/1879
这篇关于配置 Pytest 发现以忽略类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!