【Pytest】笔记

1. 安装

1.1 安装 pytest

bash 复制代码
pip install pytest

1.2 安装第三方报告插件 pytest-html

这个是非必要的,也可以安装其他第三方插件。

bash 复制代码
pip install pytest-html


2. 编写测试用例

  • 测试用例文件名必须满足的格式:test_*.py, 或者 *_test.py
  • 在这些测试文件中,类名必须以 Test 开头;函数名必须以 test 开头。


3. 运行测试用例

3.1 执行全部用例

  • 方式一:
    • 在命令行窗口,进入自动化项目的根目录,执行命令 pytest 即可。
  • 方式二:
    • 在 pycharm (或其他IDE)中的 terminal 中,执行命令 pytest

需要特别注意的是:

直接执行 pytest 命令不会将当前目录设置为模块搜索路径

所以更推荐执行命令 python -m pytest

bash 复制代码
python -m pytest

以上命令都是执行当前目录下的所有的测试用例。


3.2 挑选用例执行

指定一个模块(一个python文件)

比如,只执行 test_incorrect_login.py 文件:

bash 复制代码
python -m pytest cases\login\test_incorrect_login.py

指定一个目录

比如,执行 cases 目录下的所有测试用例

bash 复制代码
python -m pytest cases

指定多个目录

比如,执行 cases1 ,cases2\login 目录下的所有测试用例

bash 复制代码
python -m pytest cases1  cases2\login

指定模块中的一个类

比如,执行 cases\login\test_incorrect_login.py 模块中的 Test_incorrectLogin 类

bash 复制代码
python -m pytest cases\login\test_incorrect_login.py::Test_incorrectLogin 

指定模块中的一个类中的方法

比如,执行 cases\login\test_incorrect_login.py 模块中的 Test_incorrectLogin 类 中的 test_c001001 方法

bash 复制代码
python -m pytest cases\login\test_incorrect_login.py::Test_incorrectLogin::test_c001001

指定 目录、模块、类、方法 的名字

可以使用命令行参数 -k 后面加名字的一部分来挑选要执行的测试项

比如,只执行名字中包含 c001001 的用例

bash 复制代码
python -m pytest -k c001001 -sv

注意,-k 后的参数

  • 可以是测试函数的名字,可以是类的名字,可以是模块文件名,也可以是目录名字
  • 对大小写敏感
  • 不一定要完整,可以是名字其中的一部分
  • 可以用 not 表示选择名字中不包含,比如
bash 复制代码
python -m pytest -k 'not c001001' -sv
  • 可以用 and 表示选择名字同时包含多个关键字,比如
bash 复制代码
python -m pytest -k "incorrect and 密码2" -s
  • 可以用 or 表示选择名字 包含指定关键字之一即可,比如
bash 复制代码
python -m pytest -k "incorrect or 密码2" -s

3.3 执行用例时的参数解释

比如,执行用例

bash 复制代码
python -m pytest -k 'not c001001' -sv

-m

pytest 作为模块运行,确保使用当前 python 环境中的 pytest

-k

过滤测试。比如,参数后面跟需要执行的包含某个名字的用例。

-s

显示输出 。允许测试中的所有print 语句输出在控制台。

-v

详细模式。输出更详细的测试结果信息,比如每个测试用例的名称和状态。

-sv

顾名思义,-s-v 的组合模式。

-x

遇到第一个失败用例时立即停止测试

--if(两个 - )

仅重新运行上一次失败的测试测试

-m <标记名>

只运行用 @pytest.mark.<标记名> 装饰过的测试

相关推荐
阁老1 天前
pytest测试框架:如何确保登录模块先执行并共享登录状态
测试
_志哥_2 天前
Superpowers 技术指南:让 AI 编程助手拥有超能力
人工智能·ai编程·测试
西岸行者5 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky5 天前
Django入门笔记
笔记·django
勇气要爆发5 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意5 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发5 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain
FliPPeDround5 天前
浏览器扩展 E2E 测试的救星:vitest-environment-web-ext 让你告别繁琐配置
e2e·浏览器·测试
姚青&5 天前
PyCharm 配置与界面化运行
pytest
qianshanxue115 天前
计算机操作的一些笔记标题
笔记