How can I limit the maximum running time for a unit test?

Solution 1:

you can install the pytest-timeout plugin and then mark your test functions with a timeout in seconds.

@pytest.mark.timeout(300)
def test_foo():
   pass

Look at the plugin download and usage instructions at https://pypi.python.org/pypi/pytest-timeout

Solution 2:

Bash functionality can be used:

EXIT_CODE=0
TIME_LIMIT=60

timeout $TIME_LIMIT pytest ... || EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
    
    echo "Your error message to log"
    
    ...
    
    exit $EXIT_CODE
    
fi