File: test_example.py

package info (click to toggle)
openapi-pydantic 0.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 744 kB
  • sloc: python: 4,392; makefile: 4
file content (67 lines) | stat: -rw-r--r-- 1,939 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
import logging
from typing import Callable

from openapi_pydantic import Info, OpenAPI, Operation, PathItem, Response
from openapi_pydantic.compat import PYDANTIC_V2


def test_readme_example() -> None:
    open_api_1 = readme_example_1()
    assert open_api_1
    dump_json = getattr(open_api_1, "model_dump_json" if PYDANTIC_V2 else "json")
    open_api_json_1 = dump_json(by_alias=True, exclude_none=True, indent=2)
    logging.debug(open_api_json_1)
    assert open_api_json_1

    open_api_2 = readme_example_2()
    assert open_api_1 == open_api_2

    open_api_3 = readme_example_3()
    assert open_api_1 == open_api_3


def readme_example_1() -> OpenAPI:
    """Construct OpenAPI using data class"""
    return OpenAPI(
        info=Info(
            title="My own API",
            version="v0.0.1",
        ),
        paths={
            "/ping": PathItem(
                get=Operation(responses={"200": Response(description="pong")})
            )
        },
    )


def readme_example_2() -> OpenAPI:
    """Construct OpenAPI from raw data object"""
    openapi_validate: Callable[[dict], OpenAPI] = getattr(
        OpenAPI, "model_validate" if PYDANTIC_V2 else "parse_obj"
    )
    return openapi_validate(
        {
            "info": {"title": "My own API", "version": "v0.0.1"},
            "paths": {
                "/ping": {"get": {"responses": {"200": {"description": "pong"}}}}
            },
        }
    )


def readme_example_3() -> OpenAPI:
    """Construct OpenAPI from mixed object"""
    openapi_validate: Callable[[dict], OpenAPI] = getattr(
        OpenAPI, "model_validate" if PYDANTIC_V2 else "parse_obj"
    )
    return openapi_validate(
        {
            "info": {"title": "My own API", "version": "v0.0.1"},
            "paths": {
                "/ping": PathItem(
                    get={"responses": {"200": Response(description="pong")}}
                )
            },
        }
    )