-
Notifications
You must be signed in to change notification settings - Fork 10
/
test_validated_schema.py
97 lines (84 loc) · 2.81 KB
/
test_validated_schema.py
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# mypy: ignore-errors
import sys
from typing import Any, Optional
from openapi_spec_validator import validate
from pydantic import BaseModel
from openapi_pydantic.compat import PYDANTIC_V2
from openapi_pydantic.v3.v3_0 import (
Components,
DataType,
Example,
Header,
Info,
MediaType,
OpenAPI,
Operation,
PathItem,
RequestBody,
Response,
Schema,
)
from openapi_pydantic.v3.v3_0.util import (
PydanticSchema,
construct_open_api_with_schema_class,
)
if sys.version_info < (3, 9):
from typing_extensions import Literal
else:
from typing import Literal
def test_basic_schema() -> None:
class SampleModel(BaseModel):
required: bool
optional: Optional[bool] = None
one_literal_choice: Literal["only_choice"]
multiple_literal_choices: Literal["choice1", "choice2"]
part_api = construct_sample_api(SampleModel)
api = construct_open_api_with_schema_class(part_api)
assert api.components is not None
assert api.components.schemas is not None
if PYDANTIC_V2:
json_api: Any = api.model_dump(mode="json", by_alias=True, exclude_none=True)
else:
json_api: Any = api.dict(by_alias=True, exclude_none=True)
validate(json_api)
def construct_sample_api(SampleModel) -> OpenAPI:
class SampleRequest(SampleModel):
model_config = {"json_schema_mode": "validation"}
class SampleResponse(SampleModel):
model_config = {"json_schema_mode": "serialization"}
return OpenAPI(
info=Info(
title="Sample API",
version="v0.0.1",
),
paths={
"/callme": PathItem(
post=Operation(
requestBody=RequestBody(
content={
"application/json": MediaType(
schema=PydanticSchema(schema_class=SampleRequest)
)
}
),
responses={
"200": Response(
description="resp",
headers={
"WWW-Authenticate": Header(
description="Indicate how to authenticate",
schema=Schema(type=DataType.STRING),
)
},
content={
"application/json": MediaType(
schema=PydanticSchema(schema_class=SampleResponse)
)
},
)
},
)
)
},
components=Components(examples={"thing-example": Example(value="thing1")}),
)