You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Falcon单元测试与实际API的请求流类型差异问题求助

Falcon API单元测试请求体读取兼容问题解决办法

问题描述

编写Falcon API单元测试时遇到请求体读取异常:API实际运行时通过request.stream.read()可正常读取请求体,但单元测试时因流类型为wsgiref.validate.InputWrapper,直接调用read()会触发异常,且不想修改原API代码适配两种场景。

单元测试代码

class TestDetectionApi(DetectionApiSetUp):
    def test_valid_detection(self):
        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        body = {'test': 'test'}
        detection_result = self.simulate_post('/environments/e6ce2a50-f68f-4a7a-8562-ca50822b805d/detectionEvaluations',
                                              body=urlencode(body), headers=headers)
        self.assertEqual(detection_result.json, None)

API请求体读取代码

def _get_request_body(request: falcon.Request) -> dict:
    request_stream = request.stream.read()
    request_body = json.loads(request_stream)
    validate(request_body, REQUEST_VALIDATION_SCHEMA)
    return request_body

解决办法

核心矛盾是测试代码的请求格式与API预期不匹配:API用json.loads解析请求体,说明预期接收JSON格式数据,但测试却发送了application/x-www-form-urlencoded类型的表单数据,流类型差异进一步放大了这个问题。只需修正测试代码即可解决:

  1. 将请求头改为JSON类型:{"Content-Type": "application/json"}
  2. 将请求体序列化为JSON字符串,而非URL编码

修正后的测试代码:

import json

class TestDetectionApi(DetectionApiSetUp):
    def test_valid_detection(self):
        headers = {"Content-Type": "application/json"}
        body = {'test': 'test'}
        detection_result = self.simulate_post('/environments/e6ce2a50-f68f-4a7a-8562-ca50822b805d/detectionEvaluations',
                                              body=json.dumps(body), headers=headers)
        self.assertEqual(detection_result.json, None)

调整后测试请求的格式与API实际运行时的接收格式完全一致,request.stream.read()能正确读取到JSON字符串,无需修改API代码即可适配单元测试场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:01:16