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

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

安装Pytest

首先,使用pip安装Pytest:

bash 复制代码
pip install pytest

单元测试

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

python 复制代码
# math_functions.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero!")
    return a / b

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

python 复制代码
# test_math_functions.py
import pytest
from math_functions import add, subtract, multiply, divide

def test_add():
    assert add(1, 2) == 3
    assert add(-1, 1) == 0
    assert add(-1, -1) == -2

def test_subtract():
    assert subtract(2, 1) == 1
    assert subtract(-1, 1) == -2
    assert subtract(-1, -1) == 0

def test_multiply():
    assert multiply(2, 3) == 6
    assert multiply(-1, 1) == -1
    assert multiply(-1, -1) == 1

def test_divide():
    assert divide(6, 3) == 2
    assert divide(-1, 1) == -1
    assert divide(-1, -1) == 1
    with pytest.raises(ValueError):
        divide(1, 0)

运行单元测试

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

bash 复制代码
pytest

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

集成测试

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

python 复制代码
# app.py
from math_functions import add, subtract, multiply, divide

def 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!")

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

python 复制代码
# test_app.py
import pytest
from app import calculate

def test_calculate_add():
    assert calculate(1, 2, 'add') == 3

def test_calculate_subtract():
    assert calculate(2, 1, 'subtract') == 1

def test_calculate_multiply():
    assert calculate(2, 3, 'multiply') == 6

def test_calculate_divide():
    assert calculate(6, 3, 'divide') == 2
    with pytest.raises(ValueError):
        calculate(1, 0, 'divide')

def test_calculate_invalid_operation():
    with pytest.raises(ValueError):
        calculate(1, 2, 'invalid')

运行集成测试

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

bash 复制代码
pytest

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

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

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

python 复制代码
# 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")
    yield
    print("Teardown after test")

def test_add(setup_teardown):
    assert add(1, 2) == 3

def test_subtract(setup_teardown):
    assert subtract(2, 1) == 1

高级功能

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

参数化测试
python 复制代码
@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
标记测试
python 复制代码
@pytest.mark.slow
def test_slow_function():
    time.sleep(5)
    assert True

运行标记测试:

bash 复制代码
pytest -m slow
并行测试

安装 pytest-xdist

bash 复制代码
pip install pytest-xdist

使用并行测试:

bash 复制代码
pytest -n 4

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

相关推荐
MoRanzhi120320 分钟前
亲和传播聚类算法应用(Affinity Propagation)
人工智能·python·机器学习·数学建模·scikit-learn·聚类
金融OG21 分钟前
99.23 金融难点通俗解释:小卖部经营比喻PPI(生产者物价指数)vsCPI(消费者物价指数)
人工智能·python·机器学习·数学建模·金融·数据可视化
是Dream呀1 小时前
Python从0到100(八十六):神经网络-ShuffleNet通道混合轻量级网络的深入介绍
网络·python·神经网络
zxfeng~1 小时前
深度学习之“线性代数”
人工智能·python·深度学习·线性代数
qq_459340392 小时前
大厂面试题备份20250201
面试
叫我DPT2 小时前
Python 中 `finally` 的执行时机与 `return` 的微妙关系
python
CodeClimb3 小时前
【华为OD-E卷 - 最大矩阵和 100分(python、java、c++、js、c)】
java·c++·python·华为od·矩阵
aiweker5 小时前
Selenium 使用指南:从入门到精通
python·selenium·测试工具
SteveKenny6 小时前
Python 梯度下降法(六):Nadam Optimize
开发语言·python
dreadp8 小时前
解锁豆瓣高清海报(二) 使用 OpenCV 拼接和压缩
图像处理·python·opencv·计算机视觉·数据分析