Python Friday #56: 3 Useful Command-Line Options for Pytest

The more I work with pytest, the more I like the flexibility it offers. Today I post about 3 command-line options that help me a lot and are easy to overlook.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

−−collect-only: to get a list of test cases

Especially when you try to figure out how parametrized tests work the option
--collect-only is a great help. As the name suggest this option collects all test cases but does not run them.

====== test session starts =======
platform win32 — Python 3.8.1, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: D:\Python, inifile: pytest.ini
plugins: cov-2.10.1, html-3.1.1, metadata-1.10.0
collected 76 items
<Module test_fizzbuzz.py>
<Function test_1_returns_1>
<Function test_2_returns_2>
<Function test_multiples_of_3_return_Fizz[3]>
<Function test_multiples_of_3_return_Fizz[6]>
<Module first_approach/test_own_fixture_part2.py>
<Function test_add_multiple_contacts_to_phonebook>


===== no tests ran in 0.14s ======

 

−x or −−exitfirst: stop at first failure

With the -x option we can tell pytest to stop with the first failed test. This is sometimes a better behaviour than keep running until the whole test suite is done.

====== test session starts =======
platform win32 — Python 3.8.1, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: D:\Python, inifile: pytest.ini
plugins: cov-2.10.1, html-3.1.1, metadata-1.10.0
collected 76 items

test_fizzbuzz.py ……………………F

 

−−lf or −−last-failed: run only the failed tests

The more test you have, the more time it takes to run them all. With the --lf option we can run only those tests that failed in the last run. This is a great help to see if your change fixed the failed tests or if the problem needs another round.

====== test session starts =======
platform win32 — Python 3.8.1, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: D:\Python, inifile: pytest.ini
plugins: cov-2.10.1, html-3.1.1, metadata-1.10.0
collected 7 items
run-last-failure: rerun previous 7 failures (skipped 7 files)

test_fizzbuzz.py FFFFFFF [100%]

 

Conclusion

Those 3 options allow you to modify what tests pytest runs (and if it runs your tests at all). As with so many other things, they are well documented yet easy to miss.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.