当前位置: 首页 > news >正文

Python面试题:结合Python技术,如何使用Pytest进行单元测试和集成测试

使用Pytest进行单元测试和集成测试是非常常见和有效的方法。下面是如何使用Pytest进行这些测试的详细指南。

安装Pytest

首先,使用pip安装Pytest:

pip install pytest

单元测试

单元测试用于测试单个模块或函数的功能。假设我们有一个简单的Python模块 math_functions.py,其中包含几个基本的数学函数:

# math_functions.py
def add(a, b):return a + bdef subtract(a, b):return a - bdef multiply(a, b):return a * bdef divide(a, b):if b == 0:raise ValueError("Cannot divide by zero!")return a / b

为这些函数编写单元测试:

# test_math_functions.py
import pytest
from math_functions import add, subtract, multiply, dividedef test_add():assert add(1, 2) == 3assert add(-1, 1) == 0assert add(-1, -1) == -2def test_subtract():assert subtract(2, 1) == 1assert subtract(-1, 1) == -2assert subtract(-1, -1) == 0def test_multiply():assert multiply(2, 3) == 6assert multiply(-1, 1) == -1assert multiply(-1, -1) == 1def test_divide():assert divide(6, 3) == 2assert divide(-1, 1) == -1assert divide(-1, -1) == 1with pytest.raises(ValueError):divide(1, 0)

运行单元测试

在命令行中,导航到包含测试文件的目录,然后运行:

pytest

Pytest会自动发现所有以 test_ 开头的文件和函数,并运行它们。

集成测试

集成测试用于测试多个模块之间的交互。假设我们有一个简单的应用程序 app.py,它使用 math_functions.py 中的函数:

# app.py
from math_functions import add, subtract, multiply, dividedef calculate(a, b, operation):if operation == 'add':return add(a, b)elif operation == 'subtract':return subtract(a, b)elif operation == 'multiply':return multiply(a, b)elif operation == 'divide':return divide(a, b)else:raise ValueError("Invalid operation!")

为这个应用程序编写集成测试:

# test_app.py
import pytest
from app import calculatedef test_calculate_add():assert calculate(1, 2, 'add') == 3def test_calculate_subtract():assert calculate(2, 1, 'subtract') == 1def test_calculate_multiply():assert calculate(2, 3, 'multiply') == 6def test_calculate_divide():assert calculate(6, 3, 'divide') == 2with pytest.raises(ValueError):calculate(1, 0, 'divide')def test_calculate_invalid_operation():with pytest.raises(ValueError):calculate(1, 2, 'invalid')

运行集成测试

同样,在命令行中,导航到包含测试文件的目录,然后运行:

pytest

Pytest会发现并运行所有测试文件中的测试。

使用Fixtures进行测试初始化和清理

Fixtures用于在测试前进行初始化操作,并在测试后进行清理。以下是一个简单的示例:

# test_math_functions_with_fixtures.py
import pytest
from math_functions import add, subtract, multiply, divide@pytest.fixture
def setup_teardown():print("Setup before test")yieldprint("Teardown after test")def test_add(setup_teardown):assert add(1, 2) == 3def test_subtract(setup_teardown):assert subtract(2, 1) == 1

高级功能

Pytest还支持许多高级功能,例如参数化测试、标记测试和并行测试。以下是一些示例:

参数化测试
@pytest.mark.parametrize("a, b, expected", [(1, 2, 3),(-1, 1, 0),(-1, -1, -2),
])
def test_add(a, b, expected):assert add(a, b) == expected
标记测试
@pytest.mark.slow
def test_slow_function():time.sleep(5)assert True

运行标记测试:

pytest -m slow
并行测试

安装 pytest-xdist

pip install pytest-xdist

使用并行测试:

pytest -n 4

通过这些示例,你可以使用Pytest进行高效的单元测试和集成测试。Pytest的灵活性和强大的功能使其成为Python测试领域的一个重要工具。

http://www.lryc.cn/news/412783.html

相关文章:

  • Java面试必看!知己知彼才能百战百胜,如何做好面试前的准备?
  • [Vue warn]: data functions should return an object:
  • .net 7和core版 SignalR
  • 【人工智能】Transformers之Pipeline(三):文本转音频(text-to-audio/text-to-speech)
  • 前端入门知识分享:HTML 页面中 head 标签之间的代码详解
  • 【Spring Boot】手撕搜索引擎项目,深度复盘在开发中的重难点和总结(长达两万6千字的干货,系好安全带,要发车了......)
  • 测试面试宝典(四十二)—— 接口测试什么时候介入
  • 【Elasticsearch】Elasticsearch的分片和副本机制
  • 鸿蒙开发入门指南
  • 从分散到整合,细说比特币发展史
  • TreeSelect增加可筛选功能
  • 星环科技与宁夏银行“大数据联合实验室”揭牌,持续打造金融科技新范式
  • React native页面突然白屏
  • 一段直接路径读取文件LINUX C代码
  • Android让所有APK横屏显示
  • 【智能制造-26】PLC标准-SICAR
  • 浅学爬虫-处理复杂网页
  • nginx反向代理严重错误[crit] (13: Permission denied) while reading upstream问题
  • 精通Python爬虫中的XPath:从安装到实战演示
  • redis的使用场景
  • 记录new Date()的各种方法以及时间差的计算方法
  • vue项目创建+eslint+Prettier+git提交规范(commitizen+hooks+husk)
  • 从Docker拉取镜像一直失败超时?这些解决方案帮你解决烦恼
  • R语言大尺度空间数据分析模拟预测及可视化:地统计与空间自相关、空间数据插值、机器学习空间预测、空间升降尺度、空间模拟残差订正、空间制图等
  • 深入理解Java内存管理机制
  • Helm 学习之路,一文弄懂
  • 【面试题解答】一个有序数组 nums ,原地删除重复出现的元素
  • 【数据结构算法经典题目刨析(c语言)】随机链表的复制(图文详解)
  • cqyjldfx
  • 大数据——HBase原理