looki
looki

Reputation: 555

pytest - use funcargs inside setup_module

I include at conftetst.py my own command line options

def pytest_addoption(parser):
    parser.addoption("--backend" , default="test_backend",
        help="run testx for the given backend, default: test_backend")

and

def pytest_generate_tests(metafunc):
    if 'backend' in metafunc.funcargnames:
       if metafunc.config.option.backend:
          backend = metafunc.config.option.backend
          backend = backend.split(',')
          backend = map(lambda x: string.lower(x), backend)
        metafunc.parametrize("backend", backend)

If I use this command line option inside a normal function inside a module:

module: test_this.py;  

def test_me(backend): 
  print backend

it works as expected.

Now I want to include the setup_module function to create /copy some stuff before some tests:

def setup_module(backend):
   import shutil
   shutil.copy(backend, 'use_here')
   ...

unfortunately I have now idea how to get access to this command line option inside the setup_module function. Nothing works, what I tried.

Thanks for help, suggestions.

Cheers

Upvotes: 3

Views: 1687

Answers (1)

hpk42
hpk42

Reputation: 23601

There is a API-extension under discussion which would allow to use funcargs in setup resources and your use case is a good example for it. See here for the V2 draft under discussion: http://pytest.org/latest/resources.html

Today, you can solve your problem like this::

# contest of conftest.py

import string

def pytest_addoption(parser):
    parser.addoption("--backend" , default="test_backend",
        help="run testx for the given backend, default: test_backend")

def pytest_generate_tests(metafunc):
    if 'backend' in metafunc.funcargnames:
        if metafunc.config.option.backend:
            backend = metafunc.config.option.backend
            backend = backend.split(',')
            backend = map(lambda x: string.lower(x), backend)
        metafunc.parametrize("backend", backend, indirect=True)

def setupmodule(backend):
    print "copying for", backend

def pytest_funcarg__backend(request):
    request.cached_setup(setup=lambda: setupmodule(request.param),
                         extrakey=request.param)
    return request.param

Given a test module with two tests:

def test_me(backend):
    print backend

def test_me2(backend):
    print backend

you can then run to check that things happen as you expect:

$ py.test -q -s --backend=x,y

collected 4 items copying for x x .copying for y y .x .y

4 passed in 0.02 seconds

As there are two backends under test you get four tests but the module-setup is only done once per each backend used in a module.

Upvotes: 2

Related Questions