2016-09-14 36 views
0

我的目標是從一個位於conftest.py中的pytest.fixture中訪問test_function的「args」,以便pytest .skip()如果滿足某個條件。py.test:如何從@ pytest.fixture中訪問test_function的參數

這裏是conftest.py代碼:

# conftest.py 
import pytest 

def pytest_generate_tests(metafunc): 
    if 'param1' in metafunc.fixturenames: 
     metafunc.parametrize("param1", [0, 1, 'a', 3, 4]) 

@pytest.fixture(autouse=True, scope="function") 
def skip_if(request): 
    # I want to do something like this 
    # (but obviously request.node.param1 is not a real attribute): 
    if request.node.param1 == 'a': 
     xfail() 

而且test.py代碼:

# test.py 

def test_isdig(param1): 
    assert isinstance(param1, int) 

有誰碰巧知道如果請求對象可以smoehow有機會獲得當前param1的值,這樣我的自動跳過skip_if()夾具可以在一定條件下跳過它?我知道我可以將pytest.skip()調用放入test_isdig()中,但我試圖從夾具內部以某種方式進行調用。任何建議/指導非常感謝!

回答

1

將參數添加到夾具以及測試功能似乎工作。

測試代碼:

import pytest 

def pytest_generate_tests(metafunc): 
    if 'param1' in metafunc.fixturenames: 
     metafunc.parametrize("param1", [0, 1, 'a', 3, 4]) 

@pytest.fixture(autouse=True, scope="function") 
def skip_if(param1): 
    if param1 == 'a': 
     pytest.xfail() 

def test_isint(param1): 
    assert isinstance(param1, int) 

結果:但是

============================= test session starts ============================= 
platform win32 -- Python 3.5.2, pytest-3.0.0, py-1.4.31, pluggy-0.3.1 
rootdir: D:\Development\Hacks\StackOverflow\39482428 - Accessing test function p 
arameters from pytest fixture, inifile: 
collected 5 items 

test_print_request_contents.py ..x.. 

===================== 4 passed, 1 xfailed in 0.10 seconds ===================== 

注意,這skip_if燈具將爲所有的測試運行,無論他們是否有param1參數,所以這可能是有問題的。在這種情況下,最好將夾具明確包含在相關測試中,或者甚至將參數包裹在夾具中,以便只有夾具具有param1作爲參數,然後返回,並且測試代替夾具作爲其參數。

+0

太棒了,非常感謝。這將很好地工作。是的,我需要聽取您的建議,並使該設備不是autouse = true,並將其作爲相關測試中的固定設備。或者我想我可以在燈具中放置一個try/except塊,但這看起來不太雅緻。再次感謝,超級有用的人! –