1.pytest的特点:
pytest是一个非常成熟的全功能的Python测试框架,主要有以下几个特点:
简单灵活,容易上手;
支持参数化;
能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests);
pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等;
测试用例的skip和xfail处理;
可以很好的和jenkins集成;
report框架----allure 也支持了pytest。
2.pytest的规则
编写pytest测试样例需要按照下面的规则:
测试文件以test_开头(以_test结尾也可以);
测试类以Test开头,并且不能带有 init 方法;
测试函数以test_开头;
断言使用基本的assert即可。
3.pytest的运行模式
运行后生成测试报告(htmlReport):
pip install -U pytest-html
pytest ** --html=report.html
运行指定的case:
模式1:直接运行test_se.py文件中的所有cases: pytest test_se.py
模式2:运行test_se.py文件中的TestClassOne这个class下的两个cases: pytest test_se.py::TestClassOne
模式3:运行test_se.py文件中的TestClassTwo这个class下的test_one: pytest test_se.py::TestClassTwo::test_one
多进程运行cases:
pip install -U pytest-xdist
pytest test_se.py -n NUM
重试运行cases:
pip install -U pytest-rerunfailures
pytest test_se.py --reruns NUM
显示print内容:
pytest test_se.py -s
另外,pytest的多种运行模式是可以叠加执行的,比如说,你想同时运行4个进程,又想打印出print的内容。可以用:
pytest test_se.py -s -n 4
4.pytest的参数化:
如需对某测试用例(testcase)实现参数化数据驱动,需要使用parameters关键字,定义参数名称并指定数据源取值方式。
参数名称的定义分为两种情况: * 独立参数单独进行定义; * 多个参数具有关联性的参数需要将其定义在一起,采用短横线(-)进行链接。
数据源支持三种方式:
1. 脚本中直接指定参数列表:该种方式最为简单易用,适合参数列表比较小的情况。示例:
parameters:
uid: [101, 102, 103]
username-password:
- [ "user1", "111111" ]
- [ "user2", "222222" ]
- [ "user3", "333333" ]
例:
from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase
class TestCasePromotionGet(HttpRunner):
@pytest.mark.parametrize(
"param", Parameters({"id": [1, 2]})
)
def test_start(self, param):
super().test_start(param)
config = (
Config("查询海报")
.base_url("${read_ini_config(Host, manage_host)}")
.variables()
.verify(False)
.export("data")
)
teststeps = [
Step(
RunRequest("查询海报")
.get("/api/realfix-v2-app/promotion/get")
.with_headers(**{"autel-token": "${get_login_info(manage, token)}"})
.with_params(**{"client":"$id"})
.extract()
.with_jmespath("body.data", "data")
.validate()
.assert_equal("status_code", 200)
.assert_equal("body.code", 200)
.assert_equal("body.message", "success")
.assert_length_greater_or_equals("body.data", 2)
)
]
if __name__ == '__main__':
TestCasePromotionGet().test_start()
2.通过内置的parameterize(可简写为P)函数引用CSV文件:该种方式需要准备CSV数据文件,适合数据量比较大的情况。 示例:
parameters:
apkchannel: ${P(data/vip.csv)}
3.在debugtalk.py中自定义的函数生成参数列表:该种方式最为灵活,可通过自定义Python函数实现任意场景的数据驱动机制,当需要动态生成参数列表时也需要选择该种方式。 示例:
parameters:
username-password: ${get_account(10)}