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

Python阿木 发布于 17 小时前 1 次阅读


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

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

环境准备

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

1. Python 3.6 或更高版本
2. Pytest 框架
3. 电商下单功能的相关代码

假设电商下单功能的代码如下:

python
class OrderService:
def __init__(self, product_service, payment_service):
self.product_service = product_service
self.payment_service = payment_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")
order = {
'user_id': user_id,
'product_id': product_id,
'quantity': quantity,
'total_price': product.price quantity
}
self.payment_service.process_payment(user_id, order['total_price'])
return order

class ProductService:
def __init__(self, products):
self.products = products

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

class PaymentService:
def __init__(self):
pass

def process_payment(self, user_id, amount):
print(f"Processing payment for user {user_id} with amount {amount}")
这里可以添加支付逻辑,例如调用支付接口等

正常流程测试

正常流程测试主要验证下单功能在正常情况下是否能够正确执行。以下是一些测试用例:

1. 测试下单成功

python
import pytest
from unittest.mock import Mock

def test_create_order_success():
products = {
1: {'name': 'Product A', 'price': 100, 'stock': 10}
}
product_service = ProductService(products)
payment_service = Mock()
order_service = OrderService(product_service, payment_service)

order = order_service.create_order(1, 1, 1)
assert order == {
'user_id': 1,
'product_id': 1,
'quantity': 1,
'total_price': 100
}
payment_service.process_payment.assert_called_once_with(1, 100)

2. 测试库存不足

python
def test_create_order_insufficient_stock():
products = {
1: {'name': 'Product A', 'price': 100, 'stock': 0}
}
product_service = ProductService(products)
payment_service = Mock()
order_service = OrderService(product_service, payment_service)

with pytest.raises(ValueError) as exc_info:
order_service.create_order(1, 1, 1)
assert str(exc_info.value) == "Insufficient stock"

3. 测试产品不存在

python
def test_create_order_product_not_found():
products = {}
product_service = ProductService(products)
payment_service = Mock()
order_service = OrderService(product_service, payment_service)

with pytest.raises(ValueError) as exc_info:
order_service.create_order(1, 1, 1)
assert str(exc_info.value) == "Product not found"

异常场景测试

异常场景测试主要验证下单功能在遇到异常情况时的表现。以下是一些测试用例:

1. 测试支付失败

python
def test_create_order_payment_failure():
products = {
1: {'name': 'Product A', 'price': 100, 'stock': 10}
}
product_service = ProductService(products)
payment_service = Mock()
payment_service.process_payment.side_effect = Exception("Payment failed")
order_service = OrderService(product_service, payment_service)

with pytest.raises(Exception) as exc_info:
order_service.create_order(1, 1, 1)
assert str(exc_info.value) == "Payment failed"

2. 测试用户不存在

python
def test_create_order_user_not_found():
products = {
1: {'name': 'Product A', 'price': 100, 'stock': 10}
}
product_service = ProductService(products)
payment_service = Mock()
order_service = OrderService(product_service, payment_service)

with pytest.raises(ValueError) as exc_info:
order_service.create_order(999, 1, 1)
assert str(exc_info.value) == "User not found"

总结

本文使用 Python 和 Pytest 框架,围绕电商下单功能,编写了一系列单元测试,包括正常流程测试和异常场景测试。通过这些测试,我们可以确保下单功能在各种情况下都能正常工作,从而提高系统的稳定性和可靠性。在实际开发过程中,我们还可以根据需要添加更多的测试用例,以覆盖更多的场景。