Pytest
常见插件
| pytest-html | 生成html格式的自动化测试报告 |
| pytest-xdist | 测试用例多线程执行 |
| pytest-ordering | 改变测试用例执行顺序 |
| pytest-rerunfailures | 用例失败后重跑 |
| pytest-timeout | 设置用例超时时间 |
| allure-pytest | 用于生成美观的测试报告 |
| pytest-repeat | 用于重复执行某个函数 |
运行指令
pytest test_mod.py #运行模块中的测试
pytest testing/ #运行目录中所有的测试
pytest -k 'MyClass and not method' #按关键字表达式运行测试
按集合参数运行测试
传入相对于工作目录的模块文件名,后跟由 `::` 字符分隔的类名和函数名等说明符,以及用 `[]` 括起来的参数化参数。
pytest tests/test_mod.py::test_func #在模块内运行特定测试
pytest tests/test_mod.py::TestClass #运行类中的所有测试
pytest tests/test_mod.py::test_func[x1,y2] #指定测试的特定参数化
按标记表达式运行测试
pytest -m slow
# 运行所有使用 @pytest.mark.slow 装饰器装饰的测试
pytest -m "slow(phase=1)"
#运行所有使用带注释的 @pytest.mark.slow(phase=1) 装饰器装饰的测试,其中 phase 关键字参数设置为 1
pytest --pyargs pkg.testing
# 这将导入 pkg.testing 并使用其文件系统位置查找并运行测试。
| 参数 | 解释 | 用法 |
| -x | 用例一旦失败,就立刻停止执行 | |
| --maxfail | 失败用例达到多少停止执行 | --maxfail 10 |
| -k | 执行包含某个关键字的测试用例,可以在关键字之间添加 and、or、not 关键字 | -k 'tcp or udp' |
| -v | 显示更多详细信息 | |
| -s | 打印输出调试信息,包括print打印,和-v连用 | -vs |
| -n | 多线程或者分布式运行测试用例 | -n 2 |
| --reruns | 失败用例重跑,后面跟重跑次数 | --reruns 3 |
| -m | 运行对应标签的测试例,可以在标签之间添加 and、or、not 关键字 | -m 'smoke or tcpip' |
| --html | 生成html格式的测试报告 | |
| --alluredir | 生成allure测试报告 | --alluredir=./allure-results |
测试文件、类、函数的格式
测试文件默认格式为test.py或test.py
测试类默认格式为 Test*
测试函数默认格式为 test*
import pytest
class TestClass:
def test_case_1(self):
print("test case 1")
assert 1 == 1
def test_case_2(self):
print("test case 2")
assert 1 == 2
def test_case_3(self):
print("test case 3")
assert 1 == 3
def test_case_4(self):
print("test case 4")
assert 4 == 4
测试例的前后置
函数级别的 setup/teardown,运行于测试方法的始末,即:运行一次测试函数会运行一次setup和teardown
类级别的 setupclass/teardownclass,运行于测试类的始末,在一个测试内只运行一次setupclass和teardownclass,不关心测试类内有多少个测试函数。
class TestClass:
def setup_class(self):
print("\n测试类前置")
def teardown_class(self):
print("\n测试类后置")
def setup(self):
print("\n测试函数前置")
def teardown(self):
print("\n测试函数后置")
def test_case_1(self):
print("test case 1")
assert 1 == 1
def test_case_2(self):
print("test case 2")
assert 2 == 2
1503

被折叠的 条评论
为什么被折叠?



