Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: cli schema export with non-serializable types #2581

Merged
merged 3 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 24 additions & 10 deletions litestar/cli/commands/schema.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
from json import dumps
from pathlib import Path
from typing import TYPE_CHECKING

import msgspec
from yaml import dump as dump_yaml

from litestar import Litestar
from litestar._openapi.typescript_converter.converter import (
convert_openapi_to_typescript,
)
from litestar.cli._utils import JSBEAUTIFIER_INSTALLED, RICH_CLICK_INSTALLED, LitestarCLIException, LitestarGroup
from litestar.serialization import encode_json, get_serializer

if TYPE_CHECKING or not RICH_CLICK_INSTALLED: # pragma: no cover
from click import Path as ClickPath
Expand All @@ -31,6 +32,27 @@ def schema_group() -> None:
"""Manage server-side OpenAPI schemas."""


def _generate_openapi_schema(app: Litestar, output: Path) -> None:
cofin marked this conversation as resolved.
Show resolved Hide resolved
"""Generate an OpenAPI Schema."""
serializer = get_serializer(app.type_encoders)
if output.suffix in (".yml", ".yaml"):
content = dump_yaml(
msgspec.to_builtins(app.openapi_schema.to_schema(), enc_hook=serializer),
default_flow_style=False,
encoding="utf-8",
cofin marked this conversation as resolved.
Show resolved Hide resolved
)
else:
content = msgspec.json.format(
encode_json(app.openapi_schema.to_schema(), serializer=serializer),
indent=4,
)

try:
output.write_bytes(content)
except OSError as e: # pragma: no cover
raise LitestarCLIException(f"failed to write schema to path {output}") from e


@schema_group.command("openapi") # type: ignore
@option(
"--output",
Expand All @@ -41,15 +63,7 @@ def schema_group() -> None:
)
def generate_openapi_schema(app: Litestar, output: Path) -> None:
"""Generate an OpenAPI Schema."""
if output.suffix in (".yml", ".yaml"):
content = dump_yaml(app.openapi_schema.to_schema(), default_flow_style=False)
else:
content = dumps(app.openapi_schema.to_schema(), indent=4)

try:
output.write_text(content)
except OSError as e: # pragma: no cover
raise LitestarCLIException(f"failed to write schema to path {output}") from e
_generate_openapi_schema(app, output)


@schema_group.command("typescript") # type: ignore
Expand Down
34 changes: 29 additions & 5 deletions tests/unit/test_cli/test_schema_commands.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
from __future__ import annotations

from json import dumps as json_dumps
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Callable

import pytest
from yaml import dump as dump_yaml

from litestar.cli.commands.schema import _generate_openapi_schema
from litestar.cli.main import litestar_group as cli_command

if TYPE_CHECKING:
from pathlib import Path
from types import ModuleType

from click.testing import CliRunner
from pytest import MonkeyPatch
from pytest_mock import MockerFixture
Expand All @@ -19,23 +23,43 @@ def test_openapi_schema_command(
runner: CliRunner, mocker: MockerFixture, monkeypatch: MonkeyPatch, filename: str
) -> None:
monkeypatch.setenv("LITESTAR_APP", "test_apps.openapi_test_app.main:app")
mock_path_write_text = mocker.patch("pathlib.Path.write_text")
mock_path_write_bytes = mocker.patch("pathlib.Path.write_bytes")
command = "schema openapi"

from test_apps.openapi_test_app.main import app as openapi_test_app

assert openapi_test_app.openapi_schema
schema = openapi_test_app.openapi_schema.to_schema()

expected_content = json_dumps(schema, indent=4)
expected_content = json_dumps(schema, indent=4).encode()
if filename:
command += f" --output {filename}"
if filename.endswith(("yaml", "yml")):
expected_content = dump_yaml(schema, default_flow_style=False)
expected_content = dump_yaml(schema, default_flow_style=False, encoding="utf-8")

result = runner.invoke(cli_command, command)
assert result.exit_code == 0
mock_path_write_text.assert_called_once_with(expected_content)
mock_path_write_bytes.assert_called_once_with(expected_content)


@pytest.mark.parametrize("suffix", ("json", "yaml", "yml"))
def test_schema_export_with_examples(suffix: str, create_module: Callable[[str], ModuleType], tmp_path: Path) -> None:
module = create_module(
"""
from datetime import datetime
from litestar import Litestar, get
from litestar.openapi import OpenAPIConfig

@get()
async def something(date: datetime) -> None:
return None

app = Litestar([something], openapi_config=OpenAPIConfig('example', '0.0.1', True))
"""
)
pth = tmp_path / f"openapi.{suffix}"
_generate_openapi_schema(module.app, pth)
assert pth.read_text()


@pytest.mark.parametrize(
Expand Down