Skip to content

Instantly share code, notes, and snippets.

@almeidaraul
Last active May 27, 2023 03:00
Show Gist options
  • Save almeidaraul/f6eac9077c7d37db3cb17845e6c1eb42 to your computer and use it in GitHub Desktop.
Save almeidaraul/f6eac9077c7d37db3cb17845e6c1eb42 to your computer and use it in GitHub Desktop.
Making sense of pytest imports

Organizing pytest tests

Python imports can get weird, specially when dealing with tests that are to be kept separate from the application code (i.e., in sibling directories).

This is how you organize your tests with pytest.

The code

Directory structure

pkg/
  code.py
tests/
  __init__.py
  test_code.py

File structure

# pkg/code.py
def f(x):
    return x+2
# tests/__init__.py
# (may be left empty)
# tests/test_code.py
from pkg.code import f


def test_f():
    assert f(2) == 4

The testing

Now you can run your tests with the pytest command 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment