2014-09-12 34 views
1

注入值我有这种风格的测试模块:全球灯具,从当前模块

#test_mammals.py: 

PETS = ['cats', 'dogs'] 

def test_mammals_1(pet): 
    assert 0, pet 

def test_mammals_2(pet): 
    assert 0, pet 

在这里,另一个问题:

#test_birds.py: 

PETS = ['budgie', 'parrot'] 

def test_birds_1(pet): 
    assert 0, pet 

def test_birds_2(pet): 
    assert 0, pet 

而且我想定义夹具“宠物”只曾经:

#conftest.py: 

import pytest 

@pytest.fixture(scope='module', autouse=True) 
def getpets(request): 
    return getattr(request.module, 'PETS', []) 

@pytest.fixture(scope='module', params=getpets, autouse=True) 
def pet(request): 
    return request.param 

不幸的是,这不起作用,因为“宠物”期望“params”列表。但是如果我把“getpets”放到一个列表中,那么ficture将会返回一个指向“getpets”的指针,而不是来自相应模块的“PETS”的值。

回答

0

这有点难以回答,因为你的代码没有多大意义 - 如果你的'PETS'真的只是一个字符串列表,你应该只使用pytest.mark.parametrize,你不需要事实上任何特殊的事物,或任何夹具。

但是,如果你有更复杂的事情发生,最容易做的事情是在conftest中有一个通用夹具,并且在每个测试模块中,定义一个轻量级夹具,该夹具具有该模块的特定数据,您的通用pet灯具以任何需要的方式。