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"
}
相关推荐
花酒锄作田2 小时前
FastAPI 使用 session 认证
python·fastapi
lsswear2 小时前
Python 并发 线程
开发语言·python
郑州光合科技余经理2 小时前
国际版外卖系统:税率字段怎么和订单主流程解耦
android·java·开发语言·前端·后端·php·ai编程
软件课代表CiCi3 小时前
运行库是什么?电脑缺运行库怎么办?c++运行库缺失修复全攻略
开发语言·c++·windows·电脑·dll修复·dll丢失·运行库
Ivanqhz3 小时前
MLIR OpBuilder
开发语言·python·mlir
红宝村村长4 小时前
windows笔记本双系统ubuntu设置
开发语言
威联通安全存储4 小时前
TS-h2287XU-RP 在家电制造总装与质检数据场景的部署
python·制造
泡泡鱼(敲代码中)5 小时前
Python 字符串 str 完整学习笔记
python·学习
troy1285 小时前
Python 基础语法(八):Web 后端开发、数据分析与可视化、网络爬虫、人工智能 / 大模型应用
前端·python·数据分析
菜鸟~noob2335 小时前
【电子战】第15篇:混合定位——TDOA/FDOA/AOA 联合【含matlab代码】
开发语言·matlab