49

I am currently running some unit tests that might either take a long time before failing or run indefinitely. In a successful test run they will always complete within a certain amount of time.

Is it possible to create a pytest unit test that will fail if it does not complete within a certain amount of time?

Martin Thoma
  • 108,021
  • 142
  • 552
  • 849
shuttle87
  • 14,776
  • 9
  • 75
  • 105

2 Answers2

75

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

shuttle87
  • 14,776
  • 9
  • 75
  • 105
Mrinal Shukla
  • 830
  • 7
  • 7
  • is this doable without installing an extra package? – Gulzar Jan 24 '21 at 16:09
  • @Gulzar if you really need to you could vendor in this dependency or write a similar decorator yourself. – shuttle87 Jan 28 '21 at 05:40
  • This doesn't seem to work in my case: but admittedly I am using pytest-qt and the cause of the "hang" is a `QMessageBox` calling `question`, which causes the test to just stop mid-flow if there is no user input. Maybe pytest-qt has something specific... ? – mike rodent May 05 '22 at 17:31
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

Konstantin
  • 21
  • 1