3

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

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)

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

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 函数中访问此命令行选项。没有任何效果,我试过了。

感谢您的帮助,建议。

干杯

4

1 回答 1

2

有一个 API 扩展正在讨论中,它允许在设置资源中使用 funcargs,您的用例就是一个很好的例子。有关正在讨论的 V2 草案,请参见此处: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

4 个在 0.02 秒内通过

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

于 2012-07-06T08:55:20.583 回答