You need to enable JavaScript to run this app. 如何为搭载YOLO模型的Flask API编写单元测试?附代码示例
优惠活动
大模型
产品
解决方案
定价
更多

如何为搭载YOLO模型的Flask API编写单元测试?附代码示例

Flask API 单元测试解决方案

1 先解决app导入报错问题

首先调整项目结构,保证你的Flask主文件(假设命名为app.py)和测试文件同级:

项目根目录/
├── app.py  # 你的原Flask业务代码文件
├── test_app.py  # 新建的单元测试文件
├── machine_learning_model/  # 原YOLO模型目录
└── predict_images/  # 原预测结果图片存储目录

如果调整结构后还是报模块导入错误,在test_app.py最开头加入以下代码,把当前目录加入Python模块搜索路径:

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

2 测试框架与思路

我们用pytest配合Flask自带的测试客户端实现单元测试,测试覆盖两类逻辑:

  • 工具函数测试:例如你自定义的parse_json_from_request函数
  • 接口测试:覆盖POST预测接口、GET图片查询接口
    优化提示:YOLO模型加载耗时久,单元测试阶段可以mock掉YOLO相关方法,避免依赖外部模型文件、提升测试速度;如果需要验证模型效果可以去掉mock逻辑直接测试。

3 完整测试代码示例

以下是test_app.py的完整代码:

import pytest
import base64
import json
from unittest.mock import patch, MagicMock
from flask import request
# 导入你的Flask app
from app import app, parse_json_from_request

# 测试用fixture:创建Flask测试客户端
@pytest.fixture
def client():
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

# 测试工具函数parse_json_from_request
def test_parse_json_from_request():
    with app.test_request_context(json={"image": "test_base64", "other_param": 123}):
        result = parse_json_from_request(request)
        assert result == {"image": "test_base64", "other_param": 123}
        assert isinstance(result, dict)

# 测试GET图片接口
def test_get_image(client):
    # 提前在predict_images目录放一张命名为output_resize_test.jpg的测试图
    resp = client.get('/v1/resoures/predict_images/test')
    assert resp.status_code == 200
    assert resp.content_type == 'image/gif'

# 测试predict预测接口(mock掉YOLO方法,不用真实跑模型)
@patch('app.yoloModel')
def test_predict_interface(mock_yolo, client):
    # 模拟YOLO方法的返回值
    mock_yolo.detectObjectFromImage.return_value = (
        [0, 1],  # idxs
        [[10,10,50,50], [60,60,100,100]],  # boxes
        [0.95, 0.88],  # confidences
        [[30,30], [80,80]],  # centers
        [0, 16]  # classIDs 对应coco的person、dog分类
    )
    mock_yolo.bouding_box.return_value = [
        {"class": "person", "confidence": 0.95, "box": [10,10,50,50]},
        {"class": "dog", "confidence": 0.88, "box": [60,60,100,100]}
    ]

    # 构造测试用的base64图片
    test_img = base64.b64encode(b'test_image_content').decode('utf-8')
    # 发POST请求
    resp = client.post(
        '/v1/api/predict',
        json={"image": test_img},
        content_type='application/json'
    )
    # 校验返回结果
    assert resp.status_code == 200
    assert resp.content_type == 'application/json'
    resp_data = json.loads(resp.data)
    assert 'objectProperty' in resp_data
    assert len(resp_data['objectProperty']) == 2
    assert resp_data['objectProperty'][0]['class'] == 'person'

4 测试运行方法

  1. 先安装依赖:pip install pytest
  2. 进入项目根目录,执行命令:pytest test_app.py -v
  3. 所有测试用例通过后会显示pass,失败会输出具体错误原因。

可选:真实模型测试

如果要验证YOLO模型的真实效果,把test_predict_interface函数上的@patch装饰器去掉,传入真实图片的base64编码即可,注意要保证coco.names和模型权重文件路径正确。

内容的提问来源于stack exchange,提问作者tamerjar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 05:15:04