Skip to content
Advertisement

Grouping tests in pytest: Classes vs plain functions

I’m using pytest to test my app. pytest supports 2 approaches (that I’m aware of) of how to write tests:

  1. In classes:

test_feature.py -> class TestFeature -> def test_feature_sanity

  1. In functions:

test_feature.py -> def test_feature_sanity

Is the approach of grouping tests in a class needed? Is it allowed to backport unittest builtin module? Which approach would you say is better and why?

Advertisement

Answer

There are no strict rules regarding organizing tests into modules vs classes. It is a matter of personal preference. Initially I tried organizing tests into classes, after some time I realized I had no use for another level of organization. Nowadays I just collect test functions into modules (files).

I could see a valid use case when some tests could be logically organized into same file, but still have additional level of organization into classes (for instance to make use of class scoped fixture). But this can also be done just splitting into multiple modules.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement