上篇文章运行了第一个测试用例,但如果遇到多个用例时,就会写很多的代码,最后导致代码冗余且可维护性特别差...
接下来就引入了数据参数化的操作;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接收的是预期结果,用于对接口返回值进行校验是否相等...
- pytest框架参数化操作
- 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
|