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测试领域的一个重要工具。

相关推荐
wt_cs10 分钟前
银行回单ocr api集成解析-图像文字识别-文字识别技术
开发语言·python
_WndProc32 分钟前
【Python】Flask网页
开发语言·python·flask
互联网搬砖老肖34 分钟前
Python 中如何使用 Conda 管理版本和创建 Django 项目
python·django·conda
测试者家园1 小时前
基于DeepSeek和crewAI构建测试用例脚本生成器
人工智能·python·测试用例·智能体·智能化测试·crewai
大模型真好玩1 小时前
准确率飙升!Graph RAG如何利用知识图谱提升RAG答案质量(四)——微软GraphRAG代码实战
人工智能·python·mcp
呆呆的心1 小时前
JavaScript 深入理解闭包与柯里化:从原理到实践 🚀
javascript·面试
请你吃div1 小时前
JavaScript 实用函数大全(超实用)
前端·javascript·面试
前端付豪1 小时前
11、打造自己的 CLI 工具:从命令行到桌面效率神器
后端·python
前端付豪1 小时前
12、用类写出更可控、更易扩展的爬虫框架🕷
后端·python
Baihai_IDP1 小时前
vec2text 技术已开源!一定条件下,文本嵌入向量可“近乎完美地”还原
人工智能·面试·llm