File: test_validation_error.py

package info (click to toggle)
flask-openapi3 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,976 kB
  • sloc: python: 4,754; sh: 17; makefile: 15; javascript: 5
file content (78 lines) | stat: -rw-r--r-- 2,207 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# -*- coding: utf-8 -*-
# @Author  : llc
# @Time    : 2023/7/21 10:32
import pytest
from flask import make_response, current_app
from pydantic import BaseModel, Field, ValidationError

from flask_openapi3 import OpenAPI


class GenericTracebackError(BaseModel):
    location: str = Field(..., json_schema_extra={"example": "GenericError.py"})
    line: int = Field(..., json_schema_extra={"example": 1})
    method: str = Field(..., json_schema_extra={"example": "GenericError"})
    message: str = Field(..., json_schema_extra={"example": "400:Bad Request"})


class ValidationErrorModel(BaseModel):
    code: str
    message: str
    more_info: list[GenericTracebackError] = Field(..., json_schema_extra={"example": [GenericTracebackError(
        location="GenericError.py",
        line=1,
        method="GenericError",
        message="400:Bad Request")]})


def validation_error_callback(e: ValidationError):
    validation_error_object = ValidationErrorModel(
        code="400",
        message=e.json(),
        more_info=[GenericTracebackError(
            location="GenericError.py",
            line=1,
            method="GenericError",
            message="400:Bad Request"
        )]
    )
    response = make_response(validation_error_object.model_dump_json())
    response.headers["Content-Type"] = "application/json"
    response.status_code = getattr(current_app, "validation_error_status", 422)
    return response


app = OpenAPI(
    __name__,
    validation_error_status=400,
    validation_error_model=ValidationErrorModel,
    validation_error_callback=validation_error_callback
)
app.config["TESTING"] = True


@pytest.fixture
def client():
    client = app.test_client()
    return client


class BookQuery(BaseModel):
    age: int = Field(None, description="Age")


@app.get("/query")
def api_query(query: BookQuery):
    print(query)  # pragma: no cover


def test_openapi(client):
    resp = client.get("/openapi/openapi.json")
    assert resp.status_code == 200
    assert resp.json["components"]["schemas"].get("GenericTracebackError") is not None


def test_api_query(client):
    resp = client.get("/query?age=abc")
    print(resp.json)
    assert resp.status_code == 400