2012-07-06 50 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