1

I'm building an application which starts processes using subprocess.Popen(). Those processes may, depending on what they do, start processes of their own. As part of by test suite, I want to thoroughly test that functionality, but I fear that eventual bugs in my code may lead to numerous processes (across the many test cases) staying alive, which I would have to clean up manually.

Is there some functionality in py.test, or a plugin, which could solve this problem and clean up all processes started during the execution of a test case? Bonus points if processes, which had to be cleaned up, are reported and/or counted towards a test case failure.

Feuermurmel
  • 9,490
  • 10
  • 60
  • 90

1 Answers1

1

You can use yield_fixture decorator to define setup & teardown parts of creating processes, stores it's PID's and then kill them all. Ex:

import pytest
import subporcess

@pytest.yield_fixture
def run_sh():
    sh = subprocess.Popen(['/bin/sh'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    yield sh
    sh.kill()

def test_popen(run_sh):
    assert run_sh.pid > 1
Sergei Voronezhskii
  • 2,184
  • 19
  • 32
  • 1
    This will only terminate the process started by the fixture but not any subprocesses. – Feuermurmel Mar 21 '16 at 11:18
  • That seems like a plan! I will just have to write a fixture which will provide the process spawning capability to my test case so that it can inject the group-changing behavior. – Feuermurmel Mar 21 '16 at 13:38