【pytest】六、pytest之parametrize()参数化,实现数据驱动

一、@pytest.mark.parametrize()的基本用法
@pytest.mark.parametrize(args_name,args_value)
args_name:参数名称,用于将参数值传递给函数
args_value:参数值(格式:列表、字典列表、元组、字典元组),有N个值,用例就会执行N次。

第一种用法:

    @pytest.mark.parametrize('caseinfo',['Lucy','Lily','Rose'])
    def test_tangseng(self,caseinfo):
        print("0616测试登录成功-唐僧"+caseinfo)

第二种用法:数据驱动的参数名,数据驱动的参数值

@pytest.mark.parametrize(“实际变量,预期变量”,[‘实际表达式的值计算’,预期结果值])

    @pytest.mark.parametrize("x,y,expect",[(2,5,7),(11,12,23),(99,1,100),(21,12,90)])
    def test_add(self,x,y,expect):
        result = add(x,y)
        assert result == expect

二、@pytest.mark.parametrize()的数据驱动
根据数据的不一样,驱动测试用例执行,并得到对应的结果。

    @pytest.mark.parametrize('caseinfo', read_yaml_testcase('testcase/test_file_upload.yaml'))
    def test_login_01(self, caseinfo):
        print(caseinfo)
        name = caseinfo['name']
        method = caseinfo['request']['method']
        url = caseinfo['request']['url']

        # 请求头中的token,需要python赋值
        headers = caseinfo['request']['headers']
        headers["Authorization"] = read_extract_yaml("Authorization")
        
        # data得到的是一个字典,所以需要通过键值对,取值后,再以二进制流的形式上传文件
        data = caseinfo['request']['files']
        for key,value in data.items():
            print(key,value)
            data[key] = open(value,'rb')
        
        res = RequestsUtil().send_all_request(method=method, url=url, headers=headers, files=data)
        print(headers)
        print(res.json())

思考:

1、如果有接口关联,那么在一个接口中,无法直接调用python的方法,而是需要在下个接口中通过调用方法取覆盖值
2、如果在yaml中,调用随机数方法
3、一个接口对应一个yaml,如果一个接口有很多反例,那么yaml里将会有很多数据,如何精简?
4、断言封装

猜你喜欢

转载自blog.csdn.net/Moonlight_16/article/details/123205425