Pytest
lastmod 2026-01-11created 2020-12-1320 edits
The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries.
Commandline optionas
-
-k EXPRESSION - Runs only the tests matching
expression. Test case classes, function names, and so on can be used. - The matching is case-insensitive.
-
-m MARKEXPR - only run tests matching given mark expression.
-
--capture=method - Selects the capture method. Choose one of fd, sys, no, tee-sys.
-
-s - Equivalent to
--capture=no. Use this option if you want stdout and the like, which are not printed during tests, to be printed.
assertEqual vs assertSame
-
assertEqualis an assertion that compares whether two values are equal, and -
assertSameis an assertion that compares by address whether two objects are the same object.
assertSame can be used to check objects created with the Singleton pattern, and also to compare objects copied with a list's clone method.
assertEquals vs assertEqual
Actually, in Python 2.6, both assertEqual and assertEquals are convenience aliases to failUnlessEqual. The source declares them thus:
In Python 3, to your point, failUnlessEqual is explicitly deprecated. assertEquals carries this comment :-)
# Synonyms for assertion methods
# The plurals are undocumented. Keep them that way to discourage use.
# Do not add more. Do not remove.
# Going through a deprecation cycle on these would annoy many people.
So, the upshot appears to be that you should use whatever you like for Python 2.x, but tend toward assertEqual for Python 3.
| INFORMATION |
| Conclusion: use |
Parametrize
| WARNING |
| Note that the |
Plugins
- pytest-cov (coverage.py)
- pytest-flake8 (flake8)
- pytest-benchmark
- pytest-asyncio
Troubleshooting
HINT: remove pycache / .pyc files and/or use a unique basename for your test file modules
import file mismatch:
imported module 'test_msgpack' has this __file__ attribute:
/home/your/Project/type-serialize/test/test_msgpack.py
which is not the same as the test file we want to collect:
/home/your/Project/type-serialize/test/byte/test_msgpack.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules
If you get an error like the one above when running tests, check whether an __init__.py file exists in the test directory.
PytestUnhandledThreadExceptionWarning: Exception in thread {...}
An error raised inside a thread was not handled. <- Handle it.
See also
- pytest
- tox
- Python
- unittest_parametrize - For using
@pytest.mark.parametrizewith Python's unittest package.