pytest

跳过安装好python及环境

安装:

pip install pytest

安装检查:

pytest --version

出现版本号就成功了。

pytest 命名规则(必须记住)

pytest 自动识别哪些是测试用例,规则非常简单:

  1. 文件名必须以 test_ 开头 或 _test.py 结尾
  2. 函数名必须以 test_ 开头
  3. 类名以 Test 开头
  4. 类里面方法以 test_ 开头

不符合 → 不执行。

多线程启动插件安装:

pip install pytest-xdist

运行

pytest -n auto

生成报告安装插件:

pip install pytest-html

运行:

pytest --html=report.html

打开 report.html 即可看到可视化报告。

还有以下常用插件:

复制代码
pip install pytest-rerunfailures  # 失败重跑 pytest --reruns 2  # 失败自动重试2次
pip install pytest-cov         # 覆盖率报告 pytest --cov=./ --cov-report=html

启动常用命令:

复制代码
pytest                  # 运行所有用例
pytest -v               # 详细输出
pytest -s               # 显示 print 内容
pytest test_demo.py     # 只运行这个文件
pytest -k "add"         # 只运行名字含 add 的用例
pytest --tb=short       # 简化报错信息
pytest --lf             # 只跑上次失败的用例
pytest --ff             # 先跑失败的,再跑成功的

# 只运行某个文件
pytest test_login.py -v


# 运行失败时暂停
pytest -x

# 生成测试报告
pytest --html=report.html

常用判断:

复制代码
# 1. 判断相等
assert 1 + 1 == 2

# 2. 判断不相等
assert 5 != 3

# 3. 判断True/False
assert True

# 4. 判断包含
assert "hello" in "hello pytest"

# 5. 判断大于/小于
assert 6 > 3

进阶:setup/teardown ------ 用例前后自动执行

复制代码
# 所有用例执行前 执行一次
def setup_module():
    print("=== 所有用例开始 ===")

# 所有用例执行后 执行一次
def teardown_module():
    print("=== 所有用例结束 ===")

# 每个用例执行前
def setup_function():
    print("前置操作:准备数据")

# 每个用例执行后
def teardown_function():
    print("后置操作:清理数据")

# 测试用例
def test_case1():
    assert 1 == 1

def test_case2():
    assert 2 == 2

其他疑难杂症

复制代码
在你项目根目录下,新建一个文件:
文件名必须叫:
.vscode/settings.json
(没有 .vscode 文件夹就自己新建一个)
{
    "python.terminal.activateEnvironment": true,
    "python.terminal.activateEnvInCurrentTerminal": true,
    "terminal.integrated.defaultProfile.windows": "Command Prompt"
}
相关推荐
geovindu1 小时前
CSharp: Bridge Pattern
开发语言·后端·桥接模式·结构型模式
এ慕ོ冬℘゜1 小时前
深入 JavaScript BOM:掌握 window 对象的窗口控制魔法
开发语言·javascript·ecmascript
2501_941982051 小时前
企业微信二次开发:如何用 Python 搭建通用的 Webhook 实时消息接收
开发语言·python·企业微信
在世修行1 小时前
第24篇:PyInstaller打包实战 — 从Python脚本到Windows EXE
人工智能·python·pyinstaller
逝水无殇2 小时前
C# 特性详解
开发语言·后端·c#
华研前沿标杆游学2 小时前
2026年制造企业标杆参访实操指南:3步选对适配参访路线
python
Wang ruoxi2 小时前
Pygame 小游戏——一笔画挑战
python·pygame
灵晔君2 小时前
【C++】二叉搜索树
开发语言·c++
萧青山2 小时前
AI阅读增强套件:用苏格拉底诘问+对抗性阅读+知识图谱构建深度阅读技能套件(Python实现)
人工智能·python·知识图谱·ai阅读增强
LongtengGensSupreme2 小时前
C#图像内存高速拷贝:使用Marshal.AllocHGlobal与ArrayPool实现内存拷贝的几个方法
开发语言·数码相机·c#