基于Python+Pytest的支付风控系统自动化测试实战
一、测试框架搭建
1. 项目结构设计
payment_risk_test/
├── conftest.py # pytest全局配置
├── requirements.txt # 依赖库
├── tests/
│ ├── unit/ # 单元测试
│ ├── integration/ # 集成测试
│ ├── performance/ # 性能测试
│ └── data/ # 测试数据
├── utils/
│ ├── risk_engine.py # 风控引擎封装
│ └── data_generator.py # 测试数据生成
└── reports/ # 测试报告
2. 基础依赖安装
pytest==7.4.0
requests==2.31.0
pydantic==2.0.3
allure-pytest==2.13.2
faker==18.11.2
pytest-benchmark==4.0.0
二、风控规则单元测试
1. 基础规则测试类
import pytest
from utils.risk_engine import RiskEngine
@pytest.fixture
def risk_engine():
"""初始化风控引擎"""
return RiskEngine.load_rules("config/rules.json")
class TestAmountRule:
def test_normal_amount(self, risk_engine):
transaction = {
"amount": 1000, "user_id": "U1001"}
result = risk_engine.evaluate(transaction)
assert not result["blocked"]
assert result["risk_level"] == "low"
@pytest.mark.parametrize("amount,expected", [
(50001, True),
(100000, True),
(50000, False)
])
def test_amount_threshold(self, risk_engine, amount, expected):
transaction = {
"amount": amount, "user_id": "U1001"}
assert risk_engine.evaluate(transaction)["blocked"] == expected
2. 异步规则测试
@pytest.mark.asyncio
async def test_third_party_verification():
transaction = {
"user_id": "U1001", "ip": "1.1.1.1"}
result = await RiskEngine.async_evaluate(transaction)
assert result["need_verification"] is True
三、集成测试实现
1. 测试数据生成
from faker import Faker
import random
class TransactionFactory:
def __init__(self):
self.fake = Faker()
def create(self, **overrides):
"""生成测试交易数据"""
data = {
"tx_id": self.fake.uuid4(),
"user_id":