接口自动化:测试用例参数化

上篇文章运行了第一个测试用例,但如果遇到多个用例时,就会写很多的代码,最后导致代码冗余且可维护性特别差...

接下来就引入了数据参数化的操作;pytest框架中的parametrize就是专门处理参数化的装饰器...

图片


import pytest
import requests

data = [
    [{"type": 1}, {"reason": "fff"}],
    [{"type": 2}, {"reason": "fff"}],
    [{"type": 3}, {"reason": "fff"}]
]


class TestExample:
    s = requests.Session()

    @pytest.mark.parametrize("test_data, expected", data)
    def test_example(self, test_data, expected):
        print(test_data, expected)
        

if __name__ == '__main__':
    pytest.main(["-v", "-s", "test_example"])

============================= test session starts ==============================
collecting ... collected 3 items

test_example.py::TestExample::test_example[test_data0-expected0] PASSED  [ 33%]{'type': 1} {'reason': 'fff'}

test_example.py::TestExample::test_example[test_data1-expected1] PASSED  [ 66%]{'type': 2} {'reason': 'fff'}

test_example.py::TestExample::test_example[test_data2-expected2] PASSED  [100%]{'type': 3} {'reason': 'fff'}


============================== 3 passed in 0.12s ===============================

Process finished with exit code 0

print 打印了test_data和expected,从运行后的结果可以清晰的看到显示的数据信息。

test_data接收的是接口需要传递的参数;expected接收的是预期结果,用于对接口返回值进行校验是否相等...

  1. pytest框架参数化操作
  2. pytest框架参数化操作

上述引用的两篇文章总结了pytest中的parametrize的基本使用,可自行阅读...

接口中引入测试数据及预期结果后,开始运行代码


import pytest
import requests

data = [
    [{"type": 1}, {"reason": "查询成功!"}],
    [{"type": 2}, {"reason": "查询成功!"}],
    [{"type": 3}, {"reason": "查询成功!"}]
]


class TestExample:
    s = requests.Session()

    @pytest.mark.parametrize("test_data, expected", data)
    def test_example(self, test_data, expected):
        with self.s as s:
            url = "http://apis.juhe.cn/fapig/euro2020/schedule?key=9d0dfd9dbaf51de283ee8a88e58e218b"
            response = s.get(url, params=test_data)

            assert response.json()["reason"] == expected["reason"]


if __name__ == '__main__':
    pytest.main(["-v", "-s", "test_example"])

============================= test session starts ==============================
collecting ... collected 3 items

test_example.py::TestExample::test_example[test_data0-expected0] 
test_example.py::TestExample::test_example[test_data1-expected1] 
test_example.py::TestExample::test_example[test_data2-expected2] 

============================== 3 passed in 1.13s ===============================

Process finished with exit code 0

从结果可以看到,3个passed,用时1.13s

至此,参数化减少了部分代码的重复性,也初步具备了代码的可读性和可维护性...

图片

以上总结或许能帮助到你,或许帮助不到你,但还是希望能帮助到你,如有疑问、歧义,直接私信留言会及时修正发布;感觉还不错记得点赞呦,谢谢!

未完,待续…

一直都在努力,希望您也是!

微信搜索公众号:就用python

更多内容欢迎关注公众号
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值