一、特点
pytest是unittest的升级版,可以结合allure生成定制版测试报告,支持很多强大的第三方插件, allure-pytest, pytest-xdist,pytest-ordering...
二、使用规则
pytest默认规则:
1. 模块名必须以test_开头或者_test结尾
2. 测试类必须以Test开头,并且不能有init方法
3. 测试方法必须以test开头
unittest默认规则:
1. 测试文件必须先导入Import unittest
2. 测试类必须基础unittest.TestCase
3. 测试方法必须以test开头
三、用例的前置/后置
pytest:
方法集:
1. setup_method: 类里面每个用例执行前都会执行setup_method
2. teardown_method: 类里面每个用例结束后都会执行teardown_method
3. setup: 类里面每个用例执行前都会执行setup
4. teardown : 类里面每个用例结束后都会执行teardown
优先级:
setup_method-->setup-->teardown_method-->teardown
函数级:
setup_function/teardown_function 在每个函数级别用例开始前和结束后
类级:
setup_class/teardown_class 在整个测试类开始前和结束后
模块级:
setup_module: 整个.py模块开始前执行一次setup_module
teardown_module: 整个.py模块结束后执行一次teardown_module
unittest:
1. setUp或teardown 在每个用例之前和之后运行一次
2. setUpClasee和tearDownClass 在每个类运行之前或之后运行一次
3. setUpModule和teadDownModule 在每个模块之前和之后运行一次
四、断言
pytest:assert
unittest:assertTrue, assertEqual, assertin等
五、报告
pytest: allure报告,需要插件pytest-HTML
unittest: html报告,需要HTMLTestRunner插件
六、失败重跑
pytest: 支持,需要pytest-rerunfailures
unittest: 不支持
七、数据驱动
pytest:@pytest.fixture, @pytest.mark.parametrize
unittest: ddt
八、用例分类执行
pytest:@pytest.mark
unittest:默认执行所有,也可以通过testsuite来执行部分用例,或者-k参数