Skip to content
Search

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

  • assertEqual is an assertion that compares whether two values are equal, and
  • assertSame is 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:

# Synonyms for assertion methods
assertEqual = assertEquals = failUnlessEqual

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 assertEqual

Parametrize

WARNING

Note that the @pytest.mark.parametrize decorator of pytest does not work in a structure that inherits from the unittest.TestCase class.

Plugins

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 {...}

PytestUnhandledThreadExceptionWarning: Exception in thread ThreadTestCase

An error raised inside a thread was not handled. <- Handle it.

See also

Favorite site

author Zer0 sitemap