pytest - 在所有其他测试之后重新运行失败的测试

mur*_*son 5 python pytest xdist

在我的场景中,我有一个写入文件的测试,以及一个(但可能更多)想要读取该文件的测试。我不能简单地提取将该文件写入函数/夹具,因为它涉及内部正在启动其他二进制文件的其他一些夹具,以及写入该文件的二进制文件。所以我有一个夹具,可以检查文件是否已经存在。

到目前为止我尝试过的:

  • 片状pytest-rerunfailures插件 - 不合适,因为它们都在失败时立即重新运行测试(当文件仍然不存在时),我想将它附加到测试队列的末尾。
  • 手动修改测试队列,如下所示:

...

request.session.items.append(request.node)
pytest.xfail("file not present yet")
Run Code Online (Sandbox Code Playgroud)

这种工作,但只有当我在单跑步者上运行时(没有xdist,或者通过传递-n0cli arg打开它,在我的测试报告中我看到这样的东西:

test_load_file_before_save xfail
test_save_file PASSED        
test_load_file PASSED        
test_load_file_before_save PASSED    
Run Code Online (Sandbox Code Playgroud)

使用 xdist 运行时,不会重复 xfailed 测试。有谁知道如何进行?某种强制 xdist 刷新测试列表的方法?

Sil*_*Guy 3

您可以使用 pytest.cache 获取测试运行状态并将该测试附加到队列以防失败。

if request.config.cache.get(request.node):
    request.session.items.append(request.node)
    pytest.xfail("file not present yet")
Run Code Online (Sandbox Code Playgroud)

您还可以在 pytest 缓存中设置自定义值,以便在不同的运行中使用request.config.cache.set(data,val)

如果您正在编写测试目录中的文件,则可以使用--looponfailpytest-xdist 的开关。它监视目录并重新运行测试,直到测试通过。来自文档: distributed and subprocess testing: -f, --looponfail run tests in subprocess, wait for modified files and re-run failing test set until all pass.

可能有帮助的链接:Pytest-cache

作为一个友好的建议,如果您计划在并行线程中运行测试,我建议您使测试彼此独立。