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

如何使用pytest测试drf-yasg中swagger_auto_schema的方法、请求体与响应配置?

如何使用pytest测试drf-yasg中swagger_auto_schema的方法、请求体与响应配置?

嘿,我来帮你搞定用pytest测试drf-yasg的swagger_auto_schema配置这件事!其实核心思路就是直接获取被装饰过的action函数上的swagger配置元数据,然后用pytest断言这些配置是否符合你的预期。

下面我结合你的CartViewSet场景,给你具体的测试示例和步骤:

1. 核心原理:获取swagger_auto_schema的配置

drf-yasg的@swagger_auto_schema装饰器会把你定义的配置(method、request_body、responses这些)存储在被装饰函数的__swagger_operation__属性里,所以我们只需要拿到对应的action函数,就能直接读取这些配置做断言。

2. 具体pytest测试用例示例

假设你的CartViewSet里有add、remove、clear三个带swagger配置的action,我们逐个来写测试:

测试add action的配置

import pytest
from your_app.views import CartViewSet
from your_app.serializers import AddToCartSerializer, CartSerializer

def test_cart_add_swagger_config():
    # 获取add action的处理函数
    add_action = CartViewSet.add
    # 提取swagger配置
    swagger_op = add_action.__swagger_operation__

    # 断言HTTP方法是否为POST
    assert swagger_op.method == "post"

    # 断言请求体对应的序列化器是否正确
    assert swagger_op.request_body.type == AddToCartSerializer

    # 断言200状态码的响应序列化器
    assert 200 in swagger_op.responses
    assert swagger_op.responses[200].schema.type == CartSerializer
    # 也可以断言响应的描述(如果配置了的话)
    # assert swagger_op.responses[200].description == "商品成功添加到购物车"

测试remove action的配置

from your_app.serializers import RemoveFromCartSerializer

def test_cart_remove_swagger_config():
    remove_action = CartViewSet.remove
    swagger_op = remove_action.__swagger_operation__

    # 假设remove用的是DELETE方法
    assert swagger_op.method == "delete"

    # 断言请求体(如果有的话)
    assert swagger_op.request_body.type == RemoveFromCartSerializer

    # 断言删除成功的204响应
    assert 204 in swagger_op.responses
    assert swagger_op.responses[204].description == "商品成功从购物车移除"

测试clear action的配置

def test_cart_clear_swagger_config():
    clear_action = CartViewSet.clear
    swagger_op = clear_action.__swagger_operation__

    assert swagger_op.method == "post"  # 假设clear用POST方法
    # 清空购物车可能不需要请求体
    assert swagger_op.request_body is None

    # 断言200响应
    assert 200 in swagger_op.responses
    assert swagger_op.responses[200].schema.type == CartSerializer

3. 一些注意事项

  • 确保你导入的ViewSet和序列化器路径正确,和你的项目结构匹配
  • 如果你的action是用DRF的@action装饰器注册的(比如@action(detail=False, methods=["post"])),不需要额外实例化ViewSet,直接访问类的方法即可
  • 对于responses的断言,要注意每个状态码对应的是OpenApiResponse对象,你可以通过schema属性获取序列化器,description获取响应描述
  • 如果你的swagger配置里用了operation_id、summary等其他字段,也可以用同样的方式断言(比如assert swagger_op.summary == "添加商品到购物车")

备注:内容来源于stack exchange,提问作者Shervin Gharib

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 17:17:59