2012-07-06 48 views
3

使用funcargs我包括conftetst.py我自己的命令行选项pytest - 内setup_module

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函数内部此命令行选项。 没有用,我尝试过。

感谢您的帮助,建议。

干杯

回答

3

有正在讨论这将允许使用在建立资源funcargs和您的使用情况下,API扩展是它的一个很好的例子。看到这里所讨论的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 .copying y的 Ÿ .X .Y

40.02秒

由于有下测试二后端通过你得到四个测试,但模块设置仅在模块中每个后端使用一次。

+0

我有这个轻微的扭曲,并找不到解决方案的用例:我想要在模块设置上调用后端特定的init方法,然后运行该后端的所有测试,调用拆卸方法并继续下一个后端。换句话说,我需要在模块上运行参数化而不是测试基础。这可以做到吗? – kynan 2012-07-20 18:22:06

+1

我刚刚更新了一些示例,希望它有帮助:http://pytest.org/dev/example/parametrize.html#grouping-test-execution-by-parameter – hpk42 2012-07-23 08:54:12

+0

这里是我对http:// pytest的投票.org/latest/resources.html#using-funcarg-resources-in-xunit-setup-methods。我只需要一个包含合成数据的文件即可生成一次,然后在所有测试中使用。 – Tobu 2012-10-12 09:58:39