0417-pytest

Certainly! Here's a general, best-practice guide to using pytestโ€”including directory structure, naming conventions, output control, and common pitfalls. This is suitable for teaching others or serving as a quick reference.


โœ… General Guide for Using pytest Effectively

your_project/
โ”œโ”€โ”€ src/                  # Optional, for better namespace control
โ”‚   โ””โ”€โ”€ your_package/
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ”œโ”€โ”€ module1.py
โ”‚       โ””โ”€โ”€ module2.py
โ”‚
โ”œโ”€โ”€ tests/                # All test files go here
โ”‚   โ”œโ”€โ”€ __init__.py       # Optional
โ”‚   โ”œโ”€โ”€ test_module1.py
โ”‚   โ””โ”€โ”€ test_module2.py
โ”‚
โ”œโ”€โ”€ pyproject.toml        # Recommended modern config
โ”œโ”€โ”€ requirements.txt
โ””โ”€โ”€ README.md

Alternatively, if you're not using src/ layout:

your_project/
โ”œโ”€โ”€ your_package/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ module1.py
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ tests/
โ”‚   โ””โ”€โ”€ test_module1.py
โ””โ”€โ”€ ...

๐Ÿงช 2. Writing Tests

  • Test files: name them as test_*.py or *_test.py

  • Test functions: start names with test_

  • Example:

# tests/test_module1.py
from your_package import module1

def test_add():
    assert module1.add(1, 2) == 3

๐Ÿ“ฆ 3. Making Your Package Importable

From the root directory, run:

pip install -e .

This allows test files to import your package using absolute imports like:

from your_package import module1

๐Ÿ–จ๏ธ 4. Seeing print() Output

By default, pytest captures stdout, so you wonโ€™t see print() unless:

  • The test fails, or

  • You run pytest with:

pytest -s            # disables output capturing
pytest --capture=no  # same effect

โš ๏ธ 5. Common Pitfalls to Avoid

Mistake
Why it's a problem

Placing test files in the same folder as code

Can cause import conflicts

Using relative imports in test files

Not robust; breaks easily

Naming a test file the same as a module

Import shadowing (test.py, math.py, etc.)

Forgetting to install in editable mode (-e .)

Causes ModuleNotFoundError in tests

Relying on print() without -s

Output wonโ€™t appear unless test fails


โš™๏ธ 6. Optional pyproject.toml Configuration

[tool.pytest.ini_options]
addopts = "-ra -q -s"
testpaths = ["tests"]
python_files = ["test_*.py"]

This simplifies your test command to just:

pytest

Would you like a GitHub template or cookiecutter starter with this structure?

Last updated