pytest - 在 setup_module 中使用 funcargs

2024-04-11

我在 conftetst.py 中包含了我自己的命令行选项

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)

如果我在模块内的普通函数内使用此命令行选项:

module: test_this.py;  

def test_me(backend): 
  print backend

它按预期工作。

现在我想包含 setup_module 函数来在一些测试之前创建/复制一些东西:

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

不幸的是,我现在知道如何访问 setup_module 函数内的此命令行选项。 没有任何作用,我尝试过。

感谢您的帮助、建议。

Cheers


有一个正在讨论的 API 扩展,它允许在设置资源中使用 funcargs,您的用例就是一个很好的例子。请参阅此处查看正在讨论的 V2 草案:http://pytest.org/latest/resources.html http://pytest.org/latest/resources.html

今天,您可以这样解决您的问题::

# 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

给定一个包含两个测试的测试模块:

def test_me(backend):
    print backend

def test_me2(backend):
    print backend

然后你可以运行来检查事情是否按照你的预期发生:

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

收集了 4 件物品 复制 x X .复制 y y 。X .y

0.02秒内4人通过

由于有两个正在测试的后端,您将获得四个测试,但模块设置仅针对模块中使用的每个后端完成一次。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pytest - 在 setup_module 中使用 funcargs 的相关文章

随机推荐