我确实有一些更复杂的项目,如果您运行pytest --collect-only
,您将发现大量导入尚未安装的东西的测试文件所导致的导入失败。
我希望以这样的方式更改这些测试文件,使它们不会在集合上失败。
这是因为用户可能希望使用pytest -k foo
这样的特定模式来运行测试,但是如果集合在不相关的测试上失败,他将无法这样做。
我知道我可以定义一个名为durind集合的pytest_configure
方法,但是如果我将导入移到其中,那么当解释器到达试图使用缺失导入的代码时,我仍然会失败。
def pytest_configure(config):
try:
import foo
except:
pytest.skip("skipping when foo is not installed")
def test_foo()
assert foo.is_enabled() # <-- foo is undefined here
我的例子显然过于相似,因为我们都知道,我可以在测试方法中再次添加导入,但我不想在几十种方法中这样做。我正在寻找一个更清洁的解决方案。
发布于 2019-07-12 09:07:33
如果不希望在导入(或任何其他)错误时中止测试集合,请使用--continue-on-collection-errors
标志。示例:
test_spam.py
有一个未解决的导入:
import foo
def test_foo():
assert foo.is_enabled()
test_eggs.py
可以运行:
def test_bar():
assert True
运行测试结果:
$ pytest --continue-on-collection-errors -v
======================================= test session starts =======================================
...
collected 1 item / 1 errors
test_eggs.py::test_bar PASSED
============================================= ERRORS ==============================================
__________________________________ ERROR collecting test_spam.py __________________________________
ImportError while importing test module '/home/hoefling/projects/private/stackoverflow/so-56997157/test_spam.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
test_spam.py:2: in <module>
import foo
E ModuleNotFoundError: No module named 'foo'
================================ 1 passed, 1 error in 0.06 seconds ================================
这将指示pytest
运行它可以收集的所有测试(在本例中为test_eggs::test_bar
),但是执行失败,因为无法收集一个模块。如果您不想失败测试运行,pytest
提供了一个方便的importorskip
函数:
import pytest
foo = pytest.importorskip('foo')
def test_foo():
assert foo.is_enabled()
现在运行测试将产生如下结果:
$ pytest -v
======================================= test session starts =======================================
...
collected 1 item / 1 skipped
test_eggs.py::test_bar PASSED [100%]
=============================== 1 passed, 1 skipped in 0.04 seconds ===============================
正如您所看到的,这两者之间的区别在于收集错误的处理(1 errors
与1 skipped
)以及由此产生的退出代码(1vs0)。
就我个人而言,我倾向于不使用importorskip
,因为它可能导致长期不执行测试。如果您有一个大型测试套件,通常只需简要查看测试结果(失败/不失败),而不显式地检查是否有新的跳过测试。这可能导致在任何地方(甚至在CI服务器上)都不执行测试,直到有人注意到它(最好的情况),或者(最坏的情况),假设被测试的代码在生产系统上发现了错误。当然,还有其他可用的指标可以间接地保护这种情况(比如注意测试覆盖率,并禁止提交降低测试覆盖率),但IMO明确的失败设置了一个无法避免的巨大感叹号。
资料来源:跳过缺少的导入依赖项.
https://stackoverflow.com/questions/56997157
复制相似问题