pytest 运行 只有更改的文件?

pytest run only the changed file?

我是 Python 的新手,正在尝试学习工具集。

我已经想出如何让 py.test -f 在我编写代码时观看我的测试。我一直无法弄清楚的一件事是,是否有一种方法可以做一个更聪明的观察者,就像 Ruby 的 Guard 库一样工作。

使用 guard + minitest 我得到的行为是,如果我保存一个像 my_class.rb 这样的文件,然后 my_class_test.rb 被执行,如果我在 cli 中点击 enter 它 运行所有测试。

使用 pytest 到目前为止,我还没有找到一种方法来只 运行 对应于最后一个触摸文件的测试文件,从而避免等待整个测试套件 运行 直到我通过当前文件。

Python 爱好者们会怎么做?

谢谢!

一种可能是使用 pytest-testmon together with pytest-watch.

它使用 coverage.py 来跟踪哪个测试触及了哪些代码行,一旦您更改了一行代码,它就会重新运行以某种方式执行该行的所有测试。

还有一个 pytest-xdist 有一个功能叫做:

--looponfail: run your tests repeatedly in a subprocess. After each run py.test waits until a file in your project changes and then re-runs the previously failing tests. This is repeated until all tests pass after which again a full run is performed.

要添加到上面的 @The Compiler 的答案,您可以使用 pytest-watch 的 --runner 选项让 pytest-testmon and pytest-watch 一起玩:

ptw --runner "pytest --testmon"

或者简单地说:

ptw -- --testmon

如果您使用 git 作为版本控制,您可以考虑使用 pytest-picked。根据文档,这是一个插件:

Run the tests related to the unstaged files or the current branch

演示

基本功能

  • 运行 仅来自修改后的测试文件的测试
  • 运行 首先从修改后的测试文件进行测试,然后是所有未修改的测试

用法

pytest --picked

我得到的最快设置是当我将@lmiguelvargasf @BenR 和@TheCompiler answer 结合到这个

ptw --runner "pytest --picked --testmon"

你首先得安装它们

pip3 install pytest-picked pytest-testmon pytest-watch