Pytest pro-tips

Kenny Chou · September 21, 2024

A compilation of pro-tips. This page will be periodically updated.

If you haven’t done so, check out the tutorial given by Florian Bruhin at Europython 2024.

Use plug-ins.

Keeping tests clean:

  • One test, one concept
  • Aim for a single assertion per test

Make tests human-readable:

  • Name tests using the given-when-then convention (source)

Doc-tests:

  • You can test code examples inside your docstrings like so:
      $ pytest --doctest-modules http://yourmodule.py
    

Mocking:

  • Use mocking when needed
  • But mocking makes code maintenance more difficult
  • Avoid mocking and use the real thing if possible

More tips and tricks: