打印测试执行时间并使用py.test确定慢速测试

Mik*_*maa 84 python pytest

我正在使用py.test在CI服务器上运行单元测试.测试使用通过网络获取的外部资源.有时测试运行器需要太长时间,导致测试运行器中止.我无法在本地重复这些问题.

有没有办法让py.test打印出(慢)测试的执行时间,所以固定有问题的测试会变得更容易?

Bru*_*ira 132

我不确定这会解决您的问题,但您可以在测试套件完成后传递--durations=N打印最慢的N测试.

  • 如果传递`--durations = 0`,将报告所有测试的执行时间. (80认同)
  • @oLas:事实并非如此:如果测试"太快",测量的时间显然会变为0,它们仍然会被过滤掉.在这种情况下,负阈值也无济于事.这种方法的另一个烦恼是pytest将始终打印`(隐藏0.00持续时间.使用-vv显示这些持续时间.)`这没有任何意义. (4认同)
  • @bluenote10 不确定这是否是稍后添加的内容,因为现在是 2021 年,但使用 `--durations-min=N` 您可以设置包含在最慢列表中的最短持续时间(以秒为单位)。默认值为 0.005,因此即使 --durations=0 也不会显示任何低于 0.005 的值,除非您为 `durations-min` 设置了一个值 (4认同)

Phu*_*ong 8

您可以通过传递数字 --durations

pytest --durations=0?—?Show all times for tests and setup and teardown

pytest --durations=1?—?Just show me the slowest

pytest --durations=50?—?Slowest 50, with times, … etc
Run Code Online (Sandbox Code Playgroud)

请参阅:https : //medium.com/@brianokken/pytest-durations-0-show-all-times-for-tests-and-setup-and-teardown-848dccac85db

或者:https : //docs.pytest.org/en/latest/usage.html#profiling-test-execution-duration