我感觉第二种参数化方式的步骤比第一种更繁琐,请问平时工作中那种方式用的多呢?第二种参数化方式有什么优点吗?
参数化方式一:
直接在测试用例上加@pytest.mark.parametrize
def get_data(level):
with open("datas/data.yml", encoding='utf-8') as f:
datas = yaml.safe_load(f)
add_datas = datas.get("add")
div_datas = datas.get("div")
return (add_datas.get(level),div_datas.get(level))
add_P0_datas = get_data("P0")[0].get("datas")
add_P0_ids = get_data("P0")[0].get("ids")
calc = Calculator()
@pytest.mark.parametrize("a,b,expect", add_P0_datas, ids=add_P0_ids)
def test_case_add_p0(self, a, b, expect):
print(a, b, expect)
assert expect == self.calc.add(a, b)
参数化方式二:使用fixture
def get_data_from_yaml(name,level='P0'):
with open("datas/data.yml", encoding='utf-8') as f:
data = yaml.safe_load(f)
datas = data[name][level]['datas']
ids = data[name][level]['ids']
return(datas,ids)
@pytest.fixture(autouse=True)
def get_instance():
calc = Calculator()
yield calc
@pytest.fixture(params=get_data_from_yaml('add','P0')[0],ids=get_data_from_yaml('add','P0')[1])
def get_datas_with_feature_add_p0(request):
return request.param
def test_add_p0(self, get_instance,get_datas_with_feature_add_p0):
f = get_datas_with_feature_add_p0
print(f[0],f[1],f[2])
assert f[2] == round(get_instance.add(f[0], f[1]),3)