0
0
PyTesttesting~5 mins

Test packages in PyTest

Choose your learning style9 modes available
Introduction

Test packages help organize many test files into folders. This makes tests easier to find and run together.

You have many test files and want to group them by feature or module.
You want to run all tests in a folder at once.
You want to share setup code for tests in the same folder.
You want to keep your project tidy and easy to maintain.
You want to avoid running unrelated tests accidentally.
Syntax
PyTest
project_root/
  tests/
    __init__.py
    test_module1.py
    test_module2.py
    subpackage/
      __init__.py
      test_submodule.py

A test package is a folder with an __init__.py file and test files inside.

pytest automatically finds tests in files named test_*.py or *_test.py.

Examples
This creates a test package named tests with two test files.
PyTest
# Folder structure example

my_project/
  tests/
    __init__.py
    test_math.py
    test_strings.py
This command runs all tests inside the tests folder and its subfolders.
PyTest
# Running tests in a package

$ pytest tests/
You can put shared fixtures or setup code in __init__.py inside the test package.
PyTest
# Sharing setup in __init__.py

# tests/__init__.py
import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3]
Sample Program

This example shows a test package tests with one test file test_add.py. Running pytest tests/ runs all tests inside.

PyTest
# Folder structure:
# my_project/
#   tests/
#     __init__.py
#     test_add.py

# tests/__init__.py
# (empty or can have shared setup)

# tests/test_add.py
import pytest

def add(a, b):
    return a + b

def test_add_positive():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, -1) == -2

# Run command:
# pytest tests/
OutputSuccess
Important Notes

Always include an __init__.py file in test folders to make them packages.

pytest discovers tests recursively in test packages.

Use descriptive folder and file names to keep tests organized.

Summary

Test packages group test files into folders with __init__.py.

They help organize and run related tests together.

pytest automatically finds and runs tests inside these packages.