Finalizers don't run on SIGTERM · Issue #5243 · pytest-dev/pytest (original) (raw)

I caught this issue in a Jenkins environment. This is the series of events:

  1. My tests create resources outside the test environment
  2. Jenkins kills the pytest process with SIGTERM. Finalizers won't run and resources won't be cleaned up.

That doesn't seem right to me. A cleanup method should always cleanup, no matter what caused the exit. For example KeyboardInterrupt does run cleanup, so why shouldn't SIGTERM?

Here is a sample program:

import pytest


@pytest.fixture
def myfixture(request):
    print('fixture')

    def finalizer():
        print('finalizer')
    request.addfinalizer(finalizer)


def test_fast_test(myfixture):
    print('run fast test')


def test_slow_test(myfixture):
    print('run slow test')
    import time
    time.sleep(100)

Steps to reproduce:

  1. Open two terminals.
  2. In the first terminal, run the tests withn pytest: pytest -s finalizer_test.py
  3. In the second terminal, kill the pytest process with SIGTERM. For example using pkill command: pkill pytest

This is the output:

finalizer_test.py fixture
run fast test
.finalizer
fixture
run slow test
Terminated

As you can see the second finalizer didn't run.

Environment:

$ pip list
Package        Version
-------------- -------
atomicwrites   1.3.0  
attrs          19.1.0 
more-itertools 7.0.0  
pathlib2       2.3.3  
pip            19.1.1 
pkg-resources  0.0.0  
pluggy         0.11.0 
py             1.8.0  
pytest         4.4.2  
setuptools     20.7.0 
six            1.12.0