Python 语言 用 Pytest 编写电商下单功能单元测试 正常流程 + 异常场景 + 边界值测试

Python阿木 发布于 23 小时前 3 次阅读


Python Pytest 单元测试:电商下单功能测试

在电商系统中,下单功能是用户与系统交互的核心环节之一。为了保证下单流程的稳定性和可靠性,我们需要对下单功能进行全面的单元测试。本文将使用 Python 和 Pytest 框架,围绕电商下单功能,编写一系列单元测试,包括正常流程测试、异常场景测试和边界值测试。

环境准备

在开始编写测试代码之前,我们需要准备以下环境:

1. Python 3.6 或更高版本
2. Pytest 框架
3. 电商下单功能模块(假设名为 `order_service.py`)

确保你已经安装了 Pytest,如果没有,可以通过以下命令安装:

bash
pip install pytest

下单功能模块

我们需要一个简单的下单功能模块,以下是一个简单的下单功能实现:

python
order_service.py

class OrderService:
def __init__(self, product_service):
self.product_service = product_service

def create_order(self, user_id, product_id, quantity):
product = self.product_service.get_product(product_id)
if not product:
raise ValueError("Product not found")
if product['stock'] < quantity:
raise ValueError("Insufficient stock")
product['stock'] -= quantity
return {
'order_id': 1,
'user_id': user_id,
'product_id': product_id,
'quantity': quantity,
'total_price': product['price'] quantity
}

这里我们假设有一个 `product_service.py` 模块,它负责获取产品信息:

python
product_service.py

class ProductService:
def __init__(self):
self.products = {
1: {'name': 'Laptop', 'price': 1000, 'stock': 10},
2: {'name': 'Smartphone', 'price': 500, 'stock': 20}
}

def get_product(self, product_id):
return self.products.get(product_id)

Pytest 测试用例

接下来,我们将编写 Pytest 测试用例来测试下单功能。

1. 正常流程测试

python
test_order_service.py

import pytest
from order_service import OrderService
from product_service import ProductService

@pytest.fixture
def order_service():
product_service = ProductService()
return OrderService(product_service)

def test_create_order_success(order_service):
order = order_service.create_order(1, 1, 1)
assert order['order_id'] == 1
assert order['user_id'] == 1
assert order['product_id'] == 1
assert order['quantity'] == 1
assert order['total_price'] == 1000
assert order_service.product_service.products[1]['stock'] == 9

2. 异常场景测试

python
def test_create_order_product_not_found(order_service):
with pytest.raises(ValueError):
order_service.create_order(1, 3, 1)

def test_create_order_insufficient_stock(order_service):
with pytest.raises(ValueError):
order_service.create_order(1, 1, 11)

3. 边界值测试

python
def test_create_order_zero_quantity(order_service):
with pytest.raises(ValueError):
order_service.create_order(1, 1, 0)

def test_create_order_negative_quantity(order_service):
with pytest.raises(ValueError):
order_service.create_order(1, 1, -1)

4. 测试报告

运行以下命令来执行测试并生成报告:

bash
pytest test_order_service.py

这将生成一个测试报告,显示所有测试用例的执行结果。

总结

本文使用 Python 和 Pytest 框架,围绕电商下单功能,编写了一系列单元测试。这些测试涵盖了正常流程、异常场景和边界值测试,以确保下单功能的稳定性和可靠性。在实际开发过程中,我们应该根据具体业务需求,不断完善和扩展测试用例,以覆盖更多的场景。