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"
}
相关推荐
xiaotao1311 天前
01-编程基础与数学基石: Python核心数据结构完全指南
数据结构·人工智能·windows·python
青苔猿猿1 天前
【1】JupyterLab安装
python·jupyter
xiaoyaohou111 天前
023、数据增强改进(二):自适应数据增强与AutoAugment策略
开发语言·python
鬼圣1 天前
Python 上下文管理器
开发语言·python
星空椰1 天前
JavaScript 基础进阶:分支、循环与数组实战总结
开发语言·javascript·ecmascript
yong99901 天前
IHAOAVOA:天鹰优化算法与非洲秃鹫优化算法的混合算法(Matlab实现)
开发语言·算法·matlab
努力学习_小白1 天前
ResNet-50——pytorch版
人工智能·pytorch·python
t***5441 天前
有哪些常见的架构设计模式在现代C++中应用
开发语言·c++
战族狼魂1 天前
基于LibreOffice +python 实现一个小型销售管理系统的数据库原型教学实验
数据库·python
m0_640309301 天前
PHP函数怎样适配高可靠性存储硬件_PHP在ZFS RAIDZ环境配置【技巧】
jvm·数据库·python