Python好酷|zip函数的妙用

软件质量保障

专注测试圈,自动化测试、测试平台开发、测试新技术、大厂测试岗面经分享, 可以帮忙内推BATJ等大厂!欢迎加VX沟通交流: ISTE1024

zip()函数是Python的内置函数(build-in),参数为可迭代的对象,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

a = [1,2,3]
b = [4,5,6]
print(zip(a,b))
print(list(zip(a,b)))
>> <zip object at 0x7fd7a01d9b80>
[(1, 4), (2, 5), (3, 6)]

a1, a2 = zip(*zip(a,b)) 
print(a1)
print(a2)
>>(1, 2, 3)
(4, 5, 6)

而pytest的装饰器@pytest.mark.parametrize('参数名',list) 进行参数化所需的数据结构则是list;如果有多个参数名,则@pytest.mark.parametrize('参数名1,参数名2',[(参数1_data[0], 参数2_data[0]),(参数1_data[1], 参数2_data[1])]) 进行参数化的数据结构为[(参数1, 参数2),(参数1, 参数2)],这个结构则可以通过zip()函数生成。参考如下例子:

参考:Pytest系列(7)-数据驱动测试DDT

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   test_param_pytest.py
@Time    :   2021/06/12 12:58:42
@Author  :   软件质量保障
wechat   :   ISTE1024
@Email   :   byteflow@163.com
@Blog    :   https://www.zhihu.com/people/iloverain1024
@Copyright : 侵权必究
'''
import pytest

class Test():

    # 多参数传值
    @pytest.mark.parametrize("user, pwd", [("xiaoming",111111),("xiaohua",111111)])
    def test_002(self, user, pwd):
        print(user)
        assert user == 'xiaohua'
        assert pwd == 111111

所以,zip()函数结合@pytest.mark.parametrize装饰器,可以很好地实现DDT。只需将yaml中的测试数据经过zip()函数处理即可。

具体操作如下:

  1. 定义测试数据TEST_DATA_001.yaml文件。

- case: 测试登陆查询回答内容
  http:
    method: POST
    path: https://account.xinli001.com/login?next=https://www.xinli001.com/user
    headers:
      Content-Type: application/x-www-form-urlencoded; charset=UTF-8
      X-Requested-With: XMLHttpRequest
    body:
      password: xxxxxxxxxx
      username: 软件质量保障
  expected:
    response:
      message: 登陆成功
      code: 0
  1. 通过PyYAML对数据进行数据解析

 
  • def get_test_data(test_data_path:
        case = []  # 存储测试用例名称
        http = []  # 存储请求对象
        expected = []  # 存储预期结果
        data = yaml.safe_load(open(test_data_path, encoding='utf-8'))
        # test = data['tests']
        for td in data:
            case.append(td.get('case', ''))
            http.append(td.get('http', {}))
            expected.append(td.get('expected', {}))
        parameters = zip(case, http, expected)
        return list(parameters)

3. 结合装饰器@pytest.mark.parametrize

@pytest.mark.parametrize("case, http, expected", get_test_data('TEST_DATA_001.yaml'))
def test_main(case, http, expected, login):
    # 发起请求
    query_res = login.httpcore(method, url=url, headers=headers, data=body)
    print(query_res.json())
    # 断言
    assert query_res.json()['code'] == expected['response']['code']

喜欢就点个在看再走吧

往期推荐

接口测试框架开发实践4:HTTP方法封装

接口测试框架开发实践3:用例管理模块

经验分享|测试工程师转型测试开发历程

接口测试框架开发实践5:配置文件读取

接口测试框架开发实践2:接口自动化测试框架设计思路

接口自动化测试框架实践1:接口测试概述

Pytest系列(7)-数据驱动测试DDT

posted @ 2022-07-24 18:24  QualityAssurance21  阅读(51)  评论(0编辑  收藏  举报