Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/tox, start a process before tests, shut it down when done

I'm using Tox to check that the system I'm developing is behaving well when installed in a fresh environment (+ sanity checking the setup.py file). However, the system uses a memcached server, and ideally I'd like to spawn a new one for every Tox run.

Is there a preferred way to start programs before tests are run (and shut them down afterwards) or will I need to write a custom runner?

Edit: The test runner is py.test

like image 378
Jacob Oscarson Avatar asked Nov 13 '12 10:11

Jacob Oscarson


People also ask

How does Python tox work?

Tox will automatically use the right version of the interpreter, based on the version of the environment, to create the virtual environment. Tox will automatically rebuild the virtual environment if it is missing or if the dependencies change. It is possible to explicitly indicate the Python version in an environment.

What is Tox used for?

What is tox? Tox is a tool that creates virtual environments, and installs the configured dependencies for those environments, for the purpose of testing a Python package (i.e. something that will be shared via PyPi, and so it only works with code that defines a setup.py ).


3 Answers

To elaborate on flub's comment on the best way to do it with py.test, using its fixture mechanism. Create a conftest.py file with this content:

# content of conftest.py

import pytest, subprocess

@pytest.fixture(scope="session", autouse=True)
def startmemcache(request):
    proc = subprocess.Popen(...)
    request.addfinalizer(proc.kill)

The "autouse" flag means that this fixture will be activated for each test run without requiring any references from tests. In practise, however, you might want to make the connection details to the subprocess available to your tests so that you don't have to work with magic port numbers. You wouldn't use "autouse" then but rather return a fixture object for connecting to memcache, nicely encapsulating test configuration in one place (the fixture function). See the docs for many more examples.

like image 124
hpk42 Avatar answered Nov 14 '22 22:11

hpk42


This isn't really a task for tox. My recommendation is that you do this in the setup functions/methods of the actual unit testing framework (py.test, nose, unittests, ...) you are using with tox.

Original poster's comment:

pytest_configure and pytest_unconfigure in conftest.py was a good place to spawn/terminate.

like image 20
Pedro Romano Avatar answered Nov 14 '22 23:11

Pedro Romano


I recommend that you use paver - http://paver.github.com/paver/ - for the spawning up and shutting down of your memcached server or any additional "miscellaneous system admin tasks" that you need to do during the execution of setup.py by tox.

like image 32
Calvin Cheng Avatar answered Nov 14 '22 23:11

Calvin Cheng