Best practice for starting/stopping daemons as part of a unittest (using pytest)
Question: Functional testing of code often requires external resources like e.g. a
database.

There are basically two approaches:

  * assuming that a resource (e.g. database) is always running and is always available
  * start/stop the related resource as part of the test

In the "old" world of Python unittest(2) world setUp() and tearDown() methods
could be used for controlling the services.

With py.test the world became more complicated and the concept of setUp() and
tearDown() methods has been replaced with the funcarg magic for implementing
fixtures. Honestly this approach is broken - at least as a replacement for
setUp/tearDown methods.

What is the recommended way for controlling services and resources in a
project where py.test is used?

Should we continue writing our tests (at least where needed) with
setUp/tearDown methods or is there a better pattern?


Answer: pytest supports xUnit style setup/teardown methods, see
<http://pytest.org/latest/xunit_setup.html> so if you prefer this style you
can just use it.

Using <http://pytest.org/latest/fixture.html> one can also instantiate a
"session" scoped fixture which can instantiate external processes for the
whole test run and return a connection object. Code would roughly look like
this:

    
    
    # content of conftest.py
    
    import pytest
    
    @pytest.fixture(scope="session")
    def connection():
        ... instantiate process ...
        return connection_to_process_or_url
    

and test files using it like this:

    
    
    # content of test_conn.py
    def test_conn_ok(connection):
        ... work with connection ...
    

If you want to keep up the service between test runs, you will need to write
some logic (storing PID, checking it's alive, if no PID or not alive, start a
new process) yourself for the time being (a future release might include such
support code).

