pytest - use funcargs inside setup_module

纵饮孤独 提交于 2019-12-04 12:06:43

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!