2016-01-09 52 views
2

我坐下来今天更好地学习py.test,发现网站的文档已关闭(pytest.org),所以我很抱歉如果在这里找到了这个问题的答案。pytest中参数的输出

我想要做的是两场比赛的输出传递到参数多态,像这样:

import pytest 

@pytest.fixture() 
def make_1(): 
    return 1 

@pytest.fixture() 
def make_2(): 
    return 2 

@pytest.mark.parametrize('arg', [make_1, make_2]) 
def test_main(arg): 
    assert isinstance(arg, int) 

但测试失败,因为,而不是分配灯具参数“ARG”的输出灯具(功能)本身被传递。

如何以这种方式参数化各种灯具的输出?

+0

是否有一个原因,你不能让'make_1'成为一个普通的函数 - 它需要是一个灯具,因为它使用其他灯具或什么? –

+0

在参数化中不能使用fixtue。 https://bitbucket.org/pytest-dev/pytest/issues/349/using-fixtures-in-pytestmarkparametrize –

+0

这也是一个非常有用的解决方法:https://github.com/pytest-dev/pytest/issues/ 349#issuecomment-189370273 – derchambers

回答

1

这个[丑陋/大规模黑客]会诀窍吗?我很欣赏它远非理想 - 我不知道是否有办法创建一个懒惰评估的灯具,让你做你想做的事情。

import pytest 

@pytest.fixture 
def make_1(): 
    return 1 

@pytest.fixture 
def make_2(): 
    return 2 

@pytest.fixture 
def all_makes(make_1, make_2): 
    return (make_1, make_2) 

def _test_thing(make): 
    # Run your test 
    pass 

def test_main(all_makes): 
    for make in all_makes: 
     try: 
      _test_thing(make) 
     except AssertionError: 
      print "Failed for make {}".format(make) 
      raise 

一个可能是更好的替代方法可能是参数灯具本身(如果可能的话) - 参考文档:https://pytest.org/latest/fixture.html#parametrizing-a-fixture

@pytest.fixture(params=[1, 2]) 
def make(request): 
    return request.param 

def test_make(make): 
    # Run your test 
    pass 

如果你的不同“使”灯具超级不同,你可以有像这样:

def build_make_1(): 
    return 1 

def build_make_2(): 
    return 2 

@pytest.fixture(params=[build_make_1, build_make_2]) 
def make(request): 
    return request.param() 

def test_make(make): 
    # Run your test 
    pass 
+0

是的,使用夹具来调用函数,就像在你的最后一个例子中一样,应该可以正常工作,并且编写一个额外的夹具来收集和调用函数并不是什么大不了的事情。感谢你的回答!我也检查过,即使有多个使用它们的测试,看起来make作用域上的scope =“module”仍然只会调用每个函数。 – derchambers