pytest使用教程

📅 2026/7/18 18:22:31
pytest使用教程
pytest使用教程一、pytest框架1.1 pytest简介pytest是Python生态中最强大、最流行的自动化测试框架具有以下特点简洁语法使用原生assert语句无需记忆复杂的断言方法自动发现自动识别测试文件和测试函数强大的fixture依赖注入机制实现测试前后置处理丰富的插件生态覆盖HTML报告、并行执行、覆盖率等场景良好的兼容性可直接运行unittest用例1.2 安装方式# 基础安装pipinstallpytest# 安装常用插件pipinstallpytest-html pytest-xdist pytest-rerunfailures1.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):returnabdeftest_add_positive_numbers():assertadd(2,3)5deftest_add_negative_numbers():assertadd(-1,-1)-2classTestMathOperations:deftest_multiply(self):assert2*361.5 运行测试# 运行当前目录下所有测试pytest# 运行指定文件pytest test_sample.py# 运行指定函数pytest test_sample.py::test_add_positive_numbers# 运行指定类的方法pytest test_sample.py::TestMathOperations::test_multiply1.6 常用命令行参数参数作用示例-v显示详细信息pytest -v-s显示print输出pytest -s-x失败即停止pytest -x--lf只运行上次失败的用例pytest --lf-k按关键字筛选pytest -k add-m按标记筛选pytest -m smoke--htmlreport.html生成HTML报告pytest --htmlreport.html-n auto多线程并行执行pytest -n auto1.7 断言用法deftest_assertions():# 基本断言assert11asserthelloinhello worldassert105# 断言异常withpytest.raises(ZeroDivisionError):10/0# 断言包含特定消息的异常withpytest.raises(ValueError,matchinvalid):raiseValueError(invalid value)1.8 Fixture夹具1.8.1 基本用法importpytestpytest.fixturedeflogin_user():返回登录用户数据return{username:test,password:123456}deftest_login(login_user):usernamelogin_user[username]passwordlogin_user[password]assertusernametest1.8.2 Fixture作用域作用域生命周期适用场景function每个测试函数临时数据class每个测试类类级共享状态module每个测试文件数据库连接session整个测试会话WebDriver实例pytest.fixture(scopesession)defbrowser():driverwebdriver.Chrome()yielddriver driver.quit()1.8.3 带清理的Fixturepytest.fixturedefdb_connection():创建数据库连接测试后自动关闭conncreate_connection()yieldconn conn.close()1.8.4 conftest.pyconftest.py是pytest的特殊文件放在该文件中的fixture无需导入即可全局使用# tests/conftest.pyimportpytestpytest.fixture(scopesession)defbase_url():returnhttps://api.example.compytest.fixture(scopefunction)defauth_token():returnBearer test-token1.9 参数化测试importpytestpytest.mark.parametrize(username,password,expected,[(admin,123456,True),(admin,wrong,False),(nonexistent,123456,False),(,123456,False),])deftest_login_parametrized(username,password,expected):resultauthenticate(username,password)assertresultexpected1.10 测试标记importpytestpytest.mark.smokedeftest_login():passpytest.mark.regressiondeftest_checkout():passpytest.mark.skip(reason功能尚未实现)deftest_feature_not_implemented():passpytest.mark.xfail(reason已知bug)deftest_known_bug():pass运行带标记的测试pytest-msmoke# 只运行冒烟测试pytest-mnot slow# 排除慢速测试1.11 生成测试报告# HTML报告pytest--htmlreports/test_report.html# Allure报告需安装allure-pytestpipinstallallure-pytest pytest--alluredirreports/allure_results allure serve reports/allure_results1.12 实战示例API接口测试# test_api.pyimportpytestimportrequestspytest.fixturedefapi_client():returnrequests.Session()pytest.fixturedefbase_url():returnhttps://jsonplaceholder.typicode.comclassTestUserAPI:deftest_get_users(self,api_client,base_url):responseapi_client.get(f{base_url}/users)assertresponse.status_code200assertisinstance(response.json(),list)deftest_get_user_by_id(self,api_client,base_url):responseapi_client.get(f{base_url}/users/1)assertresponse.status_code200userresponse.json()assertuser[id]1assertnameinuserdeftest_create_user(self,api_client,base_url):payload{name:Test User,email:testexample.com}responseapi_client.post(f{base_url}/users,jsonpayload)assertresponse.status_code201created_userresponse.json()assertcreated_user[name]payload[name]