本文共 2033 字,大约阅读时间需要 6 分钟。
单元测试是软件开发中对功能的最小单元进行验证和测试的过程。Pytest 是一个成熟的 Python 单元测试框架,相较于 unittest,更灵活且易于上手。
通过 pip 安装 pytest:
pip install pytest
安装插件(如 HTML 报告、分布式执行等):
pip install -r requirements.txt
test_ 或 _test 结尾。TestXxx,不含 __init__ 方法。test_ 开头。pytest test_print.py
pytest ./tests
pytest ./tests/test_print.py::TestPrint::test_01_demo
-n 2)。--reruns=2)。Pytest 默认按文件顺序运行,可以通过 @pytest.mark.run(order=1) 更改顺序。
用于冒烟测试或模块分组执行:
@pytest.mark.smokedef test_01_baili(self): print("测试百里") 使用命令运行指定分组:
pytest -m "smoke or usermanage"
@pytest.mark.skipdef test_03(): print("测试3")@pytest.mark.skipif(condition, reason="原因")
结合 requests 库实现接口测试:
import requestsresponse = requests.post(url, json=data)response.status_code # 获取状态码response.json() # 解析 JSON
import yamldef read_yaml(key): with open('extract.yml', 'r') as f: data = yaml.load(f) return data[key]集成 allure 生成美观报告:
allure generate ./temp -o ./report
默认生成 HTML 格式报告。
@pytest.fixture(scope="function")def exec_database_sql(): print("前置操作-===数据库查询") yield print("后置操作=====数据校验")@pytest.fixture(params=["测试1", "测试2"])def param_info(self): yield param_info
通过 conftest.py 文件管理固件会话:
@pytest.fixture(scope="session", autouse=True)def exec_database_sql(): clear_yaml() print("前置操作-===所有请求前执行一次") yield print("后置操作=====所有请求之后执行一次") 使用 @pytest.mark.skip 或 @pytest.mark.skipif 注解。
使用 pytest-xdist 插件,通过 -n 参数指定线程数。
使用 allure 插件,通过命令生成 HTML 报告。
通过 @pytest.mark.parametrize 参数化测试用例:
@pytest.mark.parametrize("param_info,[['测试1'], ['测试2']]")def test_01(self, param_info): print(param_info) Pytest 是 Python 开发者必须掌握的工具,通过上述实用技巧,您可以高效地编写、执行和分析单元测试。希望这篇指南能为您的测试工作带来帮助!
转载地址:http://ajafk.baihongyu.com/