pytest

pytest : test_sessionfinish is not called


Using python 3.10.4 , I want to execute a specific action after all tests run by pytest are done. The following code is an example of what I am trying to achieve :

import pytest

# Test function with parametrization
@pytest.mark.parametrize("input1, input2, expected_output", [
    (1, 2, 3),
    (0, 0, 0),
    (-1, 1, 0),
    (10, 5, 15)
])
def test_addition(input1, input2, expected_output):
    assert input1 + input2 == expected_output

# Pytest hook to run Linux apps based on test results
@pytest.hookimpl()
def pytest_sessionfinish(session, exitstatus):
    if exitstatus == 0:  # All tests passed
        print("All tests passed. Running foo_pass...")
        # Run Linux app  foo_pass
    else:
        print("One or more tests failed. Running foo_fail...")
        # Run Linux app foo_fail

# Run the tests
if __name__ == "__main__":
    pytest.main()

But running this code pytest -v exemple.py (where @pytest.hookimpl is here or not), the function pytest_sessionfinish is never called. Is it due to the python revision ? or else ?


Solution

  • You should put your hooks into the conftest.py in the test directory. This file used to declare fixtures and hooks used in all tests in this directory or subdirectories.

    Also some notes:

    PyTest reference