Getting started with Pytest

Getting started with Pytest

What is pytest?

  • pytest is a popular testing framework for Python.
  • It allows us to write simple and scalable test cases for your Python code.
  • It's often used for unit testing, although it can be extended to cover various testing needs, including functional and integration testing.
  • pytest is known for its simplicity, powerful features, and extensive ecosystem of plugins and extensions.

install pytest

  • install pytest using pip and the command is pip install pytest

creating test file

  • Test filename should starts with test_ or ends with _test.py
  • Example file name: test_math_functions.py

run a sample test

  • Create file with name test_math_functions.py
  • Add the code below
def test_addition():
    assert 1 + 1 == 2

def test_subtraction():
    assert 3 - 2 == 1
  • Run the command pytest to execute the above tests.
  • Each test function should use the assert statement to check whether the code being tested behaves as expected.

pytest.ini file

[pytest]

# Add custom markers for categorizing tests
markers =
    slow: marks tests as slow
    regression: marks tests as regression tests
    integration: marks tests as integration tests

# Specify test discovery patterns
python_files = test_*.py
python_classes = Test*
python_functions = test_*

# Add default command-line options for pytest
addopts =
    -vv  # Increase verbosity to show detailed test information
    --cov=my_module  # Enable code coverage for the 'my_module' package
    --cov-report=html  # Generate an HTML code coverage report

# Configure pytest-cov options
# In this example, we exclude certain directories from code coverage
# and specify where to store the coverage data
[coverage:run]
omit =
    my_module/tests/*
    */__init__.py
source =
    my_module

# Specify environment variables for tests
env =
    TESTING_ENV=pytest
  • [pytest]: This section is used to specify various options related to pytest

    • markers: Custom markers that can be used to categorize and select tests based on specific criteria.
    • python_files, python_classes, python_functions: Patterns to discover test files, classes, and functions. In this example, it looks for test files starting with "test_", test classes starting with "Test", and test functions starting with "test_".
    • addopts: Default command-line options that pytest should use when running tests. For example, increasing verbosity and enabling code coverage.
  • [coverage:run]: Configuration section for the pytest-cov plugin, which provides code coverage reporting.

    • omit: Specify which files or directories should be omitted from code coverage analysis.
    • source: Specify the source code directory to be measured for coverage.
  • env: We can define environment variables that will be set when running tests.

    • In the above example, it sets a variable TESTING_ENV to "pytest".

References: