对于一些场景需要大量数据来支撑的测试,就可以用到参数化来节省手工测试所花费的时间
pytest参数化需要用到装饰器:parametrize
用户,导入pytest模块之后,在函数上方使用,效果如下:
import pytest @pytest.mark.parametrize("id,goodscode,goodsname",[ (12,"sp_1235444444","python 入门到放弃!!!"), (13,"sp_100001","python 入门到放弃!!!"), (14,"sp_111111","python 入门到放弃!!!")]) def test_update_goods(ke_login_setup,id,goodscode,goodsname): print("setp1:修改商品信息") res = updata_goods(ke_login_setup,id=id,goodscode=goodscode,goodsname=goodsname) print(res.json()) #断言 assert res.json()["code"] == 0 assert res.json()["msg"] == "success!"
也可以将参数拿出来单独写进一个列表中,实现简单的代码与数据分离,实现效果如下:
import pytest test_data = [ (12,"sp_1235444444","python 入门到放弃!!!"), (13,"sp_100001","python 入门到放弃!!!"), (14,"sp_111111","python 入门到放弃!!!")] @pytest.mark.parametrize("id,goodscode,goodsname",test_data) def test_update_goods(ke_login_setup,id,goodscode,goodsname): print("setp1:修改商品信息") res = updata_goods(ke_login_setup,id=id,goodscode=goodscode,goodsname=goodsname) print(res.json()) #断言 assert res.json()["code"] == 0 assert res.json()["msg"] == "success!"
也可以实现参数组合的情况,参数组合遵循“笛卡尔积”的方式
pytest使用装饰器的叠加进行参数组合,注意:离函数近的装饰器优先执行
import pytest test_goodscode = ["sp_1235444444"] test_goodsname = ["python 入门到放弃!!!","python 入门到结束!!!","python 入门到精通!!!"] @pytest.mark.parametrize("goodsname",test_goodsname) @pytest.mark.parametrize("goodscode",test_goodscode) def test_update_goods(ke_login_setup,goodscode,goodsname): print("setp1:修改商品信息") res = updata_goods(ke_login_setup,goodscode=goodscode,goodsname=goodsname) print(res.json()) #断言 assert res.json()["code"] == 0 assert res.json()["msg"] == "success!"
以上测试数据都是在代码文件内的,没有达到真正的代码与数据分离
达到代码与数据分离可以用到yaml文件或者json文件内,以下实现为存放在yaml文件:
‘‘‘读取yaml文件‘‘‘ # 获取当前文件的绝对路径 cur_path = os.path.dirname(os.path.realpath(__file__)) # 获取当前文件上一级路径 yml_path = os.path.dirname(cur_path) # 拼接获取data_test.yml测试数据的文件的相对路径 data_path = os.path.join(yml_path, "ke11", "data_test.yml") test_date = read_data_yml(data_path) print(test_date) @pytest.mark.parametrize("goodsid,goodscode,goodsname",test_date) def test_update_goods(ke_login_setup,goodsid,goodscode,goodsname): print("setp1:修改商品信息") res = updata_goods(ke_login_setup,goodsid=goodsid,goodscode=goodscode,goodsname=goodsname) print(res.json()) #断言 assert res.json()["code"] == 0 assert res.json()["msg"] == "success!"
原文:https://www.cnblogs.com/LT-XILI/p/14775038.html