Skip to content

Section 2.1: Note on python3 -m pytest is incorrect #18

@alexlyttle

Description

@alexlyttle

The note:

## Why Run Pytest Using `python3 -m pytest` and Not `pytest`?

`pytest` is another Python module that can be run via its own command but this is a good example
why invoking Python modules via `python3 -m` may be better (recall the [explanation of Python interpreter's `-m` flag](12-virtual-environments.md)).
Had we used `pytest tests/test_models.py` command directly,
this would have led to a "ModuleNotFoundError: No module named 'inflammation'" error. This is
because `pytest` command (unlike `python3 -m pytest`) does not add the current directory to its list of
directories to search for modules, hence the `inflammation` subdirectory's contents are not being
'seen' by `pytest` causing the `ModuleNotFoundError`. There are ways to work around this problem
but `python3 -m pytest` ensures it does not happen in the first place.

This is wrong. Counter example:

pytest tests/test_models.py

outputs:

=================================================== test session starts ====================================================
platform darwin -- Python 3.12.9, pytest-8.3.5, pluggy-1.5.0
rootdir: /Users/***/Repos/github.com/***/python-intermediate-inflammation
configfile: pyproject.toml
collected 2 items                                                                                                          

tests/test_models.py ..                                                                                              [100%]

==================================================== 2 passed in 0.06s =====================================================

Environment

  • OS: macOS 15.3.2
  • See pytest output above

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions