pytest与unittest区别
一、安装
unittest是标准库,不需要安装
pytest是第三方库,需要安装
二、用例编写规则
unittest
- 测试文件必须先导入import unittest
- 测试类必须继承unittest.TestCase
- 测试方法必须以test开头
pytest
- 测试文件名必须以test_开头或者是_test结尾
- 测试类命名必须以Test开头
- 测试方法必须test开头
三、用例的前置和后置
unittest
- 模块级(setUpModule/tearDownModule)在模块始末调用
- 类级(setUpClass/tearDownClass)在类始末调用(在类中)
- 方法级(setUp/tearDown)在方法始末调用(在类中)
pytest
-
模块级(setup_module/teardown_module)在模块始末调用
-
函数级(setup_function/teardown_function)在函数始末调用(在类外部)注意加装饰器@classmethod
-
类级(setup_class/teardown_class)在类始末调用(在类中) 注意加装饰器@classmethod
-
方法级(setup_method/teardown_methond)在方法始末调用(在类中)
-
方法级(setup/teardown)在方法始末调用(在类中)
- 在函数前加@pytest.fixtrue(scope=“session/module/class/function”),scope与 yield 组合使用,相当于 setup 和 teardown 方法
四、断言
unittest
- assertEqual(a,b) 判断a和b是否相等
- assertNotEqual(a,b) 判断a不等于b
- assertTrue(a,b) 判断a是否为True
- assertFalse(a,b) 判断a是否为False
- assertIn(a,b)
- 。。。。等等
pytest
- assert a == b
- assert a != b
- assert a in b
五、测试报告
unittest:HTMLTestRunner
pytest:pytest-html、allure
六、失败重跑
unittest:没有
pytest:通过安装pytest-returnfailures插件,支持用例执行失败重跑
七、参数化
unittest
- @parameterized.expand(data),data为list格式的参数化的数据
pytest
- pytest.mark.parameterize('参数1, 参数2, 参数3,.....', [(), (), ()])
- pytest.mark.parameterize(("参数1", "参数2", "参数3",.....), [(), (), ()])
八、用例分类执行
unittest:默认执行所有,也可以通过testsuite来执行部分用例,或者-k参数
pytest:@pytest.mark skip, xfail

浙公网安备 33010602011771号