news 2026/7/18 18:22:27

pytest使用教程

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
pytest使用教程

pytest使用教程

一、pytest框架

1.1 pytest简介

pytest是Python生态中最强大、最流行的自动化测试框架,具有以下特点:

  • 简洁语法:使用原生assert语句,无需记忆复杂的断言方法
  • 自动发现:自动识别测试文件和测试函数
  • 强大的fixture:依赖注入机制,实现测试前后置处理
  • 丰富的插件生态:覆盖HTML报告、并行执行、覆盖率等场景
  • 良好的兼容性:可直接运行unittest用例

1.2 安装方式

# 基础安装pipinstallpytest# 安装常用插件pipinstallpytest-html pytest-xdist pytest-rerunfailures

1.3 命名规则

pytest采用约定优于配置的设计,测试用例需遵守以下命名规范:

类型规则示例
测试文件test_*.py*_test.pytest_login.py,login_test.py
测试函数test_开头def test_login_success()
测试类Test开头,不含__init__class TestLogin:

1.4 编写第一个测试用例

# test_sample.pydefadd(a,b):returna+bdeftest_add_positive_numbers():assertadd(2,3)==5deftest_add_negative_numbers():assertadd(-1,-1)==-2classTestMathOperations:deftest_multiply(self):assert2*3==6

1.5 运行测试

# 运行当前目录下所有测试pytest# 运行指定文件pytest test_sample.py# 运行指定函数pytest test_sample.py::test_add_positive_numbers# 运行指定类的方法pytest test_sample.py::TestMathOperations::test_multiply

1.6 常用命令行参数

参数作用示例
-v显示详细信息pytest -v
-s显示print输出pytest -s
-x失败即停止pytest -x
--lf只运行上次失败的用例pytest --lf
-k按关键字筛选pytest -k "add"
-m按标记筛选pytest -m smoke
--html=report.html生成HTML报告pytest --html=report.html
-n auto多线程并行执行pytest -n auto

1.7 断言用法

deftest_assertions():# 基本断言assert1==1assert"hello"in"hello world"assert10>5# 断言异常withpytest.raises(ZeroDivisionError):10/0# 断言包含特定消息的异常withpytest.raises(ValueError,match="invalid"):raiseValueError("invalid value")

1.8 Fixture(夹具)

1.8.1 基本用法
importpytest@pytest.fixturedeflogin_user():"""返回登录用户数据"""return{"username":"test","password":"123456"}deftest_login(login_user):username=login_user["username"]password=login_user["password"]assertusername=="test"
1.8.2 Fixture作用域
作用域生命周期适用场景
function每个测试函数临时数据
class每个测试类类级共享状态
module每个测试文件数据库连接
session整个测试会话WebDriver实例
@pytest.fixture(scope="session")defbrowser():driver=webdriver.Chrome()yielddriver driver.quit()
1.8.3 带清理的Fixture
@pytest.fixturedefdb_connection():"""创建数据库连接,测试后自动关闭"""conn=create_connection()yieldconn conn.close()
1.8.4 conftest.py

conftest.py是pytest的特殊文件,放在该文件中的fixture无需导入即可全局使用:

# tests/conftest.pyimportpytest@pytest.fixture(scope="session")defbase_url():return"https://api.example.com"@pytest.fixture(scope="function")defauth_token():return"Bearer test-token"

1.9 参数化测试

importpytest@pytest.mark.parametrize("username,password,expected",[("admin","123456",True),("admin","wrong",False),("nonexistent","123456",False),("","123456",False),])deftest_login_parametrized(username,password,expected):result=authenticate(username,password)assertresult==expected

1.10 测试标记

importpytest@pytest.mark.smokedeftest_login():pass@pytest.mark.regressiondeftest_checkout():pass@pytest.mark.skip(reason="功能尚未实现")deftest_feature_not_implemented():pass@pytest.mark.xfail(reason="已知bug")deftest_known_bug():pass

运行带标记的测试:

pytest-msmoke# 只运行冒烟测试pytest-m"not slow"# 排除慢速测试

1.11 生成测试报告

# HTML报告pytest--html=reports/test_report.html# Allure报告(需安装allure-pytest)pipinstallallure-pytest pytest--alluredir=reports/allure_results allure serve reports/allure_results

1.12 实战示例:API接口测试

# test_api.pyimportpytestimportrequests@pytest.fixturedefapi_client():returnrequests.Session()@pytest.fixturedefbase_url():return"https://jsonplaceholder.typicode.com"classTestUserAPI:deftest_get_users(self,api_client,base_url):response=api_client.get(f"{base_url}/users")assertresponse.status_code==200assertisinstance(response.json(),list)deftest_get_user_by_id(self,api_client,base_url):response=api_client.get(f"{base_url}/users/1")assertresponse.status_code==200user=response.json()assertuser["id"]==1assert"name"inuserdeftest_create_user(self,api_client,base_url):payload={"name":"Test User","email":"test@example.com"}response=api_client.post(f"{base_url}/users",json=payload)assertresponse.status_code==201created_user=response.json()assertcreated_user["name"]==payload["name"]

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/18 18:22:04

每日关注简报|ChatGPT 桌面端、Win11 24H2 与硬件行情

🔥 个人主页: 杨利杰YJlio ❄️ 个人专栏: 《Windows 疑难杂症与工单复盘案例库》 《Sysinternals实战教程》 《WINDOWS教程》 《Windows PowerShell 实战》 《IOS插件分析测试》 《超简单:用Python让Excel飞起来》…

作者头像 李华
网站建设 2026/7/18 18:10:23

零基础新手背书神器怎么选,避坑指南看完就能直接上手

零基础新手选背书神器,核心记住两个判断标准就不会错,第一是能直接把你已有的付费课录音、播客内容整理成可直接背的素材,不用你手动抄录整理,第二是能精准筛选出你没掌握的内容,不用你盲目过完整本内容。接下来讲清楚…

作者头像 李华
网站建设 2026/7/18 18:10:16

ADC原理与应用:从基础到嵌入式系统实践

1. 模拟数字转换器(ADC)的基本概念 模拟数字转换器(Analog-to-Digital Converter,简称ADC)是现代电子系统中不可或缺的关键组件。简单来说,ADC的作用就是将连续变化的模拟信号(如声音、温度、压…

作者头像 李华
网站建设 2026/7/18 18:09:36

植物大战僵尸修改器终极指南:5个创意玩法让你重燃游戏激情

植物大战僵尸修改器终极指南:5个创意玩法让你重燃游戏激情 【免费下载链接】pvztoolkit 植物大战僵尸 PC 版综合修改器 项目地址: https://gitcode.com/gh_mirrors/pv/pvztoolkit 还在为植物大战僵尸的重复关卡感到厌倦吗?想要创造属于自己的独特…

作者头像 李华
网站建设 2026/7/18 18:09:30

Intel-glibc企业级部署:生产环境最佳实践指南

Intel-glibc企业级部署:生产环境最佳实践指南 【免费下载链接】Intel-glibc glibc with Intel specific enhancements 项目地址: https://gitcode.com/openeuler/Intel-glibc 前往项目官网免费下载:https://ar.openeuler.org/ar/ Intel-glibc作为…

作者头像 李华