本文共 2580 字,大约阅读时间需要 8 分钟。
pytest 是一个成熟的 Python 测试框架,支持单元测试、功能测试、Selenium/Applium 自动化测试以及接口自动化测试(如 pytest + requests)。其丰富的插件生态和高度可扩展性,使其成为测试开发的首选工具。常用插件包括 pytest-selenium、pytest-html、pytest-rerunfailures 和 pytest-xdist 等。
安装 pytest:
pip install pytest
验证安装:
pytest --version
安装 pytest-html 报告模板:
pip install pytest-html
安装失败后重复执行模板:
pip install pytest-rerunfailures
test_*.py 或 *_test.py 格式。Test 开头,不需要 __init__ 方法。test_ 开头, pytest 会自动查找符合约束的测试用例。test_ 开头。示例脚本:
import pytestdef add(a, b): return a + b@pytest.fixturedef TestCase(): passclass TestCase: @pytest.fixture def test_add(self): assert add(1, 2) == 3if __name__ == '__main__': pytest.main()
运行命令:
pytest [参数]
-v:输出详细信息。-s:输出测试函数或方法的 print 内容。-k:按关键字过滤用例。-m:按分类执行测试。-x:执行失败用例时立即停止。--maxfail:指定最大失败次数。--tb=line:错误信息以单行展示。示例:
@pytest.mark.parametrize('a', [1, 2, 3, 4, 5])def test(a): print(a)if __name__ == '__main__': pytest.main() 模块级:
setup_module():模块执行前运行一次。teardown_module():模块执行后运行一次。函数级:
setup_function():每个用例执行前运行一次。teardown_function():每个用例执行后运行一次。类级:
setup_class():类执行前运行一次。teardown_class():类执行后运行一次。方法级:
setup_method():每个方法执行前运行一次。teardown_method():每个方法执行后运行一次。import pytestimport requests@pytest.fixturedef login(): print("登录中...") yield print("退出登录")@pytest.mark.parametrize('data', data_list)def test_login(data): url = 'http://example.com/login' response = requests.post(url, data=data) assert response.status_code == 200 print(response.text)if __name__ == '__main__': pytest.main() import xlrdimport pytestimport requests@pytest.fixturedef search_params(): return { 'platf': 'Windows', 'excludePayTemplate': True, 'is_excluded': False, 'excluded_member_discount': False, 'keyword': '测试', 'start': 1, 'count': 10 }@pytest.mark.parametrize('params', params_list)def test_search(params): url = 'https://template.wps.com/server/pf/template' response = requests.get(url, params=params) print(f"响应状态码:{response.status_code}") print(f"响应内容:{response.text}")if __name__ == '__main__': pytest.main() fixture 是 pytest 的灵活前置和后置解决方案。示例:
import pytest@pytest.fixturedef login(): print("登录中...") yield print("退出登录")def test_s1(login): print("测试用例 1:登录后的操作")def test_s2(): print("测试用例 2:不需要登录的操作")if __name__ == '__main__': pytest.main() 安装 pytest-html:
pip install pytest-html
生成报告:
pytest --html=report.html tests/
通过以上内容,希望你能快速上手 pytest 并开始你的测试开发之旅!如果对某些内容有疑问或需要更深入的探讨,请随时联系我。
转载地址:http://dnafk.baihongyu.com/