repo
stringclasses 856
values | pull_number
int64 3
127k
| instance_id
stringlengths 12
58
| issue_numbers
sequencelengths 1
5
| base_commit
stringlengths 40
40
| patch
stringlengths 67
1.54M
| test_patch
stringlengths 0
107M
| problem_statement
stringlengths 3
307k
| hints_text
stringlengths 0
908k
| created_at
timestamp[s] |
---|---|---|---|---|---|---|---|---|---|
litestar-org/litestar | 1,839 | litestar-org__litestar-1839 | [
"4321",
"1234"
] | a1842a000f2f3639bc9d1b0875ae31da050689cd | diff --git a/litestar/handlers/http_handlers/_utils.py b/litestar/handlers/http_handlers/_utils.py
--- a/litestar/handlers/http_handlers/_utils.py
+++ b/litestar/handlers/http_handlers/_utils.py
@@ -87,24 +87,17 @@ async def handler(
return handler
-def create_generic_asgi_response_handler(
- after_request: AfterRequestHookHandler | None,
- cookies: frozenset[Cookie],
-) -> AsyncAnyCallable:
+def create_generic_asgi_response_handler(after_request: AfterRequestHookHandler | None) -> AsyncAnyCallable:
"""Create a handler function for Responses.
Args:
after_request: An after request handler.
- cookies: A set of pre-defined cookies.
Returns:
A handler function.
"""
async def handler(data: ASGIApp, **kwargs: Any) -> ASGIApp:
- if hasattr(data, "set_cookie"):
- for cookie in cookies:
- data.set_cookie(**cookie.dict)
return await after_request(data) if after_request else data # type: ignore
return handler
diff --git a/litestar/handlers/http_handlers/base.py b/litestar/handlers/http_handlers/base.py
--- a/litestar/handlers/http_handlers/base.py
+++ b/litestar/handlers/http_handlers/base.py
@@ -435,7 +435,7 @@ def get_response_handler(self, is_response_type_data: bool = False) -> Callable[
self._response_handler_mapping["default_handler"] = response_type_handler
elif is_async_callable(return_annotation) or return_annotation is ASGIApp:
self._response_handler_mapping["default_handler"] = create_generic_asgi_response_handler(
- after_request=after_request, cookies=cookies
+ after_request=after_request
)
else:
self._response_handler_mapping["default_handler"] = create_data_handler(
| diff --git a/tests/handlers/http/test_to_response.py b/tests/handlers/http/test_to_response.py
--- a/tests/handlers/http/test_to_response.py
+++ b/tests/handlers/http/test_to_response.py
@@ -131,7 +131,7 @@ def test_function() -> Response:
async def test_to_response_returning_starlette_response(
expected_response: StarletteResponse, anyio_backend: str
) -> None:
- @get(path="/test", response_cookies=[Cookie(key="my-cookies", value="abc", path="/test")])
+ @get(path="/test")
def test_function() -> StarletteResponse:
return expected_response
@@ -143,7 +143,6 @@ def test_function() -> StarletteResponse:
)
assert isinstance(response, StarletteResponse)
assert response is expected_response # type: ignore[unreachable]
- assert response.headers["set-cookie"] == "my-cookies=abc; Path=/test; SameSite=lax"
async def test_to_response_returning_redirect_response(anyio_backend: str) -> None:
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-06-17T23:52:23 |
litestar-org/litestar | 1,843 | litestar-org__litestar-1843 | [
"1822"
] | 762516aaec3060eab5f09f8f3df33914123a2899 | diff --git a/litestar/dto/factory/_backends/msgspec/backend.py b/litestar/dto/factory/_backends/msgspec/backend.py
--- a/litestar/dto/factory/_backends/msgspec/backend.py
+++ b/litestar/dto/factory/_backends/msgspec/backend.py
@@ -2,7 +2,7 @@
from typing import TYPE_CHECKING, NewType, TypeVar
-from msgspec import Struct, from_builtins
+from msgspec import Struct, convert
from litestar.dto.factory._backends.abc import AbstractDTOBackend
from litestar.serialization import decode_media_type
@@ -35,4 +35,4 @@ def parse_raw(self, raw: bytes, connection_context: ConnectionContext) -> Struct
)
def parse_builtins(self, builtins: Any, connection_context: ConnectionContext) -> Any:
- return from_builtins(builtins, self.annotation)
+ return convert(builtins, self.annotation)
| Migrating from `msgspec.from_builtins` to `msgspec.convert`
Msgspec deprecated `from_builtins` in favour of `convert` in the latest release. We should update accordingly.
See https://github.com/jcrist/msgspec/releases/tag/0.16.0 and https://jcristharif.com/msgspec/converters.html
| 2023-06-18T11:08:12 |
||
litestar-org/litestar | 1,850 | litestar-org__litestar-1850 | [
"1845"
] | 47c00e6096ca02bcb6fa697e6f03d096465903e6 | diff --git a/docs/examples/conftest.py b/docs/examples/conftest.py
deleted file mode 100644
--- a/docs/examples/conftest.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import logging
-import os
-from typing import Generator
-
-import pytest
-
-
[email protected]()
-def reset_httpx_logging() -> Generator[None, None, None]:
- # ensure that httpx logging is not interfering with our test client
- httpx_logger = logging.getLogger("httpx")
- initial_level = httpx_logger.level
- httpx_logger.setLevel(logging.WARNING)
- yield
- httpx_logger.setLevel(initial_level)
-
-
-# the monkeypatch fixture does not work with session scoped dependencies
[email protected](autouse=True, scope="session")
-def disable_warn_implicit_sync_to_thread() -> Generator[None, None, None]:
- old_value = os.getenv("LITESTAR_WARN_IMPLICIT_SYNC_TO_THREAD")
- os.environ["LITESTAR_WARN_IMPLICIT_SYNC_TO_THREAD"] = "0"
- yield
- if old_value is not None:
- os.environ["LITESTAR_WARN_IMPLICIT_SYNC_TO_THREAD"] = old_value
| diff --git a/docs/examples/tests/test_request_data.py b/docs/examples/tests/test_request_data.py
deleted file mode 100644
--- a/docs/examples/tests/test_request_data.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from examples.request_data.msgpack_request import app as msgpack_app
-from litestar.serialization import encode_msgpack
-from litestar.testing import TestClient
-
-
-def test_msgpack_app() -> None:
- test_data = {"name": "Moishe Zuchmir", "age": 30, "programmer": True}
-
- with TestClient(app=msgpack_app) as client:
- response = client.post("/", content=encode_msgpack(test_data))
- assert response.json() == test_data
diff --git a/test_apps/openapi_test_app/main.py b/test_apps/openapi_test_app/main.py
--- a/test_apps/openapi_test_app/main.py
+++ b/test_apps/openapi_test_app/main.py
@@ -1,7 +1,7 @@
from typing import Dict
from litestar import Litestar, get
-from tests.openapi.conftest import create_person_controller, create_pet_controller
+from tests.unit.test_openapi.conftest import create_person_controller, create_pet_controller
@get("/")
diff --git a/test_apps/piccolo_admin_test_app/home/tables.py b/test_apps/piccolo_admin_test_app/home/tables.py
--- a/test_apps/piccolo_admin_test_app/home/tables.py
+++ b/test_apps/piccolo_admin_test_app/home/tables.py
@@ -2,7 +2,6 @@
from piccolo.columns import Boolean, ForeignKey, Timestamp, Varchar
from piccolo.columns.readable import Readable
from piccolo.table import Table
-
from piccolo_conf import DB
diff --git a/tests/app/test_app.py b/tests/app/test_app.py
deleted file mode 100644
--- a/tests/app/test_app.py
+++ /dev/null
@@ -1,67 +0,0 @@
-from __future__ import annotations
-
-import logging
-
-import pytest
-from pytest import MonkeyPatch
-
-from litestar import Litestar
-from litestar.exceptions import ImproperlyConfiguredException, LitestarWarning
-
-
-def test_access_openapi_schema_raises_if_not_configured() -> None:
- """Test that accessing the openapi schema raises if not configured."""
- app = Litestar(openapi_config=None)
- with pytest.raises(ImproperlyConfiguredException):
- app.openapi_schema
-
-
-def test_set_debug_updates_logging_level() -> None:
- app = Litestar()
-
- assert app.logger is not None
- assert app.logger.level == logging.INFO # type: ignore[attr-defined]
-
- app.debug = True
- assert app.logger.level == logging.DEBUG # type: ignore[attr-defined]
-
- app.debug = False
- assert app.logger.level == logging.INFO # type: ignore[attr-defined]
-
-
[email protected]("env_name,app_attr", [("LITESTAR_DEBUG", "debug"), ("LITESTAR_PDB", "pdb_on_exception")])
[email protected](
- "env_value,app_value,expected_value",
- [
- (None, None, False),
- (None, False, False),
- (None, True, True),
- ("0", None, False),
- ("0", False, False),
- ("0", True, True),
- ("1", None, True),
- ("1", False, False),
- ("1", True, True),
- ],
-)
-def test_set_env_flags(
- monkeypatch: MonkeyPatch,
- env_value: str | None,
- app_value: bool | None,
- expected_value: bool,
- env_name: str,
- app_attr: str,
-) -> None:
- if env_value is not None:
- monkeypatch.setenv(env_name, env_value)
- else:
- monkeypatch.delenv(env_name, raising=False)
-
- app = Litestar(**{app_attr: app_value}) # type: ignore[arg-type]
-
- assert getattr(app, app_attr) is expected_value
-
-
-def test_warn_pdb_on_exception() -> None:
- with pytest.warns(LitestarWarning, match="Debugger"):
- Litestar(pdb_on_exception=True)
diff --git a/tests/app/test_app_config.py b/tests/app/test_app_config.py
deleted file mode 100644
--- a/tests/app/test_app_config.py
+++ /dev/null
@@ -1,143 +0,0 @@
-import inspect
-from dataclasses import fields
-from typing import List, Tuple
-from unittest.mock import MagicMock, Mock, PropertyMock
-
-import pytest
-
-from litestar.app import Litestar
-from litestar.config.app import AppConfig
-from litestar.config.response_cache import ResponseCacheConfig
-from litestar.datastructures import State
-from litestar.events.emitter import SimpleEventEmitter
-from litestar.logging.config import LoggingConfig
-from litestar.router import Router
-
-
[email protected]()
-def app_config_object() -> AppConfig:
- return AppConfig(
- after_exception=[],
- after_request=None,
- after_response=None,
- allowed_hosts=[],
- before_request=None,
- before_send=[],
- response_cache_config=ResponseCacheConfig(),
- cache_control=None,
- compression_config=None,
- cors_config=None,
- csrf_config=None,
- debug=False,
- dependencies={},
- etag=None,
- event_emitter_backend=SimpleEventEmitter,
- exception_handlers={},
- guards=[],
- listeners=[],
- logging_config=None,
- middleware=[],
- multipart_form_part_limit=1000,
- on_shutdown=[],
- on_startup=[],
- openapi_config=None,
- opt={},
- parameters={},
- plugins=[],
- request_class=None,
- response_class=None,
- response_cookies=[],
- response_headers=[],
- route_handlers=[],
- security=[],
- static_files_config=[],
- tags=[],
- template_config=None,
- websocket_class=None,
- )
-
-
-def test_app_params_defined_on_app_config_object() -> None:
- """Ensures that all parameters to the `Litestar` constructor are present on the `AppConfig` object."""
- litestar_signature = inspect.signature(Litestar)
- app_config_fields = {f.name for f in fields(AppConfig)}
- for name in litestar_signature.parameters:
- if name in {"on_app_init", "initial_state", "_preferred_validation_backend"}:
- continue
- assert name in app_config_fields
- # ensure there are not fields defined on AppConfig that aren't in the Litestar signature
- assert not (app_config_fields - set(litestar_signature.parameters.keys()))
-
-
-def test_app_config_object_used(app_config_object: AppConfig, monkeypatch: pytest.MonkeyPatch) -> None:
- """Ensure that the properties on the `AppConfig` object are accessed within the `Litestar` constructor.
-
- In the test we replace every field on the `AppConfig` type with a property mock so that we can check that it has at
- least been accessed. It doesn't actually check that we do the right thing with it, but is a guard against the case
- of adding a parameter to the `Litestar` signature and to the `AppConfig` object, and using the value from the
- parameter downstream from construction of the `AppConfig` object.
- """
-
- # replace each field on the `AppConfig` object with a `PropertyMock`, this allows us to assert that the properties
- # have been accessed during app instantiation.
- property_mocks: List[Tuple[str, Mock]] = []
- for field in fields(AppConfig):
- if field.name == "response_cache_config":
- property_mock = PropertyMock(return_value=ResponseCacheConfig())
- if field.name in ["event_emitter_backend", "response_cache_config"]:
- property_mock = PropertyMock(return_value=Mock())
- else:
- # default iterable return value allows the mock properties that need to be iterated over in
- # `Litestar.__init__()` to not blow up, for other properties it shouldn't matter what the value is for the
- # sake of this test.
- property_mock = PropertyMock(return_value=[])
- property_mocks.append((field.name, property_mock))
- monkeypatch.setattr(type(app_config_object), field.name, property_mock, raising=False)
-
- # Things that we don't actually need to call for this test
- monkeypatch.setattr(Litestar, "register", MagicMock())
- monkeypatch.setattr(Litestar, "_create_asgi_handler", MagicMock())
- monkeypatch.setattr(Router, "__init__", MagicMock())
-
- # instantiates the app with an `on_app_config` that returns our patched `AppConfig` object.
- Litestar(on_app_init=[MagicMock(return_value=app_config_object)])
-
- # this ensures that each of the properties of the `AppConfig` object have been accessed within `Litestar.__init__()`
- for name, mock in property_mocks:
- assert mock.called, f"expected {name} to be called"
-
-
-def test_app_debug_create_logger() -> None:
- app = Litestar([], debug=True)
-
- assert app.logging_config
- assert app.logging_config.loggers["litestar"]["level"] == "DEBUG" # type: ignore[attr-defined]
-
-
-def test_app_debug_explicitly_disable_logging() -> None:
- app = Litestar([], debug=True, logging_config=None)
-
- assert not app.logging_config
-
-
-def test_app_debug_update_logging_config() -> None:
- logging_config = LoggingConfig()
- app = Litestar([], debug=True, logging_config=logging_config)
-
- assert app.logging_config is logging_config
- assert app.logging_config.loggers["litestar"]["level"] == "DEBUG" # type: ignore[attr-defined]
-
-
-def test_set_state() -> None:
- def modify_state_in_hook(app_config: AppConfig) -> AppConfig:
- assert isinstance(app_config.state, State)
- app_config.state["c"] = "D"
- app_config.state["e"] = "f"
- return app_config
-
- app = Litestar(state=State({"a": "b", "c": "d"}), on_app_init=[modify_state_in_hook])
- assert app.state._state == {"a": "b", "c": "D", "e": "f"}
-
-
-def test_app_from_config(app_config_object: AppConfig) -> None:
- Litestar.from_config(app_config_object)
diff --git a/tests/app/test_before_send.py b/tests/app/test_before_send.py
deleted file mode 100644
--- a/tests/app/test_before_send.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# ruff: noqa: UP006
-from __future__ import annotations
-
-from typing import TYPE_CHECKING
-
-from litestar import Litestar, get
-from litestar.datastructures import MutableScopeHeaders
-from litestar.status_codes import HTTP_200_OK
-from litestar.testing import create_test_client
-
-if TYPE_CHECKING:
- from typing import Dict
-
- from litestar.types import Message, Scope
-
-
-def test_before_send() -> None:
- @get("/test")
- def handler() -> Dict[str, str]:
- return {"key": "value"}
-
- async def before_send_hook_handler(message: Message, scope: Scope) -> None:
- if message["type"] == "http.response.start":
- headers = MutableScopeHeaders(message)
- headers.add("My Header", scope["app"].state.message)
-
- def on_startup(app: Litestar) -> None:
- app.state.message = "value injected during send"
-
- with create_test_client(handler, on_startup=[on_startup], before_send=[before_send_hook_handler]) as client:
- response = client.get("/test")
- assert response.status_code == HTTP_200_OK
- assert response.headers.get("My Header") == "value injected during send"
diff --git a/tests/app/test_error_handling.py b/tests/app/test_error_handling.py
deleted file mode 100644
--- a/tests/app/test_error_handling.py
+++ /dev/null
@@ -1,68 +0,0 @@
-from litestar import Litestar, MediaType, Request, Response, get, post
-from litestar.exceptions import InternalServerException, NotFoundException
-from litestar.status_codes import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
-from litestar.testing import TestClient, create_test_client
-from tests import Person
-
-
-def test_default_handling_of_pydantic_errors() -> None:
- @post("/{param:int}")
- def my_route_handler(param: int, data: Person) -> None:
- ...
-
- with create_test_client(my_route_handler) as client:
- response = client.post("/123", json={"first_name": "moishe"})
- extra = response.json().get("extra")
- assert extra is not None
- assert len(extra) == 3
-
-
-def test_using_custom_http_exception_handler() -> None:
- @get("/{param:int}")
- def my_route_handler(param: int) -> None:
- ...
-
- def my_custom_handler(_: Request, __: Exception) -> Response:
- return Response(content="custom message", media_type=MediaType.TEXT, status_code=HTTP_400_BAD_REQUEST)
-
- with create_test_client(my_route_handler, exception_handlers={NotFoundException: my_custom_handler}) as client:
- response = client.get("/abc")
- assert response.text == "custom message"
- assert response.status_code == HTTP_400_BAD_REQUEST
-
-
-def test_debug_response_created() -> None:
- # this will test exception causes are recorded in output
- # since frames include code in context we should not raise
- # exception directly
- def exception_thrower() -> float:
- return 1 / 0
-
- @get("/")
- def my_route_handler() -> None:
- try:
- exception_thrower()
- except Exception as e:
- raise InternalServerException() from e
-
- app = Litestar(route_handlers=[my_route_handler], debug=True)
- client = TestClient(app=app)
-
- response = client.get("/")
- assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert "text/plain" in response.headers["content-type"]
-
- response = client.get("/", headers={"accept": "text/html"})
- assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert "text/html" in response.headers["content-type"]
- assert "ZeroDivisionError" in response.text
-
-
-def test_handler_error_return_status_500() -> None:
- @get("/")
- def my_route_handler() -> None:
- raise KeyError("custom message")
-
- with create_test_client(my_route_handler) as client:
- response = client.get("/")
- assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
diff --git a/tests/app/test_lifespan.py b/tests/app/test_lifespan.py
deleted file mode 100644
--- a/tests/app/test_lifespan.py
+++ /dev/null
@@ -1,68 +0,0 @@
-from __future__ import annotations
-
-from typing import TYPE_CHECKING
-
-from litestar.datastructures import State
-from litestar.testing import create_test_client
-
-if TYPE_CHECKING:
- from litestar import Litestar
-
-
-def test_lifespan() -> None:
- events: list[str] = []
- counter = {"value": 0}
-
- def sync_function_without_app() -> None:
- events.append("sync_function_without_app")
- counter["value"] += 1
-
- async def async_function_without_app() -> None:
- events.append("async_function_without_app")
- counter["value"] += 1
-
- def sync_function_with_app(app: Litestar) -> None:
- events.append("sync_function_with_app")
- assert app is not None
- assert isinstance(app.state, State)
- counter["value"] += 1
- app.state.x = True
-
- async def async_function_with_app(app: Litestar) -> None:
- events.append("async_function_with_app")
- assert app is not None
- assert isinstance(app.state, State)
- counter["value"] += 1
- app.state.y = True
-
- with create_test_client(
- [],
- on_startup=[
- sync_function_without_app,
- async_function_without_app,
- sync_function_with_app,
- async_function_with_app,
- ],
- on_shutdown=[
- sync_function_without_app,
- async_function_without_app,
- sync_function_with_app,
- async_function_with_app,
- ],
- ) as client:
- assert counter["value"] == 4
- assert client.app.state.x
- assert client.app.state.y
- counter["value"] = 0
- assert counter["value"] == 0
- assert counter["value"] == 4
- assert events == [
- "sync_function_without_app",
- "async_function_without_app",
- "sync_function_with_app",
- "async_function_with_app",
- "sync_function_without_app",
- "async_function_without_app",
- "sync_function_with_app",
- "async_function_with_app",
- ]
diff --git a/tests/app/test_registering_route_handlers.py b/tests/app/test_registering_route_handlers.py
deleted file mode 100644
--- a/tests/app/test_registering_route_handlers.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from litestar import Litestar, get
-
-
-def test_registering_route_handler_generates_openapi_docs() -> None:
- def fn() -> None:
- return
-
- app = Litestar(route_handlers=[])
- assert app.openapi_schema
-
- app.register(get("/path1")(fn))
-
- paths = app.openapi_schema.paths
-
- assert paths is not None
- assert paths.get("/path1")
-
- app.register(get("/path2")(fn))
- assert paths.get("/path2")
diff --git a/tests/asgi_router/routing_trie/test_path_param_resolution.py b/tests/asgi_router/routing_trie/test_path_param_resolution.py
deleted file mode 100644
--- a/tests/asgi_router/routing_trie/test_path_param_resolution.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from litestar import get
-from litestar.status_codes import HTTP_200_OK, HTTP_404_NOT_FOUND
-from litestar.testing import create_test_client
-
-
-def test_root_path_param_resolution() -> None:
- # https://github.com/litestar-org/litestar/issues/1830
- @get("/{name:str}")
- async def hello_world(name: str) -> str:
- return f"Hello, {name}!"
-
- with create_test_client(hello_world) as client:
- response = client.get("/jon")
- assert response.status_code == HTTP_200_OK
- assert response.text == "Hello, jon!"
-
- response = client.get("/jon/bon")
- assert response.status_code == HTTP_404_NOT_FOUND
-
- response = client.get("/jon/bon/jovi")
- assert response.status_code == HTTP_404_NOT_FOUND
diff --git a/tests/asgi_router/test_adding_routes_to_trie.py b/tests/asgi_router/test_adding_routes_to_trie.py
deleted file mode 100644
--- a/tests/asgi_router/test_adding_routes_to_trie.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import TYPE_CHECKING
-
-import pytest
-
-from litestar import Litestar, asgi
-from litestar.exceptions import ImproperlyConfiguredException
-
-if TYPE_CHECKING:
- from litestar.types import Receive, Scope, Send
-
-
-def test_add_mount_route_disallow_path_parameter() -> None:
- async def handler(scope: "Scope", receive: "Receive", send: "Send") -> None:
- return None
-
- with pytest.raises(ImproperlyConfiguredException):
- Litestar(route_handlers=[asgi("/mount-path", is_static=True)(handler), asgi("/mount-path/{id:str}")(handler)])
diff --git a/tests/conftest.py b/tests/conftest.py
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,70 +1,47 @@
from __future__ import annotations
-import asyncio
import importlib.util
import logging
import os
import random
-import re
import string
-import subprocess
import sys
-import timeit
from os import urandom
from pathlib import Path
-from typing import (
- TYPE_CHECKING,
- Any,
- Awaitable,
- Callable,
- Generator,
- TypeVar,
- Union,
- cast,
-)
+from typing import TYPE_CHECKING, Any, AsyncGenerator, Callable, Generator, TypeVar, Union, cast
+from unittest.mock import AsyncMock, MagicMock
-import asyncmy
-import asyncpg
-import oracledb
import pytest
-from _pytest.fixtures import FixtureRequest
from fakeredis.aioredis import FakeRedis
from freezegun import freeze_time
-from google.auth.credentials import AnonymousCredentials # pyright: ignore
-from google.cloud import spanner # pyright: ignore
-from oracledb.exceptions import DatabaseError, OperationalError
from pytest_lazyfixture import lazy_fixture
from redis.asyncio import Redis as AsyncRedis
-from redis.exceptions import ConnectionError as RedisConnectionError
+from redis.client import Redis
+from litestar.logging import LoggingConfig
+from litestar.logging.config import default_handlers as logging_default_handlers
from litestar.middleware.session import SessionMiddleware
from litestar.middleware.session.base import BaseSessionBackend
-from litestar.middleware.session.client_side import (
- ClientSideSessionBackend,
- CookieBackendConfig,
-)
-from litestar.middleware.session.server_side import (
- ServerSideSessionBackend,
- ServerSideSessionConfig,
-)
+from litestar.middleware.session.client_side import ClientSideSessionBackend, CookieBackendConfig
+from litestar.middleware.session.server_side import ServerSideSessionBackend, ServerSideSessionConfig
from litestar.stores.base import Store
from litestar.stores.file import FileStore
from litestar.stores.memory import MemoryStore
from litestar.stores.redis import RedisStore
from litestar.testing import RequestFactory
-from litestar.utils.sync import AsyncCallable
if TYPE_CHECKING:
from types import ModuleType
from freezegun.api import FrozenDateTimeFactory
- from pytest import MonkeyPatch
+ from pytest import FixtureRequest, MonkeyPatch
from litestar import Litestar
from litestar.types import (
AnyIOBackend,
ASGIApp,
ASGIVersion,
+ GetLogger,
Receive,
RouteHandlerType,
Scope,
@@ -73,17 +50,20 @@
)
+pytest_plugins = ["tests.docker_service_fixtures"]
+
+
[email protected]
+def mock() -> MagicMock:
+ return MagicMock()
+
+
@pytest.fixture()
-def template_dir(tmp_path: Path) -> Path:
- return tmp_path
+def async_mock() -> AsyncMock:
+ return AsyncMock()
[email protected](
- params=[
- pytest.param("asyncio", id="asyncio"),
- pytest.param("trio", id="trio"),
- ]
-)
[email protected](params=[pytest.param("asyncio", id="asyncio"), pytest.param("trio", id="trio")])
def anyio_backend(request: pytest.FixtureRequest) -> str:
return request.param # type: ignore[no-any-return]
@@ -274,11 +254,6 @@ def module_name_generator() -> str:
return wrapped
[email protected](scope="module")
-def mock_db() -> MemoryStore:
- return MemoryStore()
-
-
@pytest.fixture()
def frozen_datetime() -> Generator[FrozenDateTimeFactory, None, None]:
with freeze_time() as frozen:
@@ -320,198 +295,27 @@ def enable_warn_implicit_sync_to_thread(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setenv("LITESTAR_WARN_IMPLICIT_SYNC_TO_THREAD", "1")
-# Docker services
-
-
-async def wait_until_responsive(
- check: Callable[..., Awaitable],
- timeout: float,
- pause: float,
- **kwargs: Any,
-) -> None:
- """Wait until a service is responsive.
-
- Args:
- check: Coroutine, return truthy value when waiting should stop.
- timeout: Maximum seconds to wait.
- pause: Seconds to wait between calls to `check`.
- **kwargs: Given as kwargs to `check`.
- """
- ref = timeit.default_timer()
- now = ref
- while (now - ref) < timeout:
- if await check(**kwargs):
- return
- await asyncio.sleep(pause)
- now = timeit.default_timer()
-
- raise Exception("Timeout reached while waiting on service!")
-
-
-class DockerServiceRegistry:
- def __init__(self) -> None:
- self._running_services: set[str] = set()
- self.docker_ip = self._get_docker_ip()
- self._base_command = [
- "docker-compose",
- "--file=tests/docker-compose.yml",
- "--project-name=litestar_pytest",
- ]
-
- def _get_docker_ip(self) -> str:
- docker_host = os.environ.get("DOCKER_HOST", "").strip()
- if not docker_host or docker_host.startswith("unix://"):
- return "127.0.0.1"
-
- match = re.match(r"^tcp://(.+?):\d+$", docker_host)
- if not match:
- raise ValueError(f'Invalid value for DOCKER_HOST: "{docker_host}".')
- return match.group(1)
-
- def run_command(self, *args: str) -> None:
- subprocess.run([*self._base_command, *args], check=True, capture_output=True)
-
- async def start(
- self,
- name: str,
- *,
- check: Callable[..., Awaitable],
- timeout: float = 30,
- pause: float = 0.1,
- **kwargs: Any,
- ) -> None:
- if name not in self._running_services:
- self.run_command("up", "-d", name)
- self._running_services.add(name)
-
- await wait_until_responsive(
- check=AsyncCallable(check),
- timeout=timeout,
- pause=pause,
- host=self.docker_ip,
- **kwargs,
- )
-
- def stop(self, name: str) -> None:
- pass
-
- def down(self) -> None:
- self.run_command("down", "-t", "5")
-
-
[email protected](scope="session")
-def docker_services() -> Generator[DockerServiceRegistry, None, None]:
- registry = DockerServiceRegistry()
- yield registry
- registry.down()
-
-
[email protected](scope="session")
-def docker_ip(docker_services: DockerServiceRegistry) -> str:
- return docker_services.docker_ip
-
-
-async def redis_responsive(host: str) -> bool:
- client: AsyncRedis = AsyncRedis(host=host, port=6397)
- try:
- return await client.ping()
- except (ConnectionError, RedisConnectionError):
- return False
- finally:
- await client.close()
-
-
[email protected]()
-async def redis_service(docker_services: DockerServiceRegistry) -> None:
- await docker_services.start("redis", check=redis_responsive)
-
-
-async def mysql_responsive(host: str) -> bool:
- try:
- conn = await asyncmy.connect(
- host=host,
- port=3360,
- user="app",
- database="db",
- password="super-secret",
- )
- async with conn.cursor() as cursor:
- await cursor.execute("select 1 as is_available")
- resp = await cursor.fetchone()
- return bool(resp[0] == 1)
- except asyncmy.errors.OperationalError: # pyright: ignore
- return False
-
-
[email protected]()
-async def mysql_service(docker_services: DockerServiceRegistry) -> None:
- await docker_services.start("mysql", check=mysql_responsive)
-
-
-async def postgres_responsive(host: str) -> bool:
- try:
- conn = await asyncpg.connect(
- host=host, port=5423, user="postgres", database="postgres", password="super-secret"
- )
- except (ConnectionError, asyncpg.CannotConnectNowError):
- return False
-
- try:
- return (await conn.fetchrow("SELECT 1"))[0] == 1 # type: ignore
- finally:
- await conn.close()
[email protected]
+def get_logger() -> GetLogger:
+ # due to the limitations of caplog we have to place this call here.
+ # we also have to allow propagation.
+ return LoggingConfig(
+ handlers=logging_default_handlers,
+ loggers={
+ "litestar": {"level": "INFO", "handlers": ["queue_listener"], "propagate": True},
+ },
+ ).configure()
@pytest.fixture()
-async def postgres_service(docker_services: DockerServiceRegistry) -> None:
- await docker_services.start("postgres", check=postgres_responsive)
-
+async def redis_client(docker_ip: str, redis_service: None) -> AsyncGenerator[AsyncRedis, None]:
+ # this is to get around some weirdness with pytest-asyncio and redis interaction
+ # on 3.8 and 3.9
-def oracle_responsive(host: str) -> bool:
+ Redis(host=docker_ip, port=6397).flushall()
+ client: AsyncRedis = AsyncRedis(host=docker_ip, port=6397)
+ yield client
try:
- conn = oracledb.connect(
- host=host,
- port=1512,
- user="app",
- service_name="xepdb1",
- password="super-secret",
- )
- with conn.cursor() as cursor:
- cursor.execute("SELECT 1 FROM dual")
- resp = cursor.fetchone()
- return bool(resp[0] == 1)
- except (OperationalError, DatabaseError): # pyright: ignore
- return False
-
-
[email protected]()
-async def oracle_service(docker_services: DockerServiceRegistry) -> None:
- await docker_services.start("oracle", check=AsyncCallable(oracle_responsive), timeout=60)
-
-
-def spanner_responsive(host: str) -> bool:
- try:
- os.environ["SPANNER_EMULATOR_HOST"] = "localhost:9010"
- os.environ["GOOGLE_CLOUD_PROJECT"] = "emulator-test-project"
- spanner_client = spanner.Client(project="emulator-test-project", credentials=AnonymousCredentials())
- instance = spanner_client.instance("test-instance")
- try:
- instance.create()
- except Exception: # pyright: ignore
- pass
- database = instance.database("test-database")
- try:
- database.create()
- except Exception: # pyright: ignore
- pass
- with database.snapshot() as snapshot:
- resp = list(snapshot.execute_sql("SELECT 1"))[0]
- return bool(resp[0] == 1)
- except Exception: # pyright: ignore
- return False
-
-
[email protected]()
-async def spanner_service(docker_services: DockerServiceRegistry) -> None:
- os.environ["SPANNER_EMULATOR_HOST"] = "localhost:9010"
- await docker_services.start("spanner", timeout=60, check=AsyncCallable(spanner_responsive))
+ await client.close()
+ except RuntimeError:
+ pass
diff --git a/tests/connection/request/test_request_state.py b/tests/connection/request/test_request_state.py
deleted file mode 100644
--- a/tests/connection/request/test_request_state.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from typing import TYPE_CHECKING, Dict
-
-from litestar import Request, get
-from litestar.middleware import MiddlewareProtocol
-from litestar.testing import create_test_client
-
-if TYPE_CHECKING:
- from litestar.types import ASGIApp, Receive, Scope, Send
-
-
-class BeforeRequestMiddleWare(MiddlewareProtocol):
- def __init__(self, app: "ASGIApp") -> None:
- self.app = app
-
- async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
- scope["state"]["main"] = 1
- await self.app(scope, receive, send)
-
-
-def before_request(request: Request) -> None:
- assert request.state.main == 1
- request.state.main = 2
-
-
-def test_state() -> None:
- @get(path="/")
- async def get_state(request: Request) -> Dict[str, str]:
- return {"state": request.state.main}
-
- with create_test_client(
- route_handlers=[get_state], middleware=[BeforeRequestMiddleWare], before_request=before_request
- ) as client:
- response = client.get("/")
- assert response.json() == {"state": 2}
diff --git a/tests/contrib/sqlalchemy/conftest.py b/tests/contrib/sqlalchemy/conftest.py
deleted file mode 100644
--- a/tests/contrib/sqlalchemy/conftest.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from __future__ import annotations
-
-try:
- import sqlalchemy
-
- if sqlalchemy.__version__.startswith("1."):
- collect_ignore_glob = ["*"]
-except ImportError:
- collect_ignore_glob = ["*"]
diff --git a/tests/dependency_injection/test_dependency_validation.py b/tests/dependency_injection/test_dependency_validation.py
deleted file mode 100644
--- a/tests/dependency_injection/test_dependency_validation.py
+++ /dev/null
@@ -1,38 +0,0 @@
-import pytest
-
-from litestar import Litestar, get
-from litestar.di import Provide
-from litestar.exceptions import ImproperlyConfiguredException
-
-
-async def first_method(query_param: int) -> int:
- assert isinstance(query_param, int)
- return query_param
-
-
-async def second_method(path_param: str) -> str:
- assert isinstance(path_param, str)
- return path_param
-
-
-def test_dependency_validation() -> None:
- @get(
- path="/{path_param:int}",
- dependencies={
- "first": Provide(first_method),
- "second": Provide(second_method),
- },
- )
- def test_function(first: int, second: str, third: int) -> None:
- pass
-
- with pytest.raises(ImproperlyConfiguredException):
- Litestar(
- route_handlers=[test_function],
- dependencies={"third": Provide(first_method)},
- )
-
-
-def test_raises_when_dependency_is_not_callable() -> None:
- with pytest.raises(ImproperlyConfiguredException):
- Provide(123) # type: ignore
diff --git a/tests/docker_service_fixtures.py b/tests/docker_service_fixtures.py
new file mode 100644
--- /dev/null
+++ b/tests/docker_service_fixtures.py
@@ -0,0 +1,220 @@
+from __future__ import annotations
+
+import asyncio
+import os
+import re
+import subprocess
+import sys
+import timeit
+from typing import Any, Awaitable, Callable, Generator
+
+import asyncmy
+import asyncpg
+import oracledb
+import pytest
+from google.auth.credentials import AnonymousCredentials # pyright: ignore
+from google.cloud import spanner # pyright: ignore
+from oracledb import DatabaseError, OperationalError
+from redis.asyncio import Redis as AsyncRedis
+from redis.exceptions import ConnectionError as RedisConnectionError
+
+from litestar.utils import AsyncCallable
+
+
+async def wait_until_responsive(
+ check: Callable[..., Awaitable],
+ timeout: float,
+ pause: float,
+ **kwargs: Any,
+) -> None:
+ """Wait until a service is responsive.
+
+ Args:
+ check: Coroutine, return truthy value when waiting should stop.
+ timeout: Maximum seconds to wait.
+ pause: Seconds to wait between calls to `check`.
+ **kwargs: Given as kwargs to `check`.
+ """
+ ref = timeit.default_timer()
+ now = ref
+ while (now - ref) < timeout:
+ if await check(**kwargs):
+ return
+ await asyncio.sleep(pause)
+ now = timeit.default_timer()
+
+ raise Exception("Timeout reached while waiting on service!")
+
+
+class DockerServiceRegistry:
+ def __init__(self) -> None:
+ self._running_services: set[str] = set()
+ self.docker_ip = self._get_docker_ip()
+ self._base_command = [
+ "docker-compose",
+ "--file=tests/docker-compose.yml",
+ "--project-name=litestar_pytest",
+ ]
+
+ def _get_docker_ip(self) -> str:
+ docker_host = os.environ.get("DOCKER_HOST", "").strip()
+ if not docker_host or docker_host.startswith("unix://"):
+ return "127.0.0.1"
+
+ match = re.match(r"^tcp://(.+?):\d+$", docker_host)
+ if not match:
+ raise ValueError(f'Invalid value for DOCKER_HOST: "{docker_host}".')
+ return match.group(1)
+
+ def run_command(self, *args: str) -> None:
+ subprocess.run([*self._base_command, *args], check=True, capture_output=True)
+
+ async def start(
+ self,
+ name: str,
+ *,
+ check: Callable[..., Awaitable],
+ timeout: float = 30,
+ pause: float = 0.1,
+ **kwargs: Any,
+ ) -> None:
+ if name not in self._running_services:
+ self.run_command("up", "-d", name)
+ self._running_services.add(name)
+
+ await wait_until_responsive(
+ check=AsyncCallable(check),
+ timeout=timeout,
+ pause=pause,
+ host=self.docker_ip,
+ **kwargs,
+ )
+
+ def stop(self, name: str) -> None:
+ pass
+
+ def down(self) -> None:
+ self.run_command("down", "-t", "5")
+
+
[email protected](scope="session")
+def docker_services() -> Generator[DockerServiceRegistry, None, None]:
+ if sys.platform != "linux":
+ pytest.skip("Docker not available on this platform")
+
+ registry = DockerServiceRegistry()
+ try:
+ yield registry
+ finally:
+ registry.down()
+
+
[email protected](scope="session")
+def docker_ip(docker_services: DockerServiceRegistry) -> str:
+ return docker_services.docker_ip
+
+
+async def redis_responsive(host: str) -> bool:
+ client: AsyncRedis = AsyncRedis(host=host, port=6397)
+ try:
+ return await client.ping()
+ except (ConnectionError, RedisConnectionError):
+ return False
+ finally:
+ await client.close()
+
+
[email protected]()
+async def redis_service(docker_services: DockerServiceRegistry) -> None:
+ await docker_services.start("redis", check=redis_responsive)
+
+
+async def mysql_responsive(host: str) -> bool:
+ try:
+ conn = await asyncmy.connect(
+ host=host,
+ port=3360,
+ user="app",
+ database="db",
+ password="super-secret",
+ )
+ async with conn.cursor() as cursor:
+ await cursor.execute("select 1 as is_available")
+ resp = await cursor.fetchone()
+ return bool(resp[0] == 1)
+ except asyncmy.errors.OperationalError: # pyright: ignore
+ return False
+
+
[email protected]()
+async def mysql_service(docker_services: DockerServiceRegistry) -> None:
+ await docker_services.start("mysql", check=mysql_responsive)
+
+
+async def postgres_responsive(host: str) -> bool:
+ try:
+ conn = await asyncpg.connect(
+ host=host, port=5423, user="postgres", database="postgres", password="super-secret"
+ )
+ except (ConnectionError, asyncpg.CannotConnectNowError):
+ return False
+
+ try:
+ return (await conn.fetchrow("SELECT 1"))[0] == 1 # type: ignore
+ finally:
+ await conn.close()
+
+
[email protected]()
+async def postgres_service(docker_services: DockerServiceRegistry) -> None:
+ await docker_services.start("postgres", check=postgres_responsive)
+
+
+def oracle_responsive(host: str) -> bool:
+ try:
+ conn = oracledb.connect(
+ host=host,
+ port=1512,
+ user="app",
+ service_name="xepdb1",
+ password="super-secret",
+ )
+ with conn.cursor() as cursor:
+ cursor.execute("SELECT 1 FROM dual")
+ resp = cursor.fetchone()
+ return bool(resp[0] == 1)
+ except (OperationalError, DatabaseError): # pyright: ignore
+ return False
+
+
[email protected]()
+async def oracle_service(docker_services: DockerServiceRegistry) -> None:
+ await docker_services.start("oracle", check=AsyncCallable(oracle_responsive), timeout=60)
+
+
+def spanner_responsive(host: str) -> bool:
+ try:
+ os.environ["SPANNER_EMULATOR_HOST"] = "localhost:9010"
+ os.environ["GOOGLE_CLOUD_PROJECT"] = "emulator-test-project"
+ spanner_client = spanner.Client(project="emulator-test-project", credentials=AnonymousCredentials())
+ instance = spanner_client.instance("test-instance")
+ try:
+ instance.create()
+ except Exception: # pyright: ignore
+ pass
+ database = instance.database("test-database")
+ try:
+ database.create()
+ except Exception: # pyright: ignore
+ pass
+ with database.snapshot() as snapshot:
+ resp = list(snapshot.execute_sql("SELECT 1"))[0]
+ return bool(resp[0] == 1)
+ except Exception: # pyright: ignore
+ return False
+
+
[email protected]()
+async def spanner_service(docker_services: DockerServiceRegistry) -> None:
+ os.environ["SPANNER_EMULATOR_HOST"] = "localhost:9010"
+ await docker_services.start("spanner", timeout=60, check=AsyncCallable(spanner_responsive))
diff --git a/docs/examples/tests/__init__.py b/tests/e2e/__init__.py
similarity index 100%
rename from docs/examples/tests/__init__.py
rename to tests/e2e/__init__.py
diff --git a/docs/examples/tests/application_hooks/__init__.py b/tests/e2e/test_dependency_injection/__init__.py
similarity index 100%
rename from docs/examples/tests/application_hooks/__init__.py
rename to tests/e2e/test_dependency_injection/__init__.py
diff --git a/tests/e2e/test_dependency_injection/test_dependency_validation.py b/tests/e2e/test_dependency_injection/test_dependency_validation.py
new file mode 100644
--- /dev/null
+++ b/tests/e2e/test_dependency_injection/test_dependency_validation.py
@@ -0,0 +1,24 @@
+import pytest
+
+from litestar import Litestar, get
+from litestar.exceptions import ImproperlyConfiguredException
+
+
+async def first_method(query_param: int) -> int:
+ return query_param
+
+
+async def second_method(path_param: str) -> str:
+ return path_param
+
+
+def test_dependency_validation() -> None:
+ @get(
+ path="/{path_param:int}",
+ dependencies={"first": first_method, "second": second_method},
+ )
+ def handler(first: int, second: str, third: int) -> None:
+ pass
+
+ with pytest.raises(ImproperlyConfiguredException):
+ Litestar(route_handlers=[handler], dependencies={"third": first_method})
diff --git a/tests/dependency_injection/test_http_handler_dependency_injection.py b/tests/e2e/test_dependency_injection/test_http_handler_dependency_injection.py
similarity index 100%
rename from tests/dependency_injection/test_http_handler_dependency_injection.py
rename to tests/e2e/test_dependency_injection/test_http_handler_dependency_injection.py
diff --git a/tests/dependency_injection/test_injection_of_classes.py b/tests/e2e/test_dependency_injection/test_injection_of_classes.py
similarity index 100%
rename from tests/dependency_injection/test_injection_of_classes.py
rename to tests/e2e/test_dependency_injection/test_injection_of_classes.py
diff --git a/tests/dependency_injection/test_injection_of_generic_models.py b/tests/e2e/test_dependency_injection/test_injection_of_generic_models.py
similarity index 100%
rename from tests/dependency_injection/test_injection_of_generic_models.py
rename to tests/e2e/test_dependency_injection/test_injection_of_generic_models.py
diff --git a/tests/dependency_injection/test_inter_dependencies.py b/tests/e2e/test_dependency_injection/test_inter_dependencies.py
similarity index 100%
rename from tests/dependency_injection/test_inter_dependencies.py
rename to tests/e2e/test_dependency_injection/test_inter_dependencies.py
diff --git a/tests/dependency_injection/test_request_local_caching.py b/tests/e2e/test_dependency_injection/test_request_local_caching.py
similarity index 100%
rename from tests/dependency_injection/test_request_local_caching.py
rename to tests/e2e/test_dependency_injection/test_request_local_caching.py
diff --git a/tests/dependency_injection/test_websocket_handler_dependency_injection.py b/tests/e2e/test_dependency_injection/test_websocket_handler_dependency_injection.py
similarity index 100%
rename from tests/dependency_injection/test_websocket_handler_dependency_injection.py
rename to tests/e2e/test_dependency_injection/test_websocket_handler_dependency_injection.py
diff --git a/tests/test_exception_handlers.py b/tests/e2e/test_exception_handlers.py
similarity index 100%
rename from tests/test_exception_handlers.py
rename to tests/e2e/test_exception_handlers.py
diff --git a/docs/examples/tests/application_state/__init__.py b/tests/e2e/test_life_cycle_hooks/__init__.py
similarity index 100%
rename from docs/examples/tests/application_state/__init__.py
rename to tests/e2e/test_life_cycle_hooks/__init__.py
diff --git a/tests/life_cycle_hooks/test_after_request.py b/tests/e2e/test_life_cycle_hooks/test_after_request.py
similarity index 100%
rename from tests/life_cycle_hooks/test_after_request.py
rename to tests/e2e/test_life_cycle_hooks/test_after_request.py
diff --git a/tests/life_cycle_hooks/test_after_response.py b/tests/e2e/test_life_cycle_hooks/test_after_response.py
similarity index 100%
rename from tests/life_cycle_hooks/test_after_response.py
rename to tests/e2e/test_life_cycle_hooks/test_after_response.py
diff --git a/tests/life_cycle_hooks/test_before_request.py b/tests/e2e/test_life_cycle_hooks/test_before_request.py
similarity index 100%
rename from tests/life_cycle_hooks/test_before_request.py
rename to tests/e2e/test_life_cycle_hooks/test_before_request.py
diff --git a/tests/test_option_requests.py b/tests/e2e/test_option_requests.py
similarity index 100%
rename from tests/test_option_requests.py
rename to tests/e2e/test_option_requests.py
diff --git a/tests/test_response_caching.py b/tests/e2e/test_response_caching.py
similarity index 100%
rename from tests/test_response_caching.py
rename to tests/e2e/test_response_caching.py
diff --git a/tests/test_router_registration.py b/tests/e2e/test_router_registration.py
similarity index 100%
rename from tests/test_router_registration.py
rename to tests/e2e/test_router_registration.py
diff --git a/docs/examples/tests/contrib/__init__.py b/tests/e2e/test_routing/__init__.py
similarity index 100%
rename from docs/examples/tests/contrib/__init__.py
rename to tests/e2e/test_routing/__init__.py
diff --git a/tests/routing/test_asset_url_path.py b/tests/e2e/test_routing/test_asset_url_path.py
similarity index 100%
rename from tests/routing/test_asset_url_path.py
rename to tests/e2e/test_routing/test_asset_url_path.py
diff --git a/tests/routing/test_path_mounting.py b/tests/e2e/test_routing/test_path_mounting.py
similarity index 100%
rename from tests/routing/test_path_mounting.py
rename to tests/e2e/test_routing/test_path_mounting.py
diff --git a/tests/routing/test_path_resolution.py b/tests/e2e/test_routing/test_path_resolution.py
similarity index 93%
rename from tests/routing/test_path_resolution.py
rename to tests/e2e/test_routing/test_path_resolution.py
--- a/tests/routing/test_path_resolution.py
+++ b/tests/e2e/test_routing/test_path_resolution.py
@@ -255,3 +255,21 @@ def upper_handler(string_param: str, parth_param: Path) -> str:
response = client.get("/abc/a/b/c")
assert response.status_code == HTTP_200_OK
+
+
+def test_root_path_param_resolution() -> None:
+ # https://github.com/litestar-org/litestar/issues/1830
+ @get("/{name:str}")
+ async def hello_world(name: str) -> str:
+ return f"Hello, {name}!"
+
+ with create_test_client(hello_world) as client:
+ response = client.get("/jon")
+ assert response.status_code == HTTP_200_OK
+ assert response.text == "Hello, jon!"
+
+ response = client.get("/jon/bon")
+ assert response.status_code == HTTP_404_NOT_FOUND
+
+ response = client.get("/jon/bon/jovi")
+ assert response.status_code == HTTP_404_NOT_FOUND
diff --git a/tests/routing/test_route_indexing.py b/tests/e2e/test_routing/test_route_indexing.py
similarity index 100%
rename from tests/routing/test_route_indexing.py
rename to tests/e2e/test_routing/test_route_indexing.py
diff --git a/tests/routing/test_route_reverse.py b/tests/e2e/test_routing/test_route_reverse.py
similarity index 100%
rename from tests/routing/test_route_reverse.py
rename to tests/e2e/test_routing/test_route_reverse.py
diff --git a/tests/routing/test_validations.py b/tests/e2e/test_routing/test_validations.py
similarity index 100%
rename from tests/routing/test_validations.py
rename to tests/e2e/test_routing/test_validations.py
diff --git a/tests/compatibility/test_starlette_responses.py b/tests/e2e/test_starlette_responses.py
similarity index 100%
rename from tests/compatibility/test_starlette_responses.py
rename to tests/e2e/test_starlette_responses.py
diff --git a/docs/examples/tests/contrib/jwt/__init__.py b/tests/examples/__init__.py
similarity index 100%
rename from docs/examples/tests/contrib/jwt/__init__.py
rename to tests/examples/__init__.py
diff --git a/tests/examples/conftest.py b/tests/examples/conftest.py
new file mode 100644
--- /dev/null
+++ b/tests/examples/conftest.py
@@ -0,0 +1,14 @@
+import logging
+from typing import Generator
+
+import pytest
+
+
[email protected](autouse=True)
+def disable_httpx_logging() -> Generator[None, None, None]:
+ # ensure that httpx logging is not interfering with our test client
+ httpx_logger = logging.getLogger("httpx")
+ initial_level = httpx_logger.level
+ httpx_logger.setLevel(logging.WARNING)
+ yield
+ httpx_logger.setLevel(initial_level)
diff --git a/docs/examples/tests/contrib/sqlalchemy/__init__.py b/tests/examples/test_application_hooks/__init__.py
similarity index 100%
rename from docs/examples/tests/contrib/sqlalchemy/__init__.py
rename to tests/examples/test_application_hooks/__init__.py
diff --git a/docs/examples/tests/application_hooks/test_application_after_exception_hook.py b/tests/examples/test_application_hooks/test_application_after_exception_hook.py
similarity index 91%
rename from docs/examples/tests/application_hooks/test_application_after_exception_hook.py
rename to tests/examples/test_application_hooks/test_application_after_exception_hook.py
--- a/docs/examples/tests/application_hooks/test_application_after_exception_hook.py
+++ b/tests/examples/test_application_hooks/test_application_after_exception_hook.py
@@ -2,8 +2,8 @@
from typing import TYPE_CHECKING
import pytest
+from docs.examples.application_hooks import after_exception_hook
-from examples.application_hooks import after_exception_hook
from litestar.testing import TestClient
if TYPE_CHECKING:
diff --git a/docs/examples/tests/application_hooks/test_application_before_send.py b/tests/examples/test_application_hooks/test_application_before_send.py
similarity index 85%
rename from docs/examples/tests/application_hooks/test_application_before_send.py
rename to tests/examples/test_application_hooks/test_application_before_send.py
--- a/docs/examples/tests/application_hooks/test_application_before_send.py
+++ b/tests/examples/test_application_hooks/test_application_before_send.py
@@ -1,4 +1,5 @@
-from examples.application_hooks import before_send_hook
+from docs.examples.application_hooks import before_send_hook
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/application_hooks/test_lifespan_manager.py b/tests/examples/test_application_hooks/test_lifespan_manager.py
similarity index 78%
rename from docs/examples/tests/application_hooks/test_lifespan_manager.py
rename to tests/examples/test_application_hooks/test_lifespan_manager.py
--- a/docs/examples/tests/application_hooks/test_lifespan_manager.py
+++ b/tests/examples/test_application_hooks/test_lifespan_manager.py
@@ -1,8 +1,8 @@
from unittest.mock import AsyncMock
+from docs.examples.application_hooks.lifespan_manager import app
from pytest_mock import MockerFixture
-from examples.application_hooks.lifespan_manager import app
from litestar import get
from litestar.datastructures import State
from litestar.testing import TestClient
@@ -13,7 +13,7 @@ class FakeAsyncEngine:
async def test_startup_and_shutdown_example(mocker: MockerFixture) -> None:
- mock_create_engine = mocker.patch("examples.application_hooks.lifespan_manager.create_async_engine")
+ mock_create_engine = mocker.patch("docs.examples.application_hooks.lifespan_manager.create_async_engine")
mock_create_engine.return_value = FakeAsyncEngine
@get("/")
diff --git a/docs/examples/tests/application_hooks/test_on_app_init.py b/tests/examples/test_application_hooks/test_on_app_init.py
similarity index 50%
rename from docs/examples/tests/application_hooks/test_on_app_init.py
rename to tests/examples/test_application_hooks/test_on_app_init.py
--- a/docs/examples/tests/application_hooks/test_on_app_init.py
+++ b/tests/examples/test_application_hooks/test_on_app_init.py
@@ -1,4 +1,4 @@
-from examples.application_hooks.on_app_init import app, close_db_connection
+from docs.examples.application_hooks.on_app_init import app, close_db_connection
def test_on_app_init() -> None:
diff --git a/docs/examples/tests/contrib/sqlalchemy/plugins/__init__.py b/tests/examples/test_application_state/__init__.py
similarity index 100%
rename from docs/examples/tests/contrib/sqlalchemy/plugins/__init__.py
rename to tests/examples/test_application_state/__init__.py
diff --git a/docs/examples/tests/application_state/test_passing_initial_state.py b/tests/examples/test_application_state/test_passing_initial_state.py
similarity index 81%
rename from docs/examples/tests/application_state/test_passing_initial_state.py
rename to tests/examples/test_application_state/test_passing_initial_state.py
--- a/docs/examples/tests/application_state/test_passing_initial_state.py
+++ b/tests/examples/test_application_state/test_passing_initial_state.py
@@ -1,4 +1,5 @@
-from examples.application_state.passing_initial_state import app
+from docs.examples.application_state.passing_initial_state import app
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/application_state/test_using_application_state.py b/tests/examples/test_application_state/test_using_application_state.py
similarity index 74%
rename from docs/examples/tests/application_state/test_using_application_state.py
rename to tests/examples/test_application_state/test_using_application_state.py
--- a/docs/examples/tests/application_state/test_using_application_state.py
+++ b/tests/examples/test_application_state/test_using_application_state.py
@@ -2,15 +2,17 @@
from typing import Any
import pytest
+from docs.examples.application_state.using_application_state import app
-from examples.application_state.using_application_state import app
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
@pytest.mark.usefixtures("reset_httpx_logging")
def test_using_application_state(caplog: Any) -> None:
- with caplog.at_level(INFO, "examples.application_state.using_application_state"), TestClient(app=app) as client:
+ with caplog.at_level(INFO, "docs.examples.application_state.using_application_state"), TestClient(
+ app=app
+ ) as client:
response = client.get("/")
assert response.status_code == HTTP_200_OK
diff --git a/docs/examples/tests/application_state/test_using_custom_state.py b/tests/examples/test_application_state/test_using_custom_state.py
similarity index 81%
rename from docs/examples/tests/application_state/test_using_custom_state.py
rename to tests/examples/test_application_state/test_using_custom_state.py
--- a/docs/examples/tests/application_state/test_using_custom_state.py
+++ b/tests/examples/test_application_state/test_using_custom_state.py
@@ -1,4 +1,5 @@
-from examples.application_state.using_custom_state import app
+from docs.examples.application_state.using_custom_state import app
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/application_state/test_using_immutable_state.py b/tests/examples/test_application_state/test_using_immutable_state.py
similarity index 80%
rename from docs/examples/tests/application_state/test_using_immutable_state.py
rename to tests/examples/test_application_state/test_using_immutable_state.py
--- a/docs/examples/tests/application_state/test_using_immutable_state.py
+++ b/tests/examples/test_application_state/test_using_immutable_state.py
@@ -1,4 +1,5 @@
-from examples.application_state.using_immutable_state import app
+from docs.examples.application_state.using_immutable_state import app
+
from litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
from litestar.testing import TestClient
diff --git a/docs/examples/tests/datastructures/headers/test_cache_control.py b/tests/examples/test_cache_control_headers.py
similarity index 89%
rename from docs/examples/tests/datastructures/headers/test_cache_control.py
rename to tests/examples/test_cache_control_headers.py
--- a/docs/examples/tests/datastructures/headers/test_cache_control.py
+++ b/tests/examples/test_cache_control_headers.py
@@ -1,4 +1,5 @@
-from examples.datastructures.headers import cache_control
+from docs.examples.datastructures.headers import cache_control
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/data_transfer_objects/__init__.py b/tests/examples/test_contrib/__init__.py
similarity index 100%
rename from docs/examples/tests/data_transfer_objects/__init__.py
rename to tests/examples/test_contrib/__init__.py
diff --git a/docs/examples/tests/data_transfer_objects/factory/__init__.py b/tests/examples/test_contrib/test_jwt/__init__.py
similarity index 100%
rename from docs/examples/tests/data_transfer_objects/factory/__init__.py
rename to tests/examples/test_contrib/test_jwt/__init__.py
diff --git a/docs/examples/tests/contrib/jwt/test_using_jwt_auth.py b/tests/examples/test_contrib/test_jwt/test_using_jwt_auth.py
similarity index 92%
rename from docs/examples/tests/contrib/jwt/test_using_jwt_auth.py
rename to tests/examples/test_contrib/test_jwt/test_using_jwt_auth.py
--- a/docs/examples/tests/contrib/jwt/test_using_jwt_auth.py
+++ b/tests/examples/test_contrib/test_jwt/test_using_jwt_auth.py
@@ -1,6 +1,7 @@
from uuid import uuid4
-from examples.contrib.jwt.using_jwt_auth import app
+from docs.examples.contrib.jwt.using_jwt_auth import app
+
from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_401_UNAUTHORIZED
from litestar.testing import TestClient
diff --git a/docs/examples/tests/contrib/jwt/test_using_jwt_cookie_auth.py b/tests/examples/test_contrib/test_jwt/test_using_jwt_cookie_auth.py
similarity index 90%
rename from docs/examples/tests/contrib/jwt/test_using_jwt_cookie_auth.py
rename to tests/examples/test_contrib/test_jwt/test_using_jwt_cookie_auth.py
--- a/docs/examples/tests/contrib/jwt/test_using_jwt_cookie_auth.py
+++ b/tests/examples/test_contrib/test_jwt/test_using_jwt_cookie_auth.py
@@ -1,6 +1,7 @@
from uuid import uuid4
-from examples.contrib.jwt.using_jwt_cookie_auth import app
+from docs.examples.contrib.jwt.using_jwt_cookie_auth import app
+
from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_401_UNAUTHORIZED
from litestar.testing import TestClient
diff --git a/docs/examples/tests/contrib/jwt/test_using_oauth2_password_bearer.py b/tests/examples/test_contrib/test_jwt/test_using_oauth2_password_bearer.py
similarity index 88%
rename from docs/examples/tests/contrib/jwt/test_using_oauth2_password_bearer.py
rename to tests/examples/test_contrib/test_jwt/test_using_oauth2_password_bearer.py
--- a/docs/examples/tests/contrib/jwt/test_using_oauth2_password_bearer.py
+++ b/tests/examples/test_contrib/test_jwt/test_using_oauth2_password_bearer.py
@@ -1,6 +1,7 @@
from uuid import uuid4
-from examples.contrib.jwt.using_oauth2_password_bearer import app
+from docs.examples.contrib.jwt.using_oauth2_password_bearer import app
+
from litestar.status_codes import HTTP_201_CREATED, HTTP_401_UNAUTHORIZED
from litestar.testing import TestClient
diff --git a/docs/examples/tests/datastructures/__init__.py b/tests/examples/test_contrib/test_sqlalchemy/__init__.py
similarity index 100%
rename from docs/examples/tests/datastructures/__init__.py
rename to tests/examples/test_contrib/test_sqlalchemy/__init__.py
diff --git a/docs/examples/tests/datastructures/headers/__init__.py b/tests/examples/test_contrib/test_sqlalchemy/plugins/__init__.py
similarity index 100%
rename from docs/examples/tests/datastructures/headers/__init__.py
rename to tests/examples/test_contrib/test_sqlalchemy/plugins/__init__.py
diff --git a/docs/examples/tests/contrib/sqlalchemy/plugins/test_example_apps.py b/tests/examples/test_contrib/test_sqlalchemy/plugins/test_example_apps.py
similarity index 100%
rename from docs/examples/tests/contrib/sqlalchemy/plugins/test_example_apps.py
rename to tests/examples/test_contrib/test_sqlalchemy/plugins/test_example_apps.py
diff --git a/docs/examples/tests/contrib/sqlalchemy/plugins/test_tutorial_example_apps.py b/tests/examples/test_contrib/test_sqlalchemy/plugins/test_tutorial_example_apps.py
similarity index 100%
rename from docs/examples/tests/contrib/sqlalchemy/plugins/test_tutorial_example_apps.py
rename to tests/examples/test_contrib/test_sqlalchemy/plugins/test_tutorial_example_apps.py
diff --git a/docs/examples/tests/dependency_injection/__init__.py b/tests/examples/test_dependency_injection/__init__.py
similarity index 100%
rename from docs/examples/tests/dependency_injection/__init__.py
rename to tests/examples/test_dependency_injection/__init__.py
diff --git a/docs/examples/tests/dependency_injection/test_dependency_default_value_no_dependency_fn.py b/tests/examples/test_dependency_injection/test_dependency_default_value_no_dependency_fn.py
similarity index 81%
rename from docs/examples/tests/dependency_injection/test_dependency_default_value_no_dependency_fn.py
rename to tests/examples/test_dependency_injection/test_dependency_default_value_no_dependency_fn.py
--- a/docs/examples/tests/dependency_injection/test_dependency_default_value_no_dependency_fn.py
+++ b/tests/examples/test_dependency_injection/test_dependency_default_value_no_dependency_fn.py
@@ -1,4 +1,5 @@
-from examples.dependency_injection import dependency_default_value_no_dependency_fn
+from docs.examples.dependency_injection import dependency_default_value_no_dependency_fn
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/dependency_injection/test_dependency_default_value_with_dependency_fn.py b/tests/examples/test_dependency_injection/test_dependency_default_value_with_dependency_fn.py
similarity index 80%
rename from docs/examples/tests/dependency_injection/test_dependency_default_value_with_dependency_fn.py
rename to tests/examples/test_dependency_injection/test_dependency_default_value_with_dependency_fn.py
--- a/docs/examples/tests/dependency_injection/test_dependency_default_value_with_dependency_fn.py
+++ b/tests/examples/test_dependency_injection/test_dependency_default_value_with_dependency_fn.py
@@ -1,4 +1,5 @@
-from examples.dependency_injection import dependency_default_value_with_dependency_fn
+from docs.examples.dependency_injection import dependency_default_value_with_dependency_fn
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/dependency_injection/test_dependency_skip_validation.py b/tests/examples/test_dependency_injection/test_dependency_skip_validation.py
similarity index 78%
rename from docs/examples/tests/dependency_injection/test_dependency_skip_validation.py
rename to tests/examples/test_dependency_injection/test_dependency_skip_validation.py
--- a/docs/examples/tests/dependency_injection/test_dependency_skip_validation.py
+++ b/tests/examples/test_dependency_injection/test_dependency_skip_validation.py
@@ -1,4 +1,5 @@
-from examples.dependency_injection import dependency_skip_validation
+from docs.examples.dependency_injection import dependency_skip_validation
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/dependency_injection/test_dependency_validation_error.py b/tests/examples/test_dependency_injection/test_dependency_validation_error.py
similarity index 80%
rename from docs/examples/tests/dependency_injection/test_dependency_validation_error.py
rename to tests/examples/test_dependency_injection/test_dependency_validation_error.py
--- a/docs/examples/tests/dependency_injection/test_dependency_validation_error.py
+++ b/tests/examples/test_dependency_injection/test_dependency_validation_error.py
@@ -1,4 +1,5 @@
-from examples.dependency_injection import dependency_validation_error
+from docs.examples.dependency_injection import dependency_validation_error
+
from litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
from litestar.testing import TestClient
diff --git a/docs/examples/tests/dependency_injection/tests_dependency_non_optional_not_provided.py b/tests/examples/test_dependency_injection/tests_dependency_non_optional_not_provided.py
similarity index 78%
rename from docs/examples/tests/dependency_injection/tests_dependency_non_optional_not_provided.py
rename to tests/examples/test_dependency_injection/tests_dependency_non_optional_not_provided.py
--- a/docs/examples/tests/dependency_injection/tests_dependency_non_optional_not_provided.py
+++ b/tests/examples/test_dependency_injection/tests_dependency_non_optional_not_provided.py
@@ -1,6 +1,6 @@
import pytest
+from docs.examples.dependency_injection import dependency_non_optional_not_provided
-from examples.dependency_injection import dependency_non_optional_not_provided
from litestar import Litestar
from litestar.exceptions import ImproperlyConfiguredException
diff --git a/docs/examples/tests/middleware/__init__.py b/tests/examples/test_dto/__init__.py
similarity index 100%
rename from docs/examples/tests/middleware/__init__.py
rename to tests/examples/test_dto/__init__.py
diff --git a/docs/examples/tests/data_transfer_objects/factory/test_example_apps.py b/tests/examples/test_dto/test_example_apps.py
similarity index 100%
rename from docs/examples/tests/data_transfer_objects/factory/test_example_apps.py
rename to tests/examples/test_dto/test_example_apps.py
diff --git a/docs/examples/tests/data_transfer_objects/factory/test_tutorial.py b/tests/examples/test_dto/test_tutorial.py
similarity index 100%
rename from docs/examples/tests/data_transfer_objects/factory/test_tutorial.py
rename to tests/examples/test_dto/test_tutorial.py
diff --git a/docs/examples/tests/test_exceptions.py b/tests/examples/test_exceptions.py
similarity index 97%
rename from docs/examples/tests/test_exceptions.py
rename to tests/examples/test_exceptions.py
--- a/docs/examples/tests/test_exceptions.py
+++ b/tests/examples/test_exceptions.py
@@ -1,8 +1,9 @@
-from examples.exceptions import (
+from docs.examples.exceptions import (
layered_handlers,
override_default_handler,
per_exception_handlers,
)
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/test_hello_world.py b/tests/examples/test_hello_world.py
similarity index 88%
rename from docs/examples/tests/test_hello_world.py
rename to tests/examples/test_hello_world.py
--- a/docs/examples/tests/test_hello_world.py
+++ b/tests/examples/test_hello_world.py
@@ -1,4 +1,5 @@
-from examples import hello_world
+from docs.examples import hello_world
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/test_lifecycle_hooks.py b/tests/examples/test_lifecycle_hooks.py
similarity index 81%
rename from docs/examples/tests/test_lifecycle_hooks.py
rename to tests/examples/test_lifecycle_hooks.py
--- a/docs/examples/tests/test_lifecycle_hooks.py
+++ b/tests/examples/test_lifecycle_hooks.py
@@ -1,7 +1,8 @@
-from examples.lifecycle_hooks.after_request import app as after_request_app
-from examples.lifecycle_hooks.after_response import app as after_response_app
-from examples.lifecycle_hooks.before_request import app as before_request_app
-from examples.lifecycle_hooks.layered_hooks import app as layered_hooks_app
+from docs.examples.lifecycle_hooks.after_request import app as after_request_app
+from docs.examples.lifecycle_hooks.after_response import app as after_response_app
+from docs.examples.lifecycle_hooks.before_request import app as before_request_app
+from docs.examples.lifecycle_hooks.layered_hooks import app as layered_hooks_app
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/openapi/__init__.py b/tests/examples/test_middleware/__init__.py
similarity index 100%
rename from docs/examples/tests/openapi/__init__.py
rename to tests/examples/test_middleware/__init__.py
diff --git a/docs/examples/tests/middleware/test_abstract_middleware.py b/tests/examples/test_middleware/test_abstract_middleware.py
similarity index 95%
rename from docs/examples/tests/middleware/test_abstract_middleware.py
rename to tests/examples/test_middleware/test_abstract_middleware.py
--- a/docs/examples/tests/middleware/test_abstract_middleware.py
+++ b/tests/examples/test_middleware/test_abstract_middleware.py
@@ -1,4 +1,5 @@
-from examples.middleware.base import app
+from docs.examples.middleware.base import app
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/middleware/test_call_order.py b/tests/examples/test_middleware/test_call_order.py
similarity index 83%
rename from docs/examples/tests/middleware/test_call_order.py
rename to tests/examples/test_middleware/test_call_order.py
--- a/docs/examples/tests/middleware/test_call_order.py
+++ b/tests/examples/test_middleware/test_call_order.py
@@ -1,4 +1,5 @@
-from examples.middleware.call_order import app
+from docs.examples.middleware.call_order import app
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/middleware/test_logging_middleware.py b/tests/examples/test_middleware/test_logging_middleware.py
similarity index 56%
rename from docs/examples/tests/middleware/test_logging_middleware.py
rename to tests/examples/test_middleware/test_logging_middleware.py
--- a/docs/examples/tests/middleware/test_logging_middleware.py
+++ b/tests/examples/test_middleware/test_logging_middleware.py
@@ -8,21 +8,9 @@
from litestar.types.callable_types import GetLogger
-from examples.middleware.logging_middleware import app
-from litestar.logging.config import LoggingConfig, default_handlers
-from litestar.testing import TestClient
-
+from docs.examples.middleware.logging_middleware import app
[email protected]
-def get_logger() -> "GetLogger":
- # due to the limitations of caplog we have to place this call here.
- # we also have to allow propagation.
- return LoggingConfig(
- handlers=default_handlers,
- loggers={
- "litestar": {"level": "INFO", "handlers": ["queue_listener"], "propagate": True},
- },
- ).configure()
+from litestar.testing import TestClient
@pytest.mark.usefixtures("reset_httpx_logging")
diff --git a/docs/examples/tests/middleware/test_rate_limit_middleware.py b/tests/examples/test_middleware/test_rate_limit_middleware.py
similarity index 89%
rename from docs/examples/tests/middleware/test_rate_limit_middleware.py
rename to tests/examples/test_middleware/test_rate_limit_middleware.py
--- a/docs/examples/tests/middleware/test_rate_limit_middleware.py
+++ b/tests/examples/test_middleware/test_rate_limit_middleware.py
@@ -1,4 +1,5 @@
-from examples.middleware.rate_limit import app
+from docs.examples.middleware.rate_limit import app
+
from litestar.status_codes import HTTP_200_OK, HTTP_429_TOO_MANY_REQUESTS
from litestar.testing import TestClient
diff --git a/docs/examples/tests/middleware/test_session_middleware.py b/tests/examples/test_middleware/test_session_middleware.py
similarity index 92%
rename from docs/examples/tests/middleware/test_session_middleware.py
rename to tests/examples/test_middleware/test_session_middleware.py
--- a/docs/examples/tests/middleware/test_session_middleware.py
+++ b/tests/examples/test_middleware/test_session_middleware.py
@@ -1,4 +1,5 @@
-from examples.middleware.session.cookies_full_example import app
+from docs.examples.middleware.session.cookies_full_example import app
+
from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT
from litestar.testing import TestClient
diff --git a/docs/examples/tests/openapi/test_customize_pydantic_model_name.py b/tests/examples/test_openapi.py
similarity index 95%
rename from docs/examples/tests/openapi/test_customize_pydantic_model_name.py
rename to tests/examples/test_openapi.py
--- a/docs/examples/tests/openapi/test_customize_pydantic_model_name.py
+++ b/tests/examples/test_openapi.py
@@ -1,4 +1,5 @@
-from examples.openapi import customize_pydantic_model_name
+from docs.examples.openapi import customize_pydantic_model_name
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/pagination/__init__.py b/tests/examples/test_pagination/__init__.py
similarity index 100%
rename from docs/examples/tests/pagination/__init__.py
rename to tests/examples/test_pagination/__init__.py
diff --git a/docs/examples/tests/pagination/test_using_classic_pagination.py b/tests/examples/test_pagination/test_using_classic_pagination.py
similarity index 88%
rename from docs/examples/tests/pagination/test_using_classic_pagination.py
rename to tests/examples/test_pagination/test_using_classic_pagination.py
--- a/docs/examples/tests/pagination/test_using_classic_pagination.py
+++ b/tests/examples/test_pagination/test_using_classic_pagination.py
@@ -1,4 +1,5 @@
-from examples.pagination.using_classic_pagination import app
+from docs.examples.pagination.using_classic_pagination import app
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/pagination/test_using_cursor_pagination.py b/tests/examples/test_pagination/test_using_cursor_pagination.py
similarity index 88%
rename from docs/examples/tests/pagination/test_using_cursor_pagination.py
rename to tests/examples/test_pagination/test_using_cursor_pagination.py
--- a/docs/examples/tests/pagination/test_using_cursor_pagination.py
+++ b/tests/examples/test_pagination/test_using_cursor_pagination.py
@@ -1,4 +1,5 @@
-from examples.pagination.using_cursor_pagination import app
+from docs.examples.pagination.using_cursor_pagination import app
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/pagination/test_using_offset_pagination.py b/tests/examples/test_pagination/test_using_offset_pagination.py
similarity index 88%
rename from docs/examples/tests/pagination/test_using_offset_pagination.py
rename to tests/examples/test_pagination/test_using_offset_pagination.py
--- a/docs/examples/tests/pagination/test_using_offset_pagination.py
+++ b/tests/examples/test_pagination/test_using_offset_pagination.py
@@ -1,4 +1,5 @@
-from examples.pagination.using_offset_pagination import app
+from docs.examples.pagination.using_offset_pagination import app
+
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/parameters/__init__.py b/tests/examples/test_parameters/__init__.py
similarity index 100%
rename from docs/examples/tests/parameters/__init__.py
rename to tests/examples/test_parameters/__init__.py
diff --git a/docs/examples/tests/parameters/test_header_and_cookies_parameters.py b/tests/examples/test_parameters/test_header_and_cookies_parameters.py
similarity index 91%
rename from docs/examples/tests/parameters/test_header_and_cookies_parameters.py
rename to tests/examples/test_parameters/test_header_and_cookies_parameters.py
--- a/docs/examples/tests/parameters/test_header_and_cookies_parameters.py
+++ b/tests/examples/test_parameters/test_header_and_cookies_parameters.py
@@ -1,4 +1,5 @@
-from examples.parameters.header_and_cookie_parameters import app
+from docs.examples.parameters.header_and_cookie_parameters import app
+
from litestar.status_codes import (
HTTP_200_OK,
HTTP_400_BAD_REQUEST,
diff --git a/docs/examples/tests/parameters/test_layered_parameters.py b/tests/examples/test_parameters/test_layered_parameters.py
similarity index 96%
rename from docs/examples/tests/parameters/test_layered_parameters.py
rename to tests/examples/test_parameters/test_layered_parameters.py
--- a/docs/examples/tests/parameters/test_layered_parameters.py
+++ b/tests/examples/test_parameters/test_layered_parameters.py
@@ -1,8 +1,8 @@
from typing import Any, Dict
import pytest
+from docs.examples.parameters.layered_parameters import app
-from examples.parameters.layered_parameters import app
from litestar.testing import TestClient
diff --git a/docs/examples/tests/parameters/test_path_parameters.py b/tests/examples/test_parameters/test_path_parameters.py
similarity index 80%
rename from docs/examples/tests/parameters/test_path_parameters.py
rename to tests/examples/test_parameters/test_path_parameters.py
--- a/docs/examples/tests/parameters/test_path_parameters.py
+++ b/tests/examples/test_parameters/test_path_parameters.py
@@ -1,6 +1,7 @@
-from examples.parameters.path_parameters_1 import app
-from examples.parameters.path_parameters_2 import app as app_2
-from examples.parameters.path_parameters_3 import app as app_3
+from docs.examples.parameters.path_parameters_1 import app
+from docs.examples.parameters.path_parameters_2 import app as app_2
+from docs.examples.parameters.path_parameters_3 import app as app_3
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/parameters/test_query_parameters.py b/tests/examples/test_parameters/test_query_parameters.py
similarity index 79%
rename from docs/examples/tests/parameters/test_query_parameters.py
rename to tests/examples/test_parameters/test_query_parameters.py
--- a/docs/examples/tests/parameters/test_query_parameters.py
+++ b/tests/examples/test_parameters/test_query_parameters.py
@@ -1,11 +1,12 @@
-from examples.parameters.query_params import app as query_params_app
-from examples.parameters.query_params_constraints import (
+from docs.examples.parameters.query_params import app as query_params_app
+from docs.examples.parameters.query_params_constraints import (
app as query_params_constraints_app,
)
-from examples.parameters.query_params_default import app as query_params_default_app
-from examples.parameters.query_params_optional import app as query_params_optional_app
-from examples.parameters.query_params_remap import app as query_params_remap_app
-from examples.parameters.query_params_types import app as query_params_types_app
+from docs.examples.parameters.query_params_default import app as query_params_default_app
+from docs.examples.parameters.query_params_optional import app as query_params_optional_app
+from docs.examples.parameters.query_params_remap import app as query_params_remap_app
+from docs.examples.parameters.query_params_types import app as query_params_types_app
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/plugins/__init__.py b/tests/examples/test_plugins/__init__.py
similarity index 100%
rename from docs/examples/tests/plugins/__init__.py
rename to tests/examples/test_plugins/__init__.py
diff --git a/docs/examples/tests/plugins/test_example_apps.py b/tests/examples/test_plugins/test_example_apps.py
similarity index 100%
rename from docs/examples/tests/plugins/test_example_apps.py
rename to tests/examples/test_plugins/test_example_apps.py
diff --git a/docs/examples/tests/plugins/test_sqlalchemy_init_plugin.py b/tests/examples/test_plugins/test_sqlalchemy_init_plugin.py
similarity index 69%
rename from docs/examples/tests/plugins/test_sqlalchemy_init_plugin.py
rename to tests/examples/test_plugins/test_sqlalchemy_init_plugin.py
--- a/docs/examples/tests/plugins/test_sqlalchemy_init_plugin.py
+++ b/tests/examples/test_plugins/test_sqlalchemy_init_plugin.py
@@ -3,9 +3,9 @@
from typing import TYPE_CHECKING
import pytest
+from docs.examples.plugins.sqlalchemy_init_plugin.sqlalchemy_async import app as async_sqla_app
+from docs.examples.plugins.sqlalchemy_init_plugin.sqlalchemy_sync import app as sync_sqla_app
-from examples.plugins.sqlalchemy_init_plugin.sqlalchemy_async import app as async_sqla_app
-from examples.plugins.sqlalchemy_init_plugin.sqlalchemy_sync import app as sync_sqla_app
from litestar.testing import TestClient
if TYPE_CHECKING:
diff --git a/docs/examples/tests/request_data/test_request_data.py b/tests/examples/test_request_data.py
similarity index 73%
rename from docs/examples/tests/request_data/test_request_data.py
rename to tests/examples/test_request_data.py
--- a/docs/examples/tests/request_data/test_request_data.py
+++ b/tests/examples/test_request_data.py
@@ -1,13 +1,16 @@
-from examples.request_data.request_data_1 import app
-from examples.request_data.request_data_2 import app as app_2
-from examples.request_data.request_data_3 import app as app_3
-from examples.request_data.request_data_4 import app as app_4
-from examples.request_data.request_data_5 import app as app_5
-from examples.request_data.request_data_6 import app as app_6
-from examples.request_data.request_data_7 import app as app_7
-from examples.request_data.request_data_8 import app as app_8
-from examples.request_data.request_data_9 import app as app_9
-from examples.request_data.request_data_10 import app as app_10
+from docs.examples.request_data.msgpack_request import app as msgpack_app
+from docs.examples.request_data.request_data_1 import app
+from docs.examples.request_data.request_data_2 import app as app_2
+from docs.examples.request_data.request_data_3 import app as app_3
+from docs.examples.request_data.request_data_4 import app as app_4
+from docs.examples.request_data.request_data_5 import app as app_5
+from docs.examples.request_data.request_data_6 import app as app_6
+from docs.examples.request_data.request_data_7 import app as app_7
+from docs.examples.request_data.request_data_8 import app as app_8
+from docs.examples.request_data.request_data_9 import app as app_9
+from docs.examples.request_data.request_data_10 import app as app_10
+
+from litestar.serialization import encode_msgpack
from litestar.testing import TestClient
@@ -86,3 +89,11 @@ def test_request_data_10() -> None:
res = client.post("/", files={"foo": ("foo.txt", b"hello"), "bar": ("bar.txt", b"world")})
assert res.status_code == 201
assert res.json() == {"foo.txt": "hello", "bar.txt": "world"}
+
+
+def test_msgpack_app() -> None:
+ test_data = {"name": "Moishe Zuchmir", "age": 30, "programmer": True}
+
+ with TestClient(app=msgpack_app) as client:
+ response = client.post("/", content=encode_msgpack(test_data))
+ assert response.json() == test_data
diff --git a/docs/examples/tests/responses/__init__.py b/tests/examples/test_responses/__init__.py
similarity index 100%
rename from docs/examples/tests/responses/__init__.py
rename to tests/examples/test_responses/__init__.py
diff --git a/docs/examples/tests/responses/test_background_tasks.py b/tests/examples/test_responses/test_background_tasks.py
similarity index 82%
rename from docs/examples/tests/responses/test_background_tasks.py
rename to tests/examples/test_responses/test_background_tasks.py
--- a/docs/examples/tests/responses/test_background_tasks.py
+++ b/tests/examples/test_responses/test_background_tasks.py
@@ -2,11 +2,11 @@
from typing import TYPE_CHECKING
import pytest
+from docs.examples.responses.background_tasks_1 import app as app_1
+from docs.examples.responses.background_tasks_2 import app as app_2
+from docs.examples.responses.background_tasks_3 import app as app_3
+from docs.examples.responses.background_tasks_3 import greeted as greeted_3
-from examples.responses.background_tasks_1 import app as app_1
-from examples.responses.background_tasks_2 import app as app_2
-from examples.responses.background_tasks_3 import app as app_3
-from examples.responses.background_tasks_3 import greeted as greeted_3
from litestar.testing import TestClient
if TYPE_CHECKING:
diff --git a/docs/examples/tests/responses/test_custom_responses.py b/tests/examples/test_responses/test_custom_responses.py
similarity index 78%
rename from docs/examples/tests/responses/test_custom_responses.py
rename to tests/examples/test_responses/test_custom_responses.py
--- a/docs/examples/tests/responses/test_custom_responses.py
+++ b/tests/examples/test_responses/test_custom_responses.py
@@ -1,4 +1,5 @@
-from examples.responses.custom_responses import app as app_1
+from docs.examples.responses.custom_responses import app as app_1
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/responses/test_response_cookies.py b/tests/examples/test_responses/test_response_cookies.py
similarity index 66%
rename from docs/examples/tests/responses/test_response_cookies.py
rename to tests/examples/test_responses/test_response_cookies.py
--- a/docs/examples/tests/responses/test_response_cookies.py
+++ b/tests/examples/test_responses/test_response_cookies.py
@@ -1,10 +1,11 @@
from unittest.mock import patch
-from examples.responses.response_cookies_1 import app
-from examples.responses.response_cookies_2 import app as app_2
-from examples.responses.response_cookies_3 import app as app_3
-from examples.responses.response_cookies_4 import app as app_4
-from examples.responses.response_cookies_5 import app as app_5
+from docs.examples.responses.response_cookies_1 import app
+from docs.examples.responses.response_cookies_2 import app as app_2
+from docs.examples.responses.response_cookies_3 import app as app_3
+from docs.examples.responses.response_cookies_4 import app as app_4
+from docs.examples.responses.response_cookies_5 import app as app_5
+
from litestar.testing import TestClient
@@ -26,7 +27,7 @@ def test_response_cookies_2() -> None:
def test_response_cookies_3() -> None:
- with TestClient(app=app_3) as client, patch("examples.responses.response_cookies_3.randint") as mock_randint:
+ with TestClient(app=app_3) as client, patch("docs.examples.responses.response_cookies_3.randint") as mock_randint:
mock_randint.return_value = "42"
res = client.get("/resources")
@@ -36,7 +37,7 @@ def test_response_cookies_3() -> None:
def test_response_cookies_4() -> None:
- with TestClient(app=app_4) as client, patch("examples.responses.response_cookies_4.randint") as mock_randint:
+ with TestClient(app=app_4) as client, patch("docs.examples.responses.response_cookies_4.randint") as mock_randint:
mock_randint.return_value = "42"
res = client.get("/router-path/resources")
@@ -46,7 +47,7 @@ def test_response_cookies_4() -> None:
def test_response_cookies_5() -> None:
- with TestClient(app=app_5) as client, patch("examples.responses.response_cookies_5.randint") as mock_randint:
+ with TestClient(app=app_5) as client, patch("docs.examples.responses.response_cookies_5.randint") as mock_randint:
mock_randint.return_value = "42"
res = client.get("/router-path/resources")
diff --git a/docs/examples/tests/responses/test_response_headers.py b/tests/examples/test_responses/test_response_headers.py
similarity index 67%
rename from docs/examples/tests/responses/test_response_headers.py
rename to tests/examples/test_responses/test_response_headers.py
--- a/docs/examples/tests/responses/test_response_headers.py
+++ b/tests/examples/test_responses/test_response_headers.py
@@ -1,9 +1,10 @@
from unittest.mock import patch
-from examples.responses.response_headers_1 import app
-from examples.responses.response_headers_2 import app as app_2
-from examples.responses.response_headers_3 import app as app_3
-from examples.responses.response_headers_4 import app as app_4
+from docs.examples.responses.response_headers_1 import app
+from docs.examples.responses.response_headers_2 import app as app_2
+from docs.examples.responses.response_headers_3 import app as app_3
+from docs.examples.responses.response_headers_4 import app as app_4
+
from litestar.testing import TestClient
@@ -18,7 +19,7 @@ def test_response_headers() -> None:
def test_response_headers_2() -> None:
- with TestClient(app=app_2) as client, patch("examples.responses.response_headers_2.randint") as mock_randint:
+ with TestClient(app=app_2) as client, patch("docs.examples.responses.response_headers_2.randint") as mock_randint:
mock_randint.return_value = "42"
res = client.get("/resources")
assert res.status_code == 200
@@ -26,7 +27,7 @@ def test_response_headers_2() -> None:
def test_response_headers_3() -> None:
- with TestClient(app=app_3) as client, patch("examples.responses.response_headers_3.randint") as mock_randint:
+ with TestClient(app=app_3) as client, patch("docs.examples.responses.response_headers_3.randint") as mock_randint:
mock_randint.return_value = "42"
res = client.get("/router-path/resources")
assert res.status_code == 200
@@ -35,7 +36,7 @@ def test_response_headers_3() -> None:
def test_response_headers_4() -> None:
- with TestClient(app=app_4) as client, patch("examples.responses.response_headers_4.randint") as mock_randint:
+ with TestClient(app=app_4) as client, patch("docs.examples.responses.response_headers_4.randint") as mock_randint:
mock_randint.return_value = "42"
res = client.get("/router-path/resources")
assert res.status_code == 200
diff --git a/docs/examples/tests/responses/test_returning_responses.py b/tests/examples/test_responses/test_returning_responses.py
similarity index 84%
rename from docs/examples/tests/responses/test_returning_responses.py
rename to tests/examples/test_responses/test_returning_responses.py
--- a/docs/examples/tests/responses/test_returning_responses.py
+++ b/tests/examples/test_responses/test_returning_responses.py
@@ -1,4 +1,5 @@
-from examples.responses.returning_responses import app
+from docs.examples.responses.returning_responses import app
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/routing/test_mounting.py b/tests/examples/test_routing.py
similarity index 92%
rename from docs/examples/tests/routing/test_mounting.py
rename to tests/examples/test_routing.py
--- a/docs/examples/tests/routing/test_mounting.py
+++ b/tests/examples/test_routing.py
@@ -1,8 +1,8 @@
from typing import TYPE_CHECKING
import pytest
+from docs.examples.routing import mount_custom_app, mounting_starlette_app
-from examples.routing import mount_custom_app, mounting_starlette_app
from litestar.status_codes import HTTP_200_OK
from litestar.testing import TestClient
diff --git a/docs/examples/tests/test_signature_namespace.py b/tests/examples/test_signature_namespace.py
similarity index 81%
rename from docs/examples/tests/test_signature_namespace.py
rename to tests/examples/test_signature_namespace.py
--- a/docs/examples/tests/test_signature_namespace.py
+++ b/tests/examples/test_signature_namespace.py
@@ -1,4 +1,5 @@
-from examples.signature_namespace.app import app
+from docs.examples.signature_namespace.app import app
+
from litestar.testing import TestClient
diff --git a/docs/examples/tests/test_startup_and_shutdown.py b/tests/examples/test_startup_and_shutdown.py
similarity index 94%
rename from docs/examples/tests/test_startup_and_shutdown.py
rename to tests/examples/test_startup_and_shutdown.py
--- a/docs/examples/tests/test_startup_and_shutdown.py
+++ b/tests/examples/test_startup_and_shutdown.py
@@ -1,7 +1,8 @@
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, MagicMock
-from examples import startup_and_shutdown
+from docs.examples import startup_and_shutdown
+
from litestar import get
from litestar.datastructures import State
from litestar.testing import TestClient
diff --git a/docs/examples/tests/test_stores.py b/tests/examples/test_stores.py
similarity index 73%
rename from docs/examples/tests/test_stores.py
rename to tests/examples/test_stores.py
--- a/docs/examples/tests/test_stores.py
+++ b/tests/examples/test_stores.py
@@ -1,9 +1,7 @@
from pathlib import Path
-from typing import TYPE_CHECKING, Generator
from unittest.mock import MagicMock, patch
import anyio
-from freezegun import freeze_time
from litestar import get
from litestar.stores.file import FileStore
@@ -11,23 +9,10 @@
from litestar.stores.redis import RedisStore
from litestar.testing import TestClient
-if TYPE_CHECKING:
- from freezegun.api import FrozenDateTimeFactory
-
-from typing import cast
-
-import pytest
-
-
[email protected]()
-def frozen_datetime() -> Generator["FrozenDateTimeFactory", None, None]:
- with freeze_time() as frozen:
- yield cast("FrozenDateTimeFactory", frozen)
-
@patch("litestar.stores.redis.Redis")
async def test_configure_integrations_set_names(mock_redis: MagicMock) -> None:
- from examples.stores.configure_integrations_set_names import app
+ from docs.examples.stores.configure_integrations_set_names import app
assert isinstance(app.stores.get("redis"), RedisStore)
assert isinstance(app.stores.get("file"), FileStore)
@@ -35,7 +20,7 @@ async def test_configure_integrations_set_names(mock_redis: MagicMock) -> None:
async def test_delete_expired_after_response(frozen_datetime) -> None:
- from examples.stores.delete_expired_after_response import app, memory_store
+ from docs.examples.stores.delete_expired_after_response import app, memory_store
@get()
async def handler() -> bytes:
@@ -52,7 +37,7 @@ async def handler() -> bytes:
async def test_delete_expired_on_startup(tmp_path) -> None:
- from examples.stores.delete_expired_on_startup import app, file_store
+ from docs.examples.stores.delete_expired_on_startup import app, file_store
file_store.path = anyio.Path(tmp_path)
@@ -64,7 +49,7 @@ async def test_delete_expired_on_startup(tmp_path) -> None:
async def test_get_set(capsys) -> None:
- from examples.stores.get_set import main
+ from docs.examples.stores.get_set import main
await main()
@@ -72,7 +57,7 @@ async def test_get_set(capsys) -> None:
async def test_registry() -> None:
- from examples.stores.registry import app, memory_store, some_other_store
+ from docs.examples.stores.registry import app, memory_store, some_other_store
assert app.stores.get("memory") is memory_store
assert isinstance(memory_store, MemoryStore)
@@ -81,7 +66,7 @@ async def test_registry() -> None:
async def test_registry_access_integration() -> None:
- from examples.stores.registry_access_integration import app, rate_limit_store
+ from docs.examples.stores.registry_access_integration import app, rate_limit_store
assert app.stores.get("rate_limit") is rate_limit_store
# this is a weird assertion but the easiest way to check if our example is correct
@@ -90,7 +75,7 @@ async def test_registry_access_integration() -> None:
@patch("litestar.stores.redis.Redis")
async def test_configure_integrations(mock_redis: MagicMock) -> None:
- from examples.stores.registry_configure_integrations import app
+ from docs.examples.stores.registry_configure_integrations import app
session_store = app.middleware[0].kwargs["backend"].config.get_store_from_app(app)
cache_store = app.response_cache_config.get_store_from_app(app)
@@ -101,7 +86,7 @@ async def test_configure_integrations(mock_redis: MagicMock) -> None:
async def test_registry_default_factory() -> None:
- from examples.stores.registry_default_factory import app, memory_store
+ from docs.examples.stores.registry_default_factory import app, memory_store
assert app.stores.get("foo") is memory_store
assert app.stores.get("bar") is memory_store
@@ -109,7 +94,7 @@ async def test_registry_default_factory() -> None:
@patch("litestar.stores.redis.Redis")
async def test_default_factory_namespacing(mock_redis: MagicMock) -> None:
- from examples.stores.registry_default_factory_namespacing import app, root_store
+ from docs.examples.stores.registry_default_factory_namespacing import app, root_store
foo_store = app.stores.get("foo")
assert isinstance(foo_store, RedisStore)
diff --git a/docs/examples/tests/security/test_using_session_auth.py b/tests/examples/test_using_session_auth.py
similarity index 95%
rename from docs/examples/tests/security/test_using_session_auth.py
rename to tests/examples/test_using_session_auth.py
--- a/docs/examples/tests/security/test_using_session_auth.py
+++ b/tests/examples/test_using_session_auth.py
@@ -1,4 +1,5 @@
-from examples.security.using_session_auth import app
+from docs.examples.security.using_session_auth import app
+
from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_401_UNAUTHORIZED
from litestar.testing import TestClient
diff --git a/tests/middleware/conftest.py b/tests/middleware/conftest.py
deleted file mode 100644
--- a/tests/middleware/conftest.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import TYPE_CHECKING
-
-import pytest
-
-from litestar.logging.config import LoggingConfig, default_handlers
-
-if TYPE_CHECKING:
- from litestar.types.callable_types import GetLogger
-
-
[email protected]
-def get_logger() -> "GetLogger":
- # due to the limitations of caplog we have to place this call here.
- # we also have to allow propagation.
- return LoggingConfig(
- handlers=default_handlers,
- loggers={
- "litestar": {"level": "DEBUG", "handlers": ["queue_listener"], "propagate": True},
- },
- ).configure()
diff --git a/tests/openapi/typescript_converter/__init__.py b/tests/openapi/typescript_converter/__init__.py
deleted file mode 100644
diff --git a/tests/piccolo_conf.py b/tests/piccolo_conf.py
deleted file mode 100644
--- a/tests/piccolo_conf.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from piccolo.conf.apps import AppRegistry
-from piccolo.engine import SQLiteEngine
-
-DB = SQLiteEngine(path="test.sqlite")
-
-APP_REGISTRY = AppRegistry(apps=["tests.contrib.piccolo_orm.piccolo_app"])
diff --git a/tests/response/__init__.py b/tests/response/__init__.py
deleted file mode 100644
diff --git a/tests/routing/__init__.py b/tests/routing/__init__.py
deleted file mode 100644
diff --git a/tests/security/__init__.py b/tests/security/__init__.py
deleted file mode 100644
diff --git a/tests/signature/__init__.py b/tests/signature/__init__.py
deleted file mode 100644
diff --git a/tests/static_files/__init__.py b/tests/static_files/__init__.py
deleted file mode 100644
diff --git a/tests/template/__init__.py b/tests/template/__init__.py
deleted file mode 100644
diff --git a/tests/test_parameters.py b/tests/test_parameters.py
deleted file mode 100644
--- a/tests/test_parameters.py
+++ /dev/null
@@ -1,88 +0,0 @@
-from typing import Any, List
-
-import pytest
-from typing_extensions import Annotated
-
-from litestar import get, post
-from litestar.di import Provide
-from litestar.params import Body, Dependency, Parameter
-from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST
-from litestar.testing import create_test_client
-
-
[email protected]("backend", ("pydantic", "attrs"))
-def test_parsing_of_parameter_as_annotated(backend: Any) -> None:
- @get(path="/")
- def handler(param: Annotated[str, Parameter(min_length=1)]) -> str:
- return param
-
- with create_test_client(handler, _preferred_validation_backend=backend) as client:
- response = client.get("/")
- assert response.status_code == HTTP_400_BAD_REQUEST
-
- response = client.get("/?param=a")
- assert response.status_code == HTTP_200_OK
-
-
[email protected]("backend", ("pydantic", "attrs"))
-def test_parsing_of_parameter_as_default_value(backend: Any) -> None:
- @get(path="/")
- def handler(param: str = Parameter(min_length=1)) -> str:
- return param
-
- with create_test_client(handler, _preferred_validation_backend=backend) as client:
- response = client.get("/?param=")
- assert response.status_code == HTTP_400_BAD_REQUEST
-
- response = client.get("/?param=a")
- assert response.status_code == HTTP_200_OK
-
-
[email protected]("backend", ("pydantic", "attrs"))
-def test_parsing_of_body_as_annotated(backend: Any) -> None:
- @post(path="/")
- def handler(data: Annotated[List[str], Body(min_items=1)]) -> List[str]:
- return data
-
- with create_test_client(handler, _preferred_validation_backend=backend) as client:
- response = client.post("/", json=[])
- assert response.status_code == HTTP_400_BAD_REQUEST
-
- response = client.post("/", json=["a"])
- assert response.status_code == HTTP_201_CREATED
-
-
[email protected]("backend", ("pydantic", "attrs"))
-def test_parsing_of_body_as_default_value(backend: Any) -> None:
- @post(path="/")
- def handler(data: List[str] = Body(min_items=1)) -> List[str]:
- return data
-
- with create_test_client(handler, _preferred_validation_backend=backend) as client:
- response = client.post("/", json=[])
- assert response.status_code == HTTP_400_BAD_REQUEST
-
- response = client.post("/", json=["a"])
- assert response.status_code == HTTP_201_CREATED
-
-
[email protected]("backend", ("pydantic", "attrs"))
-def test_parsing_of_dependency_as_annotated(backend: Any) -> None:
- @get(path="/", dependencies={"dep": Provide(lambda: None, sync_to_thread=False)})
- def handler(dep: Annotated[int, Dependency(skip_validation=True)]) -> int:
- return dep
-
- with create_test_client(handler, _preferred_validation_backend=backend) as client:
- response = client.get("/")
- assert response.text == "null"
-
-
[email protected]("backend", ("pydantic", "attrs"))
-def test_parsing_of_dependency_as_default_value(backend: Any) -> None:
- @get(path="/", dependencies={"dep": Provide(lambda: None, sync_to_thread=False)})
- def handler(dep: int = Dependency(skip_validation=True)) -> int:
- return dep
-
- with create_test_client(handler, _preferred_validation_backend=backend) as client:
- response = client.get("/")
- assert response.text == "null"
diff --git a/tests/test_provide.py b/tests/test_provide.py
deleted file mode 100644
--- a/tests/test_provide.py
+++ /dev/null
@@ -1,208 +0,0 @@
-from functools import partial
-from typing import Any, AsyncGenerator, Generator
-from unittest.mock import MagicMock
-
-import pytest
-
-from litestar._kwargs.cleanup import DependencyCleanupGroup
-from litestar.di import Provide
-from litestar.exceptions import LitestarWarning
-from litestar.types import Empty
-from litestar.utils.compat import async_next
-
-
-class C:
- val = 31
-
- def __init__(self) -> None:
- self.val = 13
-
- @classmethod
- async def async_class(cls) -> int:
- return cls.val
-
- @classmethod
- def sync_class(cls) -> int:
- return cls.val
-
- @staticmethod
- async def async_static() -> str:
- return "one-three"
-
- @staticmethod
- def sync_static() -> str:
- return "one-three"
-
- async def async_instance(self) -> int:
- return self.val
-
- def sync_instance(self) -> int:
- return self.val
-
-
-async def async_fn(val: str = "three-one") -> str:
- return val
-
-
-def sync_fn(val: str = "three-one") -> str:
- return val
-
-
-async_partial = partial(async_fn, "why-three-and-one")
-sync_partial = partial(sync_fn, "why-three-and-one")
-
-
-async def test_provide_default(anyio_backend: str) -> None:
- provider = Provide(dependency=async_fn)
- value = await provider()
- assert value == "three-one"
-
-
-async def test_provide_cached(anyio_backend: str) -> None:
- provider = Provide(dependency=async_fn, use_cache=True)
- assert provider.value is Empty
- value = await provider()
- assert value == "three-one"
- assert provider.value == value
- second_value = await provider()
- assert value == second_value
- third_value = await provider()
- assert value == third_value
-
-
-async def test_run_in_thread(anyio_backend: str) -> None:
- provider = Provide(dependency=sync_fn, sync_to_thread=True)
- value = await provider()
- assert value == "three-one"
-
-
-def test_provider_equality_check() -> None:
- first_provider = Provide(dependency=sync_fn, sync_to_thread=False)
- second_provider = Provide(dependency=sync_fn, sync_to_thread=False)
- assert first_provider == second_provider
- third_provider = Provide(dependency=sync_fn, use_cache=True, sync_to_thread=False)
- assert first_provider != third_provider
- second_provider.value = True
- assert first_provider != second_provider
-
-
[email protected](
- "fn, exp",
- [
- (C.async_class, 31),
- (C.sync_class, 31),
- (C.async_static, "one-three"),
- (C.sync_static, "one-three"),
- (C().async_instance, 13),
- (C().sync_instance, 13),
- (async_fn, "three-one"),
- (sync_fn, "three-one"),
- (async_partial, "why-three-and-one"),
- (sync_partial, "why-three-and-one"),
- ],
-)
[email protected]("disable_warn_sync_to_thread_with_async")
-async def test_provide_for_callable(fn: Any, exp: Any, anyio_backend: str) -> None:
- assert await Provide(fn, sync_to_thread=False)() == exp
-
-
[email protected]
-def cleanup_mock() -> MagicMock:
- return MagicMock()
-
-
[email protected]
-def async_cleanup_mock() -> MagicMock:
- return MagicMock()
-
-
[email protected]
-def generator(cleanup_mock: MagicMock) -> Generator[str, None, None]:
- def func() -> Generator[str, None, None]:
- yield "hello"
- cleanup_mock()
-
- return func()
-
-
[email protected]
-def async_generator(async_cleanup_mock: MagicMock) -> AsyncGenerator[str, None]:
- async def func() -> AsyncGenerator[str, None]:
- yield "world"
- async_cleanup_mock()
-
- return func()
-
-
-def test_cleanup_group_add(generator: Generator[str, None, None]) -> None:
- group = DependencyCleanupGroup()
-
- group.add(generator)
-
- assert group._generators == [generator]
-
-
-async def test_cleanup_group_cleanup(generator: Generator[str, None, None], cleanup_mock: MagicMock) -> None:
- next(generator)
- group = DependencyCleanupGroup([generator])
-
- await group.cleanup()
-
- cleanup_mock.assert_called_once()
- assert group._closed
-
-
-async def test_cleanup_group_cleanup_multiple(
- generator: Generator[str, None, None],
- async_generator: AsyncGenerator[str, None],
- cleanup_mock: MagicMock,
- async_cleanup_mock: MagicMock,
-) -> None:
- next(generator)
- await async_next(async_generator)
- group = DependencyCleanupGroup([generator, async_generator])
-
- await group.cleanup()
-
- cleanup_mock.assert_called_once()
- async_cleanup_mock.assert_called_once()
- assert group._closed
-
-
-async def test_cleanup_group_cleanup_on_closed_raises(generator: Generator[str, None, None]) -> None:
- next(generator)
- group = DependencyCleanupGroup([generator])
-
- await group.cleanup()
- with pytest.raises(RuntimeError):
- await group.cleanup()
-
-
-async def test_cleanup_group_add_on_closed_raises(
- generator: Generator[str, None, None], async_generator: AsyncGenerator[str, None]
-) -> None:
- next(generator)
- group = DependencyCleanupGroup([generator])
-
- await group.cleanup()
-
- with pytest.raises(RuntimeError):
- group.add(async_generator)
-
-
[email protected]("enable_warn_implicit_sync_to_thread")
-def test_sync_callable_without_sync_to_thread_warns() -> None:
- def func() -> None:
- pass
-
- with pytest.warns(LitestarWarning, match="discouraged since synchronous callables"):
- Provide(func)
-
-
[email protected]("sync_to_thread", [True, False])
-def test_async_callable_with_sync_to_thread_warns(sync_to_thread: bool) -> None:
- async def func() -> None:
- pass
-
- with pytest.warns(LitestarWarning, match="asynchronous callable"):
- Provide(func, sync_to_thread=sync_to_thread)
diff --git a/tests/test_response_containers.py b/tests/test_response_containers.py
deleted file mode 100644
--- a/tests/test_response_containers.py
+++ /dev/null
@@ -1,187 +0,0 @@
-import os
-from os import stat
-from pathlib import Path
-from typing import TYPE_CHECKING, Optional
-
-import pytest
-from fsspec.implementations.local import LocalFileSystem
-
-from litestar import get
-from litestar.datastructures import ETag
-from litestar.exceptions import ImproperlyConfiguredException
-from litestar.file_system import BaseLocalFileSystem
-from litestar.response.file import File
-from litestar.response.redirect import Redirect
-from litestar.status_codes import HTTP_200_OK
-from litestar.testing import create_test_client
-
-if TYPE_CHECKING:
- from litestar.types import FileSystemProtocol
-
-
[email protected]("file_system", (BaseLocalFileSystem(), LocalFileSystem()))
-def test_file_with_different_file_systems(tmpdir: "Path", file_system: "FileSystemProtocol") -> None:
- path = tmpdir / "text.txt"
- path.write_text("content", "utf-8")
-
- @get("/", media_type="application/octet-stream")
- def handler() -> File:
- return File(
- filename="text.txt",
- path=path,
- file_system=file_system,
- )
-
- with create_test_client(handler, debug=True) as client:
- response = client.get("/")
- assert response.status_code == HTTP_200_OK
- assert response.text == "content"
- assert response.headers.get("content-disposition") == 'attachment; filename="text.txt"'
-
-
-def test_file_with_passed_in_file_info(tmpdir: "Path") -> None:
- path = tmpdir / "text.txt"
- path.write_text("content", "utf-8")
-
- fs = LocalFileSystem()
- fs_info = fs.info(tmpdir / "text.txt")
-
- assert fs_info
-
- @get("/", media_type="application/octet-stream")
- def handler() -> File:
- return File(filename="text.txt", path=path, file_system=fs, file_info=fs_info) # pyright: ignore
-
- with create_test_client(handler) as client:
- response = client.get("/")
- assert response.status_code == HTTP_200_OK, response.text
- assert response.text == "content"
- assert response.headers.get("content-disposition") == 'attachment; filename="text.txt"'
-
-
-def test_file_with_passed_in_stat_result(tmpdir: "Path") -> None:
- path = tmpdir / "text.txt"
- path.write_text("content", "utf-8")
-
- fs = LocalFileSystem()
- stat_result = stat(path)
-
- @get("/", media_type="application/octet-stream")
- def handler() -> File:
- return File(filename="text.txt", path=path, file_system=fs, stat_result=stat_result)
-
- with create_test_client(handler) as client:
- response = client.get("/")
- assert response.status_code == HTTP_200_OK
- assert response.text == "content"
- assert response.headers.get("content-disposition") == 'attachment; filename="text.txt"'
-
-
-async def test_file_with_symbolic_link(tmpdir: "Path") -> None:
- path = tmpdir / "text.txt"
- path.write_text("content", "utf-8")
-
- linked = tmpdir / "alt.txt"
- os.symlink(path, linked, target_is_directory=False)
-
- fs = BaseLocalFileSystem()
- file_info = await fs.info(linked)
-
- assert file_info["islink"]
-
- @get("/", media_type="application/octet-stream")
- def handler() -> File:
- return File(filename="alt.txt", path=linked, file_system=fs, file_info=file_info)
-
- with create_test_client(handler) as client:
- response = client.get("/")
- assert response.status_code == HTTP_200_OK
- assert response.text == "content"
- assert response.headers.get("content-disposition") == 'attachment; filename="alt.txt"'
-
-
-async def test_file_sets_etag_correctly(tmpdir: "Path") -> None:
- path = tmpdir / "file.txt"
- content = b"<file content>"
- Path(path).write_bytes(content)
- etag = ETag(value="special")
-
- @get("/")
- def handler() -> File:
- return File(path=path, etag=etag)
-
- with create_test_client(handler) as client:
- response = client.get("/")
- assert response.status_code == HTTP_200_OK
- assert response.headers["etag"] == '"special"'
-
-
-def test_file_system_validation(tmpdir: "Path") -> None:
- path = tmpdir / "text.txt"
- path.write_text("content", "utf-8")
-
- class FSWithoutOpen:
- def info(self) -> None:
- return
-
- with pytest.raises(ImproperlyConfiguredException):
- File(
- filename="text.txt",
- path=path,
- file_system=FSWithoutOpen(), # type:ignore[arg-type]
- )
-
- class FSWithoutInfo:
- def open(self) -> None:
- return
-
- with pytest.raises(ImproperlyConfiguredException):
- File(
- filename="text.txt",
- path=path,
- file_system=FSWithoutInfo(), # type:ignore[arg-type]
- )
-
- class ImplementedFS:
- def info(self) -> None:
- return
-
- def open(self) -> None:
- return
-
- assert File(
- filename="text.txt",
- path=path,
- file_system=ImplementedFS(), # type:ignore[arg-type]
- )
-
-
[email protected](
- "status_code,expected_status_code",
- [
- (301, 301),
- (302, 302),
- (303, 303),
- (307, 307),
- (308, 308),
- ],
-)
-def test_redirect_dynamic_status_code(status_code: Optional[int], expected_status_code: int) -> None:
- @get("/")
- def handler() -> Redirect:
- return Redirect(path="/something-else", status_code=status_code) # type: ignore[arg-type]
-
- with create_test_client([handler], debug=True) as client:
- res = client.get("/", follow_redirects=False)
- assert res.status_code == expected_status_code
-
-
[email protected]("handler_status_code", [301, 307, None])
-def test_redirect(handler_status_code: Optional[int]) -> None:
- @get("/", status_code=handler_status_code)
- def handler() -> Redirect:
- return Redirect(path="/something-else", status_code=301)
-
- with create_test_client([handler]) as client:
- res = client.get("/", follow_redirects=False)
- assert res.status_code == 301
diff --git a/tests/test_utils.py b/tests/test_utils.py
deleted file mode 100644
--- a/tests/test_utils.py
+++ /dev/null
@@ -1,61 +0,0 @@
-from functools import partial
-from typing import AsyncGenerator, Callable
-
-import pytest
-
-from litestar.utils.predicates import is_async_callable
-
-
-class AsyncTestCallable:
- async def __call__(self, param1: int, param2: int) -> None:
- ...
-
- async def method(self, param1: int, param2: int) -> None:
- ...
-
-
-async def async_generator() -> AsyncGenerator[int, None]:
- yield 1
-
-
-class SyncTestCallable:
- def __call__(self, param1: int, param2: int) -> None:
- ...
-
- def method(self, param1: int, param2: int) -> None:
- ...
-
-
-async def async_func(param1: int, param2: int) -> None:
- ...
-
-
-def sync_func(param1: int, param2: int) -> None:
- ...
-
-
-async_callable = AsyncTestCallable()
-sync_callable = SyncTestCallable()
-
-
[email protected](
- "c, exp",
- [
- (async_callable, True),
- (sync_callable, False),
- (async_callable.method, True),
- (sync_callable.method, False),
- (async_func, True),
- (sync_func, False),
- (lambda: ..., False),
- (AsyncTestCallable, True),
- (SyncTestCallable, False),
- (async_generator, False),
- ],
-)
-def test_is_async_callable(c: Callable[[int, int], None], exp: bool) -> None:
- assert is_async_callable(c) is exp
- partial_1 = partial(c, 1)
- assert is_async_callable(partial_1) is exp
- partial_2 = partial(partial_1, 2)
- assert is_async_callable(partial_2) is exp
diff --git a/tests/testing/__init__.py b/tests/testing/__init__.py
deleted file mode 100644
diff --git a/docs/examples/tests/security/__init__.py b/tests/unit/__init__.py
similarity index 100%
rename from docs/examples/tests/security/__init__.py
rename to tests/unit/__init__.py
diff --git a/tests/unit/test_app.py b/tests/unit/test_app.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/test_app.py
@@ -0,0 +1,379 @@
+# ruff: noqa: UP006
+from __future__ import annotations
+
+import inspect
+import logging
+from dataclasses import fields
+from typing import TYPE_CHECKING, List, Tuple
+from unittest.mock import MagicMock, Mock, PropertyMock
+
+import pytest
+from pytest import MonkeyPatch
+
+from litestar import Litestar, MediaType, Request, Response, get, post
+from litestar.config.app import AppConfig
+from litestar.config.response_cache import ResponseCacheConfig
+from litestar.datastructures import MutableScopeHeaders, State
+from litestar.events.emitter import SimpleEventEmitter
+from litestar.exceptions import (
+ ImproperlyConfiguredException,
+ InternalServerException,
+ LitestarWarning,
+ NotFoundException,
+)
+from litestar.logging.config import LoggingConfig
+from litestar.router import Router
+from litestar.status_codes import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
+from litestar.testing import TestClient, create_test_client
+from tests import Person
+
+if TYPE_CHECKING:
+ from typing import Dict
+
+ from litestar.types import Message, Scope
+
+
[email protected]()
+def app_config_object() -> AppConfig:
+ return AppConfig(
+ after_exception=[],
+ after_request=None,
+ after_response=None,
+ allowed_hosts=[],
+ before_request=None,
+ before_send=[],
+ response_cache_config=ResponseCacheConfig(),
+ cache_control=None,
+ compression_config=None,
+ cors_config=None,
+ csrf_config=None,
+ debug=False,
+ dependencies={},
+ etag=None,
+ event_emitter_backend=SimpleEventEmitter,
+ exception_handlers={},
+ guards=[],
+ listeners=[],
+ logging_config=None,
+ middleware=[],
+ multipart_form_part_limit=1000,
+ on_shutdown=[],
+ on_startup=[],
+ openapi_config=None,
+ opt={},
+ parameters={},
+ plugins=[],
+ request_class=None,
+ response_class=None,
+ response_cookies=[],
+ response_headers=[],
+ route_handlers=[],
+ security=[],
+ static_files_config=[],
+ tags=[],
+ template_config=None,
+ websocket_class=None,
+ )
+
+
+def test_access_openapi_schema_raises_if_not_configured() -> None:
+ """Test that accessing the openapi schema raises if not configured."""
+ app = Litestar(openapi_config=None)
+ with pytest.raises(ImproperlyConfiguredException):
+ app.openapi_schema
+
+
+def test_set_debug_updates_logging_level() -> None:
+ app = Litestar()
+
+ assert app.logger is not None
+ assert app.logger.level == logging.INFO # type: ignore[attr-defined]
+
+ app.debug = True
+ assert app.logger.level == logging.DEBUG # type: ignore[attr-defined]
+
+ app.debug = False
+ assert app.logger.level == logging.INFO # type: ignore[attr-defined]
+
+
[email protected]("env_name,app_attr", [("LITESTAR_DEBUG", "debug"), ("LITESTAR_PDB", "pdb_on_exception")])
[email protected](
+ "env_value,app_value,expected_value",
+ [
+ (None, None, False),
+ (None, False, False),
+ (None, True, True),
+ ("0", None, False),
+ ("0", False, False),
+ ("0", True, True),
+ ("1", None, True),
+ ("1", False, False),
+ ("1", True, True),
+ ],
+)
+def test_set_env_flags(
+ monkeypatch: MonkeyPatch,
+ env_value: str | None,
+ app_value: bool | None,
+ expected_value: bool,
+ env_name: str,
+ app_attr: str,
+) -> None:
+ if env_value is not None:
+ monkeypatch.setenv(env_name, env_value)
+ else:
+ monkeypatch.delenv(env_name, raising=False)
+
+ app = Litestar(**{app_attr: app_value}) # type: ignore[arg-type]
+
+ assert getattr(app, app_attr) is expected_value
+
+
+def test_warn_pdb_on_exception() -> None:
+ with pytest.warns(LitestarWarning, match="Debugger"):
+ Litestar(pdb_on_exception=True)
+
+
+def test_app_params_defined_on_app_config_object() -> None:
+ """Ensures that all parameters to the `Litestar` constructor are present on the `AppConfig` object."""
+ litestar_signature = inspect.signature(Litestar)
+ app_config_fields = {f.name for f in fields(AppConfig)}
+ for name in litestar_signature.parameters:
+ if name in {"on_app_init", "initial_state", "_preferred_validation_backend"}:
+ continue
+ assert name in app_config_fields
+ # ensure there are not fields defined on AppConfig that aren't in the Litestar signature
+ assert not (app_config_fields - set(litestar_signature.parameters.keys()))
+
+
+def test_app_config_object_used(app_config_object: AppConfig, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Ensure that the properties on the `AppConfig` object are accessed within the `Litestar` constructor.
+
+ In the test we replace every field on the `AppConfig` type with a property mock so that we can check that it has at
+ least been accessed. It doesn't actually check that we do the right thing with it, but is a guard against the case
+ of adding a parameter to the `Litestar` signature and to the `AppConfig` object, and using the value from the
+ parameter downstream from construction of the `AppConfig` object.
+ """
+
+ # replace each field on the `AppConfig` object with a `PropertyMock`, this allows us to assert that the properties
+ # have been accessed during app instantiation.
+ property_mocks: List[Tuple[str, Mock]] = []
+ for field in fields(AppConfig):
+ if field.name == "response_cache_config":
+ property_mock = PropertyMock(return_value=ResponseCacheConfig())
+ if field.name in ["event_emitter_backend", "response_cache_config"]:
+ property_mock = PropertyMock(return_value=Mock())
+ else:
+ # default iterable return value allows the mock properties that need to be iterated over in
+ # `Litestar.__init__()` to not blow up, for other properties it shouldn't matter what the value is for the
+ # sake of this test.
+ property_mock = PropertyMock(return_value=[])
+ property_mocks.append((field.name, property_mock))
+ monkeypatch.setattr(type(app_config_object), field.name, property_mock, raising=False)
+
+ # Things that we don't actually need to call for this test
+ monkeypatch.setattr(Litestar, "register", MagicMock())
+ monkeypatch.setattr(Litestar, "_create_asgi_handler", MagicMock())
+ monkeypatch.setattr(Router, "__init__", MagicMock())
+
+ # instantiates the app with an `on_app_config` that returns our patched `AppConfig` object.
+ Litestar(on_app_init=[MagicMock(return_value=app_config_object)])
+
+ # this ensures that each of the properties of the `AppConfig` object have been accessed within `Litestar.__init__()`
+ for name, mock in property_mocks:
+ assert mock.called, f"expected {name} to be called"
+
+
+def test_app_debug_create_logger() -> None:
+ app = Litestar([], debug=True)
+
+ assert app.logging_config
+ assert app.logging_config.loggers["litestar"]["level"] == "DEBUG" # type: ignore[attr-defined]
+
+
+def test_app_debug_explicitly_disable_logging() -> None:
+ app = Litestar([], debug=True, logging_config=None)
+
+ assert not app.logging_config
+
+
+def test_app_debug_update_logging_config() -> None:
+ logging_config = LoggingConfig()
+ app = Litestar([], debug=True, logging_config=logging_config)
+
+ assert app.logging_config is logging_config
+ assert app.logging_config.loggers["litestar"]["level"] == "DEBUG" # type: ignore[attr-defined]
+
+
+def test_set_state() -> None:
+ def modify_state_in_hook(app_config: AppConfig) -> AppConfig:
+ assert isinstance(app_config.state, State)
+ app_config.state["c"] = "D"
+ app_config.state["e"] = "f"
+ return app_config
+
+ app = Litestar(state=State({"a": "b", "c": "d"}), on_app_init=[modify_state_in_hook])
+ assert app.state._state == {"a": "b", "c": "D", "e": "f"}
+
+
+def test_app_from_config(app_config_object: AppConfig) -> None:
+ Litestar.from_config(app_config_object)
+
+
+def test_before_send() -> None:
+ @get("/test")
+ def handler() -> Dict[str, str]:
+ return {"key": "value"}
+
+ async def before_send_hook_handler(message: Message, scope: Scope) -> None:
+ if message["type"] == "http.response.start":
+ headers = MutableScopeHeaders(message)
+ headers.add("My Header", scope["app"].state.message)
+
+ def on_startup(app: Litestar) -> None:
+ app.state.message = "value injected during send"
+
+ with create_test_client(handler, on_startup=[on_startup], before_send=[before_send_hook_handler]) as client:
+ response = client.get("/test")
+ assert response.status_code == HTTP_200_OK
+ assert response.headers.get("My Header") == "value injected during send"
+
+
+def test_default_handling_of_pydantic_errors() -> None:
+ @post("/{param:int}")
+ def my_route_handler(param: int, data: Person) -> None:
+ ...
+
+ with create_test_client(my_route_handler) as client:
+ response = client.post("/123", json={"first_name": "moishe"})
+ extra = response.json().get("extra")
+ assert extra is not None
+ assert len(extra) == 3
+
+
+def test_using_custom_http_exception_handler() -> None:
+ @get("/{param:int}")
+ def my_route_handler(param: int) -> None:
+ ...
+
+ def my_custom_handler(_: Request, __: Exception) -> Response:
+ return Response(content="custom message", media_type=MediaType.TEXT, status_code=HTTP_400_BAD_REQUEST)
+
+ with create_test_client(my_route_handler, exception_handlers={NotFoundException: my_custom_handler}) as client:
+ response = client.get("/abc")
+ assert response.text == "custom message"
+ assert response.status_code == HTTP_400_BAD_REQUEST
+
+
+def test_debug_response_created() -> None:
+ # this will test exception causes are recorded in output
+ # since frames include code in context we should not raise
+ # exception directly
+ def exception_thrower() -> float:
+ return 1 / 0
+
+ @get("/")
+ def my_route_handler() -> None:
+ try:
+ exception_thrower()
+ except Exception as e:
+ raise InternalServerException() from e
+
+ app = Litestar(route_handlers=[my_route_handler], debug=True)
+ client = TestClient(app=app)
+
+ response = client.get("/")
+ assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
+ assert "text/plain" in response.headers["content-type"]
+
+ response = client.get("/", headers={"accept": "text/html"})
+ assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
+ assert "text/html" in response.headers["content-type"]
+ assert "ZeroDivisionError" in response.text
+
+
+def test_handler_error_return_status_500() -> None:
+ @get("/")
+ def my_route_handler() -> None:
+ raise KeyError("custom message")
+
+ with create_test_client(my_route_handler) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
+
+
+def test_lifespan() -> None:
+ events: list[str] = []
+ counter = {"value": 0}
+
+ def sync_function_without_app() -> None:
+ events.append("sync_function_without_app")
+ counter["value"] += 1
+
+ async def async_function_without_app() -> None:
+ events.append("async_function_without_app")
+ counter["value"] += 1
+
+ def sync_function_with_app(app: Litestar) -> None:
+ events.append("sync_function_with_app")
+ assert app is not None
+ assert isinstance(app.state, State)
+ counter["value"] += 1
+ app.state.x = True
+
+ async def async_function_with_app(app: Litestar) -> None:
+ events.append("async_function_with_app")
+ assert app is not None
+ assert isinstance(app.state, State)
+ counter["value"] += 1
+ app.state.y = True
+
+ with create_test_client(
+ [],
+ on_startup=[
+ sync_function_without_app,
+ async_function_without_app,
+ sync_function_with_app,
+ async_function_with_app,
+ ],
+ on_shutdown=[
+ sync_function_without_app,
+ async_function_without_app,
+ sync_function_with_app,
+ async_function_with_app,
+ ],
+ ) as client:
+ assert counter["value"] == 4
+ assert client.app.state.x
+ assert client.app.state.y
+ counter["value"] = 0
+ assert counter["value"] == 0
+ assert counter["value"] == 4
+ assert events == [
+ "sync_function_without_app",
+ "async_function_without_app",
+ "sync_function_with_app",
+ "async_function_with_app",
+ "sync_function_without_app",
+ "async_function_without_app",
+ "sync_function_with_app",
+ "async_function_with_app",
+ ]
+
+
+def test_registering_route_handler_generates_openapi_docs() -> None:
+ def fn() -> None:
+ return
+
+ app = Litestar(route_handlers=[])
+ assert app.openapi_schema
+
+ app.register(get("/path1")(fn))
+
+ paths = app.openapi_schema.paths
+
+ assert paths is not None
+ assert paths.get("/path1")
+
+ app.register(get("/path2")(fn))
+ assert paths.get("/path2")
diff --git a/tests/asgi_router/test_lifespan.py b/tests/unit/test_asgi_router.py
similarity index 92%
rename from tests/asgi_router/test_lifespan.py
rename to tests/unit/test_asgi_router.py
--- a/tests/asgi_router/test_lifespan.py
+++ b/tests/unit/test_asgi_router.py
@@ -4,17 +4,26 @@
from typing import TYPE_CHECKING, AsyncGenerator, Callable
from unittest.mock import AsyncMock, MagicMock
+import pytest
from pytest_mock import MockerFixture
-from litestar import Litestar
+from litestar import Litestar, asgi
from litestar._asgi.asgi_router import ASGIRouter
+from litestar.exceptions import ImproperlyConfiguredException
+from litestar.testing import TestClient, create_test_client
if TYPE_CHECKING:
from contextlib import AbstractAsyncContextManager
-import pytest
+ from litestar.types import Receive, Scope, Send
-from litestar.testing import TestClient, create_test_client
+
+def test_add_mount_route_disallow_path_parameter() -> None:
+ async def handler(scope: Scope, receive: Receive, send: Send) -> None:
+ return None
+
+ with pytest.raises(ImproperlyConfiguredException):
+ Litestar(route_handlers=[asgi("/mount-path", is_static=True)(handler), asgi("/mount-path/{id:str}")(handler)])
class _LifeSpanCallable:
diff --git a/tests/datastructures/test_background_task.py b/tests/unit/test_background_tasks.py
similarity index 100%
rename from tests/datastructures/test_background_task.py
rename to tests/unit/test_background_tasks.py
diff --git a/tests/app/__init__.py b/tests/unit/test_channels/__init__.py
similarity index 100%
rename from tests/app/__init__.py
rename to tests/unit/test_channels/__init__.py
diff --git a/tests/channels/conftest.py b/tests/unit/test_channels/conftest.py
similarity index 61%
rename from tests/channels/conftest.py
rename to tests/unit/test_channels/conftest.py
--- a/tests/channels/conftest.py
+++ b/tests/unit/test_channels/conftest.py
@@ -1,29 +1,12 @@
from __future__ import annotations
-from typing import AsyncGenerator
-
import pytest
-from redis import Redis
from redis.asyncio import Redis as AsyncRedis
from litestar.channels.backends.memory import MemoryChannelsBackend
from litestar.channels.backends.redis import RedisChannelsPubSubBackend, RedisChannelsStreamBackend
[email protected]()
-async def redis_client(docker_ip: str) -> AsyncGenerator[AsyncRedis, None]:
- # this is to get around some weirdness with pytest-asyncio and redis interaction
- # on 3.8 and 3.9
-
- Redis(host=docker_ip, port=6397).flushall()
- client: AsyncRedis = AsyncRedis(host=docker_ip, port=6397)
- yield client
- try:
- await client.close()
- except RuntimeError:
- pass
-
-
@pytest.fixture()
def redis_stream_backend(redis_client: AsyncRedis) -> RedisChannelsStreamBackend:
return RedisChannelsStreamBackend(history=10, redis=redis_client, cap_streams_approximate=False)
diff --git a/tests/channels/test_backends.py b/tests/unit/test_channels/test_backends.py
similarity index 94%
rename from tests/channels/test_backends.py
rename to tests/unit/test_channels/test_backends.py
--- a/tests/channels/test_backends.py
+++ b/tests/unit/test_channels/test_backends.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio
-import sys
from datetime import timedelta
from typing import AsyncGenerator, cast
@@ -14,11 +13,6 @@
from litestar.channels.backends.redis import RedisChannelsPubSubBackend, RedisChannelsStreamBackend
from litestar.utils.compat import async_next
-pytestmark = [
- pytest.mark.usefixtures("redis_service"),
- pytest.mark.skipif(sys.platform != "linux", reason="docker not available on this platform"),
-]
-
@pytest.fixture(
params=[
@@ -96,7 +90,7 @@ async def test_get_history(
assert history == expected_messages
-async def test_memory_backend_discards_history_entries(channels_backend: ChannelsBackend) -> None:
+async def test_discards_history_entries(channels_backend: ChannelsBackend) -> None:
if isinstance(channels_backend, RedisChannelsPubSubBackend):
pytest.skip()
diff --git a/tests/channels/test_plugin.py b/tests/unit/test_channels/test_plugin.py
similarity index 97%
rename from tests/channels/test_plugin.py
rename to tests/unit/test_channels/test_plugin.py
--- a/tests/channels/test_plugin.py
+++ b/tests/unit/test_channels/test_plugin.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio
-import sys
from secrets import token_hex
from typing import cast
from unittest.mock import AsyncMock, MagicMock
@@ -20,21 +19,6 @@
from .util import get_from_stream
-pytestmark = [
- pytest.mark.usefixtures("redis_service"),
- pytest.mark.skipif(sys.platform != "linux", reason="docker not available on this platform"),
-]
-
-
[email protected]
-def mock() -> MagicMock:
- return MagicMock()
-
-
[email protected]()
-def async_mock() -> AsyncMock:
- return AsyncMock()
-
@pytest.fixture(
params=[
diff --git a/tests/channels/test_subscriber.py b/tests/unit/test_channels/test_subscriber.py
similarity index 100%
rename from tests/channels/test_subscriber.py
rename to tests/unit/test_channels/test_subscriber.py
diff --git a/tests/channels/util.py b/tests/unit/test_channels/util.py
similarity index 100%
rename from tests/channels/util.py
rename to tests/unit/test_channels/util.py
diff --git a/tests/cli/__init__.py b/tests/unit/test_cli/__init__.py
similarity index 100%
rename from tests/cli/__init__.py
rename to tests/unit/test_cli/__init__.py
diff --git a/tests/cli/conftest.py b/tests/unit/test_cli/conftest.py
similarity index 96%
rename from tests/cli/conftest.py
rename to tests/unit/test_cli/conftest.py
--- a/tests/cli/conftest.py
+++ b/tests/unit/test_cli/conftest.py
@@ -13,7 +13,8 @@
from pytest_mock import MockerFixture
from litestar.cli._utils import _path_to_dotted_path
-from tests.cli import (
+
+from . import (
APP_FILE_CONTENT,
CREATE_APP_FILE_CONTENT,
GENERIC_APP_FACTORY_FILE_CONTENT,
@@ -116,6 +117,11 @@ def mock_uvicorn_run(mocker: MockerFixture) -> MagicMock:
return mocker.patch("uvicorn.run")
[email protected]()
+def mock_subprocess_run(mocker: MockerFixture) -> MagicMock:
+ return mocker.patch("subprocess.run")
+
+
@pytest.fixture
def mock_confirm_ask(mocker: MockerFixture) -> Generator[MagicMock, None, None]:
yield mocker.patch("rich.prompt.Confirm.ask", return_value=True)
diff --git a/tests/cli/test_cli.py b/tests/unit/test_cli/test_cli.py
similarity index 100%
rename from tests/cli/test_cli.py
rename to tests/unit/test_cli/test_cli.py
diff --git a/tests/cli/test_core_commands.py b/tests/unit/test_cli/test_core_commands.py
similarity index 95%
rename from tests/cli/test_core_commands.py
rename to tests/unit/test_cli/test_core_commands.py
--- a/tests/cli/test_core_commands.py
+++ b/tests/unit/test_cli/test_core_commands.py
@@ -12,26 +12,17 @@
from litestar import __version__ as litestar_version
from litestar.cli.main import litestar_group as cli_command
from litestar.exceptions import LitestarWarning
-from tests.cli import (
+
+from . import (
CREATE_APP_FILE_CONTENT,
GENERIC_APP_FACTORY_FILE_CONTENT,
GENERIC_APP_FACTORY_FILE_CONTENT_STRING_ANNOTATION,
)
-from tests.cli.conftest import CreateAppFileFixture
+from .conftest import CreateAppFileFixture
project_base = Path(__file__).parent.parent.parent
[email protected]()
-def mock_subprocess_run(mocker: MockerFixture) -> MagicMock:
- return mocker.patch("litestar.cli.commands.core.subprocess.run")
-
-
[email protected]()
-def mock_uvicorn_run(mocker: MockerFixture) -> MagicMock:
- return mocker.patch("litestar.cli.commands.core.uvicorn.run")
-
-
@pytest.fixture()
def mock_show_app_info(mocker: MockerFixture) -> MagicMock:
return mocker.patch("litestar.cli.commands.core.show_app_info")
diff --git a/tests/cli/test_env_resolution.py b/tests/unit/test_cli/test_env_resolution.py
similarity index 98%
rename from tests/cli/test_env_resolution.py
rename to tests/unit/test_cli/test_env_resolution.py
--- a/tests/cli/test_env_resolution.py
+++ b/tests/unit/test_cli/test_env_resolution.py
@@ -7,7 +7,8 @@
from litestar import Litestar
from litestar.cli._utils import LitestarEnv, _path_to_dotted_path
-from tests.cli.conftest import CreateAppFileFixture
+
+from .conftest import CreateAppFileFixture
@pytest.mark.parametrize("env_name,attr_name", [("LITESTAR_DEBUG", "debug"), ("LITESTAR_RELOAD", "reload")])
diff --git a/tests/cli/test_schema_commands.py b/tests/unit/test_cli/test_schema_commands.py
similarity index 88%
rename from tests/cli/test_schema_commands.py
rename to tests/unit/test_cli/test_schema_commands.py
--- a/tests/cli/test_schema_commands.py
+++ b/tests/unit/test_cli/test_schema_commands.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from json import dumps as json_dumps
from typing import TYPE_CHECKING
@@ -14,7 +16,7 @@
@pytest.mark.parametrize("filename", ("", "custom.json", "custom.yaml", "custom.yml"))
def test_openapi_schema_command(
- runner: "CliRunner", mocker: "MockerFixture", monkeypatch: "MonkeyPatch", filename: str
+ 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")
@@ -40,7 +42,7 @@ def test_openapi_schema_command(
"namespace, filename", (("Custom", ""), ("", "custom_specs.ts"), ("Custom", "custom_specs.ts"))
)
def test_openapi_typescript_command(
- runner: "CliRunner", mocker: "MockerFixture", monkeypatch: "MonkeyPatch", filename: str, namespace: str
+ runner: CliRunner, mocker: MockerFixture, monkeypatch: MonkeyPatch, filename: str, namespace: str
) -> None:
monkeypatch.setenv("LITESTAR_APP", "test_apps.openapi_test_app.main:app")
mock_path_write_text = mocker.patch("pathlib.Path.write_text")
diff --git a/tests/cli/test_session_commands.py b/tests/unit/test_cli/test_session_commands.py
similarity index 100%
rename from tests/cli/test_session_commands.py
rename to tests/unit/test_cli/test_session_commands.py
diff --git a/tests/asgi_router/__init__.py b/tests/unit/test_connection/__init__.py
similarity index 100%
rename from tests/asgi_router/__init__.py
rename to tests/unit/test_connection/__init__.py
diff --git a/tests/connection/test_base_properties.py b/tests/unit/test_connection/test_base.py
similarity index 100%
rename from tests/connection/test_base_properties.py
rename to tests/unit/test_connection/test_base.py
diff --git a/tests/connection/request/test_request.py b/tests/unit/test_connection/test_request.py
similarity index 94%
rename from tests/connection/request/test_request.py
rename to tests/unit/test_connection/test_request.py
--- a/tests/connection/request/test_request.py
+++ b/tests/unit/test_connection/test_request.py
@@ -9,11 +9,11 @@
import pytest
-from litestar import MediaType, get
+from litestar import MediaType, Request, get
from litestar.connection.base import empty_send
-from litestar.connection.request import Request
from litestar.datastructures import Address, Cookie
from litestar.exceptions import InternalServerException, SerializationException
+from litestar.middleware import MiddlewareProtocol
from litestar.response.base import ASGIResponse
from litestar.serialization import encode_json, encode_msgpack
from litestar.static_files.config import StaticFilesConfig
@@ -22,7 +22,7 @@
if TYPE_CHECKING:
from pathlib import Path
- from litestar.types import Receive, Scope, Send
+ from litestar.types import ASGIApp, Receive, Scope, Send
async def test_request_empty_body_to_json(anyio_backend: str) -> None:
@@ -457,3 +457,28 @@ async def app(scope: "Scope", receive: "Receive", send: "Send") -> None:
client = TestClient(app)
response = client.get("/")
assert response.json() == {"json": "Send channel not available"}
+
+
+class BeforeRequestMiddleWare(MiddlewareProtocol):
+ def __init__(self, app: "ASGIApp") -> None:
+ self.app = app
+
+ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
+ scope["state"]["main"] = 1
+ await self.app(scope, receive, send)
+
+
+def test_state() -> None:
+ def before_request(request: Request) -> None:
+ assert request.state.main == 1
+ request.state.main = 2
+
+ @get(path="/")
+ async def get_state(request: Request) -> Dict[str, str]:
+ return {"state": request.state.main}
+
+ with create_test_client(
+ route_handlers=[get_state], middleware=[BeforeRequestMiddleWare], before_request=before_request
+ ) as client:
+ response = client.get("/")
+ assert response.json() == {"state": 2}
diff --git a/tests/connection/test_websocket.py b/tests/unit/test_connection/test_websocket.py
similarity index 62%
rename from tests/connection/test_websocket.py
rename to tests/unit/test_connection/test_websocket.py
--- a/tests/connection/test_websocket.py
+++ b/tests/unit/test_connection/test_websocket.py
@@ -85,52 +85,49 @@ async def handler(socket: MyWebSocket) -> None:
def test_websocket_url() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- await websocket.send_json({"url": str(websocket.url)})
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ await socket.send_json({"url": str(socket.url)})
+ await socket.close()
- with TestClient(app).websocket_connect("/123?a=abc") as websocket:
- data = websocket.receive_json()
- assert data == {"url": "ws://testserver/123?a=abc"}
+ with TestClient(app).websocket_connect("/123?a=abc") as ws:
+ assert ws.receive_json() == {"url": "ws://testserver/123?a=abc"}
def test_websocket_binary_json() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- message = await websocket.receive_json(mode="binary")
- await websocket.send_json(message, mode="binary")
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ message = await socket.receive_json(mode="binary")
+ await socket.send_json(message, mode="binary")
+ await socket.close()
- with TestClient(app).websocket_connect("/123?a=abc") as websocket:
- websocket.send_json({"test": "data"}, mode="binary")
- data = websocket.receive_json(mode="binary")
- assert data == {"test": "data"}
+ with TestClient(app).websocket_connect("/123?a=abc") as ws:
+ ws.send_json({"test": "data"}, mode="binary")
+ assert ws.receive_json(mode="binary") == {"test": "data"}
def test_websocket_query_params() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- query_params = dict(websocket.query_params)
- await websocket.accept()
- await websocket.send_json({"params": query_params})
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ query_params = dict(socket.query_params)
+ await socket.accept()
+ await socket.send_json({"params": query_params})
+ await socket.close()
- with TestClient(app).websocket_connect("/?a=abc&b=456") as websocket:
- data = websocket.receive_json()
- assert data == {"params": {"a": "abc", "b": "456"}}
+ with TestClient(app).websocket_connect("/?a=abc&b=456") as ws:
+ assert ws.receive_json() == {"params": {"a": "abc", "b": "456"}}
def test_websocket_headers() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- headers = dict(websocket.headers)
- await websocket.accept()
- await websocket.send_json({"headers": headers})
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ headers = dict(socket.headers)
+ await socket.accept()
+ await socket.send_json({"headers": headers})
+ await socket.close()
- with TestClient(app).websocket_connect("/") as websocket:
+ with TestClient(app).websocket_connect("/") as ws:
expected_headers = {
"accept": "*/*",
"accept-encoding": "gzip, deflate, br",
@@ -140,62 +137,57 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
"sec-websocket-key": "testserver==",
"sec-websocket-version": "13",
}
- data = websocket.receive_json()
- assert data == {"headers": expected_headers}
+ assert ws.receive_json() == {"headers": expected_headers}
def test_websocket_port() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- await websocket.send_json({"port": websocket.url.port})
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ await socket.send_json({"port": socket.url.port})
+ await socket.close()
- with TestClient(app).websocket_connect("ws://example.com:123/123?a=abc") as websocket:
- data = websocket.receive_json()
- assert data == {"port": 123}
+ with TestClient(app).websocket_connect("ws://example.com:123/123?a=abc") as ws:
+ assert ws.receive_json() == {"port": 123}
def test_websocket_send_and_receive_text() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- data = await websocket.receive_text()
- await websocket.send_text("Message was: " + data)
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ data = await socket.receive_text()
+ await socket.send_text("Message was: " + data)
+ await socket.close()
- with TestClient(app).websocket_connect("/") as websocket:
- websocket.send_text("Hello, world!")
- data = websocket.receive_text()
- assert data == "Message was: Hello, world!"
+ with TestClient(app).websocket_connect("/") as ws:
+ ws.send_text("Hello, world!")
+ assert ws.receive_text() == "Message was: Hello, world!"
def test_websocket_send_and_receive_bytes() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- data = await websocket.receive_bytes()
- await websocket.send_bytes(b"Message was: " + data)
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ data = await socket.receive_bytes()
+ await socket.send_bytes(b"Message was: " + data)
+ await socket.close()
- with TestClient(app).websocket_connect("/") as websocket:
- websocket.send_bytes(b"Hello, world!")
- data = websocket.receive_bytes()
- assert data == b"Message was: Hello, world!"
+ with TestClient(app).websocket_connect("/") as ws:
+ ws.send_bytes(b"Hello, world!")
+ assert ws.receive_bytes() == b"Message was: Hello, world!"
def test_websocket_send_and_receive_json() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- data = await websocket.receive_json()
- await websocket.send_json({"message": data})
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ data = await socket.receive_json()
+ await socket.send_json({"message": data})
+ await socket.close()
- with TestClient(app).websocket_connect("/") as websocket:
- websocket.send_json({"hello": "world"})
- data = websocket.receive_json()
- assert data == {"message": {"hello": "world"}}
+ with TestClient(app).websocket_connect("/") as ws:
+ ws.send_json({"hello": "world"})
+ assert ws.receive_json() == {"message": {"hello": "world"}}
def test_send_msgpack() -> None:
@@ -295,27 +287,27 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
def test_websocket_concurrency_pattern() -> None:
stream_send, stream_receive = anyio.create_memory_object_stream()
- async def reader(websocket: WebSocket[Any, Any, Any]) -> None:
+ async def reader(socket: WebSocket[Any, Any, Any]) -> None:
async with stream_send:
- data = await websocket.receive_json()
- await stream_send.send(data)
+ json_data = await socket.receive_json()
+ await stream_send.send(json_data)
- async def writer(websocket: WebSocket[Any, Any, Any]) -> None:
+ async def writer(socket: WebSocket[Any, Any, Any]) -> None:
async with stream_receive:
async for message in stream_receive:
- await websocket.send_json(message)
+ await socket.send_json(message)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
async with anyio.create_task_group() as task_group:
- task_group.start_soon(reader, websocket)
- await writer(websocket)
- await websocket.close()
+ task_group.start_soon(reader, socket)
+ await writer(socket)
+ await socket.close()
- with TestClient(app).websocket_connect("/") as websocket:
- websocket.send_json({"hello": "world"})
- data = websocket.receive_json()
+ with TestClient(app).websocket_connect("/") as ws:
+ ws.send_json({"hello": "world"})
+ data = ws.receive_json()
assert data == {"hello": "world"}
@@ -324,33 +316,33 @@ def test_client_close() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
nonlocal close_code
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
try:
- await websocket.receive_text()
+ await socket.receive_text()
except WebSocketException as exc:
close_code = exc.code
- with TestClient(app).websocket_connect("/") as websocket:
- websocket.close(code=WS_1001_GOING_AWAY)
+ with TestClient(app).websocket_connect("/") as ws:
+ ws.close(code=WS_1001_GOING_AWAY)
assert close_code == WS_1001_GOING_AWAY
def test_application_close() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- await websocket.close(WS_1001_GOING_AWAY)
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ await socket.close(WS_1001_GOING_AWAY)
- with TestClient(app).websocket_connect("/") as websocket, pytest.raises(WebSocketDisconnect) as exc:
- websocket.receive_text()
+ with TestClient(app).websocket_connect("/") as ws, pytest.raises(WebSocketDisconnect) as exc:
+ ws.receive_text()
assert exc.value.code == WS_1001_GOING_AWAY
def test_rejected_connection() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.close(WS_1001_GOING_AWAY)
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.close(WS_1001_GOING_AWAY)
with pytest.raises(WebSocketDisconnect) as exc, TestClient(app).websocket_connect("/"):
pass
@@ -359,20 +351,20 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
def test_subprotocol() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- assert websocket.scope["subprotocols"] == ["soap", "wamp"]
- await websocket.accept(subprotocols="wamp")
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ assert socket.scope["subprotocols"] == ["soap", "wamp"]
+ await socket.accept(subprotocols="wamp")
+ await socket.close()
- with TestClient(app).websocket_connect("/", subprotocols=["soap", "wamp"]) as websocket:
- assert websocket.accepted_subprotocol == "wamp"
+ with TestClient(app).websocket_connect("/", subprotocols=["soap", "wamp"]) as ws:
+ assert ws.accepted_subprotocol == "wamp"
def test_additional_headers() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept(headers=[(b"additional", b"header")])
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept(headers=[(b"additional", b"header")])
+ await socket.close()
with TestClient(app).websocket_connect("/") as websocket:
assert websocket.extra_headers == [(b"additional", b"header")]
@@ -380,12 +372,12 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
def test_no_additional_headers() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- await websocket.close()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ await socket.close()
- with TestClient(app).websocket_connect("/") as websocket:
- assert websocket.extra_headers == []
+ with TestClient(app).websocket_connect("/") as ws:
+ assert ws.extra_headers == []
def test_websocket_exception() -> None:
@@ -398,11 +390,11 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
def test_duplicate_disconnect() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- message = await websocket.receive()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ message = await socket.receive()
assert message["type"] == "websocket.disconnect"
- message = await websocket.receive()
+ await socket.receive()
with pytest.raises(WebSocketException), TestClient(app).websocket_connect("/") as websocket:
websocket.close()
@@ -410,20 +402,20 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
def test_websocket_close_reason() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.accept()
- await websocket.close(code=WS_1001_GOING_AWAY, reason="Going Away")
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.accept()
+ await socket.close(code=WS_1001_GOING_AWAY, reason="Going Away")
- with TestClient(app).websocket_connect("/") as websocket, pytest.raises(WebSocketDisconnect) as exc:
- websocket.receive_text()
+ with TestClient(app).websocket_connect("/") as ws, pytest.raises(WebSocketDisconnect) as exc:
+ ws.receive_text()
assert exc.value.code == WS_1001_GOING_AWAY
assert exc.value.detail == "Going Away"
def test_receive_text_before_accept() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.receive_text()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.receive_text()
with pytest.raises(WebSocketException), TestClient(app).websocket_connect("/"):
pass
@@ -431,8 +423,8 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
def test_receive_bytes_before_accept() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.receive_bytes()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.receive_bytes()
with pytest.raises(WebSocketException), TestClient(app).websocket_connect("/"):
pass
@@ -440,8 +432,8 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
def test_receive_json_before_accept() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
- websocket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
- await websocket.receive_json()
+ socket = WebSocket[Any, Any, Any](scope, receive=receive, send=send)
+ await socket.receive_json()
with pytest.raises(WebSocketException), TestClient(app).websocket_connect("/"):
pass
diff --git a/tests/asgi_router/routing_trie/__init__.py b/tests/unit/test_contrib/__init__.py
similarity index 100%
rename from tests/asgi_router/routing_trie/__init__.py
rename to tests/unit/test_contrib/__init__.py
diff --git a/tests/contrib/conftest.py b/tests/unit/test_contrib/conftest.py
similarity index 100%
rename from tests/contrib/conftest.py
rename to tests/unit/test_contrib/conftest.py
diff --git a/tests/channels/__init__.py b/tests/unit/test_contrib/test_htmx/__init__.py
similarity index 100%
rename from tests/channels/__init__.py
rename to tests/unit/test_contrib/test_htmx/__init__.py
diff --git a/tests/contrib/htmx/test_htmx_request.py b/tests/unit/test_contrib/test_htmx/test_htmx_request.py
similarity index 100%
rename from tests/contrib/htmx/test_htmx_request.py
rename to tests/unit/test_contrib/test_htmx/test_htmx_request.py
diff --git a/tests/contrib/htmx/test_htmx_response.py b/tests/unit/test_contrib/test_htmx/test_htmx_response.py
similarity index 94%
rename from tests/contrib/htmx/test_htmx_response.py
rename to tests/unit/test_contrib/test_htmx/test_htmx_response.py
--- a/tests/contrib/htmx/test_htmx_response.py
+++ b/tests/unit/test_contrib/test_htmx/test_htmx_response.py
@@ -245,8 +245,8 @@ def handler() -> HXLocation:
),
),
)
-def test_HTMXTemplate_response_success(engine: Any, template: str, expected: str, template_dir: Path) -> None:
- Path(template_dir / "abc.html").write_text(template)
+def test_HTMXTemplate_response_success(engine: Any, template: str, expected: str, tmp_path: Path) -> None:
+ Path(tmp_path / "abc.html").write_text(template)
@get(path="/")
def handler() -> HTMXTemplate:
@@ -264,7 +264,7 @@ def handler() -> HTMXTemplate:
with create_test_client(
route_handlers=[handler],
template_config=TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=engine,
),
) as client:
@@ -283,8 +283,8 @@ def handler() -> HTMXTemplate:
(MakoTemplateEngine, "path: ${request.scope['path']}", "path: /"),
),
)
-def test_HTMXTemplate_response_no_params(engine: Any, template: str, expected: str, template_dir: Path) -> None:
- Path(template_dir / "abc.html").write_text(template)
+def test_HTMXTemplate_response_no_params(engine: Any, template: str, expected: str, tmp_path: Path) -> None:
+ Path(tmp_path / "abc.html").write_text(template)
@get(path="/")
def handler() -> HTMXTemplate:
@@ -296,7 +296,7 @@ def handler() -> HTMXTemplate:
with create_test_client(
route_handlers=[handler],
template_config=TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=engine,
),
) as client:
@@ -315,10 +315,8 @@ def handler() -> HTMXTemplate:
(MakoTemplateEngine, "path: ${request.scope['path']}", "path: /"),
),
)
-def test_HTMXTemplate_response_push_url_set_to_false(
- engine: Any, template: str, expected: str, template_dir: Path
-) -> None:
- Path(template_dir / "abc.html").write_text(template)
+def test_HTMXTemplate_response_push_url_set_to_false(engine: Any, template: str, expected: str, tmp_path: Path) -> None:
+ Path(tmp_path / "abc.html").write_text(template)
@get(path="/")
def handler() -> HTMXTemplate:
@@ -331,7 +329,7 @@ def handler() -> HTMXTemplate:
with create_test_client(
route_handlers=[handler],
template_config=TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=engine,
),
) as client:
@@ -350,10 +348,8 @@ def handler() -> HTMXTemplate:
(MakoTemplateEngine, "path: ${request.scope['path']}", "path: /"),
),
)
-def test_htmx_template_response_bad_trigger_params(
- engine: Any, template: str, expected: str, template_dir: Path
-) -> None:
- Path(template_dir / "abc.html").write_text(template)
+def test_htmx_template_response_bad_trigger_params(engine: Any, template: str, expected: str, tmp_path: Path) -> None:
+ Path(tmp_path / "abc.html").write_text(template)
@get(path="/")
def handler() -> HTMXTemplate:
@@ -368,7 +364,7 @@ def handler() -> HTMXTemplate:
with create_test_client(
route_handlers=[handler],
template_config=TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=engine,
),
) as client:
diff --git a/tests/compatibility/__init__.py b/tests/unit/test_contrib/test_jwt/__init__.py
similarity index 100%
rename from tests/compatibility/__init__.py
rename to tests/unit/test_contrib/test_jwt/__init__.py
diff --git a/tests/contrib/jwt/test_auth.py b/tests/unit/test_contrib/test_jwt/test_auth.py
similarity index 99%
rename from tests/contrib/jwt/test_auth.py
rename to tests/unit/test_contrib/test_jwt/test_auth.py
--- a/tests/contrib/jwt/test_auth.py
+++ b/tests/unit/test_contrib/test_jwt/test_auth.py
@@ -11,12 +11,17 @@
from litestar import Litestar, Request, Response, get
from litestar.contrib.jwt import JWTAuth, JWTCookieAuth, OAuth2PasswordBearerAuth, Token
from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_401_UNAUTHORIZED
+from litestar.stores.memory import MemoryStore
from litestar.testing import create_test_client
from tests import User, UserFactory
if TYPE_CHECKING:
from litestar.connection import ASGIConnection
- from litestar.stores.memory import MemoryStore
+
+
[email protected](scope="module")
+def mock_db() -> MemoryStore:
+ return MemoryStore()
@given(
diff --git a/tests/contrib/jwt/test_token.py b/tests/unit/test_contrib/test_jwt/test_token.py
similarity index 100%
rename from tests/contrib/jwt/test_token.py
rename to tests/unit/test_contrib/test_jwt/test_token.py
diff --git a/tests/contrib/test_msgspec.py b/tests/unit/test_contrib/test_msgspec.py
similarity index 92%
rename from tests/contrib/test_msgspec.py
rename to tests/unit/test_contrib/test_msgspec.py
--- a/tests/contrib/test_msgspec.py
+++ b/tests/unit/test_contrib/test_msgspec.py
@@ -27,7 +27,7 @@ class TestStruct(Struct):
field_defs = list(MsgspecDTO.generate_field_definitions(TestStruct))
assert (
field_defs[0].unique_model_name
- == "tests.contrib.test_msgspec.test_field_definition_generation.<locals>.TestStruct"
+ == "tests.unit.test_contrib.test_msgspec.test_field_definition_generation.<locals>.TestStruct"
)
for field_def, exp in zip(field_defs, expected_field_defs):
assert field_def == exp
diff --git a/tests/contrib/open_telemetry/test_open_telemetry_middleware.py b/tests/unit/test_contrib/test_opentelemetry.py
similarity index 100%
rename from tests/contrib/open_telemetry/test_open_telemetry_middleware.py
rename to tests/unit/test_contrib/test_opentelemetry.py
diff --git a/tests/contrib/test_pydantic.py b/tests/unit/test_contrib/test_pydantic.py
similarity index 95%
rename from tests/contrib/test_pydantic.py
rename to tests/unit/test_contrib/test_pydantic.py
--- a/tests/contrib/test_pydantic.py
+++ b/tests/unit/test_contrib/test_pydantic.py
@@ -28,7 +28,7 @@ class TestModel(BaseModel):
field_defs = list(PydanticDTO.generate_field_definitions(TestModel))
assert (
field_defs[0].unique_model_name
- == "tests.contrib.test_pydantic.test_field_definition_generation.<locals>.TestModel"
+ == "tests.unit.test_contrib.test_pydantic.test_field_definition_generation.<locals>.TestModel"
)
for field_def, exp in zip(field_defs, expected_field_defs):
assert field_def == exp
diff --git a/tests/contrib/repository/test_handlers.py b/tests/unit/test_contrib/test_repository.py
similarity index 100%
rename from tests/contrib/repository/test_handlers.py
rename to tests/unit/test_contrib/test_repository.py
diff --git a/tests/connection/__init__.py b/tests/unit/test_contrib/test_sqlalchemy/__init__.py
similarity index 100%
rename from tests/connection/__init__.py
rename to tests/unit/test_contrib/test_sqlalchemy/__init__.py
diff --git a/tests/contrib/sqlalchemy/models_bigint.py b/tests/unit/test_contrib/test_sqlalchemy/models_bigint.py
similarity index 100%
rename from tests/contrib/sqlalchemy/models_bigint.py
rename to tests/unit/test_contrib/test_sqlalchemy/models_bigint.py
diff --git a/tests/contrib/sqlalchemy/models_uuid.py b/tests/unit/test_contrib/test_sqlalchemy/models_uuid.py
similarity index 100%
rename from tests/contrib/sqlalchemy/models_uuid.py
rename to tests/unit/test_contrib/test_sqlalchemy/models_uuid.py
diff --git a/tests/contrib/sqlalchemy/test_dto.py b/tests/unit/test_contrib/test_sqlalchemy/test_dto.py
similarity index 100%
rename from tests/contrib/sqlalchemy/test_dto.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_dto.py
diff --git a/tests/contrib/sqlalchemy/test_dto_integration.py b/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
similarity index 100%
rename from tests/contrib/sqlalchemy/test_dto_integration.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
diff --git a/tests/contrib/__init__.py b/tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/__init__.py
similarity index 100%
rename from tests/contrib/__init__.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/__init__.py
diff --git a/tests/contrib/sqlalchemy/init_plugin/config/test_asyncio.py b/tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_asyncio.py
similarity index 100%
rename from tests/contrib/sqlalchemy/init_plugin/config/test_asyncio.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_asyncio.py
diff --git a/tests/contrib/sqlalchemy/init_plugin/config/test_common.py b/tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_common.py
similarity index 100%
rename from tests/contrib/sqlalchemy/init_plugin/config/test_common.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_common.py
diff --git a/tests/contrib/sqlalchemy/init_plugin/config/test_engine.py b/tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_engine.py
similarity index 100%
rename from tests/contrib/sqlalchemy/init_plugin/config/test_engine.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_engine.py
diff --git a/tests/contrib/sqlalchemy/init_plugin/config/test_sync.py b/tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_sync.py
similarity index 100%
rename from tests/contrib/sqlalchemy/init_plugin/config/test_sync.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_sync.py
diff --git a/tests/contrib/htmx/__init__.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/__init__.py
similarity index 100%
rename from tests/contrib/htmx/__init__.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/__init__.py
diff --git a/tests/contrib/sqlalchemy/repository/conftest.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/conftest.py
similarity index 97%
rename from tests/contrib/sqlalchemy/repository/conftest.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/conftest.py
--- a/tests/contrib/sqlalchemy/repository/conftest.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/conftest.py
@@ -12,8 +12,6 @@
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import Session, sessionmaker
-from tests.contrib.sqlalchemy.repository.helpers import mark_requires_docker
-
if TYPE_CHECKING:
from pytest import MonkeyPatch
@@ -283,8 +281,8 @@ def spanner_engine(docker_ip: str, spanner_service: None, monkeypatch: MonkeyPat
@pytest.fixture(
params=[
pytest.param("duckdb_engine", marks=[pytest.mark.sqlalchemy_duckdb, pytest.mark.sqlalchemy_integration]),
- pytest.param("oracle_engine", marks=[pytest.mark.sqlalchemy_oracledb, *mark_requires_docker]),
- pytest.param("psycopg_engine", marks=[pytest.mark.sqlalchemy_psycopg_sync, *mark_requires_docker]),
+ pytest.param("oracle_engine", marks=[pytest.mark.sqlalchemy_oracledb, pytest.mark.sqlalchemy_integration]),
+ pytest.param("psycopg_engine", marks=[pytest.mark.sqlalchemy_psycopg_sync, pytest.mark.sqlalchemy_integration]),
pytest.param("sqlite_engine", marks=pytest.mark.sqlalchemy_sqlite),
]
)
@@ -391,9 +389,11 @@ async def psycopg_async_engine(docker_ip: str, postgres_service: None) -> AsyncE
@pytest.fixture(
params=[
pytest.param("aiosqlite_engine", marks=pytest.mark.sqlalchemy_aiosqlite),
- pytest.param("asyncmy_engine", marks=[pytest.mark.sqlalchemy_asyncmy, *mark_requires_docker]),
- pytest.param("asyncpg_engine", marks=[pytest.mark.sqlalchemy_asyncpg, *mark_requires_docker]),
- pytest.param("psycopg_async_engine", marks=[pytest.mark.sqlalchemy_psycopg_async, *mark_requires_docker]),
+ pytest.param("asyncmy_engine", marks=[pytest.mark.sqlalchemy_asyncmy, pytest.mark.sqlalchemy_integration]),
+ pytest.param("asyncpg_engine", marks=[pytest.mark.sqlalchemy_asyncpg, pytest.mark.sqlalchemy_integration]),
+ pytest.param(
+ "psycopg_async_engine", marks=[pytest.mark.sqlalchemy_psycopg_async, pytest.mark.sqlalchemy_integration]
+ ),
]
)
def async_engine(request: FixtureRequest) -> AsyncEngine:
diff --git a/tests/contrib/sqlalchemy/repository/helpers.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/helpers.py
similarity index 86%
rename from tests/contrib/sqlalchemy/repository/helpers.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/helpers.py
--- a/tests/contrib/sqlalchemy/repository/helpers.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/helpers.py
@@ -1,12 +1,9 @@
from __future__ import annotations
import inspect
-import sys
from datetime import datetime, timezone
from typing import Any, Awaitable, TypeVar, cast, overload
-import pytest
-
T = TypeVar("T")
@@ -38,9 +35,3 @@ def update_raw_records(raw_authors: list[dict[str, Any]], raw_rules: list[dict[s
for raw_rule in raw_rules:
raw_rule["created_at"] = datetime.strptime(raw_rule["created_at"], "%Y-%m-%dT%H:%M:%S").astimezone(timezone.utc)
raw_rule["updated_at"] = datetime.strptime(raw_rule["updated_at"], "%Y-%m-%dT%H:%M:%S").astimezone(timezone.utc)
-
-
-mark_requires_docker = [
- pytest.mark.sqlalchemy_integration,
- pytest.mark.skipif(sys.platform != "linux", reason="docker not available on this platform"),
-]
diff --git a/tests/contrib/sqlalchemy/repository/test_abc.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_abc.py
similarity index 100%
rename from tests/contrib/sqlalchemy/repository/test_abc.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/test_abc.py
diff --git a/tests/contrib/sqlalchemy/repository/test_generic_mock_async_repository.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_generic_mock_async_repository.py
similarity index 99%
rename from tests/contrib/sqlalchemy/repository/test_generic_mock_async_repository.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/test_generic_mock_async_repository.py
--- a/tests/contrib/sqlalchemy/repository/test_generic_mock_async_repository.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_generic_mock_async_repository.py
@@ -7,11 +7,9 @@
from sqlalchemy.orm import Mapped, mapped_column
from litestar.contrib.repository.exceptions import ConflictError, RepositoryError
-from litestar.contrib.repository.testing.generic_mock_repository import (
- GenericAsyncMockRepository,
-)
+from litestar.contrib.repository.testing.generic_mock_repository import GenericAsyncMockRepository
from litestar.contrib.sqlalchemy import base
-from tests.contrib.sqlalchemy.models_uuid import UUIDAuthor, UUIDBook
+from tests.unit.test_contrib.test_sqlalchemy.models_uuid import UUIDAuthor, UUIDBook
@pytest.fixture(name="authors")
diff --git a/tests/contrib/sqlalchemy/repository/test_generic_mock_sync_repository.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_generic_mock_sync_repository.py
similarity index 99%
rename from tests/contrib/sqlalchemy/repository/test_generic_mock_sync_repository.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/test_generic_mock_sync_repository.py
--- a/tests/contrib/sqlalchemy/repository/test_generic_mock_sync_repository.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_generic_mock_sync_repository.py
@@ -11,7 +11,7 @@
GenericSyncMockRepository,
)
from litestar.contrib.sqlalchemy import base
-from tests.contrib.sqlalchemy.models_uuid import UUIDAuthor, UUIDBook
+from tests.unit.test_contrib.test_sqlalchemy.models_uuid import UUIDAuthor, UUIDBook
@pytest.fixture(name="authors")
diff --git a/tests/contrib/sqlalchemy/repository/test_repo_bigint.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
similarity index 99%
rename from tests/contrib/sqlalchemy/repository/test_repo_bigint.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
--- a/tests/contrib/sqlalchemy/repository/test_repo_bigint.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
@@ -14,7 +14,7 @@
from litestar.contrib.repository.exceptions import RepositoryError
from litestar.contrib.repository.filters import BeforeAfter, CollectionFilter, OrderBy, SearchFilter
from litestar.contrib.sqlalchemy import base
-from tests.contrib.sqlalchemy.models_bigint import (
+from tests.unit.test_contrib.test_sqlalchemy.models_bigint import (
AuthorAsyncRepository,
AuthorSyncRepository,
BigIntAuthor,
@@ -25,7 +25,8 @@
RuleAsyncRepository,
RuleSyncRepository,
)
-from tests.contrib.sqlalchemy.repository.helpers import maybe_async, update_raw_records
+
+from .helpers import maybe_async, update_raw_records
@pytest.fixture()
diff --git a/tests/contrib/sqlalchemy/repository/test_repo_uuid.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
similarity index 98%
rename from tests/contrib/sqlalchemy/repository/test_repo_uuid.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
--- a/tests/contrib/sqlalchemy/repository/test_repo_uuid.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
@@ -19,7 +19,7 @@
from litestar.contrib.repository.exceptions import RepositoryError
from litestar.contrib.repository.filters import BeforeAfter, CollectionFilter, OrderBy, SearchFilter
from litestar.contrib.sqlalchemy import base
-from tests.contrib.sqlalchemy.models_uuid import (
+from tests.unit.test_contrib.test_sqlalchemy.models_uuid import (
AuthorAsyncRepository,
AuthorSyncRepository,
BookAsyncRepository,
@@ -31,16 +31,16 @@
UUIDRule,
)
-from .helpers import mark_requires_docker, maybe_async, update_raw_records
+from .helpers import maybe_async, update_raw_records
@pytest.fixture(
params=[
pytest.param("sqlite_engine", marks=pytest.mark.sqlalchemy_sqlite),
- pytest.param("duckdb_engine", marks=[pytest.mark.sqlalchemy_duckdb, *mark_requires_docker]),
- pytest.param("oracle_engine", marks=[pytest.mark.sqlalchemy_oracledb, *mark_requires_docker]),
- pytest.param("psycopg_engine", marks=[pytest.mark.sqlalchemy_psycopg_sync, *mark_requires_docker]),
- pytest.param("spanner_engine", marks=[pytest.mark.sqlalchemy_spanner, *mark_requires_docker]),
+ pytest.param("duckdb_engine", marks=[pytest.mark.sqlalchemy_duckdb, pytest.mark.sqlalchemy_integration]),
+ pytest.param("oracle_engine", marks=[pytest.mark.sqlalchemy_oracledb, pytest.mark.sqlalchemy_integration]),
+ pytest.param("psycopg_engine", marks=[pytest.mark.sqlalchemy_psycopg_sync, pytest.mark.sqlalchemy_integration]),
+ pytest.param("spanner_engine", marks=[pytest.mark.sqlalchemy_spanner, pytest.mark.sqlalchemy_integration]),
]
)
def engine(request: FixtureRequest) -> Engine:
diff --git a/tests/contrib/sqlalchemy/repository/test_sqlalchemy_async.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
similarity index 100%
rename from tests/contrib/sqlalchemy/repository/test_sqlalchemy_async.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
diff --git a/tests/contrib/sqlalchemy/repository/test_sqlalchemy_oracledb_json.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_oracledb_json.py
similarity index 77%
rename from tests/contrib/sqlalchemy/repository/test_sqlalchemy_oracledb_json.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_oracledb_json.py
--- a/tests/contrib/sqlalchemy/repository/test_sqlalchemy_oracledb_json.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_oracledb_json.py
@@ -2,19 +2,16 @@
from __future__ import annotations
import platform
-import sys
import pytest
from sqlalchemy import Engine
from sqlalchemy.dialects import oracle
from sqlalchemy.schema import CreateTable
-from tests.contrib.sqlalchemy.models_uuid import UUIDEventLog
+from tests.unit.test_contrib.test_sqlalchemy.models_uuid import UUIDEventLog
pytestmark = [
- pytest.mark.skipif(sys.platform != "linux", reason="docker not available on this platform"),
pytest.mark.skipif(platform.uname()[4] != "x86_64", reason="oracle not available on this platform"),
- pytest.mark.sqlalchemy_integration,
]
diff --git a/tests/contrib/sqlalchemy/repository/test_sqlalchemy_sync.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
similarity index 100%
rename from tests/contrib/sqlalchemy/repository/test_sqlalchemy_sync.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
diff --git a/tests/contrib/sqlalchemy/test_serialization_plugin.py b/tests/unit/test_contrib/test_sqlalchemy/test_serialization_plugin.py
similarity index 100%
rename from tests/contrib/sqlalchemy/test_serialization_plugin.py
rename to tests/unit/test_contrib/test_sqlalchemy/test_serialization_plugin.py
diff --git a/tests/test_controller.py b/tests/unit/test_controller.py
similarity index 100%
rename from tests/test_controller.py
rename to tests/unit/test_controller.py
diff --git a/tests/test_data_extractors.py b/tests/unit/test_data_extractors.py
similarity index 100%
rename from tests/test_data_extractors.py
rename to tests/unit/test_data_extractors.py
diff --git a/tests/datastructures/__init_.py b/tests/unit/test_datastructures/__init_.py
similarity index 100%
rename from tests/datastructures/__init_.py
rename to tests/unit/test_datastructures/__init_.py
diff --git a/tests/datastructures/test_cookie.py b/tests/unit/test_datastructures/test_cookie.py
similarity index 100%
rename from tests/datastructures/test_cookie.py
rename to tests/unit/test_datastructures/test_cookie.py
diff --git a/tests/datastructures/test_headers.py b/tests/unit/test_datastructures/test_headers.py
similarity index 100%
rename from tests/datastructures/test_headers.py
rename to tests/unit/test_datastructures/test_headers.py
diff --git a/tests/datastructures/test_multi_dicts.py b/tests/unit/test_datastructures/test_multi_dicts.py
similarity index 100%
rename from tests/datastructures/test_multi_dicts.py
rename to tests/unit/test_datastructures/test_multi_dicts.py
diff --git a/tests/unit/test_datastructures/test_response_header.py b/tests/unit/test_datastructures/test_response_header.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/test_datastructures/test_response_header.py
@@ -0,0 +1,10 @@
+import pytest
+
+from litestar.datastructures import ResponseHeader
+from litestar.exceptions import ImproperlyConfiguredException
+
+
+def test_response_headers_validation() -> None:
+ ResponseHeader(name="test", documentation_only=True)
+ with pytest.raises(ImproperlyConfiguredException):
+ ResponseHeader(name="test")
diff --git a/tests/datastructures/test_state.py b/tests/unit/test_datastructures/test_state.py
similarity index 100%
rename from tests/datastructures/test_state.py
rename to tests/unit/test_datastructures/test_state.py
diff --git a/tests/datastructures/test_upload_file.py b/tests/unit/test_datastructures/test_upload_file.py
similarity index 100%
rename from tests/datastructures/test_upload_file.py
rename to tests/unit/test_datastructures/test_upload_file.py
diff --git a/tests/datastructures/test_url.py b/tests/unit/test_datastructures/test_url.py
similarity index 100%
rename from tests/datastructures/test_url.py
rename to tests/unit/test_datastructures/test_url.py
diff --git a/tests/unit/test_di.py b/tests/unit/test_di.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/test_di.py
@@ -0,0 +1,147 @@
+from functools import partial
+from typing import Any, AsyncGenerator, Generator
+
+import pytest
+
+from litestar.di import Provide
+from litestar.exceptions import ImproperlyConfiguredException, LitestarWarning
+from litestar.types import Empty
+
+
+def generator_func() -> Generator[float, None, None]:
+ yield 0.1
+
+
+async def async_generator_func() -> AsyncGenerator[float, None]:
+ yield 0.1
+
+
+async def async_callable(val: str = "three-one") -> str:
+ return val
+
+
+def sync_callable(val: str = "three-one") -> str:
+ return val
+
+
+async_partial = partial(async_callable, "why-three-and-one")
+sync_partial = partial(sync_callable, "why-three-and-one")
+
+
+class C:
+ val = 31
+
+ def __init__(self) -> None:
+ self.val = 13
+
+ @classmethod
+ async def async_class(cls) -> int:
+ return cls.val
+
+ @classmethod
+ def sync_class(cls) -> int:
+ return cls.val
+
+ @staticmethod
+ async def async_static() -> str:
+ return "one-three"
+
+ @staticmethod
+ def sync_static() -> str:
+ return "one-three"
+
+ async def async_instance(self) -> int:
+ return self.val
+
+ def sync_instance(self) -> int:
+ return self.val
+
+
+async def test_provide_default(anyio_backend: str) -> None:
+ provider = Provide(dependency=async_callable)
+ value = await provider()
+ assert value == "three-one"
+
+
+async def test_provide_cached(anyio_backend: str) -> None:
+ provider = Provide(dependency=async_callable, use_cache=True)
+ assert provider.value is Empty
+ value = await provider()
+ assert value == "three-one"
+ assert provider.value == value
+ second_value = await provider()
+ assert value == second_value
+ third_value = await provider()
+ assert value == third_value
+
+
+async def test_run_in_thread(anyio_backend: str) -> None:
+ provider = Provide(dependency=sync_callable, sync_to_thread=True)
+ value = await provider()
+ assert value == "three-one"
+
+
+def test_provider_equality_check() -> None:
+ first_provider = Provide(dependency=sync_callable, sync_to_thread=False)
+ second_provider = Provide(dependency=sync_callable, sync_to_thread=False)
+ assert first_provider == second_provider
+ third_provider = Provide(dependency=sync_callable, use_cache=True, sync_to_thread=False)
+ assert first_provider != third_provider
+ second_provider.value = True
+ assert first_provider != second_provider
+
+
[email protected](
+ "fn, exp",
+ [
+ (C.async_class, 31),
+ (C.sync_class, 31),
+ (C.async_static, "one-three"),
+ (C.sync_static, "one-three"),
+ (C().async_instance, 13),
+ (C().sync_instance, 13),
+ (async_callable, "three-one"),
+ (sync_callable, "three-one"),
+ (async_partial, "why-three-and-one"),
+ (sync_partial, "why-three-and-one"),
+ ],
+)
[email protected]("disable_warn_sync_to_thread_with_async")
+async def test_provide_for_callable(fn: Any, exp: Any, anyio_backend: str) -> None:
+ assert await Provide(fn, sync_to_thread=False)() == exp
+
+
[email protected]("enable_warn_implicit_sync_to_thread")
+def test_sync_callable_without_sync_to_thread_warns() -> None:
+ def func() -> None:
+ pass
+
+ with pytest.warns(LitestarWarning, match="discouraged since synchronous callables"):
+ Provide(func)
+
+
[email protected]("sync_to_thread", [True, False])
+def test_async_callable_with_sync_to_thread_warns(sync_to_thread: bool) -> None:
+ async def func() -> None:
+ pass
+
+ with pytest.warns(LitestarWarning, match="asynchronous callable"):
+ Provide(func, sync_to_thread=sync_to_thread)
+
+
[email protected](
+ ("dep", "exp"),
+ [
+ (sync_callable, True),
+ (async_callable, False),
+ (generator_func, True),
+ (async_generator_func, True),
+ ],
+)
+def test_dependency_has_async_callable(dep: Any, exp: bool) -> None:
+ assert Provide(dep).has_sync_callable is exp
+
+
+def test_raises_when_dependency_is_not_callable() -> None:
+ with pytest.raises(ImproperlyConfiguredException):
+ Provide(123) # type: ignore
diff --git a/tests/dto/__init__.py b/tests/unit/test_dto/__init__.py
similarity index 100%
rename from tests/dto/__init__.py
rename to tests/unit/test_dto/__init__.py
diff --git a/tests/dto/test_attrs_fail.py b/tests/unit/test_dto/test_attrs_fail.py
similarity index 93%
rename from tests/dto/test_attrs_fail.py
rename to tests/unit/test_dto/test_attrs_fail.py
--- a/tests/dto/test_attrs_fail.py
+++ b/tests/unit/test_dto/test_attrs_fail.py
@@ -4,7 +4,8 @@
from litestar import post
from litestar.testing import create_test_client
-from tests.dto import MockDTO, Model
+
+from . import MockDTO, Model
@pytest.mark.xfail
diff --git a/tests/dto/factory/__init__.py b/tests/unit/test_dto/test_factory/__init__.py
similarity index 100%
rename from tests/dto/factory/__init__.py
rename to tests/unit/test_dto/test_factory/__init__.py
diff --git a/tests/dto/factory/test_abc.py b/tests/unit/test_dto/test_factory/test_abc.py
similarity index 100%
rename from tests/dto/factory/test_abc.py
rename to tests/unit/test_dto/test_factory/test_abc.py
diff --git a/tests/contrib/jwt/__init__.py b/tests/unit/test_dto/test_factory/test_backends/__init__.py
similarity index 100%
rename from tests/contrib/jwt/__init__.py
rename to tests/unit/test_dto/test_factory/test_backends/__init__.py
diff --git a/tests/dto/factory/backends/test_abc.py b/tests/unit/test_dto/test_factory/test_backends/test_abc.py
similarity index 100%
rename from tests/dto/factory/backends/test_abc.py
rename to tests/unit/test_dto/test_factory/test_backends/test_abc.py
diff --git a/tests/dto/factory/backends/test_backends.py b/tests/unit/test_dto/test_factory/test_backends/test_backends.py
similarity index 100%
rename from tests/dto/factory/backends/test_backends.py
rename to tests/unit/test_dto/test_factory/test_backends/test_backends.py
diff --git a/tests/dto/factory/backends/test_utils.py b/tests/unit/test_dto/test_factory/test_backends/test_utils.py
similarity index 100%
rename from tests/dto/factory/backends/test_utils.py
rename to tests/unit/test_dto/test_factory/test_backends/test_utils.py
diff --git a/tests/dto/factory/test_integration.py b/tests/unit/test_dto/test_factory/test_integration.py
similarity index 99%
rename from tests/dto/factory/test_integration.py
rename to tests/unit/test_dto/test_factory/test_integration.py
--- a/tests/dto/factory/test_integration.py
+++ b/tests/unit/test_dto/test_factory/test_integration.py
@@ -278,7 +278,9 @@ def handler(data: Bar) -> Bar:
assert len(schemas) == 2
assert schemas[0] != schemas[1]
assert all(
- k.startswith("tests.dto.factory.test_integration.test_dto_openapi_model_name_collision.<locals>.Bar")
+ k.startswith(
+ "tests.unit.test_dto.test_factory.test_integration.test_dto_openapi_model_name_collision.<locals>.Bar"
+ )
for k in response.json()["components"]["schemas"]
)
diff --git a/tests/dto/factory/test_stdlib.py b/tests/unit/test_dto/test_factory/test_stdlib.py
similarity index 100%
rename from tests/dto/factory/test_stdlib.py
rename to tests/unit/test_dto/test_factory/test_stdlib.py
diff --git a/tests/dto/factory/test_utils.py b/tests/unit/test_dto/test_factory/test_utils.py
similarity index 100%
rename from tests/dto/factory/test_utils.py
rename to tests/unit/test_dto/test_factory/test_utils.py
diff --git a/tests/dto/test_integration.py b/tests/unit/test_dto/test_integration.py
similarity index 98%
rename from tests/dto/test_integration.py
rename to tests/unit/test_dto/test_integration.py
--- a/tests/dto/test_integration.py
+++ b/tests/unit/test_dto/test_integration.py
@@ -5,7 +5,8 @@
from litestar import Controller, Router, post
from litestar.testing import create_test_client
-from tests.dto import MockDTO, MockReturnDTO, Model
+
+from . import MockDTO, MockReturnDTO, Model
def test_dto_defined_on_handler() -> None:
diff --git a/tests/dto/test_interface.py b/tests/unit/test_dto/test_interface.py
similarity index 100%
rename from tests/dto/test_interface.py
rename to tests/unit/test_dto/test_interface.py
diff --git a/tests/events/test_listener.py b/tests/unit/test_events.py
similarity index 100%
rename from tests/events/test_listener.py
rename to tests/unit/test_events.py
diff --git a/tests/test_exceptions.py b/tests/unit/test_exceptions.py
similarity index 100%
rename from tests/test_exceptions.py
rename to tests/unit/test_exceptions.py
diff --git a/tests/test_file_system.py b/tests/unit/test_file_system.py
similarity index 100%
rename from tests/test_file_system.py
rename to tests/unit/test_file_system.py
diff --git a/tests/test_guards.py b/tests/unit/test_guards.py
similarity index 100%
rename from tests/test_guards.py
rename to tests/unit/test_guards.py
diff --git a/tests/contrib/open_telemetry/__init__.py b/tests/unit/test_handlers/__init__.py
similarity index 100%
rename from tests/contrib/open_telemetry/__init__.py
rename to tests/unit/test_handlers/__init__.py
diff --git a/tests/contrib/sqlalchemy/__init__.py b/tests/unit/test_handlers/test_asgi_handlers/__init__.py
similarity index 100%
rename from tests/contrib/sqlalchemy/__init__.py
rename to tests/unit/test_handlers/test_asgi_handlers/__init__.py
diff --git a/tests/handlers/asgi/test_handle_asgi.py b/tests/unit/test_handlers/test_asgi_handlers/test_handle_asgi.py
similarity index 100%
rename from tests/handlers/asgi/test_handle_asgi.py
rename to tests/unit/test_handlers/test_asgi_handlers/test_handle_asgi.py
diff --git a/tests/handlers/asgi/test_handle_asgi_with_future_annotations.py b/tests/unit/test_handlers/test_asgi_handlers/test_handle_asgi_with_future_annotations.py
similarity index 100%
rename from tests/handlers/asgi/test_handle_asgi_with_future_annotations.py
rename to tests/unit/test_handlers/test_asgi_handlers/test_handle_asgi_with_future_annotations.py
diff --git a/tests/handlers/asgi/test_validations.py b/tests/unit/test_handlers/test_asgi_handlers/test_validations.py
similarity index 100%
rename from tests/handlers/asgi/test_validations.py
rename to tests/unit/test_handlers/test_asgi_handlers/test_validations.py
diff --git a/tests/contrib/sqlalchemy/init_plugin/__init__.py b/tests/unit/test_handlers/test_base_handlers/__init__.py
similarity index 100%
rename from tests/contrib/sqlalchemy/init_plugin/__init__.py
rename to tests/unit/test_handlers/test_base_handlers/__init__.py
diff --git a/tests/handlers/base/test_opt.py b/tests/unit/test_handlers/test_base_handlers/test_opt.py
similarity index 100%
rename from tests/handlers/base/test_opt.py
rename to tests/unit/test_handlers/test_base_handlers/test_opt.py
diff --git a/tests/handlers/base/test_resolution.py b/tests/unit/test_handlers/test_base_handlers/test_resolution.py
similarity index 100%
rename from tests/handlers/base/test_resolution.py
rename to tests/unit/test_handlers/test_base_handlers/test_resolution.py
diff --git a/tests/handlers/base/test_validations.py b/tests/unit/test_handlers/test_base_handlers/test_validations.py
similarity index 100%
rename from tests/handlers/base/test_validations.py
rename to tests/unit/test_handlers/test_base_handlers/test_validations.py
diff --git a/tests/contrib/sqlalchemy/init_plugin/config/__init__.py b/tests/unit/test_handlers/test_http_handlers/__init__.py
similarity index 100%
rename from tests/contrib/sqlalchemy/init_plugin/config/__init__.py
rename to tests/unit/test_handlers/test_http_handlers/__init__.py
diff --git a/tests/handlers/http/test_defaults.py b/tests/unit/test_handlers/test_http_handlers/test_defaults.py
similarity index 100%
rename from tests/handlers/http/test_defaults.py
rename to tests/unit/test_handlers/test_http_handlers/test_defaults.py
diff --git a/tests/handlers/http/test_delete.py b/tests/unit/test_handlers/test_http_handlers/test_delete.py
similarity index 100%
rename from tests/handlers/http/test_delete.py
rename to tests/unit/test_handlers/test_http_handlers/test_delete.py
diff --git a/tests/handlers/http/test_head.py b/tests/unit/test_handlers/test_http_handlers/test_head.py
similarity index 100%
rename from tests/handlers/http/test_head.py
rename to tests/unit/test_handlers/test_http_handlers/test_head.py
diff --git a/tests/handlers/http/test_kwarg_handling.py b/tests/unit/test_handlers/test_http_handlers/test_kwarg_handling.py
similarity index 100%
rename from tests/handlers/http/test_kwarg_handling.py
rename to tests/unit/test_handlers/test_http_handlers/test_kwarg_handling.py
diff --git a/tests/handlers/http/test_media_type.py b/tests/unit/test_handlers/test_http_handlers/test_media_type.py
similarity index 100%
rename from tests/handlers/http/test_media_type.py
rename to tests/unit/test_handlers/test_http_handlers/test_media_type.py
diff --git a/tests/handlers/http/test_signature_namespace.py b/tests/unit/test_handlers/test_http_handlers/test_signature_namespace.py
similarity index 100%
rename from tests/handlers/http/test_signature_namespace.py
rename to tests/unit/test_handlers/test_http_handlers/test_signature_namespace.py
diff --git a/tests/handlers/http/test_sync.py b/tests/unit/test_handlers/test_http_handlers/test_sync.py
similarity index 100%
rename from tests/handlers/http/test_sync.py
rename to tests/unit/test_handlers/test_http_handlers/test_sync.py
diff --git a/tests/handlers/http/test_to_response.py b/tests/unit/test_handlers/test_http_handlers/test_to_response.py
similarity index 100%
rename from tests/handlers/http/test_to_response.py
rename to tests/unit/test_handlers/test_http_handlers/test_to_response.py
diff --git a/tests/handlers/http/test_validations.py b/tests/unit/test_handlers/test_http_handlers/test_validations.py
similarity index 100%
rename from tests/handlers/http/test_validations.py
rename to tests/unit/test_handlers/test_http_handlers/test_validations.py
diff --git a/tests/contrib/sqlalchemy/repository/__init__.py b/tests/unit/test_handlers/test_websocket_handlers/__init__.py
similarity index 100%
rename from tests/contrib/sqlalchemy/repository/__init__.py
rename to tests/unit/test_handlers/test_websocket_handlers/__init__.py
diff --git a/tests/handlers/websocket/test_handle_websocket.py b/tests/unit/test_handlers/test_websocket_handlers/test_handle_websocket.py
similarity index 100%
rename from tests/handlers/websocket/test_handle_websocket.py
rename to tests/unit/test_handlers/test_websocket_handlers/test_handle_websocket.py
diff --git a/tests/handlers/websocket/test_handle_websocket_with_future_annotations.py b/tests/unit/test_handlers/test_websocket_handlers/test_handle_websocket_with_future_annotations.py
similarity index 100%
rename from tests/handlers/websocket/test_handle_websocket_with_future_annotations.py
rename to tests/unit/test_handlers/test_websocket_handlers/test_handle_websocket_with_future_annotations.py
diff --git a/tests/handlers/websocket/test_kwarg_handling.py b/tests/unit/test_handlers/test_websocket_handlers/test_kwarg_handling.py
similarity index 100%
rename from tests/handlers/websocket/test_kwarg_handling.py
rename to tests/unit/test_handlers/test_websocket_handlers/test_kwarg_handling.py
diff --git a/tests/handlers/websocket/test_listeners.py b/tests/unit/test_handlers/test_websocket_handlers/test_listeners.py
similarity index 99%
rename from tests/handlers/websocket/test_listeners.py
rename to tests/unit/test_handlers/test_websocket_handlers/test_listeners.py
--- a/tests/handlers/websocket/test_listeners.py
+++ b/tests/unit/test_handlers/test_websocket_handlers/test_listeners.py
@@ -17,11 +17,6 @@
from litestar.types.asgi_types import WebSocketMode
[email protected]
-def mock() -> MagicMock:
- return MagicMock()
-
-
@pytest.fixture
def listener_class(mock: MagicMock) -> Type[WebsocketListener]:
class Listener(WebsocketListener):
diff --git a/tests/handlers/websocket/test_validations.py b/tests/unit/test_handlers/test_websocket_handlers/test_validations.py
similarity index 100%
rename from tests/handlers/websocket/test_validations.py
rename to tests/unit/test_handlers/test_websocket_handlers/test_validations.py
diff --git a/tests/kwargs/__init__.py b/tests/unit/test_kwargs/__init__.py
similarity index 100%
rename from tests/kwargs/__init__.py
rename to tests/unit/test_kwargs/__init__.py
diff --git a/tests/kwargs/flower.jpeg b/tests/unit/test_kwargs/flower.jpeg
similarity index 100%
rename from tests/kwargs/flower.jpeg
rename to tests/unit/test_kwargs/flower.jpeg
diff --git a/tests/kwargs/test_attrs_data.py b/tests/unit/test_kwargs/test_attrs_data.py
similarity index 100%
rename from tests/kwargs/test_attrs_data.py
rename to tests/unit/test_kwargs/test_attrs_data.py
diff --git a/tests/unit/test_kwargs/test_cleanup_group.py b/tests/unit/test_kwargs/test_cleanup_group.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/test_kwargs/test_cleanup_group.py
@@ -0,0 +1,91 @@
+from typing import AsyncGenerator, Generator
+from unittest.mock import MagicMock
+
+import pytest
+
+from litestar._kwargs.cleanup import DependencyCleanupGroup
+from litestar.utils.compat import async_next
+
+
[email protected]
+def cleanup_mock() -> MagicMock:
+ return MagicMock()
+
+
[email protected]
+def async_cleanup_mock() -> MagicMock:
+ return MagicMock()
+
+
[email protected]
+def generator(cleanup_mock: MagicMock) -> Generator[str, None, None]:
+ def func() -> Generator[str, None, None]:
+ yield "hello"
+ cleanup_mock()
+
+ return func()
+
+
[email protected]
+def async_generator(async_cleanup_mock: MagicMock) -> AsyncGenerator[str, None]:
+ async def func() -> AsyncGenerator[str, None]:
+ yield "world"
+ async_cleanup_mock()
+
+ return func()
+
+
+def test_add(generator: Generator[str, None, None]) -> None:
+ group = DependencyCleanupGroup()
+
+ group.add(generator)
+
+ assert group._generators == [generator]
+
+
+async def test_cleanup(generator: Generator[str, None, None], cleanup_mock: MagicMock) -> None:
+ next(generator)
+ group = DependencyCleanupGroup([generator])
+
+ await group.cleanup()
+
+ cleanup_mock.assert_called_once()
+ assert group._closed
+
+
+async def test_cleanup_multiple(
+ generator: Generator[str, None, None],
+ async_generator: AsyncGenerator[str, None],
+ cleanup_mock: MagicMock,
+ async_cleanup_mock: MagicMock,
+) -> None:
+ next(generator)
+ await async_next(async_generator)
+ group = DependencyCleanupGroup([generator, async_generator])
+
+ await group.cleanup()
+
+ cleanup_mock.assert_called_once()
+ async_cleanup_mock.assert_called_once()
+ assert group._closed
+
+
+async def test_cleanup_on_closed_raises(generator: Generator[str, None, None]) -> None:
+ next(generator)
+ group = DependencyCleanupGroup([generator])
+
+ await group.cleanup()
+ with pytest.raises(RuntimeError):
+ await group.cleanup()
+
+
+async def test_add_on_closed_raises(
+ generator: Generator[str, None, None], async_generator: AsyncGenerator[str, None]
+) -> None:
+ next(generator)
+ group = DependencyCleanupGroup([generator])
+
+ await group.cleanup()
+
+ with pytest.raises(RuntimeError):
+ group.add(async_generator)
diff --git a/tests/kwargs/test_cookie_params.py b/tests/unit/test_kwargs/test_cookie_params.py
similarity index 100%
rename from tests/kwargs/test_cookie_params.py
rename to tests/unit/test_kwargs/test_cookie_params.py
diff --git a/tests/kwargs/test_defaults.py b/tests/unit/test_kwargs/test_defaults.py
similarity index 100%
rename from tests/kwargs/test_defaults.py
rename to tests/unit/test_kwargs/test_defaults.py
diff --git a/tests/kwargs/test_dependency_batches.py b/tests/unit/test_kwargs/test_dependency_batches.py
similarity index 100%
rename from tests/kwargs/test_dependency_batches.py
rename to tests/unit/test_kwargs/test_dependency_batches.py
diff --git a/tests/kwargs/test_dto_extractor.py b/tests/unit/test_kwargs/test_dto_extractor.py
similarity index 86%
rename from tests/kwargs/test_dto_extractor.py
rename to tests/unit/test_kwargs/test_dto_extractor.py
--- a/tests/kwargs/test_dto_extractor.py
+++ b/tests/unit/test_kwargs/test_dto_extractor.py
@@ -3,7 +3,7 @@
from unittest.mock import AsyncMock
from litestar._kwargs.extractors import create_dto_extractor
-from tests.dto import MockDTO, Model
+from tests.unit.test_dto import MockDTO, Model
async def test_create_dto_extractor() -> None:
diff --git a/tests/kwargs/test_generator_dependencies.py b/tests/unit/test_kwargs/test_generator_dependencies.py
similarity index 100%
rename from tests/kwargs/test_generator_dependencies.py
rename to tests/unit/test_kwargs/test_generator_dependencies.py
diff --git a/tests/kwargs/test_header_params.py b/tests/unit/test_kwargs/test_header_params.py
similarity index 100%
rename from tests/kwargs/test_header_params.py
rename to tests/unit/test_kwargs/test_header_params.py
diff --git a/tests/kwargs/test_json_data.py b/tests/unit/test_kwargs/test_json_data.py
similarity index 96%
rename from tests/kwargs/test_json_data.py
rename to tests/unit/test_kwargs/test_json_data.py
--- a/tests/kwargs/test_json_data.py
+++ b/tests/unit/test_kwargs/test_json_data.py
@@ -2,7 +2,8 @@
from litestar.params import Body
from litestar.status_codes import HTTP_201_CREATED
from litestar.testing import create_test_client
-from tests.kwargs import Form
+
+from . import Form
def test_request_body_json() -> None:
diff --git a/tests/kwargs/test_layered_params.py b/tests/unit/test_kwargs/test_layered_params.py
similarity index 100%
rename from tests/kwargs/test_layered_params.py
rename to tests/unit/test_kwargs/test_layered_params.py
diff --git a/tests/kwargs/test_msgpack_data.py b/tests/unit/test_kwargs/test_msgpack_data.py
similarity index 100%
rename from tests/kwargs/test_msgpack_data.py
rename to tests/unit/test_kwargs/test_msgpack_data.py
diff --git a/tests/kwargs/test_multipart_data.py b/tests/unit/test_kwargs/test_multipart_data.py
similarity index 99%
rename from tests/kwargs/test_multipart_data.py
rename to tests/unit/test_kwargs/test_multipart_data.py
--- a/tests/kwargs/test_multipart_data.py
+++ b/tests/unit/test_kwargs/test_multipart_data.py
@@ -15,7 +15,7 @@
from litestar.status_codes import HTTP_201_CREATED, HTTP_400_BAD_REQUEST
from litestar.testing import create_test_client
from tests import Person, PersonFactory
-from tests.kwargs import Form
+from . import Form
class FormData(BaseModel):
diff --git a/tests/kwargs/test_path_params.py b/tests/unit/test_kwargs/test_path_params.py
similarity index 100%
rename from tests/kwargs/test_path_params.py
rename to tests/unit/test_kwargs/test_path_params.py
diff --git a/tests/kwargs/test_query_params.py b/tests/unit/test_kwargs/test_query_params.py
similarity index 100%
rename from tests/kwargs/test_query_params.py
rename to tests/unit/test_kwargs/test_query_params.py
diff --git a/tests/kwargs/test_reserved_kwargs_injection.py b/tests/unit/test_kwargs/test_reserved_kwargs_injection.py
similarity index 100%
rename from tests/kwargs/test_reserved_kwargs_injection.py
rename to tests/unit/test_kwargs/test_reserved_kwargs_injection.py
diff --git a/tests/kwargs/test_url_encoded_data.py b/tests/unit/test_kwargs/test_url_encoded_data.py
similarity index 97%
rename from tests/kwargs/test_url_encoded_data.py
rename to tests/unit/test_kwargs/test_url_encoded_data.py
--- a/tests/kwargs/test_url_encoded_data.py
+++ b/tests/unit/test_kwargs/test_url_encoded_data.py
@@ -5,7 +5,8 @@
from litestar.params import Body
from litestar.status_codes import HTTP_201_CREATED
from litestar.testing import create_test_client
-from tests.kwargs import Form
+
+from . import Form
def test_request_body_url_encoded() -> None:
diff --git a/tests/kwargs/test_validations.py b/tests/unit/test_kwargs/test_validations.py
similarity index 100%
rename from tests/kwargs/test_validations.py
rename to tests/unit/test_kwargs/test_validations.py
diff --git a/tests/dependency_injection/__init__.py b/tests/unit/test_logging/__init__.py
similarity index 100%
rename from tests/dependency_injection/__init__.py
rename to tests/unit/test_logging/__init__.py
diff --git a/tests/logging_config/test_logging_config.py b/tests/unit/test_logging/test_logging_config.py
similarity index 94%
rename from tests/logging_config/test_logging_config.py
rename to tests/unit/test_logging/test_logging_config.py
--- a/tests/logging_config/test_logging_config.py
+++ b/tests/unit/test_logging/test_logging_config.py
@@ -5,18 +5,9 @@
import pytest
from litestar import Request, get
-from litestar.logging.config import (
- LoggingConfig,
- _get_default_handlers,
- default_handlers,
- default_picologging_handlers,
-)
-from litestar.logging.picologging import (
- QueueListenerHandler as PicologgingQueueListenerHandler,
-)
-from litestar.logging.standard import (
- QueueListenerHandler as StandardQueueListenerHandler,
-)
+from litestar.logging.config import LoggingConfig, _get_default_handlers, default_handlers, default_picologging_handlers
+from litestar.logging.picologging import QueueListenerHandler as PicologgingQueueListenerHandler
+from litestar.logging.standard import QueueListenerHandler as StandardQueueListenerHandler
from litestar.status_codes import HTTP_200_OK
from litestar.testing import create_test_client
diff --git a/tests/logging_config/test_structlog_config.py b/tests/unit/test_logging/test_structlog_config.py
similarity index 100%
rename from tests/logging_config/test_structlog_config.py
rename to tests/unit/test_logging/test_structlog_config.py
diff --git a/tests/dto/factory/backends/__init__.py b/tests/unit/test_middleware/__init__.py
similarity index 100%
rename from tests/dto/factory/backends/__init__.py
rename to tests/unit/test_middleware/__init__.py
diff --git a/tests/middleware/test_allowed_hosts_middleware.py b/tests/unit/test_middleware/test_allowed_hosts_middleware.py
similarity index 100%
rename from tests/middleware/test_allowed_hosts_middleware.py
rename to tests/unit/test_middleware/test_allowed_hosts_middleware.py
diff --git a/tests/middleware/test_base_authentication_middleware.py b/tests/unit/test_middleware/test_base_authentication_middleware.py
similarity index 100%
rename from tests/middleware/test_base_authentication_middleware.py
rename to tests/unit/test_middleware/test_base_authentication_middleware.py
diff --git a/tests/middleware/test_base_middleware.py b/tests/unit/test_middleware/test_base_middleware.py
similarity index 100%
rename from tests/middleware/test_base_middleware.py
rename to tests/unit/test_middleware/test_base_middleware.py
diff --git a/tests/middleware/test_compression_middleware.py b/tests/unit/test_middleware/test_compression_middleware.py
similarity index 100%
rename from tests/middleware/test_compression_middleware.py
rename to tests/unit/test_middleware/test_compression_middleware.py
diff --git a/tests/middleware/test_cors_middleware.py b/tests/unit/test_middleware/test_cors_middleware.py
similarity index 100%
rename from tests/middleware/test_cors_middleware.py
rename to tests/unit/test_middleware/test_cors_middleware.py
diff --git a/tests/middleware/test_csrf_middleware.py b/tests/unit/test_middleware/test_csrf_middleware.py
similarity index 98%
rename from tests/middleware/test_csrf_middleware.py
rename to tests/unit/test_middleware/test_csrf_middleware.py
--- a/tests/middleware/test_csrf_middleware.py
+++ b/tests/unit/test_middleware/test_csrf_middleware.py
@@ -175,7 +175,7 @@ def test_custom_csrf_config(get_handler: HTTPRouteHandler, post_handler: HTTPRou
(MakoTemplateEngine, "${csrf_input}"),
),
)
-def test_csrf_form_parsing(engine: Any, template: str, template_dir: Path) -> None:
+def test_csrf_form_parsing(engine: Any, template: str, tmp_path: Path) -> None:
@get(path="/", media_type=MediaType.HTML)
def handler() -> Template:
return Template(template_name="abc.html")
@@ -187,13 +187,13 @@ def form_handler(data: dict = Body(media_type=RequestEncodingType.URL_ENCODED))
with create_test_client(
route_handlers=[handler, form_handler],
template_config=TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=engine,
),
csrf_config=CSRFConfig(secret=str(urandom(10))),
) as client:
url = str(client.base_url) + "/"
- Path(template_dir / "abc.html").write_text(
+ Path(tmp_path / "abc.html").write_text(
f'<html><body><div><form action="{url}" method="post">{template}</form></div></body></html>'
)
_ = client.get("/")
diff --git a/tests/middleware/test_exception_handler_middleware.py b/tests/unit/test_middleware/test_exception_handler_middleware.py
similarity index 100%
rename from tests/middleware/test_exception_handler_middleware.py
rename to tests/unit/test_middleware/test_exception_handler_middleware.py
diff --git a/tests/middleware/test_logging_middleware.py b/tests/unit/test_middleware/test_logging_middleware.py
similarity index 100%
rename from tests/middleware/test_logging_middleware.py
rename to tests/unit/test_middleware/test_logging_middleware.py
diff --git a/tests/middleware/test_middleware_handling.py b/tests/unit/test_middleware/test_middleware_handling.py
similarity index 100%
rename from tests/middleware/test_middleware_handling.py
rename to tests/unit/test_middleware/test_middleware_handling.py
diff --git a/tests/middleware/test_rate_limit_middleware.py b/tests/unit/test_middleware/test_rate_limit_middleware.py
similarity index 100%
rename from tests/middleware/test_rate_limit_middleware.py
rename to tests/unit/test_middleware/test_rate_limit_middleware.py
diff --git a/tests/events/__init__.py b/tests/unit/test_middleware/test_session/__init__.py
similarity index 100%
rename from tests/events/__init__.py
rename to tests/unit/test_middleware/test_session/__init__.py
diff --git a/tests/middleware/session/conftest.py b/tests/unit/test_middleware/test_session/conftest.py
similarity index 100%
rename from tests/middleware/session/conftest.py
rename to tests/unit/test_middleware/test_session/conftest.py
diff --git a/tests/middleware/session/test_client_side_backend.py b/tests/unit/test_middleware/test_session/test_client_side_backend.py
similarity index 100%
rename from tests/middleware/session/test_client_side_backend.py
rename to tests/unit/test_middleware/test_session/test_client_side_backend.py
diff --git a/tests/middleware/session/test_middleware.py b/tests/unit/test_middleware/test_session/test_middleware.py
similarity index 100%
rename from tests/middleware/session/test_middleware.py
rename to tests/unit/test_middleware/test_session/test_middleware.py
diff --git a/tests/middleware/session/test_server_side_backend.py b/tests/unit/test_middleware/test_session/test_server_side_backend.py
similarity index 100%
rename from tests/middleware/session/test_server_side_backend.py
rename to tests/unit/test_middleware/test_session/test_server_side_backend.py
diff --git a/tests/handlers/__init__.py b/tests/unit/test_openapi/__init__.py
similarity index 100%
rename from tests/handlers/__init__.py
rename to tests/unit/test_openapi/__init__.py
diff --git a/tests/openapi/conftest.py b/tests/unit/test_openapi/conftest.py
similarity index 98%
rename from tests/openapi/conftest.py
rename to tests/unit/test_openapi/conftest.py
--- a/tests/openapi/conftest.py
+++ b/tests/unit/test_openapi/conftest.py
@@ -12,7 +12,8 @@
from litestar.params import Parameter
from litestar.partial import Partial
from tests import Person, PersonFactory, Pet, VanillaDataClassPerson
-from tests.openapi.utils import Gender, PetException
+
+from .utils import Gender, PetException
def create_person_controller() -> Type[Controller]:
diff --git a/tests/openapi/test_config.py b/tests/unit/test_openapi/test_config.py
similarity index 100%
rename from tests/openapi/test_config.py
rename to tests/unit/test_openapi/test_config.py
diff --git a/tests/openapi/test_constrained_fields.py b/tests/unit/test_openapi/test_constrained_fields.py
similarity index 99%
rename from tests/openapi/test_constrained_fields.py
rename to tests/unit/test_openapi/test_constrained_fields.py
--- a/tests/openapi/test_constrained_fields.py
+++ b/tests/unit/test_openapi/test_constrained_fields.py
@@ -12,7 +12,8 @@
from litestar._openapi.schema_generation.schema import create_schema
from litestar._signature.field import SignatureField
from litestar.openapi.spec.enums import OpenAPIFormat, OpenAPIType
-from tests.openapi.utils import (
+
+from .utils import (
constrained_collection,
constrained_dates,
constrained_numbers,
diff --git a/tests/openapi/test_controller.py b/tests/unit/test_openapi/test_controller.py
similarity index 100%
rename from tests/openapi/test_controller.py
rename to tests/unit/test_openapi/test_controller.py
diff --git a/tests/openapi/test_integration.py b/tests/unit/test_openapi/test_integration.py
similarity index 100%
rename from tests/openapi/test_integration.py
rename to tests/unit/test_openapi/test_integration.py
diff --git a/tests/openapi/test_parameters.py b/tests/unit/test_openapi/test_parameters.py
similarity index 100%
rename from tests/openapi/test_parameters.py
rename to tests/unit/test_openapi/test_parameters.py
diff --git a/tests/openapi/test_path_item.py b/tests/unit/test_openapi/test_path_item.py
similarity index 100%
rename from tests/openapi/test_path_item.py
rename to tests/unit/test_openapi/test_path_item.py
diff --git a/tests/openapi/test_request_body.py b/tests/unit/test_openapi/test_request_body.py
similarity index 100%
rename from tests/openapi/test_request_body.py
rename to tests/unit/test_openapi/test_request_body.py
diff --git a/tests/openapi/test_responses.py b/tests/unit/test_openapi/test_responses.py
similarity index 99%
rename from tests/openapi/test_responses.py
rename to tests/unit/test_openapi/test_responses.py
--- a/tests/openapi/test_responses.py
+++ b/tests/unit/test_openapi/test_responses.py
@@ -36,7 +36,8 @@
HTTP_406_NOT_ACCEPTABLE,
)
from tests import Person, PersonFactory
-from tests.openapi.utils import PetException
+
+from .utils import PetException
def get_registered_route_handler(handler: "HTTPRouteHandler | type[Controller]", name: str) -> HTTPRouteHandler:
@@ -62,7 +63,7 @@ def test_create_responses(person_controller: Type[Controller], pet_controller: T
handler = get_registered_route_handler(
pet_controller,
- "tests.openapi.conftest.create_pet_controller.<locals>.PetController.get_pets_or_owners",
+ "tests.unit.test_openapi.conftest.create_pet_controller.<locals>.PetController.get_pets_or_owners",
)
responses = create_responses(
route_handler=handler,
diff --git a/tests/openapi/test_schema.py b/tests/unit/test_openapi/test_schema.py
similarity index 100%
rename from tests/openapi/test_schema.py
rename to tests/unit/test_openapi/test_schema.py
diff --git a/tests/openapi/test_security_schemes.py b/tests/unit/test_openapi/test_security_schemes.py
similarity index 100%
rename from tests/openapi/test_security_schemes.py
rename to tests/unit/test_openapi/test_security_schemes.py
diff --git a/tests/openapi/test_spec_generation.py b/tests/unit/test_openapi/test_spec_generation.py
similarity index 100%
rename from tests/openapi/test_spec_generation.py
rename to tests/unit/test_openapi/test_spec_generation.py
diff --git a/tests/openapi/test_tags.py b/tests/unit/test_openapi/test_tags.py
similarity index 100%
rename from tests/openapi/test_tags.py
rename to tests/unit/test_openapi/test_tags.py
diff --git a/tests/handlers/asgi/__init__.py b/tests/unit/test_openapi/test_typescript_converter/__init__.py
similarity index 100%
rename from tests/handlers/asgi/__init__.py
rename to tests/unit/test_openapi/test_typescript_converter/__init__.py
diff --git a/tests/openapi/typescript_converter/test_converter.py b/tests/unit/test_openapi/test_typescript_converter/test_converter.py
similarity index 100%
rename from tests/openapi/typescript_converter/test_converter.py
rename to tests/unit/test_openapi/test_typescript_converter/test_converter.py
diff --git a/tests/openapi/typescript_converter/test_schema_parsing.py b/tests/unit/test_openapi/test_typescript_converter/test_schema_parsing.py
similarity index 100%
rename from tests/openapi/typescript_converter/test_schema_parsing.py
rename to tests/unit/test_openapi/test_typescript_converter/test_schema_parsing.py
diff --git a/tests/openapi/typescript_converter/test_typescript_types.py b/tests/unit/test_openapi/test_typescript_converter/test_typescript_types.py
similarity index 100%
rename from tests/openapi/typescript_converter/test_typescript_types.py
rename to tests/unit/test_openapi/test_typescript_converter/test_typescript_types.py
diff --git a/tests/openapi/utils.py b/tests/unit/test_openapi/utils.py
similarity index 100%
rename from tests/openapi/utils.py
rename to tests/unit/test_openapi/utils.py
diff --git a/tests/test_pagination.py b/tests/unit/test_pagination.py
similarity index 100%
rename from tests/test_pagination.py
rename to tests/unit/test_pagination.py
diff --git a/tests/dependency_injection/test_dependency.py b/tests/unit/test_params.py
similarity index 53%
rename from tests/dependency_injection/test_dependency.py
rename to tests/unit/test_params.py
--- a/tests/dependency_injection/test_dependency.py
+++ b/tests/unit/test_params.py
@@ -1,15 +1,94 @@
-from typing import Any, AsyncGenerator, Dict, Generator, List, Optional
+from typing import Any, Dict, List, Optional
import pytest
+from typing_extensions import Annotated
-from litestar import Controller, Litestar, get
+from litestar import Controller, Litestar, get, post
from litestar.di import Provide
from litestar.exceptions import ImproperlyConfiguredException
-from litestar.params import Dependency
-from litestar.status_codes import HTTP_200_OK, HTTP_500_INTERNAL_SERVER_ERROR
+from litestar.params import Body, Dependency, Parameter
+from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
from litestar.testing import create_test_client
[email protected]("backend", ("pydantic", "attrs"))
+def test_parsing_of_parameter_as_annotated(backend: Any) -> None:
+ @get(path="/")
+ def handler(param: Annotated[str, Parameter(min_length=1)]) -> str:
+ return param
+
+ with create_test_client(handler, _preferred_validation_backend=backend) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_400_BAD_REQUEST
+
+ response = client.get("/?param=a")
+ assert response.status_code == HTTP_200_OK
+
+
[email protected]("backend", ("pydantic", "attrs"))
+def test_parsing_of_parameter_as_default_value(backend: Any) -> None:
+ @get(path="/")
+ def handler(param: str = Parameter(min_length=1)) -> str:
+ return param
+
+ with create_test_client(handler, _preferred_validation_backend=backend) as client:
+ response = client.get("/?param=")
+ assert response.status_code == HTTP_400_BAD_REQUEST
+
+ response = client.get("/?param=a")
+ assert response.status_code == HTTP_200_OK
+
+
[email protected]("backend", ("pydantic", "attrs"))
+def test_parsing_of_body_as_annotated(backend: Any) -> None:
+ @post(path="/")
+ def handler(data: Annotated[List[str], Body(min_items=1)]) -> List[str]:
+ return data
+
+ with create_test_client(handler, _preferred_validation_backend=backend) as client:
+ response = client.post("/", json=[])
+ assert response.status_code == HTTP_400_BAD_REQUEST
+
+ response = client.post("/", json=["a"])
+ assert response.status_code == HTTP_201_CREATED
+
+
[email protected]("backend", ("pydantic", "attrs"))
+def test_parsing_of_body_as_default_value(backend: Any) -> None:
+ @post(path="/")
+ def handler(data: List[str] = Body(min_items=1)) -> List[str]:
+ return data
+
+ with create_test_client(handler, _preferred_validation_backend=backend) as client:
+ response = client.post("/", json=[])
+ assert response.status_code == HTTP_400_BAD_REQUEST
+
+ response = client.post("/", json=["a"])
+ assert response.status_code == HTTP_201_CREATED
+
+
[email protected]("backend", ("pydantic", "attrs"))
+def test_parsing_of_dependency_as_annotated(backend: Any) -> None:
+ @get(path="/", dependencies={"dep": Provide(lambda: None, sync_to_thread=False)})
+ def handler(dep: Annotated[int, Dependency(skip_validation=True)]) -> int:
+ return dep
+
+ with create_test_client(handler, _preferred_validation_backend=backend) as client:
+ response = client.get("/")
+ assert response.text == "null"
+
+
[email protected]("backend", ("pydantic", "attrs"))
+def test_parsing_of_dependency_as_default_value(backend: Any) -> None:
+ @get(path="/", dependencies={"dep": Provide(lambda: None, sync_to_thread=False)})
+ def handler(dep: int = Dependency(skip_validation=True)) -> int:
+ return dep
+
+ with create_test_client(handler, _preferred_validation_backend=backend) as client:
+ response = client.get("/")
+ assert response.text == "null"
+
+
@pytest.mark.parametrize(
"dependency, expected",
[
@@ -28,7 +107,7 @@ def handler(value: Optional[int] = dependency) -> Dict[str, Optional[int]]:
assert resp.json() == {"value": expected}
-def test_non_optional_with_default() -> None:
+def test_dependency_non_optional_with_default() -> None:
@get("/")
def handler(value: int = Dependency(default=13)) -> Dict[str, int]:
return {"value": value}
@@ -38,7 +117,7 @@ def handler(value: int = Dependency(default=13)) -> Dict[str, int]:
assert resp.json() == {"value": 13}
-def test_no_default_dependency_provided() -> None:
+def test_dependency_no_default() -> None:
@get(dependencies={"value": Provide(lambda: 13, sync_to_thread=False)})
def test(value: int = Dependency()) -> Dict[str, int]:
return {"value": value}
@@ -105,7 +184,7 @@ def skipped(value: int = Dependency(default=1, skip_validation=True)) -> Dict[st
assert skipped_resp.json() == {"value": 1}
-def test_nested_sequence_dependency() -> None:
+def test_dependency_nested_sequence() -> None:
class Obj:
def __init__(self, seq: List[str]) -> None:
self.seq = seq
@@ -130,27 +209,3 @@ def get_seq(seq: List[str]) -> List[str]:
assert resp.json() == ["a", "b", "c"]
resp = client.get("/obj", params={"seq": seq})
assert resp.json() == ["a", "b", "c"]
-
-
-def sync_callable() -> float:
- return 0.1
-
-
-async def async_callable() -> float:
- return 0.1
-
-
-def sync_generator() -> Generator[float, None, None]:
- yield 0.1
-
-
-async def async_generator() -> AsyncGenerator[float, None]:
- yield 0.1
-
-
[email protected](
- ("dep", "exp"),
- [(sync_callable, True), (async_callable, False), (sync_generator, True), (async_generator, True)],
-)
-def test_dependency_has_async_callable(dep: Any, exp: bool) -> None:
- assert Provide(dep).has_sync_callable is exp
diff --git a/tests/test_parsers.py b/tests/unit/test_parsers.py
similarity index 100%
rename from tests/test_parsers.py
rename to tests/unit/test_parsers.py
diff --git a/tests/test_partial.py b/tests/unit/test_partial.py
similarity index 100%
rename from tests/test_partial.py
rename to tests/unit/test_partial.py
diff --git a/tests/test_plugins.py b/tests/unit/test_plugins.py
similarity index 100%
rename from tests/test_plugins.py
rename to tests/unit/test_plugins.py
diff --git a/tests/handlers/base/__init__.py b/tests/unit/test_response/__init__.py
similarity index 100%
rename from tests/handlers/base/__init__.py
rename to tests/unit/test_response/__init__.py
diff --git a/tests/response/test_base_response.py b/tests/unit/test_response/test_base_response.py
similarity index 100%
rename from tests/response/test_base_response.py
rename to tests/unit/test_response/test_base_response.py
--- a/tests/response/test_base_response.py
+++ b/tests/unit/test_response/test_base_response.py
@@ -171,11 +171,6 @@ def handler() -> Any:
assert response.status_code == HTTP_200_OK
-def test_head_response_doesnt_support_content() -> None:
- with pytest.raises(ImproperlyConfiguredException):
- ASGIResponse(body=b"hello world", media_type=MediaType.TEXT, is_head_response=True)
-
-
def test_get_serializer() -> None:
class Foo:
pass
@@ -195,3 +190,8 @@ class FooResponse(Response):
assert (
get_serializer(FooResponse(None, type_encoders={Foo: lambda f: "foo"}).response_type_encoders)(Foo()) == "foo"
)
+
+
+def test_head_response_doesnt_support_content() -> None:
+ with pytest.raises(ImproperlyConfiguredException):
+ ASGIResponse(body=b"hello world", media_type=MediaType.TEXT, is_head_response=True)
diff --git a/tests/response/test_file_response.py b/tests/unit/test_response/test_file_response.py
similarity index 53%
rename from tests/response/test_file_response.py
rename to tests/unit/test_response/test_file_response.py
--- a/tests/response/test_file_response.py
+++ b/tests/unit/test_response/test_file_response.py
@@ -1,17 +1,21 @@
+import os
from email.utils import formatdate
-from os import urandom
+from os import stat, urandom
from pathlib import Path
from typing import Any
import pytest
+from fsspec.implementations.local import LocalFileSystem
from litestar import get
from litestar.connection.base import empty_send
+from litestar.datastructures import ETag
from litestar.exceptions import ImproperlyConfiguredException
from litestar.file_system import BaseLocalFileSystem, FileSystemAdapter
from litestar.response.file import ASGIFileResponse, File, async_file_iterator
from litestar.status_codes import HTTP_200_OK
from litestar.testing import create_test_client
+from litestar.types import FileSystemProtocol
@pytest.mark.parametrize("content_disposition_type", ("inline", "attachment"))
@@ -97,13 +101,6 @@ async def test_file_response_with_directory_raises_error(tmpdir: Path) -> None:
await asgi_response.start_response(empty_send)
-async def test_file_response_with_missing_file_raises_error(tmpdir: Path) -> None:
- path = tmpdir / "404.txt"
- with pytest.raises(ImproperlyConfiguredException):
- asgi_response = ASGIFileResponse(file_path=path, filename="404.txt")
- await asgi_response.start_response(empty_send)
-
-
@pytest.mark.parametrize("chunk_size", [4, 8, 16, 256, 512, 1024, 2048])
async def test_file_iterator(tmpdir: Path, chunk_size: int) -> None:
content = urandom(1024)
@@ -135,3 +132,147 @@ def handler() -> File:
assert response.status_code == HTTP_200_OK
assert response.content == content
assert response.headers["content-length"] == str(len(content))
+
+
[email protected]("file_system", (BaseLocalFileSystem(), LocalFileSystem()))
+def test_file_with_different_file_systems(tmpdir: "Path", file_system: "FileSystemProtocol") -> None:
+ path = tmpdir / "text.txt"
+ path.write_text("content", "utf-8")
+
+ @get("/", media_type="application/octet-stream")
+ def handler() -> File:
+ return File(
+ filename="text.txt",
+ path=path,
+ file_system=file_system,
+ )
+
+ with create_test_client(handler, debug=True) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_200_OK
+ assert response.text == "content"
+ assert response.headers.get("content-disposition") == 'attachment; filename="text.txt"'
+
+
+def test_file_with_passed_in_file_info(tmpdir: "Path") -> None:
+ path = tmpdir / "text.txt"
+ path.write_text("content", "utf-8")
+
+ fs = LocalFileSystem()
+ fs_info = fs.info(tmpdir / "text.txt")
+
+ assert fs_info
+
+ @get("/", media_type="application/octet-stream")
+ def handler() -> File:
+ return File(filename="text.txt", path=path, file_system=fs, file_info=fs_info) # pyright: ignore
+
+ with create_test_client(handler) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_200_OK, response.text
+ assert response.text == "content"
+ assert response.headers.get("content-disposition") == 'attachment; filename="text.txt"'
+
+
+def test_file_with_passed_in_stat_result(tmpdir: "Path") -> None:
+ path = tmpdir / "text.txt"
+ path.write_text("content", "utf-8")
+
+ fs = LocalFileSystem()
+ stat_result = stat(path)
+
+ @get("/", media_type="application/octet-stream")
+ def handler() -> File:
+ return File(filename="text.txt", path=path, file_system=fs, stat_result=stat_result)
+
+ with create_test_client(handler) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_200_OK
+ assert response.text == "content"
+ assert response.headers.get("content-disposition") == 'attachment; filename="text.txt"'
+
+
+async def test_file_with_symbolic_link(tmpdir: "Path") -> None:
+ path = tmpdir / "text.txt"
+ path.write_text("content", "utf-8")
+
+ linked = tmpdir / "alt.txt"
+ os.symlink(path, linked, target_is_directory=False)
+
+ fs = BaseLocalFileSystem()
+ file_info = await fs.info(linked)
+
+ assert file_info["islink"]
+
+ @get("/", media_type="application/octet-stream")
+ def handler() -> File:
+ return File(filename="alt.txt", path=linked, file_system=fs, file_info=file_info)
+
+ with create_test_client(handler) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_200_OK
+ assert response.text == "content"
+ assert response.headers.get("content-disposition") == 'attachment; filename="alt.txt"'
+
+
+async def test_file_sets_etag_correctly(tmpdir: "Path") -> None:
+ path = tmpdir / "file.txt"
+ content = b"<file content>"
+ Path(path).write_bytes(content)
+ etag = ETag(value="special")
+
+ @get("/")
+ def handler() -> File:
+ return File(path=path, etag=etag)
+
+ with create_test_client(handler) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_200_OK
+ assert response.headers["etag"] == '"special"'
+
+
+def test_file_system_validation(tmpdir: "Path") -> None:
+ path = tmpdir / "text.txt"
+ path.write_text("content", "utf-8")
+
+ class FSWithoutOpen:
+ def info(self) -> None:
+ return
+
+ with pytest.raises(ImproperlyConfiguredException):
+ File(
+ filename="text.txt",
+ path=path,
+ file_system=FSWithoutOpen(), # type:ignore[arg-type]
+ )
+
+ class FSWithoutInfo:
+ def open(self) -> None:
+ return
+
+ with pytest.raises(ImproperlyConfiguredException):
+ File(
+ filename="text.txt",
+ path=path,
+ file_system=FSWithoutInfo(), # type:ignore[arg-type]
+ )
+
+ class ImplementedFS:
+ def info(self) -> None:
+ return
+
+ def open(self) -> None:
+ return
+
+ assert File(
+ filename="text.txt",
+ path=path,
+ file_system=ImplementedFS(), # type:ignore[arg-type]
+ )
+
+
+async def test_file_response_with_missing_file_raises_error(tmpdir: Path) -> None:
+ path = tmpdir / "404.txt"
+ with pytest.raises(ImproperlyConfiguredException):
+ asgi_response = ASGIFileResponse(file_path=path, filename="404.txt")
+ await asgi_response.start_response(empty_send)
diff --git a/tests/response/test_redirect_response.py b/tests/unit/test_response/test_redirect_response.py
similarity index 71%
rename from tests/response/test_redirect_response.py
rename to tests/unit/test_response/test_redirect_response.py
--- a/tests/response/test_redirect_response.py
+++ b/tests/unit/test_response/test_redirect_response.py
@@ -3,15 +3,16 @@
https://github.com/encode/starlette/blob/master/tests/test_responses.py And are meant to ensure our compatibility with
their API.
"""
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Optional
import pytest
+from litestar import get
from litestar.exceptions import ImproperlyConfiguredException
from litestar.response.base import ASGIResponse
-from litestar.response.redirect import ASGIRedirectResponse
+from litestar.response.redirect import ASGIRedirectResponse, Redirect
from litestar.status_codes import HTTP_200_OK
-from litestar.testing import TestClient
+from litestar.testing import TestClient, create_test_client
if TYPE_CHECKING:
from litestar.types import Receive, Scope, Send
@@ -81,3 +82,34 @@ async def app(scope: "Scope", receive: "Receive", send: "Send") -> None:
def test_redirect_response_media_type_validation() -> None:
with pytest.raises(ImproperlyConfiguredException):
ASGIRedirectResponse(path="/", media_type="application/json")
+
+
[email protected](
+ "status_code,expected_status_code",
+ [
+ (301, 301),
+ (302, 302),
+ (303, 303),
+ (307, 307),
+ (308, 308),
+ ],
+)
+def test_redirect_dynamic_status_code(status_code: Optional[int], expected_status_code: int) -> None:
+ @get("/")
+ def handler() -> Redirect:
+ return Redirect(path="/something-else", status_code=status_code) # type: ignore[arg-type]
+
+ with create_test_client([handler], debug=True) as client:
+ res = client.get("/", follow_redirects=False)
+ assert res.status_code == expected_status_code
+
+
[email protected]("handler_status_code", [301, 307, None])
+def test_redirect(handler_status_code: Optional[int]) -> None:
+ @get("/", status_code=handler_status_code)
+ def handler() -> Redirect:
+ return Redirect(path="/something-else", status_code=301)
+
+ with create_test_client([handler]) as client:
+ res = client.get("/", follow_redirects=False)
+ assert res.status_code == 301
diff --git a/tests/response/test_response_class.py b/tests/unit/test_response/test_response_class.py
similarity index 100%
rename from tests/response/test_response_class.py
rename to tests/unit/test_response/test_response_class.py
diff --git a/tests/response/test_response_cookies.py b/tests/unit/test_response/test_response_cookies.py
similarity index 100%
rename from tests/response/test_response_cookies.py
rename to tests/unit/test_response/test_response_cookies.py
diff --git a/tests/response/test_response_headers.py b/tests/unit/test_response/test_response_headers.py
similarity index 96%
rename from tests/response/test_response_headers.py
rename to tests/unit/test_response/test_response_headers.py
--- a/tests/response/test_response_headers.py
+++ b/tests/unit/test_response/test_response_headers.py
@@ -5,7 +5,6 @@
from litestar import Controller, HttpMethod, Litestar, Router, get, post
from litestar.datastructures import CacheControlHeader, ETag, ResponseHeader
from litestar.datastructures.headers import Header
-from litestar.exceptions import ImproperlyConfiguredException
from litestar.status_codes import HTTP_201_CREATED
from litestar.testing import TestClient, create_test_client
@@ -73,12 +72,6 @@ def handler_one() -> None:
assert handler_one.resolve_response_headers() == frozenset([ResponseHeader(name="foo", value="bar")])
-def test_response_headers_validation() -> None:
- ResponseHeader(name="test", documentation_only=True)
- with pytest.raises(ImproperlyConfiguredException):
- ResponseHeader(name="test")
-
-
def test_response_headers_rendering() -> None:
@post(
path="/test",
diff --git a/tests/response/test_serialization.py b/tests/unit/test_response/test_serialization.py
similarity index 100%
rename from tests/response/test_serialization.py
rename to tests/unit/test_response/test_serialization.py
diff --git a/tests/response/test_streaming_response.py b/tests/unit/test_response/test_streaming_response.py
similarity index 100%
rename from tests/response/test_streaming_response.py
rename to tests/unit/test_response/test_streaming_response.py
diff --git a/tests/response/test_type_encoders.py b/tests/unit/test_response/test_type_encoders.py
similarity index 100%
rename from tests/response/test_type_encoders.py
rename to tests/unit/test_response/test_type_encoders.py
diff --git a/tests/handlers/http/__init__.py b/tests/unit/test_security/__init__.py
similarity index 100%
rename from tests/handlers/http/__init__.py
rename to tests/unit/test_security/__init__.py
diff --git a/tests/security/test_security.py b/tests/unit/test_security/test_security.py
similarity index 100%
rename from tests/security/test_security.py
rename to tests/unit/test_security/test_security.py
diff --git a/tests/security/test_session_auth.py b/tests/unit/test_security/test_session_auth.py
similarity index 100%
rename from tests/security/test_session_auth.py
rename to tests/unit/test_security/test_session_auth.py
diff --git a/tests/test_serialization.py b/tests/unit/test_serialization.py
similarity index 100%
rename from tests/test_serialization.py
rename to tests/unit/test_serialization.py
diff --git a/tests/handlers/websocket/__init__.py b/tests/unit/test_signature/__init__.py
similarity index 100%
rename from tests/handlers/websocket/__init__.py
rename to tests/unit/test_signature/__init__.py
diff --git a/tests/signature/test_attrs_signature_modelling.py b/tests/unit/test_signature/test_attrs_signature_modelling.py
similarity index 100%
rename from tests/signature/test_attrs_signature_modelling.py
rename to tests/unit/test_signature/test_attrs_signature_modelling.py
diff --git a/tests/signature/test_parsing.py b/tests/unit/test_signature/test_parsing.py
similarity index 100%
rename from tests/signature/test_parsing.py
rename to tests/unit/test_signature/test_parsing.py
diff --git a/tests/signature/test_signature_validation.py b/tests/unit/test_signature/test_signature_validation.py
similarity index 100%
rename from tests/signature/test_signature_validation.py
rename to tests/unit/test_signature/test_signature_validation.py
diff --git a/tests/signature/test_utils.py b/tests/unit/test_signature/test_utils.py
similarity index 100%
rename from tests/signature/test_utils.py
rename to tests/unit/test_signature/test_utils.py
diff --git a/tests/life_cycle_hooks/__init__.py b/tests/unit/test_static_files/__init__.py
similarity index 100%
rename from tests/life_cycle_hooks/__init__.py
rename to tests/unit/test_static_files/__init__.py
diff --git a/tests/static_files/test_file_serving_resolution.py b/tests/unit/test_static_files/test_file_serving_resolution.py
similarity index 100%
rename from tests/static_files/test_file_serving_resolution.py
rename to tests/unit/test_static_files/test_file_serving_resolution.py
diff --git a/tests/static_files/test_html_mode.py b/tests/unit/test_static_files/test_html_mode.py
similarity index 100%
rename from tests/static_files/test_html_mode.py
rename to tests/unit/test_static_files/test_html_mode.py
diff --git a/tests/static_files/test_static_files_validation.py b/tests/unit/test_static_files/test_static_files_validation.py
similarity index 100%
rename from tests/static_files/test_static_files_validation.py
rename to tests/unit/test_static_files/test_static_files_validation.py
diff --git a/tests/test_stores.py b/tests/unit/test_stores.py
similarity index 100%
rename from tests/test_stores.py
rename to tests/unit/test_stores.py
diff --git a/tests/logging_config/__init__.py b/tests/unit/test_template/__init__.py
similarity index 100%
rename from tests/logging_config/__init__.py
rename to tests/unit/test_template/__init__.py
diff --git a/tests/template/test_built_in.py b/tests/unit/test_template/test_built_in.py
similarity index 84%
rename from tests/template/test_built_in.py
rename to tests/unit/test_template/test_built_in.py
--- a/tests/template/test_built_in.py
+++ b/tests/unit/test_template/test_built_in.py
@@ -41,8 +41,8 @@ def engine_test(request: Any) -> EngineTest:
@pytest.fixture()
-def index_handler(engine_test: EngineTest, template_dir: Path) -> "HTTPRouteHandler":
- Path(template_dir / "index.html").write_text(engine_test.index_template)
+def index_handler(engine_test: EngineTest, tmp_path: Path) -> "HTTPRouteHandler":
+ Path(tmp_path / "index.html").write_text(engine_test.index_template)
@get(path="/")
def index_handler() -> Template:
@@ -52,8 +52,8 @@ def index_handler() -> Template:
@pytest.fixture()
-def nested_path_handler(engine_test: EngineTest, template_dir: Path) -> "HTTPRouteHandler":
- nested_path = template_dir / "nested-dir"
+def nested_path_handler(engine_test: EngineTest, tmp_path: Path) -> "HTTPRouteHandler":
+ nested_path = tmp_path / "nested-dir"
nested_path.mkdir()
Path(nested_path / "nested.html").write_text(engine_test.nested_template)
@@ -65,8 +65,8 @@ def nested_path_handler() -> Template:
@pytest.fixture()
-def template_config(engine_test: EngineTest, template_dir: Path) -> TemplateConfig:
- return TemplateConfig(engine=engine_test.engine, directory=template_dir)
+def template_config(engine_test: EngineTest, tmp_path: Path) -> TemplateConfig:
+ return TemplateConfig(engine=engine_test.engine, directory=tmp_path)
def test_template(index_handler: "HTTPRouteHandler", template_config: TemplateConfig) -> None:
@@ -77,7 +77,7 @@ def test_template(index_handler: "HTTPRouteHandler", template_config: TemplateCo
assert response.headers["Content-Type"] == "text/html; charset=utf-8"
-def test_nested_template_directory(nested_path_handler: "HTTPRouteHandler", template_config: TemplateConfig) -> None:
+def test_nested_tmp_pathectory(nested_path_handler: "HTTPRouteHandler", template_config: TemplateConfig) -> None:
with create_test_client(route_handlers=[nested_path_handler], template_config=template_config) as client:
response = client.request("GET", "/nested")
assert response.status_code == 200, response.text
@@ -96,8 +96,8 @@ def invalid_template_name_handler() -> Template:
assert response.json() == {"detail": "Template invalid.html not found.", "status_code": 500}
-def test_no_context(template_dir: Path, template_config: TemplateConfig) -> None:
- Path(template_dir / "index.html").write_text("<html>This works!</html>")
+def test_no_context(tmp_path: Path, template_config: TemplateConfig) -> None:
+ Path(tmp_path / "index.html").write_text("<html>This works!</html>")
@get(path="/")
def index() -> Template:
diff --git a/tests/template/test_builtin_functions.py b/tests/unit/test_template/test_builtin_functions.py
similarity index 80%
rename from tests/template/test_builtin_functions.py
rename to tests/unit/test_template/test_builtin_functions.py
--- a/tests/template/test_builtin_functions.py
+++ b/tests/unit/test_template/test_builtin_functions.py
@@ -15,8 +15,8 @@
@pytest.mark.xfail(sys.platform == "win32", reason="For some reason this is flaky on windows")
-def test_jinja_url_for(template_dir: Path) -> None:
- template_config = TemplateConfig(engine=JinjaTemplateEngine, directory=template_dir)
+def test_jinja_url_for(tmp_path: Path) -> None:
+ template_config = TemplateConfig(engine=JinjaTemplateEngine, directory=tmp_path)
@get(path="/")
def tpl_renderer() -> Template:
@@ -33,7 +33,7 @@ def complex_handler() -> None:
with create_test_client(
route_handlers=[simple_handler, complex_handler, tpl_renderer], template_config=template_config, debug=True
) as client:
- Path(template_dir / "tpl.html").write_text("{{ url_for('simple') }}")
+ Path(tmp_path / "tpl.html").write_text("{{ url_for('simple') }}")
response = client.get("/")
assert response.status_code == 200
@@ -42,7 +42,7 @@ def complex_handler() -> None:
with create_test_client(
route_handlers=[simple_handler, complex_handler, tpl_renderer], template_config=template_config
) as client:
- Path(template_dir / "tpl.html").write_text("{{ url_for('complex', int_param=100, time_param='18:00') }}")
+ Path(tmp_path / "tpl.html").write_text("{{ url_for('complex', int_param=100, time_param='18:00') }}")
response = client.get("/")
assert response.status_code == 200
@@ -52,7 +52,7 @@ def complex_handler() -> None:
route_handlers=[simple_handler, complex_handler, tpl_renderer], template_config=template_config
) as client:
# missing route params should cause 500 err
- Path(template_dir / "tpl.html").write_text("{{ url_for('complex') }}")
+ Path(tmp_path / "tpl.html").write_text("{{ url_for('complex') }}")
response = client.get("/")
assert response.status_code == 500
@@ -60,7 +60,7 @@ def complex_handler() -> None:
route_handlers=[simple_handler, complex_handler, tpl_renderer], template_config=template_config
) as client:
# wrong param type should also cause 500 error
- Path(template_dir / "tpl.html").write_text("{{ url_for('complex', int_param='100', time_param='18:00') }}")
+ Path(tmp_path / "tpl.html").write_text("{{ url_for('complex', int_param='100', time_param='18:00') }}")
response = client.get("/")
assert response.status_code == 500
@@ -68,15 +68,15 @@ def complex_handler() -> None:
with create_test_client(
route_handlers=[simple_handler, complex_handler, tpl_renderer], template_config=template_config
) as client:
- Path(template_dir / "tpl.html").write_text("{{ url_for('non-existent-route') }}")
+ Path(tmp_path / "tpl.html").write_text("{{ url_for('non-existent-route') }}")
response = client.get("/")
assert response.status_code == 500
@pytest.mark.xfail(sys.platform == "win32", reason="For some reason this is flaky on windows")
-def test_jinja_url_for_static_asset(template_dir: Path, tmp_path: Path) -> None:
- template_config = TemplateConfig(engine=JinjaTemplateEngine, directory=template_dir)
+def test_jinja_url_for_static_asset(tmp_path: Path) -> None:
+ template_config = TemplateConfig(engine=JinjaTemplateEngine, directory=tmp_path)
@get(path="/", name="tpl_renderer")
def tpl_renderer() -> Template:
@@ -87,7 +87,7 @@ def tpl_renderer() -> Template:
template_config=template_config,
static_files_config=[StaticFilesConfig(path="/static/css", directories=[tmp_path], name="css")],
) as client:
- Path(template_dir / "tpl.html").write_text("{{ url_for_static_asset('css', 'main/main.css') }}")
+ Path(tmp_path / "tpl.html").write_text("{{ url_for_static_asset('css', 'main/main.css') }}")
response = client.get("/")
assert response.status_code == 200
@@ -98,7 +98,7 @@ def tpl_renderer() -> Template:
template_config=template_config,
static_files_config=[StaticFilesConfig(path="/static/css", directories=[tmp_path], name="css")],
) as client:
- Path(template_dir / "tpl.html").write_text("{{ url_for_static_asset('non-existent', 'main.css') }}")
+ Path(tmp_path / "tpl.html").write_text("{{ url_for_static_asset('non-existent', 'main.css') }}")
response = client.get("/")
assert response.status_code == 500
@@ -108,7 +108,7 @@ def tpl_renderer() -> Template:
template_config=template_config,
static_files_config=[StaticFilesConfig(path="/static/css", directories=[tmp_path], name="css")],
) as client:
- Path(template_dir / "tpl.html").write_text("{{ url_for_static_asset('tpl_renderer', 'main.css') }}")
+ Path(tmp_path / "tpl.html").write_text("{{ url_for_static_asset('tpl_renderer', 'main.css') }}")
response = client.get("/")
assert response.status_code == 500
@@ -123,9 +123,9 @@ def tpl_renderer() -> Template:
),
)
def test_mako_url_for_static_asset(
- template_dir: Path, tmp_path: Path, builtin: str, expected_status: int, expected_text: Optional[str]
+ tmp_path: Path, builtin: str, expected_status: int, expected_text: Optional[str]
) -> None:
- template_config = TemplateConfig(engine=MakoTemplateEngine, directory=template_dir)
+ template_config = TemplateConfig(engine=MakoTemplateEngine, directory=tmp_path)
@get(path="/", name="tpl_renderer")
def tpl_renderer() -> Template:
@@ -136,7 +136,7 @@ def tpl_renderer() -> Template:
template_config=template_config,
static_files_config=[StaticFilesConfig(path="/static/css", directories=[tmp_path], name="css")],
) as client:
- Path(template_dir / "tpl.html").write_text(builtin)
+ Path(tmp_path / "tpl.html").write_text(builtin)
response = client.get("/")
assert response.status_code == expected_status
@@ -153,8 +153,8 @@ def tpl_renderer() -> Template:
("${url_for('non-existent-route')}", HTTP_500_INTERNAL_SERVER_ERROR, None),
),
)
-def test_mako_url_for(template_dir: Path, builtin: str, expected_status: int, expected_text: Optional[str]) -> None:
- template_config = TemplateConfig(engine=MakoTemplateEngine, directory=template_dir)
+def test_mako_url_for(tmp_path: Path, builtin: str, expected_status: int, expected_text: Optional[str]) -> None:
+ template_config = TemplateConfig(engine=MakoTemplateEngine, directory=tmp_path)
@get(path="/")
def tpl_renderer() -> Template:
@@ -172,7 +172,7 @@ def complex_handler() -> None:
route_handlers=[simple_handler, complex_handler, tpl_renderer], template_config=template_config
) as client:
# missing route params should cause 500 err
- Path(template_dir / "tpl.html").write_text(builtin)
+ Path(tmp_path / "tpl.html").write_text(builtin)
response = client.get("/")
assert response.status_code == expected_status
if expected_text:
diff --git a/tests/template/test_config.py b/tests/unit/test_template/test_config.py
similarity index 74%
rename from tests/template/test_config.py
rename to tests/unit/test_template/test_config.py
--- a/tests/template/test_config.py
+++ b/tests/unit/test_template/test_config.py
@@ -7,9 +7,9 @@
from pathlib import Path
-def test_pytest_config_caches_engine_instance(template_dir: "Path") -> None:
+def test_pytest_config_caches_engine_instance(tmp_path: "Path") -> None:
config = TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=JinjaTemplateEngine,
)
assert config.engine_instance is config.engine_instance
diff --git a/tests/template/test_context.py b/tests/unit/test_template/test_context.py
similarity index 88%
rename from tests/template/test_context.py
rename to tests/unit/test_template/test_context.py
--- a/tests/template/test_context.py
+++ b/tests/unit/test_template/test_context.py
@@ -18,8 +18,8 @@
(MakoTemplateEngine, 'path: ${request.scope["path"]}', "path: /"),
),
)
-def test_request_is_set_in_context(engine: Any, template: str, expected: str, template_dir: Path) -> None:
- Path(template_dir / "abc.html").write_text(template)
+def test_request_is_set_in_context(engine: Any, template: str, expected: str, tmp_path: Path) -> None:
+ Path(tmp_path / "abc.html").write_text(template)
@get(path="/", media_type=MediaType.HTML)
def handler() -> Template:
@@ -28,7 +28,7 @@ def handler() -> Template:
with create_test_client(
route_handlers=[handler],
template_config=TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=engine,
),
) as client:
diff --git a/tests/template/test_csrf_token.py b/tests/unit/test_template/test_csrf_token.py
similarity index 85%
rename from tests/template/test_csrf_token.py
rename to tests/unit/test_template/test_csrf_token.py
--- a/tests/template/test_csrf_token.py
+++ b/tests/unit/test_template/test_csrf_token.py
@@ -22,8 +22,8 @@
(MakoTemplateEngine, "${csrf_token()}"),
),
)
-def test_csrf_token(engine: Any, template: str, template_dir: Path) -> None:
- Path(template_dir / "abc.html").write_text(template)
+def test_csrf_token(engine: Any, template: str, tmp_path: Path) -> None:
+ Path(tmp_path / "abc.html").write_text(template)
@get(path="/", media_type=MediaType.HTML)
def handler() -> Template:
@@ -34,7 +34,7 @@ def handler() -> Template:
with create_test_client(
route_handlers=[handler],
template_config=TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=engine,
),
csrf_config=csrf_config,
@@ -50,8 +50,8 @@ def handler() -> Template:
(MakoTemplateEngine, "${csrf_input}"),
),
)
-def test_csrf_input(engine: Any, template: str, template_dir: Path) -> None:
- Path(template_dir / "abc.html").write_text(template)
+def test_csrf_input(engine: Any, template: str, tmp_path: Path) -> None:
+ Path(tmp_path / "abc.html").write_text(template)
token = {"value": ""}
@get(path="/", media_type=MediaType.HTML)
@@ -64,7 +64,7 @@ def handler(scope: Scope) -> Template:
with create_test_client(
route_handlers=[handler],
template_config=TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=engine,
),
csrf_config=csrf_config,
diff --git a/tests/template/test_template.py b/tests/unit/test_template/test_template.py
similarity index 82%
rename from tests/template/test_template.py
rename to tests/unit/test_template/test_template.py
--- a/tests/template/test_template.py
+++ b/tests/unit/test_template/test_template.py
@@ -28,7 +28,7 @@ def invalid_path() -> Template:
assert response.json() == {"detail": "Template engine is not configured", "status_code": 500}
-def test_engine_passed_to_callback(template_dir: "Path") -> None:
+def test_engine_passed_to_callback(tmp_path: "Path") -> None:
received_engine: Optional[JinjaTemplateEngine] = None
def callback(engine: JinjaTemplateEngine) -> None:
@@ -38,7 +38,7 @@ def callback(engine: JinjaTemplateEngine) -> None:
app = Litestar(
route_handlers=[],
template_config=TemplateConfig(
- directory=template_dir,
+ directory=tmp_path,
engine=JinjaTemplateEngine,
engine_callback=callback,
),
@@ -49,8 +49,8 @@ def callback(engine: JinjaTemplateEngine) -> None:
@pytest.mark.parametrize("engine", (JinjaTemplateEngine, MakoTemplateEngine))
-def test_engine_instance(engine: Type["TemplateEngineProtocol"], template_dir: "Path") -> None:
- engine_instance = engine(template_dir)
+def test_engine_instance(engine: Type["TemplateEngineProtocol"], tmp_path: "Path") -> None:
+ engine_instance = engine(tmp_path)
if isinstance(engine_instance, JinjaTemplateEngine):
assert engine_instance.engine.autoescape is True
@@ -62,21 +62,21 @@ def test_engine_instance(engine: Type["TemplateEngineProtocol"], template_dir: "
@pytest.mark.parametrize("engine", (JinjaTemplateEngine, MakoTemplateEngine))
-def test_directory_validation(engine: Type["TemplateEngineProtocol"], template_dir: "Path") -> None:
+def test_directory_validation(engine: Type["TemplateEngineProtocol"], tmp_path: "Path") -> None:
with pytest.raises(ImproperlyConfiguredException):
TemplateConfig(engine=engine)
@pytest.mark.parametrize("media_type", [MediaType.HTML, MediaType.TEXT, "text/arbitrary"])
-def test_media_type(media_type: Union[MediaType, str], template_dir: Path) -> None:
- (template_dir / "hello.tpl").write_text("hello")
+def test_media_type(media_type: Union[MediaType, str], tmp_path: Path) -> None:
+ (tmp_path / "hello.tpl").write_text("hello")
@get("/", media_type=media_type)
def index() -> Template:
return Template(template_name="hello.tpl")
with create_test_client(
- [index], template_config=TemplateConfig(directory=template_dir, engine=JinjaTemplateEngine)
+ [index], template_config=TemplateConfig(directory=tmp_path, engine=JinjaTemplateEngine)
) as client:
res = client.get("/")
assert res.status_code == 200
@@ -100,24 +100,24 @@ def index() -> Template:
],
)
@pytest.mark.skipif(sys.platform == "win32", reason="mimetypes.guess_types is unreliable on windows")
-def test_media_type_inferred(extension: str, expected_type: MediaType, template_dir: Path) -> None:
+def test_media_type_inferred(extension: str, expected_type: MediaType, tmp_path: Path) -> None:
tpl_name = "hello" + extension
- (template_dir / tpl_name).write_text("hello")
+ (tmp_path / tpl_name).write_text("hello")
@get("/")
def index() -> Template:
return Template(template_name=tpl_name)
with create_test_client(
- [index], template_config=TemplateConfig(directory=template_dir, engine=JinjaTemplateEngine)
+ [index], template_config=TemplateConfig(directory=tmp_path, engine=JinjaTemplateEngine)
) as client:
res = client.get("/")
assert res.status_code == 200
assert res.headers["content-type"].startswith(expected_type.value)
-def test_before_request_handler_content_type(template_dir: Path) -> None:
- template_loc = template_dir / "about.html"
+def test_before_request_handler_content_type(tmp_path: Path) -> None:
+ template_loc = tmp_path / "about.html"
def before_request_handler(_: "Request") -> None:
template_loc.write_text("before request")
@@ -127,7 +127,7 @@ def index() -> Template:
return Template(template_name="about.html")
with create_test_client(
- [index], template_config=TemplateConfig(directory=template_dir, engine=JinjaTemplateEngine)
+ [index], template_config=TemplateConfig(directory=tmp_path, engine=JinjaTemplateEngine)
) as client:
res = client.get("/")
assert res.status_code == 200
diff --git a/tests/middleware/__init__.py b/tests/unit/test_testing/__init__.py
similarity index 100%
rename from tests/middleware/__init__.py
rename to tests/unit/test_testing/__init__.py
diff --git a/tests/testing/test_async_test_client.py b/tests/unit/test_testing/test_async_test_client.py
similarity index 100%
rename from tests/testing/test_async_test_client.py
rename to tests/unit/test_testing/test_async_test_client.py
diff --git a/tests/testing/test_testing.py b/tests/unit/test_testing/test_request_factory.py
similarity index 69%
rename from tests/testing/test_testing.py
rename to tests/unit/test_testing/test_request_factory.py
--- a/tests/testing/test_testing.py
+++ b/tests/unit/test_testing/test_request_factory.py
@@ -1,24 +1,16 @@
import json
-from typing import TYPE_CHECKING, Any, Callable, Dict, Union
+from typing import Any, Callable, Dict, Union
import pytest
from pydantic import BaseModel
-from litestar import HttpMethod, Litestar, Request, get, post
+from litestar import HttpMethod, Litestar, get
from litestar.datastructures import Cookie, MultiDict
from litestar.enums import ParamType, RequestEncodingType
-from litestar.middleware.session.server_side import ServerSideSessionConfig
-from litestar.stores.base import Store
-from litestar.stores.redis import RedisStore
-from litestar.testing import RequestFactory, TestClient, create_test_client
+from litestar.testing import RequestFactory
from tests import Pet, PetFactory
-if TYPE_CHECKING:
- from litestar.middleware.session.base import BaseBackendConfig
- from litestar.types import AnyIOBackend
-
_DEFAULT_REQUEST_FACTORY_URL = "http://test.org:3000/"
-
pet = PetFactory.build()
@@ -196,66 +188,3 @@ async def test_request_factory_post_put_patch(factory: Callable, method: HttpMet
assert request.headers.get("header1") == "value1"
body = await request.body()
assert json.loads(body) == pet.dict()
-
-
[email protected]()
-def skip_for_trio_redis(
- session_backend_config: "BaseBackendConfig", test_client_backend: "AnyIOBackend", store: Store
-) -> None:
- if (
- isinstance(session_backend_config, ServerSideSessionConfig)
- and isinstance(store, RedisStore)
- and test_client_backend == "trio"
- ):
- pytest.skip("fakeredis does not always play well with trio, so skip this for now")
-
-
[email protected]("skip_for_trio_redis")
[email protected]("with_domain", [False, True])
-def test_test_client_set_session_data(
- with_domain: bool,
- session_backend_config: "BaseBackendConfig",
- test_client_backend: "AnyIOBackend",
-) -> None:
- session_data = {"foo": "bar"}
-
- if with_domain:
- session_backend_config.domain = "testserver.local"
-
- @get(path="/test")
- def get_session_data(request: Request) -> Dict[str, Any]:
- return request.session
-
- app = Litestar(route_handlers=[get_session_data], middleware=[session_backend_config.middleware])
-
- with TestClient(app=app, session_config=session_backend_config, backend=test_client_backend) as client:
- client.set_session_data(session_data)
- assert session_data == client.get("/test").json()
-
-
[email protected]("skip_for_trio_redis")
[email protected]("with_domain", [False, True])
-def test_test_client_get_session_data(
- with_domain: bool, session_backend_config: "BaseBackendConfig", test_client_backend: "AnyIOBackend", store: Store
-) -> None:
- session_data = {"foo": "bar"}
-
- if with_domain:
- session_backend_config.domain = "testserver.local"
-
- @post(path="/test")
- def set_session_data(request: Request) -> None:
- request.session.update(session_data)
-
- app = Litestar(
- route_handlers=[set_session_data], middleware=[session_backend_config.middleware], stores={"session": store}
- )
-
- with TestClient(app=app, session_config=session_backend_config, backend=test_client_backend) as client:
- client.post("/test")
- assert client.get_session_data() == session_data
-
-
-def test_create_test_client_warns_problematic_domain() -> None:
- with pytest.warns(UserWarning):
- create_test_client(base_url="http://testserver", route_handlers=[])
diff --git a/tests/testing/test_sync_test_client.py b/tests/unit/test_testing/test_sync_test_client.py
similarity index 100%
rename from tests/testing/test_sync_test_client.py
rename to tests/unit/test_testing/test_sync_test_client.py
diff --git a/tests/unit/test_testing/test_test_client.py b/tests/unit/test_testing/test_test_client.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/test_testing/test_test_client.py
@@ -0,0 +1,76 @@
+from typing import TYPE_CHECKING, Any, Dict
+
+import pytest
+
+from litestar import Litestar, Request, get, post
+from litestar.middleware.session.server_side import ServerSideSessionConfig
+from litestar.stores.base import Store
+from litestar.stores.redis import RedisStore
+from litestar.testing import TestClient
+
+if TYPE_CHECKING:
+ from litestar.middleware.session.base import BaseBackendConfig
+ from litestar.types import AnyIOBackend
+
+
[email protected]()
+def skip_for_trio_redis(
+ session_backend_config: "BaseBackendConfig", test_client_backend: "AnyIOBackend", store: Store
+) -> None:
+ if (
+ isinstance(session_backend_config, ServerSideSessionConfig)
+ and isinstance(store, RedisStore)
+ and test_client_backend == "trio"
+ ):
+ pytest.skip("fakeredis does not always play well with trio, so skip this for now")
+
+
[email protected]("skip_for_trio_redis")
[email protected]("with_domain", [False, True])
+def test_test_client_set_session_data(
+ with_domain: bool,
+ session_backend_config: "BaseBackendConfig",
+ test_client_backend: "AnyIOBackend",
+) -> None:
+ session_data = {"foo": "bar"}
+
+ if with_domain:
+ session_backend_config.domain = "testserver.local"
+
+ @get(path="/test")
+ def get_session_data(request: Request) -> Dict[str, Any]:
+ return request.session
+
+ app = Litestar(route_handlers=[get_session_data], middleware=[session_backend_config.middleware])
+
+ with TestClient(app=app, session_config=session_backend_config, backend=test_client_backend) as client:
+ client.set_session_data(session_data)
+ assert session_data == client.get("/test").json()
+
+
[email protected]("skip_for_trio_redis")
[email protected]("with_domain", [False, True])
+def test_test_client_get_session_data(
+ with_domain: bool, session_backend_config: "BaseBackendConfig", test_client_backend: "AnyIOBackend", store: Store
+) -> None:
+ session_data = {"foo": "bar"}
+
+ if with_domain:
+ session_backend_config.domain = "testserver.local"
+
+ @post(path="/test")
+ def set_session_data(request: Request) -> None:
+ request.session.update(session_data)
+
+ app = Litestar(
+ route_handlers=[set_session_data], middleware=[session_backend_config.middleware], stores={"session": store}
+ )
+
+ with TestClient(app=app, session_config=session_backend_config, backend=test_client_backend) as client:
+ client.post("/test")
+ assert client.get_session_data() == session_data
+
+
+def test_create_test_client_warns_problematic_domain() -> None:
+ with pytest.warns(UserWarning):
+ TestClient(app=Litestar(), base_url="http://testserver")
diff --git a/tests/middleware/session/__init__.py b/tests/unit/test_types/__init__.py
similarity index 100%
rename from tests/middleware/session/__init__.py
rename to tests/unit/test_types/__init__.py
diff --git a/tests/types/test_protocols.py b/tests/unit/test_types/test_protocols.py
similarity index 100%
rename from tests/types/test_protocols.py
rename to tests/unit/test_types/test_protocols.py
diff --git a/tests/test_typing.py b/tests/unit/test_typing.py
similarity index 99%
rename from tests/test_typing.py
rename to tests/unit/test_typing.py
--- a/tests/test_typing.py
+++ b/tests/unit/test_typing.py
@@ -6,7 +6,8 @@
from typing_extensions import Annotated
from litestar.typing import ParsedType
-from tests.utils.test_signature import T, _check_parsed_type, parsed_type_int, test_type_hints
+
+from .test_utils.test_signature import T, _check_parsed_type, parsed_type_int, test_type_hints
@pytest.mark.parametrize(
diff --git a/tests/openapi/__init__.py b/tests/unit/test_utils/__init__.py
similarity index 100%
rename from tests/openapi/__init__.py
rename to tests/unit/test_utils/__init__.py
diff --git a/tests/utils/test_dataclass.py b/tests/unit/test_utils/test_dataclass.py
similarity index 100%
rename from tests/utils/test_dataclass.py
rename to tests/unit/test_utils/test_dataclass.py
diff --git a/tests/utils/test_helpers.py b/tests/unit/test_utils/test_helpers.py
similarity index 100%
rename from tests/utils/test_helpers.py
rename to tests/unit/test_utils/test_helpers.py
diff --git a/tests/utils/test_path.py b/tests/unit/test_utils/test_path.py
similarity index 100%
rename from tests/utils/test_path.py
rename to tests/unit/test_utils/test_path.py
diff --git a/tests/utils/test_predicates.py b/tests/unit/test_utils/test_predicates.py
similarity index 76%
rename from tests/utils/test_predicates.py
rename to tests/unit/test_utils/test_predicates.py
--- a/tests/utils/test_predicates.py
+++ b/tests/unit/test_utils/test_predicates.py
@@ -1,7 +1,10 @@
from collections import defaultdict, deque
+from functools import partial
from inspect import Signature
from typing import (
Any,
+ AsyncGenerator,
+ Callable,
ClassVar,
DefaultDict,
Deque,
@@ -24,7 +27,7 @@
from litestar import Response, get
from litestar.pagination import CursorPagination
-from litestar.utils import is_any, is_class_and_subclass, is_optional_union, is_union
+from litestar.utils import is_any, is_async_callable, is_class_and_subclass, is_optional_union, is_union
from litestar.utils.predicates import (
is_class_var,
is_generic,
@@ -200,3 +203,58 @@ def test_is_optional_union(value: Any, expected: bool) -> None:
)
def test_is_class_var(value: Any, expected: bool) -> None:
assert is_class_var(value) is expected
+
+
+class AsyncTestCallable:
+ async def __call__(self, param1: int, param2: int) -> None:
+ ...
+
+ async def method(self, param1: int, param2: int) -> None:
+ ...
+
+
+async def async_generator() -> AsyncGenerator[int, None]:
+ yield 1
+
+
+class SyncTestCallable:
+ def __call__(self, param1: int, param2: int) -> None:
+ ...
+
+ def method(self, param1: int, param2: int) -> None:
+ ...
+
+
+async def async_func(param1: int, param2: int) -> None:
+ ...
+
+
+def sync_func(param1: int, param2: int) -> None:
+ ...
+
+
+async_callable = AsyncTestCallable()
+sync_callable = SyncTestCallable()
+
+
[email protected](
+ "c, exp",
+ [
+ (async_callable, True),
+ (sync_callable, False),
+ (async_callable.method, True),
+ (sync_callable.method, False),
+ (async_func, True),
+ (sync_func, False),
+ (lambda: ..., False),
+ (AsyncTestCallable, True),
+ (SyncTestCallable, False),
+ (async_generator, False),
+ ],
+)
+def test_is_async_callable(c: Callable[[int, int], None], exp: bool) -> None:
+ assert is_async_callable(c) is exp
+ partial_1 = partial(c, 1)
+ assert is_async_callable(partial_1) is exp
+ partial_2 = partial(partial_1, 2)
+ assert is_async_callable(partial_2) is exp
diff --git a/tests/utils/test_scope.py b/tests/unit/test_utils/test_scope.py
similarity index 100%
rename from tests/utils/test_scope.py
rename to tests/unit/test_utils/test_scope.py
diff --git a/tests/utils/test_sequence.py b/tests/unit/test_utils/test_sequence.py
similarity index 100%
rename from tests/utils/test_sequence.py
rename to tests/unit/test_utils/test_sequence.py
diff --git a/tests/utils/test_signature.py b/tests/unit/test_utils/test_signature.py
similarity index 100%
rename from tests/utils/test_signature.py
rename to tests/unit/test_utils/test_signature.py
diff --git a/tests/utils/test_sync.py b/tests/unit/test_utils/test_sync.py
similarity index 100%
rename from tests/utils/test_sync.py
rename to tests/unit/test_utils/test_sync.py
diff --git a/tests/utils/test_typing.py b/tests/unit/test_utils/test_typing.py
similarity index 100%
rename from tests/utils/test_typing.py
rename to tests/unit/test_utils/test_typing.py
diff --git a/tests/utils/test_version.py b/tests/unit/test_utils/test_version.py
similarity index 100%
rename from tests/utils/test_version.py
rename to tests/unit/test_utils/test_version.py
diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py
deleted file mode 100644
| Refactor: Reorganise test suite
Our test suite has grown with the project, but as a result has become a bit disorganised in quite a few places. It should be refactored in a way that structures it in a more consistent and logical way.
| 2023-06-19T13:23:21 |
|
litestar-org/litestar | 1,852 | litestar-org__litestar-1852 | [
"4321",
"1234"
] | fa28f7c91e73eb0b7b215ad4a62b0f022925de96 | diff --git a/litestar/contrib/sqlalchemy/dto.py b/litestar/contrib/sqlalchemy/dto.py
--- a/litestar/contrib/sqlalchemy/dto.py
+++ b/litestar/contrib/sqlalchemy/dto.py
@@ -20,6 +20,7 @@
from litestar.dto.factory.data_structures import FieldDefinition
from litestar.dto.factory.field import DTO_FIELD_META_KEY, DTOField, Mark
from litestar.dto.factory.utils import get_model_type_hints
+from litestar.exceptions import ImproperlyConfiguredException
from litestar.types.empty import Empty
from litestar.utils.helpers import get_fully_qualified_class_name
from litestar.utils.signature import ParsedSignature
@@ -83,10 +84,15 @@ def _(
default, default_factory = _detect_defaults(elem)
- if (parsed_type := model_type_hints[key]).origin is Mapped:
- (parsed_type,) = parsed_type.inner_types
- else:
- raise NotImplementedError(f"Expected 'Mapped' origin, got: '{parsed_type.origin}'")
+ try:
+ if (parsed_type := model_type_hints[key]).origin is Mapped:
+ (parsed_type,) = parsed_type.inner_types
+ else:
+ raise NotImplementedError(f"Expected 'Mapped' origin, got: '{parsed_type.origin}'")
+ except KeyError as e:
+ raise ImproperlyConfiguredException(
+ f"No type information found for '{orm_descriptor}'. Has a type annotation been added to the column?"
+ ) from e
return [
FieldDefinition(
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_dto.py b/tests/unit/test_contrib/test_sqlalchemy/test_dto.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_dto.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_dto.py
@@ -6,6 +6,7 @@
from uuid import UUID, uuid4
import pytest
+import sqlalchemy
from sqlalchemy import func
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, declared_attr, mapped_column
from typing_extensions import Annotated
@@ -15,6 +16,7 @@
from litestar.dto.factory.field import DTO_FIELD_META_KEY
from litestar.dto.interface import ConnectionContext, HandlerContext
from litestar.dto.types import ForType
+from litestar.exceptions import ImproperlyConfiguredException
from litestar.serialization import encode_json
from litestar.typing import ParsedType
@@ -549,3 +551,12 @@ class A(Base):
)
assert vars(model)["a"] == {"b": 1}
assert vars(model)["c"] == [1, 2, 3]
+
+
+async def test_no_type_hints(base: type[DeclarativeBase], connection_context: ConnectionContext) -> None:
+ class Model(base):
+ field = mapped_column(sqlalchemy.String)
+
+ dto_type = SQLAlchemyDTO[Annotated[Model, DTOConfig()]]
+ with pytest.raises(ImproperlyConfiguredException, match="No type information found for 'Model.field'"):
+ await get_model_from_dto(dto_type, Model, connection_context, b"")
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-06-20T11:56:47 |
litestar-org/litestar | 1,857 | litestar-org__litestar-1857 | [
"1234",
"4321"
] | 29b465716c78e32fcf0ea187d331af8b65ff6dc0 | diff --git a/litestar/middleware/exceptions/middleware.py b/litestar/middleware/exceptions/middleware.py
--- a/litestar/middleware/exceptions/middleware.py
+++ b/litestar/middleware/exceptions/middleware.py
@@ -109,9 +109,15 @@ def create_exception_response(exc: Exception) -> Response:
Returns:
Response: HTTP response constructed from exception details.
"""
+ status_code = getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR)
+ if status_code == HTTP_500_INTERNAL_SERVER_ERROR:
+ detail = "Internal Server Error"
+ else:
+ detail = getattr(exc, "detail", repr(exc))
+
content = ExceptionResponseContent(
- status_code=getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR),
- detail=getattr(exc, "detail", repr(exc)),
+ status_code=status_code,
+ detail=detail,
headers=getattr(exc, "headers", None),
extra=getattr(exc, "extra", None),
)
| diff --git a/tests/examples/test_dto/test_example_apps.py b/tests/examples/test_dto/test_example_apps.py
--- a/tests/examples/test_dto/test_example_apps.py
+++ b/tests/examples/test_dto/test_example_apps.py
@@ -11,7 +11,6 @@ def test_dto_data_problem_statement_app() -> None:
with TestClient(app) as client:
response = client.post("/person", json={"name": "John", "age": 30})
assert response.status_code == 500
- assert "missing 1 required positional argument: 'id'" in response.json()["detail"]
def test_dto_data_usage_app() -> None:
diff --git a/tests/examples/test_dto/test_tutorial.py b/tests/examples/test_dto/test_tutorial.py
--- a/tests/examples/test_dto/test_tutorial.py
+++ b/tests/examples/test_dto/test_tutorial.py
@@ -102,7 +102,6 @@ def test_read_only_fields():
response = client.post("/person", json={"name": "peter", "age": 40, "email": "[email protected]"})
assert response.status_code == 500
- assert "__init__() missing 1 required positional argument: 'id'" in response.json()["detail"]
def test_dto_data():
diff --git a/tests/unit/test_exceptions.py b/tests/unit/test_exceptions.py
--- a/tests/unit/test_exceptions.py
+++ b/tests/unit/test_exceptions.py
@@ -87,7 +87,7 @@ def test_create_exception_response_utility_non_http_exception() -> None:
response = create_exception_response(exc)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.media_type == MediaType.JSON
- assert response.content == {"status_code": 500, "detail": "RuntimeError('yikes')"}
+ assert response.content == {"status_code": 500, "detail": "Internal Server Error"}
def test_missing_dependency_exception() -> None:
diff --git a/tests/unit/test_kwargs/test_generator_dependencies.py b/tests/unit/test_kwargs/test_generator_dependencies.py
--- a/tests/unit/test_kwargs/test_generator_dependencies.py
+++ b/tests/unit/test_kwargs/test_generator_dependencies.py
@@ -120,7 +120,7 @@ def handler(dep: str) -> Dict[str, str]:
with create_test_client(route_handlers=[handler]) as client:
res = client.get("/")
assert res.status_code == 500
- assert res.json() == {"detail": "ValueError('foo')", "status_code": 500}
+ assert res.json() == {"detail": "Internal Server Error", "status_code": 500}
cleanup_mock.assert_not_called()
exception_mock.assert_called_once()
finally_mock.assert_called_once()
@@ -144,7 +144,7 @@ def handler(dep: str) -> Dict[str, str]:
with create_test_client(route_handlers=[handler]) as client:
res = client.get("/")
assert res.status_code == 500
- assert res.json() == {"status_code": 500, "detail": "Exception('foo')"}
+ assert res.json() == {"status_code": 500, "detail": "Internal Server Error"}
cleanup_mock.assert_called_once()
finally_mock.assert_called_once()
diff --git a/tests/unit/test_middleware/test_base_authentication_middleware.py b/tests/unit/test_middleware/test_base_authentication_middleware.py
--- a/tests/unit/test_middleware/test_base_authentication_middleware.py
+++ b/tests/unit/test_middleware/test_base_authentication_middleware.py
@@ -72,7 +72,6 @@ def http_route_handler_user_scope(request: Request[User, None, Any]) -> None:
client = create_test_client(route_handlers=[http_route_handler_user_scope])
error_response = client.get("/", headers={"Authorization": "nope"})
assert error_response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert error_response.json()["detail"] == "'user' is not defined in scope, install an AuthMiddleware to set it"
def test_authentication_middleware_not_installed_raises_for_auth_scope_http() -> None:
@@ -83,7 +82,6 @@ def http_route_handler_auth_scope(request: Request[None, Auth, Any]) -> None:
client = create_test_client(route_handlers=[http_route_handler_auth_scope])
error_response = client.get("/", headers={"Authorization": "nope"})
assert error_response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert error_response.json()["detail"] == "'auth' is not defined in scope, install an AuthMiddleware to set it"
@websocket(path="/")
diff --git a/tests/unit/test_middleware/test_exception_handler_middleware.py b/tests/unit/test_middleware/test_exception_handler_middleware.py
--- a/tests/unit/test_middleware/test_exception_handler_middleware.py
+++ b/tests/unit/test_middleware/test_exception_handler_middleware.py
@@ -40,7 +40,7 @@ def test_default_handle_http_exception_handling_extra_object() -> None:
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.content == {
- "detail": "litestar_exception",
+ "detail": "Internal Server Error",
"extra": {"key": "value"},
"status_code": 500,
}
@@ -52,7 +52,7 @@ def test_default_handle_http_exception_handling_extra_none() -> None:
HTTPException(detail="litestar_exception"),
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert response.content == {"detail": "litestar_exception", "status_code": 500}
+ assert response.content == {"detail": "Internal Server Error", "status_code": 500}
def test_default_handle_litestar_http_exception_handling() -> None:
@@ -61,7 +61,7 @@ def test_default_handle_litestar_http_exception_handling() -> None:
HTTPException(detail="litestar_exception"),
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert response.content == {"detail": "litestar_exception", "status_code": 500}
+ assert response.content == {"detail": "Internal Server Error", "status_code": 500}
def test_default_handle_litestar_http_exception_extra_list() -> None:
@@ -71,7 +71,7 @@ def test_default_handle_litestar_http_exception_extra_list() -> None:
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.content == {
- "detail": "litestar_exception",
+ "detail": "Internal Server Error",
"extra": ["extra-1", "extra-2"],
"status_code": 500,
}
@@ -84,7 +84,7 @@ def test_default_handle_starlette_http_exception_handling() -> None:
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.content == {
- "detail": "litestar_exception",
+ "detail": "Internal Server Error",
"status_code": 500,
}
@@ -95,7 +95,7 @@ def test_default_handle_python_http_exception_handling() -> None:
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.content == {
- "detail": repr(AttributeError("oops")),
+ "detail": "Internal Server Error",
"status_code": HTTP_500_INTERNAL_SERVER_ERROR,
}
@@ -164,7 +164,10 @@ def handler() -> None:
client.app.logger = get_logger("litestar")
response = client.get("/test")
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert "Test debug exception" in response.text
+ if is_debug:
+ assert "Test debug exception" in response.text
+ else:
+ assert "Internal Server Error" in response.text
if should_log:
assert len(caplog.records) == 1
@@ -206,7 +209,10 @@ def handler() -> None:
with TestClient(app=app) as client, capture_logs() as cap_logs:
response = client.get("/test")
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert "Test debug exception" in response.text
+ if is_debug:
+ assert "Test debug exception" in response.text
+ else:
+ assert "Internal Server Error" in response.text
if should_log:
assert len(cap_logs) == 1
@@ -233,7 +239,7 @@ def handler() -> None:
client.app.logger = get_logger("litestar")
response = client.get("/test")
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert "Test debug exception" in response.text
+ assert "Internal Server Error" in response.text
assert len(caplog.records) == 1
assert caplog.records[0].levelname == "ERROR"
diff --git a/tests/unit/test_middleware/test_session/test_middleware.py b/tests/unit/test_middleware/test_session/test_middleware.py
--- a/tests/unit/test_middleware/test_session/test_middleware.py
+++ b/tests/unit/test_middleware/test_session/test_middleware.py
@@ -19,7 +19,7 @@ def handler(request: Request) -> None:
with create_test_client(handler) as client:
response = client.get("/test")
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert response.json()["detail"] == "'session' is not defined in scope, install a SessionMiddleware to set it"
+ assert response.json()["detail"] == "Internal Server Error"
def test_integration(session_backend_config: "BaseBackendConfig") -> None:
diff --git a/tests/unit/test_signature/test_parsing.py b/tests/unit/test_signature/test_parsing.py
--- a/tests/unit/test_signature/test_parsing.py
+++ b/tests/unit/test_signature/test_parsing.py
@@ -146,7 +146,7 @@ def test(dep: int, param: int, optional_dep: Optional[int] = Dependency()) -> No
response = client.get("/?param=13")
assert response.json() == {
- "detail": "A dependency failed validation for GET http://testserver.local/?param=13",
+ "detail": "Internal Server Error",
"extra": error_extra,
"status_code": HTTP_500_INTERNAL_SERVER_ERROR,
}
diff --git a/tests/unit/test_template/test_built_in.py b/tests/unit/test_template/test_built_in.py
--- a/tests/unit/test_template/test_built_in.py
+++ b/tests/unit/test_template/test_built_in.py
@@ -93,7 +93,7 @@ def invalid_template_name_handler() -> Template:
with create_test_client(route_handlers=[invalid_template_name_handler], template_config=template_config) as client:
response = client.request("GET", "/")
assert response.status_code == 500
- assert response.json() == {"detail": "Template invalid.html not found.", "status_code": 500}
+ assert response.json() == {"detail": "Internal Server Error", "status_code": 500}
def test_no_context(tmp_path: Path, template_config: TemplateConfig) -> None:
diff --git a/tests/unit/test_template/test_template.py b/tests/unit/test_template/test_template.py
--- a/tests/unit/test_template/test_template.py
+++ b/tests/unit/test_template/test_template.py
@@ -25,7 +25,7 @@ def invalid_path() -> Template:
with create_test_client(route_handlers=[invalid_path]) as client:
response = client.request("GET", "/")
assert response.status_code == 500
- assert response.json() == {"detail": "Template engine is not configured", "status_code": 500}
+ assert response.json() == {"detail": "Internal Server Error", "status_code": 500}
def test_engine_passed_to_callback(tmp_path: "Path") -> None:
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-06-21T09:03:32 |
litestar-org/litestar | 1,879 | litestar-org__litestar-1879 | [
"1853",
"4321"
] | 48a9719b1ad5e94b12f1b6755381d461cf517f4d | diff --git a/litestar/contrib/sqlalchemy/dto.py b/litestar/contrib/sqlalchemy/dto.py
--- a/litestar/contrib/sqlalchemy/dto.py
+++ b/litestar/contrib/sqlalchemy/dto.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from functools import singledispatchmethod
-from typing import TYPE_CHECKING, Generic, TypeVar
+from typing import TYPE_CHECKING, Generic, Optional, TypeVar
from sqlalchemy import Column, inspect, orm, sql
from sqlalchemy.ext.associationproxy import AssociationProxy, AssociationProxyExtensionType
@@ -13,6 +13,7 @@
Mapped,
NotExtension,
QueryableAttribute,
+ RelationshipDirection,
RelationshipProperty,
)
@@ -22,6 +23,7 @@
from litestar.dto.factory.utils import get_model_type_hints
from litestar.exceptions import ImproperlyConfiguredException
from litestar.types.empty import Empty
+from litestar.typing import ParsedType
from litestar.utils.helpers import get_fully_qualified_class_name
from litestar.utils.signature import ParsedSignature
@@ -30,8 +32,6 @@
from typing_extensions import TypeAlias
- from litestar.typing import ParsedType
-
__all__ = ("SQLAlchemyDTO",)
T = TypeVar("T", bound="DeclarativeBase | Collection[DeclarativeBase]")
@@ -89,10 +89,8 @@ def _(
(parsed_type,) = parsed_type.inner_types
else:
raise NotImplementedError(f"Expected 'Mapped' origin, got: '{parsed_type.origin}'")
- except KeyError as e:
- raise ImproperlyConfiguredException(
- f"No type information found for '{orm_descriptor}'. Has a type annotation been added to the column?"
- ) from e
+ except KeyError:
+ parsed_type = parse_type_from_element(elem)
return [
FieldDefinition(
@@ -221,6 +219,59 @@ def default_factory(d: Any = sqla_default) -> Any:
else:
raise ValueError("Unexpected default type")
else:
- if getattr(elem, "nullable", False):
+ if (
+ isinstance(elem, RelationshipProperty)
+ and detect_nullable_relationship(elem)
+ or getattr(elem, "nullable", False)
+ ):
default = None
+
return default, default_factory
+
+
+def parse_type_from_element(elem: ElementType) -> ParsedType:
+ """Parses a type from a SQLAlchemy element.
+
+ Args:
+ elem: The SQLAlchemy element to parse.
+
+ Returns:
+ ParsedType: The parsed type.
+
+ Raises:
+ ImproperlyConfiguredException: If the type cannot be parsed.
+ """
+
+ if isinstance(elem, Column):
+ if elem.nullable:
+ return ParsedType(Optional[elem.type.python_type])
+ return ParsedType(elem.type.python_type)
+
+ if isinstance(elem, RelationshipProperty):
+ if elem.direction in (RelationshipDirection.ONETOMANY, RelationshipDirection.MANYTOMANY):
+ collection_type = ParsedType(elem.collection_class or list)
+ return ParsedType(collection_type.safe_generic_origin[elem.mapper.class_])
+
+ if detect_nullable_relationship(elem):
+ return ParsedType(Optional[elem.mapper.class_])
+
+ return ParsedType(elem.mapper.class_)
+
+ raise ImproperlyConfiguredException(
+ f"Unable to parse type from element '{elem}'. Consider adding a type hint.",
+ )
+
+
+def detect_nullable_relationship(elem: RelationshipProperty) -> bool:
+ """Detects if a relationship is nullable.
+
+ This attempts to decide if we should allow a ``None`` default value for a relationship by looking at the
+ foreign key fields. If all foreign key fields are nullable, then we allow a ``None`` default value.
+
+ Args:
+ elem: The relationship to check.
+
+ Returns:
+ bool: ``True`` if the relationship is nullable, ``False`` otherwise.
+ """
+ return elem.direction == RelationshipDirection.MANYTOONE and all(c.nullable for c in elem.local_columns)
diff --git a/litestar/dto/factory/_backends/utils.py b/litestar/dto/factory/_backends/utils.py
--- a/litestar/dto/factory/_backends/utils.py
+++ b/litestar/dto/factory/_backends/utils.py
@@ -279,7 +279,7 @@ def transfer_type_data(
if isinstance(transfer_type, CollectionType):
if transfer_type.has_nested:
return transfer_nested_collection_type_data(
- transfer_type.parsed_type.origin, transfer_type, dto_for, source_value
+ transfer_type.parsed_type.instantiable_origin, transfer_type, dto_for, source_value
)
return transfer_type.parsed_type.instantiable_origin(source_value)
return source_value
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_dto.py b/tests/unit/test_contrib/test_sqlalchemy/test_dto.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_dto.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_dto.py
@@ -7,11 +7,11 @@
import pytest
import sqlalchemy
-from sqlalchemy import func
-from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, declared_attr, mapped_column
+from sqlalchemy import ForeignKey, func
+from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, declared_attr, mapped_column, relationship
from typing_extensions import Annotated
-from litestar.contrib.sqlalchemy.dto import SQLAlchemyDTO
+from litestar.contrib.sqlalchemy.dto import SQLAlchemyDTO, parse_type_from_element
from litestar.dto.factory import DTOConfig, DTOField, Mark
from litestar.dto.factory.field import DTO_FIELD_META_KEY
from litestar.dto.interface import ConnectionContext, HandlerContext
@@ -553,10 +553,76 @@ class A(Base):
assert vars(model)["c"] == [1, 2, 3]
-async def test_no_type_hints(base: type[DeclarativeBase], connection_context: ConnectionContext) -> None:
+async def test_no_type_hint_column(base: type[DeclarativeBase], connection_context: ConnectionContext) -> None:
class Model(base):
- field = mapped_column(sqlalchemy.String)
+ nullable_field = mapped_column(sqlalchemy.String)
+ not_nullable_field = mapped_column(sqlalchemy.String, nullable=False, default="")
dto_type = SQLAlchemyDTO[Annotated[Model, DTOConfig()]]
- with pytest.raises(ImproperlyConfiguredException, match="No type information found for 'Model.field'"):
- await get_model_from_dto(dto_type, Model, connection_context, b"")
+ model = await get_model_from_dto(dto_type, Model, connection_context, b"{}")
+ assert model.nullable_field is None
+ assert model.not_nullable_field == ""
+
+
+async def test_no_type_hint_scalar_relationship_with_nullable_fk(
+ base: type[DeclarativeBase], connection_context: ConnectionContext
+) -> None:
+ class Child(base):
+ ...
+
+ class Model(base):
+ child_id = mapped_column(ForeignKey("child.id"))
+ child = relationship(Child)
+
+ dto_type = SQLAlchemyDTO[Annotated[Model, DTOConfig(exclude={"child_id"})]]
+ model = await get_model_from_dto(dto_type, Model, connection_context, b"{}")
+ assert model.child is None
+
+
+async def test_no_type_hint_scalar_relationship_with_not_nullable_fk(
+ base: type[DeclarativeBase], connection_context: ConnectionContext
+) -> None:
+ class Child(base):
+ ...
+
+ class Model(base):
+ child_id = mapped_column(ForeignKey("child.id"), nullable=False)
+ child = relationship(Child)
+
+ dto_type = SQLAlchemyDTO[Annotated[Model, DTOConfig(exclude={"child_id"})]]
+ model = await get_model_from_dto(dto_type, Model, connection_context, b'{"child": {}}')
+ assert isinstance(model.child, Child)
+
+
+async def test_no_type_hint_collection_relationship(
+ base: type[DeclarativeBase], connection_context: ConnectionContext
+) -> None:
+ class Child(base):
+ model_id = mapped_column(ForeignKey("model.id"))
+
+ class Model(base):
+ children = relationship(Child)
+
+ dto_type = SQLAlchemyDTO[Annotated[Model, DTOConfig()]]
+ model = await get_model_from_dto(dto_type, Model, connection_context, b'{"children": []}')
+ assert model.children == []
+
+
+async def test_no_type_hint_collection_relationship_alt_collection_class(
+ base: type[DeclarativeBase], connection_context: ConnectionContext
+) -> None:
+ class Child(base):
+ model_id = mapped_column(ForeignKey("model.id"))
+
+ class Model(base):
+ children = relationship(Child, collection_class=set)
+
+ dto_type = SQLAlchemyDTO[Annotated[Model, DTOConfig()]]
+ model = await get_model_from_dto(dto_type, Model, connection_context, b'{"children": []}')
+ assert model.children == set()
+
+
+def test_parse_type_from_element_failure() -> None:
+ with pytest.raises(ImproperlyConfiguredException) as exc:
+ parse_type_from_element(1)
+ assert str(exc.value) == "500: Unable to parse type from element '1'. Consider adding a type hint."
| Enhancement [SQLAlchemy DTO]: Infer types from column if no type annotation is given
### Summary
Currently, SQLAlchemy DTOs will raise an exception if no type annotation is given for a specific column (see #1852). It would a good addition to instead try to infer the column's type from the mapped column.
### Basic Example
_No response_
### Drawbacks and Impact
_No response_
### Unresolved questions
_No response_
<!-- POLAR PLEDGE BADGE START -->
<a href="https://polar.sh/litestar-org/litestar/issues/1853">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1853/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1853/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-06-25T03:57:36 |
|
litestar-org/litestar | 1,883 | litestar-org__litestar-1883 | [
"1234",
"4321"
] | 6ff6cfae0b87ada01bef770d94b287775ba9fa50 | diff --git a/litestar/contrib/sqlalchemy/dto.py b/litestar/contrib/sqlalchemy/dto.py
--- a/litestar/contrib/sqlalchemy/dto.py
+++ b/litestar/contrib/sqlalchemy/dto.py
@@ -216,6 +216,11 @@ def _detect_defaults(elem: ElementType) -> tuple[Any, Any]:
def default_factory(d: Any = sqla_default) -> Any:
return d.arg({})
+ elif sqla_default.is_sequence:
+ # SQLAlchemy sequences represent server side defaults
+ # so we cannot infer a reasonable default value for
+ # them on the client side
+ pass
else:
raise ValueError("Unexpected default type")
else:
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py b/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
@@ -329,3 +329,45 @@ def get_handler(data: Circle) -> Circle:
response = client.post("/", json={"radius": 5})
assert response.json() == {"id": 1, "radius": 5}
assert module.DIAMETER == 10
+
+
+async def test_field_with_sequence_default_value(create_module: Callable[[str], ModuleType]) -> None:
+ module = create_module(
+ """
+from sqlalchemy import create_engine, Column, Integer, Sequence
+from sqlalchemy.orm import DeclarativeBase, Mapped, sessionmaker
+
+from litestar import Litestar, post
+from litestar.contrib.sqlalchemy.dto import SQLAlchemyDTO
+from litestar.dto.factory import DTOConfig
+
+engine = create_engine('sqlite:///:memory:', echo=True)
+Session = sessionmaker(bind=engine, expire_on_commit=False)
+
+class Base(DeclarativeBase):
+ pass
+
+class Model(Base):
+ __tablename__ = "model"
+ id: Mapped[int] = Column(Integer, Sequence('model_id_seq', optional=False), primary_key=True)
+ val: Mapped[str]
+
+class ModelCreateDTO(SQLAlchemyDTO[Model]):
+ config = DTOConfig(exclude={"id"})
+
+ModelReturnDTO = SQLAlchemyDTO[Model]
+
+@post("/", dto=ModelCreateDTO, return_dto=ModelReturnDTO, sync_to_thread=False)
+def post_handler(data: Model) -> Model:
+ Base.metadata.create_all(engine)
+
+ with Session() as session:
+ session.add(data)
+ session.commit()
+
+ return data
+ """
+ )
+ with create_test_client(route_handlers=[module.post_handler], debug=True) as client:
+ response = client.post("/", json={"val": "value"})
+ assert response.json() == {"id": 1, "val": "value"}
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-06-26T01:11:14 |
litestar-org/litestar | 1,886 | litestar-org__litestar-1886 | [
"1234",
"4321"
] | 32396925a573c02eff57aa10b2060f505b920232 | diff --git a/litestar/cli/_utils.py b/litestar/cli/_utils.py
--- a/litestar/cli/_utils.py
+++ b/litestar/cli/_utils.py
@@ -355,7 +355,8 @@ def show_app_info(app: Litestar) -> None: # pragma: no cover
if app.static_files_config:
static_files_configs = app.static_files_config
static_files_info = [
- f"path=[yellow]{static_files.path}[/] dirs=[yellow]{', '.join(map(str, static_files.directories))}[/] html_mode={_format_is_enabled(static_files.html_mode)}"
+ f"path=[yellow]{static_files.path}[/] dirs=[yellow]{', '.join(map(str, static_files.directories))}[/] "
+ f"html_mode={_format_is_enabled(static_files.html_mode)}"
for static_files in static_files_configs
]
table.add_row("Static files", "\n".join(static_files_info))
diff --git a/litestar/openapi/config.py b/litestar/openapi/config.py
--- a/litestar/openapi/config.py
+++ b/litestar/openapi/config.py
@@ -18,6 +18,7 @@
Server,
Tag,
)
+from litestar.utils.path import normalize_path
__all__ = ("OpenAPIConfig",)
@@ -94,6 +95,13 @@ class OpenAPIConfig:
"""A set of the enabled documentation sites and schema download endpoints."""
operation_id_creator: OperationIDCreator = default_operation_id_creator
"""A callable that generates unique operation ids"""
+ path: str | None = field(default=None)
+ """Base path for the OpenAPI documentation endpoints."""
+
+ def __post_init__(self) -> None:
+ if self.path:
+ self.path = normalize_path(self.path)
+ self.openapi_controller = type("OpenAPIController", (self.openapi_controller,), {"path": self.path})
def to_openapi_schema(self) -> OpenAPI:
"""Return an ``OpenAPI`` instance from the values stored in ``self``.
| diff --git a/tests/unit/test_openapi/test_config.py b/tests/unit/test_openapi/test_config.py
--- a/tests/unit/test_openapi/test_config.py
+++ b/tests/unit/test_openapi/test_config.py
@@ -113,6 +113,16 @@ def handler_2() -> None:
}
+def test_allows_customization_of_path() -> None:
+ app = Litestar(
+ openapi_config=OpenAPIConfig(title="my title", version="1.0.0", path="/custom_schema_path"),
+ )
+
+ assert app.openapi_config
+ assert app.openapi_config.path == "/custom_schema_path"
+ assert app.openapi_config.openapi_controller.path == "/custom_schema_path"
+
+
def test_raises_exception_when_no_config_in_place() -> None:
with pytest.raises(ImproperlyConfiguredException):
Litestar(route_handlers=[], openapi_config=None).update_openapi_schema()
diff --git a/tests/unit/test_openapi/test_integration.py b/tests/unit/test_openapi/test_integration.py
--- a/tests/unit/test_openapi/test_integration.py
+++ b/tests/unit/test_openapi/test_integration.py
@@ -8,7 +8,7 @@
from litestar import Controller, post
from litestar.app import DEFAULT_OPENAPI_CONFIG
from litestar.enums import OpenAPIMediaType
-from litestar.openapi import OpenAPIConfig
+from litestar.openapi import OpenAPIConfig, OpenAPIController
from litestar.status_codes import HTTP_200_OK, HTTP_404_NOT_FOUND
from litestar.testing import create_test_client
@@ -61,6 +61,63 @@ def test_openapi_json_not_allowed(person_controller: Type[Controller], pet_contr
assert response.status_code == HTTP_404_NOT_FOUND
+def test_openapi_custom_path() -> None:
+ openapi_config = OpenAPIConfig(title="my title", version="1.0.0", path="/custom_schema_path")
+ with create_test_client([], openapi_config=openapi_config) as client:
+ response = client.get("/schema")
+ assert response.status_code == HTTP_404_NOT_FOUND
+
+ response = client.get("/custom_schema_path")
+ assert response.status_code == HTTP_200_OK
+
+ response = client.get("/custom_schema_path/openapi.json")
+ assert response.status_code == HTTP_200_OK
+
+
+def test_openapi_normalizes_custom_path() -> None:
+ openapi_config = OpenAPIConfig(title="my title", version="1.0.0", path="custom_schema_path")
+ with create_test_client([], openapi_config=openapi_config) as client:
+ response = client.get("/custom_schema_path/openapi.json")
+ assert response.status_code == HTTP_200_OK
+
+ response = client.get("/custom_schema_path/openapi.json")
+ assert response.status_code == HTTP_200_OK
+
+
+def test_openapi_custom_path_avoids_override() -> None:
+ class CustomOpenAPIController(OpenAPIController):
+ path = "/custom_docs"
+
+ openapi_config = OpenAPIConfig(title="my title", version="1.0.0", openapi_controller=CustomOpenAPIController)
+ with create_test_client([], openapi_config=openapi_config) as client:
+ response = client.get("/schema")
+ assert response.status_code == HTTP_404_NOT_FOUND
+
+ response = client.get("/custom_docs/openapi.json")
+ assert response.status_code == HTTP_200_OK
+
+ response = client.get("/custom_docs/openapi.json")
+ assert response.status_code == HTTP_200_OK
+
+
+def test_openapi_custom_path_overrides_custom_controller_path() -> None:
+ class CustomOpenAPIController(OpenAPIController):
+ path = "/custom_docs"
+
+ openapi_config = OpenAPIConfig(
+ title="my title", version="1.0.0", openapi_controller=CustomOpenAPIController, path="/override_docs_path"
+ )
+ with create_test_client([], openapi_config=openapi_config) as client:
+ response = client.get("/custom_docs")
+ assert response.status_code == HTTP_404_NOT_FOUND
+
+ response = client.get("/override_docs_path/openapi.json")
+ assert response.status_code == HTTP_200_OK
+
+ response = client.get("/override_docs_path/openapi.json")
+ assert response.status_code == HTTP_200_OK
+
+
def test_msgspec_schema_generation() -> None:
class Lookup(msgspec.Struct):
id: Annotated[
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-06-27T03:00:11 |
litestar-org/litestar | 1,900 | litestar-org__litestar-1900 | [
"1895",
"1234"
] | e9241458ab324544dde60ae984f5c3b1c05f15ec | diff --git a/litestar/contrib/sqlalchemy/repository/_async.py b/litestar/contrib/sqlalchemy/repository/_async.py
--- a/litestar/contrib/sqlalchemy/repository/_async.py
+++ b/litestar/contrib/sqlalchemy/repository/_async.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Generic, Literal, cast
+from typing import TYPE_CHECKING, Any, Generic, Iterable, Literal, cast
from sqlalchemy import Result, Select, delete, over, select, text, update
from sqlalchemy import func as sql_func
@@ -31,16 +31,31 @@ class SQLAlchemyAsyncRepository(AbstractAsyncRepository[ModelT], Generic[ModelT]
match_fields: list[str] | str | None = None
- def __init__(self, *, statement: Select[tuple[ModelT]] | None = None, session: AsyncSession, **kwargs: Any) -> None:
+ def __init__(
+ self,
+ *,
+ statement: Select[tuple[ModelT]] | None = None,
+ session: AsyncSession,
+ auto_expunge: bool = False,
+ auto_refresh: bool = True,
+ auto_commit: bool = False,
+ **kwargs: Any,
+ ) -> None:
"""Repository pattern for SQLAlchemy models.
Args:
statement: To facilitate customization of the underlying select query.
session: Session managing the unit-of-work for the operation.
+ auto_expunge: Remove object from session before returning.
+ auto_refresh: Refresh object from session before returning.
+ auto_commit: Commit objects before returning.
**kwargs: Additional arguments.
"""
super().__init__(**kwargs)
+ self.auto_expunge = auto_expunge
+ self.auto_refresh = auto_refresh
+ self.auto_commit = auto_commit
self.session = session
self.statement = statement if statement is not None else select(self.model_type)
if not self.session.bind:
@@ -49,44 +64,63 @@ def __init__(self, *, statement: Select[tuple[ModelT]] | None = None, session: A
raise ValueError("Session improperly configure")
self._dialect = self.session.bind.dialect
- async def add(self, data: ModelT) -> ModelT:
+ async def add(
+ self,
+ data: ModelT,
+ **kwargs: Any,
+ ) -> ModelT:
"""Add `data` to the collection.
Args:
data: Instance to be added to the collection.
+ **kwargs: Additional arguments.
Returns:
The added instance.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
+ auto_refresh = kwargs.pop("auto_refresh", self.auto_refresh)
with wrap_sqlalchemy_exception():
instance = await self._attach_to_session(data)
- await self.session.flush()
- await self.session.refresh(instance)
- self.session.expunge(instance)
+ await self._flush_or_commit(auto_commit=auto_commit)
+ await self._refresh(instance, auto_refresh=auto_refresh)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
- async def add_many(self, data: list[ModelT]) -> list[ModelT]:
+ async def add_many(
+ self,
+ data: list[ModelT],
+ **kwargs: Any,
+ ) -> list[ModelT]:
"""Add Many `data` to the collection.
Args:
data: list of Instances to be added to the collection.
-
+ **kwargs: Additional arguments.
Returns:
The added instances.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
self.session.add_all(data)
- await self.session.flush()
+ await self._flush_or_commit(auto_commit=auto_commit)
for datum in data:
- self.session.expunge(datum)
+ self._expunge(datum, auto_expunge=auto_expunge)
return data
- async def delete(self, item_id: Any) -> ModelT:
+ async def delete(
+ self,
+ item_id: Any,
+ **kwargs: Any,
+ ) -> ModelT:
"""Delete instance identified by ``item_id``.
Args:
item_id: Identifier of instance to be deleted.
+ **kwargs: Additional arguments.
Returns:
The deleted instance.
@@ -94,23 +128,32 @@ async def delete(self, item_id: Any) -> ModelT:
Raises:
NotFoundError: If no instance found identified by ``item_id``.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
instance = await self.get(item_id)
await self.session.delete(instance)
- await self.session.flush()
- self.session.expunge(instance)
+ await self._flush_or_commit(auto_commit=auto_commit)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
- async def delete_many(self, item_ids: list[Any]) -> list[ModelT]:
+ async def delete_many(
+ self,
+ item_ids: list[Any],
+ **kwargs: Any,
+ ) -> list[ModelT]:
"""Delete instance identified by `item_id`.
Args:
item_ids: Identifier of instance to be deleted.
+ **kwargs: Additional arguments.
Returns:
The deleted instances.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
instances: list[ModelT] = []
chunk_size = 450
@@ -133,9 +176,9 @@ async def delete_many(self, item_ids: list[Any]) -> list[ModelT]:
await self.session.execute(
delete(self.model_type).where(getattr(self.model_type, self.id_attribute).in_(chunk))
)
- await self.session.flush()
+ await self._flush_or_commit(auto_commit=auto_commit)
for instance in instances:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instances
async def exists(self, **kwargs: Any) -> bool:
@@ -164,12 +207,13 @@ async def get(self, item_id: Any, **kwargs: Any) -> ModelT:
Raises:
NotFoundError: If no instance found identified by `item_id`.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
statement = kwargs.pop("statement", self.statement)
statement = self._filter_select_by_kwargs(statement=statement, **{self.id_attribute: item_id})
instance = (await self._execute(statement)).scalar_one_or_none()
instance = self.check_not_found(instance)
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
async def get_one(self, **kwargs: Any) -> ModelT:
@@ -184,12 +228,13 @@ async def get_one(self, **kwargs: Any) -> ModelT:
Raises:
NotFoundError: If no instance found identified by `item_id`.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
statement = kwargs.pop("statement", self.statement)
statement = self._filter_select_by_kwargs(statement=statement, **kwargs)
instance = (await self._execute(statement)).scalar_one_or_none()
instance = self.check_not_found(instance)
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
async def get_one_or_none(self, **kwargs: Any) -> ModelT | None:
@@ -201,27 +246,38 @@ async def get_one_or_none(self, **kwargs: Any) -> ModelT | None:
Returns:
The retrieved instance or None
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
statement = kwargs.pop("statement", self.statement)
statement = self._filter_select_by_kwargs(statement=statement, **kwargs)
instance = (await self._execute(statement)).scalar_one_or_none()
if instance:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance # type: ignore
async def get_or_create(
- self, match_fields: list[str] | str | None = None, upsert: bool = True, **kwargs: Any
+ self,
+ match_fields: list[str] | str | None = None,
+ upsert: bool = True,
+ attribute_names: Iterable[str] | None = None,
+ with_for_update: bool | None = None,
+ **kwargs: Any,
) -> tuple[ModelT, bool]:
"""Get instance identified by ``kwargs`` or create if it doesn't exist.
Args:
match_fields: a list of keys to use to match the existing model. When empty, all fields are matched.
upsert: When using match_fields and actual model values differ from `kwargs`, perform an update operation on the model.
+ attribute_names: an iterable of attribute names to pass into the ``update`` method.
+ with_for_update: indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT
**kwargs: Identifier of the instance to be retrieved.
Returns:
a tuple that includes the instance and whether or not it needed to be created. When using match_fields and actual model values differ from `kwargs`, the model value will be updated.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
+ auto_refresh = kwargs.pop("auto_refresh", self.auto_refresh)
match_fields = match_fields or self.match_fields
if isinstance(match_fields, str):
match_fields = [match_fields]
@@ -242,9 +298,11 @@ async def get_or_create(
if field and field != new_field_value:
setattr(existing, field_name, new_field_value)
existing = await self._attach_to_session(existing, strategy="merge")
- await self.session.flush()
- await self.session.refresh(existing)
- self.session.expunge(existing)
+ await self._flush_or_commit(auto_commit=auto_commit)
+ await self._refresh(
+ existing, attribute_names=attribute_names, with_for_update=with_for_update, auto_refresh=auto_refresh
+ )
+ self._expunge(existing, auto_expunge=auto_expunge)
return existing, False
async def count(self, *filters: FilterTypes, **kwargs: Any) -> int:
@@ -267,12 +325,21 @@ async def count(self, *filters: FilterTypes, **kwargs: Any) -> int:
results = await self._execute(statement)
return results.scalar_one() # type: ignore
- async def update(self, data: ModelT) -> ModelT:
+ async def update(
+ self,
+ data: ModelT,
+ attribute_names: Iterable[str] | None = None,
+ with_for_update: bool | None = None,
+ **kwargs: Any,
+ ) -> ModelT:
"""Update instance with the attribute values present on `data`.
Args:
data: An instance that should have a value for `self.id_attribute` that exists in the
collection.
+ attribute_names: an iterable of attribute names to pass into the ``update`` method.
+ with_for_update: indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT
+ **kwargs: Additional arguments.
Returns:
The updated instance.
@@ -280,18 +347,27 @@ async def update(self, data: ModelT) -> ModelT:
Raises:
NotFoundError: If no instance found with same identifier as `data`.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
+ auto_refresh = kwargs.pop("auto_refresh", self.auto_refresh)
with wrap_sqlalchemy_exception():
item_id = self.get_id_attribute_value(data)
# this will raise for not found, and will put the item in the session
await self.get(item_id)
# this will merge the inbound data to the instance we just put in the session
instance = await self._attach_to_session(data, strategy="merge")
- await self.session.flush()
- await self.session.refresh(instance)
- self.session.expunge(instance)
+ await self._flush_or_commit(auto_commit=auto_commit)
+ await self._refresh(
+ instance, attribute_names=attribute_names, with_for_update=with_for_update, auto_refresh=auto_refresh
+ )
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
- async def update_many(self, data: list[ModelT]) -> list[ModelT]:
+ async def update_many(
+ self,
+ data: list[ModelT],
+ **kwargs: Any,
+ ) -> list[ModelT]:
"""Update one or more instances with the attribute values present on `data`.
This function has an optimized bulk insert based on the configured SQL dialect:
@@ -301,6 +377,7 @@ async def update_many(self, data: list[ModelT]) -> list[ModelT]:
Args:
data: A list of instances to update. Each should have a value for `self.id_attribute` that exists in the
collection.
+ **kwargs: Additional arguments.
Returns:
The updated instances.
@@ -308,6 +385,8 @@ async def update_many(self, data: list[ModelT]) -> list[ModelT]:
Raises:
NotFoundError: If no instance found with same identifier as `data`.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
data_to_update: list[dict[str, Any]] = [v.to_dict() if isinstance(v, self.model_type) else v for v in data] # type: ignore
with wrap_sqlalchemy_exception():
if self._dialect.update_executemany_returning and self._dialect.name != "oracle":
@@ -319,15 +398,15 @@ async def update_many(self, data: list[ModelT]) -> list[ModelT]:
# https://github.com/sqlalchemy/sqlalchemy/discussions/9925
)
)
- await self.session.flush()
+ await self._flush_or_commit(auto_commit=auto_commit)
for instance in instances:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instances
await self.session.execute(
update(self.model_type),
data_to_update,
)
- await self.session.flush()
+ await self._flush_or_commit(auto_commit=auto_commit)
return data
async def list_and_count(
@@ -348,6 +427,25 @@ async def list_and_count(
return await self._list_and_count_basic(*filters, **kwargs)
return await self._list_and_count_window(*filters, **kwargs)
+ def _expunge(self, instance: ModelT, auto_expunge: bool) -> None:
+ return self.session.expunge(instance) if auto_expunge else None
+
+ async def _flush_or_commit(self, auto_commit: bool) -> None:
+ return await self.session.commit() if auto_commit else await self.session.flush()
+
+ async def _refresh(
+ self,
+ instance: ModelT,
+ auto_refresh: bool,
+ attribute_names: Iterable[str] | None = None,
+ with_for_update: bool | None = None,
+ ) -> None:
+ return (
+ await self.session.refresh(instance, attribute_names=attribute_names, with_for_update=with_for_update)
+ if auto_refresh
+ else None
+ )
+
async def _list_and_count_window(
self,
*filters: FilterTypes,
@@ -362,6 +460,7 @@ async def _list_and_count_window(
Returns:
Count of records returned by query using an analytical window function, ignoring pagination.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
statement = kwargs.pop("statement", self.statement)
statement = statement.add_columns(over(sql_func.count(self.get_id_attribute_value(self.model_type))))
statement = self._apply_filters(*filters, statement=statement)
@@ -371,7 +470,7 @@ async def _list_and_count_window(
count: int = 0
instances: list[ModelT] = []
for i, (instance, count_value) in enumerate(result):
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
instances.append(instance)
if i == 0:
count = count_value
@@ -391,6 +490,7 @@ async def _list_and_count_basic(
Returns:
Count of records returned by query using 2 queries, ignoring pagination.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
statement = kwargs.pop("statement", self.statement)
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, **kwargs)
@@ -404,7 +504,7 @@ async def _list_and_count_basic(
result = await self._execute(statement)
instances: list[ModelT] = []
for (instance,) in result:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
instances.append(instance)
return instances, count
@@ -418,6 +518,7 @@ async def list(self, *filters: FilterTypes, **kwargs: Any) -> list[ModelT]:
Returns:
The list of instances, after filtering applied.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
statement = kwargs.pop("statement", self.statement)
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, **kwargs)
@@ -426,10 +527,16 @@ async def list(self, *filters: FilterTypes, **kwargs: Any) -> list[ModelT]:
result = await self._execute(statement)
instances = list(result.scalars())
for instance in instances:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instances
- async def upsert(self, data: ModelT) -> ModelT:
+ async def upsert(
+ self,
+ data: ModelT,
+ attribute_names: Iterable[str] | None = None,
+ with_for_update: bool | None = None,
+ **kwargs: Any,
+ ) -> ModelT:
"""Update or create instance.
Updates instance with the attribute values present on `data`, or creates a new instance if
@@ -439,6 +546,9 @@ async def upsert(self, data: ModelT) -> ModelT:
data: Instance to update existing, or be created. Identifier used to determine if an
existing instance exists is the value of an attribute on `data` named as value of
`self.id_attribute`.
+ attribute_names: an iterable of attribute names to pass into the ``update`` method.
+ with_for_update: indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT
+ **kwargs: Instance attribute value filters.
Returns:
The updated or created instance.
@@ -446,11 +556,16 @@ async def upsert(self, data: ModelT) -> ModelT:
Raises:
NotFoundError: If no instance found with same identifier as `data`.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
+ auto_refresh = kwargs.pop("auto_refresh", self.auto_refresh)
with wrap_sqlalchemy_exception():
instance = await self._attach_to_session(data, strategy="merge")
- await self.session.flush()
- await self.session.refresh(instance)
- self.session.expunge(instance)
+ await self._flush_or_commit(auto_commit=auto_commit)
+ await self._refresh(
+ instance, attribute_names=attribute_names, with_for_update=with_for_update, auto_refresh=auto_refresh
+ )
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
def filter_collection_by_kwargs( # type:ignore[override]
diff --git a/litestar/contrib/sqlalchemy/repository/_sync.py b/litestar/contrib/sqlalchemy/repository/_sync.py
--- a/litestar/contrib/sqlalchemy/repository/_sync.py
+++ b/litestar/contrib/sqlalchemy/repository/_sync.py
@@ -2,7 +2,7 @@
# litestar/contrib/sqlalchemy/repository/_async.py
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Generic, Literal, cast
+from typing import TYPE_CHECKING, Any, Generic, Iterable, Literal, cast
from sqlalchemy import Result, Select, delete, over, select, text, update
from sqlalchemy import func as sql_func
@@ -33,16 +33,31 @@ class SQLAlchemySyncRepository(AbstractSyncRepository[ModelT], Generic[ModelT]):
match_fields: list[str] | str | None = None
- def __init__(self, *, statement: Select[tuple[ModelT]] | None = None, session: Session, **kwargs: Any) -> None:
+ def __init__(
+ self,
+ *,
+ statement: Select[tuple[ModelT]] | None = None,
+ session: Session,
+ auto_expunge: bool = False,
+ auto_refresh: bool = True,
+ auto_commit: bool = False,
+ **kwargs: Any,
+ ) -> None:
"""Repository pattern for SQLAlchemy models.
Args:
statement: To facilitate customization of the underlying select query.
session: Session managing the unit-of-work for the operation.
+ auto_expunge: Remove object from session before returning.
+ auto_refresh: Refresh object from session before returning.
+ auto_commit: Commit objects before returning.
**kwargs: Additional arguments.
"""
super().__init__(**kwargs)
+ self.auto_expunge = auto_expunge
+ self.auto_refresh = auto_refresh
+ self.auto_commit = auto_commit
self.session = session
self.statement = statement if statement is not None else select(self.model_type)
if not self.session.bind:
@@ -51,44 +66,63 @@ def __init__(self, *, statement: Select[tuple[ModelT]] | None = None, session: S
raise ValueError("Session improperly configure")
self._dialect = self.session.bind.dialect
- def add(self, data: ModelT) -> ModelT:
+ def add(
+ self,
+ data: ModelT,
+ **kwargs: Any,
+ ) -> ModelT:
"""Add `data` to the collection.
Args:
data: Instance to be added to the collection.
+ **kwargs: Additional arguments.
Returns:
The added instance.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
+ auto_refresh = kwargs.pop("auto_refresh", self.auto_refresh)
with wrap_sqlalchemy_exception():
instance = self._attach_to_session(data)
- self.session.flush()
- self.session.refresh(instance)
- self.session.expunge(instance)
+ self._flush_or_commit(auto_commit=auto_commit)
+ self._refresh(instance, auto_refresh=auto_refresh)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
- def add_many(self, data: list[ModelT]) -> list[ModelT]:
+ def add_many(
+ self,
+ data: list[ModelT],
+ **kwargs: Any,
+ ) -> list[ModelT]:
"""Add Many `data` to the collection.
Args:
data: list of Instances to be added to the collection.
-
+ **kwargs: Additional arguments.
Returns:
The added instances.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
self.session.add_all(data)
- self.session.flush()
+ self._flush_or_commit(auto_commit=auto_commit)
for datum in data:
- self.session.expunge(datum)
+ self._expunge(datum, auto_expunge=auto_expunge)
return data
- def delete(self, item_id: Any) -> ModelT:
+ def delete(
+ self,
+ item_id: Any,
+ **kwargs: Any,
+ ) -> ModelT:
"""Delete instance identified by ``item_id``.
Args:
item_id: Identifier of instance to be deleted.
+ **kwargs: Additional arguments.
Returns:
The deleted instance.
@@ -96,23 +130,32 @@ def delete(self, item_id: Any) -> ModelT:
Raises:
NotFoundError: If no instance found identified by ``item_id``.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
instance = self.get(item_id)
self.session.delete(instance)
- self.session.flush()
- self.session.expunge(instance)
+ self._flush_or_commit(auto_commit=auto_commit)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
- def delete_many(self, item_ids: list[Any]) -> list[ModelT]:
+ def delete_many(
+ self,
+ item_ids: list[Any],
+ **kwargs: Any,
+ ) -> list[ModelT]:
"""Delete instance identified by `item_id`.
Args:
item_ids: Identifier of instance to be deleted.
+ **kwargs: Additional arguments.
Returns:
The deleted instances.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
instances: list[ModelT] = []
chunk_size = 450
@@ -135,9 +178,9 @@ def delete_many(self, item_ids: list[Any]) -> list[ModelT]:
self.session.execute(
delete(self.model_type).where(getattr(self.model_type, self.id_attribute).in_(chunk))
)
- self.session.flush()
+ self._flush_or_commit(auto_commit=auto_commit)
for instance in instances:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instances
def exists(self, **kwargs: Any) -> bool:
@@ -166,12 +209,13 @@ def get(self, item_id: Any, **kwargs: Any) -> ModelT:
Raises:
NotFoundError: If no instance found identified by `item_id`.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
statement = kwargs.pop("statement", self.statement)
statement = self._filter_select_by_kwargs(statement=statement, **{self.id_attribute: item_id})
instance = (self._execute(statement)).scalar_one_or_none()
instance = self.check_not_found(instance)
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
def get_one(self, **kwargs: Any) -> ModelT:
@@ -186,12 +230,13 @@ def get_one(self, **kwargs: Any) -> ModelT:
Raises:
NotFoundError: If no instance found identified by `item_id`.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
statement = kwargs.pop("statement", self.statement)
statement = self._filter_select_by_kwargs(statement=statement, **kwargs)
instance = (self._execute(statement)).scalar_one_or_none()
instance = self.check_not_found(instance)
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
def get_one_or_none(self, **kwargs: Any) -> ModelT | None:
@@ -203,27 +248,38 @@ def get_one_or_none(self, **kwargs: Any) -> ModelT | None:
Returns:
The retrieved instance or None
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
with wrap_sqlalchemy_exception():
statement = kwargs.pop("statement", self.statement)
statement = self._filter_select_by_kwargs(statement=statement, **kwargs)
instance = (self._execute(statement)).scalar_one_or_none()
if instance:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance # type: ignore
def get_or_create(
- self, match_fields: list[str] | str | None = None, upsert: bool = True, **kwargs: Any
+ self,
+ match_fields: list[str] | str | None = None,
+ upsert: bool = True,
+ attribute_names: Iterable[str] | None = None,
+ with_for_update: bool | None = None,
+ **kwargs: Any,
) -> tuple[ModelT, bool]:
"""Get instance identified by ``kwargs`` or create if it doesn't exist.
Args:
match_fields: a list of keys to use to match the existing model. When empty, all fields are matched.
upsert: When using match_fields and actual model values differ from `kwargs`, perform an update operation on the model.
+ attribute_names: an iterable of attribute names to pass into the ``update`` method.
+ with_for_update: indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT
**kwargs: Identifier of the instance to be retrieved.
Returns:
a tuple that includes the instance and whether or not it needed to be created. When using match_fields and actual model values differ from `kwargs`, the model value will be updated.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
+ auto_refresh = kwargs.pop("auto_refresh", self.auto_refresh)
match_fields = match_fields or self.match_fields
if isinstance(match_fields, str):
match_fields = [match_fields]
@@ -244,9 +300,11 @@ def get_or_create(
if field and field != new_field_value:
setattr(existing, field_name, new_field_value)
existing = self._attach_to_session(existing, strategy="merge")
- self.session.flush()
- self.session.refresh(existing)
- self.session.expunge(existing)
+ self._flush_or_commit(auto_commit=auto_commit)
+ self._refresh(
+ existing, attribute_names=attribute_names, with_for_update=with_for_update, auto_refresh=auto_refresh
+ )
+ self._expunge(existing, auto_expunge=auto_expunge)
return existing, False
def count(self, *filters: FilterTypes, **kwargs: Any) -> int:
@@ -269,12 +327,21 @@ def count(self, *filters: FilterTypes, **kwargs: Any) -> int:
results = self._execute(statement)
return results.scalar_one() # type: ignore
- def update(self, data: ModelT) -> ModelT:
+ def update(
+ self,
+ data: ModelT,
+ attribute_names: Iterable[str] | None = None,
+ with_for_update: bool | None = None,
+ **kwargs: Any,
+ ) -> ModelT:
"""Update instance with the attribute values present on `data`.
Args:
data: An instance that should have a value for `self.id_attribute` that exists in the
collection.
+ attribute_names: an iterable of attribute names to pass into the ``update`` method.
+ with_for_update: indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT
+ **kwargs: Additional arguments.
Returns:
The updated instance.
@@ -282,18 +349,27 @@ def update(self, data: ModelT) -> ModelT:
Raises:
NotFoundError: If no instance found with same identifier as `data`.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
+ auto_refresh = kwargs.pop("auto_refresh", self.auto_refresh)
with wrap_sqlalchemy_exception():
item_id = self.get_id_attribute_value(data)
# this will raise for not found, and will put the item in the session
self.get(item_id)
# this will merge the inbound data to the instance we just put in the session
instance = self._attach_to_session(data, strategy="merge")
- self.session.flush()
- self.session.refresh(instance)
- self.session.expunge(instance)
+ self._flush_or_commit(auto_commit=auto_commit)
+ self._refresh(
+ instance, attribute_names=attribute_names, with_for_update=with_for_update, auto_refresh=auto_refresh
+ )
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
- def update_many(self, data: list[ModelT]) -> list[ModelT]:
+ def update_many(
+ self,
+ data: list[ModelT],
+ **kwargs: Any,
+ ) -> list[ModelT]:
"""Update one or more instances with the attribute values present on `data`.
This function has an optimized bulk insert based on the configured SQL dialect:
@@ -303,6 +379,7 @@ def update_many(self, data: list[ModelT]) -> list[ModelT]:
Args:
data: A list of instances to update. Each should have a value for `self.id_attribute` that exists in the
collection.
+ **kwargs: Additional arguments.
Returns:
The updated instances.
@@ -310,6 +387,8 @@ def update_many(self, data: list[ModelT]) -> list[ModelT]:
Raises:
NotFoundError: If no instance found with same identifier as `data`.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
data_to_update: list[dict[str, Any]] = [v.to_dict() if isinstance(v, self.model_type) else v for v in data] # type: ignore
with wrap_sqlalchemy_exception():
if self._dialect.update_executemany_returning and self._dialect.name != "oracle":
@@ -321,15 +400,15 @@ def update_many(self, data: list[ModelT]) -> list[ModelT]:
# https://github.com/sqlalchemy/sqlalchemy/discussions/9925
)
)
- self.session.flush()
+ self._flush_or_commit(auto_commit=auto_commit)
for instance in instances:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instances
self.session.execute(
update(self.model_type),
data_to_update,
)
- self.session.flush()
+ self._flush_or_commit(auto_commit=auto_commit)
return data
def list_and_count(
@@ -350,6 +429,25 @@ def list_and_count(
return self._list_and_count_basic(*filters, **kwargs)
return self._list_and_count_window(*filters, **kwargs)
+ def _expunge(self, instance: ModelT, auto_expunge: bool) -> None:
+ return self.session.expunge(instance) if auto_expunge else None
+
+ def _flush_or_commit(self, auto_commit: bool) -> None:
+ return self.session.commit() if auto_commit else self.session.flush()
+
+ def _refresh(
+ self,
+ instance: ModelT,
+ auto_refresh: bool,
+ attribute_names: Iterable[str] | None = None,
+ with_for_update: bool | None = None,
+ ) -> None:
+ return (
+ self.session.refresh(instance, attribute_names=attribute_names, with_for_update=with_for_update)
+ if auto_refresh
+ else None
+ )
+
def _list_and_count_window(
self,
*filters: FilterTypes,
@@ -364,6 +462,7 @@ def _list_and_count_window(
Returns:
Count of records returned by query using an analytical window function, ignoring pagination.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
statement = kwargs.pop("statement", self.statement)
statement = statement.add_columns(over(sql_func.count(self.get_id_attribute_value(self.model_type))))
statement = self._apply_filters(*filters, statement=statement)
@@ -373,7 +472,7 @@ def _list_and_count_window(
count: int = 0
instances: list[ModelT] = []
for i, (instance, count_value) in enumerate(result):
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
instances.append(instance)
if i == 0:
count = count_value
@@ -393,6 +492,7 @@ def _list_and_count_basic(
Returns:
Count of records returned by query using 2 queries, ignoring pagination.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
statement = kwargs.pop("statement", self.statement)
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, **kwargs)
@@ -406,7 +506,7 @@ def _list_and_count_basic(
result = self._execute(statement)
instances: list[ModelT] = []
for (instance,) in result:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
instances.append(instance)
return instances, count
@@ -420,6 +520,7 @@ def list(self, *filters: FilterTypes, **kwargs: Any) -> list[ModelT]:
Returns:
The list of instances, after filtering applied.
"""
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
statement = kwargs.pop("statement", self.statement)
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, **kwargs)
@@ -428,10 +529,16 @@ def list(self, *filters: FilterTypes, **kwargs: Any) -> list[ModelT]:
result = self._execute(statement)
instances = list(result.scalars())
for instance in instances:
- self.session.expunge(instance)
+ self._expunge(instance, auto_expunge=auto_expunge)
return instances
- def upsert(self, data: ModelT) -> ModelT:
+ def upsert(
+ self,
+ data: ModelT,
+ attribute_names: Iterable[str] | None = None,
+ with_for_update: bool | None = None,
+ **kwargs: Any,
+ ) -> ModelT:
"""Update or create instance.
Updates instance with the attribute values present on `data`, or creates a new instance if
@@ -441,6 +548,9 @@ def upsert(self, data: ModelT) -> ModelT:
data: Instance to update existing, or be created. Identifier used to determine if an
existing instance exists is the value of an attribute on `data` named as value of
`self.id_attribute`.
+ attribute_names: an iterable of attribute names to pass into the ``update`` method.
+ with_for_update: indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT
+ **kwargs: Instance attribute value filters.
Returns:
The updated or created instance.
@@ -448,11 +558,16 @@ def upsert(self, data: ModelT) -> ModelT:
Raises:
NotFoundError: If no instance found with same identifier as `data`.
"""
+ auto_commit = kwargs.pop("auto_commit", self.auto_commit)
+ auto_expunge = kwargs.pop("auto_expunge", self.auto_expunge)
+ auto_refresh = kwargs.pop("auto_refresh", self.auto_refresh)
with wrap_sqlalchemy_exception():
instance = self._attach_to_session(data, strategy="merge")
- self.session.flush()
- self.session.refresh(instance)
- self.session.expunge(instance)
+ self._flush_or_commit(auto_commit=auto_commit)
+ self._refresh(
+ instance, attribute_names=attribute_names, with_for_update=with_for_update, auto_refresh=auto_refresh
+ )
+ self._expunge(instance, auto_expunge=auto_expunge)
return instance
def filter_collection_by_kwargs( # type:ignore[override]
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/models_bigint.py b/tests/unit/test_contrib/test_sqlalchemy/models_bigint.py
--- a/tests/unit/test_contrib/test_sqlalchemy/models_bigint.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/models_bigint.py
@@ -4,7 +4,7 @@
from datetime import date, datetime
from typing import List
-from sqlalchemy import FetchedValue, ForeignKey, String, func
+from sqlalchemy import Column, FetchedValue, ForeignKey, String, Table, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from litestar.contrib.sqlalchemy.base import BigIntAuditBase, BigIntBase
@@ -43,14 +43,39 @@ class BigIntEventLog(BigIntAuditBase):
class BigIntModelWithFetchedValue(BigIntBase):
"""The ModelWithFetchedValue BigIntBase."""
- val: Mapped[int]
- updated: Mapped[datetime] = mapped_column(
+ val: Mapped[int] # pyright: ignore
+ updated: Mapped[datetime] = mapped_column( # pyright: ignore
server_default=func.current_timestamp(),
onupdate=func.current_timestamp(),
server_onupdate=FetchedValue(),
)
+bigint_item_tag = Table(
+ "bigint_item_tag",
+ BigIntBase.metadata,
+ Column("item_id", ForeignKey("big_int_item.id"), primary_key=True),
+ Column("tag_id", ForeignKey("big_int_tag.id"), primary_key=True),
+)
+
+
+class BigIntItem(BigIntBase):
+ name: Mapped[str] = mapped_column(String(length=50)) # pyright: ignore
+ description: Mapped[str] = mapped_column(String(length=100), nullable=True) # pyright: ignore
+ tags: Mapped[List[BigIntTag]] = relationship( # pyright: ignore # noqa: UP
+ secondary=lambda: bigint_item_tag, back_populates="items"
+ )
+
+
+class BigIntTag(BigIntBase):
+ """The event log domain object."""
+
+ name: Mapped[str] = mapped_column(String(length=50)) # pyright: ignore
+ items: Mapped[List[BigIntItem]] = relationship( # pyright: ignore # noqa: UP
+ secondary=lambda: bigint_item_tag, back_populates="tags"
+ )
+
+
class BigIntRule(BigIntAuditBase):
"""The rule domain object."""
@@ -88,6 +113,18 @@ class ModelWithFetchedValueAsyncRepository(SQLAlchemyAsyncRepository[BigIntModel
model_type = BigIntModelWithFetchedValue
+class TagAsyncRepository(SQLAlchemyAsyncRepository[BigIntTag]):
+ """Tag repository."""
+
+ model_type = BigIntTag
+
+
+class ItemAsyncRepository(SQLAlchemyAsyncRepository[BigIntItem]):
+ """Item repository."""
+
+ model_type = BigIntItem
+
+
class AuthorSyncRepository(SQLAlchemySyncRepository[BigIntAuthor]):
"""Author repository."""
@@ -116,3 +153,15 @@ class ModelWithFetchedValueSyncRepository(SQLAlchemySyncRepository[BigIntModelWi
"""ModelWithFetchedValue repository."""
model_type = BigIntModelWithFetchedValue
+
+
+class TagSyncRepository(SQLAlchemySyncRepository[BigIntTag]):
+ """Tag repository."""
+
+ model_type = BigIntTag
+
+
+class ItemSyncRepository(SQLAlchemySyncRepository[BigIntItem]):
+ """Item repository."""
+
+ model_type = BigIntItem
diff --git a/tests/unit/test_contrib/test_sqlalchemy/models_uuid.py b/tests/unit/test_contrib/test_sqlalchemy/models_uuid.py
--- a/tests/unit/test_contrib/test_sqlalchemy/models_uuid.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/models_uuid.py
@@ -6,9 +6,10 @@
from typing import List
from uuid import UUID
-from sqlalchemy import FetchedValue, ForeignKey, String, func
+from sqlalchemy import Column, FetchedValue, ForeignKey, String, Table, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
+from litestar.contrib.sqlalchemy import base
from litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase
from litestar.contrib.sqlalchemy.repository import SQLAlchemyAsyncRepository, SQLAlchemySyncRepository
@@ -43,14 +44,39 @@ class UUIDEventLog(UUIDAuditBase):
class UUIDModelWithFetchedValue(UUIDBase):
"""The ModelWithFetchedValue UUIDBase."""
- val: Mapped[int]
- updated: Mapped[datetime] = mapped_column(
+ val: Mapped[int] # pyright: ignore
+ updated: Mapped[datetime] = mapped_column( # pyright: ignore
server_default=func.current_timestamp(),
onupdate=func.current_timestamp(),
server_onupdate=FetchedValue(),
)
+uuid_item_tag = Table(
+ "uuid_item_tag",
+ base.orm_registry.metadata,
+ Column("item_id", ForeignKey("uuid_item.id"), primary_key=True),
+ Column("tag_id", ForeignKey("uuid_tag.id"), primary_key=True),
+)
+
+
+class UUIDItem(UUIDBase):
+ name: Mapped[str] = mapped_column(String(length=50)) # pyright: ignore
+ description: Mapped[str] = mapped_column(String(length=100), nullable=True) # pyright: ignore
+ tags: Mapped[List[UUIDTag]] = relationship( # pyright: ignore # noqa: UP
+ secondary=lambda: uuid_item_tag, back_populates="items"
+ )
+
+
+class UUIDTag(UUIDAuditBase):
+ """The event log domain object."""
+
+ name: Mapped[str] = mapped_column(String(length=50)) # pyright: ignore
+ items: Mapped[List[UUIDItem]] = relationship( # pyright: ignore # noqa: UP
+ secondary=lambda: uuid_item_tag, back_populates="tags"
+ )
+
+
class UUIDRule(UUIDAuditBase):
"""The rule domain object."""
@@ -88,6 +114,18 @@ class ModelWithFetchedValueAsyncRepository(SQLAlchemyAsyncRepository[UUIDModelWi
model_type = UUIDModelWithFetchedValue
+class TagAsyncRepository(SQLAlchemyAsyncRepository[UUIDTag]):
+ """Tag repository."""
+
+ model_type = UUIDTag
+
+
+class ItemAsyncRepository(SQLAlchemyAsyncRepository[UUIDItem]):
+ """Item repository."""
+
+ model_type = UUIDItem
+
+
class AuthorSyncRepository(SQLAlchemySyncRepository[UUIDAuthor]):
"""Author repository."""
@@ -116,3 +154,15 @@ class ModelWithFetchedValueSyncRepository(SQLAlchemySyncRepository[UUIDModelWith
"""ModelWithFetchedValue repository."""
model_type = UUIDModelWithFetchedValue
+
+
+class TagSyncRepository(SQLAlchemySyncRepository[UUIDTag]):
+ """Tag repository."""
+
+ model_type = UUIDTag
+
+
+class ItemSyncRepository(SQLAlchemySyncRepository[UUIDItem]):
+ """Item repository."""
+
+ model_type = UUIDItem
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/conftest.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/conftest.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/conftest.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/conftest.py
@@ -292,7 +292,7 @@ def engine(request: FixtureRequest) -> Engine:
@pytest.fixture()
def session(engine: Engine) -> Generator[Session, None, None]:
- session = sessionmaker(bind=engine)()
+ session = sessionmaker(bind=engine, expire_on_commit=False)()
try:
yield session
finally:
@@ -402,7 +402,7 @@ def async_engine(request: FixtureRequest) -> AsyncEngine:
@pytest.fixture()
async def async_session(async_engine: AsyncEngine) -> AsyncGenerator[AsyncSession, None]:
- session = async_sessionmaker(bind=async_engine)()
+ session = async_sessionmaker(bind=async_engine, expire_on_commit=False)()
try:
yield session
finally:
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
@@ -20,14 +20,20 @@
AuthorSyncRepository,
BigIntAuthor,
BigIntBook,
+ BigIntItem,
BigIntModelWithFetchedValue,
BigIntRule,
+ BigIntTag,
BookAsyncRepository,
BookSyncRepository,
+ ItemAsyncRepository,
+ ItemSyncRepository,
ModelWithFetchedValueAsyncRepository,
ModelWithFetchedValueSyncRepository,
RuleAsyncRepository,
RuleSyncRepository,
+ TagAsyncRepository,
+ TagSyncRepository,
)
from .helpers import maybe_async, update_raw_records
@@ -102,6 +108,20 @@ def model_with_fetched_value_repo(
return ModelWithFetchedValueSyncRepository(session=any_session)
[email protected]()
+def tag_repo(any_session: AsyncSession | Session) -> TagAsyncRepository | TagSyncRepository:
+ if isinstance(any_session, AsyncSession):
+ return TagAsyncRepository(session=any_session)
+ return TagSyncRepository(session=any_session)
+
+
[email protected]()
+def item_repo(any_session: AsyncSession | Session) -> ItemAsyncRepository | ItemSyncRepository:
+ if isinstance(any_session, AsyncSession):
+ return ItemAsyncRepository(session=any_session)
+ return ItemSyncRepository(session=any_session)
+
+
def test_filter_by_kwargs_with_incorrect_attribute_name(author_repo: AuthorAsyncRepository) -> None:
"""Test SQLALchemy filter by kwargs with invalid column name.
@@ -506,3 +526,36 @@ async def test_repo_fetched_value(model_with_fetched_value_repo: ModelWithFetche
assert obj.updated is not None
assert obj.val == 2
assert obj.updated != first_time
+
+
+async def test_lazy_load(item_repo: ItemAsyncRepository, tag_repo: TagAsyncRepository) -> None:
+ """Test SQLALchemy fetched value in various places.
+
+ Args:
+ item_repo (ItemAsyncRepository): The item mock repository
+ tag_repo (TagAsyncRepository): The tag mock repository
+ """
+
+ tag_obj = await maybe_async(tag_repo.add(BigIntTag(name="A new tag")))
+ assert tag_obj
+ new_items = await maybe_async(
+ item_repo.add_many([BigIntItem(name="The first item"), BigIntItem(name="The second item")])
+ )
+ await maybe_async(item_repo.session.commit())
+ await maybe_async(tag_repo.session.commit())
+ assert len(new_items) > 0
+ first_item_id = new_items[0].id
+ new_items[1].id
+ update_data = {
+ "name": "A modified Name",
+ "tag_names": ["A new tag"],
+ "id": first_item_id,
+ }
+ tags_to_add = await maybe_async(tag_repo.list(CollectionFilter("name", update_data.pop("tag_names", [])))) # type: ignore
+ assert len(tags_to_add) > 0
+ assert tags_to_add[0].id is not None
+ update_data["tags"] = tags_to_add
+ updated_obj = await maybe_async(item_repo.update(BigIntItem(**update_data), auto_refresh=False))
+ await maybe_async(item_repo.session.commit())
+ assert len(updated_obj.tags) > 0
+ assert updated_obj.tags[0].name == "A new tag"
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
@@ -25,14 +25,20 @@
AuthorSyncRepository,
BookAsyncRepository,
BookSyncRepository,
+ ItemAsyncRepository,
+ ItemSyncRepository,
ModelWithFetchedValueAsyncRepository,
ModelWithFetchedValueSyncRepository,
RuleAsyncRepository,
RuleSyncRepository,
+ TagAsyncRepository,
+ TagSyncRepository,
UUIDAuthor,
UUIDBook,
+ UUIDItem,
UUIDModelWithFetchedValue,
UUIDRule,
+ UUIDTag,
)
from .helpers import maybe_async, update_raw_records
@@ -189,6 +195,20 @@ def book_repo(any_session: AsyncSession | Session) -> BookAsyncRepository | Book
return BookSyncRepository(session=any_session)
[email protected]()
+def tag_repo(any_session: AsyncSession | Session) -> TagAsyncRepository | TagSyncRepository:
+ if isinstance(any_session, AsyncSession):
+ return TagAsyncRepository(session=any_session)
+ return TagSyncRepository(session=any_session)
+
+
[email protected]()
+def item_repo(any_session: AsyncSession | Session) -> ItemAsyncRepository | ItemSyncRepository:
+ if isinstance(any_session, AsyncSession):
+ return ItemAsyncRepository(session=any_session)
+ return ItemSyncRepository(session=any_session)
+
+
@pytest.fixture()
def model_with_fetched_value_repo(
any_session: AsyncSession | Session,
@@ -612,3 +632,36 @@ async def test_repo_fetched_value(model_with_fetched_value_repo: ModelWithFetche
assert obj.updated is not None
assert obj.val == 2
assert obj.updated != first_time
+
+
+async def test_lazy_load(item_repo: ItemAsyncRepository, tag_repo: TagAsyncRepository) -> None:
+ """Test SQLALchemy fetched value in various places.
+
+ Args:
+ item_repo (ItemAsyncRepository): The item mock repository
+ tag_repo (TagAsyncRepository): The tag mock repository
+ """
+
+ tag_obj = await maybe_async(tag_repo.add(UUIDTag(name="A new tag")))
+ assert tag_obj
+ new_items = await maybe_async(
+ item_repo.add_many([UUIDItem(name="The first item"), UUIDItem(name="The second item")])
+ )
+ await maybe_async(item_repo.session.commit())
+ await maybe_async(tag_repo.session.commit())
+ assert len(new_items) > 0
+ first_item_id = new_items[0].id
+ new_items[1].id
+ update_data = {
+ "name": "A modified Name",
+ "tag_names": ["A new tag"],
+ "id": first_item_id,
+ }
+ tags_to_add = await maybe_async(tag_repo.list(CollectionFilter("name", update_data.pop("tag_names", [])))) # type: ignore
+ assert len(tags_to_add) > 0
+ assert tags_to_add[0].id is not None
+ update_data["tags"] = tags_to_add
+ updated_obj = await maybe_async(item_repo.update(UUIDItem(**update_data), auto_refresh=False))
+ await maybe_async(item_repo.session.commit())
+ assert len(updated_obj.tags) > 0
+ assert updated_obj.tags[0].name == "A new tag"
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
@@ -122,8 +122,8 @@ async def test_sqlalchemy_repo_add(mock_repo: SQLAlchemyAsyncRepository) -> None
assert instance is mock_instance
mock_repo.session.add.assert_called_once_with(mock_instance)
mock_repo.session.flush.assert_called_once()
- mock_repo.session.refresh.assert_called_once_with(mock_instance)
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.refresh.assert_called_once_with(mock_instance, attribute_names=None, with_for_update=None)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -151,7 +151,7 @@ class BigIntModel(base.BigIntAuditBase):
assert len(instances) == 3
for row in instances:
assert row.id is not None
- mock_repo.session.expunge.assert_called()
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -194,7 +194,7 @@ async def test_sqlalchemy_repo_delete(mock_repo: SQLAlchemyAsyncRepository, monk
assert instance is mock_instance
mock_repo.session.delete.assert_called_once_with(mock_instance)
mock_repo.session.flush.assert_called_once()
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -236,7 +236,7 @@ async def test_sqlalchemy_repo_get_member(mock_repo: SQLAlchemyAsyncRepository,
monkeypatch.setattr(mock_repo, "_execute", execute_mock)
instance = await mock_repo.get("instance-id")
assert instance is mock_instance
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -249,7 +249,7 @@ async def test_sqlalchemy_repo_get_one_member(mock_repo: SQLAlchemyAsyncReposito
monkeypatch.setattr(mock_repo, "_execute", execute_mock)
instance = await mock_repo.get_one(id="instance-id")
assert instance is mock_instance
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -267,7 +267,7 @@ async def test_sqlalchemy_repo_get_or_create_member_existing(
instance, created = await mock_repo.get_or_create(id="instance-id", upsert=False)
assert instance is mock_instance
assert created is False
- mock_repo.session.expunge.assert_called_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.merge.assert_not_called()
mock_repo.session.refresh.assert_not_called()
@@ -286,10 +286,10 @@ async def test_sqlalchemy_repo_get_or_create_member_existing_upsert(
instance, created = await mock_repo.get_or_create(id="instance-id", upsert=True, an_extra_attribute="yep")
assert instance is mock_instance
assert created is False
- mock_repo.session.expunge.assert_called_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo._attach_to_session.assert_called_once()
mock_repo.session.flush.assert_called_once()
- mock_repo.session.refresh.assert_called_once_with(mock_instance)
+ mock_repo.session.refresh.assert_called_once_with(mock_instance, attribute_names=None, with_for_update=None)
async def test_sqlalchemy_repo_get_or_create_member_existing_no_upsert(
@@ -304,7 +304,7 @@ async def test_sqlalchemy_repo_get_or_create_member_existing_no_upsert(
instance, created = await mock_repo.get_or_create(id="instance-id", upsert=False, an_extra_attribute="yep")
assert instance is mock_instance
assert created is False
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.add.assert_not_called()
mock_repo.session.refresh.assert_not_called()
@@ -320,9 +320,9 @@ async def test_sqlalchemy_repo_get_or_create_member_created(
instance, created = await mock_repo.get_or_create(id="new-id")
assert instance is not None
assert created is True
- mock_repo.session.expunge.assert_called_once_with(instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.add.assert_called_once_with(instance)
- mock_repo.session.refresh.assert_called_once_with(instance)
+ mock_repo.session.refresh.assert_called_once_with(instance, attribute_names=None, with_for_update=None)
async def test_sqlalchemy_repo_get_one_or_none_member(
@@ -336,7 +336,7 @@ async def test_sqlalchemy_repo_get_one_or_none_member(
monkeypatch.setattr(mock_repo, "_execute", execute_mock)
instance = await mock_repo.get_one_or_none(id="instance-id")
assert instance is mock_instance
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -364,7 +364,7 @@ async def test_sqlalchemy_repo_list(mock_repo: SQLAlchemyAsyncRepository, monkey
monkeypatch.setattr(mock_repo, "_execute", execute_mock)
instances = await mock_repo.list()
assert instances == mock_instances
- mock_repo.session.expunge.assert_has_calls(*mock_instances)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -378,7 +378,7 @@ async def test_sqlalchemy_repo_list_and_count(mock_repo: SQLAlchemyAsyncReposito
instances, instance_count = await mock_repo.list_and_count()
assert instances == mock_instances
assert instance_count == mock_count
- mock_repo.session.expunge.assert_has_calls(*mock_instances)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -475,9 +475,9 @@ async def test_sqlalchemy_repo_update(mock_repo: SQLAlchemyAsyncRepository, monk
assert instance is mock_instance
mock_repo.session.merge.assert_called_once_with(mock_instance)
mock_repo.session.flush.assert_called_once()
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
- mock_repo.session.refresh.assert_called_once_with(mock_instance)
+ mock_repo.session.refresh.assert_called_once_with(mock_instance, attribute_names=None, with_for_update=None)
async def test_sqlalchemy_repo_upsert(mock_repo: SQLAlchemyAsyncRepository) -> None:
@@ -488,9 +488,9 @@ async def test_sqlalchemy_repo_upsert(mock_repo: SQLAlchemyAsyncRepository) -> N
assert instance is mock_instance
mock_repo.session.merge.assert_called_once_with(mock_instance)
mock_repo.session.flush.assert_called_once()
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
- mock_repo.session.refresh.assert_called_once_with(mock_instance)
+ mock_repo.session.refresh.assert_called_once_with(mock_instance, attribute_names=None, with_for_update=None)
async def test_attach_to_session_unexpected_strategy_raises_valueerror(
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
@@ -121,8 +121,8 @@ def test_sqlalchemy_repo_add(mock_repo: SQLAlchemySyncRepository) -> None:
assert instance is mock_instance
mock_repo.session.add.assert_called_once_with(mock_instance)
mock_repo.session.flush.assert_called_once()
- mock_repo.session.refresh.assert_called_once_with(mock_instance)
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.refresh.assert_called_once_with(mock_instance, attribute_names=None, with_for_update=None)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -150,7 +150,7 @@ class BigIntModel(base.BigIntAuditBase):
assert len(instances) == 3
for row in instances:
assert row.id is not None
- mock_repo.session.expunge.assert_called()
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -193,7 +193,7 @@ def test_sqlalchemy_repo_delete(mock_repo: SQLAlchemySyncRepository, monkeypatch
assert instance is mock_instance
mock_repo.session.delete.assert_called_once_with(mock_instance)
mock_repo.session.flush.assert_called_once()
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -235,7 +235,7 @@ def test_sqlalchemy_repo_get_member(mock_repo: SQLAlchemySyncRepository, monkeyp
monkeypatch.setattr(mock_repo, "_execute", execute_mock)
instance = mock_repo.get("instance-id")
assert instance is mock_instance
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -248,7 +248,7 @@ def test_sqlalchemy_repo_get_one_member(mock_repo: SQLAlchemySyncRepository, mon
monkeypatch.setattr(mock_repo, "_execute", execute_mock)
instance = mock_repo.get_one(id="instance-id")
assert instance is mock_instance
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -267,7 +267,7 @@ def test_sqlalchemy_repo_get_or_create_member_existing(
instance, created = mock_repo.get_or_create(id="instance-id", upsert=False)
assert instance is mock_instance
assert created is False
- mock_repo.session.expunge.assert_called_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.merge.assert_not_called()
mock_repo.session.refresh.assert_not_called()
@@ -286,10 +286,10 @@ def test_sqlalchemy_repo_get_or_create_member_existing_upsert(
instance, created = mock_repo.get_or_create(id="instance-id", upsert=True, an_extra_attribute="yep")
assert instance is mock_instance
assert created is False
- mock_repo.session.expunge.assert_called_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo._attach_to_session.assert_called_once()
mock_repo.session.flush.assert_called_once()
- mock_repo.session.refresh.assert_called_once_with(mock_instance)
+ mock_repo.session.refresh.assert_called_once_with(mock_instance, attribute_names=None, with_for_update=None)
def test_sqlalchemy_repo_get_or_create_member_existing_no_upsert(
@@ -304,7 +304,7 @@ def test_sqlalchemy_repo_get_or_create_member_existing_no_upsert(
instance, created = mock_repo.get_or_create(id="instance-id", upsert=False, an_extra_attribute="yep")
assert instance is mock_instance
assert created is False
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.add.assert_not_called()
mock_repo.session.refresh.assert_not_called()
@@ -320,9 +320,9 @@ def test_sqlalchemy_repo_get_or_create_member_created(
instance, created = mock_repo.get_or_create(id="new-id")
assert instance is not None
assert created is True
- mock_repo.session.expunge.assert_called_with(instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.add.assert_called_once_with(instance)
- mock_repo.session.refresh.assert_called_once_with(instance)
+ mock_repo.session.refresh.assert_called_once_with(instance, attribute_names=None, with_for_update=None)
def test_sqlalchemy_repo_get_one_or_none_member(mock_repo: SQLAlchemySyncRepository, monkeypatch: MonkeyPatch) -> None:
@@ -334,7 +334,7 @@ def test_sqlalchemy_repo_get_one_or_none_member(mock_repo: SQLAlchemySyncReposit
monkeypatch.setattr(mock_repo, "_execute", execute_mock)
instance = mock_repo.get_one_or_none(id="instance-id")
assert instance is mock_instance
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -362,7 +362,7 @@ def test_sqlalchemy_repo_list(mock_repo: SQLAlchemySyncRepository, monkeypatch:
monkeypatch.setattr(mock_repo, "_execute", execute_mock)
instances = mock_repo.list()
assert instances == mock_instances
- mock_repo.session.expunge.assert_has_calls(*mock_instances)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -376,7 +376,7 @@ def test_sqlalchemy_repo_list_and_count(mock_repo: SQLAlchemySyncRepository, mon
instances, instance_count = mock_repo.list_and_count()
assert instances == mock_instances
assert instance_count == mock_count
- mock_repo.session.expunge.assert_has_calls(*mock_instances)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
@@ -471,9 +471,9 @@ def test_sqlalchemy_repo_update(mock_repo: SQLAlchemySyncRepository, monkeypatch
assert instance is mock_instance
mock_repo.session.merge.assert_called_once_with(mock_instance)
mock_repo.session.flush.assert_called_once()
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
- mock_repo.session.refresh.assert_called_once_with(mock_instance)
+ mock_repo.session.refresh.assert_called_once_with(mock_instance, attribute_names=None, with_for_update=None)
def test_sqlalchemy_repo_upsert(mock_repo: SQLAlchemySyncRepository) -> None:
@@ -484,9 +484,9 @@ def test_sqlalchemy_repo_upsert(mock_repo: SQLAlchemySyncRepository) -> None:
assert instance is mock_instance
mock_repo.session.merge.assert_called_once_with(mock_instance)
mock_repo.session.flush.assert_called_once()
- mock_repo.session.expunge.assert_called_once_with(mock_instance)
+ mock_repo.session.expunge.assert_not_called()
mock_repo.session.commit.assert_not_called()
- mock_repo.session.refresh.assert_called_once_with(mock_instance)
+ mock_repo.session.refresh.assert_called_once_with(mock_instance, attribute_names=None, with_for_update=None)
def test_attach_to_session_unexpected_strategy_raises_valueerror(
| Question: problems with sqlalchemy repository update and lazy loading
I'm having trouble reading a field representing a many-to-many relationship after using the [repo `update` method](https://github.com/litestar-org/litestar/blob/main/litestar/contrib/sqlalchemy/repository/_async.py#L270). This is what I found out so far.
My sqla repository has `statement=select(Item).options(selectinload(Item.tags))` in order to include the tags in the response, which works great for the `get` and `list` methods.
When setting for the `lazy` arg for the `tags` relationship defined for the `Item` model, AKA configuring the loader strategy at [mapping time](https://docs.sqlalchemy.org/en/20/orm/queryguide/relationships.html#configuring-loader-strategies-at-mapping-time) :
- If I set the `lazy` arg to `"noload"`, the one that I desire, the response ends up with an empty tags list in the case I'm updating a field other than `tags`. I only get a valid response when the `tags` field itself is being updated.
- If I set the `lazy` arg to `"selectin"`, then it works as expected for `update`, but then I also get tags for regular `select(Item)` statement, which is undesired.
- If I leave the `lazy` arg empty/default/`"select"`, then I get:
```
sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Item at 0x7fb31aaea590> is not bound to a Session; lazy load operation of attribute 'tags' cannot proceed (Background on this error at: https://sqla
lche.me/e/20/bhk3)
```
I read through the above [error help](https://docs.sqlalchemy.org/en/20/errors.html#error-bhk3). I already have `expire_on_commit=False` and my sqla repository has `statement=select(Item).options(selectinload(Item.tags))`, but for some reason `update` doesn't care about the statement options even though it calls `get` internally, and, from what I can tell, instead uses the loader strategies configured at mapping time.
Here's some of my code:
```python
item_tag = Table(
"item_tag",
UUIDBase.metadata,
Column("item_id", ForeignKey("item.id"), primary_key=True),
Column("tag_id", ForeignKey("tag.id"), primary_key=True),
)
class Item(UUIDBase):
name: Mapped[str] = mapped_column(String(), unique=True)
description: Mapped[str | None]
tags: Mapped[list[Tag]] = relationship(
secondary=item_tag,
back_populates="items"
lazy="noload" # <-- here be problems
)
class Tag(UUIDBase):
name: Mapped[str] = mapped_column(String(), unique=True,
items: Mapped[list[Item]] = relationship(
secondary=item_tag,
back_populates="tags",
lazy="noload"
)
@patch(
path="/{item_id:uuid}",
)
async def update_item(
item_repo: ItemRepository,
tag_repo: TagRepository,
data: ItemUpdate,
item_id: UUID = Parameter(
title="Item ID",
description="The item to update",
),
) -> ItemDB:
dd = data.dict(exclude_unset=True)
dd.update({"id": item_id})
if "tag_names" in dd:
if len(dd["tag_names"]) != 0:
dd["tags"] = await tag_repo.list(
CollectionFilter("name", dd["tag_names"])
)
else:
dd["tags"] = []
del dd["tag_names"]
obj = await item_repo.update(Item(**dd))
await item_repo.session.commit()
return parse_obj_as(ItemDB, obj) # <-- here be errors
```
Hopefully that was clear and I provided enough context. I'm a bit lost on how to solve this and wondering if it may indicate an issue with the method's implementation itself.
<!-- POLAR PLEDGE BADGE START -->
## Funding
* You can sponsor this specific effort via a [Polar.sh](https://polar.sh) pledge below
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/1895">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1895/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1895/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| Out of curiosity, does this issue persist if the `refresh` method on the `update` is not called?
@peterschutt, this error looks familiar to me, but I haven't seen it in a while. This may have something to do with why I removed the `refresh`.
> Out of curiosity, does this issue persist if the `refresh` method on the `update` is not called?
>
> @peterschutt, this error looks familiar to me, but I haven't seen it in a while. This may have something to do with why I removed the `refresh`.
I initially noticed this on [v2.0.0beta2](https://github.com/litestar-org/litestar/releases/tag/v2.0.0beta2), that didn't have the refresh. I updated the litestar dep to point to main and the behavior persists.
I'll try to set up a test repo.
I've actually almost finished setting up the test case. I'll link the PR here in just a moment in case you want to test as well.
I agree. Do you want to submit a PR? | 2023-07-01T18:04:56 |
litestar-org/litestar | 1,906 | litestar-org__litestar-1906 | [
"1905",
"1234"
] | 32396925a573c02eff57aa10b2060f505b920232 | diff --git a/litestar/contrib/sqlalchemy/base.py b/litestar/contrib/sqlalchemy/base.py
--- a/litestar/contrib/sqlalchemy/base.py
+++ b/litestar/contrib/sqlalchemy/base.py
@@ -66,7 +66,7 @@ def touch_updated_timestamp(session: Session, *_: Any) -> None:
"""
for instance in session.dirty:
if hasattr(instance, "updated_at"):
- instance.updated = (datetime.now(timezone.utc),)
+ instance.updated_at = datetime.now(timezone.utc)
@runtime_checkable
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
@@ -164,7 +164,7 @@ async def test_repo_created_updated(author_repo: AuthorAsyncRepository) -> None:
author.books.append(BigIntBook(title="Testing"))
author = await maybe_async(author_repo.update(author))
- assert author.updated_at == original_update_dt
+ assert author.updated_at > original_update_dt
async def test_repo_list_method(raw_authors_bigint: list[dict[str, Any]], author_repo: AuthorAsyncRepository) -> None:
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
@@ -260,7 +260,7 @@ async def test_repo_created_updated(author_repo: AuthorAsyncRepository) -> None:
author.books.append(UUIDBook(title="Testing"))
author = await maybe_async(author_repo.update(author))
- assert author.updated_at == original_update_dt
+ assert author.updated_at > original_update_dt
async def test_repo_list_method(
| Bug: SQL Alchemy repository `updated` vs `updated_at` column reference.
https://github.com/litestar-org/litestar/blob/32396925a573c02eff57aa10b2060f505b920232/litestar/contrib/sqlalchemy/base.py#L69
This incorrectly references the old `updated` column name instead of the `updated_at` column name.
<!-- POLAR PLEDGE BADGE START -->
## Funding
* You can sponsor this specific effort via a [Polar.sh](https://polar.sh) pledge below
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/1905">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1905/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1905/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
|
I agree. Do you want to submit a PR? | 2023-07-01T20:55:27 |
litestar-org/litestar | 1,908 | litestar-org__litestar-1908 | [
"4321",
"1234"
] | 55ce3a64886475c4243409d8d76758f68d437483 | diff --git a/litestar/constants.py b/litestar/constants.py
--- a/litestar/constants.py
+++ b/litestar/constants.py
@@ -14,7 +14,7 @@
ONE_MEGABYTE = 1024 * 1024
OPENAPI_NOT_INITIALIZED = "Litestar has not been instantiated with OpenAPIConfig"
REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308}
-REDIRECT_ALLOWED_MEDIA_TYPES = {MediaType.TEXT, MediaType.HTML}
+REDIRECT_ALLOWED_MEDIA_TYPES = {MediaType.TEXT, MediaType.HTML, MediaType.JSON}
RESERVED_KWARGS = {"state", "headers", "cookies", "request", "socket", "data", "query", "scope", "body"}
SCOPE_STATE_DEPENDENCY_CACHE: Literal["dependency_cache"] = "dependency_cache"
SCOPE_STATE_NAMESPACE: Literal["__litestar__"] = "__litestar__"
| diff --git a/tests/unit/test_response/test_redirect_response.py b/tests/unit/test_response/test_redirect_response.py
--- a/tests/unit/test_response/test_redirect_response.py
+++ b/tests/unit/test_response/test_redirect_response.py
@@ -81,7 +81,7 @@ async def app(scope: "Scope", receive: "Receive", send: "Send") -> None:
def test_redirect_response_media_type_validation() -> None:
with pytest.raises(ImproperlyConfiguredException):
- ASGIRedirectResponse(path="/", media_type="application/json")
+ ASGIRedirectResponse(path="/", media_type="application/mspgpack")
@pytest.mark.parametrize(
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-07-02T00:52:40 |
litestar-org/litestar | 1,917 | litestar-org__litestar-1917 | [
"1386"
] | a1b77530d9d74db69a12bc3cec95832809920746 | diff --git a/litestar/datastructures/headers.py b/litestar/datastructures/headers.py
--- a/litestar/datastructures/headers.py
+++ b/litestar/datastructures/headers.py
@@ -2,6 +2,7 @@
from abc import ABC, abstractmethod
from contextlib import suppress
from copy import copy
+from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
@@ -13,14 +14,18 @@
Mapping,
MutableMapping,
Optional,
+ Pattern,
+ Set,
Tuple,
+ Type,
Union,
cast,
+ get_args,
+ get_origin,
+ get_type_hints,
)
from multidict import CIMultiDict, CIMultiDictProxy, MultiMapping
-from pydantic import BaseModel, Extra, Field, ValidationError, validator
-from typing_extensions import Annotated
from litestar._multipart import parse_content_header
from litestar._parsers import parse_headers
@@ -29,6 +34,7 @@
__all__ = ("Accept", "CacheControlHeader", "ETag", "Header", "Headers", "MutableScopeHeaders")
+from litestar.utils.dataclass import simple_asdict
if TYPE_CHECKING:
from litestar.types.asgi_types import (
@@ -39,6 +45,7 @@
)
ETAG_RE = re.compile(r'([Ww]/)?"(.+)"')
+PRINTABLE_ASCII_RE: Pattern[str] = re.compile(r"^[ -~]+$")
def _encode_headers(headers: Iterable[Tuple[str, str]]) -> "RawHeadersList":
@@ -231,20 +238,12 @@ def __iter__(self) -> Iterator[str]:
return iter(h[0].decode("latin-1") for h in self.headers)
-class Header(BaseModel, ABC):
+@dataclass
+class Header(ABC):
"""An abstract type for HTTP headers."""
HEADER_NAME: ClassVar[str] = ""
- class Config:
- allow_population_by_field_name = True
- extra = Extra.forbid
-
- @classmethod
- def alias_generator(cls, field_name: str) -> str:
- """Generate field-aliases by replacing dashes with underscores in header-names."""
- return field_name.replace("_", "-")
-
documentation_only: bool = False
"""Defines the header instance as for OpenAPI documentation purpose only."""
@@ -272,7 +271,33 @@ def to_header(self, include_header_name: bool = False) -> str:
return (f"{self.HEADER_NAME}: " if include_header_name else "") + self._get_header_value()
-
+ def dict(
+ self,
+ exclude_none: bool = False,
+ exclude_empty: bool = False,
+ by_alias: bool = False,
+ exclude: Optional[Set[str]] = None,
+ exclude_unset: bool = False,
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ dictionary = simple_asdict(self, exclude_none=exclude_none, exclude_empty=exclude_empty, exclude=exclude)
+
+ if exclude_unset:
+ # This is a hack to get tests passing due to dataclasses not supporting exclude_unset see: https://github.com/pydantic/pydantic/discussions/5716
+ # Not sure how this should be handled properly
+ dictionary = {
+ k: v
+ for k, v in dictionary.items()
+ if (k == "documentation_only" and v is True) or k != "documentation_only"
+ }
+
+ if by_alias:
+ dictionary = {k.replace("_", "-"): v for k, v in dictionary.items()}
+
+ return dictionary
+
+
+@dataclass
class CacheControlHeader(Header):
"""A ``cache-control`` header."""
@@ -303,6 +328,8 @@ class CacheControlHeader(Header):
stale_while_revalidate: Optional[int] = None
"""Accessor for the ``stale-while-revalidate`` directive."""
+ _type_annotations: ClassVar[Optional[Dict[str, Type]]] = None
+
def _get_header_value(self) -> str:
"""Get the header value as string."""
@@ -330,18 +357,23 @@ def from_header(cls, header_value: str) -> "CacheControlHeader":
cc_items = [v.strip() for v in header_value.split(",")]
kwargs: Dict[str, Any] = {}
+ type_annotations = cls._get_type_annotations()
for cc_item in cc_items:
key_value = cc_item.split("=")
+ key_value[0] = key_value[0].replace("-", "_")
if len(key_value) == 1:
kwargs[key_value[0]] = True
elif len(key_value) == 2:
- kwargs[key_value[0]] = key_value[1]
+ key, value = key_value
+ if key not in type_annotations:
+ raise ImproperlyConfiguredException("Invalid cache-control header")
+ kwargs[key] = cls._convert_to_type(value, expected_type=type_annotations[key])
else:
raise ImproperlyConfiguredException("Invalid cache-control header value")
try:
return CacheControlHeader(**kwargs)
- except ValidationError as exc:
+ except TypeError as exc:
raise ImproperlyConfiguredException from exc
@classmethod
@@ -352,14 +384,70 @@ def prevent_storing(cls) -> "CacheControlHeader":
return cls(no_store=True)
+ @classmethod
+ def _get_type_annotations(cls) -> Dict[str, Type]:
+ """Get the type annotations for the ``CacheControlHeader`` class properties.
+
+ This is needed due to the conversion from pydantic models to dataclasses. Dataclasses do not support
+ automatic conversion of types like pydantic models do.
+
+ Returns:
+ A dictionary of type annotations
+
+ """
+
+ def is_concrete_type(value: Type) -> bool:
+ args = get_args(value)
+ origin = get_origin(value)
+ return len(args) == 0 and origin is None
+
+ if cls._type_annotations is None:
+ cls._type_annotations = {}
+ for key, value in get_type_hints(cls).items():
+ if key == "_type_annotations":
+ continue
+
+ args = get_args(value)
+ origin = get_origin(value)
+ is_optional = len(args) == 2 and args[1] is type(None)
+ is_concrete = is_concrete_type(value)
+ is_concrete_class_var = len(args) == 1 and is_concrete_type(args[0]) and origin is ClassVar
+
+ if is_optional or is_concrete_class_var:
+ cls._type_annotations[key] = args[0]
+ elif is_concrete:
+ cls._type_annotations[key] = value
+ else:
+ # Union types are not supported e.g. Union[int, str] neither are generic types e.g. List[str]
+ raise ImproperlyConfiguredException("Unsupported type annotation")
+ return cls._type_annotations
+
+ @classmethod
+ def _convert_to_type(cls, value: str, expected_type: Type) -> Any:
+ """Convert the value to the expected type.
+
+ Args:
+ value: the value of the cache-control directive
+ expected_type: the expected type of the value
+
+ Returns:
+ The value converted to the expected type
+ """
+ # bool values shouldn't be initiated since they should have been caught earlier in the from_header method and
+ # set with a value of True
+ if expected_type is bool:
+ raise ImproperlyConfiguredException("Invalid cache-control header value")
+ return expected_type(value)
+
+@dataclass
class ETag(Header):
"""An ``etag`` header."""
HEADER_NAME: ClassVar[str] = "etag"
weak: bool = False
- value: Annotated[Optional[str], Field(regex=r"^[ -~]+$")] = None # only ASCII characters
+ value: Optional[str] = None # only ASCII characters
def _get_header_value(self) -> str:
value = f'"{self.value}"'
@@ -377,15 +465,14 @@ def from_header(cls, header_value: str) -> "ETag":
weak, value = match.group(1, 2)
try:
return cls(weak=bool(weak), value=value)
- except ValidationError as exc:
+ except ValueError as exc:
raise ImproperlyConfiguredException from exc
- @validator("value", always=True)
- def validate_value(cls, value: Any, values: Dict[str, Any]) -> Any:
- """Ensure that either value is set or the instance is for ``documentation_only``."""
- if values.get("documentation_only") or value is not None:
- return value
- raise ValueError("value must be set if documentation_only is false")
+ def __post_init__(self) -> None:
+ if self.documentation_only is False and self.value is None:
+ raise ValueError("value must be set if documentation_only is false")
+ if self.value and not PRINTABLE_ASCII_RE.fullmatch(self.value):
+ raise ValueError("value must only contain ASCII printable characters")
class MediaTypeHeader:
diff --git a/litestar/utils/dataclass.py b/litestar/utils/dataclass.py
--- a/litestar/utils/dataclass.py
+++ b/litestar/utils/dataclass.py
@@ -83,7 +83,11 @@ def extract_dataclass_items(
def simple_asdict(
- obj: DataclassProtocol, exclude_none: bool = False, exclude_empty: bool = False, convert_nested: bool = True
+ obj: DataclassProtocol,
+ exclude_none: bool = False,
+ exclude_empty: bool = False,
+ convert_nested: bool = True,
+ exclude: set[str] | None = None,
) -> dict[str, Any]:
"""Convert a dataclass to a dictionary.
@@ -96,12 +100,13 @@ def simple_asdict(
exclude_none: Whether to exclude None values.
exclude_empty: Whether to exclude Empty values.
convert_nested: Whether to recursively convert nested dataclasses.
+ exclude: An iterable of fields to exclude.
Returns:
A dictionary of key/value pairs.
"""
ret = {}
- for field in extract_dataclass_fields(obj, exclude_none, exclude_empty):
+ for field in extract_dataclass_fields(obj, exclude_none, exclude_empty, exclude=exclude):
value = getattr(obj, field.name)
if is_dataclass_instance(value) and convert_nested:
ret[field.name] = simple_asdict(value, exclude_none, exclude_empty)
| diff --git a/tests/unit/test_datastructures/test_headers.py b/tests/unit/test_datastructures/test_headers.py
--- a/tests/unit/test_datastructures/test_headers.py
+++ b/tests/unit/test_datastructures/test_headers.py
@@ -1,7 +1,7 @@
-from typing import TYPE_CHECKING, List, Optional
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, List, Optional, Union
import pytest
-from pydantic import ValidationError
from pytest import FixtureRequest
from litestar import MediaType
@@ -274,7 +274,7 @@ def test_cache_control_from_header_single_value() -> None:
assert header_dict == {"no-cache": True}
[email protected]("invalid_value", ["x=y=z", "x, ", "no-cache=10"])
[email protected]("invalid_value", ["x=y=z", "x, ", "no-cache=10", "invalid-header=10"])
def test_cache_control_from_header_invalid_value(invalid_value: str) -> None:
with pytest.raises(ImproperlyConfiguredException):
CacheControlHeader.from_header(invalid_value)
@@ -286,20 +286,29 @@ def test_cache_control_header_prevent_storing() -> None:
assert header_dict == {"no-store": True}
+def test_cache_control_header_unsupported_type_annotation() -> None:
+ @dataclass
+ class InvalidCacheControlHeader(CacheControlHeader):
+ unsupported_type: Union[int, str] = "foo"
+
+ with pytest.raises(ImproperlyConfiguredException):
+ InvalidCacheControlHeader.from_header("unsupported_type")
+
+
def test_etag_documentation_only() -> None:
assert ETag(documentation_only=True).value is None
def test_etag_no_value() -> None:
- with pytest.raises(ValidationError):
+ with pytest.raises(ValueError):
ETag()
- with pytest.raises(ValidationError):
+ with pytest.raises(ValueError):
ETag(weak=True)
def test_etag_non_ascii() -> None:
- with pytest.raises(ValidationError):
+ with pytest.raises(ValueError):
ETag(value="f↓o")
| Enhancement: Replace Headers with Dataclasses
### Summary
Currently we have some left over pydantic models in the `datastructure.headers` namespace. These should be replaced with dataclasses.
### Basic Example
_No response_
### Drawbacks and Impact
_No response_
### Unresolved questions
_No response_
<!-- POLAR PLEDGE BADGE START -->
<a href="https://polar.sh/litestar-org/litestar/issues/1386">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1386/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1386/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Can I take this on?
Also are there any reference PRs for thsi
> Can I take this on? Also are there any reference PRs for thsi
you're most welcome to. We replaced all the pydantic models with dataclasses, so there are a lot of dataclasses in the codebase (look for @dataclass decorators)
> > Can I take this on? Also are there any reference PRs for thsi
>
> you're most welcome to. We replaced all the pydantic models with dataclasses, so there are a lot of dataclasses in the codebase (look for @dataclass decorators)
Thank you
@JacobCoffee Should I update test cases as well, since a lot of Header classes are using dict method of Pydantic Base model which is not available in dataclasses
> @JacobCoffee Should I update test cases as well, since a lot of Header classes are using dict method of Pydantic Base model which is not available in dataclasses
I am out for a bit dealing with a family issue - @Goldziher ?
> @JacobCoffee Should I update test cases as well, since a lot of Header classes are using dict method of Pydantic Base model which is not available in dataclasses
of course, we have done this everywhere
> > @JacobCoffee Should I update test cases as well, since a lot of Header classes are using dict method of Pydantic Base model which is not available in dataclasses
>
> of course, we have done this everywhere
Would that not affect users calling dict on there headers ?
> > > @JacobCoffee Should I update test cases as well, since a lot of Header classes are using dict method of Pydantic Base model which is not available in dataclasses
> >
> > of course, we have done this everywhere
> Would that not affect users calling dict on there headers ?
Good point.
You can implement a dict method for Headers that proxies to our helper
`simple_asdict`
From https://github.com/litestar-org/litestar/blob/main/litestar/utils/dataclass.py | 2023-07-04T09:16:06 |
litestar-org/litestar | 1,933 | litestar-org__litestar-1933 | [
"4321",
"1234"
] | 7ae05228bd23e24355151fa57eaf8b6a8665ed12 | diff --git a/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py b/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py
--- a/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py
+++ b/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py
@@ -22,8 +22,8 @@ class Author(UUIDBase):
# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
-# additional columns: `created` and `updated`. `created` is a timestamp of when the
-# record created, and `updated` is the last time the record was modified.
+# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
+# record created, and `updated_at` is the last time the record was modified.
class Book(UUIDAuditBase):
title: Mapped[str]
author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id"))
diff --git a/litestar/contrib/sqlalchemy/base.py b/litestar/contrib/sqlalchemy/base.py
--- a/litestar/contrib/sqlalchemy/base.py
+++ b/litestar/contrib/sqlalchemy/base.py
@@ -93,7 +93,7 @@ class UUIDPrimaryKey:
@declared_attr
def _sentinel(cls) -> Mapped[int]:
- return orm_insert_sentinel()
+ return orm_insert_sentinel(name="sa_orm_sentinel")
class BigIntPrimaryKey:
@@ -143,7 +143,7 @@ def to_dict(self, exclude: set[str] | None = None) -> dict[str, Any]:
Returns:
dict[str, Any]: A dict representation of the model
"""
- exclude = {"_sentinel"}.union(self._sa_instance_state.unloaded).union(exclude or []) # type: ignore[attr-defined]
+ exclude = {"sa_orm_sentinel", "_sentinel"}.union(self._sa_instance_state.unloaded).union(exclude or []) # type: ignore[attr-defined]
return {field.name: getattr(self, field.name) for field in self.__table__.columns if field.name not in exclude}
diff --git a/litestar/contrib/sqlalchemy/dto.py b/litestar/contrib/sqlalchemy/dto.py
--- a/litestar/contrib/sqlalchemy/dto.py
+++ b/litestar/contrib/sqlalchemy/dto.py
@@ -225,7 +225,7 @@ def _detect_defaults(elem: ElementType) -> tuple[Any, Any]:
def default_factory(d: Any = sqla_default) -> Any:
return d.arg({})
- elif sqla_default.is_sequence:
+ elif sqla_default.is_sequence or sqla_default.is_sentinel:
# SQLAlchemy sequences represent server side defaults
# so we cannot infer a reasonable default value for
# them on the client side
| diff --git a/tests/unit/test_cli/test_cli.py b/tests/unit/test_cli/test_cli.py
--- a/tests/unit/test_cli/test_cli.py
+++ b/tests/unit/test_cli/test_cli.py
@@ -45,7 +45,7 @@ def test_register_commands_from_entrypoint(mocker: "MockerFixture", runner: "Cli
def custom_group() -> None:
pass
- @custom_group.command() # type: ignore
+ @custom_group.command() # type: ignore[attr-defined]
def custom_command(app: Litestar) -> None:
mock_command_callback()
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
@@ -12,7 +12,7 @@
from sqlalchemy.ext.asyncio import (
AsyncSession,
)
-from sqlalchemy.orm import Mapped, MappedColumn, mapped_column
+from sqlalchemy.orm import InstrumentedAttribute, Mapped, mapped_column
from litestar.contrib.repository.exceptions import ConflictError, RepositoryError
from litestar.contrib.repository.filters import (
@@ -88,8 +88,8 @@ class TheBigIntModel(base.BigIntBase):
sa_instance_mock = MagicMock()
sa_instance_mock.unloaded = unloaded_cols
- assert isinstance(AnotherModel._sentinel, MappedColumn)
- assert isinstance(TheTestModel._sentinel, MappedColumn)
+ assert isinstance(AnotherModel._sentinel, InstrumentedAttribute) # pyright: ignore
+ assert isinstance(TheTestModel._sentinel, InstrumentedAttribute) # pyright: ignore
assert not hasattr(TheBigIntModel, "_sentinel")
model1, model2, model3 = AnotherModel(), TheTestModel(), TheBigIntModel()
monkeypatch.setattr(model1, "_sa_instance_state", sa_instance_mock)
@@ -97,6 +97,9 @@ class TheBigIntModel(base.BigIntBase):
monkeypatch.setattr(model3, "_sa_instance_state", sa_instance_mock)
assert "created_at" not in model1.to_dict(exclude={"created_at"}).keys()
assert "the_extra_col" not in model1.to_dict(exclude={"created_at"}).keys()
+ assert "sa_orm_sentinel" not in model1.to_dict().keys()
+ assert "sa_orm_sentinel" not in model2.to_dict().keys()
+ assert "sa_orm_sentinel" not in model3.to_dict().keys()
assert "_sentinel" not in model1.to_dict().keys()
assert "_sentinel" not in model2.to_dict().keys()
assert "_sentinel" not in model3.to_dict().keys()
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
@@ -9,7 +9,7 @@
import pytest
from sqlalchemy import String
from sqlalchemy.exc import IntegrityError, InvalidRequestError, SQLAlchemyError
-from sqlalchemy.orm import Mapped, MappedColumn, Session, mapped_column
+from sqlalchemy.orm import InstrumentedAttribute, Mapped, Session, mapped_column
from litestar.contrib.repository.exceptions import ConflictError, RepositoryError
from litestar.contrib.repository.filters import (
@@ -87,15 +87,18 @@ class TheBigIntModel(base.BigIntBase):
unloaded_cols = {"the_extra_col"}
sa_instance_mock = MagicMock()
sa_instance_mock.unloaded = unloaded_cols
- assert isinstance(AnotherModel._sentinel, MappedColumn)
- assert isinstance(TheTestModel._sentinel, MappedColumn)
+ assert isinstance(AnotherModel._sentinel, InstrumentedAttribute) # pyright: ignore
+ assert isinstance(TheTestModel._sentinel, InstrumentedAttribute) # pyright: ignore
assert not hasattr(TheBigIntModel, "_sentinel")
model1, model2, model3 = AnotherModel(), TheTestModel(), TheBigIntModel()
monkeypatch.setattr(model1, "_sa_instance_state", sa_instance_mock)
monkeypatch.setattr(model2, "_sa_instance_state", sa_instance_mock)
monkeypatch.setattr(model3, "_sa_instance_state", sa_instance_mock)
- assert "created" not in model1.to_dict(exclude={"created"}).keys()
- assert "the_extra_col" not in model1.to_dict(exclude={"created"}).keys()
+ assert "created_at" not in model1.to_dict(exclude={"created_at"}).keys()
+ assert "the_extra_col" not in model1.to_dict(exclude={"created_at"}).keys()
+ assert "sa_orm_sentinel" not in model1.to_dict().keys()
+ assert "sa_orm_sentinel" not in model2.to_dict().keys()
+ assert "sa_orm_sentinel" not in model3.to_dict().keys()
assert "_sentinel" not in model1.to_dict().keys()
assert "_sentinel" not in model2.to_dict().keys()
assert "_sentinel" not in model3.to_dict().keys()
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-07-10T19:19:36 |
litestar-org/litestar | 1,938 | litestar-org__litestar-1938 | [
"1934",
"4321",
"1934"
] | e02716e6a0844ae90782dcd51277c981f6044c08 | diff --git a/litestar/contrib/prometheus/middleware.py b/litestar/contrib/prometheus/middleware.py
--- a/litestar/contrib/prometheus/middleware.py
+++ b/litestar/contrib/prometheus/middleware.py
@@ -5,6 +5,7 @@
from typing import TYPE_CHECKING, Any, Callable, ClassVar, cast
from litestar.connection.request import Request
+from litestar.enums import ScopeType
from litestar.exceptions import MissingDependencyException
from litestar.middleware.base import AbstractMiddleware
@@ -115,7 +116,7 @@ def _get_default_labels(self, request: Request[Any, Any, Any]) -> dict[str, str
"""
return {
- "method": request.method,
+ "method": request.method if request.scope["type"] == ScopeType.HTTP else request.scope["type"],
"path": request.url.path,
"status_code": 200,
"app_name": self._config.app_name,
| diff --git a/tests/unit/test_contrib/prometheus/test_prometheus_exporter_middleware.py b/tests/unit/test_contrib/prometheus/test_prometheus_exporter_middleware.py
--- a/tests/unit/test_contrib/prometheus/test_prometheus_exporter_middleware.py
+++ b/tests/unit/test_contrib/prometheus/test_prometheus_exporter_middleware.py
@@ -5,7 +5,7 @@
from prometheus_client import REGISTRY
-from litestar import get, post
+from litestar import get, post, websocket_listener
from litestar.contrib.prometheus import PrometheusConfig, PrometheusController, PrometheusMiddleware
from litestar.status_codes import HTTP_200_OK
from litestar.testing import create_test_client
@@ -172,3 +172,26 @@ def test() -> dict:
"""litestar_requests_total{app_name="litestar",method="GET",path="/test",status_code="200"} 1.0 # {trace_id="1234"} 1.0"""
in metrics
)
+
+
+def test_prometheus_with_websocket() -> None:
+ config = create_config()
+
+ @websocket_listener("/test")
+ def test(data: str) -> dict:
+ return {"hello": data}
+
+ with create_test_client([test, PrometheusController], middleware=[config.middleware]) as client:
+ with client.websocket_connect("/test") as websocket:
+ websocket.send_text("litestar")
+ websocket.receive_json()
+
+ metrix_exporter_response = client.get("/metrics")
+
+ assert metrix_exporter_response.status_code == HTTP_200_OK
+ metrics = metrix_exporter_response.content.decode()
+
+ assert (
+ """litestar_requests_total{app_name="litestar",method="websocket",path="/test",status_code="200"} 1.0"""
+ in metrics
+ )
| Bug: Prometheus client causes immediate websocket disconnect
### Description
When using the Prometheus integration, websockets always disconnect immediately after opening the connection.
I've done a bit of digging, and the error arises in `PrometheusMiddleware._get_default_labels` [here](https://github.com/litestar-org/litestar/blob/main/litestar/contrib/prometheus/middleware.py#L107-L122), where `request.method` raises an attribute error for websockets. One possible fix that I've tested locally is to change it to:
```python
"method": (
request.method
if request.scope["type"] == "http"
else request.scope["type"]
),
```
I'd be happy to open a PR for this change or some other fix if someone has a better idea.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, websocket_listener
from litestar.testing import TestClient
from litestar.contrib.prometheus import PrometheusConfig, PrometheusController
config = PrometheusConfig()
@websocket_listener("/")
def websocket_handler(data: str):
return f"Hello, {data}!"
app_with_prometheus = Litestar(
route_handlers=[websocket_handler, PrometheusController],
middleware=[config.middleware]
)
app_without_prometheus = Litestar(route_handlers=[websocket_handler])
def test_app(app_to_test):
with TestClient(app=app_to_test) as test_client:
with test_client.websocket_connect("/") as socket:
socket.send("World")
response = socket.receive()
print(response)
test_app(app_without_prometheus)
test_app(app_with_prometheus)
```
### Steps to reproduce
```bash
1. Run the MCVE
2. Observe the traceback
```
### Screenshots
_No response_
### Logs
```bash
Traceback (most recent call last):
File "/Users/erik/test.py", line 27, in <module>
test_app(app_with_prometheus)
File "/Users/erik/test.py", line 20, in test_app
with test_client.websocket_connect("/") as socket:
File "/Users/erik/Library/Caches/pypoetry/virtualenvs/*****-ocilal_E-py3.11/lib/python3.11/site-packages/litestar/testing/websocket_test_session.py", line 52, in __enter__
message = self.receive(timeout=self.client.timeout.read)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/erik/Library/Caches/pypoetry/virtualenvs/*****-ocilal_E-py3.11/lib/python3.11/site-packages/litestar/testing/websocket_test_session.py", line 195, in receive
raise WebSocketDisconnect(
litestar.exceptions.websocket_exceptions.WebSocketDisconnect: KeyError('method')
```
### Litestar Version
2.0.0b2
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
## Funding
* You can sponsor this specific effort via a [Polar.sh](https://polar.sh) pledge below
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/1934">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1934/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1934/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
Bug: Prometheus client causes immediate websocket disconnect
### Description
When using the Prometheus integration, websockets always disconnect immediately after opening the connection.
I've done a bit of digging, and the error arises in `PrometheusMiddleware._get_default_labels` [here](https://github.com/litestar-org/litestar/blob/main/litestar/contrib/prometheus/middleware.py#L107-L122), where `request.method` raises an attribute error for websockets. One possible fix that I've tested locally is to change it to:
```python
"method": (
request.method
if request.scope["type"] == "http"
else request.scope["type"]
),
```
I'd be happy to open a PR for this change or some other fix if someone has a better idea.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, websocket_listener
from litestar.testing import TestClient
from litestar.contrib.prometheus import PrometheusConfig, PrometheusController
config = PrometheusConfig()
@websocket_listener("/")
def websocket_handler(data: str):
return f"Hello, {data}!"
app_with_prometheus = Litestar(
route_handlers=[websocket_handler, PrometheusController],
middleware=[config.middleware]
)
app_without_prometheus = Litestar(route_handlers=[websocket_handler])
def test_app(app_to_test):
with TestClient(app=app_to_test) as test_client:
with test_client.websocket_connect("/") as socket:
socket.send("World")
response = socket.receive()
print(response)
test_app(app_without_prometheus)
test_app(app_with_prometheus)
```
### Steps to reproduce
```bash
1. Run the MCVE
2. Observe the traceback
```
### Screenshots
_No response_
### Logs
```bash
Traceback (most recent call last):
File "/Users/erik/test.py", line 27, in <module>
test_app(app_with_prometheus)
File "/Users/erik/test.py", line 20, in test_app
with test_client.websocket_connect("/") as socket:
File "/Users/erik/Library/Caches/pypoetry/virtualenvs/*****-ocilal_E-py3.11/lib/python3.11/site-packages/litestar/testing/websocket_test_session.py", line 52, in __enter__
message = self.receive(timeout=self.client.timeout.read)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/erik/Library/Caches/pypoetry/virtualenvs/*****-ocilal_E-py3.11/lib/python3.11/site-packages/litestar/testing/websocket_test_session.py", line 195, in receive
raise WebSocketDisconnect(
litestar.exceptions.websocket_exceptions.WebSocketDisconnect: KeyError('method')
```
### Litestar Version
2.0.0b2
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
## Funding
* You can sponsor this specific effort via a [Polar.sh](https://polar.sh) pledge below
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/1934">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1934/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1934/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| @JacobCoffee can you try to reproduce this?
`"method": request.method if request.scope["type"] == "http" else request.scope["type"],` does indeed solve this but I am not certain it is the right place to fix. Investigating...
@erik-hasse would you like to open a PR with your fix? This will be okay.
@JacobCoffee can you try to reproduce this?
`"method": request.method if request.scope["type"] == "http" else request.scope["type"],` does indeed solve this but I am not certain it is the right place to fix. Investigating...
@erik-hasse would you like to open a PR with your fix? This will be okay. | 2023-07-11T21:24:40 |
litestar-org/litestar | 1,946 | litestar-org__litestar-1946 | [
"4321",
"1234"
] | 240a54a4f460a98ba0cea6b4005dfb46db163a88 | diff --git a/litestar/_openapi/schema_generation/schema.py b/litestar/_openapi/schema_generation/schema.py
--- a/litestar/_openapi/schema_generation/schema.py
+++ b/litestar/_openapi/schema_generation/schema.py
@@ -33,6 +33,7 @@
from uuid import UUID
from _decimal import Decimal
+from msgspec.structs import FieldInfo
from msgspec.structs import fields as msgspec_struct_fields
from typing_extensions import Annotated, NotRequired, Required, get_args, get_type_hints
@@ -669,12 +670,16 @@ def for_struct_class(self, annotation: type[Struct], dto_for: ForType | None) ->
Returns:
A schema instance.
"""
+
+ def _is_field_required(field: FieldInfo) -> bool:
+ return field.required or field.default_factory is Empty
+
return Schema(
required=sorted(
[
field.encode_name
for field in msgspec_struct_fields(annotation)
- if field.required and not is_optional_union(field.type)
+ if _is_field_required(field=field) and not is_optional_union(field.type)
]
),
properties={
| diff --git a/tests/unit/test_dto/test_factory/test_integration.py b/tests/unit/test_dto/test_factory/test_integration.py
--- a/tests/unit/test_dto/test_factory/test_integration.py
+++ b/tests/unit/test_dto/test_factory/test_integration.py
@@ -5,10 +5,16 @@
from typing import TYPE_CHECKING, Dict, Optional, Sequence
from unittest.mock import MagicMock
+import msgspec
import pytest
+from msgspec import Struct
+from pydantic import BaseModel
from typing_extensions import Annotated
-from litestar import patch, post
+from litestar import Litestar, patch, post
+from litestar.connection.request import Request
+from litestar.contrib.msgspec import MsgspecDTO
+from litestar.contrib.pydantic import PydanticDTO
from litestar.datastructures import UploadFile
from litestar.dto.factory import DTOConfig, DTOData, dto_field
from litestar.dto.factory.stdlib.dataclass import DataclassDTO
@@ -681,3 +687,112 @@ def handler() -> Response[List[User]]:
with TestClient(app=module.app) as client:
response = client.get("/")
assert response.json() == [{"name": "John"}, {"name": "Jane"}]
+
+
+def test_schema_required_fields_with_msgspec_dto() -> None:
+ class MsgspecUser(Struct):
+ age: int
+ name: str
+
+ class UserDTO(MsgspecDTO[MsgspecUser]):
+ pass
+
+ @post(dto=UserDTO, return_dto=None, signature_namespace={"MsgspecUser": MsgspecUser})
+ def handler(data: MsgspecUser, request: Request) -> dict:
+ schema = request.app.openapi_schema
+ return schema.to_schema()
+
+ app = Litestar(route_handlers=[handler])
+ with TestClient(app=app) as client:
+ data = MsgspecUser(name="A", age=10)
+ headers = {}
+ headers["Content-Type"] = "application/json; charset=utf-8"
+ received = client.post(
+ "/",
+ content=msgspec.json.encode(data),
+ headers=headers,
+ )
+ required = list(received.json()["components"]["schemas"].values())[0]["required"]
+ assert len(required) == 2
+
+
+def test_schema_required_fields_with_pydantic_dto() -> None:
+ class PydanticUser(BaseModel):
+ age: int
+ name: str
+
+ class UserDTO(PydanticDTO[PydanticUser]):
+ pass
+
+ @post(dto=UserDTO, return_dto=None, signature_namespace={"PydanticUser": PydanticUser})
+ def handler(data: PydanticUser, request: Request) -> dict:
+ schema = request.app.openapi_schema
+ return schema.to_schema()
+
+ app = Litestar(route_handlers=[handler])
+ with TestClient(app=app) as client:
+ data = PydanticUser(name="A", age=10)
+ headers = {}
+ headers["Content-Type"] = "application/json; charset=utf-8"
+ received = client.post(
+ "/",
+ content=data.json(),
+ headers=headers,
+ )
+ required = list(received.json()["components"]["schemas"].values())[0]["required"]
+ assert len(required) == 2
+
+
+def test_schema_required_fields_with_dataclass_dto() -> None:
+ @dataclass
+ class DataclassUser:
+ age: int
+ name: str
+
+ class UserDTO(DataclassDTO[DataclassUser]):
+ pass
+
+ @post(dto=UserDTO, return_dto=None, signature_namespace={"DataclassUser": DataclassUser})
+ def handler(data: DataclassUser, request: Request) -> dict:
+ schema = request.app.openapi_schema
+ return schema.to_schema()
+
+ app = Litestar(route_handlers=[handler])
+ with TestClient(app=app) as client:
+ data = DataclassUser(name="A", age=10)
+ headers = {}
+ headers["Content-Type"] = "application/json; charset=utf-8"
+ received = client.post(
+ "/",
+ content=msgspec.json.encode(data),
+ headers=headers,
+ )
+ required = list(received.json()["components"]["schemas"].values())[0]["required"]
+ assert len(required) == 2
+
+
+def test_schema_required_fields_with_msgspec_dto_and_default_fields() -> None:
+ class MsgspecUser(Struct):
+ age: int
+ name: str = "A"
+
+ class UserDTO(MsgspecDTO[MsgspecUser]):
+ pass
+
+ @post(dto=UserDTO, return_dto=None, signature_namespace={"MsgspecUser": MsgspecUser})
+ def handler(data: MsgspecUser, request: Request) -> dict:
+ schema = request.app.openapi_schema
+ return schema.to_schema()
+
+ app = Litestar(route_handlers=[handler])
+ with TestClient(app=app) as client:
+ data = MsgspecUser(name="A", age=10)
+ headers = {}
+ headers["Content-Type"] = "application/json; charset=utf-8"
+ received = client.post(
+ "/",
+ content=msgspec.json.encode(data),
+ headers=headers,
+ )
+ required = list(received.json()["components"]["schemas"].values())[0]["required"]
+ assert required == ["age"]
diff --git a/tests/unit/test_openapi/test_schema.py b/tests/unit/test_openapi/test_schema.py
--- a/tests/unit/test_openapi/test_schema.py
+++ b/tests/unit/test_openapi/test_schema.py
@@ -254,6 +254,7 @@ class Lookup(msgspec.Struct):
assert schema.properties["id"].description == "description" # type: ignore
assert schema.properties["id"].title == "title" # type: ignore
assert schema.properties["id"].max_length == 16 # type: ignore
+ assert schema.required == ["id"]
def test_create_schema_for_pydantic_field() -> None:
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-07-13T17:14:07 |
litestar-org/litestar | 1,961 | litestar-org__litestar-1961 | [
"1960"
] | b32088f6618dd6b2fa8202da9883d5225b83bffe | diff --git a/litestar/contrib/jwt/jwt_token.py b/litestar/contrib/jwt/jwt_token.py
--- a/litestar/contrib/jwt/jwt_token.py
+++ b/litestar/contrib/jwt/jwt_token.py
@@ -3,7 +3,7 @@
import dataclasses
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
-from typing import TYPE_CHECKING, Any, cast
+from typing import TYPE_CHECKING, Any
from jose import JWSError, JWTError, jwt
@@ -112,11 +112,8 @@ def encode(self, secret: str, algorithm: str) -> str:
ImproperlyConfiguredException: If encoding fails.
"""
try:
- return cast(
- "str",
- jwt.encode(
- claims={k: v for k, v in asdict(self).items() if v is not None}, key=secret, algorithm=algorithm
- ),
+ return jwt.encode(
+ claims={k: v for k, v in asdict(self).items() if v is not None}, key=secret, algorithm=algorithm
)
except (JWTError, JWSError) as e:
raise ImproperlyConfiguredException("Failed to encode token") from e
| Local run of `mypy` produces unexpected results
### Description
Mypy produces unexpected failures locally, but the CI job passes: https://github.com/litestar-org/litestar/actions/runs/5561581892/jobs/10159348023?pr=1959
I think that this happens because `.pre-commit-config` and local mypy settings are not in sync.
I will fix that.
### URL to code causing the issue
_No response_
### MCVE
_No response_
### Steps to reproduce
```bash
1. `poetry install --with lint -E full`
2. `poetry run mypy litestar`
```
### Screenshots
_No response_
### Logs
```bash
» mypy litestar
litestar/contrib/jwt/jwt_token.py:115: error: Redundant cast to "str" [redundant-cast]
litestar/_signature/models/attrs_signature_model.py:43: error: Skipping analyzing "pytimeparse.timeparse": module is installed, but missing library stubs or py.typed marker [import]
litestar/_signature/models/attrs_signature_model.py:43: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
litestar/middleware/compression.py:29: error: Skipping analyzing "brotli": module is installed, but missing library stubs or py.typed marker [import]
litestar/contrib/mako.py:19: error: Skipping analyzing "mako": module is installed, but missing library stubs or py.typed marker [import]
litestar/contrib/mako.py:24: error: Skipping analyzing "mako.exceptions": module is installed, but missing library stubs or py.typed marker [import]
litestar/contrib/mako.py:25: error: Skipping analyzing "mako.lookup": module is installed, but missing library stubs or py.typed marker [import]
litestar/contrib/mako.py:28: error: Skipping analyzing "mako.template": module is installed, but missing library stubs or py.typed marker [import]
litestar/cli/commands/schema.py:5: error: Skipping analyzing "jsbeautifier": module is installed, but missing library stubs or py.typed marker [import]
Found 8 errors in 5 files (checked 303 source files)
```
### Litestar Version
`main`
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/1960">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1960/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1960/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-07-15T10:33:01 |
||
litestar-org/litestar | 1,980 | litestar-org__litestar-1980 | [
"4321",
"1234"
] | d18627026a40da8c869e61287e44a0779b2fc01f | diff --git a/litestar/_openapi/path_item.py b/litestar/_openapi/path_item.py
--- a/litestar/_openapi/path_item.py
+++ b/litestar/_openapi/path_item.py
@@ -88,7 +88,7 @@ def create_path_item(
operation_ids: list[str] = []
request_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)
- response_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=False)
+ response_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)
for http_method, handler_tuple in route.route_handler_map.items():
route_handler, _ = handler_tuple
diff --git a/litestar/contrib/pydantic/pydantic_init_plugin.py b/litestar/contrib/pydantic/pydantic_init_plugin.py
--- a/litestar/contrib/pydantic/pydantic_init_plugin.py
+++ b/litestar/contrib/pydantic/pydantic_init_plugin.py
@@ -102,16 +102,20 @@ def _create_pydantic_v1_encoders() -> dict[Any, Callable[[Any], Any]]: # pragma
@staticmethod
def _create_pydantic_v2_encoders() -> dict[Any, Callable[[Any], Any]]:
- from pydantic_extra_types import color
-
- return {
+ try:
+ from pydantic_extra_types import color
+ except ImportError:
+ color = None # type: ignore[assignment]
+ encoders: dict[Any, Callable[[Any], Any]] = {
pydantic.BaseModel: lambda model: model.model_dump(mode="json"),
- color.Color: str,
pydantic.types.SecretStr: lambda val: "**********" if val else "",
pydantic.types.SecretBytes: lambda val: "**********" if val else "",
}
+ if color:
+ encoders[color.Color] = str
+ return encoders
def on_app_init(self, app_config: AppConfig) -> AppConfig:
- app_config.type_encoders = {**(app_config.type_encoders or {}), **self.encoders()}
- app_config.type_decoders = [*(app_config.type_decoders or []), *self.decoders()]
+ app_config.type_encoders = {**self.encoders(), **(app_config.type_encoders or {})}
+ app_config.type_decoders = [*self.decoders(), *(app_config.type_decoders or [])]
return app_config
| diff --git a/tests/unit/test_openapi/test_config.py b/tests/unit/test_openapi/test_config.py
--- a/tests/unit/test_openapi/test_config.py
+++ b/tests/unit/test_openapi/test_config.py
@@ -69,9 +69,9 @@ def handler(data: RequestWithAlias) -> ResponseWithAlias:
"title": "RequestWithAlias",
}
assert schemas["ResponseWithAlias"] == {
- "properties": {"first": {"type": "string"}},
+ "properties": {"second": {"type": "string"}},
"type": "object",
- "required": ["first"],
+ "required": ["second"],
"title": "ResponseWithAlias",
}
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-07-16T21:13:59 |
litestar-org/litestar | 1,999 | litestar-org__litestar-1999 | [
"1996"
] | 702037026719c2c7af65735f04c70fd845db403a | diff --git a/litestar/_openapi/schema_generation/examples.py b/litestar/_openapi/schema_generation/examples.py
--- a/litestar/_openapi/schema_generation/examples.py
+++ b/litestar/_openapi/schema_generation/examples.py
@@ -34,7 +34,9 @@ def _normalize_example_value(value: Any) -> Any:
if isinstance(value, Enum):
value = value.value
if is_pydantic_model_instance(value):
- value = value.dict()
+ from litestar.contrib.pydantic import _model_dump
+
+ value = _model_dump(value)
if isinstance(value, (list, set)):
value = [_normalize_example_value(v) for v in value]
if isinstance(value, dict):
diff --git a/litestar/contrib/pydantic/__init__.py b/litestar/contrib/pydantic/__init__.py
--- a/litestar/contrib/pydantic/__init__.py
+++ b/litestar/contrib/pydantic/__init__.py
@@ -1,5 +1,24 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
from .pydantic_dto_factory import PydanticDTO
from .pydantic_init_plugin import PydanticInitPlugin
from .pydantic_schema_plugin import PydanticSchemaPlugin
+if TYPE_CHECKING:
+ import pydantic
+
__all__ = ("PydanticDTO", "PydanticInitPlugin", "PydanticSchemaPlugin")
+
+
+def _model_dump(model: pydantic.BaseModel, *, by_alias: bool = False) -> dict[str, Any]:
+ return (
+ model.model_dump(mode="json", by_alias=by_alias)
+ if hasattr(model, "model_dump")
+ else model.dict(by_alias=by_alias)
+ )
+
+
+def _model_dump_json(model: pydantic.BaseModel) -> str:
+ return model.model_dump_json() if hasattr(model, "model_dump_json") else model.json()
diff --git a/litestar/contrib/pydantic/pydantic_init_plugin.py b/litestar/contrib/pydantic/pydantic_init_plugin.py
--- a/litestar/contrib/pydantic/pydantic_init_plugin.py
+++ b/litestar/contrib/pydantic/pydantic_init_plugin.py
@@ -90,9 +90,7 @@ def decoders(cls) -> list[tuple[Callable[[Any], bool], Callable[[Any, Any], Any]
@staticmethod
def _create_pydantic_v1_encoders() -> dict[Any, Callable[[Any], Any]]: # pragma: no cover
return {
- pydantic.BaseModel: lambda model: {
- k: v.decode() if isinstance(v, bytes) else v for k, v in model.dict().items()
- },
+ pydantic.BaseModel: lambda model: model.dict(),
pydantic.SecretField: str,
pydantic.StrictBool: int,
pydantic.color.Color: str, # pyright: ignore
| diff --git a/litestar/testing/request_factory.py b/litestar/testing/request_factory.py
--- a/litestar/testing/request_factory.py
+++ b/litestar/testing/request_factory.py
@@ -266,7 +266,9 @@ def _create_request_with_data(
data = attrs_as_dict(data) # type: ignore[arg-type]
elif is_pydantic_model_instance(data):
- data = data.model_dump(mode="json") if hasattr(data, "model_dump") else data.dict()
+ from litestar.contrib.pydantic import _model_dump
+
+ data = _model_dump(data)
if request_media_type == RequestEncodingType.JSON:
encoding_headers, stream = httpx_encode_json(data)
diff --git a/tests/e2e/test_routing/test_path_resolution.py b/tests/e2e/test_routing/test_path_resolution.py
--- a/tests/e2e/test_routing/test_path_resolution.py
+++ b/tests/e2e/test_routing/test_path_resolution.py
@@ -4,6 +4,7 @@
import pytest
from litestar import Controller, MediaType, delete, get, post
+from litestar.contrib.pydantic import _model_dump
from litestar.status_codes import (
HTTP_200_OK,
HTTP_204_NO_CONTENT,
@@ -105,7 +106,7 @@ def test_method(self) -> PydanticPerson:
with create_test_client([MyController, delete_handler] if delete_handler else MyController) as client:
response = client.get(decorator_path or test_path)
assert response.status_code == HTTP_200_OK, response.json()
- assert response.json() == person_instance.dict()
+ assert response.json() == _model_dump(person_instance)
if delete_handler:
delete_response = client.delete("/")
assert delete_response.status_code == HTTP_204_NO_CONTENT
diff --git a/tests/unit/test_contrib/test_jwt/test_auth.py b/tests/unit/test_contrib/test_jwt/test_auth.py
--- a/tests/unit/test_contrib/test_jwt/test_auth.py
+++ b/tests/unit/test_contrib/test_jwt/test_auth.py
@@ -10,6 +10,7 @@
from litestar import Litestar, Request, Response, get
from litestar.contrib.jwt import JWTAuth, JWTCookieAuth, OAuth2PasswordBearerAuth, Token
+from litestar.contrib.pydantic import _model_dump
from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_401_UNAUTHORIZED
from litestar.stores.memory import MemoryStore
from litestar.testing import create_test_client
@@ -72,7 +73,7 @@ async def retrieve_user_handler(token: Token, _: "ASGIConnection") -> Any:
@get("/my-endpoint", middleware=[jwt_auth.middleware])
def my_handler(request: Request["User", Token, Any]) -> None:
assert request.user
- assert request.user.dict() == user.dict()
+ assert _model_dump(request.user) == _model_dump(user)
assert request.auth.sub == str(user.id)
@get("/login")
@@ -174,7 +175,7 @@ async def retrieve_user_handler(token: Token, connection: Any) -> Any:
@get("/my-endpoint", middleware=[jwt_auth.middleware])
def my_handler(request: Request["User", Token, Any]) -> None:
assert request.user
- assert request.user.dict() == user.dict()
+ assert _model_dump(request.user) == _model_dump(user)
assert request.auth.sub == str(user.id)
@get("/login")
@@ -403,7 +404,7 @@ async def retrieve_user_handler(token: Token, connection: "ASGIConnection[Any, A
retrieve_user_handler=retrieve_user_handler,
token_secret="abc1234",
exclude=["/"],
- type_encoders={BaseModel: lambda m: m.dict(by_alias=True)},
+ type_encoders={BaseModel: lambda m: _model_dump(m, by_alias=True)},
)
@get()
diff --git a/tests/unit/test_contrib/test_pydantic/test_plugin_serialization.py b/tests/unit/test_contrib/test_pydantic/test_plugin_serialization.py
--- a/tests/unit/test_contrib/test_pydantic/test_plugin_serialization.py
+++ b/tests/unit/test_contrib/test_pydantic/test_plugin_serialization.py
@@ -26,6 +26,7 @@
constr,
)
+from litestar.contrib.pydantic import _model_dump, _model_dump_json
from litestar.contrib.pydantic.pydantic_init_plugin import PydanticInitPlugin
if VERSION.startswith("1"):
@@ -170,11 +171,12 @@ def test_default_serializer(model: BaseModel, attribute_name: str, expected: Any
def test_serialization_of_model_instance(model: BaseModel) -> None:
- assert serializer(model) == model.model_dump(mode="json") if hasattr(model, "model_dump") else model.dict()
+ assert serializer(getattr(model, "conbytes")) == b"hello"
+ assert serializer(model) == _model_dump(model)
def test_pydantic_json_compatibility(model: BaseModel) -> None:
- raw = model.model_dump_json() if hasattr(model, "model_dump_json") else model.json()
+ raw = _model_dump_json(model)
encoded_json = encode_json(model, serializer=get_serializer(PydanticInitPlugin.encoders()))
raw_result = json.loads(raw)
@@ -202,15 +204,13 @@ def test_decode_json_raises_serialization_exception(model: BaseModel, decoder: A
def test_decode_json_typed(model: BaseModel) -> None:
- dumped_model = model.model_dump_json() if hasattr(model, "model_dump_json") else model.json()
+ dumped_model = _model_dump_json(model)
decoded_model = decode_json(value=dumped_model, target_type=Model, type_decoders=PydanticInitPlugin.decoders())
- assert (
- decoded_model.model_dump_json() if hasattr(decoded_model, "model_dump_json") else decoded_model.json()
- ) == dumped_model
+ assert _model_dump_json(decoded_model) == dumped_model
def test_decode_msgpack_typed(model: BaseModel) -> None:
- model_json = model.json()
+ model_json = _model_dump_json(model)
assert (
decode_msgpack(
encode_msgpack(model, serializer=get_serializer(PydanticInitPlugin.encoders())),
diff --git a/tests/unit/test_controller.py b/tests/unit/test_controller.py
--- a/tests/unit/test_controller.py
+++ b/tests/unit/test_controller.py
@@ -16,6 +16,7 @@
websocket,
)
from litestar.connection import WebSocket
+from litestar.contrib.pydantic import _model_dump
from litestar.exceptions import ImproperlyConfiguredException
from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT
from litestar.testing import create_test_client
@@ -59,7 +60,8 @@ def test_method(self) -> return_annotation:
response = client.request(http_method, test_path)
assert response.status_code == expected_status_code
if return_value:
- assert response.json() == return_value.dict() if isinstance(return_value, BaseModel) else return_value
+ if isinstance(return_value, BaseModel):
+ assert response.json() == _model_dump(return_value)
def test_controller_with_websocket_handler() -> None:
diff --git a/tests/unit/test_dto/test_factory/test_integration.py b/tests/unit/test_dto/test_factory/test_integration.py
--- a/tests/unit/test_dto/test_factory/test_integration.py
+++ b/tests/unit/test_dto/test_factory/test_integration.py
@@ -13,7 +13,7 @@
from litestar import Litestar, patch, post
from litestar.connection.request import Request
-from litestar.contrib.pydantic import PydanticDTO
+from litestar.contrib.pydantic import PydanticDTO, _model_dump_json
from litestar.datastructures import UploadFile
from litestar.dto import DataclassDTO, DTOConfig, DTOData, MsgspecDTO, dto_field
from litestar.dto.types import RenameStrategy
@@ -732,7 +732,7 @@ def handler(data: PydanticUser, request: Request) -> dict:
headers = {"Content-Type": "application/json; charset=utf-8"}
received = client.post(
"/",
- content=data.json(),
+ content=_model_dump_json(data),
headers=headers,
)
required = list(received.json()["components"]["schemas"].values())[0]["required"]
diff --git a/tests/unit/test_handlers/test_http_handlers/test_to_response.py b/tests/unit/test_handlers/test_http_handlers/test_to_response.py
--- a/tests/unit/test_handlers/test_http_handlers/test_to_response.py
+++ b/tests/unit/test_handlers/test_http_handlers/test_to_response.py
@@ -13,6 +13,7 @@
from litestar._signature import SignatureModel
from litestar.background_tasks import BackgroundTask
from litestar.contrib.jinja import JinjaTemplateEngine
+from litestar.contrib.pydantic import _model_dump
from litestar.datastructures import Cookie, ResponseHeader
from litestar.response.base import ASGIResponse
from litestar.response.file import ASGIFileResponse, File
@@ -101,7 +102,7 @@ async def test_function(data: PydanticPerson) -> PydanticPerson:
app=Litestar(route_handlers=[test_function]),
request=RequestFactory().get(route_handler=test_function),
)
- assert loads(response.body) == person_instance.dict() # type: ignore
+ assert loads(response.body) == _model_dump(person_instance) # type: ignore
async def test_to_response_returning_litestar_response() -> None:
diff --git a/tests/unit/test_kwargs/test_json_data.py b/tests/unit/test_kwargs/test_json_data.py
--- a/tests/unit/test_kwargs/test_json_data.py
+++ b/tests/unit/test_kwargs/test_json_data.py
@@ -1,4 +1,5 @@
from litestar import post
+from litestar.contrib.pydantic import _model_dump
from litestar.params import Body
from litestar.status_codes import HTTP_201_CREATED
from litestar.testing import create_test_client
@@ -12,7 +13,7 @@ def test_method(data: Form = Body()) -> None:
assert isinstance(data, Form)
with create_test_client(test_method) as client:
- response = client.post("/test", json=Form(name="Moishe Zuchmir", age=30, programmer=True).dict())
+ response = client.post("/test", json=_model_dump(Form(name="Moishe Zuchmir", age=30, programmer=True)))
assert response.status_code == HTTP_201_CREATED
diff --git a/tests/unit/test_kwargs/test_multipart_data.py b/tests/unit/test_kwargs/test_multipart_data.py
--- a/tests/unit/test_kwargs/test_multipart_data.py
+++ b/tests/unit/test_kwargs/test_multipart_data.py
@@ -10,6 +10,7 @@
from pydantic import BaseConfig, BaseModel
from litestar import Request, post
+from litestar.contrib.pydantic import _model_dump, _model_dump_json
from litestar.datastructures.upload_file import UploadFile
from litestar.enums import RequestEncodingType
from litestar.params import Body
@@ -89,7 +90,7 @@ def test_request_body_multi_part(t_type: Type[Any]) -> None:
body = Body(media_type=RequestEncodingType.MULTI_PART)
test_path = "/test"
- data = Form(name="Moishe Zuchmir", age=30, programmer=True).dict()
+ data = _model_dump(Form(name="Moishe Zuchmir", age=30, programmer=True))
@post(path=test_path)
def test_method(data: t_type = body) -> None: # type: ignore
@@ -120,7 +121,7 @@ async def test_method(data: MultiPartFormWithMixedFields = Body(media_type=Reque
response = client.post(
"/form",
files={"image": ("image.png", b"data")},
- data={"tags": ["1", "2", "3"], "profile": person.json()},
+ data={"tags": ["1", "2", "3"], "profile": _model_dump_json(person)},
)
assert response.status_code == HTTP_201_CREATED
diff --git a/tests/unit/test_kwargs/test_reserved_kwargs_injection.py b/tests/unit/test_kwargs/test_reserved_kwargs_injection.py
--- a/tests/unit/test_kwargs/test_reserved_kwargs_injection.py
+++ b/tests/unit/test_kwargs/test_reserved_kwargs_injection.py
@@ -17,6 +17,7 @@
post,
put,
)
+from litestar.contrib.pydantic import _model_dump
from litestar.datastructures.state import ImmutableState, State
from litestar.exceptions import ImproperlyConfiguredException
from litestar.status_codes import (
@@ -100,7 +101,7 @@ def test_method(self, data: PydanticPerson) -> None:
assert data == person_instance
with create_test_client(MyController) as client:
- response = client.request(http_method, test_path, json=person_instance.dict())
+ response = client.request(http_method, test_path, json=_model_dump(person_instance))
assert response.status_code == expected_status_code
@@ -126,7 +127,7 @@ def test_method(self, data: List[PydanticPerson]) -> None:
assert data == people
with create_test_client(MyController) as client:
- response = client.request(http_method, test_path, json=[p.dict() for p in people])
+ response = client.request(http_method, test_path, json=[_model_dump(p) for p in people])
assert response.status_code == expected_status_code
diff --git a/tests/unit/test_kwargs/test_url_encoded_data.py b/tests/unit/test_kwargs/test_url_encoded_data.py
--- a/tests/unit/test_kwargs/test_url_encoded_data.py
+++ b/tests/unit/test_kwargs/test_url_encoded_data.py
@@ -1,6 +1,7 @@
from typing import Optional
from litestar import post
+from litestar.contrib.pydantic import _model_dump
from litestar.enums import RequestEncodingType
from litestar.params import Body
from litestar.status_codes import HTTP_201_CREATED
@@ -15,7 +16,7 @@ def test_method(data: Form = Body(media_type=RequestEncodingType.URL_ENCODED)) -
assert isinstance(data, Form)
with create_test_client(test_method) as client:
- response = client.post("/test", data=Form(name="Moishe Zuchmir", age=30, programmer=True).dict())
+ response = client.post("/test", data=_model_dump(Form(name="Moishe Zuchmir", age=30, programmer=True)))
assert response.status_code == HTTP_201_CREATED
diff --git a/tests/unit/test_response/test_serialization.py b/tests/unit/test_response/test_serialization.py
--- a/tests/unit/test_response/test_serialization.py
+++ b/tests/unit/test_response/test_serialization.py
@@ -8,7 +8,7 @@
from pydantic import SecretStr
from litestar import MediaType, Response
-from litestar.contrib.pydantic import PydanticInitPlugin
+from litestar.contrib.pydantic import PydanticInitPlugin, _model_dump
from litestar.exceptions import ImproperlyConfiguredException
from litestar.serialization import get_serializer
from tests import (
@@ -37,9 +37,9 @@ class _TestEnum(enum.Enum):
[person, PydanticPerson],
[{"key": 123}, Dict[str, int]],
[[{"key": 123}], List[Dict[str, int]]],
- [VanillaDataClassPerson(**person.dict()), VanillaDataClassPerson],
- [PydanticDataClassPerson(**person.dict()), PydanticDataClassPerson],
- [MsgSpecStructPerson(**person.dict()), MsgSpecStructPerson],
+ [VanillaDataClassPerson(**_model_dump(person)), VanillaDataClassPerson],
+ [PydanticDataClassPerson(**_model_dump(person)), PydanticDataClassPerson],
+ [MsgSpecStructPerson(**_model_dump(person)), MsgSpecStructPerson],
[{"enum": _TestEnum.A}, Dict[str, _TestEnum]],
[{"secret": secret}, Dict[str, SecretStr]],
[{"pure_path": pure_path}, Dict[str, PurePath]],
diff --git a/tests/unit/test_security/test_session_auth.py b/tests/unit/test_security/test_session_auth.py
--- a/tests/unit/test_security/test_session_auth.py
+++ b/tests/unit/test_security/test_session_auth.py
@@ -9,6 +9,7 @@
)
from litestar import Litestar, Request, delete, get, post
+from litestar.contrib.pydantic import _model_dump
from litestar.middleware.session.server_side import (
ServerSideSessionBackend,
ServerSideSessionConfig,
@@ -38,7 +39,7 @@ def test_authentication(session_backend_config_memory: ServerSideSessionConfig)
@post("/login")
def login_handler(request: "Request[Any, Any, Any]", data: User) -> None:
- request.set_session(data.dict())
+ request.set_session(_model_dump(data))
@delete("/user/{user_id:str}")
def delete_user_handler(request: "Request[User, Any, Any]") -> None:
diff --git a/tests/unit/test_testing/test_request_factory.py b/tests/unit/test_testing/test_request_factory.py
--- a/tests/unit/test_testing/test_request_factory.py
+++ b/tests/unit/test_testing/test_request_factory.py
@@ -5,6 +5,7 @@
from pydantic import BaseModel
from litestar import HttpMethod, Litestar, get
+from litestar.contrib.pydantic import _model_dump
from litestar.datastructures import Cookie, MultiDict
from litestar.enums import ParamType, RequestEncodingType
from litestar.testing import RequestFactory
@@ -65,7 +66,7 @@ def test_request_factory_build_headers() -> None:
@pytest.mark.parametrize("data_cls", [PydanticPerson, VanillaDataClassPerson, AttrsPerson, MsgSpecStructPerson])
async def test_request_factory_create_with_data(data_cls: DataContainerType) -> None:
- person = PydanticPersonFactory.build().dict()
+ person = _model_dump(PydanticPersonFactory.build())
request = RequestFactory()._create_request_with_data(
HttpMethod.POST,
"/",
@@ -78,7 +79,7 @@ async def test_request_factory_create_with_data(data_cls: DataContainerType) ->
@pytest.mark.parametrize(
"request_media_type, verify_data",
[
- [RequestEncodingType.JSON, lambda data: json.loads(data) == pet.dict()],
+ [RequestEncodingType.JSON, lambda data: json.loads(data) == _model_dump(pet)],
[RequestEncodingType.MULTI_PART, lambda data: "Content-Disposition" in data],
[
RequestEncodingType.URL_ENCODED,
@@ -92,7 +93,7 @@ async def test_request_factory_create_with_content_type(
request = RequestFactory()._create_request_with_data(
HttpMethod.POST,
"/",
- data=pet.dict(),
+ data=_model_dump(pet),
request_media_type=request_media_type,
)
assert request.headers["Content-Type"].startswith(request_media_type.value)
@@ -196,4 +197,4 @@ async def test_request_factory_post_put_patch(factory: Callable, method: HttpMet
assert len(request.headers.keys()) == 3
assert request.headers.get("header1") == "value1"
body = await request.body()
- assert json.loads(body) == pet.dict()
+ assert json.loads(body) == _model_dump(pet)
| Lots of `pydantic` warnings: `.dict()` and `.json()` are deprecated
### Description
You can find lots of `DeprecationWarning` instances here: https://github.com/litestar-org/litestar/actions/runs/5578844701/jobs/10193581342
I propose to add a compat layer to call `.model_dump` and `.model_dump_json` on v2 and `.dict` and `.json` on v1, since they are both supported right now.
### URL to code causing the issue
_No response_
### MCVE
_No response_
### Steps to reproduce
_No response_
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
`main`
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/1996">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1996/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1996/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Sounds good to me | 2023-07-18T06:54:46 |
litestar-org/litestar | 2,017 | litestar-org__litestar-2017 | [
"1830"
] | 3151e0b790bd3d38987f3780fcef9503266b20ab | diff --git a/litestar/_asgi/routing_trie/traversal.py b/litestar/_asgi/routing_trie/traversal.py
--- a/litestar/_asgi/routing_trie/traversal.py
+++ b/litestar/_asgi/routing_trie/traversal.py
@@ -51,8 +51,7 @@ def traverse_route_map(
path_params.append(component)
continue
- if i != len(path_components) - 1 or not current_node.children:
- raise NotFoundException()
+ raise NotFoundException()
if not current_node.asgi_handlers:
raise NotFoundException()
| diff --git a/tests/e2e/test_routing/test_path_resolution.py b/tests/e2e/test_routing/test_path_resolution.py
--- a/tests/e2e/test_routing/test_path_resolution.py
+++ b/tests/e2e/test_routing/test_path_resolution.py
@@ -3,7 +3,7 @@
import pytest
-from litestar import Controller, MediaType, delete, get, post
+from litestar import Controller, MediaType, Router, delete, get, post
from litestar.contrib.pydantic import _model_dump
from litestar.status_codes import (
HTTP_200_OK,
@@ -274,3 +274,29 @@ async def hello_world(name: str) -> str:
response = client.get("/jon/bon/jovi")
assert response.status_code == HTTP_404_NOT_FOUND
+
+
+def test_root_path_param_resolution_2() -> None:
+ # https://github.com/litestar-org/litestar/issues/1830#issuecomment-1642291149
+ @get("/{name:str}")
+ async def name_greeting(name: str) -> str:
+ return f"Hello, {name}!"
+
+ @get("/{age:int}")
+ async def age_greeting(name: str, age: int) -> str:
+ return f"Hello, {name}! {age} is a great age to be!"
+
+ age_router = Router("/{name:str}/age", route_handlers=[age_greeting])
+ name_router = Router("/name", route_handlers=[name_greeting, age_router])
+
+ with create_test_client(name_router) as client:
+ response = client.get("/name/jon")
+ assert response.status_code == HTTP_200_OK
+ assert response.text == "Hello, jon!"
+
+ response = client.get("/name/jon/age/42")
+ assert response.status_code == HTTP_200_OK
+ assert response.text == "Hello, jon! 42 is a great age to be!"
+
+ response = client.get("/name/jon/bon")
+ assert response.status_code == HTTP_404_NOT_FOUND
| Bug: route with path parameters matches longer paths
### Description
A route registered for `/{param:str}`, in addition to matching `/foo` matches also `/foo/bar` (but not `/foo/bar/baz`).
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, get
@get("/{name:str}")
async def hello_world(name: str) -> str:
return f"Hello, {name}!"
app = Litestar([hello_world])
```
### Steps to reproduce
```bash
✗ http -b 'localhost:8000/jon'
Hello, jon!
✗ http -b 'localhost:8000/jon/bon'
Hello, jon!
✗ http -b 'localhost:8000/jon/bon/jovi'
{
"detail": "Not Found",
"status_code": 404
}
```
```
### Screenshots
```bash
""
```
### Logs
_No response_
### Litestar Version
Main branch
### Platform
- [ ] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/1830">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1830/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1830/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| This seems to be a regression. @Goldziher?
I'll handle it this weekend
It turns out this is not completely fixed (or I hit a similar bug).
MCVE:
```py
from litestar import Litestar, Router, get
@get("/{name:str}")
async def name_greeting(name: str) -> str:
return f"Hello, {name}!"
@get("/{age:int}")
async def age_greeting(name: str, age: int) -> str:
return f"Hello, {name}! {age} is a great age to be!"
app = Litestar(
[
Router(
"/name",
route_handlers=[
name_greeting,
Router("/{name:str}/age", route_handlers=[age_greeting]),
],
)
]
)
```
----
```
✅ curl http://localhost:8508/name/jon
Hello, jon!
✅ curl http://localhost:8508/name/jon/age/42
Hello, jon! 42 is a great age to be!
❌ curl http://localhost:8508/name/jon/some-bogus-path
Hello, jon!
```
can you take this one on @gsakkis ? the fix should be in `traversal.py` | 2023-07-20T08:56:53 |
litestar-org/litestar | 2,029 | litestar-org__litestar-2029 | [
"2025"
] | 49754e0c02022e96191a413d43e22649e0e0f856 | diff --git a/litestar/contrib/sqlalchemy/dto.py b/litestar/contrib/sqlalchemy/dto.py
--- a/litestar/contrib/sqlalchemy/dto.py
+++ b/litestar/contrib/sqlalchemy/dto.py
@@ -37,7 +37,7 @@
T = TypeVar("T", bound="DeclarativeBase | Collection[DeclarativeBase]")
-ElementType: TypeAlias = "Column[Any] | RelationshipProperty[Any]"
+ElementType: TypeAlias = "Column | RelationshipProperty"
SQLA_NS = {**vars(orm), **vars(sql)}
diff --git a/litestar/contrib/sqlalchemy/plugins/init/config/common.py b/litestar/contrib/sqlalchemy/plugins/init/config/common.py
--- a/litestar/contrib/sqlalchemy/plugins/init/config/common.py
+++ b/litestar/contrib/sqlalchemy/plugins/init/config/common.py
@@ -52,7 +52,7 @@ class GenericSessionConfig(Generic[ConnectionT, EngineT, SessionT]):
bind: EngineT | ConnectionT | None | EmptyType = Empty
"""The :class:`Engine <sqlalchemy.engine.Engine>` or :class:`Connection <sqlalchemy.engine.Connection>` that new
:class:`Session <sqlalchemy.orm.Session>` objects will be bound to."""
- binds: dict[type[Any] | Mapper[Any] | TableClause | str, EngineT | ConnectionT] | None | EmptyType = Empty
+ binds: dict[type[Any] | Mapper | TableClause | str, EngineT | ConnectionT] | None | EmptyType = Empty
"""A dictionary which may specify any number of :class:`Engine <sqlalchemy.engine.Engine>` or :class:`Connection
<sqlalchemy.engine.Connection>` objects as the source of connectivity for SQL operations on a per-entity basis. The
keys of the dictionary consist of any series of mapped classes, arbitrary Python classes that are bases for mapped
| diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -57,7 +57,7 @@ jobs:
path: ~/.cache
key: cache-${{ runner.os }}-${{ inputs.python-version }}-${{ inputs.pydantic-version }}-${{ hashFiles('**/poetry.lock') }}
- name: Install dependencies
- run: poetry install --no-interaction
+ run: poetry install --no-interaction --extras full
- if: ${{ inputs.pydantic-version == '1' }}
name: Install pydantic v1
run: poetry remove pydantic-extra-types && poetry add "pydantic>=1.10.10,<2" piccolo beanie
diff --git a/tests/unit/test_cli/test_cli.py b/tests/unit/test_cli/test_cli.py
--- a/tests/unit/test_cli/test_cli.py
+++ b/tests/unit/test_cli/test_cli.py
@@ -45,7 +45,7 @@ def test_register_commands_from_entrypoint(mocker: "MockerFixture", runner: "Cli
def custom_group() -> None:
pass
- @custom_group.command() # type: ignore[attr-defined]
+ @custom_group.command()
def custom_command(app: Litestar) -> None:
mock_command_callback()
diff --git a/tests/unit/test_middleware/test_csrf_middleware.py b/tests/unit/test_middleware/test_csrf_middleware.py
--- a/tests/unit/test_middleware/test_csrf_middleware.py
+++ b/tests/unit/test_middleware/test_csrf_middleware.py
@@ -199,7 +199,7 @@ def form_handler(data: dict = Body(media_type=RequestEncodingType.URL_ENCODED))
_ = client.get("/")
response = client.get("/")
html_soup = BeautifulSoup(html.unescape(response.text), features="html.parser")
- data = {"_csrf_token": html_soup.body.div.form.input.attrs.get("value")} # type: ignore
+ data = {"_csrf_token": html_soup.body.div.form.input.attrs.get("value")} # type: ignore[union-attr]
response = client.post("/", data=data)
assert response.status_code == HTTP_201_CREATED
assert response.json() == data
| Enhancement(Infra): Move away from Poetry
### Summary
This issue serves as a launchpad to potentially swap from Poetry to another solution. We don't have to change or go anywhere, but this is just to get an idea for options, thoughts, and concerns.
Poetry causes many issues, its dependency resolution sometimes takes multiple minutes, they have more than once made questionable changes (https://github.com/python-poetry/poetry/pull/6297), dependencies leak outside of their intended target (https://discord.com/channels/919193495116337154/919193495690936353/1131650830060245094, https://github.com/python-poetry/poetry/issues/4401).
### Basic Example
_No response_
### Drawbacks and Impact
- New tool = new learning curve for everyone
- CI Changes
### Unresolved questions
#### Where to?
- [PDM](https://pdm.fming.dev/latest/)
- [Hatch](https://hatch.pypa.io/latest/)
- PDM + Hatch's build system, Hatchling
- [Rye](https://github.com/mitsuhiko/rye/) _(experimental)_
- [Huak](https://github.com/cnpryer/huak) _(experimental)_
#### Other
This doesn't really solve the "The Python packaging ecosystem is terrible overall" issue...
> **__NOTE__**: PDM does have a potential issue around [PEP582](https://peps.python.org/pep-0582/) being rejected.
<!-- POLAR PLEDGE BADGE START -->
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2025">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2025/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2025/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| I noticed recently that `hatch` has been adopted by [attrs](https://github.com/python-attrs/attrs/pull/1094) (they are a project I've always viewed as setting a good standard as far as project/build/testing configuration goes).
One thing hatch doesn't have is lock files: [ref](https://github.com/pypa/hatch/issues/749), [ref](https://github.com/pypa/hatch/issues/716). However, that's not really an end-user issue, and seems we could do something to work around that by using `pip-tools` to compile a hashed set of requirements for development environments.
Given that hatch is a PyPA project - it probably will be a bit more "boring" than other package managers out there - but sometimes boring is a good thing.
Just my 2c.
Why is this an issue? Sorry, this is not decided. | 2023-07-21T09:25:22 |
litestar-org/litestar | 2,060 | litestar-org__litestar-2060 | [
"4321",
"1234"
] | cc5a13c0cf549029f0c31cb756927ac249dabe3c | diff --git a/litestar/contrib/sqlalchemy/repository/_async.py b/litestar/contrib/sqlalchemy/repository/_async.py
--- a/litestar/contrib/sqlalchemy/repository/_async.py
+++ b/litestar/contrib/sqlalchemy/repository/_async.py
@@ -2,7 +2,7 @@
from typing import TYPE_CHECKING, Any, Generic, Iterable, Literal, cast
-from sqlalchemy import Result, Select, delete, over, select, text, update
+from sqlalchemy import Result, Select, TextClause, delete, over, select, text, update
from sqlalchemy import func as sql_func
from litestar.contrib.repository import AbstractAsyncRepository, RepositoryError
@@ -711,12 +711,19 @@ async def check_health(cls, session: AsyncSession) -> bool:
session: through which we run a check statement
Returns:
- `True` if healthy.
+ ``True`` if healthy.
"""
- return ( # type:ignore[no-any-return] # pragma: no cover
- await session.execute(text("SELECT 1"))
+
+ return ( # type:ignore[no-any-return]
+ await session.execute(cls._get_health_check_statement(session))
).scalar_one() == 1
+ @staticmethod
+ def _get_health_check_statement(session: AsyncSession) -> TextClause:
+ if session.bind and session.bind.dialect.name == "oracle":
+ return text("SELECT 1 FROM DUAL")
+ return text("SELECT 1")
+
async def _attach_to_session(self, model: ModelT, strategy: Literal["add", "merge"] = "add") -> ModelT:
"""Attach detached instance to the session.
diff --git a/litestar/contrib/sqlalchemy/repository/_sync.py b/litestar/contrib/sqlalchemy/repository/_sync.py
--- a/litestar/contrib/sqlalchemy/repository/_sync.py
+++ b/litestar/contrib/sqlalchemy/repository/_sync.py
@@ -4,7 +4,7 @@
from typing import TYPE_CHECKING, Any, Generic, Iterable, Literal, cast
-from sqlalchemy import Result, Select, delete, over, select, text, update
+from sqlalchemy import Result, Select, TextClause, delete, over, select, text, update
from sqlalchemy import func as sql_func
from litestar.contrib.repository import AbstractSyncRepository, RepositoryError
@@ -713,12 +713,19 @@ def check_health(cls, session: Session) -> bool:
session: through which we run a check statement
Returns:
- `True` if healthy.
+ ``True`` if healthy.
"""
- return ( # type:ignore[no-any-return] # pragma: no cover
- session.execute(text("SELECT 1"))
+
+ return ( # type:ignore[no-any-return]
+ session.execute(cls._get_health_check_statement(session))
).scalar_one() == 1
+ @staticmethod
+ def _get_health_check_statement(session: Session) -> TextClause:
+ if session.bind and session.bind.dialect.name == "oracle":
+ return text("SELECT 1 FROM DUAL")
+ return text("SELECT 1")
+
def _attach_to_session(self, model: ModelT, strategy: Literal["add", "merge"] = "add") -> ModelT:
"""Attach detached instance to the session.
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
@@ -559,3 +559,14 @@ async def test_lazy_load(item_repo: ItemAsyncRepository, tag_repo: TagAsyncRepos
await maybe_async(item_repo.session.commit())
assert len(updated_obj.tags) > 0
assert updated_obj.tags[0].name == "A new tag"
+
+
+async def test_repo_health_check(author_repo: AuthorAsyncRepository) -> None:
+ """Test SQLALchemy health check.
+
+ Args:
+ author_repo (AuthorAsyncRepository): The mock repository
+ """
+
+ healthy = await maybe_async(author_repo.check_health(author_repo.session))
+ assert healthy
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
@@ -665,3 +665,14 @@ async def test_lazy_load(item_repo: ItemAsyncRepository, tag_repo: TagAsyncRepos
await maybe_async(item_repo.session.commit())
assert len(updated_obj.tags) > 0
assert updated_obj.tags[0].name == "A new tag"
+
+
+async def test_repo_health_check(author_repo: AuthorAsyncRepository) -> None:
+ """Test SQLALchemy health check.
+
+ Args:
+ author_repo (AuthorAsyncRepository): The mock repository
+ """
+
+ healthy = await maybe_async(author_repo.check_health(author_repo.session))
+ assert healthy
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-07-23T20:16:30 |
litestar-org/litestar | 2,061 | litestar-org__litestar-2061 | [
"4321",
"1234"
] | 418b732c60f5e67f1abbd5239fb1f7063ef475a0 | diff --git a/litestar/contrib/sqlalchemy/repository/_async.py b/litestar/contrib/sqlalchemy/repository/_async.py
--- a/litestar/contrib/sqlalchemy/repository/_async.py
+++ b/litestar/contrib/sqlalchemy/repository/_async.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Generic, Iterable, Literal, cast
+from typing import TYPE_CHECKING, Any, Final, Generic, Iterable, Literal, cast
from sqlalchemy import Result, Select, TextClause, delete, over, select, text, update
from sqlalchemy import func as sql_func
@@ -28,6 +28,8 @@
from sqlalchemy.engine.interfaces import _CoreSingleExecuteParams
from sqlalchemy.ext.asyncio import AsyncSession
+DEFAULT_INSERTMANYVALUES_MAX_PARAMETERS: Final = 950
+
class SQLAlchemyAsyncRepository(AbstractAsyncRepository[ModelT], Generic[ModelT]):
"""SQLAlchemy based implementation of the repository interface."""
@@ -157,6 +159,7 @@ async def delete_many(
auto_commit: bool | None = None,
auto_expunge: bool | None = None,
id_attribute: Any | None = None,
+ chunk_size: int | None = None,
) -> list[ModelT]:
"""Delete instance identified by `item_id`.
@@ -168,6 +171,8 @@ async def delete_many(
:class:`SQLAlchemyAsyncRepository.auto_commit <SQLAlchemyAsyncRepository>`
id_attribute: Allows customization of the unique identifier to use for model fetching.
Defaults to `id`, but can reference any surrogate or candidate key for the table.
+ chunk_size: Allows customization of the ``insertmanyvalues_max_parameters`` setting for the driver.
+ Defaults to `950` if left unset.
Returns:
The deleted instances.
@@ -177,7 +182,7 @@ async def delete_many(
with wrap_sqlalchemy_exception():
id_attribute = id_attribute if id_attribute is not None else self.id_attribute
instances: list[ModelT] = []
- chunk_size = 450
+ chunk_size = self._get_insertmanyvalues_max_parameters(chunk_size)
for idx in range(0, len(item_ids), chunk_size):
chunk = item_ids[idx : min(idx + chunk_size, len(item_ids))]
if self._dialect.delete_executemany_returning:
@@ -202,6 +207,9 @@ async def delete_many(
self._expunge(instance, auto_expunge=auto_expunge)
return instances
+ def _get_insertmanyvalues_max_parameters(self, chunk_size: int | None = None) -> int:
+ return chunk_size if chunk_size is not None else DEFAULT_INSERTMANYVALUES_MAX_PARAMETERS
+
async def exists(self, **kwargs: Any) -> bool:
"""Return true if the object specified by ``kwargs`` exists.
diff --git a/litestar/contrib/sqlalchemy/repository/_sync.py b/litestar/contrib/sqlalchemy/repository/_sync.py
--- a/litestar/contrib/sqlalchemy/repository/_sync.py
+++ b/litestar/contrib/sqlalchemy/repository/_sync.py
@@ -2,7 +2,7 @@
# litestar/contrib/sqlalchemy/repository/_async.py
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Generic, Iterable, Literal, cast
+from typing import TYPE_CHECKING, Any, Final, Generic, Iterable, Literal, cast
from sqlalchemy import Result, Select, TextClause, delete, over, select, text, update
from sqlalchemy import func as sql_func
@@ -30,6 +30,8 @@
from sqlalchemy.engine.interfaces import _CoreSingleExecuteParams
from sqlalchemy.orm import Session
+DEFAULT_INSERTMANYVALUES_MAX_PARAMETERS: Final = 950
+
class SQLAlchemySyncRepository(AbstractSyncRepository[ModelT], Generic[ModelT]):
"""SQLAlchemy based implementation of the repository interface."""
@@ -159,6 +161,7 @@ def delete_many(
auto_commit: bool | None = None,
auto_expunge: bool | None = None,
id_attribute: Any | None = None,
+ chunk_size: int | None = None,
) -> list[ModelT]:
"""Delete instance identified by `item_id`.
@@ -170,6 +173,8 @@ def delete_many(
:class:`SQLAlchemyAsyncRepository.auto_commit <SQLAlchemyAsyncRepository>`
id_attribute: Allows customization of the unique identifier to use for model fetching.
Defaults to `id`, but can reference any surrogate or candidate key for the table.
+ chunk_size: Allows customization of the ``insertmanyvalues_max_parameters`` setting for the driver.
+ Defaults to `950` if left unset.
Returns:
The deleted instances.
@@ -179,7 +184,7 @@ def delete_many(
with wrap_sqlalchemy_exception():
id_attribute = id_attribute if id_attribute is not None else self.id_attribute
instances: list[ModelT] = []
- chunk_size = 450
+ chunk_size = self._get_insertmanyvalues_max_parameters(chunk_size)
for idx in range(0, len(item_ids), chunk_size):
chunk = item_ids[idx : min(idx + chunk_size, len(item_ids))]
if self._dialect.delete_executemany_returning:
@@ -204,6 +209,9 @@ def delete_many(
self._expunge(instance, auto_expunge=auto_expunge)
return instances
+ def _get_insertmanyvalues_max_parameters(self, chunk_size: int | None = None) -> int:
+ return chunk_size if chunk_size is not None else DEFAULT_INSERTMANYVALUES_MAX_PARAMETERS
+
def exists(self, **kwargs: Any) -> bool:
"""Return true if the object specified by ``kwargs`` exists.
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_bigint.py
@@ -305,7 +305,7 @@ async def test_repo_delete_many_method(author_repo: AuthorAsyncRepository) -> No
BigIntAuthor(
name="author name %d" % chunk,
)
- for chunk in range(1000)
+ for chunk in range(2000)
]
_ = await maybe_async(author_repo.add_many(data_to_insert))
all_objs = await maybe_async(author_repo.list())
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repo_uuid.py
@@ -411,7 +411,7 @@ async def test_repo_delete_many_method(author_repo: AuthorAsyncRepository) -> No
UUIDAuthor(
name="author name %d" % chunk,
)
- for chunk in range(1000)
+ for chunk in range(2000)
]
_ = await maybe_async(author_repo.add_many(data_to_insert))
all_objs = await maybe_async(author_repo.list())
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_async.py
@@ -203,7 +203,7 @@ async def test_sqlalchemy_repo_delete(mock_repo: SQLAlchemyAsyncRepository, monk
mock_repo.session.commit.assert_not_called()
-async def test_sqlalchemy_repo_delete_many(mock_repo: SQLAlchemyAsyncRepository, monkeypatch: MonkeyPatch) -> None:
+async def test_sqlalchemy_repo_delete_many_uuid(mock_repo: SQLAlchemyAsyncRepository, monkeypatch: MonkeyPatch) -> None:
"""Test expected method calls for delete operation."""
class UUIDModel(base.UUIDAuditBase):
@@ -212,6 +212,25 @@ class UUIDModel(base.UUIDAuditBase):
...
+ mock_instances = [MagicMock(), MagicMock(id=uuid4())]
+ monkeypatch.setattr(mock_repo.session, "scalars", AsyncMock(return_value=mock_instances))
+ monkeypatch.setattr(mock_repo, "model_type", UUIDModel)
+ monkeypatch.setattr(mock_repo.session, "execute", AsyncMock(return_value=mock_instances))
+ monkeypatch.setattr(mock_repo, "list", AsyncMock(return_value=mock_instances))
+ monkeypatch.setattr(mock_repo.session.bind.dialect, "insertmanyvalues_max_parameters", 2)
+
+ added_instances = await mock_repo.add_many(mock_instances)
+ instances = await mock_repo.delete_many([obj.id for obj in added_instances])
+ assert len(instances) == len(mock_instances)
+ mock_repo.session.flush.assert_called()
+ mock_repo.session.commit.assert_not_called()
+
+
+async def test_sqlalchemy_repo_delete_many_bigint(
+ mock_repo: SQLAlchemyAsyncRepository, monkeypatch: MonkeyPatch
+) -> None:
+ """Test expected method calls for delete operation."""
+
class BigIntModel(base.BigIntAuditBase):
"""Inheriting from BigIntAuditBase gives the model 'created_at' and 'updated_at'
columns."""
@@ -220,11 +239,11 @@ class BigIntModel(base.BigIntAuditBase):
mock_instances = [MagicMock(), MagicMock(id=uuid4())]
monkeypatch.setattr(mock_repo.session, "scalars", AsyncMock(return_value=mock_instances))
- monkeypatch.setattr(mock_repo, "model_type", UUIDModel)
- monkeypatch.setattr(mock_repo.session, "execute", AsyncMock(return_value=mock_instances))
monkeypatch.setattr(mock_repo, "model_type", BigIntModel)
monkeypatch.setattr(mock_repo.session, "execute", AsyncMock(return_value=mock_instances))
monkeypatch.setattr(mock_repo, "list", AsyncMock(return_value=mock_instances))
+ monkeypatch.setattr(mock_repo.session.bind.dialect, "insertmanyvalues_max_parameters", 2)
+
added_instances = await mock_repo.add_many(mock_instances)
instances = await mock_repo.delete_many([obj.id for obj in added_instances])
assert len(instances) == len(mock_instances)
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy_sync.py
@@ -202,7 +202,7 @@ def test_sqlalchemy_repo_delete(mock_repo: SQLAlchemySyncRepository, monkeypatch
mock_repo.session.commit.assert_not_called()
-def test_sqlalchemy_repo_delete_many(mock_repo: SQLAlchemySyncRepository, monkeypatch: MonkeyPatch) -> None:
+def test_sqlalchemy_repo_delete_many_uuid(mock_repo: SQLAlchemySyncRepository, monkeypatch: MonkeyPatch) -> None:
"""Test expected method calls for delete operation."""
class UUIDModel(base.UUIDAuditBase):
@@ -211,6 +211,23 @@ class UUIDModel(base.UUIDAuditBase):
...
+ mock_instances = [MagicMock(), MagicMock(id=uuid4())]
+ monkeypatch.setattr(mock_repo.session, "scalars", MagicMock(return_value=mock_instances))
+ monkeypatch.setattr(mock_repo, "model_type", UUIDModel)
+ monkeypatch.setattr(mock_repo.session, "execute", MagicMock(return_value=mock_instances))
+ monkeypatch.setattr(mock_repo, "list", MagicMock(return_value=mock_instances))
+ monkeypatch.setattr(mock_repo.session.bind.dialect, "insertmanyvalues_max_parameters", 100) # type: ignore[union-attr]
+
+ added_instances = mock_repo.add_many(mock_instances)
+ instances = mock_repo.delete_many([obj.id for obj in added_instances])
+ assert len(instances) == len(mock_instances)
+ mock_repo.session.flush.assert_called()
+ mock_repo.session.commit.assert_not_called()
+
+
+def test_sqlalchemy_repo_delete_many_bigint(mock_repo: SQLAlchemySyncRepository, monkeypatch: MonkeyPatch) -> None:
+ """Test expected method calls for delete operation."""
+
class BigIntModel(base.BigIntAuditBase):
"""Inheriting from BigIntAuditBase gives the model 'created_at' and 'updated_at'
columns."""
@@ -219,11 +236,11 @@ class BigIntModel(base.BigIntAuditBase):
mock_instances = [MagicMock(), MagicMock(id=uuid4())]
monkeypatch.setattr(mock_repo.session, "scalars", MagicMock(return_value=mock_instances))
- monkeypatch.setattr(mock_repo, "model_type", UUIDModel)
- monkeypatch.setattr(mock_repo.session, "execute", MagicMock(return_value=mock_instances))
monkeypatch.setattr(mock_repo, "model_type", BigIntModel)
monkeypatch.setattr(mock_repo.session, "execute", MagicMock(return_value=mock_instances))
monkeypatch.setattr(mock_repo, "list", MagicMock(return_value=mock_instances))
+ monkeypatch.setattr(mock_repo.session.bind.dialect, "insertmanyvalues_max_parameters", 100) # type: ignore[union-attr]
+
added_instances = mock_repo.add_many(mock_instances)
instances = mock_repo.delete_many([obj.id for obj in added_instances])
assert len(instances) == len(mock_instances)
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-07-24T01:35:07 |
litestar-org/litestar | 2,065 | litestar-org__litestar-2065 | [
"4321",
"1234"
] | 4903e34aeb4ab4d8590b233ba171f1f61b710e95 | diff --git a/litestar/dto/_backend.py b/litestar/dto/_backend.py
--- a/litestar/dto/_backend.py
+++ b/litestar/dto/_backend.py
@@ -50,6 +50,7 @@ class DTOBackend:
"reverse_name_map",
"transfer_model_type",
"wrapper_attribute_name",
+ "is_dto_data_type",
)
_seen_model_names: ClassVar[set[str]] = set()
@@ -87,10 +88,12 @@ def __init__(
model_name=model_type.__name__, field_definitions=self.parsed_field_definitions
)
self.dto_data_type: type[DTOData] | None = None
+ self.is_dto_data_type: bool = False
if field_definition.is_subclass_of(DTOData):
self.dto_data_type = field_definition.annotation
annotation = self.field_definition.inner_types[0].annotation
+ self.is_dto_data_type = True
else:
annotation = field_definition.annotation
@@ -242,6 +245,7 @@ def populate_data_from_builtins(self, builtins: Any, asgi_connection: ASGIConnec
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
+ is_dto_data_type=self.is_dto_data_type,
),
)
return self.transfer_data_from_builtins(self.parse_builtins(builtins, asgi_connection))
@@ -261,6 +265,7 @@ def transfer_data_from_builtins(self, builtins: Any) -> Any:
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
+ is_dto_data_type=self.is_dto_data_type,
)
def populate_data_from_raw(self, raw: bytes, asgi_connection: ASGIConnection) -> Any:
@@ -282,6 +287,7 @@ def populate_data_from_raw(self, raw: bytes, asgi_connection: ASGIConnection) ->
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
+ is_dto_data_type=self.is_dto_data_type,
),
)
return _transfer_data(
@@ -290,6 +296,7 @@ def populate_data_from_raw(self, raw: bytes, asgi_connection: ASGIConnection) ->
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
+ is_dto_data_type=self.is_dto_data_type,
)
def encode_data(self, data: Any) -> LitestarEncodableType:
@@ -308,6 +315,7 @@ def encode_data(self, data: Any) -> LitestarEncodableType:
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
+ is_dto_data_type=self.is_dto_data_type,
)
setattr(
data,
@@ -324,6 +332,7 @@ def encode_data(self, data: Any) -> LitestarEncodableType:
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
+ is_dto_data_type=self.is_dto_data_type,
),
)
@@ -512,6 +521,7 @@ def _transfer_data(
field_definitions: tuple[TransferDTOFieldDefinition, ...],
field_definition: FieldDefinition,
is_data_field: bool,
+ is_dto_data_type: bool,
) -> Any:
"""Create instance or iterable of instances of ``destination_type``.
@@ -521,6 +531,7 @@ def _transfer_data(
field_definitions: model field definitions.
field_definition: the parsed type that represents the handler annotation for which the DTO is being applied.
is_data_field: whether the DTO is being applied to a ``data`` field.
+ is_dto_data_type: whether the field definition is an `DTOData` type.
Returns:
Data parsed into ``destination_type``.
@@ -533,6 +544,7 @@ def _transfer_data(
field_definitions=field_definitions,
field_definition=field_definition.inner_types[0],
is_data_field=is_data_field,
+ is_dto_data_type=is_dto_data_type,
)
for item in source_data
)
@@ -542,6 +554,7 @@ def _transfer_data(
source_instance=source_data,
field_definitions=field_definitions,
is_data_field=is_data_field,
+ is_dto_data_type=is_dto_data_type,
)
@@ -550,6 +563,7 @@ def _transfer_instance_data(
source_instance: Any,
field_definitions: tuple[TransferDTOFieldDefinition, ...],
is_data_field: bool,
+ is_dto_data_type: bool,
) -> Any:
"""Create instance of ``destination_type`` with data from ``source_instance``.
@@ -558,6 +572,7 @@ def _transfer_instance_data(
source_instance: primitive data that has been parsed and validated via the backend.
field_definitions: model field definitions.
is_data_field: whether the given field is a 'data' kwarg field.
+ is_dto_data_type: whether the field definition is an `DTOData` type.
Returns:
Data parsed into ``model_type``.
@@ -565,7 +580,8 @@ def _transfer_instance_data(
unstructured_data = {}
for field_definition in field_definitions:
- source_name = field_definition.serialization_name if is_data_field else field_definition.name
+ should_use_serialization_name = is_data_field and not is_dto_data_type
+ source_name = field_definition.serialization_name if should_use_serialization_name else field_definition.name
source_has_value = (
source_name in source_instance
@@ -592,13 +608,18 @@ def _transfer_instance_data(
transfer_type=transfer_type,
nested_as_dict=destination_type is dict,
is_data_field=is_data_field,
+ is_dto_data_type=is_dto_data_type,
)
return destination_type(**unstructured_data)
def _transfer_type_data(
- source_value: Any, transfer_type: TransferType, nested_as_dict: bool, is_data_field: bool
+ source_value: Any,
+ transfer_type: TransferType,
+ nested_as_dict: bool,
+ is_data_field: bool,
+ is_dto_data_type: bool,
) -> Any:
if isinstance(transfer_type, SimpleType) and transfer_type.nested_field_info:
if nested_as_dict:
@@ -613,11 +634,15 @@ def _transfer_type_data(
source_instance=source_value,
field_definitions=transfer_type.nested_field_info.field_definitions,
is_data_field=is_data_field,
+ is_dto_data_type=is_dto_data_type,
)
if isinstance(transfer_type, UnionType) and transfer_type.has_nested:
return _transfer_nested_union_type_data(
- transfer_type=transfer_type, source_value=source_value, is_data_field=is_data_field
+ transfer_type=transfer_type,
+ source_value=source_value,
+ is_data_field=is_data_field,
+ is_dto_data_type=is_dto_data_type,
)
if isinstance(transfer_type, CollectionType):
@@ -628,6 +653,7 @@ def _transfer_type_data(
transfer_type=transfer_type.inner_type,
nested_as_dict=False,
is_data_field=is_data_field,
+ is_dto_data_type=is_dto_data_type,
)
for item in source_value
)
@@ -636,7 +662,12 @@ def _transfer_type_data(
return source_value
-def _transfer_nested_union_type_data(transfer_type: UnionType, source_value: Any, is_data_field: bool) -> Any:
+def _transfer_nested_union_type_data(
+ transfer_type: UnionType,
+ source_value: Any,
+ is_data_field: bool,
+ is_dto_data_type: bool,
+) -> Any:
for inner_type in transfer_type.inner_types:
if isinstance(inner_type, CompositeType):
raise RuntimeError("Composite inner types not (yet) supported for nested unions.")
@@ -652,6 +683,7 @@ def _transfer_nested_union_type_data(transfer_type: UnionType, source_value: Any
source_instance=source_value,
field_definitions=inner_type.nested_field_info.field_definitions,
is_data_field=is_data_field,
+ is_dto_data_type=is_dto_data_type,
)
return source_value
| diff --git a/tests/unit/test_dto/test_factory/test_backends/test_utils.py b/tests/unit/test_dto/test_factory/test_backends/test_utils.py
--- a/tests/unit/test_dto/test_factory/test_backends/test_utils.py
+++ b/tests/unit/test_dto/test_factory/test_backends/test_utils.py
@@ -53,7 +53,12 @@ def test_transfer_nested_union_type_data_raises_runtime_error_for_complex_union(
has_nested=True,
)
with pytest.raises(RuntimeError):
- _transfer_nested_union_type_data(transfer_type=transfer_type, is_data_field=True, source_value=1)
+ _transfer_nested_union_type_data(
+ transfer_type=transfer_type,
+ is_data_field=True,
+ source_value=1,
+ is_dto_data_type=True,
+ )
def test_create_transfer_model_type_annotation_simple_type_without_nested_field_info() -> None:
diff --git a/tests/unit/test_dto/test_factory/test_integration.py b/tests/unit/test_dto/test_factory/test_integration.py
--- a/tests/unit/test_dto/test_factory/test_integration.py
+++ b/tests/unit/test_dto/test_factory/test_integration.py
@@ -214,6 +214,31 @@ def handler(data: DTOData[User] = Body(media_type=RequestEncodingType.URL_ENCODE
assert response.json() == {"name": "John", "age": 42, "read_only": "read-only"}
+@dataclass
+class RenamedBar:
+ bar: str
+ foo_foo: str
+
+
+def test_dto_data_create_instance_renamed_fields() -> None:
+ @post(
+ dto=DataclassDTO[Annotated[RenamedBar, DTOConfig(exclude={"foo_foo"}, rename_strategy="camel")]],
+ return_dto=DataclassDTO[Annotated[RenamedBar, DTOConfig(rename_strategy="camel")]],
+ )
+ def handler(data: DTOData[RenamedBar]) -> RenamedBar:
+ assert isinstance(data, DTOData)
+ result = data.create_instance(foo_foo="world")
+ assert result.foo_foo == "world"
+ return result
+
+ with create_test_client(
+ route_handlers=[handler], signature_namespace={"NestedFoo": NestedFoo, "NestingBar": NestingBar}
+ ) as client:
+ response = client.post("/", json={"bar": "hello"})
+ assert response.status_code == 201
+ assert response.json() == {"bar": "hello", "fooFoo": "world"}
+
+
def test_dto_data_with_patch_request() -> None:
class PatchDTO(DataclassDTO[User]):
config = DTOConfig(partial=True)
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-07-25T16:59:29 |
litestar-org/litestar | 2,069 | litestar-org__litestar-2069 | [
"2033",
"2033"
] | 33bac083e495e1ba23d56de40d98ceb4036b7539 | diff --git a/litestar/middleware/session/server_side.py b/litestar/middleware/session/server_side.py
--- a/litestar/middleware/session/server_side.py
+++ b/litestar/middleware/session/server_side.py
@@ -119,7 +119,9 @@ async def store_in_message(self, scope_session: ScopeSession, message: Message,
else:
serialised_data = self.serialize_data(scope_session, scope)
await self.set(session_id=session_id, data=serialised_data, store=store)
- headers["Set-Cookie"] = Cookie(value=session_id, key=self.config.key, **cookie_params).to_header(header="")
+ headers.add(
+ "Set-Cookie", Cookie(value=session_id, key=self.config.key, **cookie_params).to_header(header="")
+ )
async def load_from_connection(self, connection: ASGIConnection) -> dict[str, Any]:
"""Load session data from a connection and return it as a dictionary to be used in the current application
| diff --git a/tests/unit/test_middleware/test_session/test_middleware.py b/tests/unit/test_middleware/test_session/test_middleware.py
--- a/tests/unit/test_middleware/test_session/test_middleware.py
+++ b/tests/unit/test_middleware/test_session/test_middleware.py
@@ -1,6 +1,6 @@
from typing import TYPE_CHECKING, Dict, Optional
-from litestar import HttpMethod, Request, get, post, route
+from litestar import HttpMethod, Request, Response, get, post, route
from litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
from litestar.testing import create_test_client
from litestar.types import Empty
@@ -146,3 +146,15 @@ def south_handler(request: Request) -> Dict[str, bool]:
response = client.get("/south")
assert response.json() == {"has_session": False}
+
+
+def test_does_not_override_cookies(session_backend_config_memory: "ServerSideSessionConfig") -> None:
+ # https://github.com/litestar-org/litestar/issues/2033
+
+ @get("/")
+ async def index() -> Response[str]:
+ return Response(cookies={"foo": "bar"}, content="hello")
+
+ with create_test_client(index, middleware=[session_backend_config_memory.middleware]) as client:
+ res = client.get("/")
+ assert res.cookies.get("foo") == "bar"
| Bug: Server-side session middleware overrides CSRF cookies
### Description
I noticed that it seems applying both a ServerSideSession and CSRF protection, breaks the CSRF middleware.
I have recently been digging into the session features and noticed this. Using no or client Cookie side session middleware does not affect the CSRF middleware. On a normal get, the token gets set and csrf protection will be enabled.
However, slotting in ServerSideSession, which I'm using a redis store for, causes the csrftoken to never be set. No GET or HEAD request ever gets a set-cookie response. I haven't seen this behavior with any other middleware, whether its custom or any of the other builtins.
I was looking through the code and noticed that on line 122 of litstar.middleware.session.server_side.py, it is using a headers['Set-Cookie'] instead of a headers.add. Causing it to override the set-cookie from the csrf. Im sure this could cause other issues as well.
If you change this to a headesr.add, it fixes the issue and both middlewares work properly.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, get, post
from litestar.config.csrf import CSRFConfig
from litestar.middleware.session.server_side import ServerSideSessionConfig
@get('/')
async def index() -> dict[str, str]:
return {'status': "success"}
@post('/')
async def index_post() -> dict[str, str]:
return {'status': "success"}
app = Litestar(
route_handlers=[index, index_post],
csrf_config=CSRFConfig(
secret="Change_Me",
cookie_name="x-csrftoken",
),
middleware=[
ServerSideSessionConfig(
renew_on_access=True,
max_age=30*60
).middleware
]
)
```
### Steps to reproduce
```bash
1. Make a GET request to the app
2. Observe that a cookie is set for session, but not for the csrf
3. Change line 122 of litestar.middleware.session.server_side.py to a headers.add
4. Remake the GET request to the app
5. Observe both cookies are now set
6. Make a POST request and observe the app functions as expected
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
I was using 2.0.0b2 when I noticed it, however it is also present in 2.0.0b3
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2033">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2033/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2033/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
Bug: Server-side session middleware overrides CSRF cookies
### Description
I noticed that it seems applying both a ServerSideSession and CSRF protection, breaks the CSRF middleware.
I have recently been digging into the session features and noticed this. Using no or client Cookie side session middleware does not affect the CSRF middleware. On a normal get, the token gets set and csrf protection will be enabled.
However, slotting in ServerSideSession, which I'm using a redis store for, causes the csrftoken to never be set. No GET or HEAD request ever gets a set-cookie response. I haven't seen this behavior with any other middleware, whether its custom or any of the other builtins.
I was looking through the code and noticed that on line 122 of litstar.middleware.session.server_side.py, it is using a headers['Set-Cookie'] instead of a headers.add. Causing it to override the set-cookie from the csrf. Im sure this could cause other issues as well.
If you change this to a headesr.add, it fixes the issue and both middlewares work properly.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, get, post
from litestar.config.csrf import CSRFConfig
from litestar.middleware.session.server_side import ServerSideSessionConfig
@get('/')
async def index() -> dict[str, str]:
return {'status': "success"}
@post('/')
async def index_post() -> dict[str, str]:
return {'status': "success"}
app = Litestar(
route_handlers=[index, index_post],
csrf_config=CSRFConfig(
secret="Change_Me",
cookie_name="x-csrftoken",
),
middleware=[
ServerSideSessionConfig(
renew_on_access=True,
max_age=30*60
).middleware
]
)
```
### Steps to reproduce
```bash
1. Make a GET request to the app
2. Observe that a cookie is set for session, but not for the csrf
3. Change line 122 of litestar.middleware.session.server_side.py to a headers.add
4. Remake the GET request to the app
5. Observe both cookies are now set
6. Make a POST request and observe the app functions as expected
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
I was using 2.0.0b2 when I noticed it, however it is also present in 2.0.0b3
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2033">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2033/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2033/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-07-26T11:48:40 |
|
litestar-org/litestar | 2,105 | litestar-org__litestar-2105 | [
"1948",
"4321",
"1948"
] | cefdb8c6fc62db5ac4ed0f628cc2dd53bd6e5d17 | diff --git a/starlite/config/logging.py b/starlite/config/logging.py
--- a/starlite/config/logging.py
+++ b/starlite/config/logging.py
@@ -259,7 +259,7 @@ class StructLoggingConfig(BaseLoggingConfig, BaseModel):
processors: Optional[List[Processor]] = Field(default_factory=default_structlog_processors) # pyright: ignore
"""Iterable of structlog logging processors."""
- wrapper_class: Optional[Type[BindableLogger]] = Field(default_factory=default_wrapper_class) # pyright: ignore
+ wrapper_class: Any = Field(default_factory=default_wrapper_class) # pyright: ignore
"""Structlog bindable logger."""
context_class: Optional[Dict[str, Any]] = None
"""Context class (a 'contextvar' context) for the logger."""
| Bug: passing wrapper_class to StructLoggingConfig causes Pydantic exception
### Description
When trying to hook up structlog to starlite v1.51.12, I got the Pydantic exception below on starting up the app. I tried the same with the litestar v2 beta hello-world app, and it worked. I realize this may not get fixed in v1.51.x. Is there a suggested workaround?
### URL to code causing the issue
https://github.com/kpetersen-rgare/litestar-hello-world/blob/structlog-logging-config-bug/main.py
### MCVE
```python
# see URL to code
```
### Steps to reproduce
```bash
1. clone MRE repo and `poetry install`
2. `poetry run uvicorn main:app`
3. See error
```
### Screenshots
```bash
""
```
### Logs
```bash
Traceback (most recent call last):
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/bin/uvicorn", line 8, in <module>
sys.exit(main())
^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/click/core.py", line 1157, in __call__
return self.main(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/click/core.py", line 1078, in main
rv = self.invoke(ctx)
^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/click/core.py", line 1434, in invoke
return ctx.invoke(self.callback, **ctx.params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/click/core.py", line 783, in invoke
return __callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/main.py", line 410, in main
run(
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/main.py", line 578, in run
server.run()
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/server.py", line 61, in run
return asyncio.run(self.serve(sockets=sockets))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/server.py", line 68, in serve
config.load()
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/config.py", line 473, in load
self.loaded_app = import_from_string(self.app)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Users/me/Developer/kpetersen-rgare/litestar-hello-world/main.py", line 19, in <module>
logging_config = StructLoggingConfig(
^^^^^^^^^^^^^^^^^^^^
File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for StructLoggingConfig
wrapper_class
Protocols with non-method members don't support issubclass() (type=type_error)
```
### Litestar Version
1.51.12
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/1948">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1948/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1948/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
Bug: passing wrapper_class to StructLoggingConfig causes Pydantic exception
### Description
When trying to hook up structlog to starlite v1.51.12, I got the Pydantic exception below on starting up the app. I tried the same with the litestar v2 beta hello-world app, and it worked. I realize this may not get fixed in v1.51.x. Is there a suggested workaround?
### URL to code causing the issue
https://github.com/kpetersen-rgare/litestar-hello-world/blob/structlog-logging-config-bug/main.py
### MCVE
```python
# see URL to code
```
### Steps to reproduce
```bash
1. clone MRE repo and `poetry install`
2. `poetry run uvicorn main:app`
3. See error
```
### Screenshots
```bash
""
```
### Logs
```bash
Traceback (most recent call last):
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/bin/uvicorn", line 8, in <module>
sys.exit(main())
^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/click/core.py", line 1157, in __call__
return self.main(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/click/core.py", line 1078, in main
rv = self.invoke(ctx)
^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/click/core.py", line 1434, in invoke
return ctx.invoke(self.callback, **ctx.params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/click/core.py", line 783, in invoke
return __callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/main.py", line 410, in main
run(
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/main.py", line 578, in run
server.run()
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/server.py", line 61, in run
return asyncio.run(self.serve(sockets=sockets))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/server.py", line 68, in serve
config.load()
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/config.py", line 473, in load
self.loaded_app = import_from_string(self.app)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/me/Library/Caches/pypoetry/virtualenvs/starlite-hello-world-cQlwT1sN-py3.11/lib/python3.11/site-packages/uvicorn/importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Users/me/Developer/kpetersen-rgare/litestar-hello-world/main.py", line 19, in <module>
logging_config = StructLoggingConfig(
^^^^^^^^^^^^^^^^^^^^
File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for StructLoggingConfig
wrapper_class
Protocols with non-method members don't support issubclass() (type=type_error)
```
### Litestar Version
1.51.12
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/1948">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1948/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1948/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Hi @kpetersen-rgare! Thanks for the report. We have squashed a few bugs around structlog issues and we should backport these.
_edited: I am a bad reader and shouldnt answer issues so late 🙃_
Hey, thanks for the quick response. I realized a simple workaround is to create my own structlog config class from the `BaseLoggingConfig` class that does not inherit from pydantic's `BaseModel`:
```python
class MyStructLoggingConfig(BaseLoggingConfig):
def configure(self) -> "GetLogger":
structlog.configure(
processors=processors,
wrapper_class=structlog.make_filtering_bound_logger(logging.DEBUG),
logger_factory=logger_factory,
)
return structlog.get_logger
```
@JacobCoffee can you take this one?
Hi yes, I will look into this starting tonight
Hi @kpetersen-rgare! Thanks for the report. We have squashed a few bugs around structlog issues and we should backport these.
_edited: I am a bad reader and shouldnt answer issues so late 🙃_
Hey, thanks for the quick response. I realized a simple workaround is to create my own structlog config class from the `BaseLoggingConfig` class that does not inherit from pydantic's `BaseModel`:
```python
class MyStructLoggingConfig(BaseLoggingConfig):
def configure(self) -> "GetLogger":
structlog.configure(
processors=processors,
wrapper_class=structlog.make_filtering_bound_logger(logging.DEBUG),
logger_factory=logger_factory,
)
return structlog.get_logger
```
@JacobCoffee can you take this one?
Hi yes, I will look into this starting tonight | 2023-08-02T02:32:02 |
|
litestar-org/litestar | 2,124 | litestar-org__litestar-2124 | [
"4321",
"1234"
] | 0cd62d8802588ceb7bb2d9b16f11992bc854243c | diff --git a/litestar/contrib/sqlalchemy/dto.py b/litestar/contrib/sqlalchemy/dto.py
--- a/litestar/contrib/sqlalchemy/dto.py
+++ b/litestar/contrib/sqlalchemy/dto.py
@@ -9,9 +9,11 @@
from sqlalchemy.ext.hybrid import HybridExtensionType, hybrid_property
from sqlalchemy.orm import (
ColumnProperty,
+ CompositeProperty,
DeclarativeBase,
InspectionAttr,
Mapped,
+ MappedColumn,
NotExtension,
QueryableAttribute,
RelationshipDirection,
@@ -35,7 +37,7 @@
T = TypeVar("T", bound="DeclarativeBase | Collection[DeclarativeBase]")
-ElementType: TypeAlias = "Column | RelationshipProperty"
+ElementType: TypeAlias = "Column | RelationshipProperty | CompositeProperty"
SQLA_NS = {**vars(orm), **vars(sql)}
@@ -72,7 +74,7 @@ def _(
if not isinstance(orm_descriptor.property.expression, Column):
raise NotImplementedError(f"Expected 'Column', got: '{orm_descriptor.property.expression}'")
elem = orm_descriptor.property.expression
- elif isinstance(orm_descriptor.property, RelationshipProperty):
+ elif isinstance(orm_descriptor.property, (RelationshipProperty, CompositeProperty)):
elem = orm_descriptor.property
else:
raise NotImplementedError(f"Unhandled property type: '{orm_descriptor.property}'")
@@ -189,6 +191,13 @@ def generate_field_definitions(cls, model_type: type[DeclarativeBase]) -> Genera
# the same hybrid property descriptor can be included in `all_orm_descriptors` multiple times, once
# for each method name it is bound to. We only need to see it once, so track views of it here.
seen_hybrid_descriptors: set[hybrid_property] = set()
+ skipped_columns: set[str] = set()
+ for composite_property in mapper.composites:
+ for attr in composite_property.attrs:
+ if isinstance(attr, (MappedColumn, Column)):
+ skipped_columns.add(attr.name)
+ elif isinstance(attr, str):
+ skipped_columns.add(attr)
for key, orm_descriptor in mapper.all_orm_descriptors.items():
if isinstance(orm_descriptor, hybrid_property):
if orm_descriptor in seen_hybrid_descriptors:
@@ -196,6 +205,9 @@ def generate_field_definitions(cls, model_type: type[DeclarativeBase]) -> Genera
seen_hybrid_descriptors.add(orm_descriptor)
+ if key in skipped_columns:
+ continue
+
yield from cls.handle_orm_descriptor(
orm_descriptor.extension_type, key, orm_descriptor, model_type_hints, model_name
)
@@ -262,6 +274,9 @@ def parse_type_from_element(elem: ElementType) -> FieldDefinition:
return FieldDefinition.from_annotation(elem.mapper.class_)
+ if isinstance(elem, CompositeProperty):
+ return FieldDefinition.from_annotation(elem.composite_class)
+
raise ImproperlyConfiguredException(
f"Unable to parse type from element '{elem}'. Consider adding a type hint.",
)
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py b/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
@@ -3,8 +3,8 @@
from typing import Any, Callable, Dict, List, Tuple
import pytest
-from sqlalchemy import ForeignKey, String
-from sqlalchemy.orm import DeclarativeBase, Mapped, declared_attr, mapped_column, relationship
+from sqlalchemy import Column, ForeignKey, Integer, String, Table
+from sqlalchemy.orm import DeclarativeBase, Mapped, composite, declared_attr, mapped_column, relationship
from typing_extensions import Annotated
from litestar import get, post
@@ -328,6 +328,121 @@ def get_handler(data: Circle) -> Circle:
assert module.DIAMETER == 10
+async def test_dto_with_composite_map() -> None:
+ @dataclass
+ class Point:
+ x: int
+ y: int
+
+ class Vertex1(Base):
+ start: Mapped[Point] = composite(mapped_column("x1"), mapped_column("y1"))
+ end: Mapped[Point] = composite(mapped_column("x2"), mapped_column("y2"))
+
+ dto = SQLAlchemyDTO[Vertex1]
+
+ @post(dto=dto, signature_namespace={"Vertex": Vertex1})
+ def post_handler(data: Vertex1) -> Vertex1:
+ return data
+
+ with create_test_client(route_handlers=[post_handler]) as client:
+ response = client.post(
+ "/",
+ json={
+ "id": "1",
+ "start": {"x": 10, "y": 20},
+ "end": {"x": 1, "y": 2},
+ },
+ )
+ assert response.json() == {
+ "id": "1",
+ "start": {"x": 10, "y": 20},
+ "end": {"x": 1, "y": 2},
+ }
+
+
+async def test_dto_with_composite_map_using_explicit_columns() -> None:
+ @dataclass
+ class Point:
+ x: int
+ y: int
+
+ class Vertex2(Base):
+ x1: Mapped[int]
+ y1: Mapped[int]
+ x2: Mapped[int]
+ y2: Mapped[int]
+
+ start: Mapped[Point] = composite("x1", "y1")
+ end: Mapped[Point] = composite("x2", "y2")
+
+ dto = SQLAlchemyDTO[Vertex2]
+
+ @post(dto=dto, signature_namespace={"Vertex": Vertex2})
+ def post_handler(data: Vertex2) -> Vertex2:
+ return data
+
+ with create_test_client(route_handlers=[post_handler]) as client:
+ response = client.post(
+ "/",
+ json={
+ "id": "1",
+ "start": {"x": 10, "y": 20},
+ "end": {"x": 1, "y": 2},
+ },
+ )
+ assert response.json() == {
+ "id": "1",
+ "start": {"x": 10, "y": 20},
+ "end": {"x": 1, "y": 2},
+ }
+
+
+async def test_dto_with_composite_map_using_hybrid_imperative_mapping() -> None:
+ @dataclass
+ class Point:
+ x: int
+ y: int
+
+ table = Table(
+ "vertices2",
+ Base.metadata,
+ Column("id", String, primary_key=True),
+ Column("x1", Integer),
+ Column("y1", Integer),
+ Column("x2", Integer),
+ Column("y2", Integer),
+ )
+
+ class Vertex3(Base):
+ __table__ = table
+
+ id: Mapped[str]
+
+ start = composite(Point, table.c.x1, table.c.y1)
+ end = composite(Point, table.c.x2, table.c.y2)
+
+ dto = SQLAlchemyDTO[Vertex3]
+
+ @post(dto=dto, signature_namespace={"Vertex": Vertex3})
+ def post_handler(data: Vertex3) -> Vertex3:
+ return data
+
+ with create_test_client(route_handlers=[post_handler]) as client:
+ response = client.post(
+ "/",
+ json={
+ "id": "1",
+ "start": {"x": 10, "y": 20},
+ "end": {"x": 1, "y": 2},
+ },
+ )
+ assert response.json() == {
+ "id": "1",
+ "start": {"x": 10, "y": 20},
+ "end": {"x": 1, "y": 2},
+ }
+
+
async def test_field_with_sequence_default(create_module: Callable[[str], ModuleType]) -> None:
module = create_module(
"""
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-08-05T10:02:09 |
litestar-org/litestar | 2,127 | litestar-org__litestar-2127 | [
"2125",
"4321",
"1234"
] | 2be2309688652b125dcbd921da54182950ae0aa0 | diff --git a/litestar/dto/_backend.py b/litestar/dto/_backend.py
--- a/litestar/dto/_backend.py
+++ b/litestar/dto/_backend.py
@@ -583,13 +583,14 @@ def _transfer_instance_data(
should_use_serialization_name = is_data_field and not is_dto_data_type
source_name = field_definition.serialization_name if should_use_serialization_name else field_definition.name
- source_has_value = (
+ if not is_data_field:
+ if field_definition.is_excluded:
+ continue
+ elif not (
source_name in source_instance
if isinstance(source_instance, Mapping)
else hasattr(source_instance, source_name)
- )
-
- if (is_data_field and not source_has_value) or (not is_data_field and field_definition.is_excluded):
+ ):
continue
transfer_type = field_definition.transfer_type
| diff --git a/tests/unit/test_dto/test_factory/test_backends/test_backends.py b/tests/unit/test_dto/test_factory/test_backends/test_backends.py
--- a/tests/unit/test_dto/test_factory/test_backends/test_backends.py
+++ b/tests/unit/test_dto/test_factory/test_backends/test_backends.py
@@ -4,6 +4,7 @@
from dataclasses import dataclass, field
from types import ModuleType
from typing import TYPE_CHECKING, Callable, List, Optional
+from unittest.mock import MagicMock
import pytest
from msgspec import Struct, to_builtins
@@ -294,6 +295,37 @@ def test_backend_encode_collection_data(
assert encode_json(data) == COLLECTION_RAW
+def test_transfer_only_touches_included_attributes() -> None:
+ """Ensure attribute that are not included are never touched in any way during
+ transfer.
+
+ https://github.com/litestar-org/litestar/issues/2125
+ """
+ mock = MagicMock()
+
+ @dataclass()
+ class Foo:
+ id: str
+ bar: str = ""
+
+ class Factory(DataclassDTO):
+ config = DTOConfig(include={"excluded"})
+
+ backend = DTOBackend(
+ handler_id="test",
+ dto_factory=Factory,
+ field_definition=TransferDTOFieldDefinition.from_annotation(Foo),
+ model_type=Foo,
+ wrapper_attribute_name=None,
+ is_data_field=False,
+ )
+
+ Foo.bar = property(fget=lambda s: mock(return_value=""), fset=lambda s, v: None) # type: ignore[assignment]
+
+ backend.encode_data(Foo(id="1"))
+ assert mock.call_count == 0
+
+
def test_parse_model_nested_exclude(create_module: Callable[[str], ModuleType]) -> None:
module = create_module(
"""
| Bug: SQA DTO touches ignored properties triggering lazy loading
### Description
The SQA DTO engine doesn't make use of ignored properties to skip touching SQA object properties, in particular lazy loaded properties that get loaded when the DTO touches them.
As a minimal (but not complete) example.
```python
class Fund(Base):
name: Mapped[str]
charges: Mapped[list[Charge]] = relationship(lazy=True, ...)
FundDTO = SQLAlchemyDTO[
Annotated[
Fund,
DTOConfig(include={"name"}),
],
]
@get("/fund", dto=FundDTO)
def fetch_one_fund(fund_number: str, *, db_session: Session) -> Fund:
if fund := db_session.get(Fund, fund_number):
return fund
raise NotFoundException
```
Despite explicitly including only the `"name"` property and implicitly ignoring the `"charges"` property, `charges` still gets loaded in. The DTO returned object is just `{"name": ...}`. (I only noticed this because the `charges` table is quite large and the route gets quote slow.)
This currently be alleviated by explicitly specifying `noload` for ignored properties.
```python
if fund := db_session.get(Fund, fund_number, options=[noload(Fund.charges)]):
...
```
But doesn't seem ideal, and instead the DTO should only be touching non-ignored properties.
### URL to code causing the issue
_No response_
### MCVE
_No response_
### Steps to reproduce
_No response_
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.0.0b4
### Platform
- [X] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2125">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2125/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2125/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
|
I agree. Do you want to submit a PR? | 2023-08-06T11:03:39 |
litestar-org/litestar | 2,139 | litestar-org__litestar-2139 | [
"2137"
] | 9f98636d8a2d3c22ce260b37a1543eee9e74bbc8 | diff --git a/litestar/contrib/sqlalchemy/plugins/init/config/common.py b/litestar/contrib/sqlalchemy/plugins/init/config/common.py
--- a/litestar/contrib/sqlalchemy/plugins/init/config/common.py
+++ b/litestar/contrib/sqlalchemy/plugins/init/config/common.py
@@ -186,7 +186,7 @@ def create_engine(self) -> EngineT:
engine_config = self.engine_config_dict
try:
self.engine_instance = self.create_engine_callable(self.connection_string, **engine_config)
- except ValueError:
+ except TypeError:
# likely due to a dialect that doesn't support json type
del engine_config["json_deserializer"]
del engine_config["json_serializer"]
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_common.py b/tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_common.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_common.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_init_plugin/test_common.py
@@ -66,7 +66,7 @@ def test_create_engine_if_no_engine_instance_or_connection_string_provided(
config.create_engine()
-def test_call_create_engine_callable_value_error_handling(
+def test_call_create_engine_callable_type_error_handling(
config_cls: type[SQLAlchemySyncConfig | SQLAlchemySyncConfig], monkeypatch: MonkeyPatch
) -> None:
"""If the dialect doesn't support JSON types, we get a ValueError.
@@ -78,7 +78,7 @@ def side_effect(*args: Any, **kwargs: Any) -> None:
nonlocal call_count
call_count += 1
if call_count == 1:
- raise ValueError()
+ raise TypeError()
config = config_cls(connection_string="sqlite://")
create_engine_callable_mock = MagicMock(side_effect=side_effect)
| Bug: Handle dialect that doesn't support JSON type
### Description
I'm using a custom dialect that doesn't support JSON types. As you can see [here](https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/engine/create.py#L680), SQLAlchemy throws a `TypeError` when it receives invalid arguments on `create_engine`.
Litestar anticipates this error can happen, but it handles the wrong exception type (`ValueError` instead of `TypeError`).
https://github.com/litestar-org/litestar/blob/9f98636d8a2d3c22ce260b37a1543eee9e74bbc8/litestar/contrib/sqlalchemy/plugins/init/config/common.py#L187-L193
### URL to code causing the issue
_No response_
### MCVE
```python
# Your MCVE code here
```
### Steps to reproduce
```bash
1. Install a dialect that doesn't support JSON
2. Setup the SQLAlchemy plugin to use that dialect
3. Start the Litestar app
```
### Screenshots
_No response_
### Logs
```bash
Using Litestar app from env: 'app.main:app'
...
INFO: Started server process [55936]
INFO: Waiting for application startup.
ERROR: Traceback (most recent call last):
File "<dev>/.venv/lib/python3.11/site-packages/litestar/app.py", line 541, in lifespan
await self._call_lifespan_hook(hook)
File "<dev>/.venv/lib/python3.11/site-packages/litestar/app.py", line 514, in _call_lifespan_hook
ret = hook(self) if inspect.signature(hook).parameters else hook() # type: ignore
^^^^^^^^^^
File "<dev>/.venv/lib/python3.11/site-packages/litestar/contrib/sqlalchemy/plugins/init/config/common.py", line 252, in update_app_state
app.state.update(self.create_app_state_items())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<dev>/.venv/lib/python3.11/site-packages/litestar/contrib/sqlalchemy/plugins/init/config/common.py", line 242, in create_app_state_items
self.engine_app_state_key: self.create_engine(),
^^^^^^^^^^^^^^^^^^^^
File "<dev>/.venv/lib/python3.11/site-packages/litestar/contrib/sqlalchemy/plugins/init/config/common.py", line 188, in create_engine
self.engine_instance = self.create_engine_callable(self.connection_string, **engine_config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 2, in create_engine
File "<dev>/.venv/lib/python3.11/site-packages/sqlalchemy/util/deprecations.py", line 281, in warned
return fn(*args, **kwargs) # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^^^
File "<dev>/.venv/lib/python3.11/site-packages/sqlalchemy/engine/create.py", line 680, in create_engine
raise TypeError(
TypeError: Invalid argument(s) 'json_deserializer','json_serializer' sent to create_engine(), using configuration BigQueryDialect/QueuePool/Engine. Please check that the keyword arguments are appropriate for this combination of components.
```
### Litestar Version
2.0.0rc1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2137">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2137/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2137/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| What DB engine are you using here? | 2023-08-08T15:06:07 |
litestar-org/litestar | 2,144 | litestar-org__litestar-2144 | [
"4321",
"1234"
] | 89bb310aa9fe1246bc65c97eb22d9ca4c6cfbbbc | diff --git a/litestar/dto/_backend.py b/litestar/dto/_backend.py
--- a/litestar/dto/_backend.py
+++ b/litestar/dto/_backend.py
@@ -46,11 +46,11 @@ class DTOBackend:
"handler_id",
"is_data_field",
"model_type",
+ "override_serialization_name",
"parsed_field_definitions",
"reverse_name_map",
"transfer_model_type",
"wrapper_attribute_name",
- "is_dto_data_type",
)
_seen_model_names: ClassVar[set[str]] = set()
@@ -88,12 +88,11 @@ def __init__(
model_name=model_type.__name__, field_definitions=self.parsed_field_definitions
)
self.dto_data_type: type[DTOData] | None = None
- self.is_dto_data_type: bool = False
+ self.override_serialization_name: bool = False
if field_definition.is_subclass_of(DTOData):
self.dto_data_type = field_definition.annotation
annotation = self.field_definition.inner_types[0].annotation
- self.is_dto_data_type = True
else:
annotation = field_definition.annotation
@@ -245,28 +244,33 @@ def populate_data_from_builtins(self, builtins: Any, asgi_connection: ASGIConnec
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
- is_dto_data_type=self.is_dto_data_type,
+ override_serialization_name=self.override_serialization_name,
),
)
return self.transfer_data_from_builtins(self.parse_builtins(builtins, asgi_connection))
- def transfer_data_from_builtins(self, builtins: Any) -> Any:
+ def transfer_data_from_builtins(self, builtins: Any, override_serialization_name: bool = False) -> Any:
"""Populate model instance from builtin types.
Args:
builtins: Builtin type.
+ override_serialization_name: Use the original field names, used when creating
+ an instance using `DTOData.create_instance`
Returns:
Instance or collection of ``model_type`` instances.
"""
- return _transfer_data(
+ self.override_serialization_name = override_serialization_name
+ data = _transfer_data(
destination_type=self.model_type,
source_data=builtins,
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
- is_dto_data_type=self.is_dto_data_type,
+ override_serialization_name=self.override_serialization_name,
)
+ self.override_serialization_name = False
+ return data
def populate_data_from_raw(self, raw: bytes, asgi_connection: ASGIConnection) -> Any:
"""Parse raw bytes into instance of `model_type`.
@@ -287,7 +291,7 @@ def populate_data_from_raw(self, raw: bytes, asgi_connection: ASGIConnection) ->
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
- is_dto_data_type=self.is_dto_data_type,
+ override_serialization_name=self.override_serialization_name,
),
)
return _transfer_data(
@@ -296,7 +300,7 @@ def populate_data_from_raw(self, raw: bytes, asgi_connection: ASGIConnection) ->
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
- is_dto_data_type=self.is_dto_data_type,
+ override_serialization_name=self.override_serialization_name,
)
def encode_data(self, data: Any) -> LitestarEncodableType:
@@ -315,7 +319,7 @@ def encode_data(self, data: Any) -> LitestarEncodableType:
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
- is_dto_data_type=self.is_dto_data_type,
+ override_serialization_name=self.override_serialization_name,
)
setattr(
data,
@@ -332,7 +336,7 @@ def encode_data(self, data: Any) -> LitestarEncodableType:
field_definitions=self.parsed_field_definitions,
field_definition=self.field_definition,
is_data_field=self.is_data_field,
- is_dto_data_type=self.is_dto_data_type,
+ override_serialization_name=self.override_serialization_name,
),
)
@@ -521,7 +525,7 @@ def _transfer_data(
field_definitions: tuple[TransferDTOFieldDefinition, ...],
field_definition: FieldDefinition,
is_data_field: bool,
- is_dto_data_type: bool,
+ override_serialization_name: bool,
) -> Any:
"""Create instance or iterable of instances of ``destination_type``.
@@ -531,7 +535,8 @@ def _transfer_data(
field_definitions: model field definitions.
field_definition: the parsed type that represents the handler annotation for which the DTO is being applied.
is_data_field: whether the DTO is being applied to a ``data`` field.
- is_dto_data_type: whether the field definition is an `DTOData` type.
+ override_serialization_name: Use the original field names, used when creating
+ an instance using `DTOData.create_instance`
Returns:
Data parsed into ``destination_type``.
@@ -544,7 +549,7 @@ def _transfer_data(
field_definitions=field_definitions,
field_definition=field_definition.inner_types[0],
is_data_field=is_data_field,
- is_dto_data_type=is_dto_data_type,
+ override_serialization_name=override_serialization_name,
)
for item in source_data
)
@@ -554,7 +559,7 @@ def _transfer_data(
source_instance=source_data,
field_definitions=field_definitions,
is_data_field=is_data_field,
- is_dto_data_type=is_dto_data_type,
+ override_serialization_name=override_serialization_name,
)
@@ -563,7 +568,7 @@ def _transfer_instance_data(
source_instance: Any,
field_definitions: tuple[TransferDTOFieldDefinition, ...],
is_data_field: bool,
- is_dto_data_type: bool,
+ override_serialization_name: bool,
) -> Any:
"""Create instance of ``destination_type`` with data from ``source_instance``.
@@ -572,7 +577,8 @@ def _transfer_instance_data(
source_instance: primitive data that has been parsed and validated via the backend.
field_definitions: model field definitions.
is_data_field: whether the given field is a 'data' kwarg field.
- is_dto_data_type: whether the field definition is an `DTOData` type.
+ override_serialization_name: Use the original field names, used when creating
+ an instance using `DTOData.create_instance`
Returns:
Data parsed into ``model_type``.
@@ -580,7 +586,7 @@ def _transfer_instance_data(
unstructured_data = {}
for field_definition in field_definitions:
- should_use_serialization_name = is_data_field and not is_dto_data_type
+ should_use_serialization_name = not override_serialization_name and is_data_field
source_name = field_definition.serialization_name if should_use_serialization_name else field_definition.name
if not is_data_field:
@@ -609,7 +615,7 @@ def _transfer_instance_data(
transfer_type=transfer_type,
nested_as_dict=destination_type is dict,
is_data_field=is_data_field,
- is_dto_data_type=is_dto_data_type,
+ override_serialization_name=override_serialization_name,
)
return destination_type(**unstructured_data)
@@ -620,7 +626,7 @@ def _transfer_type_data(
transfer_type: TransferType,
nested_as_dict: bool,
is_data_field: bool,
- is_dto_data_type: bool,
+ override_serialization_name: bool,
) -> Any:
if isinstance(transfer_type, SimpleType) and transfer_type.nested_field_info:
if nested_as_dict:
@@ -635,7 +641,7 @@ def _transfer_type_data(
source_instance=source_value,
field_definitions=transfer_type.nested_field_info.field_definitions,
is_data_field=is_data_field,
- is_dto_data_type=is_dto_data_type,
+ override_serialization_name=override_serialization_name,
)
if isinstance(transfer_type, UnionType) and transfer_type.has_nested:
@@ -643,7 +649,7 @@ def _transfer_type_data(
transfer_type=transfer_type,
source_value=source_value,
is_data_field=is_data_field,
- is_dto_data_type=is_dto_data_type,
+ override_serialization_name=override_serialization_name,
)
if isinstance(transfer_type, CollectionType):
@@ -654,7 +660,7 @@ def _transfer_type_data(
transfer_type=transfer_type.inner_type,
nested_as_dict=False,
is_data_field=is_data_field,
- is_dto_data_type=is_dto_data_type,
+ override_serialization_name=override_serialization_name,
)
for item in source_value
)
@@ -667,7 +673,7 @@ def _transfer_nested_union_type_data(
transfer_type: UnionType,
source_value: Any,
is_data_field: bool,
- is_dto_data_type: bool,
+ override_serialization_name: bool,
) -> Any:
for inner_type in transfer_type.inner_types:
if isinstance(inner_type, CompositeType):
@@ -684,7 +690,7 @@ def _transfer_nested_union_type_data(
source_instance=source_value,
field_definitions=inner_type.nested_field_info.field_definitions,
is_data_field=is_data_field,
- is_dto_data_type=is_dto_data_type,
+ override_serialization_name=override_serialization_name,
)
return source_value
diff --git a/litestar/dto/data_structures.py b/litestar/dto/data_structures.py
--- a/litestar/dto/data_structures.py
+++ b/litestar/dto/data_structures.py
@@ -32,7 +32,9 @@ def create_instance(self, **kwargs: Any) -> T:
data = dict(self._data_as_builtins)
for k, v in kwargs.items():
_set_nested_dict_value(data, k.split("__"), v)
- return self._backend.transfer_data_from_builtins(data) # type:ignore[no-any-return]
+ return self._backend.transfer_data_from_builtins( # type:ignore[no-any-return]
+ data, override_serialization_name=True
+ )
def update_instance(self, instance: T, **kwargs: Any) -> T:
"""Update an instance with the DTO validated data.
| diff --git a/tests/unit/test_dto/test_factory/test_backends/test_utils.py b/tests/unit/test_dto/test_factory/test_backends/test_utils.py
--- a/tests/unit/test_dto/test_factory/test_backends/test_utils.py
+++ b/tests/unit/test_dto/test_factory/test_backends/test_utils.py
@@ -57,7 +57,7 @@ def test_transfer_nested_union_type_data_raises_runtime_error_for_complex_union(
transfer_type=transfer_type,
is_data_field=True,
source_value=1,
- is_dto_data_type=True,
+ override_serialization_name=True,
)
diff --git a/tests/unit/test_dto/test_factory/test_integration.py b/tests/unit/test_dto/test_factory/test_integration.py
--- a/tests/unit/test_dto/test_factory/test_integration.py
+++ b/tests/unit/test_dto/test_factory/test_integration.py
@@ -214,12 +214,26 @@ def handler(data: DTOData[User] = Body(media_type=RequestEncodingType.URL_ENCODE
assert response.json() == {"name": "John", "age": 42, "read_only": "read-only"}
+RenamedBarT = TypeVar("RenamedBarT")
+
+
@dataclass
-class RenamedBar:
+class GenericRenamedBar(Generic[RenamedBarT]):
bar: str
+ spam_bar: RenamedBarT
foo_foo: str
+@dataclass
+class InnerBar:
+ best_greeting: str
+
+
+@dataclass
+class RenamedBar(GenericRenamedBar[InnerBar]):
+ pass
+
+
def test_dto_data_create_instance_renamed_fields() -> None:
@post(
dto=DataclassDTO[Annotated[RenamedBar, DTOConfig(exclude={"foo_foo"}, rename_strategy="camel")]],
@@ -229,14 +243,15 @@ def handler(data: DTOData[RenamedBar]) -> RenamedBar:
assert isinstance(data, DTOData)
result = data.create_instance(foo_foo="world")
assert result.foo_foo == "world"
+ assert result.spam_bar.best_greeting == "hello world"
return result
with create_test_client(
route_handlers=[handler], signature_namespace={"NestedFoo": NestedFoo, "NestingBar": NestingBar}
) as client:
- response = client.post("/", json={"bar": "hello"})
+ response = client.post("/", json={"bar": "hello", "spamBar": {"bestGreeting": "hello world"}})
assert response.status_code == 201
- assert response.json() == {"bar": "hello", "fooFoo": "world"}
+ assert response.json() == {"bar": "hello", "fooFoo": "world", "spamBar": {"bestGreeting": "hello world"}}
def test_dto_data_with_patch_request() -> None:
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-08-10T11:00:03 |
litestar-org/litestar | 2,153 | litestar-org__litestar-2153 | [
"2147",
"4321",
"1234"
] | edbe1c9389fa7da402c64f889b29d7745961f8aa | diff --git a/litestar/cli/commands/core.py b/litestar/cli/commands/core.py
--- a/litestar/cli/commands/core.py
+++ b/litestar/cli/commands/core.py
@@ -10,7 +10,7 @@
import uvicorn
from rich.tree import Tree
-from litestar.cli._utils import RICH_CLICK_INSTALLED, console, show_app_info
+from litestar.cli._utils import RICH_CLICK_INSTALLED, LitestarEnv, console, show_app_info
from litestar.routes import HTTPRoute, WebSocketRoute
from litestar.utils.helpers import unwrap_partial
@@ -118,7 +118,7 @@ def run_command(
if pdb:
ctx.obj.app.pdb_on_exception = True
- env = ctx.obj
+ env: LitestarEnv = ctx.obj
app = env.app
reload_dirs = env.reload_dirs or reload_dir
diff --git a/litestar/middleware/exceptions/middleware.py b/litestar/middleware/exceptions/middleware.py
--- a/litestar/middleware/exceptions/middleware.py
+++ b/litestar/middleware/exceptions/middleware.py
@@ -15,6 +15,7 @@
from litestar.middleware.exceptions._debug_response import create_debug_response
from litestar.serialization import encode_json
from litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
+from litestar.utils.deprecation import warn_deprecation
__all__ = ("ExceptionHandlerMiddleware", "ExceptionResponseContent", "create_exception_response")
@@ -147,17 +148,33 @@ class ExceptionHandlerMiddleware:
This used in multiple layers of Litestar.
"""
- def __init__(self, app: ASGIApp, debug: bool, exception_handlers: ExceptionHandlersMap) -> None:
+ def __init__(self, app: ASGIApp, debug: bool | None, exception_handlers: ExceptionHandlersMap) -> None:
"""Initialize ``ExceptionHandlerMiddleware``.
Args:
app: The ``next`` ASGI app to call.
- debug: Whether ``debug`` mode is enabled
+ debug: Whether ``debug`` mode is enabled. Deprecated. Debug mode will be inferred from the request scope
exception_handlers: A dictionary mapping status codes and/or exception types to handler functions.
+
+ .. deprecated:: 2.0.0
+ The ``debug`` parameter is deprecated. It will be inferred from the request scope
"""
self.app = app
self.exception_handlers = exception_handlers
self.debug = debug
+ if debug is not None:
+ warn_deprecation(
+ "2.0.0",
+ deprecated_name="debug",
+ kind="parameter",
+ info="Debug mode will be inferred from the request scope",
+ )
+
+ self._get_debug = self._get_debug_scope if debug is None else lambda *a: debug
+
+ @staticmethod
+ def _get_debug_scope(scope: Scope) -> bool:
+ return scope["app"].debug
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""ASGI-callable.
@@ -249,7 +266,7 @@ def default_http_exception_handler(self, request: Request, exc: Exception) -> Re
An HTTP response.
"""
status_code = getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR)
- if status_code == HTTP_500_INTERNAL_SERVER_ERROR and self.debug:
+ if status_code == HTTP_500_INTERNAL_SERVER_ERROR and self._get_debug_scope(request.scope):
return create_debug_response(request=request, exc=exc)
return create_exception_response(request=request, exc=exc)
@@ -265,6 +282,7 @@ def handle_exception_logging(self, logger: Logger, logging_config: BaseLoggingCo
None
"""
if (
- logging_config.log_exceptions == "always" or (logging_config.log_exceptions == "debug" and self.debug)
+ logging_config.log_exceptions == "always"
+ or (logging_config.log_exceptions == "debug" and self._get_debug_scope(scope))
) and logging_config.exception_logging_handler:
logging_config.exception_logging_handler(logger, scope, format_exception(*exc_info()))
| diff --git a/tests/unit/test_middleware/test_exception_handler_middleware.py b/tests/unit/test_middleware/test_exception_handler_middleware.py
--- a/tests/unit/test_middleware/test_exception_handler_middleware.py
+++ b/tests/unit/test_middleware/test_exception_handler_middleware.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, Callable, Optional
import pytest
from _pytest.capture import CaptureFixture
@@ -7,17 +7,14 @@
from structlog.testing import capture_logs
from litestar import Litestar, Request, Response, get
-from litestar.exceptions import (
- HTTPException,
- InternalServerException,
- ValidationException,
-)
+from litestar.exceptions import HTTPException, InternalServerException, ValidationException
from litestar.logging.config import LoggingConfig, StructLoggingConfig
from litestar.middleware.exceptions import ExceptionHandlerMiddleware
from litestar.middleware.exceptions.middleware import get_exception_handler
from litestar.status_codes import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
from litestar.testing import TestClient, create_test_client
from litestar.types import ExceptionHandlersMap
+from litestar.types.asgi_types import HTTPScope
if TYPE_CHECKING:
from _pytest.logging import LogCaptureFixture
@@ -30,13 +27,26 @@ async def dummy_app(scope: Any, receive: Any, send: Any) -> None:
return None
-middleware = ExceptionHandlerMiddleware(dummy_app, False, {})
[email protected]()
+def app() -> Litestar:
+ return Litestar()
+
+
[email protected]()
+def middleware() -> ExceptionHandlerMiddleware:
+ return ExceptionHandlerMiddleware(dummy_app, False, {})
+
+
[email protected]()
+def scope(create_scope: Callable[..., HTTPScope], app: Litestar) -> HTTPScope:
+ return create_scope(app=app)
-def test_default_handle_http_exception_handling_extra_object() -> None:
+def test_default_handle_http_exception_handling_extra_object(
+ scope: HTTPScope, middleware: ExceptionHandlerMiddleware
+) -> None:
response = middleware.default_http_exception_handler(
- Request(scope={"type": "http", "method": "GET"}), # type: ignore
- HTTPException(detail="litestar_exception", extra={"key": "value"}),
+ Request(scope=scope), HTTPException(detail="litestar_exception", extra={"key": "value"})
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.content == {
@@ -46,28 +56,31 @@ def test_default_handle_http_exception_handling_extra_object() -> None:
}
-def test_default_handle_http_exception_handling_extra_none() -> None:
+def test_default_handle_http_exception_handling_extra_none(
+ scope: HTTPScope, middleware: ExceptionHandlerMiddleware
+) -> None:
response = middleware.default_http_exception_handler(
- Request(scope={"type": "http", "method": "GET"}), # type: ignore
- HTTPException(detail="litestar_exception"),
+ Request(scope=scope), HTTPException(detail="litestar_exception")
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.content == {"detail": "Internal Server Error", "status_code": 500}
-def test_default_handle_litestar_http_exception_handling() -> None:
+def test_default_handle_litestar_http_exception_handling(
+ scope: HTTPScope, middleware: ExceptionHandlerMiddleware
+) -> None:
response = middleware.default_http_exception_handler(
- Request(scope={"type": "http", "method": "GET"}), # type: ignore
- HTTPException(detail="litestar_exception"),
+ Request(scope=scope), HTTPException(detail="litestar_exception")
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.content == {"detail": "Internal Server Error", "status_code": 500}
-def test_default_handle_litestar_http_exception_extra_list() -> None:
+def test_default_handle_litestar_http_exception_extra_list(
+ scope: HTTPScope, middleware: ExceptionHandlerMiddleware
+) -> None:
response = middleware.default_http_exception_handler(
- Request(scope={"type": "http", "method": "GET"}), # type: ignore
- HTTPException(detail="litestar_exception", extra=["extra-1", "extra-2"]),
+ Request(scope=scope), HTTPException(detail="litestar_exception", extra=["extra-1", "extra-2"])
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.content == {
@@ -77,22 +90,21 @@ def test_default_handle_litestar_http_exception_extra_list() -> None:
}
-def test_default_handle_starlette_http_exception_handling() -> None:
+def test_default_handle_starlette_http_exception_handling(
+ scope: HTTPScope, middleware: ExceptionHandlerMiddleware
+) -> None:
response = middleware.default_http_exception_handler(
- Request(scope={"type": "http", "method": "GET"}), # type: ignore
+ Request(scope=scope),
StarletteHTTPException(detail="litestar_exception", status_code=HTTP_500_INTERNAL_SERVER_ERROR),
)
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
- assert response.content == {
- "detail": "Internal Server Error",
- "status_code": 500,
- }
+ assert response.content == {"detail": "Internal Server Error", "status_code": 500}
-def test_default_handle_python_http_exception_handling() -> None:
- response = middleware.default_http_exception_handler(
- Request(scope={"type": "http", "method": "GET"}), AttributeError("oops") # type: ignore
- )
+def test_default_handle_python_http_exception_handling(
+ scope: HTTPScope, middleware: ExceptionHandlerMiddleware
+) -> None:
+ response = middleware.default_http_exception_handler(Request(scope=scope), AttributeError("oops"))
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
assert response.content == {
"detail": "Internal Server Error",
@@ -307,3 +319,24 @@ def handler() -> None:
assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
mock_post_mortem.assert_called_once()
+
+
+def test_get_debug_from_scope(get_logger: "GetLogger", caplog: "LogCaptureFixture") -> None:
+ @get("/test")
+ def handler() -> None:
+ raise ValueError("Test debug exception")
+
+ app = Litestar([handler], debug=False)
+ app.debug = True
+
+ with caplog.at_level("ERROR", "litestar"), TestClient(app=app) as client:
+ client.app.logger = get_logger("litestar")
+ response = client.get("/test")
+
+ assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
+ assert "Test debug exception" in response.text
+ assert len(caplog.records) == 1
+ assert caplog.records[0].levelname == "ERROR"
+ assert caplog.records[0].message.startswith(
+ "exception raised on http connection to route /test\n\nTraceback (most recent call last):\n"
+ )
| Bug: 2.0.0rc1: `--debug` CLI flag not respected
### Description
Running with --debug does not work. Running with Litestart(..., debug=True) does.
### URL to code causing the issue
https://github.com/Mattwmaster58/mac-bid-utils
### MCVE
```python
from litestar import Litestar, get
@get("/")
async def perch(should_raise_error_that_seen_in_debug: bool) -> str:
return "helo"
app = Litestar(route_handlers=[perch])
```
### Steps to reproduce
1. Run with `litestar run --debug`
2. Go to root route to trigger what should be an error that's printed with a traceback to the console.
3. Instead, only a single line is shown
I am having this issue in my own app and the issue disappears (ie, logs properly shown) when I comment large chunks of arguments to the Litestar instance that seem completely unrelated, I will investigate further. As of d3318ae on my repo, --debug IS working.
### Screenshots
_No response_
### Logs
```bash
(.venv) ➜ delete_me_litestar_debug_repro litestar run -p 3214 --debug
Using Litestar app from app:app
┌──────────────────────────────┬──────────────────────┐
│ Litestar version │ 2.0.0 │
│ Debug mode │ Enabled │
│ Python Debugger on exception │ Disabled │
│ CORS │ Disabled │
│ CSRF │ Disabled │
│ OpenAPI │ Enabled path=/schema │
│ Compression │ Disabled │
└──────────────────────────────┴──────────────────────┘
INFO: Started server process [387087]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:3214 (Press CTRL+C to quit)
INFO: 127.0.0.1:47810 - "GET / HTTP/1.1" 400 Bad Request
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [387087]
```
### Litestar Version
2.0.0rc1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
#### Other
Some discussion on discord about this: https://discord.com/channels/919193495116337154/1138671763190972416
Per some discussion in the thread, this seems to be a separate issue than #1804
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2147">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2147/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2147/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
|
I agree. Do you want to submit a PR? | 2023-08-12T10:53:09 |
litestar-org/litestar | 2,170 | litestar-org__litestar-2170 | [
"4321",
"1234"
] | 3b0becb8fdc6cf9feb737fe5c15fa8aa9b81ed34 | diff --git a/litestar/contrib/sqlalchemy/dto.py b/litestar/contrib/sqlalchemy/dto.py
--- a/litestar/contrib/sqlalchemy/dto.py
+++ b/litestar/contrib/sqlalchemy/dto.py
@@ -1,8 +1,8 @@
from __future__ import annotations
-from dataclasses import replace
+from dataclasses import asdict, replace
from functools import singledispatchmethod
-from typing import TYPE_CHECKING, Collection, Generic, Optional, TypeVar
+from typing import TYPE_CHECKING, ClassVar, Collection, Generic, Optional, TypeVar
from sqlalchemy import Column, inspect, orm, sql
from sqlalchemy.ext.associationproxy import AssociationProxy, AssociationProxyExtensionType
@@ -21,6 +21,7 @@
)
from litestar.dto.base_dto import AbstractDTO
+from litestar.dto.config import DTOConfig, SQLAlchemyDTOConfig
from litestar.dto.data_structures import DTOFieldDefinition
from litestar.dto.field import DTO_FIELD_META_KEY, DTOField, Mark
from litestar.exceptions import ImproperlyConfiguredException
@@ -44,6 +45,20 @@
class SQLAlchemyDTO(AbstractDTO[T], Generic[T]):
"""Support for domain modelling with SQLAlchemy."""
+ config: ClassVar[SQLAlchemyDTOConfig]
+
+ @staticmethod
+ def _ensure_sqla_dto_config(config: DTOConfig | SQLAlchemyDTOConfig) -> SQLAlchemyDTOConfig:
+ if not isinstance(config, SQLAlchemyDTOConfig):
+ return SQLAlchemyDTOConfig(**asdict(config))
+
+ return config
+
+ def __init_subclass__(cls, **kwargs: Any) -> None:
+ super().__init_subclass__(**kwargs)
+ if hasattr(cls, "config"):
+ cls.config = cls._ensure_sqla_dto_config(cls.config)
+
@singledispatchmethod
@classmethod
def handle_orm_descriptor(
@@ -187,25 +202,54 @@ def generate_field_definitions(cls, model_type: type[DeclarativeBase]) -> Genera
namespace = {**SQLA_NS, **{m.class_.__name__: m.class_ for m in mapper.registry.mappers if m is not mapper}}
model_type_hints = cls.get_model_type_hints(model_type, namespace=namespace)
model_name = model_type.__name__
+ include_implicit_fields = cls.config.include_implicit_fields
# the same hybrid property descriptor can be included in `all_orm_descriptors` multiple times, once
# for each method name it is bound to. We only need to see it once, so track views of it here.
seen_hybrid_descriptors: set[hybrid_property] = set()
- skipped_columns: set[str] = set()
+ skipped_descriptors: set[str] = set()
for composite_property in mapper.composites:
for attr in composite_property.attrs:
if isinstance(attr, (MappedColumn, Column)):
- skipped_columns.add(attr.name)
+ skipped_descriptors.add(attr.name)
elif isinstance(attr, str):
- skipped_columns.add(attr)
+ skipped_descriptors.add(attr)
for key, orm_descriptor in mapper.all_orm_descriptors.items():
- if isinstance(orm_descriptor, hybrid_property):
+ if is_hybrid_property := isinstance(orm_descriptor, hybrid_property):
if orm_descriptor in seen_hybrid_descriptors:
continue
seen_hybrid_descriptors.add(orm_descriptor)
- if key in skipped_columns:
+ if key in skipped_descriptors:
+ continue
+
+ should_skip_descriptor = False
+ dto_field: DTOField | None = None
+ if hasattr(orm_descriptor, "property"):
+ dto_field = orm_descriptor.property.info.get(DTO_FIELD_META_KEY) # pyright: ignore
+
+ # Case 1
+ is_field_marked_not_private = dto_field and dto_field.mark is not Mark.PRIVATE
+
+ # Case 2
+ should_exclude_anything_implicit = not include_implicit_fields and key not in model_type_hints
+
+ # Case 3
+ should_exclude_non_hybrid_only = (
+ not is_hybrid_property and include_implicit_fields == "hybrid-only" and key not in model_type_hints
+ )
+
+ # Descriptor is marked with with either Mark.READ_ONLY or Mark.WRITE_ONLY (see Case 1):
+ # - always include it regardless of anything else.
+ # Descriptor is not marked:
+ # - It's implicit BUT config excludes anything implicit (see Case 2): exclude
+ # - It's implicit AND not hybrid BUT config includes hybdrid-only implicit descriptors (Case 3): exclude
+ should_skip_descriptor = not is_field_marked_not_private and (
+ should_exclude_anything_implicit or should_exclude_non_hybrid_only
+ )
+
+ if should_skip_descriptor:
continue
yield from cls.handle_orm_descriptor(
diff --git a/litestar/dto/base_dto.py b/litestar/dto/base_dto.py
--- a/litestar/dto/base_dto.py
+++ b/litestar/dto/base_dto.py
@@ -268,9 +268,7 @@ def get_dto_config_from_annotated_type(field_definition: FieldDefinition) -> DTO
Returns:
The type and config object extracted from the annotation.
"""
- if configs := [item for item in field_definition.metadata if isinstance(item, DTOConfig)]:
- return configs[0]
- return None
+ return next((item for item in field_definition.metadata if isinstance(item, DTOConfig)), None)
@classmethod
def resolve_model_type(cls, field_definition: FieldDefinition) -> FieldDefinition:
diff --git a/litestar/dto/config.py b/litestar/dto/config.py
--- a/litestar/dto/config.py
+++ b/litestar/dto/config.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Literal
from litestar.exceptions import ImproperlyConfiguredException
@@ -10,7 +10,10 @@
from litestar.dto.types import RenameStrategy
-__all__ = ("DTOConfig",)
+__all__ = (
+ "DTOConfig",
+ "SQLAlchemyDTOConfig",
+)
@dataclass(frozen=True)
@@ -62,3 +65,17 @@ def __post_init__(self) -> None:
raise ImproperlyConfiguredException(
"'include' and 'exclude' are mutually exclusive options, please use one of them"
)
+
+
+@dataclass(frozen=True)
+class SQLAlchemyDTOConfig(DTOConfig):
+ """Additional controls for the generated SQLAlchemy DTO."""
+
+ include_implicit_fields: bool | Literal["hybrid-only"] = True
+ """Fields that are implicitly mapped are included.
+
+ Turning this off will lead to exclude all fields not using ``Mapped`` annotation,
+
+ When setting this to ``hybrid-only``, all implicitly mapped fields are excluded
+ with the exception for hybrid properties.
+ """
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py b/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_dto_integration.py
@@ -4,13 +4,25 @@
import pytest
from sqlalchemy import Column, ForeignKey, Integer, String, Table
-from sqlalchemy.orm import DeclarativeBase, Mapped, composite, declared_attr, mapped_column, relationship
+from sqlalchemy.ext.hybrid import hybrid_property
+from sqlalchemy.orm import (
+ DeclarativeBase,
+ Mapped,
+ column_property,
+ composite,
+ declared_attr,
+ mapped_column,
+ relationship,
+)
from typing_extensions import Annotated
from litestar import get, post
from litestar.contrib.sqlalchemy.dto import SQLAlchemyDTO
-from litestar.dto import DTOConfig
+from litestar.di import Provide
+from litestar.dto import DTOConfig, DTOField, Mark
from litestar.dto._backend import _rename_field
+from litestar.dto.config import SQLAlchemyDTOConfig
+from litestar.dto.field import DTO_FIELD_META_KEY
from litestar.dto.types import RenameStrategy
from litestar.testing import create_test_client
@@ -481,5 +493,139 @@ def post_handler(data: Model) -> Model:
"""
)
with create_test_client(route_handlers=[module.post_handler]) as client:
- response = client.post("/", json={"val": "value"})
+ response = client.post("/", json={"id": 1, "val": "value"})
assert response.json() == {"id": 1, "val": "value"}
+
+
+async def test_disable_implicitly_mapped_columns_using_annotated_notation() -> None:
+ class Base(DeclarativeBase):
+ id: Mapped[int] = mapped_column(default=int, primary_key=True)
+
+ table = Table(
+ "vertices2",
+ Base.metadata,
+ Column("id", Integer, primary_key=True),
+ Column("field", String, nullable=True),
+ )
+
+ class Model(Base):
+ __table__ = table
+ id: Mapped[int]
+
+ @hybrid_property
+ def id_multiplied(self) -> int:
+ return self.id * 10
+
+ dto_type = SQLAlchemyDTO[Annotated[Model, SQLAlchemyDTOConfig(include_implicit_fields=False)]]
+
+ @get(
+ dto=None,
+ return_dto=dto_type,
+ signature_namespace={"Model": Model},
+ dependencies={"model": Provide(lambda: Model(id=123, field="hi"), sync_to_thread=False)},
+ )
+ def post_handler(model: Model) -> Model:
+ return model
+
+ with create_test_client(route_handlers=[post_handler]) as client:
+ response = client.get(
+ "/",
+ )
+
+ json = response.json()
+ assert json.get("field") is None
+ assert json.get("id_multiplied") is None
+
+
+async def test_disable_implicitly_mapped_columns_special() -> None:
+ class Base(DeclarativeBase):
+ id: Mapped[int] = mapped_column(default=int, primary_key=True)
+
+ table = Table(
+ "vertices2",
+ Base.metadata,
+ Column("id", Integer, primary_key=True),
+ Column("field", String, nullable=True),
+ )
+
+ class Model(Base):
+ __table__ = table
+ id: Mapped[int]
+
+ class dto_type(SQLAlchemyDTO[Model]):
+ config = SQLAlchemyDTOConfig(include_implicit_fields=False)
+
+ @get(
+ dto=None,
+ return_dto=dto_type,
+ signature_namespace={"Model": Model},
+ dependencies={"model": Provide(lambda: Model(id=123, field="hi"), sync_to_thread=False)},
+ )
+ def post_handler(model: Model) -> Model:
+ return model
+
+ with create_test_client(route_handlers=[post_handler]) as client:
+ response = client.get(
+ "/",
+ )
+
+ json = response.json()
+ assert json.get("field") is None
+
+
+async def test_disable_implicitly_mapped_columns_with_hybrid_properties_and_Mark_overrides() -> None:
+ class Base(DeclarativeBase):
+ id: Mapped[int] = mapped_column(default=int, primary_key=True)
+
+ table = Table(
+ "vertices2",
+ Base.metadata,
+ Column("id", Integer, primary_key=True),
+ Column("field", String, nullable=True),
+ Column("field2", String),
+ Column("field3", String),
+ Column("field4", String),
+ )
+
+ class Model(Base):
+ __table__ = table
+ id: Mapped[int]
+ field2 = column_property(table.c.field2, info={DTO_FIELD_META_KEY: DTOField(mark=Mark.READ_ONLY)}) # type: ignore
+ field3 = column_property(table.c.field3, info={DTO_FIELD_META_KEY: DTOField(mark=Mark.WRITE_ONLY)}) # type: ignore
+ field4 = column_property(table.c.field4, info={DTO_FIELD_META_KEY: DTOField(mark=Mark.PRIVATE)}) # type: ignore
+
+ @hybrid_property
+ def id_multiplied(self) -> int:
+ return self.id * 10
+
+ dto_type = SQLAlchemyDTO[
+ Annotated[
+ Model,
+ SQLAlchemyDTOConfig(include_implicit_fields="hybrid-only"),
+ ]
+ ]
+
+ @get(
+ dto=None,
+ return_dto=dto_type,
+ signature_namespace={"Model": Model},
+ dependencies={
+ "model": Provide(
+ lambda: Model(id=12, field="hi", field2="bye2", field3="bye3", field4="bye4"), sync_to_thread=False
+ )
+ },
+ )
+ def post_handler(model: Model) -> Model:
+ return model
+
+ with create_test_client(route_handlers=[post_handler]) as client:
+ response = client.get(
+ "/",
+ )
+
+ json = response.json()
+ assert json.get("id_multiplied") == 120
+ assert json.get("field") is None
+ assert json.get("field2") is not None
+ assert json.get("field3") is not None
+ assert json.get("field4") is None
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-08-15T18:10:13 |
litestar-org/litestar | 2,178 | litestar-org__litestar-2178 | [
"2133",
"1234"
] | d257d099993179f1133a96441bf816e1de435007 | diff --git a/litestar/_openapi/schema_generation/examples.py b/litestar/_openapi/schema_generation/examples.py
--- a/litestar/_openapi/schema_generation/examples.py
+++ b/litestar/_openapi/schema_generation/examples.py
@@ -1,14 +1,18 @@
from __future__ import annotations
+import typing
from dataclasses import replace
from decimal import Decimal
from enum import Enum
from typing import TYPE_CHECKING, Any
+import msgspec
from polyfactory.exceptions import ParameterException
from polyfactory.factories import DataclassFactory
from polyfactory.field_meta import FieldMeta, Null
from polyfactory.utils.helpers import unwrap_annotation
+from polyfactory.utils.predicates import is_union
+from typing_extensions import get_args
from litestar.openapi.spec import Example
from litestar.types import Empty
@@ -25,6 +29,18 @@ class ExampleFactory(DataclassFactory[Example]):
def _normalize_example_value(value: Any) -> Any:
"""Normalize the example value to make it look a bit prettier."""
+ # if UnsetType is part of the union, then it might get chosen as the value
+ # but that will not be properly serialized by msgspec unless it is for a field
+ # in a msgspec Struct
+ if is_union(value):
+ args = list(get_args(value))
+ try:
+ args.remove(msgspec.UnsetType)
+ value = typing.Union[tuple(args)] # pyright: ignore
+ except ValueError:
+ # UnsetType not part of the Union
+ pass
+
value = unwrap_annotation(annotation=value, random=ExampleFactory.__random__)
if isinstance(value, (Decimal, float)):
value = round(float(value), 2)
diff --git a/litestar/openapi/controller.py b/litestar/openapi/controller.py
--- a/litestar/openapi/controller.py
+++ b/litestar/openapi/controller.py
@@ -12,6 +12,7 @@
from litestar.handlers import get
from litestar.response.base import ASGIResponse
from litestar.serialization import encode_json
+from litestar.serialization.msgspec_hooks import decode_json
from litestar.status_codes import HTTP_404_NOT_FOUND
__all__ = ("OpenAPIController",)
@@ -64,7 +65,8 @@ class OpenAPIController(Controller):
"""Download url for the Stoplight Elements JS bundle."""
# internal
- _dumped_schema: str = ""
+ _dumped_json_schema: str = ""
+ _dumped_yaml_schema: bytes = b""
# until swagger-ui supports v3.1.* of OpenAPI officially, we need to modify the schema for it and keep it
# separate from the redoc version of the schema, which is unmodified.
dto = None
@@ -143,10 +145,11 @@ def retrieve_schema_yaml(self, request: Request[Any, Any, Any]) -> ASGIResponse:
A Response instance with the YAML object rendered into a string.
"""
if self.should_serve_endpoint(request):
- content = dump_yaml(self.get_schema_from_request(request).to_schema(), default_flow_style=False).encode(
- "utf-8"
- )
- return ASGIResponse(body=content, media_type=OpenAPIMediaType.OPENAPI_YAML)
+ if not self._dumped_json_schema:
+ schema_json = decode_json(self._get_schema_as_json(request))
+ schema_yaml = dump_yaml(schema_json, default_flow_style=False)
+ self._dumped_yaml_schema = schema_yaml.encode("utf-8")
+ return ASGIResponse(body=self._dumped_yaml_schema, media_type=OpenAPIMediaType.OPENAPI_YAML)
return ASGIResponse(body=b"", status_code=HTTP_404_NOT_FOUND, media_type=MediaType.HTML)
@get(path="/openapi.json", media_type=OpenAPIMediaType.OPENAPI_JSON, include_in_schema=False, sync_to_thread=False)
@@ -162,7 +165,7 @@ def retrieve_schema_json(self, request: Request[Any, Any, Any]) -> ASGIResponse:
"""
if self.should_serve_endpoint(request):
return ASGIResponse(
- body=encode_json(self.get_schema_from_request(request).to_schema()),
+ body=self._get_schema_as_json(request),
media_type=OpenAPIMediaType.OPENAPI_JSON,
)
return ASGIResponse(body=b"", status_code=HTTP_404_NOT_FOUND, media_type=MediaType.HTML)
@@ -272,7 +275,7 @@ def render_swagger_ui(self, request: Request[Any, Any, Any]) -> bytes:
<div id='swagger-container'/>
<script type="text/javascript">
const ui = SwaggerUIBundle({{
- spec: {encode_json(schema.to_schema()).decode("utf-8")},
+ spec: {self._get_schema_as_json(request)},
dom_id: '#swagger-container',
deepLinking: true,
showExtensions: true,
@@ -353,9 +356,6 @@ def render_redoc(self, request: Request[Any, Any, Any]) -> bytes: # pragma: no
"""
schema = self.get_schema_from_request(request)
- if not self._dumped_schema:
- self._dumped_schema = encode_json(schema.to_schema()).decode("utf-8")
-
head = f"""
<head>
<title>{schema.info.title}</title>
@@ -382,7 +382,7 @@ def render_redoc(self, request: Request[Any, Any, Any]) -> bytes: # pragma: no
<div id='redoc-container'/>
<script type="text/javascript">
Redoc.init(
- {self._dumped_schema},
+ {self._get_schema_as_json(request)},
undefined,
document.getElementById('redoc-container')
)
@@ -422,3 +422,13 @@ def render_404_page(self) -> bytes:
</body>
</html>
""".encode()
+
+ def _get_schema_as_json(self, request: Request) -> str:
+ """Get the schema encoded as a JSON string."""
+
+ if not self._dumped_json_schema:
+ schema = self.get_schema_from_request(request).to_schema()
+ json_encoded_schema = encode_json(schema, request.route_handler.default_serializer)
+ self._dumped_json_schema = json_encoded_schema.decode("utf-8")
+
+ return self._dumped_json_schema
| diff --git a/tests/unit/test_openapi/test_integration.py b/tests/unit/test_openapi/test_integration.py
--- a/tests/unit/test_openapi/test_integration.py
+++ b/tests/unit/test_openapi/test_integration.py
@@ -1,6 +1,7 @@
from typing import Type
import msgspec
+import pytest
import yaml
from pydantic import BaseModel, Field
from typing_extensions import Annotated
@@ -9,12 +10,19 @@
from litestar.app import DEFAULT_OPENAPI_CONFIG
from litestar.enums import OpenAPIMediaType
from litestar.openapi import OpenAPIConfig, OpenAPIController
+from litestar.serialization.msgspec_hooks import decode_json, encode_json, get_serializer
from litestar.status_codes import HTTP_200_OK, HTTP_404_NOT_FOUND
from litestar.testing import create_test_client
+CREATE_EXAMPLES_VALUES = (True, False)
-def test_openapi_yaml(person_controller: Type[Controller], pet_controller: Type[Controller]) -> None:
- with create_test_client([person_controller, pet_controller], openapi_config=DEFAULT_OPENAPI_CONFIG) as client:
+
[email protected]("create_examples", CREATE_EXAMPLES_VALUES)
+def test_openapi_yaml(
+ person_controller: Type[Controller], pet_controller: Type[Controller], create_examples: bool
+) -> None:
+ openapi_config = OpenAPIConfig("Example API", "1.0.0", create_examples=create_examples)
+ with create_test_client([person_controller, pet_controller], openapi_config=openapi_config) as client:
assert client.app.openapi_schema
openapi_schema = client.app.openapi_schema
assert openapi_schema.paths
@@ -22,11 +30,17 @@ def test_openapi_yaml(person_controller: Type[Controller], pet_controller: Type[
assert response.status_code == HTTP_200_OK
assert response.headers["content-type"] == OpenAPIMediaType.OPENAPI_YAML.value
assert client.app.openapi_schema
- assert yaml.unsafe_load(response.content) == client.app.openapi_schema.to_schema()
+ serializer = get_serializer(client.app.type_encoders)
+ schema_json = decode_json(encode_json(openapi_schema.to_schema(), serializer))
+ assert response.content.decode("utf-8") == yaml.dump(schema_json)
-def test_openapi_json(person_controller: Type[Controller], pet_controller: Type[Controller]) -> None:
- with create_test_client([person_controller, pet_controller], openapi_config=DEFAULT_OPENAPI_CONFIG) as client:
[email protected]("create_examples", CREATE_EXAMPLES_VALUES)
+def test_openapi_json(
+ person_controller: Type[Controller], pet_controller: Type[Controller], create_examples: bool
+) -> None:
+ openapi_config = OpenAPIConfig("Example API", "1.0.0", create_examples=create_examples)
+ with create_test_client([person_controller, pet_controller], openapi_config=openapi_config) as client:
assert client.app.openapi_schema
openapi_schema = client.app.openapi_schema
assert openapi_schema.paths
@@ -34,7 +48,8 @@ def test_openapi_json(person_controller: Type[Controller], pet_controller: Type[
assert response.status_code == HTTP_200_OK
assert response.headers["content-type"] == OpenAPIMediaType.OPENAPI_JSON.value
assert client.app.openapi_schema
- assert response.json() == client.app.openapi_schema.to_schema()
+ serializer = get_serializer(client.app.type_encoders)
+ assert response.content == encode_json(openapi_schema.to_schema(), serializer)
def test_openapi_yaml_not_allowed(person_controller: Type[Controller], pet_controller: Type[Controller]) -> None:
@@ -118,7 +133,8 @@ class CustomOpenAPIController(OpenAPIController):
assert response.status_code == HTTP_200_OK
-def test_msgspec_schema_generation() -> None:
[email protected]("create_examples", CREATE_EXAMPLES_VALUES)
+def test_msgspec_schema_generation(create_examples: bool) -> None:
class Lookup(msgspec.Struct):
id: Annotated[
str,
@@ -139,6 +155,7 @@ async def example_route() -> Lookup:
openapi_config=OpenAPIConfig(
title="Example API",
version="1.0.0",
+ create_examples=create_examples,
),
) as client:
response = client.get("/schema/openapi.json")
@@ -152,7 +169,8 @@ async def example_route() -> Lookup:
}
-def test_pydantic_schema_generation() -> None:
[email protected]("create_examples", CREATE_EXAMPLES_VALUES)
+def test_pydantic_schema_generation(create_examples: bool) -> None:
class Lookup(BaseModel):
id: Annotated[
str,
@@ -173,6 +191,7 @@ async def example_route() -> Lookup:
openapi_config=OpenAPIConfig(
title="Example API",
version="1.0.0",
+ create_examples=create_examples,
),
) as client:
response = client.get("/schema/openapi.json")
diff --git a/tests/unit/test_openapi/test_parameters.py b/tests/unit/test_openapi/test_parameters.py
--- a/tests/unit/test_openapi/test_parameters.py
+++ b/tests/unit/test_openapi/test_parameters.py
@@ -5,6 +5,7 @@
from litestar import Controller, Litestar, Router, get
from litestar._openapi.parameters import create_parameter_for_handler
from litestar._openapi.schema_generation import SchemaCreator
+from litestar._openapi.schema_generation.examples import ExampleFactory
from litestar._openapi.typescript_converter.schema_parsing import is_schema_value
from litestar._signature import SignatureModel
from litestar.di import Provide
@@ -41,6 +42,8 @@ def _create_parameters(app: Litestar, path: str) -> List["OpenAPIParameter"]:
def test_create_parameters(person_controller: Type[Controller]) -> None:
+ ExampleFactory.seed_random(10)
+
parameters = _create_parameters(app=Litestar(route_handlers=[person_controller]), path="/{service_id}/person")
assert len(parameters) == 9
page, name, page_size, service_id, from_date, to_date, gender, secret_header, cookie_value = tuple(parameters)
| Bug: Swagger generation fails when using pydantic BaseModel
### Description
Litestar version: 2.0.0rc1
Pydantic version: 2.1.1
(coming from #2101)
Swagger creation fails if multiple responses are defined on the endpoint definition and the responses subclass pydantic.BaseModel.
However, if I use dataclasses (as the code below)
```python
from litestar import Litestar, get, status_codes
from litestar.openapi import ResponseSpec
from dataclasses import dataclass
@dataclass
class User:
id: str
@dataclass
class NotFoundResponse:
message: str
@get(
path="/user/{user_id:str}",
responses={
status_codes.HTTP_200_OK: ResponseSpec(data_container=User),
status_codes.HTTP_404_NOT_FOUND: ResponseSpec(data_container=NotFoundResponse),
},
)
def get_user(user_id: str) -> User:
if user_id == "null":
return NotFoundResponse(message="not found")
return User(id=user_id)
app = Litestar(route_handlers=[get_user])
```
The result is the following

### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, get, status_codes
from litestar.openapi import ResponseSpec
from pydantic import BaseModel
class User(BaseModel):
id: str
class NotFoundResponse(BaseModel):
message: str
@get(
path="/user/{user_id:str}",
responses={
status_codes.HTTP_200_OK: ResponseSpec(data_container=User),
status_codes.HTTP_404_NOT_FOUND: ResponseSpec(data_container=NotFoundResponse),
},
)
def get_user(user_id: str) -> User:
if user_id == "null":
return NotFoundResponse(message="not found")
return User(id=user_id)
app = Litestar(route_handlers=[get_user])
```
### Steps to reproduce
```bash
1. `litestar run`
2. Go to localhost:8000/schema/swagger
```
### Screenshots
_No response_
### Logs
```bash
INFO: Started server process [66800]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit)
ERROR - 2023-08-01 16:44:26,204 - litestar - config - exception raised on http connection to route /schema/swagger
Traceback (most recent call last):
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 141, in encode_json
return msgspec.json.encode(value, enc_hook=serializer) if serializer else _msgspec_json_encoder.encode(value)
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 88, in default_serializer
raise TypeError(f"Unsupported type: {type(value)!r}")
TypeError: Unsupported type: <class 'app.User'>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/middleware/exceptions/middleware.py", line 157, in __call__
await self.app(scope, receive, send)
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 77, in handle
response = await self._get_response_for_request(
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 129, in _get_response_for_request
response = await self._call_handler_function(
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 158, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 204, in _get_response_data
data = route_handler.fn.value(**parsed_kwargs)
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 209, in swagger_ui
return ASGIResponse(body=self.render_swagger_ui(request), media_type=MediaType.HTML)
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 275, in render_swagger_ui
spec: {encode_json(schema.to_schema()).decode("utf-8")},
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 143, in encode_json
raise SerializationException(str(msgspec_error)) from msgspec_error
litestar.exceptions.base_exceptions.SerializationException: Unsupported type: <class 'app.User'>
Traceback (most recent call last):
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 141, in encode_json
return msgspec.json.encode(value, enc_hook=serializer) if serializer else _msgspec_json_encoder.encode(value)
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 88, in default_serializer
raise TypeError(f"Unsupported type: {type(value)!r}")
TypeError: Unsupported type: <class 'app.User'>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/middleware/exceptions/middleware.py", line 157, in __call__
await self.app(scope, receive, send)
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 77, in handle
response = await self._get_response_for_request(
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 129, in _get_response_for_request
response = await self._call_handler_function(
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 158, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 204, in _get_response_data
data = route_handler.fn.value(**parsed_kwargs)
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 209, in swagger_ui
return ASGIResponse(body=self.render_swagger_ui(request), media_type=MediaType.HTML)
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 275, in render_swagger_ui
spec: {encode_json(schema.to_schema()).decode("utf-8")},
File "/home/myuser/projects/litestar-test/.venv/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 143, in encode_json
raise SerializationException(str(msgspec_error)) from msgspec_error
litestar.exceptions.base_exceptions.SerializationException: Unsupported type: <class 'app.User'>
INFO: 127.0.0.1:44104 - "GET /schema/swagger HTTP/1.1" 500 Internal Server Error
```
### Litestar Version
2.0.0rc1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2133">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2133/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2133/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| From a little investigation, it seems to happen because
_create_examples_for_field()_ in litestar/_openapi/schema_generation/examples.py
creates an instance of the class without serializing.
Modifying the function like this works, but I don't think it's the proper way to do it. I'm not familiar with the codebase
```python
def create_examples_for_field(field: FieldDefinition) -> list[Example]:
"""Create an OpenAPI Example instance.
Args:
field: A signature field.
Returns:
A list including a single example.
"""
try:
field_meta = _create_field_meta(replace(field, annotation=_normalize_example_value(field.annotation)))
value = Factory.get_field_value(field_meta)
# Start new code
value = value.model_dump() if hasattr(value, "model_dump") else value
# End new code
return [Example(description=f"Example {field.name} value", value=value).to_schema()]
except ParameterException:
return []
```
This is the same as the issue discussed [here](https://discord.com/channels/919193495116337154/1134060657629745304). @JacobCoffee or @Xemnas0 , could you edit the title to reflect that the bug is swagger generation fails when using a pydantic BaseModel?
@guacs you now should have privileges to do this
I agree. Do you want to submit a PR? | 2023-08-19T15:17:34 |
litestar-org/litestar | 2,179 | litestar-org__litestar-2179 | [
"4321",
"1234"
] | 65e9d8f1d3b2b5b6d6a8c30beda74ce763668097 | diff --git a/litestar/contrib/sqlalchemy/base.py b/litestar/contrib/sqlalchemy/base.py
--- a/litestar/contrib/sqlalchemy/base.py
+++ b/litestar/contrib/sqlalchemy/base.py
@@ -23,6 +23,7 @@
if TYPE_CHECKING:
from sqlalchemy.sql import FromClause
+ from sqlalchemy.sql.schema import _NamingSchemaParameter as NamingSchemaParameter
__all__ = (
"AuditColumns",
@@ -42,7 +43,7 @@
UUIDBaseT = TypeVar("UUIDBaseT", bound="UUIDBase")
BigIntBaseT = TypeVar("BigIntBaseT", bound="BigIntBase")
-convention = {
+convention: NamingSchemaParameter = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
@@ -151,7 +152,7 @@ def to_dict(self, exclude: set[str] | None = None) -> dict[str, Any]:
def create_registry() -> registry:
"""Create a new SQLAlchemy registry."""
- meta = MetaData(naming_convention=convention) # type: ignore[arg-type]
+ meta = MetaData(naming_convention=convention)
return registry(
metadata=meta,
type_annotation_map={
diff --git a/litestar/contrib/sqlalchemy/repository/_async.py b/litestar/contrib/sqlalchemy/repository/_async.py
--- a/litestar/contrib/sqlalchemy/repository/_async.py
+++ b/litestar/contrib/sqlalchemy/repository/_async.py
@@ -2,7 +2,18 @@
from typing import TYPE_CHECKING, Any, Final, Generic, Iterable, Literal, cast
-from sqlalchemy import Result, Select, TextClause, delete, over, select, text, update
+from sqlalchemy import (
+ Result,
+ Select,
+ StatementLambdaElement,
+ TextClause,
+ delete,
+ lambda_stmt,
+ over,
+ select,
+ text,
+ update,
+)
from sqlalchemy import func as sql_func
from sqlalchemy.orm import InstrumentedAttribute
@@ -20,7 +31,7 @@
)
from ._util import get_instrumented_attr, wrap_sqlalchemy_exception
-from .types import ModelT, RowT, SelectT
+from .types import ModelT
if TYPE_CHECKING:
from collections import abc
@@ -41,7 +52,7 @@ class SQLAlchemyAsyncRepository(AbstractAsyncRepository[ModelT], Generic[ModelT]
def __init__(
self,
*,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
session: AsyncSession,
auto_expunge: bool = False,
auto_refresh: bool = True,
@@ -64,7 +75,13 @@ def __init__(
self.auto_refresh = auto_refresh
self.auto_commit = auto_commit
self.session = session
- self.statement = statement if statement is not None else select(self.model_type)
+ if isinstance(statement, Select):
+ self.statement = lambda_stmt(lambda: statement)
+ elif statement is None:
+ statement = select(self.model_type)
+ self.statement = lambda_stmt(lambda: statement)
+ else:
+ self.statement = statement
if not self.session.bind:
# this shouldn't actually ever happen, but we include it anyway to properly
# narrow down the types
@@ -192,12 +209,36 @@ async def delete_many(
if self._dialect.delete_executemany_returning:
instances.extend(
await self.session.scalars(
- delete(self.model_type).where(id_attribute.in_(chunk)).returning(self.model_type)
+ self._get_delete_many_statement(
+ statement_type="delete",
+ model_type=self.model_type,
+ id_attribute=id_attribute,
+ id_chunk=chunk,
+ supports_returning=self._dialect.delete_executemany_returning,
+ )
)
)
else:
- instances.extend(await self.session.scalars(select(self.model_type).where(id_attribute.in_(chunk))))
- await self.session.execute(delete(self.model_type).where(id_attribute.in_(chunk)))
+ instances.extend(
+ await self.session.scalars(
+ self._get_delete_many_statement(
+ statement_type="select",
+ model_type=self.model_type,
+ id_attribute=id_attribute,
+ id_chunk=chunk,
+ supports_returning=self._dialect.delete_executemany_returning,
+ )
+ )
+ )
+ await self.session.execute(
+ self._get_delete_many_statement(
+ statement_type="delete",
+ model_type=self.model_type,
+ id_attribute=id_attribute,
+ id_chunk=chunk,
+ supports_returning=self._dialect.delete_executemany_returning,
+ )
+ )
await self._flush_or_commit(auto_commit=auto_commit)
for instance in instances:
self._expunge(instance, auto_expunge=auto_expunge)
@@ -219,11 +260,35 @@ async def exists(self, **kwargs: Any) -> bool:
existing = await self.count(**kwargs)
return existing > 0
+ def _get_base_stmt(
+ self, statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None
+ ) -> StatementLambdaElement:
+ if isinstance(statement, Select):
+ return lambda_stmt(lambda: statement)
+ return self.statement if statement is None else statement
+
+ @staticmethod
+ def _get_delete_many_statement(
+ model_type: type[ModelT],
+ id_attribute: InstrumentedAttribute,
+ id_chunk: list[Any],
+ supports_returning: bool,
+ statement_type: Literal["delete", "select"] = "delete",
+ ) -> StatementLambdaElement:
+ if statement_type == "delete":
+ statement = lambda_stmt(lambda: delete(model_type))
+ elif statement_type == "select":
+ statement = lambda_stmt(lambda: select(model_type))
+ statement += lambda s: s.where(id_attribute.in_(id_chunk))
+ if supports_returning and statement_type != "select":
+ statement += lambda s: s.returning(model_type)
+ return statement
+
async def get( # type: ignore[override]
self,
item_id: Any,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
id_attribute: str | InstrumentedAttribute | None = None,
) -> ModelT:
"""Get instance identified by `item_id`.
@@ -245,8 +310,8 @@ async def get( # type: ignore[override]
"""
with wrap_sqlalchemy_exception():
id_attribute = id_attribute if id_attribute is not None else self.id_attribute
- statement = statement if statement is not None else self.statement
- statement = self._filter_select_by_kwargs(statement=statement, kwargs=[(id_attribute, item_id)])
+ statement = self._get_base_stmt(statement)
+ statement = self._filter_select_by_kwargs(statement, [(id_attribute, item_id)])
instance = (await self._execute(statement)).scalar_one_or_none()
instance = self.check_not_found(instance)
self._expunge(instance, auto_expunge=auto_expunge)
@@ -255,7 +320,7 @@ async def get( # type: ignore[override]
async def get_one(
self,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> ModelT:
"""Get instance identified by ``kwargs``.
@@ -274,8 +339,8 @@ async def get_one(
NotFoundError: If no instance found identified by `item_id`.
"""
with wrap_sqlalchemy_exception():
- statement = statement if statement is not None else self.statement
- statement = self._filter_select_by_kwargs(statement=statement, kwargs=kwargs)
+ statement = self._get_base_stmt(statement)
+ statement = self._filter_select_by_kwargs(statement, kwargs)
instance = (await self._execute(statement)).scalar_one_or_none()
instance = self.check_not_found(instance)
self._expunge(instance, auto_expunge=auto_expunge)
@@ -284,7 +349,7 @@ async def get_one(
async def get_one_or_none(
self,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> ModelT | None:
"""Get instance identified by ``kwargs`` or None if not found.
@@ -300,9 +365,9 @@ async def get_one_or_none(
The retrieved instance or None
"""
with wrap_sqlalchemy_exception():
- statement = statement if statement is not None else self.statement
- statement = self._filter_select_by_kwargs(statement=statement, kwargs=kwargs)
- instance = (await self._execute(statement)).scalar_one_or_none()
+ statement = self._get_base_stmt(statement)
+ statement = self._filter_select_by_kwargs(statement, kwargs)
+ instance = cast("Result[tuple[ModelT]]", (await self._execute(statement))).scalar_one_or_none()
if instance:
self._expunge(instance, auto_expunge=auto_expunge)
return instance
@@ -373,7 +438,7 @@ async def get_or_create(
async def count(
self,
*filters: FilterTypes,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> int:
"""Get the count of records returned by a query.
@@ -387,11 +452,9 @@ async def count(
Returns:
Count of records returned by query, ignoring pagination.
"""
- statement = statement if statement is not None else self.statement
- statement = statement.with_only_columns(
- sql_func.count(self.get_id_attribute_value(self.model_type)),
- maintain_column_froms=True,
- ).order_by(None)
+ statement = self._get_base_stmt(statement)
+ fragment = self.get_id_attribute_value(self.model_type)
+ statement += lambda s: s.with_only_columns(sql_func.count(fragment), maintain_column_froms=True).order_by(None)
statement = self._apply_filters(*filters, apply_pagination=False, statement=statement)
statement = self._filter_select_by_kwargs(statement, kwargs)
results = await self._execute(statement)
@@ -475,10 +538,12 @@ async def update_many(
"""
data_to_update: list[dict[str, Any]] = [v.to_dict() if isinstance(v, self.model_type) else v for v in data] # type: ignore
with wrap_sqlalchemy_exception():
- if self._dialect.update_executemany_returning and self._dialect.name != "oracle":
+ supports_returning = self._dialect.update_executemany_returning and self._dialect.name != "oracle"
+ statement = self._get_update_many_statement(self.model_type, supports_returning)
+ if supports_returning:
instances = list(
await self.session.scalars(
- update(self.model_type).returning(self.model_type),
+ statement,
cast("_CoreSingleExecuteParams", data_to_update), # this is not correct but the only way
# currently to deal with an SQLAlchemy typing issue. See
# https://github.com/sqlalchemy/sqlalchemy/discussions/9925
@@ -488,17 +553,25 @@ async def update_many(
for instance in instances:
self._expunge(instance, auto_expunge=auto_expunge)
return instances
- await self.session.execute(update(self.model_type), data_to_update)
+ await self.session.execute(statement, data_to_update)
await self._flush_or_commit(auto_commit=auto_commit)
return data
+ @staticmethod
+ def _get_update_many_statement(model_type: type[ModelT], supports_returning: bool) -> StatementLambdaElement:
+ statement = lambda_stmt(lambda: update(model_type))
+ if supports_returning:
+ statement += lambda s: s.returning(model_type)
+ return statement
+
async def list_and_count(
self,
*filters: FilterTypes,
auto_commit: bool | None = None,
auto_expunge: bool | None = None,
auto_refresh: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
+ force_basic_query_mode: bool | None = None,
**kwargs: Any,
) -> tuple[list[ModelT], int]:
"""List records with total count.
@@ -513,12 +586,13 @@ async def list_and_count(
:class:`SQLAlchemyAsyncRepository.auto_commit <SQLAlchemyAsyncRepository>`
statement: To facilitate customization of the underlying select query.
Defaults to :class:`SQLAlchemyAsyncRepository.statement <SQLAlchemyAsyncRepository>`
+ force_basic_query_mode: Force list and count to use two queries instead of an analytical window function.
**kwargs: Instance attribute value filters.
Returns:
Count of records returned by query, ignoring pagination.
"""
- if self._dialect.name in {"spanner", "spanner+spanner"}:
+ if self._dialect.name in {"spanner", "spanner+spanner"} or force_basic_query_mode:
return await self._list_and_count_basic(*filters, auto_expunge=auto_expunge, statement=statement, **kwargs)
return await self._list_and_count_window(*filters, auto_expunge=auto_expunge, statement=statement, **kwargs)
@@ -554,7 +628,7 @@ async def _list_and_count_window(
self,
*filters: FilterTypes,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> tuple[list[ModelT], int]:
"""List records with total count.
@@ -570,8 +644,9 @@ async def _list_and_count_window(
Returns:
Count of records returned by query using an analytical window function, ignoring pagination.
"""
- statement = statement if statement is not None else self.statement
- statement = statement.add_columns(over(sql_func.count(self.get_id_attribute_value(self.model_type))))
+ statement = self._get_base_stmt(statement)
+ field = self.get_id_attribute_value(self.model_type)
+ statement += lambda s: s.add_columns(over(sql_func.count(field)))
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, kwargs)
with wrap_sqlalchemy_exception():
@@ -589,7 +664,7 @@ async def _list_and_count_basic(
self,
*filters: FilterTypes,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> tuple[list[ModelT], int]:
"""List records with total count.
@@ -605,15 +680,12 @@ async def _list_and_count_basic(
Returns:
Count of records returned by query using 2 queries, ignoring pagination.
"""
- statement = statement if statement is not None else self.statement
+ statement = self._get_base_stmt(statement)
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, kwargs)
- count_statement = statement.with_only_columns(
- sql_func.count(self.get_id_attribute_value(self.model_type)),
- maintain_column_froms=True,
- ).order_by(None)
+
with wrap_sqlalchemy_exception():
- count_result = await self.session.execute(count_statement)
+ count_result = await self.session.execute(self._get_count_stmt(statement))
count = count_result.scalar_one()
result = await self._execute(statement)
instances: list[ModelT] = []
@@ -622,6 +694,12 @@ async def _list_and_count_basic(
instances.append(instance)
return instances, count
+ def _get_count_stmt(self, statement: StatementLambdaElement) -> StatementLambdaElement:
+ fragment = self.get_id_attribute_value(self.model_type)
+ statement += lambda s: s.with_only_columns(sql_func.count(fragment), maintain_column_froms=True)
+ statement += lambda s: s.order_by(None)
+ return statement
+
async def upsert(
self,
data: ModelT,
@@ -718,7 +796,7 @@ async def list(
self,
*filters: FilterTypes,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> list[ModelT]:
"""Get a list of instances, optionally filtered.
@@ -734,7 +812,7 @@ async def list(
Returns:
The list of instances, after filtering applied.
"""
- statement = statement if statement is not None else self.statement
+ statement = self._get_base_stmt(statement)
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, kwargs)
@@ -746,8 +824,8 @@ async def list(
return instances
def filter_collection_by_kwargs( # type:ignore[override]
- self, collection: SelectT, /, **kwargs: Any
- ) -> SelectT:
+ self, collection: Select[tuple[ModelT]] | StatementLambdaElement, /, **kwargs: Any
+ ) -> StatementLambdaElement:
"""Filter the collection by kwargs.
Args:
@@ -756,7 +834,9 @@ def filter_collection_by_kwargs( # type:ignore[override]
have the property that their attribute named `key` has value equal to `value`.
"""
with wrap_sqlalchemy_exception():
- return collection.filter_by(**kwargs)
+ collection = lambda_stmt(lambda: collection)
+ collection += lambda s: s.filter_by(**kwargs)
+ return collection
@classmethod
async def check_health(cls, session: AsyncSession) -> bool:
@@ -799,13 +879,18 @@ async def _attach_to_session(self, model: ModelT, strategy: Literal["add", "merg
return await self.session.merge(model)
raise ValueError("Unexpected value for `strategy`, must be `'add'` or `'merge'`")
- async def _execute(self, statement: Select[RowT]) -> Result[RowT]:
- return cast("Result[RowT]", await self.session.execute(statement))
+ async def _execute(self, statement: Select[Any] | StatementLambdaElement) -> Result[Any]:
+ return await self.session.execute(statement)
- def _apply_limit_offset_pagination(self, limit: int, offset: int, statement: SelectT) -> SelectT:
- return statement.limit(limit).offset(offset)
+ def _apply_limit_offset_pagination(
+ self, limit: int, offset: int, statement: StatementLambdaElement
+ ) -> StatementLambdaElement:
+ statement += lambda s: s.limit(limit).offset(offset)
+ return statement
- def _apply_filters(self, *filters: FilterTypes, apply_pagination: bool = True, statement: SelectT) -> SelectT:
+ def _apply_filters(
+ self, *filters: FilterTypes, apply_pagination: bool = True, statement: StatementLambdaElement
+ ) -> StatementLambdaElement:
"""Apply filters to a select statement.
Args:
@@ -843,11 +928,7 @@ def _apply_filters(self, *filters: FilterTypes, apply_pagination: bool = True, s
elif isinstance(filter_, CollectionFilter):
statement = self._filter_in_collection(filter_.field_name, filter_.values, statement=statement)
elif isinstance(filter_, OrderBy):
- statement = self._order_by(
- statement,
- filter_.field_name,
- sort_desc=filter_.sort_order == "desc",
- )
+ statement = self._order_by(statement, filter_.field_name, sort_desc=filter_.sort_order == "desc")
elif isinstance(filter_, SearchFilter):
statement = self._filter_by_like(
statement, filter_.field_name, value=filter_.value, ignore_case=bool(filter_.ignore_case)
@@ -860,57 +941,85 @@ def _apply_filters(self, *filters: FilterTypes, apply_pagination: bool = True, s
raise RepositoryError(f"Unexpected filter: {filter_}")
return statement
- def _filter_in_collection(self, field_name: str, values: abc.Collection[Any], statement: SelectT) -> SelectT:
+ def _filter_in_collection(
+ self, field_name: str, values: abc.Collection[Any], statement: StatementLambdaElement
+ ) -> StatementLambdaElement:
if not values:
return statement
- return statement.where(getattr(self.model_type, field_name).in_(values))
+ field = getattr(self.model_type, field_name)
+ statement += lambda s: s.where(field.in_(values))
+ return statement
- def _filter_not_in_collection(self, field_name: str, values: abc.Collection[Any], statement: SelectT) -> SelectT:
+ def _filter_not_in_collection(
+ self, field_name: str, values: abc.Collection[Any], statement: StatementLambdaElement
+ ) -> StatementLambdaElement:
if not values:
return statement
- return statement.where(getattr(self.model_type, field_name).notin_(values))
+ field = getattr(self.model_type, field_name)
+ statement += lambda s: s.where(field.notin_(values))
+ return statement
def _filter_on_datetime_field(
self,
field_name: str,
- statement: SelectT,
+ statement: StatementLambdaElement,
before: datetime | None = None,
after: datetime | None = None,
on_or_before: datetime | None = None,
on_or_after: datetime | None = None,
- ) -> SelectT:
+ ) -> StatementLambdaElement:
field = getattr(self.model_type, field_name)
if before is not None:
- statement = statement.where(field < before)
+ statement += lambda s: s.where(field < before)
if after is not None:
- statement = statement.where(field > after)
+ statement += lambda s: s.where(field > after)
if on_or_before is not None:
- statement = statement.where(field <= on_or_before)
+ statement += lambda s: s.where(field <= on_or_before)
if on_or_after is not None:
- statement = statement.where(field >= on_or_after)
+ statement += lambda s: s.where(field >= on_or_after)
return statement
def _filter_select_by_kwargs(
- self, statement: SelectT, kwargs: dict[Any, Any] | Iterable[tuple[Any, Any]]
- ) -> SelectT:
+ self, statement: StatementLambdaElement, kwargs: dict[Any, Any] | Iterable[tuple[Any, Any]]
+ ) -> StatementLambdaElement:
for key, val in kwargs.items() if isinstance(kwargs, dict) else kwargs:
- statement = statement.where(get_instrumented_attr(self.model_type, key) == val) # pyright: ignore
+ statement = self._filter_by_where(statement, key, val) # pyright: ignore[reportGeneralTypeIssues]
+ return statement
+
+ def _filter_by_where(self, statement: StatementLambdaElement, key: str, val: Any) -> StatementLambdaElement:
+ model_type = self.model_type
+ field = get_instrumented_attr(model_type, key)
+ statement += lambda s: s.where(field == val)
return statement
def _filter_by_like(
- self, statement: SelectT, field_name: str | InstrumentedAttribute, value: str, ignore_case: bool
- ) -> SelectT:
+ self, statement: StatementLambdaElement, field_name: str | InstrumentedAttribute, value: str, ignore_case: bool
+ ) -> StatementLambdaElement:
field = get_instrumented_attr(self.model_type, field_name)
search_text = f"%{value}%"
- return statement.where(field.ilike(search_text) if ignore_case else field.like(search_text))
+ if ignore_case:
+ statement += lambda s: s.where(field.ilike(search_text))
+ else:
+ statement += lambda s: s.where(field.like(search_text))
+ return statement
- def _filter_by_not_like(self, statement: SelectT, field_name: str, value: str, ignore_case: bool) -> SelectT:
+ def _filter_by_not_like(
+ self, statement: StatementLambdaElement, field_name: str, value: str, ignore_case: bool
+ ) -> StatementLambdaElement:
field = getattr(self.model_type, field_name)
search_text = f"%{value}%"
- return statement.where(field.not_ilike(search_text) if ignore_case else field.not_like(search_text))
+ if ignore_case:
+ statement += lambda s: s.where(field.not_ilike(search_text))
+ else:
+ statement += lambda s: s.where(field.not_like(search_text))
+ return statement
def _order_by(
- self, statement: SelectT, field_name: str | InstrumentedAttribute, sort_desc: bool = False
- ) -> SelectT:
+ self, statement: StatementLambdaElement, field_name: str | InstrumentedAttribute, sort_desc: bool = False
+ ) -> StatementLambdaElement:
field = get_instrumented_attr(self.model_type, field_name)
- return statement.order_by(field.desc() if sort_desc else field.asc())
+ if sort_desc:
+ statement += lambda s: s.order_by(field.desc())
+ else:
+ statement += lambda s: s.order_by(field.asc())
+ return statement
diff --git a/litestar/contrib/sqlalchemy/repository/_sync.py b/litestar/contrib/sqlalchemy/repository/_sync.py
--- a/litestar/contrib/sqlalchemy/repository/_sync.py
+++ b/litestar/contrib/sqlalchemy/repository/_sync.py
@@ -4,7 +4,18 @@
from typing import TYPE_CHECKING, Any, Final, Generic, Iterable, Literal, cast
-from sqlalchemy import Result, Select, TextClause, delete, over, select, text, update
+from sqlalchemy import (
+ Result,
+ Select,
+ StatementLambdaElement,
+ TextClause,
+ delete,
+ lambda_stmt,
+ over,
+ select,
+ text,
+ update,
+)
from sqlalchemy import func as sql_func
from sqlalchemy.orm import InstrumentedAttribute, Session
@@ -22,7 +33,7 @@
)
from ._util import get_instrumented_attr, wrap_sqlalchemy_exception
-from .types import ModelT, RowT, SelectT
+from .types import ModelT
if TYPE_CHECKING:
from collections import abc
@@ -42,7 +53,7 @@ class SQLAlchemySyncRepository(AbstractSyncRepository[ModelT], Generic[ModelT]):
def __init__(
self,
*,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
session: Session,
auto_expunge: bool = False,
auto_refresh: bool = True,
@@ -65,7 +76,13 @@ def __init__(
self.auto_refresh = auto_refresh
self.auto_commit = auto_commit
self.session = session
- self.statement = statement if statement is not None else select(self.model_type)
+ if isinstance(statement, Select):
+ self.statement = lambda_stmt(lambda: statement)
+ elif statement is None:
+ statement = select(self.model_type)
+ self.statement = lambda_stmt(lambda: statement)
+ else:
+ self.statement = statement
if not self.session.bind:
# this shouldn't actually ever happen, but we include it anyway to properly
# narrow down the types
@@ -193,12 +210,36 @@ def delete_many(
if self._dialect.delete_executemany_returning:
instances.extend(
self.session.scalars(
- delete(self.model_type).where(id_attribute.in_(chunk)).returning(self.model_type)
+ self._get_delete_many_statement(
+ statement_type="delete",
+ model_type=self.model_type,
+ id_attribute=id_attribute,
+ id_chunk=chunk,
+ supports_returning=self._dialect.delete_executemany_returning,
+ )
)
)
else:
- instances.extend(self.session.scalars(select(self.model_type).where(id_attribute.in_(chunk))))
- self.session.execute(delete(self.model_type).where(id_attribute.in_(chunk)))
+ instances.extend(
+ self.session.scalars(
+ self._get_delete_many_statement(
+ statement_type="select",
+ model_type=self.model_type,
+ id_attribute=id_attribute,
+ id_chunk=chunk,
+ supports_returning=self._dialect.delete_executemany_returning,
+ )
+ )
+ )
+ self.session.execute(
+ self._get_delete_many_statement(
+ statement_type="delete",
+ model_type=self.model_type,
+ id_attribute=id_attribute,
+ id_chunk=chunk,
+ supports_returning=self._dialect.delete_executemany_returning,
+ )
+ )
self._flush_or_commit(auto_commit=auto_commit)
for instance in instances:
self._expunge(instance, auto_expunge=auto_expunge)
@@ -220,11 +261,35 @@ def exists(self, **kwargs: Any) -> bool:
existing = self.count(**kwargs)
return existing > 0
+ def _get_base_stmt(
+ self, statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None
+ ) -> StatementLambdaElement:
+ if isinstance(statement, Select):
+ return lambda_stmt(lambda: statement)
+ return self.statement if statement is None else statement
+
+ @staticmethod
+ def _get_delete_many_statement(
+ model_type: type[ModelT],
+ id_attribute: InstrumentedAttribute,
+ id_chunk: list[Any],
+ supports_returning: bool,
+ statement_type: Literal["delete", "select"] = "delete",
+ ) -> StatementLambdaElement:
+ if statement_type == "delete":
+ statement = lambda_stmt(lambda: delete(model_type))
+ elif statement_type == "select":
+ statement = lambda_stmt(lambda: select(model_type))
+ statement += lambda s: s.where(id_attribute.in_(id_chunk))
+ if supports_returning and statement_type != "select":
+ statement += lambda s: s.returning(model_type)
+ return statement
+
def get( # type: ignore[override]
self,
item_id: Any,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
id_attribute: str | InstrumentedAttribute | None = None,
) -> ModelT:
"""Get instance identified by `item_id`.
@@ -246,8 +311,8 @@ def get( # type: ignore[override]
"""
with wrap_sqlalchemy_exception():
id_attribute = id_attribute if id_attribute is not None else self.id_attribute
- statement = statement if statement is not None else self.statement
- statement = self._filter_select_by_kwargs(statement=statement, kwargs=[(id_attribute, item_id)])
+ statement = self._get_base_stmt(statement)
+ statement = self._filter_select_by_kwargs(statement, [(id_attribute, item_id)])
instance = (self._execute(statement)).scalar_one_or_none()
instance = self.check_not_found(instance)
self._expunge(instance, auto_expunge=auto_expunge)
@@ -256,7 +321,7 @@ def get( # type: ignore[override]
def get_one(
self,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> ModelT:
"""Get instance identified by ``kwargs``.
@@ -275,8 +340,8 @@ def get_one(
NotFoundError: If no instance found identified by `item_id`.
"""
with wrap_sqlalchemy_exception():
- statement = statement if statement is not None else self.statement
- statement = self._filter_select_by_kwargs(statement=statement, kwargs=kwargs)
+ statement = self._get_base_stmt(statement)
+ statement = self._filter_select_by_kwargs(statement, kwargs)
instance = (self._execute(statement)).scalar_one_or_none()
instance = self.check_not_found(instance)
self._expunge(instance, auto_expunge=auto_expunge)
@@ -285,7 +350,7 @@ def get_one(
def get_one_or_none(
self,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> ModelT | None:
"""Get instance identified by ``kwargs`` or None if not found.
@@ -301,9 +366,9 @@ def get_one_or_none(
The retrieved instance or None
"""
with wrap_sqlalchemy_exception():
- statement = statement if statement is not None else self.statement
- statement = self._filter_select_by_kwargs(statement=statement, kwargs=kwargs)
- instance = (self._execute(statement)).scalar_one_or_none()
+ statement = self._get_base_stmt(statement)
+ statement = self._filter_select_by_kwargs(statement, kwargs)
+ instance = cast("Result[tuple[ModelT]]", (self._execute(statement))).scalar_one_or_none()
if instance:
self._expunge(instance, auto_expunge=auto_expunge)
return instance
@@ -374,7 +439,7 @@ def get_or_create(
def count(
self,
*filters: FilterTypes,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> int:
"""Get the count of records returned by a query.
@@ -388,11 +453,9 @@ def count(
Returns:
Count of records returned by query, ignoring pagination.
"""
- statement = statement if statement is not None else self.statement
- statement = statement.with_only_columns(
- sql_func.count(self.get_id_attribute_value(self.model_type)),
- maintain_column_froms=True,
- ).order_by(None)
+ statement = self._get_base_stmt(statement)
+ fragment = self.get_id_attribute_value(self.model_type)
+ statement += lambda s: s.with_only_columns(sql_func.count(fragment), maintain_column_froms=True).order_by(None)
statement = self._apply_filters(*filters, apply_pagination=False, statement=statement)
statement = self._filter_select_by_kwargs(statement, kwargs)
results = self._execute(statement)
@@ -476,10 +539,12 @@ def update_many(
"""
data_to_update: list[dict[str, Any]] = [v.to_dict() if isinstance(v, self.model_type) else v for v in data] # type: ignore
with wrap_sqlalchemy_exception():
- if self._dialect.update_executemany_returning and self._dialect.name != "oracle":
+ supports_returning = self._dialect.update_executemany_returning and self._dialect.name != "oracle"
+ statement = self._get_update_many_statement(self.model_type, supports_returning)
+ if supports_returning:
instances = list(
self.session.scalars(
- update(self.model_type).returning(self.model_type),
+ statement,
cast("_CoreSingleExecuteParams", data_to_update), # this is not correct but the only way
# currently to deal with an SQLAlchemy typing issue. See
# https://github.com/sqlalchemy/sqlalchemy/discussions/9925
@@ -489,17 +554,25 @@ def update_many(
for instance in instances:
self._expunge(instance, auto_expunge=auto_expunge)
return instances
- self.session.execute(update(self.model_type), data_to_update)
+ self.session.execute(statement, data_to_update)
self._flush_or_commit(auto_commit=auto_commit)
return data
+ @staticmethod
+ def _get_update_many_statement(model_type: type[ModelT], supports_returning: bool) -> StatementLambdaElement:
+ statement = lambda_stmt(lambda: update(model_type))
+ if supports_returning:
+ statement += lambda s: s.returning(model_type)
+ return statement
+
def list_and_count(
self,
*filters: FilterTypes,
auto_commit: bool | None = None,
auto_expunge: bool | None = None,
auto_refresh: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
+ force_basic_query_mode: bool | None = None,
**kwargs: Any,
) -> tuple[list[ModelT], int]:
"""List records with total count.
@@ -514,12 +587,13 @@ def list_and_count(
:class:`SQLAlchemyAsyncRepository.auto_commit <SQLAlchemyAsyncRepository>`
statement: To facilitate customization of the underlying select query.
Defaults to :class:`SQLAlchemyAsyncRepository.statement <SQLAlchemyAsyncRepository>`
+ force_basic_query_mode: Force list and count to use two queries instead of an analytical window function.
**kwargs: Instance attribute value filters.
Returns:
Count of records returned by query, ignoring pagination.
"""
- if self._dialect.name in {"spanner", "spanner+spanner"}:
+ if self._dialect.name in {"spanner", "spanner+spanner"} or force_basic_query_mode:
return self._list_and_count_basic(*filters, auto_expunge=auto_expunge, statement=statement, **kwargs)
return self._list_and_count_window(*filters, auto_expunge=auto_expunge, statement=statement, **kwargs)
@@ -555,7 +629,7 @@ def _list_and_count_window(
self,
*filters: FilterTypes,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> tuple[list[ModelT], int]:
"""List records with total count.
@@ -571,8 +645,9 @@ def _list_and_count_window(
Returns:
Count of records returned by query using an analytical window function, ignoring pagination.
"""
- statement = statement if statement is not None else self.statement
- statement = statement.add_columns(over(sql_func.count(self.get_id_attribute_value(self.model_type))))
+ statement = self._get_base_stmt(statement)
+ field = self.get_id_attribute_value(self.model_type)
+ statement += lambda s: s.add_columns(over(sql_func.count(field)))
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, kwargs)
with wrap_sqlalchemy_exception():
@@ -590,7 +665,7 @@ def _list_and_count_basic(
self,
*filters: FilterTypes,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> tuple[list[ModelT], int]:
"""List records with total count.
@@ -606,15 +681,12 @@ def _list_and_count_basic(
Returns:
Count of records returned by query using 2 queries, ignoring pagination.
"""
- statement = statement if statement is not None else self.statement
+ statement = self._get_base_stmt(statement)
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, kwargs)
- count_statement = statement.with_only_columns(
- sql_func.count(self.get_id_attribute_value(self.model_type)),
- maintain_column_froms=True,
- ).order_by(None)
+
with wrap_sqlalchemy_exception():
- count_result = self.session.execute(count_statement)
+ count_result = self.session.execute(self._get_count_stmt(statement))
count = count_result.scalar_one()
result = self._execute(statement)
instances: list[ModelT] = []
@@ -623,6 +695,12 @@ def _list_and_count_basic(
instances.append(instance)
return instances, count
+ def _get_count_stmt(self, statement: StatementLambdaElement) -> StatementLambdaElement:
+ fragment = self.get_id_attribute_value(self.model_type)
+ statement += lambda s: s.with_only_columns(sql_func.count(fragment), maintain_column_froms=True)
+ statement += lambda s: s.order_by(None)
+ return statement
+
def upsert(
self,
data: ModelT,
@@ -719,7 +797,7 @@ def list(
self,
*filters: FilterTypes,
auto_expunge: bool | None = None,
- statement: Select[tuple[ModelT]] | None = None,
+ statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> list[ModelT]:
"""Get a list of instances, optionally filtered.
@@ -735,7 +813,7 @@ def list(
Returns:
The list of instances, after filtering applied.
"""
- statement = statement if statement is not None else self.statement
+ statement = self._get_base_stmt(statement)
statement = self._apply_filters(*filters, statement=statement)
statement = self._filter_select_by_kwargs(statement, kwargs)
@@ -747,8 +825,8 @@ def list(
return instances
def filter_collection_by_kwargs( # type:ignore[override]
- self, collection: SelectT, /, **kwargs: Any
- ) -> SelectT:
+ self, collection: Select[tuple[ModelT]] | StatementLambdaElement, /, **kwargs: Any
+ ) -> StatementLambdaElement:
"""Filter the collection by kwargs.
Args:
@@ -757,7 +835,9 @@ def filter_collection_by_kwargs( # type:ignore[override]
have the property that their attribute named `key` has value equal to `value`.
"""
with wrap_sqlalchemy_exception():
- return collection.filter_by(**kwargs)
+ collection = lambda_stmt(lambda: collection)
+ collection += lambda s: s.filter_by(**kwargs)
+ return collection
@classmethod
def check_health(cls, session: Session) -> bool:
@@ -800,13 +880,18 @@ def _attach_to_session(self, model: ModelT, strategy: Literal["add", "merge"] =
return self.session.merge(model)
raise ValueError("Unexpected value for `strategy`, must be `'add'` or `'merge'`")
- def _execute(self, statement: Select[RowT]) -> Result[RowT]:
- return cast("Result[RowT]", self.session.execute(statement))
+ def _execute(self, statement: Select[Any] | StatementLambdaElement) -> Result[Any]:
+ return self.session.execute(statement)
- def _apply_limit_offset_pagination(self, limit: int, offset: int, statement: SelectT) -> SelectT:
- return statement.limit(limit).offset(offset)
+ def _apply_limit_offset_pagination(
+ self, limit: int, offset: int, statement: StatementLambdaElement
+ ) -> StatementLambdaElement:
+ statement += lambda s: s.limit(limit).offset(offset)
+ return statement
- def _apply_filters(self, *filters: FilterTypes, apply_pagination: bool = True, statement: SelectT) -> SelectT:
+ def _apply_filters(
+ self, *filters: FilterTypes, apply_pagination: bool = True, statement: StatementLambdaElement
+ ) -> StatementLambdaElement:
"""Apply filters to a select statement.
Args:
@@ -844,11 +929,7 @@ def _apply_filters(self, *filters: FilterTypes, apply_pagination: bool = True, s
elif isinstance(filter_, CollectionFilter):
statement = self._filter_in_collection(filter_.field_name, filter_.values, statement=statement)
elif isinstance(filter_, OrderBy):
- statement = self._order_by(
- statement,
- filter_.field_name,
- sort_desc=filter_.sort_order == "desc",
- )
+ statement = self._order_by(statement, filter_.field_name, sort_desc=filter_.sort_order == "desc")
elif isinstance(filter_, SearchFilter):
statement = self._filter_by_like(
statement, filter_.field_name, value=filter_.value, ignore_case=bool(filter_.ignore_case)
@@ -861,57 +942,85 @@ def _apply_filters(self, *filters: FilterTypes, apply_pagination: bool = True, s
raise RepositoryError(f"Unexpected filter: {filter_}")
return statement
- def _filter_in_collection(self, field_name: str, values: abc.Collection[Any], statement: SelectT) -> SelectT:
+ def _filter_in_collection(
+ self, field_name: str, values: abc.Collection[Any], statement: StatementLambdaElement
+ ) -> StatementLambdaElement:
if not values:
return statement
- return statement.where(getattr(self.model_type, field_name).in_(values))
+ field = getattr(self.model_type, field_name)
+ statement += lambda s: s.where(field.in_(values))
+ return statement
- def _filter_not_in_collection(self, field_name: str, values: abc.Collection[Any], statement: SelectT) -> SelectT:
+ def _filter_not_in_collection(
+ self, field_name: str, values: abc.Collection[Any], statement: StatementLambdaElement
+ ) -> StatementLambdaElement:
if not values:
return statement
- return statement.where(getattr(self.model_type, field_name).notin_(values))
+ field = getattr(self.model_type, field_name)
+ statement += lambda s: s.where(field.notin_(values))
+ return statement
def _filter_on_datetime_field(
self,
field_name: str,
- statement: SelectT,
+ statement: StatementLambdaElement,
before: datetime | None = None,
after: datetime | None = None,
on_or_before: datetime | None = None,
on_or_after: datetime | None = None,
- ) -> SelectT:
+ ) -> StatementLambdaElement:
field = getattr(self.model_type, field_name)
if before is not None:
- statement = statement.where(field < before)
+ statement += lambda s: s.where(field < before)
if after is not None:
- statement = statement.where(field > after)
+ statement += lambda s: s.where(field > after)
if on_or_before is not None:
- statement = statement.where(field <= on_or_before)
+ statement += lambda s: s.where(field <= on_or_before)
if on_or_after is not None:
- statement = statement.where(field >= on_or_after)
+ statement += lambda s: s.where(field >= on_or_after)
return statement
def _filter_select_by_kwargs(
- self, statement: SelectT, kwargs: dict[Any, Any] | Iterable[tuple[Any, Any]]
- ) -> SelectT:
+ self, statement: StatementLambdaElement, kwargs: dict[Any, Any] | Iterable[tuple[Any, Any]]
+ ) -> StatementLambdaElement:
for key, val in kwargs.items() if isinstance(kwargs, dict) else kwargs:
- statement = statement.where(get_instrumented_attr(self.model_type, key) == val) # pyright: ignore
+ statement = self._filter_by_where(statement, key, val) # pyright: ignore[reportGeneralTypeIssues]
+ return statement
+
+ def _filter_by_where(self, statement: StatementLambdaElement, key: str, val: Any) -> StatementLambdaElement:
+ model_type = self.model_type
+ field = get_instrumented_attr(model_type, key)
+ statement += lambda s: s.where(field == val)
return statement
def _filter_by_like(
- self, statement: SelectT, field_name: str | InstrumentedAttribute, value: str, ignore_case: bool
- ) -> SelectT:
+ self, statement: StatementLambdaElement, field_name: str | InstrumentedAttribute, value: str, ignore_case: bool
+ ) -> StatementLambdaElement:
field = get_instrumented_attr(self.model_type, field_name)
search_text = f"%{value}%"
- return statement.where(field.ilike(search_text) if ignore_case else field.like(search_text))
+ if ignore_case:
+ statement += lambda s: s.where(field.ilike(search_text))
+ else:
+ statement += lambda s: s.where(field.like(search_text))
+ return statement
- def _filter_by_not_like(self, statement: SelectT, field_name: str, value: str, ignore_case: bool) -> SelectT:
+ def _filter_by_not_like(
+ self, statement: StatementLambdaElement, field_name: str, value: str, ignore_case: bool
+ ) -> StatementLambdaElement:
field = getattr(self.model_type, field_name)
search_text = f"%{value}%"
- return statement.where(field.not_ilike(search_text) if ignore_case else field.not_like(search_text))
+ if ignore_case:
+ statement += lambda s: s.where(field.not_ilike(search_text))
+ else:
+ statement += lambda s: s.where(field.not_like(search_text))
+ return statement
def _order_by(
- self, statement: SelectT, field_name: str | InstrumentedAttribute, sort_desc: bool = False
- ) -> SelectT:
+ self, statement: StatementLambdaElement, field_name: str | InstrumentedAttribute, sort_desc: bool = False
+ ) -> StatementLambdaElement:
field = get_instrumented_attr(self.model_type, field_name)
- return statement.order_by(field.desc() if sort_desc else field.asc())
+ if sort_desc:
+ statement += lambda s: s.order_by(field.desc())
+ else:
+ statement += lambda s: s.order_by(field.asc())
+ return statement
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repository.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repository.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repository.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repository.py
@@ -573,6 +573,20 @@ async def test_repo_list_and_count_method(raw_authors: RawRecordData, author_rep
assert len(collection) == exp_count
+async def test_repo_list_and_count_basic_method(raw_authors: RawRecordData, author_repo: AuthorRepository) -> None:
+ """Test SQLAlchemy basic list with count in asyncpg.
+
+ Args:
+ raw_authors: list of authors pre-seeded into the mock repository
+ author_repo: The author mock repository
+ """
+ exp_count = len(raw_authors)
+ collection, count = await maybe_async(author_repo.list_and_count(force_basic_query_mode=True))
+ assert exp_count == count
+ assert isinstance(collection, list)
+ assert len(collection) == exp_count
+
+
async def test_repo_list_and_count_method_empty(book_repo: BookRepository) -> None:
collection, count = await maybe_async(book_repo.list_and_count())
assert 0 == count
diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_sqlalchemy.py
@@ -3,7 +3,7 @@
from datetime import datetime
from typing import TYPE_CHECKING, Union, cast
-from unittest.mock import AsyncMock, MagicMock, call
+from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
@@ -476,7 +476,7 @@ async def test_sqlalchemy_repo_list_and_count(mock_repo: SQLAlchemyAsyncReposito
"""Test expected method calls for list operation."""
mock_instances = [MagicMock(), MagicMock()]
mock_count = len(mock_instances)
- mocker.patch.object(mock_repo, "_list_and_count_window", return_value=(mock_instances, mock_count))
+ mocker.patch.object(mock_repo, "_list_and_count_basic", return_value=(mock_instances, mock_count))
mocker.patch.object(mock_repo, "_list_and_count_window", return_value=(mock_instances, mock_count))
instances, instance_count = await maybe_async(mock_repo.list_and_count())
@@ -487,6 +487,23 @@ async def test_sqlalchemy_repo_list_and_count(mock_repo: SQLAlchemyAsyncReposito
mock_repo.session.commit.assert_not_called()
+async def test_sqlalchemy_repo_list_and_count_basic(
+ mock_repo: SQLAlchemyAsyncRepository, mocker: MockerFixture
+) -> None:
+ """Test expected method calls for list operation."""
+ mock_instances = [MagicMock(), MagicMock()]
+ mock_count = len(mock_instances)
+ mocker.patch.object(mock_repo, "_list_and_count_basic", return_value=(mock_instances, mock_count))
+ mocker.patch.object(mock_repo, "_list_and_count_window", return_value=(mock_instances, mock_count))
+
+ instances, instance_count = await maybe_async(mock_repo.list_and_count(force_basic_query_mode=True))
+
+ assert instances == mock_instances
+ assert instance_count == mock_count
+ mock_repo.session.expunge.assert_not_called()
+ mock_repo.session.commit.assert_not_called()
+
+
async def test_sqlalchemy_repo_exists(
mock_repo: SQLAlchemyAsyncRepository,
monkeypatch: MonkeyPatch,
@@ -518,17 +535,15 @@ async def test_sqlalchemy_repo_count(
async def test_sqlalchemy_repo_list_with_pagination(
- mock_repo: SQLAlchemyAsyncRepository, monkeypatch: MonkeyPatch, mock_repo_execute: AnyMock
+ mock_repo: SQLAlchemyAsyncRepository, monkeypatch: MonkeyPatch, mock_repo_execute: AnyMock, mocker: MockerFixture
) -> None:
"""Test list operation with pagination."""
+ mocker.patch.object(mock_repo, "_apply_limit_offset_pagination", return_value=mock_repo.statement)
mock_repo_execute.return_value = MagicMock()
- mock_repo.statement.limit.return_value = mock_repo.statement
- mock_repo.statement.offset.return_value = mock_repo.statement
-
+ mock_repo.statement.where.return_value = mock_repo.statement
await maybe_async(mock_repo.list(LimitOffset(2, 3)))
-
- mock_repo.statement.limit.assert_called_once_with(2)
- mock_repo.statement.limit().offset.assert_called_once_with(3) # type:ignore[call-arg]
+ assert mock_repo._apply_limit_offset_pagination.call_count == 1
+ mock_repo._apply_limit_offset_pagination.assert_called_with(2, 3, statement=mock_repo.statement)
async def test_sqlalchemy_repo_list_with_before_after_filter(
@@ -537,14 +552,14 @@ async def test_sqlalchemy_repo_list_with_before_after_filter(
"""Test list operation with BeforeAfter filter."""
mocker.patch.object(mock_repo.model_type.updated_at, "__lt__", return_value="lt")
mocker.patch.object(mock_repo.model_type.updated_at, "__gt__", return_value="gt")
-
+ mocker.patch.object(mock_repo, "_filter_on_datetime_field", return_value=mock_repo.statement)
mock_repo_execute.return_value = MagicMock()
mock_repo.statement.where.return_value = mock_repo.statement
-
await maybe_async(mock_repo.list(BeforeAfter("updated_at", datetime.max, datetime.min)))
-
- assert mock_repo.statement.where.call_count == 2
- mock_repo.statement.where.assert_has_calls([call("gt"), call("lt")], any_order=True)
+ assert mock_repo._filter_on_datetime_field.call_count == 1
+ mock_repo._filter_on_datetime_field.assert_called_with(
+ field_name="updated_at", before=datetime.max, after=datetime.min, statement=mock_repo.statement
+ )
async def test_sqlalchemy_repo_list_with_on_before_after_filter(
@@ -553,43 +568,42 @@ async def test_sqlalchemy_repo_list_with_on_before_after_filter(
"""Test list operation with BeforeAfter filter."""
mocker.patch.object(mock_repo.model_type.updated_at, "__le__", return_value="le")
mocker.patch.object(mock_repo.model_type.updated_at, "__ge__", return_value="ge")
-
+ mocker.patch.object(mock_repo, "_filter_on_datetime_field", return_value=mock_repo.statement)
mock_repo_execute.return_value = MagicMock()
mock_repo.statement.where.return_value = mock_repo.statement
await maybe_async(mock_repo.list(OnBeforeAfter("updated_at", datetime.max, datetime.min)))
-
- assert mock_repo.statement.where.call_count == 2
- mock_repo.statement.where.assert_has_calls([call("ge"), call("le")], any_order=True)
+ assert mock_repo._filter_on_datetime_field.call_count == 1
+ mock_repo._filter_on_datetime_field.assert_called_with(
+ field_name="updated_at", on_or_before=datetime.max, on_or_after=datetime.min, statement=mock_repo.statement
+ )
async def test_sqlalchemy_repo_list_with_collection_filter(
- mock_repo: SQLAlchemyAsyncRepository, monkeypatch: MonkeyPatch, mock_repo_execute: AnyMock
+ mock_repo: SQLAlchemyAsyncRepository, monkeypatch: MonkeyPatch, mock_repo_execute: AnyMock, mocker: MockerFixture
) -> None:
"""Test behavior of list operation given CollectionFilter."""
field_name = "id"
mock_repo_execute.return_value = MagicMock()
mock_repo.statement.where.return_value = mock_repo.statement
+ mocker.patch.object(mock_repo, "_filter_in_collection", return_value=mock_repo.statement)
values = [1, 2, 3]
-
await maybe_async(mock_repo.list(CollectionFilter(field_name, values)))
-
- mock_repo.statement.where.assert_called_once()
- getattr(mock_repo.model_type, field_name).in_.assert_called_once_with(values)
+ assert mock_repo._filter_in_collection.call_count == 1
+ mock_repo._filter_in_collection.assert_called_with(field_name, values, statement=mock_repo.statement)
async def test_sqlalchemy_repo_list_with_not_in_collection_filter(
- mock_repo: SQLAlchemyAsyncRepository, monkeypatch: MonkeyPatch, mock_repo_execute: AnyMock
+ mock_repo: SQLAlchemyAsyncRepository, monkeypatch: MonkeyPatch, mock_repo_execute: AnyMock, mocker: MockerFixture
) -> None:
"""Test behavior of list operation given CollectionFilter."""
field_name = "id"
mock_repo_execute.return_value = MagicMock()
mock_repo.statement.where.return_value = mock_repo.statement
+ mocker.patch.object(mock_repo, "_filter_not_in_collection", return_value=mock_repo.statement)
values = [1, 2, 3]
-
await maybe_async(mock_repo.list(NotInCollectionFilter(field_name, values)))
-
- mock_repo.statement.where.assert_called_once()
- getattr(mock_repo.model_type, field_name).notin_.assert_called_once_with(values)
+ assert mock_repo._filter_not_in_collection.call_count == 1
+ mock_repo._filter_not_in_collection.assert_called_with(field_name, values, statement=mock_repo.statement)
async def test_sqlalchemy_repo_unknown_filter_type_raises(mock_repo: SQLAlchemyAsyncRepository) -> None:
@@ -650,7 +664,7 @@ async def test_execute(mock_repo: SQLAlchemyAsyncRepository) -> None:
def test_filter_in_collection_noop_if_collection_empty(mock_repo: SQLAlchemyAsyncRepository) -> None:
"""Ensures we don't filter on an empty collection."""
mock_repo._filter_in_collection("id", [], statement=mock_repo.statement)
- mock_repo.statement.where.assert_not_called() # type: ignore
+ mock_repo.statement.where.assert_not_called()
@pytest.mark.parametrize(
@@ -670,18 +684,21 @@ def test_filter_on_datetime_field(before: datetime, after: datetime, mock_repo:
mock_repo._filter_on_datetime_field("updated_at", before=before, after=after, statement=mock_repo.statement)
-def test_filter_collection_by_kwargs(mock_repo: SQLAlchemyAsyncRepository) -> None:
+def test_filter_collection_by_kwargs(mock_repo: SQLAlchemyAsyncRepository, mocker: MockerFixture) -> None:
"""Test `filter_by()` called with kwargs."""
+ mock_repo_execute.return_value = MagicMock()
+ mock_repo.statement.where.return_value = mock_repo.statement
+ mocker.patch.object(mock_repo, "filter_collection_by_kwargs", return_value=mock_repo.statement)
_ = mock_repo.filter_collection_by_kwargs(mock_repo.statement, a=1, b=2)
- mock_repo.statement.filter_by.assert_called_once_with(a=1, b=2)
+ mock_repo.filter_collection_by_kwargs.assert_called_once_with(mock_repo.statement, a=1, b=2)
def test_filter_collection_by_kwargs_raises_repository_exception_for_attribute_error(
- mock_repo: SQLAlchemyAsyncRepository,
+ mock_repo: SQLAlchemyAsyncRepository, mocker: MockerFixture
) -> None:
"""Test that we raise a repository exception if an attribute name is
incorrect."""
- mock_repo.statement.filter_by = MagicMock( # type:ignore[method-assign]
+ mock_repo.statement.filter_by = MagicMock( # pyright: ignore[reportGeneralTypeIssues]
side_effect=InvalidRequestError,
)
with pytest.raises(RepositoryError):
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-08-19T17:05:23 |
litestar-org/litestar | 2,182 | litestar-org__litestar-2182 | [
"2181",
"1234"
] | 3e712e7f80df10a61da45093576f3e9f767b7deb | diff --git a/litestar/security/session_auth/auth.py b/litestar/security/session_auth/auth.py
--- a/litestar/security/session_auth/auth.py
+++ b/litestar/security/session_auth/auth.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Callable, Dict, Generic, Iterable
+from typing import TYPE_CHECKING, Any, Callable, Dict, Generic, Iterable, Sequence, cast
from litestar.middleware.base import DefineMiddleware
from litestar.middleware.session.base import BaseBackendConfig, BaseSessionBackendT
@@ -14,7 +14,7 @@
if TYPE_CHECKING:
from litestar.connection import ASGIConnection
from litestar.di import Provide
- from litestar.types import ControllerRouterHandler, Guard, Scopes, SyncOrAsyncUnion, TypeEncodersMap
+ from litestar.types import ControllerRouterHandler, Guard, Method, Scopes, SyncOrAsyncUnion, TypeEncodersMap
@dataclass
@@ -46,6 +46,10 @@ class SessionAuth(Generic[UserType, BaseSessionBackendT], AbstractSecurityConfig
"""A pattern or list of patterns to skip in the authentication middleware."""
exclude_opt_key: str = field(default="exclude_from_auth")
"""An identifier to use on routes to disable authentication and authorization checks for a particular route."""
+ exclude_http_methods: Sequence[Method] | None = field(
+ default_factory=lambda: cast("Sequence[Method]", ["OPTIONS", "HEAD"])
+ )
+ """A sequence of http methods that do not require authentication. Defaults to ['OPTIONS', 'HEAD']"""
scopes: Scopes | None = field(default=None)
"""ASGI scopes processed by the authentication middleware, if ``None``, both ``http`` and ``websocket`` will be
processed."""
diff --git a/litestar/security/session_auth/middleware.py b/litestar/security/session_auth/middleware.py
--- a/litestar/security/session_auth/middleware.py
+++ b/litestar/security/session_auth/middleware.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Sequence
from litestar.exceptions import NotAuthorizedException
from litestar.middleware.authentication import (
@@ -9,11 +9,10 @@
)
from litestar.middleware.exceptions import ExceptionHandlerMiddleware
from litestar.middleware.session.base import SessionMiddleware
-from litestar.types import Empty, Scopes
+from litestar.types import Empty, Method, Scopes
__all__ = ("MiddlewareWrapper", "SessionAuthMiddleware")
-
if TYPE_CHECKING:
from litestar.connection import ASGIConnection
from litestar.security.session_auth.auth import SessionAuth
@@ -53,6 +52,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
auth_middleware = self.config.authentication_middleware_class(
app=self.app,
exclude=self.config.exclude,
+ exclude_http_methods=self.config.exclude_http_methods,
exclude_opt_key=self.config.exclude_opt_key,
scopes=self.config.scopes,
retrieve_user_handler=self.config.retrieve_user_handler, # type: ignore
@@ -77,20 +77,28 @@ def __init__(
self,
app: ASGIApp,
exclude: str | list[str] | None,
+ exclude_http_methods: Sequence[Method] | None,
exclude_opt_key: str,
- scopes: Scopes | None,
retrieve_user_handler: AsyncCallable[[dict[str, Any], ASGIConnection[Any, Any, Any, Any]], Any],
+ scopes: Scopes | None,
) -> None:
"""Session based authentication middleware.
Args:
app: An ASGIApp, this value is the next ASGI handler to call in the middleware stack.
exclude: A pattern or list of patterns to skip in the authentication middleware.
+ exclude_http_methods: A sequence of http methods that do not require authentication.
exclude_opt_key: An identifier to use on routes to disable authentication and authorization checks for a particular route.
scopes: ASGI scopes processed by the authentication middleware.
retrieve_user_handler: Callable that receives the ``session`` value from the authentication middleware and returns a ``user`` value.
"""
- super().__init__(app=app, exclude=exclude, exclude_from_auth_key=exclude_opt_key, scopes=scopes)
+ super().__init__(
+ app=app,
+ exclude=exclude,
+ exclude_from_auth_key=exclude_opt_key,
+ exclude_http_methods=exclude_http_methods,
+ scopes=scopes,
+ )
self.retrieve_user_handler = retrieve_user_handler
async def authenticate_request(self, connection: ASGIConnection[Any, Any, Any, Any]) -> AuthenticationResult:
| diff --git a/tests/unit/test_middleware/test_session/test_integration.py b/tests/unit/test_middleware/test_session/test_integration.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/test_middleware/test_session/test_integration.py
@@ -0,0 +1,70 @@
+from typing import Any, Dict, Literal, Optional
+from uuid import UUID
+
+from pydantic import BaseModel, EmailStr, SecretStr
+
+from litestar import Request, get, post
+from litestar.connection import ASGIConnection
+from litestar.exceptions import NotAuthorizedException
+from litestar.middleware.session.server_side import (
+ ServerSideSessionBackend,
+ ServerSideSessionConfig,
+)
+from litestar.security.session_auth import SessionAuth
+from litestar.status_codes import HTTP_204_NO_CONTENT
+from litestar.stores.memory import MemoryStore
+from litestar.testing import create_test_client
+
+
+class User(BaseModel):
+ id: UUID
+ name: str
+ email: EmailStr
+
+
+class UserLoginPayload(BaseModel):
+ email: EmailStr
+ password: SecretStr
+
+
+MOCK_DB: Dict[str, User] = {}
+memory_store = MemoryStore()
+
+
+async def retrieve_user_handler(
+ session: Dict[str, Any], connection: "ASGIConnection[Any, Any, Any, Any]"
+) -> Optional[User]:
+ return MOCK_DB.get(user_id) if (user_id := session.get("user_id")) else None
+
+
+@post("/login")
+async def login(data: UserLoginPayload, request: "Request[Any, Any, Any]") -> User:
+ user_id_bytes = await memory_store.get(data.email)
+
+ if not user_id_bytes:
+ raise NotAuthorizedException
+
+ user_id = user_id_bytes.decode("utf-8")
+ request.set_session({"user_id": user_id})
+ return MOCK_DB[user_id]
+
+
+@get("/user", sync_to_thread=False)
+def get_user(request: Request[User, Dict[Literal["user_id"], str], Any]) -> Any:
+ return request.user
+
+
+session_auth = SessionAuth[User, ServerSideSessionBackend](
+ retrieve_user_handler=retrieve_user_handler,
+ session_backend_config=ServerSideSessionConfig(),
+ exclude=["/login", "/schema"],
+)
+
+
+def test_options_request_with_session_auth() -> None:
+ with create_test_client(
+ route_handlers=[login, get_user],
+ on_app_init=[session_auth.on_app_init],
+ ) as client:
+ response = client.options(get_user.paths.pop())
+ assert response.status_code == HTTP_204_NO_CONTENT
| Bug: regression v2.0.0beta4 -> main@HEAD
### Description
There appears to be a regression between tag v2.0.0beta4 and the current (2.0.0rc1 PyPi release) (or if you prefer, also commit d257d099993179f1133a96441bf816e1de435007, which is the latest commit on main. This seems very likely related to #2160 which my guess would be only fixed the problem for JWT, not the SessionAuth middleware that I am using.
### URL to code causing the issue
https://github.com/Mattwmaster58/MacTrack/tree/broken-auth
### MCVE
```python
(working on this)
```
### Steps to reproduce
```bash
1. Clone repo, checkout `broken-auth` branch, poetry install, run, request to OPTIONS endpoint, observe:
`INFO: 127.0.0.1:55754 - "OPTIONS /api/filters/create HTTP/1.1" 401 Unauthorized`
```
### Screenshots
_No response_
### Logs
```bash
ERROR - 2023-08-19 18:27:03,266908605 - litestar - middleware - exception raised on http connection to route /api/filters/create
Traceback (most recent call last):
File "/home/user/Documents/projects/mac-track/api/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/user/Documents/projects/mac-track/api/.venv/lib/python3.11/site-packages/litestar/middleware/authentication.py", line 87, in __call__
auth_result = await self.authenticate_request(ASGIConnection(scope))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/Documents/projects/mac-track/api/.venv/lib/python3.11/site-packages/litestar/security/session_auth/middleware.py", line 111, in authenticate_request
raise NotAuthorizedException("no session data found")
litestar.exceptions.http_exceptions.NotAuthorizedException: 401: no session data found
Traceback (most recent call last):
File "/home/user/Documents/projects/mac-track/api/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/user/Documents/projects/mac-track/api/.venv/lib/python3.11/site-packages/litestar/middleware/authentication.py", line 87, in __call__
auth_result = await self.authenticate_request(ASGIConnection(scope))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/Documents/projects/mac-track/api/.venv/lib/python3.11/site-packages/litestar/security/session_auth/middleware.py", line 111, in authenticate_request
raise NotAuthorizedException("no session data found")
litestar.exceptions.http_exceptions.NotAuthorizedException: 401: no session data found
INFO: 127.0.0.1:55754 - "OPTIONS /api/filters/create HTTP/1.1" 401 Unauthorized
```
### Litestar Version
2.0.0rc1 as well as d257d099993179f1133a96441bf816e1de435007
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2181">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2181/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2181/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
|
I agree. Do you want to submit a PR? | 2023-08-19T23:11:43 |
litestar-org/litestar | 2,189 | litestar-org__litestar-2189 | [
"2138",
"2138"
] | f915b5a40b64c01a0cf8b7c83e9929b6eddca353 | diff --git a/litestar/response/redirect.py b/litestar/response/redirect.py
--- a/litestar/response/redirect.py
+++ b/litestar/response/redirect.py
@@ -6,7 +6,7 @@
from litestar.enums import MediaType
from litestar.exceptions import ImproperlyConfiguredException
from litestar.response.base import ASGIResponse, Response
-from litestar.status_codes import HTTP_307_TEMPORARY_REDIRECT
+from litestar.status_codes import HTTP_302_FOUND
from litestar.utils import url_quote
from litestar.utils.helpers import filter_cookies, get_enum_string_value
@@ -40,7 +40,7 @@ def __init__(
) -> None:
headers = {**(headers or {}), "location": url_quote(path)}
media_type = media_type or MediaType.TEXT
- status_code = status_code or HTTP_307_TEMPORARY_REDIRECT
+ status_code = status_code or HTTP_302_FOUND
if status_code not in REDIRECT_STATUS_CODES:
raise ImproperlyConfiguredException(
@@ -95,6 +95,8 @@ def __init__(
supported.
"""
self.url = path
+ if status_code is None:
+ status_code = HTTP_302_FOUND
super().__init__(
background=background,
content=b"",
| diff --git a/tests/unit/test_openapi/test_responses.py b/tests/unit/test_openapi/test_responses.py
--- a/tests/unit/test_openapi/test_responses.py
+++ b/tests/unit/test_openapi/test_responses.py
@@ -249,6 +249,23 @@ def handler() -> Stream:
def test_create_success_response_redirect() -> None:
+ @get(path="/test", name="test")
+ def redirect_handler() -> Redirect:
+ return Redirect(path="/target")
+
+ handler = get_registered_route_handler(redirect_handler, "test")
+
+ response = create_success_response(handler, SchemaCreator(generate_examples=True))
+ assert response.description == "Redirect Response"
+ assert response.headers
+ location = response.headers["location"]
+ assert isinstance(location, OpenAPIHeader)
+ assert isinstance(location.schema, Schema)
+ assert location.schema.type == OpenAPIType.STRING
+ assert location.description
+
+
+def test_create_success_response_redirect_override() -> None:
@get(path="/test", status_code=HTTP_307_TEMPORARY_REDIRECT, name="test")
def redirect_handler() -> Redirect:
return Redirect(path="/target")
diff --git a/tests/unit/test_response/test_redirect_response.py b/tests/unit/test_response/test_redirect_response.py
--- a/tests/unit/test_response/test_redirect_response.py
+++ b/tests/unit/test_response/test_redirect_response.py
@@ -110,8 +110,8 @@ def handler() -> Redirect:
def test_redirect(handler_status_code: Optional[int]) -> None:
@get("/", status_code=handler_status_code)
def handler() -> Redirect:
- return Redirect(path="/something-else", status_code=301)
+ return Redirect(path="/something-else", status_code=handler_status_code) # type: ignore[arg-type]
with create_test_client([handler]) as client:
res = client.get("/", follow_redirects=False)
- assert res.status_code == 301
+ assert res.status_code == 302 if handler_status_code is None else handler_status_code
| Enhancement: make 302 the default status_code for Redirect
### Summary
I wish `Redirect()` would have a default status_code of 302. This is, I believe, the most common use case.
### Basic Example
```
Redirect(url)
```
instead of
```
Redirect(url, status_code=HTTP_302_FOUND)
```
### Drawbacks and Impact
No impact on existing code.
Some people may use 302 by default when they actually meant to use something else.
### Unresolved questions
_No response_
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2138">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2138/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2138/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
Enhancement: make 302 the default status_code for Redirect
### Summary
I wish `Redirect()` would have a default status_code of 302. This is, I believe, the most common use case.
### Basic Example
```
Redirect(url)
```
instead of
```
Redirect(url, status_code=HTTP_302_FOUND)
```
### Drawbacks and Impact
No impact on existing code.
Some people may use 302 by default when they actually meant to use something else.
### Unresolved questions
_No response_
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2138">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2138/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2138/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-08-21T00:52:34 |
|
litestar-org/litestar | 2,204 | litestar-org__litestar-2204 | [
"2190",
"1234"
] | 65e9d8f1d3b2b5b6d6a8c30beda74ce763668097 | diff --git a/litestar/contrib/pydantic/pydantic_dto_factory.py b/litestar/contrib/pydantic/pydantic_dto_factory.py
--- a/litestar/contrib/pydantic/pydantic_dto_factory.py
+++ b/litestar/contrib/pydantic/pydantic_dto_factory.py
@@ -3,20 +3,23 @@
from dataclasses import replace
from typing import TYPE_CHECKING, Collection, Generic, TypeVar
+from typing_extensions import override
+
from litestar.dto.base_dto import AbstractDTO
from litestar.dto.data_structures import DTOFieldDefinition
from litestar.dto.field import DTO_FIELD_META_KEY, DTOField
-from litestar.exceptions import MissingDependencyException
+from litestar.exceptions import MissingDependencyException, ValidationException
from litestar.types.empty import Empty
if TYPE_CHECKING:
- from typing import Generator
+ from typing import Any, Generator
from litestar.typing import FieldDefinition
try:
import pydantic
+ from pydantic import ValidationError
if pydantic.VERSION.startswith("2"):
from pydantic_core import PydanticUndefined
@@ -33,6 +36,20 @@
class PydanticDTO(AbstractDTO[T], Generic[T]):
"""Support for domain modelling with Pydantic."""
+ @override
+ def decode_builtins(self, value: dict[str, Any]) -> Any:
+ try:
+ return super().decode_builtins(value)
+ except ValidationError as ex:
+ raise ValidationException(extra=ex.errors()) from ex
+
+ @override
+ def decode_bytes(self, value: bytes) -> Any:
+ try:
+ return super().decode_bytes(value)
+ except ValidationError as ex:
+ raise ValidationException(extra=ex.errors()) from ex
+
@classmethod
def generate_field_definitions(
cls, model_type: type[pydantic.BaseModel]
| diff --git a/tests/unit/test_contrib/test_pydantic/test_integration.py b/tests/unit/test_contrib/test_pydantic/test_integration.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/test_contrib/test_pydantic/test_integration.py
@@ -0,0 +1,54 @@
+from typing import Any
+
+from pydantic import VERSION, BaseModel, Field
+
+from litestar import post
+from litestar.contrib.pydantic.pydantic_dto_factory import PydanticDTO
+from litestar.testing import create_test_client
+
+
+def test_pydantic_validation_error_raises_400() -> None:
+ class Model(BaseModel):
+ foo: str = Field(max_length=2)
+
+ ModelDTO = PydanticDTO[Model]
+
+ @post(dto=ModelDTO)
+ def handler(data: Model) -> Model:
+ return data
+
+ model_json = {"foo": "too long"}
+ expected_errors: list[dict[str, Any]]
+
+ if VERSION.startswith("1"):
+ expected_errors = [
+ {
+ "loc": ["foo"],
+ "msg": "ensure this value has at most 2 characters",
+ "type": "value_error.any_str.max_length",
+ "ctx": {"limit_value": 2},
+ }
+ ]
+ else:
+ expected_errors = [
+ {
+ "type": "string_too_long",
+ "loc": ["foo"],
+ "msg": "String should have at most 2 characters",
+ "input": "too long",
+ "ctx": {"max_length": 2},
+ }
+ ]
+
+ with create_test_client(route_handlers=handler) as client:
+ response = client.post("/", json=model_json)
+
+ assert response.status_code == 400
+
+ extra = response.json()["extra"]
+
+ if VERSION.startswith("2"):
+ # the URL keeps on changing as per the installed pydantic version
+ extra[0].pop("url")
+
+ assert extra == expected_errors
diff --git a/tests/unit/test_contrib/test_pydantic/test_pydanticdt_dto_factory.py b/tests/unit/test_contrib/test_pydantic/test_pydantic_dto_factory.py
similarity index 100%
rename from tests/unit/test_contrib/test_pydantic/test_pydanticdt_dto_factory.py
rename to tests/unit/test_contrib/test_pydantic/test_pydantic_dto_factory.py
| Bug: pydantic validations aren't being handled by DTOs
### Description
In the documentation of Litestar we have:
> When a value fails pydantic validation, the result will be a ValidationException with the extra key set to the pydantic validation errors. Thus, this data will be made available for the API consumers by default.
But when combined with DTO's in a post request, if a pydantic validation fails the exception is not handled and the client receives an InternalServerError (500) instead of a BadRequest (400):
```
__pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)
pydantic_core._pydantic_core.ValidationError: 1 validation error for User
name
String should have at most 2 characters [type=string_too_long, input_value='abc', input_type=str]
For further information visit https://errors.pydantic.dev/2.2/v/string_too_long
Status code: 500
```
If the validation isn't handled by pydantic (or at least it isn't handled **first** by pydantic) it works, for example an Enum validation returns a proper 400 status code because `msgspec` catches it first:
```python
from enum import Enum
class NameEnum(str, Enum):
a = "A"
b = "B"
# (replace the User class of the example with this)
class User(BaseModel):
name: NameEnum
```
Output for incorrect Enum:
```
File ".../.venv/lib64/python3.11/site-packages/litestar/serialization/msgspec_hooks.py", line 191, in decode_json
raise SerializationException(str(msgspec_error)) from msgspec_error
litestar.exceptions.base_exceptions.SerializationException: Invalid enum value 'abc' - at `$.name`
...
File ".../.venv/lib64/python3.11/site-packages/litestar/routes/http.py", line 186, in _get_response_data
raise ClientException(str(e)) from e
litestar.exceptions.http_exceptions.ClientException: 400: Invalid enum value 'abc' - at `$.name`
```
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, post
from litestar.contrib.pydantic import PydanticDTO
from litestar.testing import TestClient
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(max_length=2)
UserDTO = PydanticDTO[User]
@post("/user", dto=UserDTO, sync_to_thread=False)
def create_user(data: User) -> User:
return data
with TestClient(Litestar([create_user], debug=True)) as client:
response = client.post("/user", json={"name": "abc"})
print(response.text)
print(f"Status code: {response.status_code}")
assert response.status_code == 201
```
### Steps to reproduce
```bash
1. Execute the MCVE
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.0.0rc1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2190">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2190/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2190/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| If no one else is looking into this, could someone assign this to me please?
I agree. Do you want to submit a PR? | 2023-08-23T15:37:57 |
litestar-org/litestar | 2,214 | litestar-org__litestar-2214 | [
"2208",
"1234"
] | 88de686dd44457ed34573e572f3268f61a361f93 | diff --git a/litestar/channels/plugin.py b/litestar/channels/plugin.py
--- a/litestar/channels/plugin.py
+++ b/litestar/channels/plugin.py
@@ -333,8 +333,6 @@ async def _on_shutdown(self) -> None:
]
)
- await self._backend.on_shutdown()
-
if self._sub_task:
self._sub_task.cancel()
with suppress(CancelledError):
@@ -345,6 +343,8 @@ async def _on_shutdown(self) -> None:
with suppress(CancelledError):
await self._pub_task
+ await self._backend.on_shutdown()
+
async def __aenter__(self) -> ChannelsPlugin:
await self._on_startup()
return self
| diff --git a/tests/docker_service_fixtures.py b/tests/docker_service_fixtures.py
--- a/tests/docker_service_fixtures.py
+++ b/tests/docker_service_fixtures.py
@@ -6,6 +6,7 @@
import subprocess
import sys
import timeit
+from pathlib import Path
from typing import Any, Awaitable, Callable, Generator
import asyncmy
@@ -53,7 +54,7 @@ def __init__(self, worker_id: str) -> None:
self._base_command = [
"docker",
"compose",
- "--file=tests/docker-compose.yml",
+ f"--file={Path(__file__).parent / 'docker-compose.yml'}",
f"--project-name=litestar_pytest-{worker_id}",
]
| Bug: Fix issues with py-redis >=4.5.0
### Description
We currently pin redis to version `4.4.4` because any version above that causes test failues. I was not able to determine the reason for this test failures, but this will cause issues for users who wish to use the newer versions of the library (version 5.0.0 is already out).
Tasks:
1. unpin the redis version.
2. fix the issues causing the test failures.
### URL to code causing the issue
_No response_
### MCVE
_No response_
### Steps to reproduce
_No response_
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
v2.0.0
### Platform
- [X] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2208">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2208/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2208/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
|
I agree. Do you want to submit a PR? | 2023-08-25T07:25:30 |
litestar-org/litestar | 2,223 | litestar-org__litestar-2223 | [
"4321",
"1234"
] | f227a8ce5538554b9f60b6fb4772e7bc530d1ef7 | diff --git a/litestar/stores/file.py b/litestar/stores/file.py
--- a/litestar/stores/file.py
+++ b/litestar/stores/file.py
@@ -64,7 +64,7 @@ def _write_sync(self, target_file: Path, storage_obj: StorageObject) -> None:
finally:
os.close(tmp_file_fd)
- shutil.move(tmp_file_name, target_file)
+ os.replace(tmp_file_name, target_file) # noqa: PTH105
renamed = True
finally:
if not renamed:
| diff --git a/tests/unit/test_stores.py b/tests/unit/test_stores.py
--- a/tests/unit/test_stores.py
+++ b/tests/unit/test_stores.py
@@ -344,7 +344,7 @@ def test_registry_register_exist_override(memory_store: MemoryStore) -> None:
async def test_file_store_handle_rename_fail(file_store: FileStore, mocker: MockerFixture) -> None:
- mocker.patch("litestar.stores.file.shutil.move", side_effect=OSError)
+ mocker.patch("litestar.stores.file.os.replace", side_effect=OSError)
mock_unlink = mocker.patch("litestar.stores.file.os.unlink")
await file_store.set("foo", "bar")
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-08-25T17:31:42 |
litestar-org/litestar | 2,224 | litestar-org__litestar-2224 | [
"2222"
] | f227a8ce5538554b9f60b6fb4772e7bc530d1ef7 | diff --git a/litestar/_openapi/parameters.py b/litestar/_openapi/parameters.py
--- a/litestar/_openapi/parameters.py
+++ b/litestar/_openapi/parameters.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-from dataclasses import replace
from typing import TYPE_CHECKING
from litestar.constants import RESERVED_KWARGS
@@ -49,8 +48,17 @@ def add(self, parameter: Parameter) -> None:
If an existing parameter with the same name but different type exists, raises
``ImproperlyConfiguredException``.
"""
+
if parameter.name not in self._parameters:
- self._parameters[parameter.name] = parameter
+ # because we are defining routes as unique per path, we have to handle here a situation when there is an optional
+ # path parameter. e.g. get(path=["/", "/{param:str}"]). When parsing the parameter for path, the route handler
+ # would still have a kwarg called param:
+ # def handler(param: str | None) -> ...
+ if parameter.param_in != ParamType.QUERY or all(
+ "{" + parameter.name + ":" not in path
+ for path in self.route_handler.paths
+ ):
+ self._parameters[parameter.name] = parameter
return
pre_existing = self._parameters[parameter.name]
@@ -83,8 +91,7 @@ def create_parameter(
if any(path_param.name == parameter_name for path_param in path_parameters):
param_in = ParamType.PATH
is_required = True
- path_parameter = next(p for p in path_parameters if parameter_name in p.name)
- result = schema_creator.for_field_definition(replace(field_definition, annotation=path_parameter.type))
+ result = schema_creator.for_field_definition(field_definition)
elif kwarg_definition and kwarg_definition.header:
parameter_name = kwarg_definition.header
param_in = ParamType.HEADER
@@ -193,7 +200,6 @@ def create_parameter_for_handler(
"""Create a list of path/query/header Parameter models for the given PathHandler."""
parameters = ParameterCollection(route_handler=route_handler)
dependency_providers = route_handler.resolve_dependencies()
-
layered_parameters = route_handler.resolve_layered_parameters()
unique_handler_fields = tuple(
| diff --git a/tests/unit/test_kwargs/test_path_params.py b/tests/unit/test_kwargs/test_path_params.py
--- a/tests/unit/test_kwargs/test_path_params.py
+++ b/tests/unit/test_kwargs/test_path_params.py
@@ -1,7 +1,7 @@
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from pathlib import Path
-from typing import Any
+from typing import Any, Optional
from unittest.mock import MagicMock
from uuid import UUID, uuid1, uuid4
@@ -172,3 +172,17 @@ def post_greeting(title: str) -> str:
response = client.post("/Moishe")
assert response.status_code == HTTP_201_CREATED
assert response.text == "Hello, Moishe!"
+
+
+def test_optional_path_parameter() -> None:
+ @get(path=["/", "/{message:str}"], media_type=MediaType.TEXT, sync_to_thread=False)
+ def handler(message: Optional[str]) -> str:
+ return message if message else "no message"
+
+ with create_test_client(route_handlers=[handler]) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_200_OK
+ assert response.text == "no message"
+ response = client.get("/hello")
+ assert response.status_code == HTTP_200_OK
+ assert response.text == "hello"
diff --git a/tests/unit/test_openapi/test_integration.py b/tests/unit/test_openapi/test_integration.py
--- a/tests/unit/test_openapi/test_integration.py
+++ b/tests/unit/test_openapi/test_integration.py
@@ -1,4 +1,4 @@
-from typing import Type
+from __future__ import annotations
import msgspec
import pytest
@@ -6,9 +6,9 @@
from pydantic import BaseModel, Field
from typing_extensions import Annotated
-from litestar import Controller, post
+from litestar import Controller, get, post
from litestar.app import DEFAULT_OPENAPI_CONFIG
-from litestar.enums import OpenAPIMediaType
+from litestar.enums import MediaType, OpenAPIMediaType, ParamType
from litestar.openapi import OpenAPIConfig, OpenAPIController
from litestar.serialization.msgspec_hooks import decode_json, encode_json, get_serializer
from litestar.status_codes import HTTP_200_OK, HTTP_404_NOT_FOUND
@@ -19,7 +19,7 @@
@pytest.mark.parametrize("create_examples", CREATE_EXAMPLES_VALUES)
def test_openapi_yaml(
- person_controller: Type[Controller], pet_controller: Type[Controller], create_examples: bool
+ person_controller: type[Controller], pet_controller: type[Controller], create_examples: bool
) -> None:
openapi_config = OpenAPIConfig("Example API", "1.0.0", create_examples=create_examples)
with create_test_client([person_controller, pet_controller], openapi_config=openapi_config) as client:
@@ -37,7 +37,7 @@ def test_openapi_yaml(
@pytest.mark.parametrize("create_examples", CREATE_EXAMPLES_VALUES)
def test_openapi_json(
- person_controller: Type[Controller], pet_controller: Type[Controller], create_examples: bool
+ person_controller: type[Controller], pet_controller: type[Controller], create_examples: bool
) -> None:
openapi_config = OpenAPIConfig("Example API", "1.0.0", create_examples=create_examples)
with create_test_client([person_controller, pet_controller], openapi_config=openapi_config) as client:
@@ -52,7 +52,7 @@ def test_openapi_json(
assert response.content == encode_json(openapi_schema.to_schema(), serializer)
-def test_openapi_yaml_not_allowed(person_controller: Type[Controller], pet_controller: Type[Controller]) -> None:
+def test_openapi_yaml_not_allowed(person_controller: type[Controller], pet_controller: type[Controller]) -> None:
openapi_config = DEFAULT_OPENAPI_CONFIG
openapi_config.enabled_endpoints.discard("openapi.yaml")
@@ -64,7 +64,7 @@ def test_openapi_yaml_not_allowed(person_controller: Type[Controller], pet_contr
assert response.status_code == HTTP_404_NOT_FOUND
-def test_openapi_json_not_allowed(person_controller: Type[Controller], pet_controller: Type[Controller]) -> None:
+def test_openapi_json_not_allowed(person_controller: type[Controller], pet_controller: type[Controller]) -> None:
openapi_config = DEFAULT_OPENAPI_CONFIG
openapi_config.enabled_endpoints.discard("openapi.json")
@@ -157,6 +157,7 @@ async def example_route() -> Lookup:
version="1.0.0",
create_examples=create_examples,
),
+ signature_namespace={"Lookup": Lookup},
) as client:
response = client.get("/schema/openapi.json")
assert response.status_code == HTTP_200_OK
@@ -193,6 +194,7 @@ async def example_route() -> Lookup:
version="1.0.0",
create_examples=create_examples,
),
+ signature_namespace={"Lookup": Lookup},
) as client:
response = client.get("/schema/openapi.json")
assert response.status_code == HTTP_200_OK
@@ -203,3 +205,25 @@ async def example_route() -> Lookup:
"minLength": 12,
"type": "string",
}
+
+
+def test_schema_for_optional_path_parameter() -> None:
+ @get(path=["/", "/{test_message:str}"], media_type=MediaType.TEXT, sync_to_thread=False)
+ def handler(test_message: str | None) -> str:
+ return test_message if test_message else "no message"
+
+ with create_test_client(
+ route_handlers=[handler],
+ openapi_config=OpenAPIConfig(
+ title="Example API",
+ version="1.0.0",
+ create_examples=True,
+ ),
+ ) as client:
+ response = client.get("/schema/openapi.json")
+ assert response.status_code == HTTP_200_OK
+ assert "parameters" not in response.json()["paths"]["/"]["get"] # type[ignore]
+ parameter = response.json()["paths"]["/{test_message}"]["get"]["parameters"][0] # type[ignore]
+ assert parameter
+ assert parameter["in"] == ParamType.PATH
+ assert parameter["name"] == "test_message"
| Bug: OpenAPI generation throws exception when using an optional path value
### Description
I think I found an OpenAPI generation bug when using multiple paths on the same route with an optional path parameter value. The first call to /schema always fails with a 500 status code. Subsequent calls are successful but do not contain the problem route. I assume this is due to caching.
Another interesting thing I found is that if you load /schema/openapi.json first, you still get a 500 the first time but the cache is built with the route defined for subsequent calls. Although, the parameter is listed as a query parameter instead of a path parameter.
Thanks!
Kyle
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, get, MediaType
@get(path=["/", "/{message:str}"], media_type=MediaType.TEXT, sync_to_thread=False)
def route(message: str | None) -> str:
if message:
return message
return "no message"
app = Litestar(route_handlers=[route])
```
### Steps to reproduce
```bash
* Run app: litestar run
* Load http://localhost:8000/schema
* Get 500 Internal Server Error
```
### Screenshots
_No response_
### Logs
```bash
Traceback (most recent call last):
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/routes/http.py", line 206, in _get_response_data
data = route_handler.fn.value(**parsed_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/openapi/controller.py", line 197, in root
return ASGIResponse(body=render_method(request), media_type=MediaType.HTML)
^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/openapi/controller.py", line 357, in render_redoc
schema = self.get_schema_from_request(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/openapi/controller.py", line 85, in get_schema_from_request
return request.app.openapi_schema
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/app.py", line 562, in openapi_schema
self.update_openapi_schema()
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/app.py", line 818, in update_openapi_schema
path_item, created_operation_ids = create_path_item(
^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/path_item.py", line 97, in create_path_item
create_parameter_for_handler(
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/parameters.py", line 214, in create_parameter_for_handler
for parameter in get_recursive_handler_parameters(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/parameters.py", line 131, in get_recursive_handler_parameters
create_parameter(
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/parameters.py", line 87, in create_parameter
result = schema_creator.for_field_definition(replace(field_definition, annotation=path_parameter.type))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/schema_generation/schema.py", line 265, in for_field_definition
result = self.for_optional_field(field_definition)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/schema_generation/schema.py", line 306, in for_optional_field
annotation=make_non_optional_union(field_definition.annotation),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/utils/typing.py", line 175, in make_non_optional_union
return cast("UnionT", Union[args]) # pyright: ignore
~~~~~^^^^^^
File "/home/ksmith/.pyenv/versions/3.11.4/lib/python3.11/typing.py", line 355, in inner
return func(*args, **kwds)
^^^^^^^^^^^^^^^^^^^
File "/home/ksmith/.pyenv/versions/3.11.4/lib/python3.11/typing.py", line 478, in __getitem__
return self._getitem(self, parameters)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ksmith/.pyenv/versions/3.11.4/lib/python3.11/typing.py", line 685, in Union
raise TypeError("Cannot take a Union of no types.")
TypeError: Cannot take a Union of no types.
Traceback (most recent call last):
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/routes/http.py", line 206, in _get_response_data
data = route_handler.fn.value(**parsed_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/openapi/controller.py", line 197, in root
return ASGIResponse(body=render_method(request), media_type=MediaType.HTML)
^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/openapi/controller.py", line 357, in render_redoc
schema = self.get_schema_from_request(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/openapi/controller.py", line 85, in get_schema_from_request
return request.app.openapi_schema
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/app.py", line 562, in openapi_schema
self.update_openapi_schema()
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/app.py", line 818, in update_openapi_schema
path_item, created_operation_ids = create_path_item(
^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/path_item.py", line 97, in create_path_item
create_parameter_for_handler(
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/parameters.py", line 214, in create_parameter_for_handler
for parameter in get_recursive_handler_parameters(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/parameters.py", line 131, in get_recursive_handler_parameters
create_parameter(
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/parameters.py", line 87, in create_parameter
result = schema_creator.for_field_definition(replace(field_definition, annotation=path_parameter.type))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/schema_generation/schema.py", line 265, in for_field_definition
result = self.for_optional_field(field_definition)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/_openapi/schema_generation/schema.py", line 306, in for_optional_field
annotation=make_non_optional_union(field_definition.annotation),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/mvce/.venv/lib/python3.11/site-packages/litestar/utils/typing.py", line 175, in make_non_optional_union
return cast("UnionT", Union[args]) # pyright: ignore
~~~~~^^^^^^
File "/home/ksmith/.pyenv/versions/3.11.4/lib/python3.11/typing.py", line 355, in inner
return func(*args, **kwds)
^^^^^^^^^^^^^^^^^^^
File "/home/ksmith/.pyenv/versions/3.11.4/lib/python3.11/typing.py", line 478, in __getitem__
return self._getitem(self, parameters)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ksmith/.pyenv/versions/3.11.4/lib/python3.11/typing.py", line 685, in Union
raise TypeError("Cannot take a Union of no types.")
TypeError: Cannot take a Union of no types.
```
### Litestar Version
2.0.1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2222">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2222/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2222/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| +1: I noticed this behavior yesterday, I'm also getting a 500 on first page load of the schema paths
Can you give a minimum reproduction? | 2023-08-25T18:51:08 |
litestar-org/litestar | 2,244 | litestar-org__litestar-2244 | [
"4321",
"1234"
] | 2f4219a87d61887d442ebda0aa9e02069727bc17 | diff --git a/litestar/cli/main.py b/litestar/cli/main.py
--- a/litestar/cli/main.py
+++ b/litestar/cli/main.py
@@ -27,7 +27,7 @@
click.rich_click.STYLE_ERRORS_SUGGESTION = "magenta italic"
click.rich_click.ERRORS_SUGGESTION = ""
click.rich_click.ERRORS_EPILOGUE = ""
- click.rich_click.MAX_WIDTH = 100
+ click.rich_click.MAX_WIDTH = 80
click.rich_click.SHOW_METAVARS_COLUMN = True
click.rich_click.APPEND_METAVARS_HELP = True
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-08-27T18:59:16 |
|
litestar-org/litestar | 2,259 | litestar-org__litestar-2259 | [
"4321",
"1234"
] | 8474267a76f4304e90e208a746f3985d873d0e75 | diff --git a/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py b/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py
--- a/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py
+++ b/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py
@@ -63,7 +63,7 @@ def run_script() -> None:
USState.metadata.create_all(conn)
with session_factory() as db_session:
- # 1) load the JSON data into the US States table
+ # 1) Load the JSON data into the US States table.
repo = USStateRepository(session=db_session)
fixture = open_fixture(here, USStateRepository.model_type.__tablename__) # type: ignore
objs = repo.add_many([USStateRepository.model_type(**raw_obj) for raw_obj in fixture])
@@ -74,11 +74,11 @@ def run_script() -> None:
created_objs, total_objs = repo.list_and_count(LimitOffset(limit=10, offset=0))
console.print(f"Selected {len(created_objs)} records out of a total of {total_objs}.")
- # 2) Let's remove the batch of records selected.
+ # 3) Let's remove the batch of records selected.
deleted_objs = repo.delete_many([new_obj.id for new_obj in created_objs])
console.print(f"Removed {len(deleted_objs)} records out of a total of {total_objs}.")
- # 3) Le'ts count the remaining rows
+ # 4) Let's count the remaining rows
remaining_count = repo.count()
console.print(f"Found {remaining_count} remaining records after delete.")
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-08-29T22:51:49 |
|
litestar-org/litestar | 2,265 | litestar-org__litestar-2265 | [
"4321",
"1234"
] | 8277182fd978bb33e50f80c3386f96cd8f929e54 | diff --git a/litestar/contrib/sqlalchemy/repository/_async.py b/litestar/contrib/sqlalchemy/repository/_async.py
--- a/litestar/contrib/sqlalchemy/repository/_async.py
+++ b/litestar/contrib/sqlalchemy/repository/_async.py
@@ -16,6 +16,7 @@
)
from sqlalchemy import func as sql_func
from sqlalchemy.orm import InstrumentedAttribute
+from sqlalchemy.sql import ColumnElement, ColumnExpressionArgument
from litestar.repository import AbstractAsyncRepository, RepositoryError
from litestar.repository.filters import (
@@ -42,6 +43,8 @@
DEFAULT_INSERTMANYVALUES_MAX_PARAMETERS: Final = 950
+WhereClauseT = ColumnExpressionArgument[bool]
+
class SQLAlchemyAsyncRepository(AbstractAsyncRepository[ModelT], Generic[ModelT]):
"""SQLAlchemy based implementation of the repository interface."""
@@ -247,7 +250,7 @@ async def delete_many(
def _get_insertmanyvalues_max_parameters(self, chunk_size: int | None = None) -> int:
return chunk_size if chunk_size is not None else DEFAULT_INSERTMANYVALUES_MAX_PARAMETERS
- async def exists(self, *filters: FilterTypes, **kwargs: Any) -> bool:
+ async def exists(self, *filters: FilterTypes | ColumnElement[bool], **kwargs: Any) -> bool:
"""Return true if the object specified by ``kwargs`` exists.
Args:
@@ -438,7 +441,7 @@ async def get_or_create(
async def count(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> int:
@@ -455,9 +458,10 @@ async def count(
"""
statement = self._get_base_stmt(statement)
fragment = self.get_id_attribute_value(self.model_type)
- statement += lambda s: s.with_only_columns(sql_func.count(fragment), maintain_column_froms=True).order_by(None)
- statement = self._apply_filters(*filters, apply_pagination=False, statement=statement)
+ statement += lambda s: s.with_only_columns(sql_func.count(fragment), maintain_column_froms=True)
+ statement += lambda s: s.order_by(None)
statement = self._filter_select_by_kwargs(statement, kwargs)
+ statement = self._apply_filters(*filters, apply_pagination=False, statement=statement)
results = await self._execute(statement)
return results.scalar_one() # type: ignore
@@ -567,7 +571,7 @@ def _get_update_many_statement(model_type: type[ModelT], supports_returning: boo
async def list_and_count(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
auto_commit: bool | None = None,
auto_expunge: bool | None = None,
auto_refresh: bool | None = None,
@@ -627,7 +631,7 @@ async def _refresh(
async def _list_and_count_window(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
auto_expunge: bool | None = None,
statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
@@ -663,7 +667,7 @@ async def _list_and_count_window(
async def _list_and_count_basic(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
auto_expunge: bool | None = None,
statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
@@ -795,7 +799,7 @@ async def upsert_many(
async def list(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
auto_expunge: bool | None = None,
statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
@@ -890,7 +894,10 @@ def _apply_limit_offset_pagination(
return statement
def _apply_filters(
- self, *filters: FilterTypes, apply_pagination: bool = True, statement: StatementLambdaElement
+ self,
+ *filters: FilterTypes | ColumnElement[bool],
+ apply_pagination: bool = True,
+ statement: StatementLambdaElement,
) -> StatementLambdaElement:
"""Apply filters to a select statement.
@@ -906,7 +913,9 @@ def _apply_filters(
The select with filters applied.
"""
for filter_ in filters:
- if isinstance(filter_, LimitOffset):
+ if isinstance(filter_, ColumnElement):
+ statement = self._filter_by_expression(expression=filter_, statement=statement)
+ elif isinstance(filter_, LimitOffset):
if apply_pagination:
statement = self._apply_limit_offset_pagination(filter_.limit, filter_.offset, statement=statement)
elif isinstance(filter_, BeforeAfter):
@@ -987,10 +996,18 @@ def _filter_select_by_kwargs(
statement = self._filter_by_where(statement, key, val) # pyright: ignore[reportGeneralTypeIssues]
return statement
- def _filter_by_where(self, statement: StatementLambdaElement, key: str, val: Any) -> StatementLambdaElement:
+ def _filter_by_expression(
+ self, statement: StatementLambdaElement, expression: ColumnElement[bool]
+ ) -> StatementLambdaElement:
+ statement += lambda s: s.filter(expression)
+ return statement
+
+ def _filter_by_where(
+ self, statement: StatementLambdaElement, field_name: str | InstrumentedAttribute, value: Any
+ ) -> StatementLambdaElement:
model_type = self.model_type
- field = get_instrumented_attr(model_type, key)
- statement += lambda s: s.where(field == val)
+ field = get_instrumented_attr(model_type, field_name)
+ statement += lambda s: s.where(field == value)
return statement
def _filter_by_like(
@@ -1005,9 +1022,9 @@ def _filter_by_like(
return statement
def _filter_by_not_like(
- self, statement: StatementLambdaElement, field_name: str, value: str, ignore_case: bool
+ self, statement: StatementLambdaElement, field_name: str | InstrumentedAttribute, value: str, ignore_case: bool
) -> StatementLambdaElement:
- field = getattr(self.model_type, field_name)
+ field = get_instrumented_attr(self.model_type, field_name)
search_text = f"%{value}%"
if ignore_case:
statement += lambda s: s.where(field.not_ilike(search_text))
diff --git a/litestar/contrib/sqlalchemy/repository/_sync.py b/litestar/contrib/sqlalchemy/repository/_sync.py
--- a/litestar/contrib/sqlalchemy/repository/_sync.py
+++ b/litestar/contrib/sqlalchemy/repository/_sync.py
@@ -18,6 +18,7 @@
)
from sqlalchemy import func as sql_func
from sqlalchemy.orm import InstrumentedAttribute, Session
+from sqlalchemy.sql import ColumnElement, ColumnExpressionArgument
from litestar.repository import AbstractSyncRepository, RepositoryError
from litestar.repository.filters import (
@@ -43,6 +44,8 @@
DEFAULT_INSERTMANYVALUES_MAX_PARAMETERS: Final = 950
+WhereClauseT = ColumnExpressionArgument[bool]
+
class SQLAlchemySyncRepository(AbstractSyncRepository[ModelT], Generic[ModelT]):
"""SQLAlchemy based implementation of the repository interface."""
@@ -248,7 +251,7 @@ def delete_many(
def _get_insertmanyvalues_max_parameters(self, chunk_size: int | None = None) -> int:
return chunk_size if chunk_size is not None else DEFAULT_INSERTMANYVALUES_MAX_PARAMETERS
- def exists(self, *filters: FilterTypes, **kwargs: Any) -> bool:
+ def exists(self, *filters: FilterTypes | ColumnElement[bool], **kwargs: Any) -> bool:
"""Return true if the object specified by ``kwargs`` exists.
Args:
@@ -439,7 +442,7 @@ def get_or_create(
def count(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
) -> int:
@@ -456,9 +459,10 @@ def count(
"""
statement = self._get_base_stmt(statement)
fragment = self.get_id_attribute_value(self.model_type)
- statement += lambda s: s.with_only_columns(sql_func.count(fragment), maintain_column_froms=True).order_by(None)
- statement = self._apply_filters(*filters, apply_pagination=False, statement=statement)
+ statement += lambda s: s.with_only_columns(sql_func.count(fragment), maintain_column_froms=True)
+ statement += lambda s: s.order_by(None)
statement = self._filter_select_by_kwargs(statement, kwargs)
+ statement = self._apply_filters(*filters, apply_pagination=False, statement=statement)
results = self._execute(statement)
return results.scalar_one() # type: ignore
@@ -568,7 +572,7 @@ def _get_update_many_statement(model_type: type[ModelT], supports_returning: boo
def list_and_count(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
auto_commit: bool | None = None,
auto_expunge: bool | None = None,
auto_refresh: bool | None = None,
@@ -628,7 +632,7 @@ def _refresh(
def _list_and_count_window(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
auto_expunge: bool | None = None,
statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
@@ -664,7 +668,7 @@ def _list_and_count_window(
def _list_and_count_basic(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
auto_expunge: bool | None = None,
statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
@@ -796,7 +800,7 @@ def upsert_many(
def list(
self,
- *filters: FilterTypes,
+ *filters: FilterTypes | ColumnElement[bool],
auto_expunge: bool | None = None,
statement: Select[tuple[ModelT]] | StatementLambdaElement | None = None,
**kwargs: Any,
@@ -891,7 +895,10 @@ def _apply_limit_offset_pagination(
return statement
def _apply_filters(
- self, *filters: FilterTypes, apply_pagination: bool = True, statement: StatementLambdaElement
+ self,
+ *filters: FilterTypes | ColumnElement[bool],
+ apply_pagination: bool = True,
+ statement: StatementLambdaElement,
) -> StatementLambdaElement:
"""Apply filters to a select statement.
@@ -907,7 +914,9 @@ def _apply_filters(
The select with filters applied.
"""
for filter_ in filters:
- if isinstance(filter_, LimitOffset):
+ if isinstance(filter_, ColumnElement):
+ statement = self._filter_by_expression(expression=filter_, statement=statement)
+ elif isinstance(filter_, LimitOffset):
if apply_pagination:
statement = self._apply_limit_offset_pagination(filter_.limit, filter_.offset, statement=statement)
elif isinstance(filter_, BeforeAfter):
@@ -988,10 +997,18 @@ def _filter_select_by_kwargs(
statement = self._filter_by_where(statement, key, val) # pyright: ignore[reportGeneralTypeIssues]
return statement
- def _filter_by_where(self, statement: StatementLambdaElement, key: str, val: Any) -> StatementLambdaElement:
+ def _filter_by_expression(
+ self, statement: StatementLambdaElement, expression: ColumnElement[bool]
+ ) -> StatementLambdaElement:
+ statement += lambda s: s.filter(expression)
+ return statement
+
+ def _filter_by_where(
+ self, statement: StatementLambdaElement, field_name: str | InstrumentedAttribute, value: Any
+ ) -> StatementLambdaElement:
model_type = self.model_type
- field = get_instrumented_attr(model_type, key)
- statement += lambda s: s.where(field == val)
+ field = get_instrumented_attr(model_type, field_name)
+ statement += lambda s: s.where(field == value)
return statement
def _filter_by_like(
@@ -1006,9 +1023,9 @@ def _filter_by_like(
return statement
def _filter_by_not_like(
- self, statement: StatementLambdaElement, field_name: str, value: str, ignore_case: bool
+ self, statement: StatementLambdaElement, field_name: str | InstrumentedAttribute, value: str, ignore_case: bool
) -> StatementLambdaElement:
- field = getattr(self.model_type, field_name)
+ field = get_instrumented_attr(self.model_type, field_name)
search_text = f"%{value}%"
if ignore_case:
statement += lambda s: s.where(field.not_ilike(search_text))
| diff --git a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repository.py b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repository.py
--- a/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repository.py
+++ b/tests/unit/test_contrib/test_sqlalchemy/test_repository/test_repository.py
@@ -559,6 +559,23 @@ async def test_repo_count_method(author_repo: AuthorRepository) -> None:
assert await maybe_async(author_repo.count()) == 2
+async def test_repo_count_method_with_filters(raw_authors: RawRecordData, author_repo: AuthorRepository) -> None:
+ """Test SQLAlchemy count with filters.
+
+ Args:
+ author_repo: The author mock repository
+ """
+ assert (
+ await maybe_async(
+ author_repo.count(
+ author_repo.model_type.id == raw_authors[0]["id"],
+ author_repo.model_type.name == raw_authors[0]["name"],
+ )
+ )
+ == 1
+ )
+
+
async def test_repo_list_and_count_method(raw_authors: RawRecordData, author_repo: AuthorRepository) -> None:
"""Test SQLAlchemy list with count in asyncpg.
@@ -573,6 +590,27 @@ async def test_repo_list_and_count_method(raw_authors: RawRecordData, author_rep
assert len(collection) == exp_count
+async def test_repo_list_and_count_method_with_filters(
+ raw_authors: RawRecordData, author_repo: AuthorRepository
+) -> None:
+ """Test SQLAlchemy list with count and filters in asyncpg.
+
+ Args:
+ raw_authors: list of authors pre-seeded into the mock repository
+ author_repo: The author mock repository
+ """
+ exp_name = raw_authors[0]["name"]
+ exp_id = raw_authors[0]["id"]
+ collection, count = await maybe_async(
+ author_repo.list_and_count(author_repo.model_type.id == exp_id, author_repo.model_type.name == exp_name)
+ )
+ assert count == 1
+ assert isinstance(collection, list)
+ assert len(collection) == 1
+ assert collection[0].id == exp_id
+ assert collection[0].name == exp_name
+
+
async def test_repo_list_and_count_basic_method(raw_authors: RawRecordData, author_repo: AuthorRepository) -> None:
"""Test SQLAlchemy basic list with count in asyncpg.
@@ -624,6 +662,21 @@ async def test_repo_list_method(
assert len(collection) == exp_count
+async def test_repo_list_method_with_filters(
+ raw_authors: RawRecordData,
+ author_repo: AuthorRepository,
+) -> None:
+ exp_name = raw_authors[0]["name"]
+ exp_id = raw_authors[0]["id"]
+ collection = await maybe_async(
+ author_repo.list(author_repo.model_type.id == exp_id, author_repo.model_type.name == exp_name)
+ )
+ assert isinstance(collection, list)
+ assert len(collection) == 1
+ assert collection[0].id == exp_id
+ assert collection[0].name == exp_name
+
+
async def test_repo_add_method(
raw_authors: RawRecordData, author_repo: AuthorRepository, author_model: AuthorModel
) -> None:
@@ -675,6 +728,18 @@ async def test_repo_exists_method(author_repo: AuthorRepository, first_author_id
assert exists
+async def test_repo_exists_method_with_filters(
+ raw_authors: RawRecordData, author_repo: AuthorRepository, first_author_id: Any
+) -> None:
+ exists = await maybe_async(
+ author_repo.exists(
+ author_repo.model_type.name == raw_authors[0]["name"],
+ id=first_author_id,
+ )
+ )
+ assert exists
+
+
async def test_repo_update_method(author_repo: AuthorRepository, first_author_id: Any) -> None:
obj = await maybe_async(author_repo.get(first_author_id))
obj.name = "Updated Name"
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-08-30T16:31:21 |
litestar-org/litestar | 2,269 | litestar-org__litestar-2269 | [
"4321",
"1234"
] | 3b3ed502de26bb945857fa8b94af45afdde7e075 | diff --git a/litestar/contrib/sqlalchemy/plugins/__init__.py b/litestar/contrib/sqlalchemy/plugins/__init__.py
--- a/litestar/contrib/sqlalchemy/plugins/__init__.py
+++ b/litestar/contrib/sqlalchemy/plugins/__init__.py
@@ -1,5 +1,10 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
+
+from litestar.contrib.sqlalchemy.plugins import _slots_base
+from litestar.plugins import InitPluginProtocol
+
from .init import (
AsyncSessionConfig,
EngineConfig,
@@ -12,13 +17,29 @@
)
from .serialization import SQLAlchemySerializationPlugin
+if TYPE_CHECKING:
+ from litestar.config.app import AppConfig
+
-class SQLAlchemyPlugin(SQLAlchemyInitPlugin, SQLAlchemySerializationPlugin):
+class SQLAlchemyPlugin(InitPluginProtocol, _slots_base.SlotsBase):
"""A plugin that provides SQLAlchemy integration."""
def __init__(self, config: SQLAlchemyAsyncConfig | SQLAlchemySyncConfig) -> None:
- SQLAlchemyInitPlugin.__init__(self, config=config)
- SQLAlchemySerializationPlugin.__init__(self)
+ """Initialize ``SQLAlchemyPlugin``.
+
+ Args:
+ config: configure DB connection and hook handlers and dependencies.
+ """
+ self._config = config
+
+ def on_app_init(self, app_config: AppConfig) -> AppConfig:
+ """Configure application for use with SQLAlchemy.
+
+ Args:
+ app_config: The :class:`AppConfig <.config.app.AppConfig>` instance.
+ """
+ app_config.plugins.extend([SQLAlchemyInitPlugin(config=self._config), SQLAlchemySerializationPlugin()])
+ return app_config
__all__ = (
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-09-01T18:35:55 |
|
litestar-org/litestar | 2,277 | litestar-org__litestar-2277 | [
"2266",
"1234"
] | c36dba249337062266fe2175a256ed7de099fa0e | diff --git a/litestar/cli/_utils.py b/litestar/cli/_utils.py
--- a/litestar/cli/_utils.py
+++ b/litestar/cli/_utils.py
@@ -91,12 +91,12 @@ class LitestarEnv:
is_app_factory: bool = False
@classmethod
- def from_env(cls, app_path: str | None) -> LitestarEnv:
+ def from_env(cls, app_path: str | None, app_dir: Path | None = None) -> LitestarEnv:
"""Load environment variables.
If ``python-dotenv`` is installed, use it to populate environment first
"""
- cwd = Path().cwd()
+ cwd = Path().cwd() if app_dir is None else app_dir
cwd_str_path = str(cwd)
if cwd_str_path not in sys.path:
sys.path.append(cwd_str_path)
@@ -212,7 +212,7 @@ def _prepare(self, ctx: Context) -> None:
env: LitestarEnv | None = ctx.obj
else:
try:
- env = ctx.obj = LitestarEnv.from_env(ctx.params.get("app_path"))
+ env = ctx.obj = LitestarEnv.from_env(ctx.params.get("app_path"), ctx.params.get("app_dir"))
except LitestarCLIException:
env = None
diff --git a/litestar/cli/main.py b/litestar/cli/main.py
--- a/litestar/cli/main.py
+++ b/litestar/cli/main.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import sys
from pathlib import Path
from typing import TYPE_CHECKING
@@ -47,10 +46,8 @@
@pass_context
def litestar_group(ctx: Context, app_path: str | None, app_dir: Path | None = None) -> None:
"""Litestar CLI."""
- sys.path.append(str(app_dir))
-
if ctx.obj is None: # env has not been loaded yet, so we can lazy load it
- ctx.obj = lambda: LitestarEnv.from_env(app_path)
+ ctx.obj = lambda: LitestarEnv.from_env(app_path, app_dir=app_dir)
# add sub commands here
| diff --git a/tests/unit/test_cli/test_cli.py b/tests/unit/test_cli/test_cli.py
--- a/tests/unit/test_cli/test_cli.py
+++ b/tests/unit/test_cli/test_cli.py
@@ -3,6 +3,9 @@
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
+from tests.unit.test_cli import CREATE_APP_FILE_CONTENT
+from tests.unit.test_cli.conftest import CreateAppFileFixture
+
try:
from rich_click import group
except ImportError:
@@ -38,6 +41,25 @@ def test_info_command(mocker: "MockerFixture", runner: "CliRunner", app_file: "P
mock.assert_called_once()
+def test_info_command_with_app_dir(
+ mocker: "MockerFixture", runner: "CliRunner", create_app_file: CreateAppFileFixture
+) -> None:
+ app_file = "main.py"
+ app_file_without_extension = app_file.split(".")[0]
+ create_app_file(
+ file=app_file,
+ directory="src",
+ content=CREATE_APP_FILE_CONTENT,
+ subdir="info_with_app_dir",
+ init_content=f"from .{app_file_without_extension} import create_app",
+ )
+ mock = mocker.patch("litestar.cli.commands.core.show_app_info")
+ result = runner.invoke(cli_command, ["--app", "info_with_app_dir:create_app", "--app-dir", "src", "info"])
+
+ assert result.exception is None
+ mock.assert_called_once()
+
+
def test_register_commands_from_entrypoint(mocker: "MockerFixture", runner: "CliRunner", app_file: "Path") -> None:
mock_command_callback = MagicMock()
diff --git a/tests/unit/test_cli/test_core_commands.py b/tests/unit/test_cli/test_core_commands.py
--- a/tests/unit/test_cli/test_core_commands.py
+++ b/tests/unit/test_cli/test_core_commands.py
@@ -127,7 +127,7 @@ def test_run_command(
else:
args.extend([f"--reload-dir={s}" for s in reload_dir])
- path = create_app_file(custom_app_file or "app.py", subdir=app_dir)
+ path = create_app_file(custom_app_file or "app.py", directory=app_dir)
result = runner.invoke(cli_command, args)
diff --git a/tests/unit/test_cli/test_env_resolution.py b/tests/unit/test_cli/test_env_resolution.py
--- a/tests/unit/test_cli/test_env_resolution.py
+++ b/tests/unit/test_cli/test_env_resolution.py
@@ -114,3 +114,32 @@ def test_env_from_env_autodiscover_from_files_ignore_paths(
with pytest.raises(ClickException):
LitestarEnv.from_env(None)
+
+
[email protected]("use_file_in_app_path", [True, False])
+def test_env_using_app_dir(
+ app_file_content: str, app_file_app_name: str, create_app_file: CreateAppFileFixture, use_file_in_app_path: bool
+) -> None:
+ app_file = "main.py"
+ app_file_without_extension = app_file.split(".")[0]
+ tmp_file_path = create_app_file(
+ file=app_file,
+ directory="src",
+ content=app_file_content,
+ subdir=f"litestar_test_{app_file_app_name}",
+ init_content=f"from .{app_file_without_extension} import {app_file_app_name}",
+ )
+ app_path_components = [f"litestar_test_{app_file_app_name}"]
+ if use_file_in_app_path:
+ app_path_components.append(app_file_without_extension)
+
+ app_path = f"{'.'.join(app_path_components)}:{app_file_app_name}"
+ env = LitestarEnv.from_env(app_path, app_dir=Path().cwd() / "src")
+
+ dotted_path = _path_to_dotted_path(tmp_file_path.relative_to(Path.cwd()))
+
+ assert isinstance(env.app, Litestar)
+ dotted_path = dotted_path.replace("src.", "")
+ if not use_file_in_app_path:
+ dotted_path = dotted_path.replace(".main", "")
+ assert env.app_path == f"{dotted_path}:{app_file_app_name}"
| Bug: `--app-dir` option does not work/fails during autodiscovery.
### Description
Hi! I'm trying to use the Litestar CLI with the following invocation:
`litestar --app-dir src --app litestar_test:app`
with the following project structure:
```
.
├── pyproject.toml
└── src
└── litestar_test
└── __init__.py
```
where `__init__.py` contains:
```python
from litestar import Litestar
app = Litestar()
```
However I'm getting the following error:
```
Using Litestar app from env: 'litestar_test:app'
Traceback (most recent call last):
File "/home/sykloid/src/litestar_test/.venv/bin/litestar", line 8, in <module>
sys.exit(run_cli())
^^^^^^^^^
File "/home/sykloid/src/litestar_test/.venv/lib/python3.11/site-packages/litestar/__main__.py", line 6, in run_cli
litestar_group()
File "/home/sykloid/src/litestar_test/.venv/lib/python3.11/site-packages/click/core.py", line 1157, in __call__
return self.main(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/sykloid/src/litestar_test/.venv/lib/python3.11/site-packages/rich_click/rich_group.py", line 21, in main
rv = super().main(*args, standalone_mode=False, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/sykloid/src/litestar_test/.venv/lib/python3.11/site-packages/click/core.py", line 1077, in main
with self.make_context(prog_name, args, **extra) as ctx:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/sykloid/src/litestar_test/.venv/lib/python3.11/site-packages/litestar/cli/_utils.py", line 237, in make_context
self._prepare(ctx)
File "/home/sykloid/src/litestar_test/.venv/lib/python3.11/site-packages/litestar/cli/_utils.py", line 218, in _prepare env = ctx\.obj = LitestarEnv.from_env(ctx.params.get("app_path"), ctx.params.get("app_dir"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/sykloid/src/litestar_test/.venv/lib/python3.11/site-packages/litestar/cli/_utils.py", line 114, in from_env loaded_ap\p = _load_app_from_path(app_path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/sykloid/src/litestar_test/.venv/lib/python3.11/site-packages/litestar/cli/_utils.py", line 290, in _load_app_from_path
module = importlib.import_module(module_path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/sykloid/.rye/py/[email protected]/install/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'litestar_test'
```
My guess is that this is because even though `sys.path.append(app_dir)` is happening in `litestar.cli.main.litestar_group`, the call to `litestar.cli._utils.LitestarEnv.from_env` is happening before that, and `app_dir` is not added to `sys.path` in that case.
I was able to verify that the following changes worked:
1. Manually adding `src` to `PYTHONPATH` (obviously)
2. Modifying `litestar.cli._utils.LitestarEnv.from_env` to take an extra parameter `app_dir`, and calling it as `env = ctx.obj = LitestarEnv.from_env(ctx.params.get("app_path"), ctx.params.get("app_dir"))` in `LitestarExtensionGroup.prepare`
### URL to code causing the issue
_No response_
### MCVE
_No response_
### Steps to reproduce
```bash
`litestar --app-dir src --app litestar_test:app info`
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.0.1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2266">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2266/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2266/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
|
I agree. Do you want to submit a PR? | 2023-09-03T19:57:26 |
litestar-org/litestar | 2,280 | litestar-org__litestar-2280 | [
"2278",
"1234"
] | 6c61f7a67f8d9ae8d8bbaa015e421de68bad018d | diff --git a/litestar/_multipart.py b/litestar/_multipart.py
--- a/litestar/_multipart.py
+++ b/litestar/_multipart.py
@@ -31,8 +31,7 @@
from urllib.parse import unquote
from litestar.datastructures.upload_file import UploadFile
-from litestar.exceptions import SerializationException, ValidationException
-from litestar.serialization import decode_json
+from litestar.exceptions import ValidationException
__all__ = ("parse_body", "parse_content_header", "parse_multipart_form")
@@ -156,10 +155,7 @@ def parse_multipart_form(
)
fields[field_name].append(form_file)
elif post_data:
- try:
- fields[field_name].append(decode_json(post_data, type_decoders=type_decoders))
- except SerializationException:
- fields[field_name].append(post_data.decode(content_charset))
+ fields[field_name].append(post_data.decode(content_charset))
else:
fields[field_name].append(None)
| diff --git a/tests/unit/test_kwargs/test_multipart_data.py b/tests/unit/test_kwargs/test_multipart_data.py
--- a/tests/unit/test_kwargs/test_multipart_data.py
+++ b/tests/unit/test_kwargs/test_multipart_data.py
@@ -5,18 +5,20 @@
from pathlib import Path
from typing import Any, DefaultDict, Dict, List, Optional
+import msgspec
import pytest
-from pydantic import BaseConfig, BaseModel
+from attr import define, field
+from attr.validators import ge, instance_of, lt
+from pydantic import BaseConfig, BaseModel, ConfigDict, Field
from typing_extensions import Annotated
from litestar import Request, post
-from litestar.contrib.pydantic import _model_dump, _model_dump_json
+from litestar.contrib.pydantic import _model_dump
from litestar.datastructures.upload_file import UploadFile
from litestar.enums import RequestEncodingType
from litestar.params import Body
from litestar.status_codes import HTTP_201_CREATED, HTTP_400_BAD_REQUEST
from litestar.testing import create_test_client
-from tests import PydanticPerson, PydanticPersonFactory
from . import Form
@@ -100,26 +102,24 @@ def test_method(data: Annotated[t_type, Body(media_type=RequestEncodingType.MULT
def test_request_body_multi_part_mixed_field_content_types() -> None:
- person = PydanticPersonFactory.build()
-
@dataclass
class MultiPartFormWithMixedFields:
image: UploadFile
tags: List[int]
- profile: PydanticPerson
@post(path="/form")
async def test_method(data: MultiPartFormWithMixedFields = Body(media_type=RequestEncodingType.MULTI_PART)) -> None:
file_data = await data.image.read()
assert file_data == b"data"
assert data.tags == [1, 2, 3]
- assert data.profile == person
with create_test_client(test_method) as client:
response = client.post(
"/form",
files={"image": ("image.png", b"data")},
- data={"tags": ["1", "2", "3"], "profile": _model_dump_json(person)},
+ data={
+ "tags": ["1", "2", "3"],
+ },
)
assert response.status_code == HTTP_201_CREATED
@@ -449,7 +449,7 @@ async def hello_world(
class ProductForm:
name: str
int_field: int
- options: List[int]
+ options: str
optional_without_default: Optional[float]
optional_with_default: Optional[int] = None
@@ -490,41 +490,61 @@ def handler(
assert response.status_code == HTTP_201_CREATED
-def test_multipart_handling_of_none_json_lists_with_multiple_elements() -> None:
- @post("/")
- def handler(
- data: Annotated[ProductForm, Body(media_type=RequestEncodingType.MULTI_PART)],
- ) -> None:
- assert data
+MAX_INT_POSTGRES = 10
- with create_test_client(route_handlers=[handler]) as client:
- response = client.post(
- "/",
- content=(
- b"--1f35df74046888ceaa62d8a534a076dd\r\n"
- b'Content-Disposition: form-data; name="name"\r\n'
- b"Content-Type: application/octet-stream\r\n\r\n"
- b"moishe zuchmir\r\n"
- b"--1f35df74046888ceaa62d8a534a076dd\r\n"
- b'Content-Disposition: form-data; name="int_field"\r\n'
- b"Content-Type: application/octet-stream\r\n\r\n"
- b"1\r\n"
- b"--1f35df74046888ceaa62d8a534a076dd\r\n"
- b'Content-Disposition: form-data; name="options"\r\n'
- b"Content-Type: application/octet-stream\r\n\r\n"
- b"1\r\n"
- b"--1f35df74046888ceaa62d8a534a076dd\r\n"
- b'Content-Disposition: form-data; name="options"\r\n'
- b"Content-Type: application/octet-stream\r\n\r\n"
- b"2\r\n"
- b"--1f35df74046888ceaa62d8a534a076dd\r\n"
- b'Content-Disposition: form-data; name="optional_without_default"\r\n'
- b"Content-Type: application/octet-stream\r\n\r\n\r\n"
- b"--1f35df74046888ceaa62d8a534a076dd\r\n"
- b'Content-Disposition: form-data; name="optional_with_default"\r\n'
- b"Content-Type: application/octet-stream\r\n\r\n\r\n"
- b"--1f35df74046888ceaa62d8a534a076dd--\r\n"
- ),
- headers={"Content-Type": "multipart/form-data; boundary=1f35df74046888ceaa62d8a534a076dd"},
- )
+
+@define
+class AddProductFormAttrs:
+ name: str
+ amount: int = field(validator=[instance_of(int), ge(1), lt(MAX_INT_POSTGRES)])
+
+
+class AddProductFormPydantic(BaseModel):
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+ name: str
+ amount: int = Field(ge=1, lt=MAX_INT_POSTGRES)
+
+
+class AddProductFormMsgspec(msgspec.Struct):
+ name: str
+ amount: Annotated[int, msgspec.Meta(lt=MAX_INT_POSTGRES, ge=1)]
+
+
[email protected]("form_object", [AddProductFormMsgspec, AddProductFormPydantic, AddProductFormAttrs])
[email protected]("form_type", [RequestEncodingType.URL_ENCODED, RequestEncodingType.MULTI_PART])
+def test_multipart_and_url_encoded_behave_the_same(form_object, form_type) -> None: # type: ignore[no-untyped-def]
+ @post(path="/form")
+ async def form_(request: Request, data: Annotated[form_object, Body(media_type=form_type)]) -> int:
+ assert isinstance(data.name, str)
+ return data.amount # type: ignore[no-any-return]
+
+ with create_test_client(
+ route_handlers=[
+ form_,
+ ]
+ ) as client:
+ if form_type == RequestEncodingType.URL_ENCODED:
+ response = client.post(
+ "/form",
+ data={
+ "name": 1,
+ "amount": 1,
+ },
+ )
+ else:
+ response = client.post(
+ "/form",
+ content=(
+ b"--1f35df74046888ceaa62d8a534a076dd\r\n"
+ b'Content-Disposition: form-data; name="name"\r\n'
+ b"Content-Type: application/octet-stream\r\n\r\n"
+ b"1\r\n"
+ b"--1f35df74046888ceaa62d8a534a076dd\r\n"
+ b'Content-Disposition: form-data; name="amount"\r\n'
+ b"Content-Type: application/octet-stream\r\n\r\n"
+ b"1\r\n"
+ b"--1f35df74046888ceaa62d8a534a076dd--\r\n"
+ ),
+ headers={"Content-Type": "multipart/form-data; boundary=1f35df74046888ceaa62d8a534a076dd"},
+ )
assert response.status_code == HTTP_201_CREATED
| Bug: forms validation discrepency between underlying object and form type
### Description
Given this little app that basically enables in a browser to post a form to 6 different routes: atrts/msgspec/pydantic times url-encoded/multi-part version, I have isues to understand why the multi-part pydantic vs attrs/msgspec different behaviour.
I would expect a 201 on all and get a 400 on multi-part msgspec and attrs (see logs), is that intended ?
Input I pass is purposedely 1 and 1 for name and amount and the same for all POST logs below.
### URL to code causing the issue
_No response_
### MCVE
```python
from typing import Annotated
import msgspec
from attr import define, field
from attr.validators import ge, instance_of, lt
from jinja2 import Environment, DictLoader
from pydantic import BaseModel, ConfigDict, Field
from litestar import Litestar, Request, post, get
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.enums import RequestEncodingType
from litestar.params import Body
from litestar.response import Template
from litestar.template import TemplateConfig
MAX_INT_POSTGRES = 10
@define
class AddProductFormAttrs:
name: str
amount: int = field(validator=[instance_of(int), ge(1), lt(MAX_INT_POSTGRES)])
class AddProductFormPydantic(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
name: str
amount: int = Field(ge=1, lt=MAX_INT_POSTGRES)
class AddProductFormMsgspec(msgspec.Struct):
name: str
amount: Annotated[int, msgspec.Meta(lt=MAX_INT_POSTGRES, ge=1)]
@get(path="/")
async def form_index() -> Template:
return Template(template_name="form.html", context={"templates": ["attrs", "pydantic", "msgspec"]})
@post(path="/form/attrs")
async def form_attrs(
request: Request, data: Annotated[AddProductFormAttrs, Body(media_type=RequestEncodingType.URL_ENCODED)]
) -> int:
print(type(data.name))
return data.amount
@post(path="/form/pydantic")
async def form_pydantic(
request: Request, data: Annotated[AddProductFormPydantic, Body(media_type=RequestEncodingType.URL_ENCODED)]
) -> int:
print(type(data.name))
return data.amount
@post(path="/form/msgspec")
async def form_msgspec(
request: Request, data: Annotated[AddProductFormMsgspec, Body(media_type=RequestEncodingType.URL_ENCODED)]
) -> int:
print(type(data.name))
return data.amount
@post(path="/form/multipart/attrs")
async def form_multipart_attrs(
request: Request, data: Annotated[AddProductFormAttrs, Body(media_type=RequestEncodingType.MULTI_PART)]
) -> int:
print(type(data.name))
return data.amount
@post(path="/form/multipart/pydantic")
async def form_multipart_pydantic(
request: Request, data: Annotated[AddProductFormPydantic, Body(media_type=RequestEncodingType.MULTI_PART)]
) -> int:
print(type(data.name))
return data.amount
@post(path="/form/multipart/msgspec")
async def form_multipart_msgspec(
request: Request, data: Annotated[AddProductFormMsgspec, Body(media_type=RequestEncodingType.MULTI_PART)]
) -> int:
print(type(data.name))
return data.amount
form_html = """
<html>
<body>
{% for t in templates %}
<div>{{ t }}
<form action="/form/{{ t }}" method="post">
<input type="text" name="name"/>
<input type="number" name="amount"/>
<button type="submit">Submit</button>
</form>
</div>
<div>{{ t }} multipart
<form action="/form/multipart//{{ t }}" method="post" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="number" name="amount"/>
<button type="submit">Submit</button>
</form>
</div>
{% endfor %}
</body>
</html>
"""
environment = Environment(loader=DictLoader({"form.html": form_html}))
app = Litestar(route_handlers=[form_index, form_attrs, form_pydantic, form_msgspec, form_multipart_attrs, form_multipart_pydantic, form_multipart_msgspec],
template_config=TemplateConfig(JinjaTemplateEngine.from_environment(jinja_environment=environment)),
debug=True)
```
```
```
### Steps to reproduce
_No response_
### Screenshots
```bash
""
```
### Logs
```bash
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [29797]
INFO: Started server process [29878]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:48782 - "GET / HTTP/1.1" 200 OK
<class 'str'>
INFO: 127.0.0.1:48782 - "POST /form/multipart/pydantic HTTP/1.1" 201 Created
INFO: 127.0.0.1:55766 - "GET / HTTP/1.1" 200 OK
<class 'str'>
INFO: 127.0.0.1:59238 - "POST /form/attrs HTTP/1.1" 201 Created
INFO: 127.0.0.1:56858 - "POST /form/multipart/attrs HTTP/1.1" 400 Bad Request
ERROR - 2023-09-04 14:24:31,1613157331 - litestar - middleware - exception raised on http connection to route /form/multipart/attrs
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `str`, got `int` - at `$.data.name`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 203, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://localhost:8000/form/multipart/attrs
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `str`, got `int` - at `$.data.name`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 203, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://localhost:8000/form/multipart/attrs
<class 'str'>
INFO: 127.0.0.1:56870 - "POST /form/pydantic HTTP/1.1" 201 Created
<class 'str'>
INFO: 127.0.0.1:52932 - "POST /form/multipart/pydantic HTTP/1.1" 201 Created
<class 'str'>
INFO: 127.0.0.1:56944 - "POST /form/msgspec HTTP/1.1" 201 Created
INFO: 127.0.0.1:56944 - "POST /form/multipart/msgspec HTTP/1.1" 400 Bad Request
ERROR - 2023-09-04 14:24:57,1613183344 - litestar - middleware - exception raised on http connection to route /form/multipart/msgspec
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `str`, got `int` - at `$.data.name`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 203, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://localhost:8000/form/multipart/msgspec
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `str`, got `int` - at `$.data.name`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 203, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://localhost:8000/form/multipart/msgspec
WARNING: StatReload detected changes in 'te.py'. Reloading...
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [29878]
INFO: Started server process [30406]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:50626 - "GET / HTTP/1.1" 200 OK
<class 'str'>
INFO: 127.0.0.1:48508 - "POST /form/attrs HTTP/1.1" 201 Created
<class 'str'>
INFO: 127.0.0.1:48508 - "POST /form/pydantic HTTP/1.1" 201 Created
<class 'str'>
INFO: 127.0.0.1:48508 - "POST /form/msgspec HTTP/1.1" 201 Created
INFO: 127.0.0.1:35918 - "POST /form/multipart/attrs HTTP/1.1" 400 Bad Request
ERROR - 2023-09-04 14:26:37,1613283298 - litestar - middleware - exception raised on http connection to route /form/multipart/attrs
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `str`, got `int` - at `$.data.name`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 203, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://localhost:8000/form/multipart/attrs
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `str`, got `int` - at `$.data.name`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 203, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://localhost:8000/form/multipart/attrs
<class 'str'>
INFO: 127.0.0.1:55018 - "POST /form/multipart/pydantic HTTP/1.1" 201 Created
INFO: 127.0.0.1:51360 - "POST /form/multipart/msgspec HTTP/1.1" 400 Bad Request
ERROR - 2023-09-04 14:26:58,1613303675 - litestar - middleware - exception raised on http connection to route /form/multipart/msgspec
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `str`, got `int` - at `$.data.name`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 203, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://localhost:8000/form/multipart/msgspec
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `str`, got `int` - at `$.data.name`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lotso/PycharmProjects/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/lotso/PycharmProjects/litestar/litestar/_signature/model.py", line 203, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://localhost:8000/form/multipart/msgspec
WARNING: StatReload detected changes in 'te.py'. Reloading...
```
### Litestar Version
```
❯ litestar version
2.0.0beta4
```
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2278">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2278/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2278/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| whats the input you are sending?
> whats the input you are sending?
the short version of the log above is that I'm entering 1 for both the input `name` and input `amount` in the form.
what is strange is that for url-encoded forms I get a 201 on all 3 endpoints, the data.name is a string as expected.
but as soon as you have multi-part forms, for the same inputs, the pydantic is the only one returning a 201, others return a 400 complaining data.name is not a string
if I take as an example the multipart vs url-encoded using the msgspec Struct only, by the time we reach this line:
https://github.com/litestar-org/litestar/blob/c36dba249337062266fe2175a256ed7de099fa0e/litestar/_signature/model.py#L190
what we have when entering both times 1 and 1 in the browser.
1. in the url-encoded case is
`{'request': <litestar.connection.request.Request object at 0x7f955cf165c0>, 'data': {'amount': '1', 'name': '1'}}
`
2. vs for the multi-part case
`{'request': <litestar.connection.request.Request object at 0x7f955cf16fc0>, 'data': {'name': 1, 'amount': 1}}`
Well, the difference between url-encoded and multipart is that for url encoded we parse the raw request to a dict of string/string key value pairs and then let msgspec, attrs, pydantic etc. to handle validation and parsing. For multipart we use regex, and I think it's probable we do some conversion there.
We might need to ensure everything remains a string as well.
from briefly looking at it, I think this might be due to this line in https://github.com/litestar-org/litestar/blob/c36dba249337062266fe2175a256ed7de099fa0e/litestar/_multipart.py#L160
if you replace it with `fields[field_name].append(post_data.decode())` then a 201 occurs.
I think the decoding using msgspec is too early,
will try a PR with this and see how it afffects the tests :)
> from briefly looking at it, I think this might be due to this line in https://github.com/litestar-org/litestar/blob/c36dba249337062266fe2175a256ed7de099fa0e/litestar/_multipart.py#L160
>
> if you replace it with `fields[field_name].append(post_data.decode())` then a 201 occurs.
>
> I think the decoding using msgspec is too early,
>
> will try a PR with this and see how it afffects the tests :)
Great 👍
I agree. Do you want to submit a PR? | 2023-09-05T10:13:52 |
litestar-org/litestar | 2,316 | litestar-org__litestar-2316 | [
"4321",
"1234"
] | 7ed396e3da988e995e2281a2a06204f90a588dbc | diff --git a/litestar/contrib/sqlalchemy/base.py b/litestar/contrib/sqlalchemy/base.py
--- a/litestar/contrib/sqlalchemy/base.py
+++ b/litestar/contrib/sqlalchemy/base.py
@@ -12,6 +12,7 @@
UUIDBase,
UUIDPrimaryKey,
create_registry,
+ orm_registry,
touch_updated_timestamp,
)
@@ -27,4 +28,5 @@
"UUIDAuditBase",
"UUIDBase",
"UUIDPrimaryKey",
+ "orm_registry",
)
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-09-18T19:44:51 |
|
litestar-org/litestar | 2,325 | litestar-org__litestar-2325 | [
"2205",
"1234"
] | 195bcbcfb51b8630079baee9c634288eab85cd03 | diff --git a/litestar/middleware/authentication.py b/litestar/middleware/authentication.py
--- a/litestar/middleware/authentication.py
+++ b/litestar/middleware/authentication.py
@@ -5,7 +5,7 @@
from typing import TYPE_CHECKING, Any, Sequence
from litestar.connection import ASGIConnection
-from litestar.enums import ScopeType
+from litestar.enums import HttpMethod, ScopeType
from litestar.middleware._utils import (
build_exclude_path_pattern,
should_bypass_middleware,
@@ -62,7 +62,7 @@ def __init__(
"""
self.app = app
self.exclude = build_exclude_path_pattern(exclude=exclude)
- self.exclude_http_methods = exclude_http_methods
+ self.exclude_http_methods = (HttpMethod.OPTIONS,) if exclude_http_methods is None else exclude_http_methods
self.exclude_opt_key = exclude_from_auth_key
self.scopes = scopes or {ScopeType.HTTP, ScopeType.WEBSOCKET}
diff --git a/litestar/types/asgi_types.py b/litestar/types/asgi_types.py
--- a/litestar/types/asgi_types.py
+++ b/litestar/types/asgi_types.py
@@ -44,6 +44,8 @@
Union,
)
+from litestar.enums import HttpMethod
+
__all__ = (
"ASGIApp",
"ASGIVersion",
@@ -101,7 +103,7 @@
from .internal_types import LitestarType, RouteHandlerType
from .serialization import DataContainerType
-Method: TypeAlias = Literal["GET", "POST", "DELETE", "PATCH", "PUT", "HEAD", "TRACE", "OPTIONS"]
+Method: TypeAlias = Union[Literal["GET", "POST", "DELETE", "PATCH", "PUT", "HEAD", "TRACE", "OPTIONS"], HttpMethod]
ScopeSession: TypeAlias = "EmptyType | Dict[str, Any] | DataContainerType | None"
| diff --git a/tests/unit/test_middleware/test_base_authentication_middleware.py b/tests/unit/test_middleware/test_base_authentication_middleware.py
--- a/tests/unit/test_middleware/test_base_authentication_middleware.py
+++ b/tests/unit/test_middleware/test_base_authentication_middleware.py
@@ -5,6 +5,7 @@
from litestar import Litestar, get, websocket
from litestar.connection import Request, WebSocket
+from litestar.enums import HttpMethod
from litestar.exceptions import PermissionDeniedException, WebSocketDisconnect
from litestar.middleware.authentication import (
AbstractAuthenticationMiddleware,
@@ -225,3 +226,34 @@ def east_handler() -> None:
response = client.get("/west")
assert response.status_code == HTTP_403_FORBIDDEN
+
+
+def test_authentication_exclude_http_methods() -> None:
+ auth_mw = DefineMiddleware(AuthMiddleware, exclude_http_methods=[HttpMethod.GET])
+
+ @get("/")
+ def exclude_get_handler() -> None:
+ return None
+
+ with create_test_client(route_handlers=[exclude_get_handler], middleware=[auth_mw]) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_200_OK
+
+ response = client.options("/")
+ assert response.status_code == HTTP_403_FORBIDDEN
+
+
+def test_authentication_exclude_http_methods_default() -> None:
+ auth_mw = DefineMiddleware(AuthMiddleware)
+
+ @get("/")
+ def exclude_get_handler() -> None:
+ return None
+
+ with create_test_client(route_handlers=[exclude_get_handler], middleware=[auth_mw]) as client:
+ response = client.get("/")
+ assert response.status_code == HTTP_403_FORBIDDEN
+
+ # OPTIONS should be excluded by default
+ response = client.options("/")
+ assert response.is_success
| Bug: OPTIONS getting 401 Error with custom AuthMiddleware
### Description
After version 2.0.0b4 POST calls fail on OPTIONS preflight with Authorization Error. I'm using a custom JWTAuthMiddleware. Code below.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, get
from litestar.connection import ASGIConnection
from litestar.exceptions import NotAuthorizedException
from litestar.middleware import AbstractAuthenticationMiddleware, AuthenticationResult
from litestar.middleware.base import DefineMiddleware
from litestar.testing.client import TestClient
@get("/healthcheck")
async def healthcheck() -> dict[str, str]:
return {"status": "OK"}
class JWTAuthMiddleware(AbstractAuthenticationMiddleware):
async def authenticate_request(self, connection: ASGIConnection) -> AuthenticationResult:
if auth_header := connection.headers.get("authorization"):
auth_scheme, token = auth_header.split()
return AuthenticationResult(user=None, auth=token)
raise NotAuthorizedException()
app = Litestar(route_handlers=[healthcheck], middleware=[DefineMiddleware(JWTAuthMiddleware)])
if __name__ == "__main__":
client = TestClient(app)
result = client.options("/healthcheck/")
assert result.status_code == 204
```
### Steps to reproduce
```bash
run file with newest version of litestart (2.0.1)
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.0.0rc – 2.0.1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2205">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2205/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2205/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
|
I agree. Do you want to submit a PR? | 2023-09-21T04:50:40 |
litestar-org/litestar | 2,330 | litestar-org__litestar-2330 | [
"4321",
"1234"
] | 0ad355a0f395ed08aa92ef25f0e76b733493d08c | diff --git a/litestar/openapi/spec/enums.py b/litestar/openapi/spec/enums.py
--- a/litestar/openapi/spec/enums.py
+++ b/litestar/openapi/spec/enums.py
@@ -26,6 +26,7 @@ class OpenAPIFormat(str, Enum):
IRI_REFERENCE = "iri-reference" # noqa: PIE796
UUID = "uuid"
REGEX = "regex"
+ BINARY = "binary"
class OpenAPIType(str, Enum):
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-09-21T15:33:10 |
|
litestar-org/litestar | 2,346 | litestar-org__litestar-2346 | [
"4321",
"2318"
] | 4aac36d303389fe399618938b94cd3d61412a919 | diff --git a/litestar/cli/_utils.py b/litestar/cli/_utils.py
--- a/litestar/cli/_utils.py
+++ b/litestar/cli/_utils.py
@@ -20,13 +20,20 @@
from litestar.utils import get_name
RICH_CLICK_INSTALLED = False
-try:
+with contextlib.suppress(ImportError):
import rich_click # noqa: F401
RICH_CLICK_INSTALLED = True
-except ImportError:
- pass
+UVICORN_INSTALLED = False
+with contextlib.suppress(ImportError):
+ import uvicorn # noqa: F401
+ UVICORN_INSTALLED = True
+JSBEAUTIFIER_INSTALLED = False
+with contextlib.suppress(ImportError):
+ import jsbeautifier # noqa: F401
+
+ JSBEAUTIFIER_INSTALLED = True
if TYPE_CHECKING or not RICH_CLICK_INSTALLED: # pragma: no cover
from click import ClickException, Command, Context, Group, pass_context
else:
@@ -37,6 +44,8 @@
__all__ = (
"RICH_CLICK_INSTALLED",
+ "UVICORN_INSTALLED",
+ "JSBEAUTIFIER_INSTALLED",
"LoadedApp",
"LitestarCLIException",
"LitestarEnv",
diff --git a/litestar/cli/commands/core.py b/litestar/cli/commands/core.py
--- a/litestar/cli/commands/core.py
+++ b/litestar/cli/commands/core.py
@@ -7,13 +7,15 @@
import sys
from typing import TYPE_CHECKING, Any
-import uvicorn
from rich.tree import Tree
-from litestar.cli._utils import RICH_CLICK_INSTALLED, LitestarEnv, console, show_app_info
+from litestar.cli._utils import RICH_CLICK_INSTALLED, UVICORN_INSTALLED, LitestarEnv, console, show_app_info
from litestar.routes import HTTPRoute, WebSocketRoute
from litestar.utils.helpers import unwrap_partial
+if UVICORN_INSTALLED:
+ import uvicorn
+
if TYPE_CHECKING or not RICH_CLICK_INSTALLED: # pragma: no cover
import click
from click import Context, command, option
@@ -95,7 +97,7 @@ def run_command(
pdb: bool,
ctx: Context,
) -> None:
- """Run a Litestar app.
+ """Run a Litestar app; requires ``uvicorn``.
The app can be either passed as a module path in the form of <module name>.<submodule>:<app instance or factory>,
set as an environment variable LITESTAR_APP with the same format or automatically discovered from one of these
@@ -110,6 +112,12 @@ def run_command(
if pdb:
os.environ["LITESTAR_PDB"] = "1"
+ if not UVICORN_INSTALLED:
+ console.print(
+ r"uvicorn is not installed. Please install the standard group, litestar\[standard], to use this command."
+ )
+ sys.exit(1)
+
if callable(ctx.obj):
ctx.obj = ctx.obj()
else:
@@ -135,7 +143,10 @@ def run_command(
show_app_info(app)
if workers == 1 and not reload:
- uvicorn.run(
+ # A guard statement at the beginning of this function prevents uvicorn from being unbound
+ # See "reportUnboundVariable in:
+ # https://microsoft.github.io/pyright/#/configuration?id=type-check-diagnostics-settings
+ uvicorn.run( # pyright: ignore
app=env.app_path,
host=host,
port=port,
diff --git a/litestar/cli/commands/schema.py b/litestar/cli/commands/schema.py
--- a/litestar/cli/commands/schema.py
+++ b/litestar/cli/commands/schema.py
@@ -2,14 +2,13 @@
from pathlib import Path
from typing import TYPE_CHECKING
-from jsbeautifier import Beautifier
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 RICH_CLICK_INSTALLED, LitestarCLIException, LitestarGroup
+from litestar.cli._utils import JSBEAUTIFIER_INSTALLED, RICH_CLICK_INSTALLED, LitestarCLIException, LitestarGroup
if TYPE_CHECKING or not RICH_CLICK_INSTALLED: # pragma: no cover
from click import Path as ClickPath
@@ -18,11 +17,13 @@
from rich_click import Path as ClickPath
from rich_click import group, option
+if JSBEAUTIFIER_INSTALLED: # pragma: no cover
+ from jsbeautifier import Beautifier
-__all__ = ("generate_openapi_schema", "generate_typescript_specs", "schema_group")
+ beautifier = Beautifier()
-beautifier = Beautifier()
+__all__ = ("generate_openapi_schema", "generate_typescript_specs", "schema_group")
@group(cls=LitestarGroup, name="schema")
@@ -64,7 +65,10 @@ def generate_typescript_specs(app: Litestar, output: Path, namespace: str) -> No
"""Generate TypeScript specs from the OpenAPI schema."""
try:
specs = convert_openapi_to_typescript(app.openapi_schema, namespace)
- beautified_output = beautifier.beautify(specs.write())
- output.write_text(beautified_output)
+ # beautifier will be defined if JSBEAUTIFIER_INSTALLED is True
+ specs_output = (
+ beautifier.beautify(specs.write()) if JSBEAUTIFIER_INSTALLED else specs.write() # pyright: ignore
+ )
+ output.write_text(specs_output)
except OSError as e: # pragma: no cover
raise LitestarCLIException(f"failed to write schema to path {output}") from e
| diff --git a/tests/unit/test_cli/test_core_commands.py b/tests/unit/test_cli/test_core_commands.py
--- a/tests/unit/test_cli/test_core_commands.py
+++ b/tests/unit/test_cli/test_core_commands.py
@@ -250,6 +250,24 @@ def test_run_command_pdb(
assert os.getenv("LITESTAR_PDB") == "1"
[email protected]("mock_uvicorn_run", "unset_env")
+def test_run_command_without_uvicorn_installed(
+ app_file: Path,
+ runner: CliRunner,
+ monkeypatch: MonkeyPatch,
+ create_app_file: CreateAppFileFixture,
+ mocker: MockerFixture,
+) -> None:
+ mocker.patch("litestar.cli.commands.core.UVICORN_INSTALLED", False)
+ console_print_mock = mocker.patch("litestar.cli.commands.core.console.print")
+ path = create_app_file("_create_app_with_path.py", content=CREATE_APP_FILE_CONTENT)
+ app_path = f"{path.stem}:create_app"
+
+ result = runner.invoke(cli_command, ["--app", app_path, "run"])
+ assert result.exit_code == 1
+ assert any("uvicorn is not installed" in arg for args, kwargs in console_print_mock.call_args_list for arg in args)
+
+
@pytest.mark.parametrize("short", [True, False])
def test_version_command(short: bool, runner: CliRunner) -> None:
result = runner.invoke(cli_command, "version --short" if short else "version")
diff --git a/tests/unit/test_cli/test_schema_commands.py b/tests/unit/test_cli/test_schema_commands.py
--- a/tests/unit/test_cli/test_schema_commands.py
+++ b/tests/unit/test_cli/test_schema_commands.py
@@ -56,3 +56,24 @@ def test_openapi_typescript_command(
result = runner.invoke(cli_command, command)
assert result.exit_code == 0
assert mock_path_write_text.called
+
+
[email protected](
+ "namespace, filename", (("Custom", ""), ("", "custom_specs.ts"), ("Custom", "custom_specs.ts"))
+)
+def test_openapi_typescript_command_without_jsbeautifier(
+ runner: CliRunner, mocker: MockerFixture, monkeypatch: MonkeyPatch, filename: str, namespace: str
+) -> None:
+ monkeypatch.setenv("LITESTAR_APP", "test_apps.openapi_test_app.main:app")
+ mocker.patch("litestar.cli.commands.schema.JSBEAUTIFIER_INSTALLED", False)
+ mock_path_write_text = mocker.patch("pathlib.Path.write_text")
+ command = "schema typescript"
+
+ if namespace:
+ command += f" --namespace {namespace}"
+ if filename:
+ command += f" --output {filename}"
+
+ result = runner.invoke(cli_command, command)
+ assert result.exit_code == 0
+ assert mock_path_write_text.called
| Enhancement: Make `litestar` CLI part of the base package
### Summary
Move the CLI dependencies into the core package
### Basic Example
`pip install litestar` should include the Litestar CLI
`pip install litestar[standard]` should continue to do the same thing (base + uvicorn, etc.)
### Drawbacks and Impact
- Heavier package with click-rich (click + rich) installed
### Unresolved questions
_No response_
###
Flask, Django, etc. do this; It makes sense for us. Relevant Discord forum post:
https://discord.com/channels/919193495116337154/1152738535397404752
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2318">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2318/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2318/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| I can look into this. | 2023-09-23T22:59:03 |
litestar-org/litestar | 2,366 | litestar-org__litestar-2366 | [
"2348",
"4321"
] | 0ecb1602ba9f7db8a4d0eec6536baf537ecd3d37 | diff --git a/litestar/app.py b/litestar/app.py
--- a/litestar/app.py
+++ b/litestar/app.py
@@ -212,7 +212,9 @@ def __init__(
type_encoders: TypeEncodersMap | None = None,
type_decoders: TypeDecodersSequence | None = None,
websocket_class: type[WebSocket] | None = None,
- lifespan: list[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager] | None = None,
+ lifespan: OptionalSequence[
+ Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager
+ ] = None,
pdb_on_exception: bool | None = None,
) -> None:
"""Initialize a ``Litestar`` application.
@@ -330,7 +332,7 @@ def __init__(
exception_handlers=exception_handlers or {},
guards=list(guards or []),
include_in_schema=include_in_schema,
- lifespan=lifespan or [],
+ lifespan=list(lifespan or []),
listeners=list(listeners or []),
logging_config=cast("BaseLoggingConfig | None", logging_config),
middleware=list(middleware or []),
| Bug: typing error passing list of context managers to `lifespan` app parameter
### Description
Passing a list of pre-constructed async context managers to `lifespan` parameter causes:
```
app.py:20: error: Argument "lifespan" to "Litestar" has incompatible type "list[AioCtxMgr]"; expected "list[Callable[[Litestar], AbstractAsyncContextManager[Any]] | AbstractAsyncContextManager[Any]] | None" [arg-type]
app.py:20: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
app.py:20: note: Consider using "Sequence" instead, which is covariant
```
### URL to code causing the issue
_No response_
### MCVE
```python
from __future__ import annotations
from typing import Any
from litestar import Litestar
class AioCtxMgr:
"""A dummy context manager."""
async def __aenter__(self) -> None:
pass
async def __aexit__(self, *args: Any) -> None:
pass
ctx_mgrs = [AioCtxMgr()]
Litestar(route_handlers=[], lifespan=ctx_mgrs)
Litestar(route_handlers=[], lifespan=[AioCtxMgr()]) # OK
```
### Steps to reproduce
```bash
Run mypy on MCVE code.
```
### Screenshots
```bash
""
```
### Logs
_No response_
### Litestar Version
2.0.1final0
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2348">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2348/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2348/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Can this be typed with `OptionalSequence`?
> Can this be typed with `OptionalSequence`?
I don't see why not :+1: | 2023-09-26T05:00:12 |
|
litestar-org/litestar | 2,370 | litestar-org__litestar-2370 | [
"4321",
"1234"
] | 735cc6aa592b1a72c7d26e86c423e980dc66291a | diff --git a/litestar/app.py b/litestar/app.py
--- a/litestar/app.py
+++ b/litestar/app.py
@@ -84,7 +84,6 @@
Message,
Middleware,
OnAppInitHandler,
- OptionalSequence,
ParametersMap,
Receive,
ResponseCookies,
@@ -165,14 +164,14 @@ class Litestar(Router):
def __init__(
self,
- route_handlers: OptionalSequence[ControllerRouterHandler] | None = None,
+ route_handlers: Sequence[ControllerRouterHandler] | None = None,
*,
- after_exception: OptionalSequence[AfterExceptionHookHandler] | None = None,
+ after_exception: Sequence[AfterExceptionHookHandler] | None = None,
after_request: AfterRequestHookHandler | None = None,
after_response: AfterResponseHookHandler | None = None,
allowed_hosts: Sequence[str] | AllowedHostsConfig | None = None,
before_request: BeforeRequestHookHandler | None = None,
- before_send: OptionalSequence[BeforeMessageSendHookHandler] | None = None,
+ before_send: Sequence[BeforeMessageSendHookHandler] | None = None,
cache_control: CacheControlHeader | None = None,
compression_config: CompressionConfig | None = None,
cors_config: CORSConfig | None = None,
@@ -183,38 +182,37 @@ def __init__(
etag: ETag | None = None,
event_emitter_backend: type[BaseEventEmitterBackend] = SimpleEventEmitter,
exception_handlers: ExceptionHandlersMap | None = None,
- guards: OptionalSequence[Guard] | None = None,
+ guards: Sequence[Guard] | None = None,
include_in_schema: bool | EmptyType = Empty,
- listeners: OptionalSequence[EventListener] | None = None,
+ listeners: Sequence[EventListener] | None = None,
logging_config: BaseLoggingConfig | EmptyType | None = Empty,
- middleware: OptionalSequence[Middleware] | None = None,
+ middleware: Sequence[Middleware] | None = None,
multipart_form_part_limit: int = 1000,
- on_app_init: OptionalSequence[OnAppInitHandler] | None = None,
- on_shutdown: OptionalSequence[LifespanHook] | None = None,
- on_startup: OptionalSequence[LifespanHook] | None = None,
+ on_app_init: Sequence[OnAppInitHandler] | None = None,
+ on_shutdown: Sequence[LifespanHook] | None = None,
+ on_startup: Sequence[LifespanHook] | None = None,
openapi_config: OpenAPIConfig | None = DEFAULT_OPENAPI_CONFIG,
opt: Mapping[str, Any] | None = None,
parameters: ParametersMap | None = None,
- plugins: OptionalSequence[PluginProtocol] | None = None,
+ plugins: Sequence[PluginProtocol] | None = None,
request_class: type[Request] | None = None,
response_cache_config: ResponseCacheConfig | None = None,
response_class: ResponseType | None = None,
response_cookies: ResponseCookies | None = None,
- response_headers: OptionalSequence[ResponseHeader] | None = None,
+ response_headers: Sequence[ResponseHeader] | None = None,
return_dto: type[AbstractDTO] | None | EmptyType = Empty,
- security: OptionalSequence[SecurityRequirement] | None = None,
+ security: Sequence[SecurityRequirement] | None = None,
signature_namespace: Mapping[str, Any] | None = None,
state: State | None = None,
- static_files_config: OptionalSequence[StaticFilesConfig] | None = None,
+ static_files_config: Sequence[StaticFilesConfig] | None = None,
stores: StoreRegistry | dict[str, Store] | None = None,
tags: Sequence[str] | None = None,
template_config: TemplateConfig | None = None,
type_encoders: TypeEncodersMap | None = None,
type_decoders: TypeDecodersSequence | None = None,
websocket_class: type[WebSocket] | None = None,
- lifespan: OptionalSequence[
- Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager
- ] = None,
+ lifespan: Sequence[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager]
+ | None = None,
pdb_on_exception: bool | None = None,
) -> None:
"""Initialize a ``Litestar`` application.
diff --git a/litestar/controller.py b/litestar/controller.py
--- a/litestar/controller.py
+++ b/litestar/controller.py
@@ -4,7 +4,7 @@
from copy import deepcopy
from functools import partial
from operator import attrgetter
-from typing import TYPE_CHECKING, Any, Mapping, cast
+from typing import TYPE_CHECKING, Any, Mapping, Sequence, cast
from litestar._layers.utils import narrow_response_cookies, narrow_response_headers
from litestar.exceptions import ImproperlyConfiguredException
@@ -31,7 +31,6 @@
ExceptionHandlersMap,
Guard,
Middleware,
- OptionalSequence,
ParametersMap,
ResponseCookies,
TypeEncodersMap,
@@ -105,11 +104,11 @@ class Controller:
"""
exception_handlers: ExceptionHandlersMap | None
"""A map of handler functions to status codes and/or exception types."""
- guards: OptionalSequence[Guard]
+ guards: Sequence[Guard] | None
"""A sequence of :class:`Guard <.types.Guard>` callables."""
include_in_schema: bool | EmptyType
"""A boolean flag dictating whether the route handler should be documented in the OpenAPI schema"""
- middleware: OptionalSequence[Middleware]
+ middleware: Sequence[Middleware] | None
"""A sequence of :class:`Middleware <.types.Middleware>`."""
opt: Mapping[str, Any] | None
"""A string key mapping of arbitrary values that can be accessed in :class:`Guards <.types.Guard>` or wherever you
@@ -139,9 +138,9 @@ class Controller:
""":class:`AbstractDTO <.dto.base_dto.AbstractDTO>` to use for serializing outbound response
data.
"""
- tags: OptionalSequence[str]
+ tags: Sequence[str] | None
"""A sequence of string tags that will be appended to the schema of all route handlers under the controller."""
- security: OptionalSequence[SecurityRequirement]
+ security: Sequence[SecurityRequirement] | None
"""A sequence of dictionaries that to the schema of all route handlers under the controller."""
signature_namespace: dict[str, Any]
"""A mapping of names to types for use in forward reference resolution during signature modelling."""
| diff --git a/litestar/testing/client/sync_client.py b/litestar/testing/client/sync_client.py
--- a/litestar/testing/client/sync_client.py
+++ b/litestar/testing/client/sync_client.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from contextlib import ExitStack
-from typing import TYPE_CHECKING, Any, Generic, Mapping, TypeVar
+from typing import TYPE_CHECKING, Any, Generic, Mapping, Sequence, TypeVar
from urllib.parse import urljoin
from httpx import USE_CLIENT_DEFAULT, Client, Response
@@ -28,7 +28,6 @@
from litestar.middleware.session.base import BaseBackendConfig
from litestar.testing.websocket_test_session import WebSocketTestSession
- from litestar.types.helper_types import OptionalSequence
T = TypeVar("T", bound=ASGIApp)
@@ -476,7 +475,7 @@ def delete(
def websocket_connect(
self,
url: str,
- subprotocols: OptionalSequence[str] | None = None,
+ subprotocols: Sequence[str] | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
diff --git a/litestar/testing/helpers.py b/litestar/testing/helpers.py
--- a/litestar/testing/helpers.py
+++ b/litestar/testing/helpers.py
@@ -44,7 +44,6 @@
LifespanHook,
Middleware,
OnAppInitHandler,
- OptionalSequence,
ParametersMap,
ResponseCookies,
ResponseType,
@@ -55,7 +54,7 @@
def create_test_client(
route_handlers: ControllerRouterHandler | Sequence[ControllerRouterHandler] | None = None,
*,
- after_exception: OptionalSequence[AfterExceptionHookHandler] | None = None,
+ after_exception: Sequence[AfterExceptionHookHandler] | None = None,
after_request: AfterRequestHookHandler | None = None,
after_response: AfterResponseHookHandler | None = None,
allowed_hosts: Sequence[str] | AllowedHostsConfig | None = None,
@@ -63,7 +62,7 @@ def create_test_client(
backend_options: Mapping[str, Any] | None = None,
base_url: str = "http://testserver.local",
before_request: BeforeRequestHookHandler | None = None,
- before_send: OptionalSequence[BeforeMessageSendHookHandler] | None = None,
+ before_send: Sequence[BeforeMessageSendHookHandler] | None = None,
cache_control: CacheControlHeader | None = None,
compression_config: CompressionConfig | None = None,
cors_config: CORSConfig | None = None,
@@ -74,19 +73,19 @@ def create_test_client(
etag: ETag | None = None,
event_emitter_backend: type[BaseEventEmitterBackend] = SimpleEventEmitter,
exception_handlers: ExceptionHandlersMap | None = None,
- guards: OptionalSequence[Guard] | None = None,
+ guards: Sequence[Guard] | None = None,
include_in_schema: bool | EmptyType = Empty,
- listeners: OptionalSequence[EventListener] | None = None,
+ listeners: Sequence[EventListener] | None = None,
logging_config: BaseLoggingConfig | EmptyType | None = Empty,
- middleware: OptionalSequence[Middleware] | None = None,
+ middleware: Sequence[Middleware] | None = None,
multipart_form_part_limit: int = 1000,
- on_app_init: OptionalSequence[OnAppInitHandler] | None = None,
- on_shutdown: OptionalSequence[LifespanHook] | None = None,
- on_startup: OptionalSequence[LifespanHook] | None = None,
+ on_app_init: Sequence[OnAppInitHandler] | None = None,
+ on_shutdown: Sequence[LifespanHook] | None = None,
+ on_startup: Sequence[LifespanHook] | None = None,
openapi_config: OpenAPIConfig | None = DEFAULT_OPENAPI_CONFIG,
opt: Mapping[str, Any] | None = None,
parameters: ParametersMap | None = None,
- plugins: OptionalSequence[PluginProtocol] | None = None,
+ plugins: Sequence[PluginProtocol] | None = None,
lifespan: list[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager] | None = None,
raise_server_exceptions: bool = True,
pdb_on_exception: bool | None = None,
@@ -94,14 +93,14 @@ def create_test_client(
response_cache_config: ResponseCacheConfig | None = None,
response_class: ResponseType | None = None,
response_cookies: ResponseCookies | None = None,
- response_headers: OptionalSequence[ResponseHeader] | None = None,
+ response_headers: Sequence[ResponseHeader] | None = None,
return_dto: type[AbstractDTO] | None | EmptyType = Empty,
root_path: str = "",
- security: OptionalSequence[SecurityRequirement] | None = None,
+ security: Sequence[SecurityRequirement] | None = None,
session_config: BaseBackendConfig | None = None,
signature_namespace: Mapping[str, Any] | None = None,
state: State | None = None,
- static_files_config: OptionalSequence[StaticFilesConfig] | None = None,
+ static_files_config: Sequence[StaticFilesConfig] | None = None,
stores: StoreRegistry | dict[str, Store] | None = None,
tags: Sequence[str] | None = None,
template_config: TemplateConfig | None = None,
@@ -300,7 +299,7 @@ def test_my_handler() -> None:
def create_async_test_client(
route_handlers: ControllerRouterHandler | Sequence[ControllerRouterHandler] | None = None,
*,
- after_exception: OptionalSequence[AfterExceptionHookHandler] | None = None,
+ after_exception: Sequence[AfterExceptionHookHandler] | None = None,
after_request: AfterRequestHookHandler | None = None,
after_response: AfterResponseHookHandler | None = None,
allowed_hosts: Sequence[str] | AllowedHostsConfig | None = None,
@@ -308,7 +307,7 @@ def create_async_test_client(
backend_options: Mapping[str, Any] | None = None,
base_url: str = "http://testserver.local",
before_request: BeforeRequestHookHandler | None = None,
- before_send: OptionalSequence[BeforeMessageSendHookHandler] | None = None,
+ before_send: Sequence[BeforeMessageSendHookHandler] | None = None,
cache_control: CacheControlHeader | None = None,
compression_config: CompressionConfig | None = None,
cors_config: CORSConfig | None = None,
@@ -319,34 +318,34 @@ def create_async_test_client(
etag: ETag | None = None,
event_emitter_backend: type[BaseEventEmitterBackend] = SimpleEventEmitter,
exception_handlers: ExceptionHandlersMap | None = None,
- guards: OptionalSequence[Guard] | None = None,
+ guards: Sequence[Guard] | None = None,
include_in_schema: bool | EmptyType = Empty,
lifespan: list[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager] | None = None,
- listeners: OptionalSequence[EventListener] | None = None,
+ listeners: Sequence[EventListener] | None = None,
logging_config: BaseLoggingConfig | EmptyType | None = Empty,
- middleware: OptionalSequence[Middleware] | None = None,
+ middleware: Sequence[Middleware] | None = None,
multipart_form_part_limit: int = 1000,
- on_app_init: OptionalSequence[OnAppInitHandler] | None = None,
- on_shutdown: OptionalSequence[LifespanHook] | None = None,
- on_startup: OptionalSequence[LifespanHook] | None = None,
+ on_app_init: Sequence[OnAppInitHandler] | None = None,
+ on_shutdown: Sequence[LifespanHook] | None = None,
+ on_startup: Sequence[LifespanHook] | None = None,
openapi_config: OpenAPIConfig | None = DEFAULT_OPENAPI_CONFIG,
opt: Mapping[str, Any] | None = None,
parameters: ParametersMap | None = None,
pdb_on_exception: bool | None = None,
- plugins: OptionalSequence[PluginProtocol] | None = None,
+ plugins: Sequence[PluginProtocol] | None = None,
raise_server_exceptions: bool = True,
request_class: type[Request] | None = None,
response_cache_config: ResponseCacheConfig | None = None,
response_class: ResponseType | None = None,
response_cookies: ResponseCookies | None = None,
- response_headers: OptionalSequence[ResponseHeader] | None = None,
+ response_headers: Sequence[ResponseHeader] | None = None,
return_dto: type[AbstractDTO] | None | EmptyType = Empty,
root_path: str = "",
- security: OptionalSequence[SecurityRequirement] | None = None,
+ security: Sequence[SecurityRequirement] | None = None,
session_config: BaseBackendConfig | None = None,
signature_namespace: Mapping[str, Any] | None = None,
state: State | None = None,
- static_files_config: OptionalSequence[StaticFilesConfig] | None = None,
+ static_files_config: Sequence[StaticFilesConfig] | None = None,
stores: StoreRegistry | dict[str, Store] | None = None,
tags: Sequence[str] | None = None,
template_config: TemplateConfig | None = None,
diff --git a/tests/unit/test_signature/test_parsing.py b/tests/unit/test_signature/test_parsing.py
--- a/tests/unit/test_signature/test_parsing.py
+++ b/tests/unit/test_signature/test_parsing.py
@@ -11,7 +11,6 @@
from litestar.status_codes import HTTP_200_OK, HTTP_204_NO_CONTENT
from litestar.testing import TestClient, create_test_client
from litestar.types import Empty
-from litestar.types.helper_types import OptionalSequence
from litestar.utils.signature import ParsedSignature
@@ -114,7 +113,7 @@ def fn(a: Iterable[int], b: Optional[Iterable[int]]) -> None:
def test_field_definition_is_non_string_sequence() -> None:
- def fn(a: Sequence[int], b: OptionalSequence[int]) -> None:
+ def fn(a: Sequence[int], b: Optional[Sequence[int]]) -> None:
pass
model = SignatureModel.create(
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-09-27T05:42:22 |
litestar-org/litestar | 2,377 | litestar-org__litestar-2377 | [
"4321",
"2375"
] | ab84566a8a7c2693b517240c2197917da34edbce | diff --git a/litestar/app.py b/litestar/app.py
--- a/litestar/app.py
+++ b/litestar/app.py
@@ -528,9 +528,8 @@ async def lifespan(self) -> AsyncGenerator[None, None]:
It will be entered when the ``lifespan`` message has been received from the
server, and exit after the ``asgi.shutdown`` message. During this period, it is
- responsible for calling the ``before_startup``, ``after_startup``,
- `on_startup``, ``before_shutdown``, ``on_shutdown`` and ``after_shutdown``
- hooks, as well as custom lifespan managers.
+ responsible for calling the ``on_startup``, ``on_shutdown`` hooks, as well as
+ custom lifespan managers.
"""
async with AsyncExitStack() as exit_stack:
for hook in self.on_shutdown[::-1]:
| Docs: stale chart for lifecycle hooks
### Summary

We only have `on_startup` and `on_shutdown` hooks now, so this should probably be removed.
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2375">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2375/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2375/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-09-27T23:49:12 |
||
litestar-org/litestar | 2,378 | litestar-org__litestar-2378 | [
"4321",
"1234"
] | 1dca41fe8521e0545b816ae837a86f89a33da8dc | diff --git a/litestar/types/callable_types.py b/litestar/types/callable_types.py
--- a/litestar/types/callable_types.py
+++ b/litestar/types/callable_types.py
@@ -1,15 +1,6 @@
from __future__ import annotations
-from typing import (
- TYPE_CHECKING,
- Any,
- AsyncGenerator,
- Awaitable,
- Callable,
- Generator,
- List,
- Union,
-)
+from typing import TYPE_CHECKING, Any, AsyncGenerator, Awaitable, Callable, Generator
if TYPE_CHECKING:
from typing_extensions import TypeAlias
@@ -25,43 +16,23 @@
from litestar.types.internal_types import LitestarType, PathParameterDefinition
from litestar.types.protocols import Logger
- AfterExceptionHookHandler: TypeAlias = Callable[[Exception, Scope], SyncOrAsyncUnion[None]]
- AfterRequestHookHandler: TypeAlias = Union[
- Callable[[ASGIApp], SyncOrAsyncUnion[ASGIApp]], Callable[[Response], SyncOrAsyncUnion[Response]]
- ]
- AfterResponseHookHandler: TypeAlias = Callable[[Request], SyncOrAsyncUnion[None]]
- AsyncAnyCallable: TypeAlias = Callable[..., Awaitable[Any]]
- AnyCallable: TypeAlias = Callable[..., Any]
- AnyGenerator: TypeAlias = Union[Generator[Any, Any, Any], AsyncGenerator[Any, Any]]
- BeforeMessageSendHookHandler: TypeAlias = Callable[[Message, Scope], SyncOrAsyncUnion[None]]
- BeforeRequestHookHandler: TypeAlias = Callable[[Request], Union[Any, Awaitable[Any]]]
- CacheKeyBuilder: TypeAlias = Callable[[Request], str]
- ExceptionHandler: TypeAlias = Callable[[Request, Exception], Response]
- ExceptionLoggingHandler: TypeAlias = Callable[[Logger, Scope, List[str]], None]
- GetLogger: TypeAlias = Callable[..., Logger]
- Guard: TypeAlias = Callable[[ASGIConnection, BaseRouteHandler], SyncOrAsyncUnion[None]]
- LifespanHook: TypeAlias = Union[
- Callable[[LitestarType], SyncOrAsyncUnion[Any]],
- Callable[[], SyncOrAsyncUnion[Any]],
- ]
- OnAppInitHandler: TypeAlias = Callable[[AppConfig], AppConfig]
- OperationIDCreator: TypeAlias = Callable[[HTTPRouteHandler, Method, List[Union[str, PathParameterDefinition]]], str]
- Serializer: TypeAlias = Callable[[Any], Any]
-else:
- AfterExceptionHookHandler: TypeAlias = Any
- AfterRequestHookHandler: TypeAlias = Any
- AfterResponseHookHandler: TypeAlias = Any
- AsyncAnyCallable: TypeAlias = Any
- AnyCallable: TypeAlias = Any
- AnyGenerator: TypeAlias = Any
- BeforeMessageSendHookHandler: TypeAlias = Any
- BeforeRequestHookHandler: TypeAlias = Any
- CacheKeyBuilder: TypeAlias = Any
- ExceptionHandler: TypeAlias = Any
- ExceptionLoggingHandler: TypeAlias = Any
- GetLogger: TypeAlias = Any
- Guard: TypeAlias = Any
- LifespanHook: TypeAlias = Any
- OnAppInitHandler: TypeAlias = Any
- OperationIDCreator: TypeAlias = Any
- Serializer: TypeAlias = Any
+
+AfterExceptionHookHandler: TypeAlias = "Callable[[Exception, Scope], SyncOrAsyncUnion[None]]"
+AfterRequestHookHandler: TypeAlias = (
+ "Callable[[ASGIApp], SyncOrAsyncUnion[ASGIApp]] | Callable[[Response], SyncOrAsyncUnion[Response]]"
+)
+AfterResponseHookHandler: TypeAlias = "Callable[[Request], SyncOrAsyncUnion[None]]"
+AsyncAnyCallable: TypeAlias = Callable[..., Awaitable[Any]]
+AnyCallable: TypeAlias = Callable[..., Any]
+AnyGenerator: TypeAlias = "Generator[Any, Any, Any] | AsyncGenerator[Any, Any]"
+BeforeMessageSendHookHandler: TypeAlias = "Callable[[Message, Scope], SyncOrAsyncUnion[None]]"
+BeforeRequestHookHandler: TypeAlias = "Callable[[Request], Any | Awaitable[Any]]"
+CacheKeyBuilder: TypeAlias = "Callable[[Request], str]"
+ExceptionHandler: TypeAlias = "Callable[[Request, Exception], Response]"
+ExceptionLoggingHandler: TypeAlias = "Callable[[Logger, Scope, list[str]], None]"
+GetLogger: TypeAlias = "Callable[..., Logger]"
+Guard: TypeAlias = "Callable[[ASGIConnection, BaseRouteHandler], SyncOrAsyncUnion[None]]"
+LifespanHook: TypeAlias = "Callable[[LitestarType], SyncOrAsyncUnion[Any]] | Callable[[], SyncOrAsyncUnion[Any]]"
+OnAppInitHandler: TypeAlias = "Callable[[AppConfig], AppConfig]"
+OperationIDCreator: TypeAlias = "Callable[[HTTPRouteHandler, Method, list[str | PathParameterDefinition]], str]"
+Serializer: TypeAlias = Callable[[Any], Any]
diff --git a/litestar/types/internal_types.py b/litestar/types/internal_types.py
--- a/litestar/types/internal_types.py
+++ b/litestar/types/internal_types.py
@@ -1,14 +1,6 @@
from __future__ import annotations
-from typing import (
- TYPE_CHECKING,
- Any,
- Callable,
- Dict,
- Literal,
- NamedTuple,
- Union,
-)
+from typing import TYPE_CHECKING, Any, Callable, Literal, NamedTuple
__all__ = (
"ControllerRouterHandler",
@@ -34,19 +26,12 @@
from litestar.router import Router
from litestar.types import Method
- ReservedKwargs: TypeAlias = Literal["request", "socket", "headers", "query", "cookies", "state", "data"]
- LitestarType: TypeAlias = Litestar
- RouteHandlerType: TypeAlias = Union[HTTPRouteHandler, WebsocketRouteHandler, ASGIRouteHandler]
- ResponseType: TypeAlias = type[Response]
- ControllerRouterHandler: TypeAlias = Union[type[Controller], RouteHandlerType, Router, Callable[..., Any]]
- RouteHandlerMapItem: TypeAlias = Dict[Union[Method, Literal["websocket", "asgi"]], RouteHandlerType]
-else:
- ReservedKwargs: TypeAlias = Any
- LitestarType: TypeAlias = Any
- RouteHandlerType: TypeAlias = Any
- ResponseType: TypeAlias = Any
- ControllerRouterHandler: TypeAlias = Any
- RouteHandlerMapItem: TypeAlias = Any
+ReservedKwargs: TypeAlias = Literal["request", "socket", "headers", "query", "cookies", "state", "data"]
+LitestarType: TypeAlias = "Litestar"
+RouteHandlerType: TypeAlias = "HTTPRouteHandler | WebsocketRouteHandler | ASGIRouteHandler"
+ResponseType: TypeAlias = "type[Response]"
+ControllerRouterHandler: TypeAlias = "type[Controller] | RouteHandlerType | Router | Callable[..., Any]"
+RouteHandlerMapItem: TypeAlias = 'dict[Method | Literal["websocket", "asgi"], RouteHandlerType]'
class PathParameterDefinition(NamedTuple):
| StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem.
This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.
https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32
| I agree. Do you want to submit a PR? | 2023-09-28T00:07:07 |
|
litestar-org/litestar | 2,384 | litestar-org__litestar-2384 | [
"2381"
] | 82aeb3dca433d7236bd0820323166158854a62f9 | diff --git a/litestar/middleware/exceptions/_debug_response.py b/litestar/middleware/exceptions/_debug_response.py
--- a/litestar/middleware/exceptions/_debug_response.py
+++ b/litestar/middleware/exceptions/_debug_response.py
@@ -48,8 +48,9 @@ def get_symbol_name(frame: FrameInfo) -> str:
locals_dict = frame.frame.f_locals
# this piece assumes that the code uses standard names "self" and "cls"
# in instance and class methods
- instance_or_cls = locals_dict.get("self") or locals_dict.get("cls")
- classname = f"{get_name(instance_or_cls)}." if instance_or_cls else ""
+ instance_or_cls = inst if (inst := locals_dict.get("self")) is not None else locals_dict.get("cls")
+
+ classname = f"{get_name(instance_or_cls)}." if instance_or_cls is not None else ""
return f"{classname}{frame.function}"
| diff --git a/tests/unit/test_middleware/test_exception_handler_middleware.py b/tests/unit/test_middleware/test_exception_handler_middleware.py
--- a/tests/unit/test_middleware/test_exception_handler_middleware.py
+++ b/tests/unit/test_middleware/test_exception_handler_middleware.py
@@ -1,3 +1,4 @@
+from inspect import getinnerframes
from typing import TYPE_CHECKING, Any, Callable, Optional
import pytest
@@ -10,6 +11,7 @@
from litestar.exceptions import HTTPException, InternalServerException, ValidationException
from litestar.logging.config import LoggingConfig, StructLoggingConfig
from litestar.middleware.exceptions import ExceptionHandlerMiddleware
+from litestar.middleware.exceptions._debug_response import get_symbol_name
from litestar.middleware.exceptions.middleware import get_exception_handler
from litestar.status_codes import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
from litestar.testing import TestClient, create_test_client
@@ -340,3 +342,23 @@ def handler() -> None:
assert caplog.records[0].message.startswith(
"exception raised on http connection to route /test\n\nTraceback (most recent call last):\n"
)
+
+
+def test_get_symbol_name_where_type_doesnt_support_bool() -> None:
+ class Test:
+ def __bool__(self) -> bool:
+ raise TypeError("This type doesn't support bool")
+
+ def method(self) -> None:
+ raise RuntimeError("Oh no!")
+
+ exc = None
+
+ try:
+ Test().method()
+ except Exception as e:
+ exc = e
+
+ if exc is not None and exc.__traceback__ is not None:
+ frame = getinnerframes(exc.__traceback__, 2)[-1]
+ assert get_symbol_name(frame) == "Test.method"
| Bug: converting objects to a Bool in debug response
### Description
The function `litestar.middleware.exceptions._debug_response.get_symbol_name` [on line 51](https://github.com/litestar-org/litestar/blob/main/litestar/middleware/exceptions/_debug_response.py#L51):
```py
instance_or_cls = locals_dict.get("self") or locals_dict.get("cls")
```
The use of `or` operator calls the `__bool__` function of the objects mapped to the `self` or `cls` keys. This causes problems when the object cannot be converted to bool which is unfortunately the case when using sqlalchemy, because it raises a `TypeError` for some of its classes ([see here](https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/elements.py#L749)). The problem being that instead of the original DB error, the TypeError is propagated and the web exception renderer doesn't work for this case.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, get
from litestar.contrib.sqlalchemy.base import BigIntBase
from litestar.contrib.sqlalchemy.plugins import (
AsyncSessionConfig,
SQLAlchemyAsyncConfig,
SQLAlchemyInitPlugin,
)
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, mapped_column
class Name(BigIntBase):
name: Mapped[str] = mapped_column(unique=True)
@get("/")
async def add_row(db_session: AsyncSession) -> dict:
async with db_session.begin():
new_name = Name(name="taken")
db_session.add(new_name)
return {"status": "ok"}
sqlalchemy_config = SQLAlchemyAsyncConfig(
connection_string="sqlite+aiosqlite:///test.sqlite3",
session_config=AsyncSessionConfig(expire_on_commit=False),
)
sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)
async def on_startup() -> None:
"""Initializes the database."""
async with sqlalchemy_config.get_engine().begin() as conn:
await conn.run_sync(BigIntBase.metadata.create_all)
app = Litestar(
route_handlers=[add_row], plugins=[sqlalchemy_plugin], on_startup=[on_startup]
)
# Run "get /" twice - first call creates the entry, second one causes the error.
```
### Steps to reproduce
```bash
1. Run the MCVE app (requires `aiosqlite` to be installed) with `--debug`
2. Navigate to "/" for the first time which creates the db row
3. Navigate to "/" for the second time to cause an IntegrityError
4. A `TypeError` is raised and propagated instead of the original DB error
5. The web debug exception renderer doesn't work
```
### Screenshots
_No response_
### Logs
```bash
[SQL: INSERT INTO name (name) VALUES (?)]
[parameters: ('taken',)]
(Background on this error at: https://sqlalche.me/e/20/gkpj)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 205, in __call__
await self.handle_request_exception(
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 234, in handle_request_exception
response = exception_handler(request, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 270, in default_http_exception_handler
return create_debug_response(request=request, exc=exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 184, in create_debug_response
content: Any = create_html_response_content(exc=exc, request=request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 137, in create_html_response_content
exception_data: list[str] = [create_exception_html(exc, line_limit)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 122, in create_exception_html
result = [create_frame_html(frame=frame, collapsed=idx > 0) for idx, frame in enumerate(reversed(frames))]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 122, in <listcomp>
result = [create_frame_html(frame=frame, collapsed=idx > 0) for idx, frame in enumerate(reversed(frames))]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 104, in create_frame_html
"symbol_name": escape(get_symbol_name(frame)),
^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 51, in get_symbol_name
instance_or_cls = locals_dict.get("self") or locals_dict.get("cls")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 749, in __bool__
raise TypeError("Boolean value of this clause is not defined")
TypeError: Boolean value of this clause is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/_asgi/asgi_router.py", line 84, in __call__
await asgi_app(scope, receive, send)
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 205, in __call__
await self.handle_request_exception(
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 234, in handle_request_exception
response = exception_handler(request, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 270, in default_http_exception_handler
return create_debug_response(request=request, exc=exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 184, in create_debug_response
content: Any = create_html_response_content(exc=exc, request=request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 137, in create_html_response_content
exception_data: list[str] = [create_exception_html(exc, line_limit)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 122, in create_exception_html
result = [create_frame_html(frame=frame, collapsed=idx > 0) for idx, frame in enumerate(reversed(frames))]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 122, in <listcomp>
result = [create_frame_html(frame=frame, collapsed=idx > 0) for idx, frame in enumerate(reversed(frames))]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 104, in create_frame_html
"symbol_name": escape(get_symbol_name(frame)),
^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 51, in get_symbol_name
instance_or_cls = locals_dict.get("self") or locals_dict.get("cls")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 749, in __bool__
raise TypeError("Boolean value of this clause is not defined")
TypeError: Boolean value of this clause is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 426, in run_asgi
result = await app( # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__
return await self.app(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/app.py", line 517, in __call__
await self.asgi_handler(scope, receive, self._wrap_send(send=send, scope=scope)) # type: ignore[arg-type]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 205, in __call__
await self.handle_request_exception(
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 234, in handle_request_exception
response = exception_handler(request, exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 270, in default_http_exception_handler
return create_debug_response(request=request, exc=exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 184, in create_debug_response
content: Any = create_html_response_content(exc=exc, request=request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 137, in create_html_response_content
exception_data: list[str] = [create_exception_html(exc, line_limit)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 122, in create_exception_html
result = [create_frame_html(frame=frame, collapsed=idx > 0) for idx, frame in enumerate(reversed(frames))]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 122, in <listcomp>
result = [create_frame_html(frame=frame, collapsed=idx > 0) for idx, frame in enumerate(reversed(frames))]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 104, in create_frame_html
"symbol_name": escape(get_symbol_name(frame)),
^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/litestar/middleware/exceptions/_debug_response.py", line 51, in get_symbol_name
instance_or_cls = locals_dict.get("self") or locals_dict.get("cls")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/geeshta/prog/litestar/bugs/.venv/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 749, in __bool__
raise TypeError("Boolean value of this clause is not defined")
TypeError: Boolean value of this clause is not defined
INFO: 127.0.0.1:48748 - "GET / HTTP/1.1" 500 Internal Server Error
```
### Litestar Version
2.1.1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2381">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2381/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2381/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-09-28T23:35:19 |
|
litestar-org/litestar | 2,391 | litestar-org__litestar-2391 | [
"2368"
] | 4ef5feef104997bc23fa35b6206784e3ffe89c10 | diff --git a/litestar/handlers/http_handlers/base.py b/litestar/handlers/http_handlers/base.py
--- a/litestar/handlers/http_handlers/base.py
+++ b/litestar/handlers/http_handlers/base.py
@@ -435,11 +435,6 @@ def get_response_handler(self, is_response_type_data: bool = False) -> Callable[
return_type = self.parsed_fn_signature.return_type
return_annotation = return_type.annotation
- if before_request_handler := self.resolve_before_request():
- handler_return_type = before_request_handler.parsed_signature.return_type
- if not handler_return_type.is_subclass_of((Empty, NoneType)):
- return_annotation = handler_return_type.annotation
-
self._response_handler_mapping["response_type_handler"] = response_type_handler = create_response_handler(
after_request=after_request,
background=self.background,
@@ -494,9 +489,6 @@ async def to_response(self, app: Litestar, data: Any, request: Request) -> ASGIA
return await response_handler(app=app, data=data, request=request) # type: ignore
def on_registration(self, app: Litestar) -> None:
- if before_request := self.resolve_before_request():
- before_request.set_parsed_signature(self.resolve_signature_namespace())
-
super().on_registration(app)
self.resolve_after_response()
self.resolve_include_in_schema()
@@ -527,13 +519,6 @@ def _validate_handler_function(self) -> None:
"If the function should return a value, change the route handler status code to an appropriate value.",
)
- if (
- (before_request := self.resolve_before_request())
- and not before_request.parsed_signature.return_type.is_subclass_of(NoneType)
- and not before_request.parsed_signature.return_type.is_optional
- ):
- return_type = before_request.parsed_signature.return_type
-
if not self.media_type:
if return_type.is_subclass_of((str, bytes)) or return_type.annotation is AnyStr:
self.media_type = MediaType.TEXT
| Bug: using Any return type on before_request handler throws an error on schema
### Description
Using `Any` as a return type for a `before_request` handler throws an error when accessing the schema pages/openapi.json endpoints. Looking at the documentation, it should return some value or `None`, and using one or both of those as a return type is successful. The API itself runs just fine with an invalid return type, and this only seems to affect the schema routes.
It seems like maybe this is expected behavior so that you are forced to set a proper return type, but maybe a more extensive error message pointing to the location of the issue could be added? The current error I get is `litestar.exceptions.http_exceptions.ImproperlyConfiguredException: 500: Unable to serialize response content`, which took a while to figure out what caused it.
### URL to code causing the issue
https://github.com/rseeley/litestar-before-request-error-mvce/blob/main/app.py
### MCVE
_No response_
### Steps to reproduce
```bash
1. Follow the steps in the README section titled "Install litestar"
2. Access the schema at http://127.0.0.1:8000/schema or http://127.0.0.1:8000/schema/openapi.json
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.1.1
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2368">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2368/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2368/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Thanks for the great MCVE!
What's happening here is Litestar alters the return type of the handler based on the return type of the hook if it's not `None` or ` | None`. Since the hook returns an `ASGIResponse` if you don't return anything, and we default to encode with JSON, Litestar will then attempt to encode the `ASGIResponse` as JSON.
I'm not entirely sure *why* we alter the return type like this, @peterschutt do you have any insight there? I removed the code in question and it didn't seem to break anything, so I'm not even sure this is actually intentional.
In any case, I don't think we *should* be doing this, since it's extremely unexpected and I can't think of a good reason why this would be the desired behaviour. The return type of the handler should be the source of truth in any case, and it's the user's responsibility to return an appropriate type from any hooks that might be in the pipeline. | 2023-09-30T10:51:40 |
|
litestar-org/litestar | 2,396 | litestar-org__litestar-2396 | [
"4321",
"1862"
] | 999776ae4b1fc2d25efc3e09799d65292ab5dc71 | diff --git a/litestar/logging/config.py b/litestar/logging/config.py
--- a/litestar/logging/config.py
+++ b/litestar/logging/config.py
@@ -40,6 +40,7 @@
"class": "litestar.logging.standard.QueueListenerHandler",
"level": "DEBUG",
"formatter": "standard",
+ "handlers": ["console"],
},
}
@@ -327,7 +328,6 @@ def configure(self) -> GetLogger:
from structlog import configure, get_logger
- # we now configure structlog
configure(
**{
k: v
diff --git a/litestar/logging/standard.py b/litestar/logging/standard.py
--- a/litestar/logging/standard.py
+++ b/litestar/logging/standard.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import atexit
+import sys
from logging import StreamHandler
from logging.handlers import QueueHandler, QueueListener
from queue import Queue
@@ -11,18 +12,23 @@
__all__ = ("QueueListenerHandler",)
-class QueueListenerHandler(QueueHandler):
- """Configure queue listener and handler to support non-blocking logging configuration."""
+if sys.version_info < (3, 12):
- def __init__(self, handlers: list[Any] | None = None) -> None:
- """Initialize `?QueueListenerHandler`.
+ class QueueListenerHandler(QueueHandler):
+ """Configure queue listener and handler to support non-blocking logging configuration."""
- Args:
- handlers: Optional 'ConvertingList'
- """
- super().__init__(Queue(-1))
- handlers = resolve_handlers(handlers) if handlers else [StreamHandler()]
- self.listener = QueueListener(self.queue, *handlers)
- self.listener.start()
+ def __init__(self, handlers: list[Any] | None = None) -> None:
+ """Initialize `?QueueListenerHandler`.
- atexit.register(self.listener.stop)
+ Args:
+ handlers: Optional 'ConvertingList'
+ """
+ super().__init__(Queue(-1))
+ handlers = resolve_handlers(handlers) if handlers else [StreamHandler()]
+ self.listener = QueueListener(self.queue, *handlers)
+ self.listener.start()
+
+ atexit.register(self.listener.stop)
+
+else:
+ QueueListenerHandler = QueueHandler
diff --git a/litestar/middleware/logging.py b/litestar/middleware/logging.py
--- a/litestar/middleware/logging.py
+++ b/litestar/middleware/logging.py
@@ -106,7 +106,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""
if not hasattr(self, "logger"):
self.logger = scope["app"].get_logger(self.config.logger_name)
- self.is_struct_logger = structlog_installed and isinstance(self.logger, BindableLogger)
+ self.is_struct_logger = structlog_installed and repr(self.logger).startswith("<BoundLoggerLazyProxy")
if self.config.response_log_fields:
send = self.create_send_wrapper(scope=scope, send=send)
| diff --git a/tests/unit/test_cli/test_session_commands.py b/tests/unit/test_cli/test_session_commands.py
--- a/tests/unit/test_cli/test_session_commands.py
+++ b/tests/unit/test_cli/test_session_commands.py
@@ -48,7 +48,7 @@ def test_delete_session(
result = runner.invoke(cli_command, ["sessions", "delete", "foo"])
- assert mock_confirm_ask.called_once_with("[red]Delete session 'foo'?")
+ mock_confirm_ask.assert_called_once_with("Delete session 'foo'?")
assert not result.exception
mock_delete.assert_called_once_with("foo")
@@ -78,6 +78,6 @@ def test_clear_sessions(
result = runner.invoke(cli_command, ["sessions", "clear"])
- assert mock_confirm_ask.called_once_with("[red]Delete all sessions?")
+ mock_confirm_ask.assert_called_once_with("[red]Delete all sessions?")
assert not result.exception
mock_delete.assert_called_once()
diff --git a/tests/unit/test_logging/test_logging_config.py b/tests/unit/test_logging/test_logging_config.py
--- a/tests/unit/test_logging/test_logging_config.py
+++ b/tests/unit/test_logging/test_logging_config.py
@@ -1,4 +1,5 @@
import logging
+import sys
from typing import TYPE_CHECKING, Any, Dict
from unittest.mock import Mock, patch
@@ -144,12 +145,18 @@ def test_root_logger(handlers: Any, listener: Any) -> None:
@pytest.mark.parametrize(
"handlers, listener",
[
- [default_handlers, StandardQueueListenerHandler],
+ pytest.param(
+ default_handlers,
+ StandardQueueListenerHandler,
+ marks=pytest.mark.xfail(
+ condition=sys.version_info >= (3, 12), reason="change to QueueHandler/QueueListener config in 3.12"
+ ),
+ ),
[default_picologging_handlers, PicologgingQueueListenerHandler],
],
)
-def test_customizing_handler(handlers: Any, listener: Any) -> None:
- handlers["queue_listener"]["handlers"] = ["cfg://handlers.console"]
+def test_customizing_handler(handlers: Any, listener: Any, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setitem(handlers["queue_listener"], "handlers", ["cfg://handlers.console"])
logging_config = LoggingConfig(handlers=handlers)
get_logger = logging_config.configure()
diff --git a/tests/unit/test_logging/test_structlog_config.py b/tests/unit/test_logging/test_structlog_config.py
--- a/tests/unit/test_logging/test_structlog_config.py
+++ b/tests/unit/test_logging/test_structlog_config.py
@@ -13,8 +13,8 @@
def test_structlog_config_default(capsys: CaptureFixture) -> None:
with create_test_client([], logging_config=StructLoggingConfig()) as client:
assert client.app.logger
- assert isinstance(client.app.logger, BindableLogger)
- client.app.logger.info("message", key="value") # type: ignore [attr-defined]
+ assert isinstance(client.app.logger.bind(), BindableLogger)
+ client.app.logger.info("message", key="value")
log_messages = [decode_json(value=x) for x in capsys.readouterr().out.splitlines()]
assert len(log_messages) == 1
@@ -29,11 +29,11 @@ def test_structlog_config_specify_processors(capsys: CaptureFixture) -> None:
with create_test_client([], logging_config=logging_config) as client:
assert client.app.logger
- assert isinstance(client.app.logger, BindableLogger)
+ assert isinstance(client.app.logger.bind(), BindableLogger)
- client.app.logger.info("message1", key="value1") # type: ignore [attr-defined]
+ client.app.logger.info("message1", key="value1")
# Log twice to make sure issue #882 doesn't appear again
- client.app.logger.info("message2", key="value2") # type: ignore [attr-defined]
+ client.app.logger.info("message2", key="value2")
log_messages = [decode_json(value=x) for x in capsys.readouterr().out.splitlines()]
| Enhancement: Python 3.12
### Summary
3.12.0b4 is underway and the release date for 3.12 quickly approaches.
Release Schedule: https://peps.python.org/pep-0693/
Available Betas/RCs: https://www.python.org/ftp/python/3.12.0/
Tooling is beginning to support this (https://github.com/astral-sh/ruff/commit/8bc7378002d080094d572e83f3a3a69df1023030), I imagine we will have a waiting game for some things.. but it would be nice to get a head start on this once 2.0 is released.
Support 3.12, adding it to our CI matrix version, testing, docs, etc.
## Pre-3.12 Release Pending Upstream Packages
- [x] `greenlet`
- [x] https://github.com/python-greenlet/greenlet/pull/327
- [x] Greenlet 3.0 release
- [x] `grpcio`
- [x] https://github.com/grpc/grpc/issues/33063
- [x] `orjson >= 3.8.10`
- [x] https://github.com/ijl/orjson/releases/tag/3.8.10
## Post-3.12 Release Pending Upstream Packages
- [x] https://github.com/MagicStack/uvloop/issues/567
---
<!-- POLAR PLEDGE BADGE START -->
<a href="https://polar.sh/litestar-org/litestar/issues/1862">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/1862/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/1862/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| added greenlet, grpcio, and orjson deps.
Why orjson?
piccolo | 2023-10-03T06:55:47 |
litestar-org/litestar | 2,433 | litestar-org__litestar-2433 | [
"2434"
] | 4d4af99098348192247d866ac287e9da6c0f6eac | diff --git a/litestar/types/internal_types.py b/litestar/types/internal_types.py
--- a/litestar/types/internal_types.py
+++ b/litestar/types/internal_types.py
@@ -48,7 +48,7 @@ class PathParameterDefinition(NamedTuple):
def __getattr__(name: str) -> Any:
if name == "LitestarType":
warn_deprecation(
- "2.3.0",
+ "2.2.1",
"LitestarType",
"import",
removal_in="3.0.0",
| Bug: `2.2.0` does not have `[full]` group
### Description
The move from `poetry` to `pdm` in 2.2.0 has a regression for the `[full]` group.
### URL to code causing the issue
_No response_
### MCVE
```python
pip install litestar[full]==2.2.0 && pip show pydantic
```
### Steps to reproduce
- `pip install litestar[full]`
- Observe no `[full]` group is available, and `pip show $package` does not show expected pacakges
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.2.0
### Platform
- [ ] Linux
- [ ] Mac
- [ ] Windows
- [X] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
> [!NOTE]
> Check out all issues funded or available for funding here: https://polar.sh/litestar-org
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2434">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2434/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2434/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-10-12T23:23:51 |
||
litestar-org/litestar | 2,444 | litestar-org__litestar-2444 | [
"2399"
] | 8af3768bbe55a81e60e01887567c708ec9851a6f | diff --git a/litestar/middleware/exceptions/middleware.py b/litestar/middleware/exceptions/middleware.py
--- a/litestar/middleware/exceptions/middleware.py
+++ b/litestar/middleware/exceptions/middleware.py
@@ -7,7 +7,6 @@
from traceback import format_exception
from typing import TYPE_CHECKING, Any, Type, cast
-from litestar.connection import Request
from litestar.datastructures import Headers
from litestar.enums import MediaType, ScopeType
from litestar.exceptions import WebSocketException
@@ -23,6 +22,7 @@
if TYPE_CHECKING:
from litestar import Response
from litestar.app import Litestar
+ from litestar.connection import Request
from litestar.logging import BaseLoggingConfig
from litestar.types import (
ASGIApp,
@@ -230,7 +230,7 @@ async def handle_request_exception(
send = cors_middleware.send_wrapper(send=send, origin=origin, has_cookie="cookie" in headers)
exception_handler = get_exception_handler(self.exception_handlers, exc) or self.default_http_exception_handler
- request = Request[Any, Any, Any](scope=scope, receive=receive, send=send)
+ request: Request[Any, Any, Any] = litestar_app.request_class(scope=scope, receive=receive, send=send)
response = exception_handler(request, exc)
await response.to_asgi_response(app=None, request=request)(scope=scope, receive=receive, send=send)
| diff --git a/tests/e2e/test_exception_handlers.py b/tests/e2e/test_exception_handlers.py
--- a/tests/e2e/test_exception_handlers.py
+++ b/tests/e2e/test_exception_handlers.py
@@ -67,3 +67,20 @@ def my_handler(self) -> None:
response = client.get("/base/test/")
assert response.status_code == exc_to_raise.status_code, response.json()
assert caller["name"] == expected_layer
+
+
+def test_exception_handler_with_custom_request_class() -> None:
+ class CustomRequest(Request):
+ ...
+
+ def handler(req: Request, exc: Exception) -> Response:
+ assert isinstance(req, CustomRequest)
+
+ return Response(content={})
+
+ @get()
+ async def index() -> None:
+ _ = 1 / 0
+
+ with create_test_client([index], exception_handlers={Exception: handler}, request_class=CustomRequest) as client:
+ client.get("/")
| Bug: `HTMXRequest` not passed to exception handlers, only gets access to standard `Request` object
### Description
I am trying to handle exceptions caused during HTMX requests. But it looks like the exception handler only receives a standard `request` object, even when the routes are set to receive an `HTMXRequest`.
In the exception handler, the only flag I can find to indicate it's an HTMX request is `request._headers.get("hx-request")`. We lose context on all other HTMX attributes in the request, which makes it difficult to troubleshoot and handle nicely.
Having access to the original HTMX request attributes can improve the flexibility of exception handling for these cases.
### URL to code causing the issue
_No response_
### MCVE
```python
import logging
from typing import Callable
from litestar import Litestar, MediaType, Request, Response, get
from litestar.contrib.htmx.request import HTMXRequest
from litestar.contrib.htmx.response import HTMXTemplate
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.response import Template
from litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
from litestar.template import TemplateConfig
logger = logging.getLogger("litestar")
html = """
<html>
<head>
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
<button hx-get="/htmx">Trigger HTMX</button>
</body>
</html>
"""
def http_500(request: Request | HTMXRequest, exc: Exception) -> Template:
"""Something broke, lets fix it"""
request.logger.exception(f"🚨 500 ERROR: something broke on {request.url}: {exc}")
meta = {
"title": "500 Error... something broke bad",
"description": "Sorry about this, we'll work on it",
}
return Template(
template_name="errors/500.html.j2",
context={
"request": request,
"meta": meta,
},
)
exception_config: dict[int | type[Exception], Callable] = {
HTTP_500_INTERNAL_SERVER_ERROR: http_500,
}
@get("/")
async def serveHomepage(request: Request) -> Response:
return Response(html, media_type=MediaType.HTML)
@get("/htmx")
async def serveHTMXResponse(request: HTMXRequest) -> Template:
break_here = 1 / 0
request.logger.info(break_here)
return HTMXTemplate(template_name="Some HTMX Template")
app = Litestar(
route_handlers=[serveHomepage, serveHTMXResponse],
request_class=HTMXRequest,
debug=True,
exception_handlers=exception_config,
template_config=TemplateConfig(
directory="src/templates", engine=JinjaTemplateEngine
),
)
```
### Steps to reproduce
```bash
1. Load up the MRE in your favorite IDE
2. Add a breakpoint inside the `http_500` function
3. Run the app in debug mode
4. Open the homepage and click the button. It should automatically trigger a DivisionByZero exception
5. Your IDE should break in the `http_500` function.
6. Inspect the `request` object. If it was an `HTMXRequest`, the object type would be `litestar.contrib.htmx.request.HTMXDetails` and you would see attributes for `request.htmx`.
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
Litestar `2.1.1 ` and Python `3.11.5`
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2399">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2399/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2399/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-10-14T19:33:22 |
|
litestar-org/litestar | 2,455 | litestar-org__litestar-2455 | [
"2454"
] | 231934625f3ac3a6f86983a430b7d4aa4f34f9b8 | diff --git a/litestar/response/template.py b/litestar/response/template.py
--- a/litestar/response/template.py
+++ b/litestar/response/template.py
@@ -56,7 +56,6 @@ def __init__(
media_type: A string or member of the :class:`MediaType <.enums.MediaType>` enum. If not set, try to infer
the media type based on the template name. If this fails, fall back to ``text/plain``.
status_code: A value for the response HTTP status code.
- template_engine: The template engine class to use to render the response.
"""
super().__init__(
background=background,
| Docs: `template_engine` documented but not actually used
### Summary
In the `Template` response, there's a `template_engine` parameter that is taken as per the docstrings as seen [here](https://github.com/litestar-org/litestar/blob/2385b32b52a786634bcef6059900165123f31705/litestar/response/template.py#L59) (it's also there in the reference documentation). Was this meant to be removed or should support for giving a custom engine class on instantiation of the response be allowed?
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2454">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2454/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2454/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| It was removed in favor of retrieving it from the application as part of the PR that created the ASGI response variants. That PR was merged somewhat abruptly, so not surprising there are some rough edges around that stuff.
Should be safe to remove the docstring for it. | 2023-10-16T03:48:21 |
|
litestar-org/litestar | 2,475 | litestar-org__litestar-2475 | [
"2471"
] | 38b35adceea5db537123c4eb93891ce03de4e7b9 | diff --git a/litestar/_openapi/schema_generation/schema.py b/litestar/_openapi/schema_generation/schema.py
--- a/litestar/_openapi/schema_generation/schema.py
+++ b/litestar/_openapi/schema_generation/schema.py
@@ -43,12 +43,13 @@
create_string_constrained_field_schema,
)
from litestar._openapi.schema_generation.utils import (
+ _get_normalized_schema_key,
_should_create_enum_schema,
_should_create_literal_schema,
_type_or_first_not_none_inner_type,
get_formatted_examples,
)
-from litestar.datastructures.upload_file import UploadFile
+from litestar.datastructures import UploadFile
from litestar.exceptions import ImproperlyConfiguredException
from litestar.openapi.spec import Reference
from litestar.openapi.spec.enums import OpenAPIFormat, OpenAPIType
@@ -56,7 +57,6 @@
from litestar.pagination import ClassicPagination, CursorPagination, OffsetPagination
from litestar.params import BodyKwarg, ParameterKwarg
from litestar.plugins import OpenAPISchemaPlugin
-from litestar.serialization import encode_json
from litestar.types import Empty
from litestar.typing import FieldDefinition
from litestar.utils.helpers import get_name
@@ -652,15 +652,11 @@ def process_schema_result(self, field: FieldDefinition, schema: Schema) -> Schem
schema.examples = get_formatted_examples(field, create_examples_for_field(field))
if schema.title and schema.type in (OpenAPIType.OBJECT, OpenAPIType.ARRAY):
- if schema.title in self.schemas and hash(self.schemas[schema.title]) != hash(schema):
- raise ImproperlyConfiguredException(
- f"Two different schemas with the title {schema.title} have been defined.\n\n"
- f"first: {encode_json(self.schemas[schema.title].to_schema()).decode()}\n"
- f"second: {encode_json(schema.to_schema()).decode()}\n\n"
- f"To fix this issue, either rename the base classes from which these titles are derived or manually"
- f"set a 'title' kwarg in the route handler."
- )
+ class_name = _get_normalized_schema_key(str(field.annotation))
+
+ if class_name in self.schemas:
+ return Reference(ref=f"#/components/schemas/{class_name}", description=schema.description)
- self.schemas[schema.title] = schema
- return Reference(ref=f"#/components/schemas/{schema.title}")
+ self.schemas[class_name] = schema
+ return Reference(ref=f"#/components/schemas/{class_name}")
return schema
diff --git a/litestar/_openapi/schema_generation/utils.py b/litestar/_openapi/schema_generation/utils.py
--- a/litestar/_openapi/schema_generation/utils.py
+++ b/litestar/_openapi/schema_generation/utils.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
from enum import Enum
from typing import TYPE_CHECKING, Any, Mapping
@@ -15,6 +16,7 @@
"_type_or_first_not_none_inner_type",
"_should_create_enum_schema",
"_should_create_literal_schema",
+ "_get_normalized_schema_key",
)
@@ -82,6 +84,25 @@ def _should_create_literal_schema(field_definition: FieldDefinition) -> bool:
)
+TYPE_NAME_NORMALIZATION_SUB_REGEX = re.compile(r"[^a-zA-Z0-9]+")
+TYPE_NAME_NORMALIZATION_TRIM_REGEX = re.compile(r"^(_+class_+|_+)|_+$")
+
+
+def _get_normalized_schema_key(type_annotation_str: str) -> str:
+ """Normalize a type annotation, replacing all non-alphanumeric with underscores. Existing underscores will be left as-is
+
+ Args:
+ type_annotation_str (str): A string representing a type annotation (i.e. 'typing.Dict[str, typing.Any]' or '<class 'model.Foo'>')
+
+ Returns:
+ str: A normalized version of the input string
+ """
+ # Use a regular expression to replace non-alphanumeric characters with underscores
+ return re.sub(
+ TYPE_NAME_NORMALIZATION_TRIM_REGEX, "", re.sub(TYPE_NAME_NORMALIZATION_SUB_REGEX, "_", type_annotation_str)
+ )
+
+
def get_formatted_examples(field_definition: FieldDefinition, examples: Sequence[Example]) -> Mapping[str, Example]:
"""Format the examples into the OpenAPI schema format."""
| diff --git a/tests/examples/test_openapi.py b/tests/examples/test_openapi.py
--- a/tests/examples/test_openapi.py
+++ b/tests/examples/test_openapi.py
@@ -19,7 +19,11 @@ def test_schema_generation() -> None:
"description": "Request fulfilled, document follows",
"headers": {},
"content": {
- "application/json": {"schema": {"$ref": "#/components/schemas/IdContainer"}}
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/docs_examples_openapi_customize_pydantic_model_name_IdModel"
+ }
+ }
},
}
},
@@ -29,7 +33,7 @@ def test_schema_generation() -> None:
},
"components": {
"schemas": {
- "IdContainer": {
+ "docs_examples_openapi_customize_pydantic_model_name_IdModel": {
"properties": {"id": {"type": "string", "format": "uuid", "description": "Any UUID string"}},
"type": "object",
"required": ["id"],
diff --git a/tests/unit/test_contrib/test_attrs/test_schema_plugin.py b/tests/unit/test_contrib/test_attrs/test_schema_plugin.py
--- a/tests/unit/test_contrib/test_attrs/test_schema_plugin.py
+++ b/tests/unit/test_contrib/test_attrs/test_schema_plugin.py
@@ -5,8 +5,8 @@
from litestar._openapi.schema_generation.schema import (
SchemaCreator,
- _get_type_schema_name,
)
+from litestar._openapi.schema_generation.utils import _get_normalized_schema_key
from litestar.contrib.attrs.attrs_schema_plugin import AttrsSchemaPlugin
from litestar.openapi.spec import OpenAPIType
from litestar.openapi.spec.schema import Schema
@@ -30,7 +30,7 @@ def test_schema_generation_with_generic_classes() -> None:
schemas: Dict[str, Schema] = {}
SchemaCreator(schemas=schemas, plugins=[AttrsSchemaPlugin()]).for_field_definition(field_definition)
- name = _get_type_schema_name(field_definition)
+ name = _get_normalized_schema_key(str(field_definition.annotation))
properties = schemas[name].properties
expected_foo_schema = Schema(type=OpenAPIType.INTEGER)
expected_optional_foo_schema = Schema(one_of=[Schema(type=OpenAPIType.NULL), Schema(type=OpenAPIType.INTEGER)])
diff --git a/tests/unit/test_contrib/test_attrs/test_schema_spec_generation.py b/tests/unit/test_contrib/test_attrs/test_schema_spec_generation.py
--- a/tests/unit/test_contrib/test_attrs/test_schema_spec_generation.py
+++ b/tests/unit/test_contrib/test_attrs/test_schema_spec_generation.py
@@ -24,8 +24,8 @@ def handler(data: Person) -> Person:
with create_test_client(handler) as client:
schema = client.app.openapi_schema
assert schema
-
- assert schema.to_schema()["components"]["schemas"]["Person"] == {
+ key_name = "tests_unit_test_contrib_test_attrs_test_schema_spec_generation_test_spec_generation_locals_Person"
+ assert schema.to_schema()["components"]["schemas"][key_name] == {
"properties": {
"first_name": {"type": "string"},
"last_name": {"type": "string"},
@@ -41,7 +41,10 @@ def handler(data: Person) -> Person:
"pets": {
"oneOf": [
{"type": "null"},
- {"items": {"$ref": "#/components/schemas/DataclassPet"}, "type": "array"},
+ {
+ "items": {"$ref": "#/components/schemas/tests_models_DataclassPet"},
+ "type": "array",
+ },
]
},
},
diff --git a/tests/unit/test_contrib/test_piccolo_orm/test_piccolo_orm_dto.py b/tests/unit/test_contrib/test_piccolo_orm/test_piccolo_orm_dto.py
--- a/tests/unit/test_contrib/test_piccolo_orm/test_piccolo_orm_dto.py
+++ b/tests/unit/test_contrib/test_piccolo_orm/test_piccolo_orm_dto.py
@@ -96,22 +96,22 @@ def test_piccolo_dto_openapi_spec_generation() -> None:
post_operation = concert_path.post
assert (
post_operation.request_body.content["application/json"].schema.ref # type: ignore
- == "#/components/schemas/CreateConcertConcertRequestBody"
+ == "#/components/schemas/litestar_dto_backend_CreateConcertConcertRequestBody"
)
studio_path_get_operation = studio_path.get
assert (
studio_path_get_operation.responses["200"].content["application/json"].schema.ref # type: ignore
- == "#/components/schemas/RetrieveStudioRecordingStudioResponseBody"
+ == "#/components/schemas/litestar_dto_backend_RetrieveStudioRecordingStudioResponseBody"
)
venues_path_get_operation = venues_path.get
assert (
venues_path_get_operation.responses["200"].content["application/json"].schema.items.ref # type: ignore
- == "#/components/schemas/RetrieveVenuesVenueResponseBody"
+ == "#/components/schemas/litestar_dto_backend_RetrieveVenuesVenueResponseBody"
)
- concert_schema = schema.components.schemas["CreateConcertConcertRequestBody"]
+ concert_schema = schema.components.schemas["litestar_dto_backend_CreateConcertConcertRequestBody"]
assert concert_schema
assert concert_schema.to_schema() == {
"properties": {
@@ -124,7 +124,7 @@ def test_piccolo_dto_openapi_spec_generation() -> None:
"type": "object",
}
- record_studio_schema = schema.components.schemas["RetrieveStudioRecordingStudioResponseBody"]
+ record_studio_schema = schema.components.schemas["litestar_dto_backend_RetrieveStudioRecordingStudioResponseBody"]
assert record_studio_schema
assert record_studio_schema.to_schema() == {
"properties": {
@@ -138,7 +138,7 @@ def test_piccolo_dto_openapi_spec_generation() -> None:
"type": "object",
}
- venue_schema = schema.components.schemas["RetrieveVenuesVenueResponseBody"]
+ venue_schema = schema.components.schemas["litestar_dto_backend_RetrieveVenuesVenueResponseBody"]
assert venue_schema
assert venue_schema.to_schema() == {
"properties": {
diff --git a/tests/unit/test_contrib/test_pydantic/test_openapi.py b/tests/unit/test_contrib/test_pydantic/test_openapi.py
--- a/tests/unit/test_contrib/test_pydantic/test_openapi.py
+++ b/tests/unit/test_contrib/test_pydantic/test_openapi.py
@@ -15,6 +15,7 @@
create_string_constrained_field_schema,
)
from litestar._openapi.schema_generation.schema import SchemaCreator
+from litestar._openapi.schema_generation.utils import _get_normalized_schema_key
from litestar.contrib.pydantic import PydanticPlugin, PydanticSchemaPlugin
from litestar.openapi import OpenAPIConfig
from litestar.openapi.spec import Example, Schema
@@ -319,8 +320,9 @@ def handler(data: cls) -> cls:
with create_test_client(handler) as client:
schema = client.app.openapi_schema
assert schema
+ key_name = _get_normalized_schema_key(str(cls))
- assert schema.to_schema()["components"]["schemas"][cls.__name__] == {
+ assert schema.to_schema()["components"]["schemas"][key_name] == {
"properties": {
"first_name": {"type": "string"},
"last_name": {"type": "string"},
@@ -336,7 +338,10 @@ def handler(data: cls) -> cls:
"pets": {
"oneOf": [
{"type": "null"},
- {"items": {"$ref": "#/components/schemas/DataclassPet"}, "type": "array"},
+ {
+ "items": {"$ref": "#/components/schemas/tests_models_DataclassPet"},
+ "type": "array",
+ },
]
},
},
@@ -373,8 +378,9 @@ async def example_route() -> Lookup:
signature_namespace={"Lookup": Lookup},
) as client:
response = client.get("/schema/openapi.json")
+ key_name = "tests_unit_test_contrib_test_pydantic_test_openapi_test_schema_generation_v1_locals_Lookup"
assert response.status_code == HTTP_200_OK
- assert response.json()["components"]["schemas"]["Lookup"]["properties"]["id"] == {
+ assert response.json()["components"]["schemas"][key_name]["properties"]["id"] == {
"description": "A unique identifier",
"examples": {"id-example-1": {"value": "e4eaaaf2-d142-11e1-b3e4-080027620cdd"}},
"maxLength": 16,
@@ -411,7 +417,8 @@ async def example_route() -> Lookup:
) as client:
response = client.get("/schema/openapi.json")
assert response.status_code == HTTP_200_OK
- assert response.json()["components"]["schemas"]["Lookup"]["properties"]["id"] == {
+ key_name = "tests_unit_test_contrib_test_pydantic_test_openapi_test_schema_generation_v2_locals_Lookup"
+ assert response.json()["components"]["schemas"][key_name]["properties"]["id"] == {
"description": "A unique identifier",
"examples": {"id-example-1": {"value": "e4eaaaf2-d142-11e1-b3e4-080027620cdd"}},
"maxLength": 16,
@@ -436,14 +443,18 @@ def handler(data: RequestWithAlias) -> ResponseWithAlias:
assert app.openapi_schema
schemas = app.openapi_schema.to_schema()["components"]["schemas"]
request_key = "second"
- assert schemas["RequestWithAlias"] == {
+ assert schemas[
+ "tests_unit_test_contrib_test_pydantic_test_openapi_test_schema_by_alias_locals_RequestWithAlias"
+ ] == {
"properties": {request_key: {"type": "string"}},
"type": "object",
"required": [request_key],
"title": "RequestWithAlias",
}
response_key = "first"
- assert schemas["ResponseWithAlias"] == {
+ assert schemas[
+ "tests_unit_test_contrib_test_pydantic_test_openapi_test_schema_by_alias_locals_ResponseWithAlias"
+ ] == {
"properties": {response_key: {"type": "string"}},
"type": "object",
"required": [response_key],
@@ -471,18 +482,21 @@ def handler(data: RequestWithAlias) -> ResponseWithAlias:
openapi_config=OpenAPIConfig(title="my title", version="1.0.0"),
plugins=[PydanticPlugin(prefer_alias=True)],
)
-
assert app.openapi_schema
schemas = app.openapi_schema.to_schema()["components"]["schemas"]
request_key = "second"
- assert schemas["RequestWithAlias"] == {
+ assert schemas[
+ "tests_unit_test_contrib_test_pydantic_test_openapi_test_schema_by_alias_plugin_override_locals_RequestWithAlias"
+ ] == {
"properties": {request_key: {"type": "string"}},
"type": "object",
"required": [request_key],
"title": "RequestWithAlias",
}
response_key = "second"
- assert schemas["ResponseWithAlias"] == {
+ assert schemas[
+ "tests_unit_test_contrib_test_pydantic_test_openapi_test_schema_by_alias_plugin_override_locals_ResponseWithAlias"
+ ] == {
"properties": {response_key: {"type": "string"}},
"type": "object",
"required": [response_key],
@@ -506,7 +520,7 @@ class Model(pydantic_v1.BaseModel):
schemas: Dict[str, Schema] = {}
field_definition = FieldDefinition.from_kwarg(name="Model", annotation=Model)
SchemaCreator(schemas=schemas, plugins=[PydanticSchemaPlugin()]).for_field_definition(field_definition)
- schema = schemas["Model"]
+ schema = schemas["tests_unit_test_contrib_test_pydantic_test_openapi_test_create_schema_for_field_v1_locals_Model"]
assert schema.properties
@@ -527,7 +541,7 @@ class Model(pydantic_v2.BaseModel):
schemas: Dict[str, Schema] = {}
field_definition = FieldDefinition.from_kwarg(name="Model", annotation=Model)
SchemaCreator(schemas=schemas, plugins=[PydanticSchemaPlugin()]).for_field_definition(field_definition)
- schema = schemas["Model"]
+ schema = schemas["tests_unit_test_contrib_test_pydantic_test_openapi_test_create_schema_for_field_v2_locals_Model"]
assert schema.properties
@@ -558,7 +572,8 @@ class Foo(BaseModel):
SchemaCreator(schemas=schemas, plugins=[PydanticSchemaPlugin()]).for_field_definition(
FieldDefinition.from_annotation(module.Foo)
)
- schema = schemas["Foo"]
+ key_name = _get_normalized_schema_key(str(module.Foo))
+ schema = schemas[key_name]
assert schema.properties and "foo" in schema.properties
@@ -584,7 +599,7 @@ class Model(BaseModel):
SchemaCreator(schemas=schemas, plugins=[PydanticSchemaPlugin()]).for_field_definition(
FieldDefinition.from_annotation(module.Model)
)
- schema = schemas["Model"]
+ schema = schemas[f"{module.__name__}_Model"]
assert schema.properties
assert "dict_default" in schema.properties
assert "dict_default_in_field" in schema.properties
diff --git a/tests/unit/test_contrib/test_pydantic/test_schema_plugin.py b/tests/unit/test_contrib/test_pydantic/test_schema_plugin.py
--- a/tests/unit/test_contrib/test_pydantic/test_schema_plugin.py
+++ b/tests/unit/test_contrib/test_pydantic/test_schema_plugin.py
@@ -10,8 +10,8 @@
from litestar._openapi.schema_generation.schema import (
SchemaCreator,
- _get_type_schema_name,
)
+from litestar._openapi.schema_generation.utils import _get_normalized_schema_key
from litestar.contrib.pydantic.pydantic_schema_plugin import PydanticSchemaPlugin
from litestar.openapi.spec import OpenAPIType
from litestar.openapi.spec.schema import Schema
@@ -41,7 +41,7 @@ def test_schema_generation_with_generic_classes(model: Type[Union[PydanticV1Gene
schemas: Dict[str, Schema] = {}
SchemaCreator(schemas=schemas, plugins=[PydanticSchemaPlugin()]).for_field_definition(field_definition)
- name = _get_type_schema_name(field_definition)
+ name = _get_normalized_schema_key(str(field_definition.annotation))
properties = schemas[name].properties
expected_foo_schema = Schema(type=OpenAPIType.INTEGER)
expected_optional_foo_schema = Schema(one_of=[Schema(type=OpenAPIType.NULL), Schema(type=OpenAPIType.INTEGER)])
diff --git a/tests/unit/test_openapi/test_integration.py b/tests/unit/test_openapi/test_integration.py
--- a/tests/unit/test_openapi/test_integration.py
+++ b/tests/unit/test_openapi/test_integration.py
@@ -169,7 +169,9 @@ async def example_route() -> Lookup:
) as client:
response = client.get("/schema/openapi.json")
assert response.status_code == HTTP_200_OK
- assert response.json()["components"]["schemas"]["Lookup"]["properties"]["id"] == {
+ assert response.json()["components"]["schemas"][
+ "tests_unit_test_openapi_test_integration_test_msgspec_schema_generation_locals_Lookup"
+ ]["properties"]["id"] == {
"description": "A unique identifier",
"examples": {"id-example-1": {"value": "e4eaaaf2-d142-11e1-b3e4-080027620cdd"}},
"maxLength": 16,
@@ -225,7 +227,6 @@ def handler_foo_int() -> Foo[int]:
),
) as client:
response = client.get("/schema/openapi.json")
-
assert response.status_code == HTTP_200_OK
assert response.json() == {
"info": {"title": "Example API", "version": "1.0.0"},
@@ -240,7 +241,13 @@ def handler_foo_int() -> Foo[int]:
"200": {
"description": "Request fulfilled, document follows",
"headers": {},
- "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Foo[str]"}}},
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/tests_unit_test_openapi_test_integration_Foo_str"
+ }
+ }
+ },
}
},
"deprecated": False,
@@ -254,7 +261,13 @@ def handler_foo_int() -> Foo[int]:
"200": {
"description": "Request fulfilled, document follows",
"headers": {},
- "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Foo[int]"}}},
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/tests_unit_test_openapi_test_integration_Foo_int"
+ }
+ }
+ },
}
},
"deprecated": False,
@@ -263,13 +276,13 @@ def handler_foo_int() -> Foo[int]:
},
"components": {
"schemas": {
- "Foo[str]": {
+ "tests_unit_test_openapi_test_integration_Foo_str": {
"properties": {"foo": {"type": "string"}},
"type": "object",
"required": ["foo"],
"title": "Foo[str]",
},
- "Foo[int]": {
+ "tests_unit_test_openapi_test_integration_Foo_int": {
"properties": {"foo": {"type": "integer"}},
"type": "object",
"required": ["foo"],
diff --git a/tests/unit/test_openapi/test_request_body.py b/tests/unit/test_openapi/test_request_body.py
--- a/tests/unit/test_openapi/test_request_body.py
+++ b/tests/unit/test_openapi/test_request_body.py
@@ -62,9 +62,10 @@ async def handle_file_list_upload(
"items": {"type": "string", "contentMediaType": "application/octet-stream"},
"type": "array",
}
+
assert components == {
"schemas": {
- "FormData": {
+ "tests_unit_test_openapi_test_request_body_FormData": {
"properties": {
"cv": {
"type": "string",
diff --git a/tests/unit/test_openapi/test_responses.py b/tests/unit/test_openapi/test_responses.py
--- a/tests/unit/test_openapi/test_responses.py
+++ b/tests/unit/test_openapi/test_responses.py
@@ -226,7 +226,8 @@ def handler() -> Response[DataclassPerson]:
assert isinstance(reference, Reference)
key = reference.ref.split("/")[-1]
assert isinstance(schemas[key], Schema)
- assert key == DataclassPerson.__name__
+
+ assert key == "tests_models_DataclassPerson"
def test_create_success_response_with_stream() -> None:
diff --git a/tests/unit/test_openapi/test_schema.py b/tests/unit/test_openapi/test_schema.py
--- a/tests/unit/test_openapi/test_schema.py
+++ b/tests/unit/test_openapi/test_schema.py
@@ -27,18 +27,16 @@
from litestar._openapi.schema_generation.schema import (
KWARG_DEFINITION_ATTRIBUTE_TO_OPENAPI_PROPERTY_MAP,
SchemaCreator,
- _get_type_schema_name,
)
-from litestar._openapi.schema_generation.utils import _type_or_first_not_none_inner_type
+from litestar._openapi.schema_generation.utils import _get_normalized_schema_key, _type_or_first_not_none_inner_type
from litestar.app import DEFAULT_OPENAPI_CONFIG
from litestar.di import Provide
from litestar.enums import ParamType
-from litestar.exceptions import ImproperlyConfiguredException
from litestar.openapi.spec import ExternalDocumentation, OpenAPIType, Reference
from litestar.openapi.spec.example import Example
from litestar.openapi.spec.schema import Schema
from litestar.pagination import ClassicPagination, CursorPagination, OffsetPagination
-from litestar.params import BodyKwarg, Parameter, ParameterKwarg
+from litestar.params import Parameter, ParameterKwarg
from litestar.testing import create_test_client
from litestar.types.builtin_types import NoneType
from litestar.typing import FieldDefinition
@@ -87,6 +85,47 @@ def test_process_schema_result() -> None:
assert getattr(schema, schema_key) == getattr(kwarg_definition, signature_key)
+def test_get_normalized_schema_key() -> None:
+ class LocalClass(msgspec.Struct):
+ id: str
+
+ assert (
+ "tests_unit_test_openapi_test_schema_test_get_normalized_schema_key_locals_LocalClass"
+ == _get_normalized_schema_key(str(LocalClass))
+ )
+
+ assert "tests_models_DataclassPerson" == _get_normalized_schema_key(str(DataclassPerson))
+
+ builtin_dict = Dict[str, List[int]]
+ assert "typing_Dict_str_typing_List_int" == _get_normalized_schema_key(str(builtin_dict))
+
+ builtin_with_custom = Dict[str, DataclassPerson]
+ assert "typing_Dict_str_tests_models_DataclassPerson" == _get_normalized_schema_key(str(builtin_with_custom))
+
+ class LocalGeneric(Generic[T]):
+ pass
+
+ assert (
+ "tests_unit_test_openapi_test_schema_test_get_normalized_schema_key_locals_LocalGeneric"
+ == _get_normalized_schema_key(str(LocalGeneric))
+ )
+
+ generic_int = LocalGeneric[int]
+ generic_str = LocalGeneric[str]
+
+ assert (
+ "tests_unit_test_openapi_test_schema_test_get_normalized_schema_key_locals_LocalGeneric_int"
+ == _get_normalized_schema_key(str(generic_int))
+ )
+
+ assert (
+ "tests_unit_test_openapi_test_schema_test_get_normalized_schema_key_locals_LocalGeneric_str"
+ == _get_normalized_schema_key(str(generic_str))
+ )
+
+ assert _get_normalized_schema_key(str(generic_int)) != _get_normalized_schema_key(str(generic_str))
+
+
def test_dependency_schema_generation() -> None:
async def top_dependency(query_param: int) -> int:
return query_param
@@ -153,7 +192,7 @@ class DataclassWithLiteral:
)
assert isinstance(result, Reference)
- schema = schemas["DataclassWithLiteral"]
+ schema = schemas["tests_unit_test_openapi_test_schema_test_handling_of_literals_locals_DataclassWithLiteral"]
assert isinstance(schema, Schema)
assert schema.properties
@@ -187,17 +226,10 @@ def test_title_validation() -> None:
schema_creator = SchemaCreator(schemas=schemas)
schema_creator.for_field_definition(FieldDefinition.from_kwarg(name="Person", annotation=DataclassPerson))
- assert schemas.get("DataclassPerson")
+ assert schemas.get("tests_models_DataclassPerson")
schema_creator.for_field_definition(FieldDefinition.from_kwarg(name="Pet", annotation=DataclassPet))
- assert schemas.get("DataclassPet")
-
- with pytest.raises(ImproperlyConfiguredException):
- schema_creator.for_field_definition(
- FieldDefinition.from_kwarg(
- name="DataclassPerson", annotation=DataclassPet, kwarg_definition=BodyKwarg(title="DataclassPerson")
- )
- )
+ assert schemas.get("tests_models_DataclassPet")
@pytest.mark.parametrize("with_future_annotations", [True, False])
@@ -218,7 +250,8 @@ class Foo:
)
schemas: Dict[str, Schema] = {}
SchemaCreator(schemas=schemas).for_field_definition(FieldDefinition.from_annotation(module.Foo))
- schema = schemas["Foo"]
+ schema_key = _get_normalized_schema_key(str(module.Foo))
+ schema = schemas[schema_key]
assert schema.properties and "foo" in schema.properties
@@ -241,7 +274,8 @@ class Foo(TypedDict):
)
schemas: Dict[str, Schema] = {}
SchemaCreator(schemas=schemas).for_field_definition(FieldDefinition.from_annotation(module.Foo))
- schema = schemas["Foo"]
+ schema_key = _get_normalized_schema_key(str(module.Foo))
+ schema = schemas[schema_key]
assert schema.properties and all(key in schema.properties for key in ("foo", "bar", "baz"))
@@ -251,7 +285,7 @@ class Lookup(msgspec.Struct):
schemas: Dict[str, Schema] = {}
SchemaCreator(schemas=schemas).for_field_definition(FieldDefinition.from_kwarg(name="Lookup", annotation=Lookup))
- schema = schemas["Lookup"]
+ schema = schemas["tests_unit_test_openapi_test_schema_test_create_schema_from_msgspec_annotated_type_locals_Lookup"]
assert schema.properties["id"].type == OpenAPIType.STRING # type: ignore
assert schema.properties["id"].examples == {"id-example-1": Example(value="example")} # type: ignore
@@ -279,7 +313,7 @@ class MyDataclass:
SchemaCreator(schemas=schemas).for_field_definition(
FieldDefinition.from_kwarg(name="MyDataclass", annotation=MyDataclass)
)
- schema = schemas["MyDataclass"]
+ schema = schemas["tests_unit_test_openapi_test_schema_test_annotated_types_locals_MyDataclass"]
assert schema.properties["constrained_int"].exclusive_minimum == 1 # type: ignore
assert schema.properties["constrained_int"].exclusive_maximum == 10 # type: ignore
@@ -337,8 +371,8 @@ def test_schema_generation_with_generic_classes(cls: Any) -> None:
schemas: Dict[str, Schema] = {}
SchemaCreator(schemas=schemas).for_field_definition(field_definition)
- name = _get_type_schema_name(field_definition)
- properties = schemas[name].properties
+ path_name = _get_normalized_schema_key(str(cls))
+ properties = schemas[path_name].properties
expected_foo_schema = Schema(type=OpenAPIType.INTEGER)
expected_optional_foo_schema = Schema(one_of=[Schema(type=OpenAPIType.NULL), Schema(type=OpenAPIType.INTEGER)])
@@ -368,8 +402,7 @@ def test_schema_generation_with_generic_classes_constrained() -> None:
schemas: Dict[str, Schema] = {}
SchemaCreator(schemas=schemas).for_field_definition(field_definition)
- name = _get_type_schema_name(field_definition)
- properties = schemas[name].properties
+ properties = schemas["tests_unit_test_openapi_test_schema_ConstrainedGenericDataclass"].properties
assert properties
assert properties["bound"] == Schema(type=OpenAPIType.INTEGER)
@@ -397,8 +430,8 @@ def test_schema_generation_with_pagination(annotation: Any) -> None:
field_definition = FieldDefinition.from_annotation(annotation)
schemas: Dict[str, Schema] = {}
SchemaCreator(schemas=schemas).for_field_definition(field_definition)
- name = _get_type_schema_name(field_definition.inner_types[-1])
- properties = schemas[name].properties
+ schema_key = _get_normalized_schema_key(str(field_definition.inner_types[-1].annotation))
+ properties = schemas[str(schema_key)].properties
expected_foo_schema = Schema(type=OpenAPIType.INTEGER)
expected_optional_foo_schema = Schema(one_of=[Schema(type=OpenAPIType.NULL), Schema(type=OpenAPIType.INTEGER)])
diff --git a/tests/unit/test_openapi/test_spec_generation.py b/tests/unit/test_openapi/test_spec_generation.py
--- a/tests/unit/test_openapi/test_spec_generation.py
+++ b/tests/unit/test_openapi/test_spec_generation.py
@@ -4,6 +4,7 @@
from msgspec import Struct
from litestar import post
+from litestar._openapi.schema_generation.utils import _get_normalized_schema_key
from litestar.testing import create_test_client
from tests.models import DataclassPerson, MsgSpecStructPerson, TypedDictPerson
@@ -17,8 +18,9 @@ def handler(data: cls) -> cls:
with create_test_client(handler) as client:
schema = client.app.openapi_schema
assert schema
+ schema_key = _get_normalized_schema_key(str(cls))
- assert schema.to_schema()["components"]["schemas"][cls.__name__] == {
+ assert schema.to_schema()["components"]["schemas"][schema_key] == {
"properties": {
"first_name": {"type": "string"},
"last_name": {"type": "string"},
@@ -34,7 +36,10 @@ def handler(data: cls) -> cls:
"pets": {
"oneOf": [
{"type": "null"},
- {"items": {"$ref": "#/components/schemas/DataclassPet"}, "type": "array"},
+ {
+ "items": {"$ref": "#/components/schemas/tests_models_DataclassPet"},
+ "type": "array",
+ },
]
},
},
@@ -57,7 +62,9 @@ def handler(data: CamelizedStruct) -> CamelizedStruct:
schema = client.app.openapi_schema
assert schema
- assert schema.to_schema()["components"]["schemas"][CamelizedStruct.__name__] == {
+ assert schema.to_schema()["components"]["schemas"][
+ "tests_unit_test_openapi_test_spec_generation_test_msgspec_schema_locals_CamelizedStruct"
+ ] == {
"properties": {"fieldOne": {"type": "integer"}, "fieldTwo": {"type": "number"}},
"required": ["fieldOne", "fieldTwo"],
"title": "CamelizedStruct",
diff --git a/tests/unit/test_pagination.py b/tests/unit/test_pagination.py
--- a/tests/unit/test_pagination.py
+++ b/tests/unit/test_pagination.py
@@ -120,7 +120,10 @@ def sync_handler(page_size: int, current_page: int) -> ClassicPagination[Datacla
assert spec == {
"schema": {
"properties": {
- "items": {"items": {"$ref": "#/components/schemas/DataclassPerson"}, "type": "array"},
+ "items": {
+ "items": {"$ref": "#/components/schemas/tests_models_DataclassPerson"},
+ "type": "array",
+ },
"page_size": {"type": "integer", "description": "Number of items per page."},
"current_page": {"type": "integer", "description": "Current page number."},
"total_pages": {"type": "integer", "description": "Total number of pages."},
@@ -174,7 +177,10 @@ def sync_handler(limit: int, offset: int) -> OffsetPagination[DataclassPerson]:
assert spec == {
"schema": {
"properties": {
- "items": {"items": {"$ref": "#/components/schemas/DataclassPerson"}, "type": "array"},
+ "items": {
+ "items": {"$ref": "#/components/schemas/tests_models_DataclassPerson"},
+ "type": "array",
+ },
"limit": {"type": "integer", "description": "Maximal number of items to send."},
"offset": {"type": "integer", "description": "Offset from the beginning of the query."},
"total": {"type": "integer", "description": "Total number of items."},
@@ -251,7 +257,10 @@ def sync_handler(cursor: Optional[str] = None) -> CursorPagination[str, Dataclas
assert spec == {
"schema": {
"properties": {
- "items": {"items": {"$ref": "#/components/schemas/DataclassPerson"}, "type": "array"},
+ "items": {
+ "items": {"$ref": "#/components/schemas/tests_models_DataclassPerson"},
+ "type": "array",
+ },
"cursor": {
"type": "string",
"description": "Unique ID, designating the last identifier in the given data set. This value can be used to request the 'next' batch of records.",
| enhancement: OpenAPI re-use existing schemas of same name
### Description
We're getting an unexpected `ImproperlyConfiguredException` in `litestar/_openapi/schema_generation/schema.py", line 594, in process_schema_result`.
In our app, we defined a base`Player` model using Pydantic. This model is returned on its own and also as a subdocument in other endpoints.
Schema generation fails recognizes two different schemas with the same title. However, the schemas only differ in their description. The description itself is set as a field-level annotation when `Player` is used as a subdocument.
This makes setting the `description` at the field level much less useful.
I may be missing something. Looking at the code it hashes the schemas to ensure a 1-1 relationship between titles and schemas. I don't believe this was previously a constraint and schemas were produced based on the module path. I may not understand why this is now a requirement.
I've provided an example showing this behavior for both msgspec and Pydantic.
This behavior is new to Litestar 2.0 and did not exist in Litestar 1.51
### URL to code causing the issue
_No response_
### MCVE
```python
### Example showing the issue with Pydantic
import traceback
from litestar import Litestar, get
from litestar.params import Parameter
from pydantic import BaseModel, Field
from litestar.types.asgi_types import Scope
class Player(BaseModel):
id: str
name: str
position: str
jersey: str
class Play(BaseModel):
id: str
ball_carrier: Player = Field(description="Sub document representing player who carried the ball")
@get("/player", sync_to_thread=True)
def get_player_by_id(id: str = Parameter(str)) -> Player:
return Player(id=id, name="Chris", position="RB", jersey="00")
@get("/play", sync_to_thread=True, include_in_schema=True)
def get_play_by_id(id: str = Parameter(str)) -> Play:
return Play(id=id, ball_carrier=Player(id="asdasd", name="chris", position="rb", jersey="00"))
async def after_exception_hook(exc: Exception, scope: "Scope") -> None:
traceback.print_exc()
app = Litestar(route_handlers=[get_player_by_id, get_play_by_id], after_exception=[after_exception_hook])
if __name__ == "__main__":
import uvicorn
uvicorn.run(app)
```
### Example using msgspec
```py
import traceback
from litestar import Litestar, get
from litestar.params import Parameter
from litestar.types.asgi_types import Scope
from msgspec import Meta, Struct
from typing import Annotated
class Player(Struct):
id: str
name: str
position: str
jersey: str
class Play(Struct):
id: str
ball_carrier: Annotated[Player, Meta(description="Sub document representing player who carried the ball")]
@get("/player", sync_to_thread=True)
def get_player_by_id(id: str = Parameter(str)) -> Player:
return Player(id=id, name="Chris", position="RB", jersey="00")
@get("/play", sync_to_thread=True, include_in_schema=True)
def get_play_by_id(id: str = Parameter(str)) -> Play:
return Play(id=id, ball_carrier=Player(id="asdasd", name="chris", position="rb", jersey="00"))
async def after_exception_hook(exc: Exception, scope: "Scope") -> None:
traceback.print_exc()
app = Litestar(route_handlers=[get_player_by_id, get_play_by_id], after_exception=[after_exception_hook])
if __name__ == "__main__":
import uvicorn
uvicorn.run(app)
```
```
### Steps to reproduce
```bash
1. Create a base app
2. Define a model and set it as the return type of an endpoint
3. Define a second model, containing a field annotated with the model defined in step 2. Set a `description` on the field (i.e. Pydantic `Field(description="{desc}"` or msgspec Annotated[Player, Meta(description="{desc}")]). Create a second endpoint returning this model
4. See error
```
### Screenshots
_No response_
### Logs
```bash
litestar.exceptions.http_exceptions.ImproperlyConfiguredException: 500: Two different schemas with the title Player have been defined.
first: {"properties":{"id":{"type":"string"},"name":{"type":"string"},"position":{"type":"string"},"jersey":{"type":"string"}},"type":"object","required":["id","jersey","name","position"],"title":"Player"}
second: {"properties":{"id":{"type":"string"},"name":{"type":"string"},"position":{"type":"string"},"jersey":{"type":"string"}},"type":"object","required":["id","jersey","name","position"],"title":"Player","description":"Sub document representing player who carried the ball"}
```
### Litestar Version
Python 3.11
litestar[full] @ 2.2.1
pydantic @ 2.4.2
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2471">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2471/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2471/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| After poking around for a bit I guess I'm somewhat confused as to why we care so much about the title being unique.
In `litestar._openapi.schema_generation.schema`.
Revising this:
```python
if schema.title and schema.type in (OpenAPIType.OBJECT, OpenAPIType.ARRAY):
if schema.title in self.schemas and hash(self.schemas[schema.title]) != hash(schema):
raise ImproperlyConfiguredException(
f"Two different schemas with the title {schema.title} have been defined.\n\n"
f"first: {encode_json(self.schemas[schema.title].to_schema()).decode()}\n"
f"second: {encode_json(schema.to_schema()).decode()}\n\n"
f"To fix this issue, either rename the base classes from which these titles are derived or manually"
f"set a 'title' kwarg in the route handler."
)
self.schemas[schema.title] = schema
return Reference(ref=f"#/components/schemas/{schema.title}")
return schema
```
To this:
```python
if schema.title and schema.type in (OpenAPIType.OBJECT, OpenAPIType.ARRAY):
class_name = str(get_text_in_single_quotes(str(field.annotation)).replace(".", ""))
existing = self.schemas.get(class_name)
if existing:
return schema
self.schemas[name_title] = schema
return Reference(ref=f"#/components/schemas/{class_name}")
return schema
```
Seems to work. I'm sure I'm missing something here. Open to any input on it.
Thanks for the excellent report! Hopefully someone with more knowledge on this than me can chime in. Git blame is no help.
Do all tests pass with your change?
No, they would need to be updated to reflect the new naming scheme as they're currently hardcoded to the old one.
I'd make a PR for this but I'm afraid I'm not particularly familiar with the OpenAPI spec and I'm not quite sure if this was changed for compliance purposes? | 2023-10-20T05:41:08 |
litestar-org/litestar | 2,478 | litestar-org__litestar-2478 | [
"2477"
] | 7c3d24f9b70731df372b29bff9eb5cf359055b3a | diff --git a/litestar/logging/config.py b/litestar/logging/config.py
--- a/litestar/logging/config.py
+++ b/litestar/logging/config.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import sys
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass, field
from importlib.util import find_spec
@@ -40,10 +41,13 @@
"class": "litestar.logging.standard.QueueListenerHandler",
"level": "DEBUG",
"formatter": "standard",
- "handlers": ["console"],
},
}
+if sys.version_info >= (3, 12, 0):
+ default_handlers["queue_listener"]["handlers"] = ["console"]
+
+
default_picologging_handlers: dict[str, dict[str, Any]] = {
"console": {
"class": "picologging.StreamHandler",
| Bug: logging AttributeError: 'str' object has no attribute 'handle'
### Description
I get this error using a slightly modified mvce that comes from the docs (just changed the handler to be async)
```
❯ uvicorn l:app
INFO: Started server process [269081]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:35226 - "GET / HTTP/1.1" 200 OK
Exception in thread Thread-1 (_monitor):
Traceback (most recent call last):
File "/home/lotso/.asdf/installs/python/3.11.6/lib/python3.11/threading.py", line 1045, in _bootstrap_inner
self.run()
File "/home/lotso/.asdf/installs/python/3.11.6/lib/python3.11/threading.py", line 982, in run
self._target(*self._args, **self._kwargs)
File "/home/lotso/.asdf/installs/python/3.11.6/lib/python3.11/logging/handlers.py", line 1584, in _monitor
self.handle(record)
File "/home/lotso/.asdf/installs/python/3.11.6/lib/python3.11/logging/handlers.py", line 1565, in handle
handler.handle(record)
^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'handle'
INFO: 127.0.0.1:35226 - "GET / HTTP/1.1" 200 OK
```
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, Request, get
from litestar.logging import LoggingConfig
@get("/")
async def my_router_handler(request: Request) -> None:
request.logger.info("inside a request")
return None
logging_config = LoggingConfig(
loggers={
"my_app": {
"level": "INFO",
"handlers": ["queue_listener"],
}
}
)
app = Litestar(route_handlers=[my_router_handler], logging_config=logging_config)
```
### Steps to reproduce
```bash
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
```
### Screenshots
```bash
""
```
### Logs
_No response_
### Litestar Version
` • Installing litestar (2.2.1 7c3d24f)`
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2477">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2477/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2477/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2.2.1 nor 2.2.0 exhibit the traceback, there might have been a regression recently
What py version?
it's 3.11.6
I also have the bug on same litestar git version but without using LoggingConfig
I think this is the culprit:
https://github.com/litestar-org/litestar/blob/7c3d24f9b70731df372b29bff9eb5cf359055b3a/litestar/logging/config.py#L43
however that just defies my comprehension :)
I think that might just need to be added under an `if >= 3.12.0` guard if that is the case. There have been changes to the way queue handlers/listeners are configured in 3.12 (https://docs.python.org/3/library/logging.config.html#configuring-queuehandler-and-queuelistener).
The thing is, that change hasn't made it into a release yet - you are installing from main? | 2023-10-20T10:22:16 |
|
litestar-org/litestar | 2,509 | litestar-org__litestar-2509 | [
"2494"
] | 0d4fe01a9d361e09748f71aa7adf70672b97c822 | diff --git a/litestar/_openapi/parameters.py b/litestar/_openapi/parameters.py
--- a/litestar/_openapi/parameters.py
+++ b/litestar/_openapi/parameters.py
@@ -18,7 +18,7 @@
from litestar._openapi.schema_generation import SchemaCreator
from litestar.di import Provide
from litestar.handlers.base import BaseRouteHandler
- from litestar.openapi.spec import Reference
+ from litestar.openapi.spec import Example, Reference
from litestar.types.internal_types import PathParameterDefinition
@@ -109,12 +109,17 @@ def create_parameter(
schema = result if isinstance(result, Schema) else schema_creator.schemas[result.value]
+ examples: dict[str, Example | Reference] = {}
+ for i, example in enumerate(kwarg_definition.examples or [] if kwarg_definition else []):
+ examples[f"{field_definition.name}-example-{i}"] = example
+
return Parameter(
description=schema.description,
name=parameter_name,
param_in=param_in,
required=is_required,
schema=result,
+ examples=examples or None,
)
| diff --git a/tests/unit/test_openapi/test_parameters.py b/tests/unit/test_openapi/test_parameters.py
--- a/tests/unit/test_openapi/test_parameters.py
+++ b/tests/unit/test_openapi/test_parameters.py
@@ -1,6 +1,7 @@
from typing import TYPE_CHECKING, List, Optional, Type, cast
import pytest
+from typing_extensions import Annotated
from litestar import Controller, Litestar, Router, get
from litestar._openapi.parameters import create_parameter_for_handler
@@ -11,9 +12,11 @@
from litestar.di import Provide
from litestar.enums import ParamType
from litestar.exceptions import ImproperlyConfiguredException
-from litestar.openapi.spec import OpenAPI
+from litestar.openapi import OpenAPIConfig
+from litestar.openapi.spec import Example, OpenAPI
from litestar.openapi.spec.enums import OpenAPIType
from litestar.params import Dependency, Parameter
+from litestar.testing import create_test_client
from litestar.utils import find_index
if TYPE_CHECKING:
@@ -306,3 +309,19 @@ def my_handler(
assert local.schema.type == OpenAPIType.INTEGER # type: ignore
assert local.required
assert local.schema.examples # type: ignore
+
+
+def test_parameter_examples() -> None:
+ @get(path="/")
+ async def index(
+ text: Annotated[str, Parameter(examples=[Example(value="example value", summary="example summary")])]
+ ) -> str:
+ return text
+
+ with create_test_client(
+ route_handlers=[index], openapi_config=OpenAPIConfig(title="Test API", version="1.0.0")
+ ) as client:
+ response = client.get("/schema/openapi.json")
+ assert response.json()["paths"]["/"]["get"]["parameters"][0]["examples"] == {
+ "text-example-0": {"summary": "example summary", "value": "example value"}
+ }
| Bug: Wrong OpenAPI `examples` format and nesting
### Description
For examples to show up on SwaggerUI, the `examples` array should be an object and nested on the same level as `schema`, not under it.
Wrong definition:
```json
{
"parameters": [
{
"schema": {
"type": "string",
"examples": [
{
"summary": "example summary",
"value": "example value"
}
]
}
}
]
}
````
Correct definition:
```json
{
"parameters": [
{
"schema": {
"type": "string"
},
"examples": {
"example1": {
"summary": "example summary"
"value": "example value"
}
}
}
]
}
```
### MCVE
```python
from litestar import Litestar, get
from litestar.openapi import OpenAPIConfig
from litestar.openapi.spec.example import Example
from litestar.params import Parameter
from typing import Annotated
@get(path="/")
async def index(
text: Annotated[
str,
Parameter(
examples=[Example(value="example value", summary="example summary")]
)
]
) -> str:
return text
app = Litestar(
route_handlers=[
index
],
openapi_config=OpenAPIConfig(
title="Test API",
version="1.0.0"
)
)
```
### Steps to reproduce
```bash
1. Go to the SwaggerUI docs.
2. Click on the `index` GET method.
3. See that there are no examples under the `text` query parameter.
```
### Screenshots

### Litestar Version
2.1.1
### Platform
- [ ] Linux
- [ ] Mac
- [X] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2494">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2494/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2494/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Thanks for reporting @Teraskull!
https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-9.5
> The value of this keyword MUST be an array. There are no
restrictions placed on the values within the array. When multiple
occurrences of this keyword are applicable to a single sub-instance,
implementations MUST provide a flat array of all values rather than
an array of arrays.
Maybe this is a swagger bug? https://github.com/swagger-api/swagger-ui/issues/9045
Elements:

Redoc:

I think we are to spec.
The thing I think we have an issue with is `Parameter.examples` argument, e.g., it seems to work better if the examples are passed as strings, but our types don't allow it:



But that is a different issue.
Closing this as an upstream issue.
Opened https://github.com/litestar-org/litestar/issues/2495 for the related issue.
I was too hasty to close this off and it does appear we have a bug in the parameter examples representations.
The above documentation that I've cited is specifically for schema examples, but parameters have their own structure for providing examples, which we aren't hitting.
From [here](https://github.com/litestar-org/litestar/issues/2495#issuecomment-1776287832):
Thanks @Teraskull - OK I'm slowly catching on.
This example:
```py
@get(path="/")
async def index(
text: Annotated[
str,
Parameter(
examples=[Example(value="example value", summary="example summary")]
)
]
) -> str:
return text
```
should look like this?
```py
@get(path="/")
async def index(
text: Annotated[
str,
Parameter(
examples={"an-example": Example(value="example value", summary="example summary")}
)
]
) -> str:
return text
```
And in the rendered schema, that mapping of example name to example object should exist outside of of the schema object, but we are rendering it as a schema example - which is why these are rendering funky or not at all? Does that sound like I've caught up?
If so, I'll reopen your other issue in favor of this one. | 2023-10-24T03:35:12 |
litestar-org/litestar | 2,530 | litestar-org__litestar-2530 | [
"2529"
] | 24ec7bbda9596ac0e5f267179a54cc50df53dc64 | diff --git a/litestar/middleware/logging.py b/litestar/middleware/logging.py
--- a/litestar/middleware/logging.py
+++ b/litestar/middleware/logging.py
@@ -161,7 +161,7 @@ def log_message(self, values: dict[str, Any]) -> None:
def _serialize_value(self, serializer: Serializer | None, value: Any) -> Any:
if not self.is_struct_logger and isinstance(value, (dict, list, tuple, set)):
value = encode_json(value, serializer)
- return value.decode("utf-8") if isinstance(value, bytes) else value
+ return value.decode("utf-8", errors="backslashreplace") if isinstance(value, bytes) else value
async def extract_request_data(self, request: Request) -> dict[str, Any]:
"""Create a dictionary of values for the message.
| diff --git a/tests/unit/test_middleware/test_logging_middleware.py b/tests/unit/test_middleware/test_logging_middleware.py
--- a/tests/unit/test_middleware/test_logging_middleware.py
+++ b/tests/unit/test_middleware/test_logging_middleware.py
@@ -3,20 +3,25 @@
import pytest
from structlog.testing import capture_logs
+from typing_extensions import Annotated
from litestar import Response, get, post
from litestar.config.compression import CompressionConfig
from litestar.connection import Request
-from litestar.datastructures import Cookie
+from litestar.datastructures import Cookie, UploadFile
+from litestar.enums import RequestEncodingType
from litestar.exceptions import ImproperlyConfiguredException
from litestar.handlers import HTTPRouteHandler
from litestar.logging.config import LoggingConfig, StructLoggingConfig
+from litestar.middleware import logging as middleware_logging
from litestar.middleware.logging import LoggingMiddlewareConfig
+from litestar.params import Body
from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED
from litestar.testing import create_test_client
if TYPE_CHECKING:
from _pytest.logging import LogCaptureFixture
+ from pytest import MonkeyPatch
from litestar.middleware.session.server_side import ServerSideSessionConfig
from litestar.types.callable_types import GetLogger
@@ -191,6 +196,25 @@ def post_handler(data: Dict[str, str]) -> Dict[str, str]:
assert res.json() == {"foo": "bar"}
+async def test_logging_middleware_post_binary_file_without_structlog(monkeypatch: "MonkeyPatch") -> None:
+ # https://github.com/litestar-org/litestar/issues/2529
+
+ @post("/")
+ async def post_handler(data: Annotated[UploadFile, Body(media_type=RequestEncodingType.MULTI_PART)]) -> str:
+ content = await data.read()
+ return f"{len(content)} bytes"
+
+ # force LoggingConfig to not parse body data
+ monkeypatch.setattr(middleware_logging, "structlog_installed", False)
+
+ with create_test_client(
+ route_handlers=[post_handler], middleware=[LoggingMiddlewareConfig().middleware], logging_config=LoggingConfig()
+ ) as client:
+ res = client.post("/", files={"foo": b"\xfa\xfb"})
+ assert res.status_code == 201
+ assert res.text == "2 bytes"
+
+
@pytest.mark.parametrize("logger_name", ("litestar", "other"))
def test_logging_messages_are_not_doubled(
get_logger: "GetLogger", logger_name: str, caplog: "LogCaptureFixture"
| Bug: binary files can't be uploaded if logging is active without structlog installed
### Description
*This is a pro forma report, I will create a PR that fixes this*
### URL to code causing the issue
_No response_
### MCVE
```python
from typing import Annotated
from litestar import Litestar, post
from litestar.datastructures import UploadFile
from litestar.enums import RequestEncodingType
from litestar.logging import LoggingConfig
from litestar.middleware.logging import LoggingMiddlewareConfig
from litestar.params import Body
@post("/")
async def handler(data: Annotated[UploadFile, Body(media_type=RequestEncodingType.MULTI_PART)]) -> str:
return "foo"
app = Litestar(
route_handlers=[handler],
middleware=[LoggingMiddlewareConfig().middleware],
logging_config=LoggingConfig(),
)
```
### Steps to reproduce
Now, install litestar *without* structlog and run it:
```bash
pip install litestar[standard]
LITESTAR_APP=bug:app litestar run --debug
```
Posting a binary file that contains an invalid UTF-8 sequence will cause an exception.
```
Traceback (most recent call last):
File "/home/dennis/src/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/dennis/src/litestar/litestar/middleware/base.py", line 129, in wrapped_call
await original__call__(self, scope, receive, send)
File "/home/dennis/src/litestar/litestar/middleware/logging.py", line 115, in __call__
await self.log_request(scope=scope, receive=receive)
File "/home/dennis/src/litestar/litestar/middleware/logging.py", line 129, in log_request
extracted_data = await self.extract_request_data(request=scope["app"].request_class(scope, receive=receive))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dennis/src/litestar/litestar/middleware/logging.py", line 183, in extract_request_data
data[key] = self._serialize_value(serializer, value)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dennis/src/litestar/litestar/middleware/logging.py", line 164, in _serialize_value
return value.decode("utf-8") if isinstance(value, bytes) else value
^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfa in position 134: invalid start byte
```
The problem is that the body is not parsed when structlog is not installed, and therefore the raw byte sequence will get logged, however, the serialize function assumes it's always valid utf-8.
### Litestar Version
2.2.1 and main
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
| 2023-10-26T20:05:40 |
|
litestar-org/litestar | 2,533 | litestar-org__litestar-2533 | [
"2520"
] | 59576c0494d9c174c069a8178ef06d25a3d0a47e | diff --git a/litestar/types/callable_types.py b/litestar/types/callable_types.py
--- a/litestar/types/callable_types.py
+++ b/litestar/types/callable_types.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, AsyncGenerator, Awaitable, Callable, Generator
+from typing import TYPE_CHECKING, Any, AsyncGenerator, Awaitable, Callable, Generator, TypeVar
if TYPE_CHECKING:
from typing_extensions import TypeAlias
@@ -17,8 +17,9 @@
from litestar.types.internal_types import PathParameterDefinition
from litestar.types.protocols import Logger
+ExceptionT = TypeVar("ExceptionT", bound=Exception)
-AfterExceptionHookHandler: TypeAlias = "Callable[[Exception, Scope], SyncOrAsyncUnion[None]]"
+AfterExceptionHookHandler: TypeAlias = "Callable[[ExceptionT, Scope], SyncOrAsyncUnion[None]]"
AfterRequestHookHandler: TypeAlias = (
"Callable[[ASGIApp], SyncOrAsyncUnion[ASGIApp]] | Callable[[Response], SyncOrAsyncUnion[Response]]"
)
@@ -29,7 +30,7 @@
BeforeMessageSendHookHandler: TypeAlias = "Callable[[Message, Scope], SyncOrAsyncUnion[None]]"
BeforeRequestHookHandler: TypeAlias = "Callable[[Request], Any | Awaitable[Any]]"
CacheKeyBuilder: TypeAlias = "Callable[[Request], str]"
-ExceptionHandler: TypeAlias = "Callable[[Request, Exception], Response]"
+ExceptionHandler: TypeAlias = "Callable[[Request, ExceptionT], Response]"
ExceptionLoggingHandler: TypeAlias = "Callable[[Logger, Scope, list[str]], None]"
GetLogger: TypeAlias = "Callable[..., Logger]"
Guard: TypeAlias = "Callable[[ASGIConnection, BaseRouteHandler], SyncOrAsyncUnion[None]]"
| Enhancement: allow custom exception types in the `ExceptionHandlersMap` and `ExceptionHandler` type
### Summary
The current typing of the `ExceptionHandler` and `ExceptionHandlersMap` causes type checkers to complain if the type of the exception on an exception handler is a subclass of `Exception`. This can be resolved by making the exception type generic (bound to `Exception`).
### Basic Example
# Current Behavior
```python
from litestar import Litestar, Request, Response
class CustomException(Exception):
...
def handle_exc(req: Request, exc: CustomException) -> Response:
...
app = Litestar([], exception_handlers={Exception: handle_exc})
```
MyPy error:
```
error: Dict entry 0 has incompatible type "Type[CustomException]": "Callable[[Request[Any, Any, Any], CustomException], Response[Any]]"; expected "Union[int, Type[Exception]]": "Callable[[Request[Any, Any, Any], Exception], Response[Any]]" [dict-item]
```
Expected Behavior:
No errors from type checkers.
### Drawbacks and Impact
_No response_
### Unresolved questions
_No response_
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2520">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2520/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2520/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-10-26T23:05:30 |
||
litestar-org/litestar | 2,534 | litestar-org__litestar-2534 | [
"2508"
] | 9a9d9b46bd3c180ea4912b61c1d06b1c4e876768 | diff --git a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py
--- a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py
+++ b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py
@@ -21,7 +21,7 @@ class TodoItem(Base):
done: Mapped[bool]
-@post("/", sync_to_thread=True)
+@post("/", sync_to_thread=False)
def add_item(data: TodoItem) -> List[TodoItem]:
return [data]
diff --git a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py
--- a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py
+++ b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py
@@ -23,7 +23,7 @@ class TodoItem(Base):
super_secret_value: Mapped[str] = mapped_column(info=dto_field("private"))
-@post("/", sync_to_thread=True)
+@post("/", sync_to_thread=False)
def add_item(data: TodoItem) -> List[TodoItem]:
data.super_secret_value = "This is a secret"
return [data]
diff --git a/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py b/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py
--- a/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py
+++ b/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py
@@ -117,7 +117,7 @@ def provide_limit_offset_pagination(
class AuthorController(Controller):
"""Author CRUD"""
- dependencies = {"authors_repo": Provide(provide_authors_repo, sync_to_thread=True)}
+ dependencies = {"authors_repo": Provide(provide_authors_repo, sync_to_thread=False)}
@get(path="/authors")
def list_authors(
@@ -151,7 +151,7 @@ def create_author(
# we override the authors_repo to use the version that joins the Books in
@get(
path="/authors/{author_id:uuid}",
- dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=True)},
+ dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=False)},
)
def get_author(
self,
@@ -167,7 +167,7 @@ def get_author(
@patch(
path="/authors/{author_id:uuid}",
- dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=True)},
+ dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=False)},
)
def update_author(
self,
| Documentation: Unnecessary use of sync_to_thread=True
The following are calling object constructors with no I/O, so should be right to run sync.
https://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L120
https://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L154
https://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L170
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2508">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2508/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2508/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-10-26T23:18:11 |
||
litestar-org/litestar | 2,537 | litestar-org__litestar-2537 | [
"2508"
] | fd06486e2ad4ed0a41636659fec4f093a09e3dd0 | diff --git a/litestar/config/response_cache.py b/litestar/config/response_cache.py
--- a/litestar/config/response_cache.py
+++ b/litestar/config/response_cache.py
@@ -1,17 +1,23 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, final
+from typing import TYPE_CHECKING, Any, Callable, final
from urllib.parse import urlencode
-__all__ = ("ResponseCacheConfig", "default_cache_key_builder", "CACHE_FOREVER")
-
+from litestar.status_codes import (
+ HTTP_200_OK,
+ HTTP_300_MULTIPLE_CHOICES,
+ HTTP_301_MOVED_PERMANENTLY,
+ HTTP_308_PERMANENT_REDIRECT,
+)
if TYPE_CHECKING:
from litestar import Litestar
from litestar.connection import Request
from litestar.stores.base import Store
- from litestar.types import CacheKeyBuilder
+ from litestar.types import CacheKeyBuilder, HTTPScope
+
+__all__ = ("ResponseCacheConfig", "default_cache_key_builder", "CACHE_FOREVER")
@final
@@ -35,6 +41,22 @@ def default_cache_key_builder(request: Request[Any, Any, Any]) -> str:
return request.url.path + urlencode(query_params, doseq=True)
+def default_do_cache_predicate(_: HTTPScope, status_code: int) -> bool:
+ """Given a status code, returns a boolean indicating whether the response should be cached.
+
+ Args:
+ _: ASGI scope.
+ status_code: status code of the response.
+
+ Returns:
+ A boolean indicating whether the response should be cached.
+ """
+ return HTTP_200_OK <= status_code < HTTP_300_MULTIPLE_CHOICES or status_code in (
+ HTTP_301_MOVED_PERMANENTLY,
+ HTTP_308_PERMANENT_REDIRECT,
+ )
+
+
@dataclass
class ResponseCacheConfig:
"""Configuration for response caching.
@@ -49,6 +71,9 @@ class ResponseCacheConfig:
""":class:`CacheKeyBuilder <.types.CacheKeyBuilder>`. Defaults to :func:`default_cache_key_builder`."""
store: str = "response_cache"
"""Name of the :class:`Store <.stores.base.Store>` to use."""
+ cache_response_filter: Callable[[HTTPScope, int], bool] = field(default=default_do_cache_predicate)
+ """A callable that receives connection scope and a status code, and returns a boolean indicating whether the
+ response should be cached."""
def get_store_from_app(self, app: Litestar) -> Store:
"""Get the store defined in :attr:`store` from an :class:`Litestar <.app.Litestar>` instance."""
diff --git a/litestar/constants.py b/litestar/constants.py
--- a/litestar/constants.py
+++ b/litestar/constants.py
@@ -21,6 +21,7 @@
SCOPE_STATE_DEPENDENCY_CACHE: Final = "dependency_cache"
SCOPE_STATE_NAMESPACE: Final = "__litestar__"
SCOPE_STATE_RESPONSE_COMPRESSED: Final = "response_compressed"
+SCOPE_STATE_DO_CACHE: Final = "do_cache"
SCOPE_STATE_IS_CACHED: Final = "is_cached"
SKIP_VALIDATION_NAMES: Final = {"request", "socket", "scope", "receive", "send"}
UNDEFINED_SENTINELS: Final = {Signature.empty, Empty, Ellipsis, MISSING, UnsetType}
diff --git a/litestar/middleware/response_cache.py b/litestar/middleware/response_cache.py
--- a/litestar/middleware/response_cache.py
+++ b/litestar/middleware/response_cache.py
@@ -1,23 +1,22 @@
from __future__ import annotations
+from typing import TYPE_CHECKING, cast
+
from msgspec.msgpack import encode as encode_msgpack
+from litestar import Request
+from litestar.constants import HTTP_RESPONSE_BODY, HTTP_RESPONSE_START, SCOPE_STATE_DO_CACHE, SCOPE_STATE_IS_CACHED
from litestar.enums import ScopeType
-from litestar.utils import get_litestar_scope_state
+from litestar.utils import get_litestar_scope_state, set_litestar_scope_state
from .base import AbstractMiddleware
-__all__ = ["ResponseCacheMiddleware"]
-
-from typing import TYPE_CHECKING, cast
-
-from litestar import Request
-from litestar.constants import SCOPE_STATE_IS_CACHED
-
if TYPE_CHECKING:
from litestar.config.response_cache import ResponseCacheConfig
from litestar.handlers import HTTPRouteHandler
- from litestar.types import ASGIApp, Message, Receive, Scope, Send
+ from litestar.types import ASGIApp, HTTPScope, Message, Receive, Scope, Send
+
+__all__ = ["ResponseCacheMiddleware"]
class ResponseCacheMiddleware(AbstractMiddleware):
@@ -27,7 +26,6 @@ def __init__(self, app: ASGIApp, config: ResponseCacheConfig) -> None:
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
route_handler = cast("HTTPRouteHandler", scope["route_handler"])
- store = self.config.get_store_from_app(scope["app"])
expires_in: int | None = None
if route_handler.cache is True:
@@ -35,13 +33,21 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
elif route_handler.cache is not False and isinstance(route_handler.cache, int):
expires_in = route_handler.cache
- messages = []
+ messages: list[Message] = []
async def wrapped_send(message: Message) -> None:
if not get_litestar_scope_state(scope, SCOPE_STATE_IS_CACHED):
- messages.append(message)
- if message["type"] == "http.response.body" and not message["more_body"]:
+ if message["type"] == HTTP_RESPONSE_START:
+ do_cache = self.config.cache_response_filter(cast("HTTPScope", scope), message["status"])
+ set_litestar_scope_state(scope, SCOPE_STATE_DO_CACHE, do_cache)
+ if do_cache:
+ messages.append(message)
+ elif get_litestar_scope_state(scope, SCOPE_STATE_DO_CACHE):
+ messages.append(message)
+
+ if messages and message["type"] == HTTP_RESPONSE_BODY and not message["more_body"]:
key = (route_handler.cache_key_builder or self.config.key_builder)(Request(scope))
+ store = self.config.get_store_from_app(scope["app"])
await store.set(key, encode_msgpack(messages), expires_in=expires_in)
await send(message)
| diff --git a/tests/e2e/test_response_caching.py b/tests/e2e/test_response_caching.py
--- a/tests/e2e/test_response_caching.py
+++ b/tests/e2e/test_response_caching.py
@@ -8,11 +8,12 @@
import msgspec
import pytest
-from litestar import Litestar, Request, get
+from litestar import Litestar, Request, Response, get
from litestar.config.compression import CompressionConfig
from litestar.config.response_cache import CACHE_FOREVER, ResponseCacheConfig
from litestar.enums import CompressionEncoding
from litestar.middleware.response_cache import ResponseCacheMiddleware
+from litestar.status_codes import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
from litestar.stores.base import Store
from litestar.stores.memory import MemoryStore
from litestar.testing import TestClient, create_test_client
@@ -20,8 +21,6 @@
if TYPE_CHECKING:
from time_machine import Coordinates
- from litestar import Response
-
@pytest.fixture()
def mock() -> MagicMock:
@@ -248,3 +247,42 @@ def handler_fn() -> str:
assert stored_value
stored_messages = msgspec.msgpack.decode(stored_value)
assert gzip.decompress(stored_messages[1]["body"]).decode() == return_value
+
+
[email protected](
+ ("response", "should_cache"),
+ [
+ (HTTP_200_OK, True),
+ (HTTP_400_BAD_REQUEST, False),
+ (HTTP_500_INTERNAL_SERVER_ERROR, False),
+ (RuntimeError, False),
+ ],
+)
+def test_default_do_response_cache_predicate(
+ mock: MagicMock, response: Union[int, Type[RuntimeError]], should_cache: bool
+) -> None:
+ @get("/", cache=True)
+ def handler() -> Response:
+ mock()
+ if isinstance(response, int):
+ return Response(None, status_code=response)
+ raise RuntimeError
+
+ with create_test_client([handler]) as client:
+ client.get("/")
+ client.get("/")
+ assert mock.call_count == 1 if should_cache else 2
+
+
+def test_custom_do_response_cache_predicate(mock: MagicMock) -> None:
+ @get("/", cache=True)
+ def handler() -> str:
+ mock()
+ return "OK"
+
+ with create_test_client(
+ [handler], response_cache_config=ResponseCacheConfig(cache_response_filter=lambda *_: False)
+ ) as client:
+ client.get("/")
+ client.get("/")
+ assert mock.call_count == 2
| Documentation: Unnecessary use of sync_to_thread=True
The following are calling object constructors with no I/O, so should be right to run sync.
https://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L120
https://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L154
https://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L170
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2508">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2508/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2508/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-10-27T01:21:36 |
|
litestar-org/litestar | 2,547 | litestar-org__litestar-2547 | [
"2503"
] | 5f0cb6a17c43fb4c906b0e29df43e8f5084d94d7 | diff --git a/litestar/channels/backends/memory.py b/litestar/channels/backends/memory.py
--- a/litestar/channels/backends/memory.py
+++ b/litestar/channels/backends/memory.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import asyncio
from asyncio import Queue
from collections import defaultdict, deque
from typing import Any, AsyncGenerator, Iterable
@@ -65,9 +64,6 @@ async def unsubscribe(self, channels: Iterable[str]) -> None:
async def stream_events(self) -> AsyncGenerator[tuple[str, Any], None]:
"""Return a generator, iterating over events of subscribed channels as they become available"""
while self._queue:
- if not len(self._channels):
- await asyncio.sleep(0)
- continue
yield await self._queue.get()
self._queue.task_done()
diff --git a/litestar/channels/backends/redis.py b/litestar/channels/backends/redis.py
--- a/litestar/channels/backends/redis.py
+++ b/litestar/channels/backends/redis.py
@@ -23,6 +23,35 @@
_XADD_EXPIRE_SCRIPT = (_resource_path / "_redis_xadd_expire.lua").read_text()
+class _LazyEvent:
+ """A lazy proxy to asyncio.Event that only creates the event once it's accessed.
+
+ It ensures that the Event is created within a running event loop. If it's not, there can be an issue where a future
+ within the event itself is attached to a different loop.
+
+ This happens in our tests and could also happen when a user creates an instance of the backend outside an event loop
+ in their application.
+ """
+
+ def __init__(self) -> None:
+ self.__event: asyncio.Event | None = None
+
+ @property
+ def _event(self) -> asyncio.Event:
+ if self.__event is None:
+ self.__event = asyncio.Event()
+ return self.__event
+
+ def set(self) -> None:
+ self._event.set()
+
+ def clear(self) -> None:
+ self._event.clear()
+
+ async def wait(self) -> None:
+ await self._event.wait()
+
+
class RedisChannelsBackend(ChannelsBackend, ABC):
def __init__(self, *, redis: Redis, key_prefix: str, stream_sleep_no_subscriptions: int) -> None:
"""Base redis channels backend.
@@ -35,7 +64,7 @@ def __init__(self, *, redis: Redis, key_prefix: str, stream_sleep_no_subscriptio
"""
self._redis = redis
self._key_prefix = key_prefix
- self._stream_sleep_no_subscriptions = stream_sleep_no_subscriptions / 1000
+ self._stream_sleep_no_subscriptions = stream_sleep_no_subscriptions
def _make_key(self, channel: str) -> str:
return f"{self._key_prefix}_{channel.upper()}"
@@ -60,6 +89,7 @@ def __init__(
)
self.__pub_sub: PubSub | None = None
self._publish_script = self._redis.register_script(_PUBSUB_PUBLISH_SCRIPT)
+ self._has_subscribed = _LazyEvent()
@property
def _pub_sub(self) -> PubSub:
@@ -77,10 +107,13 @@ async def on_shutdown(self) -> None:
async def subscribe(self, channels: Iterable[str]) -> None:
"""Subscribe to ``channels``, and enable publishing to them"""
await self._pub_sub.subscribe(*channels)
+ self._has_subscribed.set()
async def unsubscribe(self, channels: Iterable[str]) -> None:
"""Stop listening for events on ``channels``"""
await self._pub_sub.unsubscribe(*channels)
+ if not self._pub_sub.subscribed:
+ self._has_subscribed.clear()
async def publish(self, data: bytes, channels: Iterable[str]) -> None:
"""Publish ``data`` to ``channels``
@@ -98,11 +131,10 @@ async def stream_events(self) -> AsyncGenerator[tuple[str, Any], None]:
"""
while True:
- if not self._pub_sub.subscribed:
- await asyncio.sleep(self._stream_sleep_no_subscriptions) # no subscriptions found so we sleep a bit
- continue
-
- message = await self._pub_sub.get_message(ignore_subscribe_messages=True, timeout=None) # type: ignore[arg-type]
+ await self._has_subscribed.wait()
+ message = await self._pub_sub.get_message(
+ ignore_subscribe_messages=True, timeout=self._stream_sleep_no_subscriptions
+ )
if message is None:
continue
@@ -149,6 +181,7 @@ def __init__(
self._stream_ttl = stream_ttl if isinstance(stream_ttl, int) else int(stream_ttl.total_seconds() * 1000)
self._flush_all_streams_script = self._redis.register_script(_FLUSHALL_STREAMS_SCRIPT)
self._publish_script = self._redis.register_script(_XADD_EXPIRE_SCRIPT)
+ self._has_subscribed_channels = _LazyEvent()
async def on_startup(self) -> None:
"""Called on application startup"""
@@ -159,10 +192,13 @@ async def on_shutdown(self) -> None:
async def subscribe(self, channels: Iterable[str]) -> None:
"""Subscribe to ``channels``"""
self._subscribed_channels.update(channels)
+ self._has_subscribed_channels.set()
async def unsubscribe(self, channels: Iterable[str]) -> None:
"""Unsubscribe from ``channels``"""
self._subscribed_channels -= set(channels)
+ if not len(self._subscribed_channels):
+ self._has_subscribed_channels.clear()
async def publish(self, data: bytes, channels: Iterable[str]) -> None:
"""Publish ``data`` to ``channels``.
@@ -182,6 +218,11 @@ async def publish(self, data: bytes, channels: Iterable[str]) -> None:
],
)
+ async def _get_subscribed_channels(self) -> set[str]:
+ """Get subscribed channels. If no channels are currently subscribed, wait"""
+ await self._has_subscribed_channels.wait()
+ return self._subscribed_channels
+
async def stream_events(self) -> AsyncGenerator[tuple[str, Any], None]:
"""Return a generator, iterating over events of subscribed channels as they become available.
@@ -190,13 +231,14 @@ async def stream_events(self) -> AsyncGenerator[tuple[str, Any], None]:
"""
stream_ids: dict[str, bytes] = {}
while True:
- stream_keys = [self._make_key(c) for c in self._subscribed_channels]
+ # We wait for subscribed channels, because we can't pass an empty dict to
+ # xread and block for subscribers
+ stream_keys = [self._make_key(c) for c in await self._get_subscribed_channels()]
if not stream_keys:
- await asyncio.sleep(self._stream_sleep_no_subscriptions) # no subscriptions found so we sleep a bit
continue
data: list[tuple[bytes, list[tuple[bytes, dict[bytes, bytes]]]]] = await self._redis.xread(
- {key: stream_ids.get(key, 0) for key in stream_keys}, block=1
+ {key: stream_ids.get(key, 0) for key in stream_keys}, block=self._stream_sleep_no_subscriptions
)
if not data:
| diff --git a/tests/unit/test_channels/test_backends.py b/tests/unit/test_channels/test_backends.py
--- a/tests/unit/test_channels/test_backends.py
+++ b/tests/unit/test_channels/test_backends.py
@@ -74,6 +74,10 @@ async def test_pub_sub_shutdown_leftover_messages(channels_backend_instance: Cha
await asyncio.wait_for(channels_backend_instance.on_shutdown(), timeout=0.1)
+async def test_unsubscribe_without_subscription(channels_backend: ChannelsBackend) -> None:
+ await channels_backend.unsubscribe(["foo"])
+
+
@pytest.mark.parametrize("history_limit,expected_history_length", [(None, 10), (1, 1), (5, 5), (10, 10)])
async def test_get_history(
channels_backend: ChannelsBackend, history_limit: int | None, expected_history_length: int
| Litestar consumes high amount of CPU
### Description
Running litestar `litestar app run` with uvicorn consumes in an idling state on my machines 40-45% CPU.
Is this normal or is there a way to reduce the idling CPU consumption?
Attached a picture of cProfile. `python -m cProfile -o litestar.pstats ./.venv/bin/litestar run`

### URL to code causing the issue
_No response_
### MCVE
```python
UVICORN_LOOP=uvloop litestar run
Using Litestar app from env: 'app.asgi:create_app'
Starting server process ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌──────────────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Litestar version │ 2.2.1 │
│ Debug mode │ Disabled │
│ Python Debugger on exception │ Disabled │
│ CORS │ Enabled │
│ CSRF │ Disabled │
│ OpenAPI │ Enabled path=/schema │
│ Compression │ Disabled │
│ Template engine │ ViteTemplateEngine │
│ Static files │ path=/static dirs=.../src/app/domain/web/public html_mode=Enabled │
│ Middlewares │ JWTCookieAuthenticationMiddleware, SentryLitestarASGIMiddleware, middleware_factory │
└──────────────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
2023-10-23T19:12:38.780745Z [info ] Started server process [4257] [uvicorn.error]
2023-10-23T19:12:38.781923Z [info ] Waiting for application startup. [uvicorn.error]
2023-10-23T19:12:38.789916Z [info ] Application startup complete. [uvicorn.error]
2023-10-23T19:12:38.792650Z [info ] Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) [uvicorn.error]
^C2023-10-23T19:15:04.770399Z [info ] Shutting down [uvicorn.error]
^C2023-10-23T19:15:04.910332Z [info ] Finished server process [4257] [uvicorn.error]
^C2023-10-23T19:15:04.974529Z [info ] ASGI 'lifespan' protocol appears unsupported. [uvicorn.error]
```
```
### Steps to reproduce
```bash
- Run `litestar run`
- Look process ressources
```
### Screenshots

### Logs
_No response_
### Litestar Version
2.2.1
python3.11
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2503">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2503/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2503/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| I cannot reproduce this with a basic application. Can you provide a reproducible example? It’s really hard to debug this without actually know what your app looks like, but I’m fairly certain that there’s some kind of busy loop involved you’re not aware of. | 2023-10-27T18:14:35 |
litestar-org/litestar | 2,550 | litestar-org__litestar-2550 | [
"2456"
] | fa87e08c288461d005bc0d6a2e1951b6ff79d4b2 | diff --git a/litestar/_openapi/schema_generation/schema.py b/litestar/_openapi/schema_generation/schema.py
--- a/litestar/_openapi/schema_generation/schema.py
+++ b/litestar/_openapi/schema_generation/schema.py
@@ -42,6 +42,11 @@
create_numerical_constrained_field_schema,
create_string_constrained_field_schema,
)
+from litestar._openapi.schema_generation.utils import (
+ _should_create_enum_schema,
+ _should_create_literal_schema,
+ _type_or_first_not_none_inner_type,
+)
from litestar.datastructures.upload_file import UploadFile
from litestar.exceptions import ImproperlyConfiguredException
from litestar.openapi.spec import Reference
@@ -159,16 +164,19 @@ def _get_type_schema_name(field_definition: FieldDefinition) -> str:
return name
-def create_enum_schema(annotation: EnumMeta) -> Schema:
+def create_enum_schema(annotation: EnumMeta, include_null: bool = False) -> Schema:
"""Create a schema instance for an enum.
Args:
annotation: An enum.
+ include_null: Whether to include null as a possible value.
Returns:
A schema instance.
"""
- enum_values: list[str | int] = [v.value for v in annotation] # type: ignore
+ enum_values: list[str | int | None] = [v.value for v in annotation] # type: ignore
+ if include_null:
+ enum_values.append(None)
openapi_type = OpenAPIType.STRING if isinstance(enum_values[0], str) else OpenAPIType.INTEGER
return Schema(type=openapi_type, enum=enum_values)
@@ -189,16 +197,19 @@ def _iter_flat_literal_args(annotation: Any) -> Iterable[Any]:
yield arg.value if isinstance(arg, Enum) else arg
-def create_literal_schema(annotation: Any) -> Schema:
+def create_literal_schema(annotation: Any, include_null: bool = False) -> Schema:
"""Create a schema instance for a Literal.
Args:
annotation: An Literal annotation.
+ include_null: Whether to include null as a possible value.
Returns:
A schema instance.
"""
- args = tuple(_iter_flat_literal_args(annotation))
+ args = list(_iter_flat_literal_args(annotation))
+ if include_null:
+ args.append(None)
schema = copy(TYPE_MAP[type(args[0])])
if len(args) > 1:
schema.enum = args
@@ -217,13 +228,7 @@ def create_schema_for_annotation(annotation: Any) -> Schema:
A schema instance or None.
"""
- if annotation in TYPE_MAP:
- return copy(TYPE_MAP[annotation])
-
- if isinstance(annotation, EnumMeta):
- return create_enum_schema(annotation)
-
- return Schema()
+ return copy(TYPE_MAP[annotation]) if annotation in TYPE_MAP else Schema()
class SchemaCreator:
@@ -292,17 +297,26 @@ def for_field_definition(self, field_definition: FieldDefinition) -> Schema | Re
result: Schema | Reference
- # NOTE: The check for whether the field_definition.annotation is a Pagination type
- # has to come before the `is_dataclass_check` since the Pagination classes are dataclasses,
- # but we want to handle them differently from how dataclasses are normally handled.
-
if plugin_for_annotation := self.get_plugin_for(field_definition):
result = self.for_plugin(field_definition, plugin_for_annotation)
+ elif _should_create_enum_schema(field_definition):
+ annotation = _type_or_first_not_none_inner_type(field_definition)
+ result = create_enum_schema(annotation, include_null=field_definition.is_optional)
+ elif _should_create_literal_schema(field_definition):
+ annotation = (
+ make_non_optional_union(field_definition.annotation)
+ if field_definition.is_optional
+ else field_definition.annotation
+ )
+ result = create_literal_schema(annotation, include_null=field_definition.is_optional)
elif field_definition.is_optional:
result = self.for_optional_field(field_definition)
elif field_definition.is_union:
result = self.for_union_field(field_definition)
elif field_definition.origin in (CursorPagination, OffsetPagination, ClassicPagination):
+ # NOTE: The check for whether the field_definition.annotation is a Pagination type
+ # has to come before the `is_dataclass_check` since the Pagination classes are dataclasses,
+ # but we want to handle them differently from how dataclasses are normally handled.
result = self.for_builtin_generics(field_definition)
elif field_definition.is_type_var:
result = self.for_typevar()
@@ -394,9 +408,6 @@ def for_object_type(self, field_definition: FieldDefinition) -> Schema:
items=Schema(one_of=items) if len(items) > 1 else items[0],
)
- if field_definition.is_literal:
- return create_literal_schema(field_definition.annotation)
-
raise ImproperlyConfiguredException(
f"Parameter '{field_definition.name}' with type '{field_definition.annotation}' could not be mapped to an Open API type. "
f"This can occur if a user-defined generic type is resolved as a parameter. If '{field_definition.name}' should "
diff --git a/litestar/_openapi/schema_generation/utils.py b/litestar/_openapi/schema_generation/utils.py
new file mode 100644
--- /dev/null
+++ b/litestar/_openapi/schema_generation/utils.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+from enum import Enum
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from litestar.typing import FieldDefinition
+
+__all__ = (
+ "_type_or_first_not_none_inner_type",
+ "_should_create_enum_schema",
+ "_should_create_literal_schema",
+)
+
+
+def _type_or_first_not_none_inner_type(field_definition: FieldDefinition) -> Any:
+ """Get the first inner type that is not None.
+
+ This is a narrow focussed utility to be used when we know that a field definition either represents
+ a single type, or a single type in a union with `None`, and we want the single type.
+
+ Args:
+ field_definition: A field definition instance.
+
+ Returns:
+ A field definition instance.
+ """
+ if not field_definition.is_optional:
+ return field_definition.annotation
+ inner = next((t for t in field_definition.inner_types if not t.is_none_type), None)
+ if inner is None:
+ raise ValueError("Field definition has no inner type that is not None")
+ return inner.annotation
+
+
+def _should_create_enum_schema(field_definition: FieldDefinition) -> bool:
+ """Predicate to determine if we should create an enum schema for the field def, or not.
+
+ This returns true if the field definition is an enum, or if the field definition is a union
+ of an enum and ``None``.
+
+ When an annotation is ``SomeEnum | None`` we should create a schema for the enum that includes ``null``
+ in the enum values.
+
+ Args:
+ field_definition: A field definition instance.
+
+ Returns:
+ A boolean
+ """
+ return field_definition.is_subclass_of(Enum) or (
+ field_definition.is_optional
+ and len(field_definition.args) == 2
+ and field_definition.has_inner_subclass_of(Enum)
+ )
+
+
+def _should_create_literal_schema(field_definition: FieldDefinition) -> bool:
+ """Predicate to determine if we should create a literal schema for the field def, or not.
+
+ This returns ``True`` if the field definition is an literal, or if the field definition is a union
+ of a literal and None.
+
+ When an annotation is `Literal["anything"] | None` we should create a schema for the literal that includes `null`
+ in the enum values.
+
+ Args:
+ field_definition: A field definition instance.
+
+ Returns:
+ A boolean
+ """
+ return (
+ field_definition.is_literal
+ or field_definition.is_optional
+ and all(inner.is_literal for inner in field_definition.inner_types if not inner.is_none_type)
+ )
diff --git a/litestar/typing.py b/litestar/typing.py
--- a/litestar/typing.py
+++ b/litestar/typing.py
@@ -7,7 +7,7 @@
from typing import Any, AnyStr, Callable, Collection, ForwardRef, Literal, Mapping, Protocol, Sequence, TypeVar, cast
from msgspec import UnsetType
-from typing_extensions import Annotated, NotRequired, Required, Self, get_args, get_origin, get_type_hints, is_typeddict
+from typing_extensions import NotRequired, Required, Self, get_args, get_origin, get_type_hints, is_typeddict
from litestar.exceptions import ImproperlyConfiguredException
from litestar.openapi.spec import Example
@@ -336,12 +336,12 @@ def is_required(self) -> bool:
@property
def is_annotated(self) -> bool:
"""Check if the field type is Annotated."""
- return Annotated in self.type_wrappers # type: ignore[comparison-overlap]
+ return bool(self.metadata)
@property
def is_literal(self) -> bool:
"""Check if the field type is Literal."""
- return get_origin(self.annotation) is Literal
+ return self.origin is Literal
@property
def is_forward_ref(self) -> bool:
@@ -373,6 +373,11 @@ def is_optional(self) -> bool:
"""Whether the annotation is Optional or not."""
return bool(self.is_union and NoneType in self.args)
+ @property
+ def is_none_type(self) -> bool:
+ """Whether the annotation is NoneType or not."""
+ return self.annotation is NoneType
+
@property
def is_collection(self) -> bool:
"""Whether the annotation is a collection type or not."""
| diff --git a/tests/unit/test_openapi/test_schema.py b/tests/unit/test_openapi/test_schema.py
--- a/tests/unit/test_openapi/test_schema.py
+++ b/tests/unit/test_openapi/test_schema.py
@@ -2,7 +2,20 @@
from dataclasses import dataclass
from datetime import date
from enum import Enum, auto
-from typing import TYPE_CHECKING, Any, Dict, Generic, List, Literal, Optional, Tuple, TypedDict, TypeVar, Union
+from typing import ( # type: ignore[attr-defined]
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ Generic,
+ List,
+ Literal,
+ Optional,
+ Tuple,
+ TypedDict,
+ TypeVar,
+ Union,
+ _GenericAlias, # pyright: ignore
+)
import annotated_types
import msgspec
@@ -15,8 +28,8 @@
KWARG_DEFINITION_ATTRIBUTE_TO_OPENAPI_PROPERTY_MAP,
SchemaCreator,
_get_type_schema_name,
- create_schema_for_annotation,
)
+from litestar._openapi.schema_generation.utils import _type_or_first_not_none_inner_type
from litestar.app import DEFAULT_OPENAPI_CONFIG
from litestar.di import Provide
from litestar.enums import ParamType
@@ -27,6 +40,7 @@
from litestar.pagination import ClassicPagination, CursorPagination, OffsetPagination
from litestar.params import BodyKwarg, Parameter, ParameterKwarg
from litestar.testing import create_test_client
+from litestar.types.builtin_types import NoneType
from litestar.typing import FieldDefinition
from litestar.utils.helpers import get_name
from tests.models import DataclassPerson, DataclassPet
@@ -112,12 +126,8 @@ class Opts(str, Enum):
opt1 = "opt1"
opt2 = "opt2"
- @dataclass()
- class M:
- opt: Opts
-
- schema = create_schema_for_annotation(annotation=M.__annotations__["opt"])
- assert schema
+ schema = SchemaCreator().for_field_definition(FieldDefinition.from_annotation(Opts))
+ assert isinstance(schema, Schema)
assert schema.enum == ["opt1", "opt2"]
@@ -144,7 +154,7 @@ class DataclassWithLiteral:
value = schema.properties["value"]
assert isinstance(value, Schema)
- assert value.enum == ("a", "b", "c")
+ assert value.enum == ["a", "b", "c"]
const = schema.properties["const"]
assert isinstance(const, Schema)
@@ -152,7 +162,7 @@ class DataclassWithLiteral:
composite = schema.properties["composite"]
assert isinstance(composite, Schema)
- assert composite.enum == ("a", "b", "c", 1)
+ assert composite.enum == ["a", "b", "c", 1]
def test_schema_hashing() -> None:
@@ -283,15 +293,10 @@ class Foo(Enum):
A = auto()
B = auto()
- @dataclass
- class MyDataclass:
- bar: List[Literal[Foo.A]]
-
- schemas: Dict[str, Schema] = {}
- SchemaCreator(schemas=schemas).for_field_definition(
- FieldDefinition.from_kwarg(name="MyDataclass", annotation=MyDataclass)
- )
- assert schemas["MyDataclass"].properties["bar"].items.const == 1 # type: ignore
+ schema = SchemaCreator().for_field_definition(FieldDefinition.from_annotation(List[Literal[Foo.A]]))
+ assert isinstance(schema, Schema)
+ assert isinstance(schema.items, Schema)
+ assert schema.items.const == 1
@dataclass
@@ -414,3 +419,39 @@ def test_schema_tuple_with_union() -> None:
Schema(type=OpenAPIType.INTEGER),
Schema(one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING)]),
]
+
+
+def test_optional_enum() -> None:
+ class Foo(Enum):
+ A = 1
+ B = 2
+
+ schema = SchemaCreator().for_field_definition(FieldDefinition.from_annotation(Optional[Foo]))
+ assert isinstance(schema, Schema)
+ assert schema.type == OpenAPIType.INTEGER
+ assert schema.enum == [1, 2, None]
+
+
+def test_optional_literal() -> None:
+ schema = SchemaCreator().for_field_definition(FieldDefinition.from_annotation(Optional[Literal[1]]))
+ assert isinstance(schema, Schema)
+ assert schema.type == OpenAPIType.INTEGER
+ assert schema.enum == [1, None]
+
+
[email protected](
+ ("in_type", "out_type"),
+ [
+ (FieldDefinition.from_annotation(Optional[int]), int),
+ (FieldDefinition.from_annotation(Union[None, int]), int),
+ (FieldDefinition.from_annotation(int), int),
+ # hack to create a union of NoneType, NoneType to hit a branch for coverage
+ (FieldDefinition.from_annotation(_GenericAlias(Union, (NoneType, NoneType))), ValueError),
+ ],
+)
+def test_type_or_first_not_none_inner_type_utility(in_type: Any, out_type: Any) -> None:
+ if out_type is ValueError:
+ with pytest.raises(out_type):
+ _type_or_first_not_none_inner_type(in_type)
+ else:
+ assert _type_or_first_not_none_inner_type(in_type) == out_type
| build: extend build timeout for platform compat CI.
<!--
By submitting this pull request, you agree to:
- follow [Litestar's Code of Conduct](https://github.com/litestar-org/.github/blob/main/CODE_OF_CONDUCT.md)
- follow [Litestar's contribution guidelines](https://github.com/litestar-org/.github/blob/main/CONTRIBUTING.md)
- follow the [PSFs's Code of Conduct](https://www.python.org/psf/conduct/)
-->
### Pull Request Checklist
- [ ] New code has 100% test coverage
- [ ] (If applicable) The prose documentation has been updated to reflect the changes introduced by this PR
- [ ] (If applicable) The reference documentation has been updated to reflect the changes introduced by this PR
- [ ] Pre-Commit Checks were ran and passed
- [ ] Tests were ran and passed
### Description
<!--
Please describe your pull request for new release changelog purposes
-->
I've experienced multiple consecutive timeouts on the windows compat CI step.
This PR makes "timeout" an input for the test workflow, and extends it for the compat tests.
### Close Issue(s)
<!--
Please add in issue numbers this pull request will close, if applicable
Examples: Fixes #4321 or Closes #1234
-->
-
| Kudos, SonarCloud Quality Gate passed! [](https://sonarcloud.io/dashboard?id=litestar-org_litestar&pullRequest=2456)
[](https://sonarcloud.io/project/issues?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=BUG) [](https://sonarcloud.io/project/issues?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=BUG)
[](https://sonarcloud.io/project/issues?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=VULNERABILITY) [](https://sonarcloud.io/project/issues?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=VULNERABILITY)
[](https://sonarcloud.io/project/security_hotspots?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=SECURITY_HOTSPOT) [](https://sonarcloud.io/project/security_hotspots?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=SECURITY_HOTSPOT)
[](https://sonarcloud.io/project/issues?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=CODE_SMELL) [](https://sonarcloud.io/project/issues?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=CODE_SMELL) [0 Code Smells](https://sonarcloud.io/project/issues?id=litestar-org_litestar&pullRequest=2456&resolved=false&types=CODE_SMELL)
[](https://sonarcloud.io/component_measures?id=litestar-org_litestar&pullRequest=2456&metric=coverage&view=list) No Coverage information
[](https://sonarcloud.io/component_measures?id=litestar-org_litestar&pullRequest=2456&metric=duplicated_lines_density&view=list) No Duplication information
Documentation preview will be available shortly at https://litestar-org.github.io/litestar-docs-preview/2456 | 2023-10-28T00:35:38 |
litestar-org/litestar | 2,552 | litestar-org__litestar-2552 | [
"2460"
] | 5db8d81fbf24788d38d210e90300e5f0926f830a | diff --git a/litestar/_openapi/schema_generation/schema.py b/litestar/_openapi/schema_generation/schema.py
--- a/litestar/_openapi/schema_generation/schema.py
+++ b/litestar/_openapi/schema_generation/schema.py
@@ -372,7 +372,9 @@ def for_object_type(self, field_definition: FieldDefinition) -> Schema:
)
if field_definition.is_non_string_sequence or field_definition.is_non_string_iterable:
- items = list(map(self.for_field_definition, field_definition.inner_types or ()))
+ # filters out ellipsis from tuple[int, ...] type annotations
+ inner_types = (f for f in field_definition.inner_types if f.annotation is not Ellipsis)
+ items = list(map(self.for_field_definition, inner_types or ()))
return Schema(
type=OpenAPIType.ARRAY,
items=Schema(one_of=sort_schemas_and_references(items)) if len(items) > 1 else items[0],
| diff --git a/tests/unit/test_openapi/test_schema.py b/tests/unit/test_openapi/test_schema.py
--- a/tests/unit/test_openapi/test_schema.py
+++ b/tests/unit/test_openapi/test_schema.py
@@ -2,7 +2,7 @@
from dataclasses import dataclass
from datetime import date
from enum import Enum, auto
-from typing import TYPE_CHECKING, Any, Dict, Generic, List, Literal, Optional, TypedDict, TypeVar, Union
+from typing import TYPE_CHECKING, Any, Dict, Generic, List, Literal, Optional, Tuple, TypedDict, TypeVar, Union
import annotated_types
import msgspec
@@ -397,3 +397,10 @@ def test_schema_generation_with_pagination(annotation: Any) -> None:
assert properties["foo"] == expected_foo_schema
assert properties["annotated_foo"] == expected_foo_schema
assert properties["optional_foo"] == expected_optional_foo_schema
+
+
+def test_schema_generation_with_ellipsis() -> None:
+ schema = SchemaCreator().for_field_definition(FieldDefinition.from_annotation(Tuple[int, ...]))
+ assert isinstance(schema, Schema)
+ assert isinstance(schema.items, Schema)
+ assert schema.items.type == OpenAPIType.INTEGER
| Bug: OpenAPI schema generation doesn't support Ellipsis type hint
### Description
if you use an Ellipsis in your type hint, when generating the OpenAPI document the generation of the schema failed with the error
`'<' not supported between instances of 'NoneType' and 'OpenAPIType'`
it would seem that for v2.0.0 on line 219 in `schema_generation/schema.py` it returns an empty `Schema()` object, which has the property `type = None`. This get passed along to
`litestar/_openapi/schema_generation/utils.py in sort_schemas_and_references at line 17`
where a `<` comparison is done against a NoneType which fails.
### URL to code causing the issue
_No response_
### MCVE
```python
from __future__ import annotations
from litestar import Litestar, get
from msgspec import Struct
class A(Struct)
variable_number_of_ints: tuple[int, ...]
@get("/")
async def test() -> A:
return A()
```
### Steps to reproduce
```bash
1. Run the litestar API
2. Go to http://localhost:8000/schema/swagger
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.0.0
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2460">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2460/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2460/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-10-28T02:23:30 |
|
litestar-org/litestar | 2,554 | litestar-org__litestar-2554 | [
"2335"
] | 0ea62a3ae60c8aa0b7d99027733e41b54e07a8de | diff --git a/litestar/cli/_utils.py b/litestar/cli/_utils.py
--- a/litestar/cli/_utils.py
+++ b/litestar/cli/_utils.py
@@ -5,6 +5,7 @@
import inspect
import sys
from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
from functools import wraps
from itertools import chain
from os import getenv
@@ -34,6 +35,7 @@
import jsbeautifier # noqa: F401
JSBEAUTIFIER_INSTALLED = True
+
if TYPE_CHECKING or not RICH_CLICK_INSTALLED: # pragma: no cover
from click import ClickException, Command, Context, Group, pass_context
else:
@@ -98,6 +100,9 @@ class LitestarEnv:
reload_dirs: tuple[str, ...] | None = None
web_concurrency: int | None = None
is_app_factory: bool = False
+ certfile_path: str | None = None
+ keyfile_path: str | None = None
+ create_self_signed_cert: bool = False
@classmethod
def from_env(cls, app_path: str | None, app_dir: Path | None = None) -> LitestarEnv:
@@ -140,6 +145,9 @@ def from_env(cls, app_path: str | None, app_dir: Path | None = None) -> Litestar
web_concurrency=int(web_concurrency) if web_concurrency else None,
is_app_factory=loaded_app.is_factory,
cwd=cwd,
+ certfile_path=getenv("LITESTAR_SSL_CERT_PATH"),
+ keyfile_path=getenv("LITESTAR_SSL_KEY_PATH"),
+ create_self_signed_cert=_bool_from_env("LITESTAR_CREATE_SELF_SIGNED_CERT"),
)
@@ -410,3 +418,118 @@ def show_app_info(app: Litestar) -> None: # pragma: no cover
table.add_row("Middlewares", ", ".join(middlewares))
console.print(table)
+
+
+def validate_ssl_file_paths(certfile_arg: str | None, keyfile_arg: str | None) -> tuple[str, str] | tuple[None, None]:
+ """Validate whether given paths exist, are not directories and were both provided or none was. Return the resolved paths.
+
+ Args:
+ certfile_arg: path argument for the certificate file
+ keyfile_arg: path argument for the key file
+
+ Returns:
+ tuple of resolved paths converted to str or tuple of None's if no argument was provided
+ """
+ if certfile_arg is None and keyfile_arg is None:
+ return (None, None)
+
+ resolved_paths = []
+
+ for argname, arg in {"--ssl-certfile": certfile_arg, "--ssl-keyfile": keyfile_arg}.items():
+ if arg is None:
+ raise LitestarCLIException(f"No value provided for {argname}")
+ path = Path(arg).resolve()
+ if path.is_dir():
+ raise LitestarCLIException(f"Path provided for {argname} is a directory: {path}")
+ if not path.exists():
+ raise LitestarCLIException(f"File provided for {argname} was not found: {path}")
+ resolved_paths.append(str(path))
+
+ return tuple(resolved_paths) # type: ignore
+
+
+def create_ssl_files(
+ certfile_arg: str | None, keyfile_arg: str | None, common_name: str = "localhost"
+) -> tuple[str, str]:
+ """Validate whether both files were provided, are not directories, their parent dirs exist and either both files exists or none does.
+ If neither file exists, create a self-signed ssl certificate and a passwordless key at the location.
+
+ Args:
+ certfile_arg: path argument for the certificate file
+ keyfile_arg: path argument for the key file
+ common_name: the CN to be used as cert issuer and subject
+
+ Returns:
+ resolved paths of the found or generated files
+ """
+ resolved_paths = []
+
+ for argname, arg in {"--ssl-certfile": certfile_arg, "--ssl-keyfile": keyfile_arg}.items():
+ if arg is None:
+ raise LitestarCLIException(f"No value provided for {argname}")
+ path = Path(arg).resolve()
+ if path.is_dir():
+ raise LitestarCLIException(f"Path provided for {argname} is a directory: {path}")
+ if not (parent_dir := path.parent).exists():
+ raise LitestarCLIException(
+ f"Could not create file, parent directory for {argname} doesn't exist: {parent_dir}"
+ )
+ resolved_paths.append(path)
+
+ if (not resolved_paths[0].exists()) ^ (not resolved_paths[1].exists()):
+ raise LitestarCLIException(
+ "Both certificate and key file must exists or both must not exists when using --create-self-signed-cert"
+ )
+
+ if (not resolved_paths[0].exists()) and (not resolved_paths[1].exists()):
+ _generate_self_signed_cert(resolved_paths[0], resolved_paths[1], common_name)
+
+ return (str(resolved_paths[0]), str(resolved_paths[1]))
+
+
+def _generate_self_signed_cert(certfile_path: Path, keyfile_path: Path, common_name: str) -> None:
+ """Create a self-signed certificate using the cryptography modules at given paths"""
+ try:
+ from cryptography import x509
+ from cryptography.hazmat.backends import default_backend
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import rsa
+ from cryptography.x509.oid import NameOID
+ except ImportError as err:
+ raise LitestarCLIException(
+ "Cryptogpraphy must be installed when using --create-self-signed-cert\nPlease install the litestar[cryptography] extras"
+ ) from err
+
+ subject = x509.Name(
+ [
+ x509.NameAttribute(NameOID.COMMON_NAME, common_name),
+ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Development Certificate"),
+ ]
+ )
+
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
+
+ cert = (
+ x509.CertificateBuilder()
+ .subject_name(subject)
+ .issuer_name(subject)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(datetime.now(tz=timezone.utc))
+ .not_valid_after(datetime.now(tz=timezone.utc) + timedelta(days=365))
+ .add_extension(x509.SubjectAlternativeName([x509.DNSName(common_name)]), critical=False)
+ .add_extension(x509.ExtendedKeyUsage([x509.OID_SERVER_AUTH]), critical=False)
+ .sign(key, hashes.SHA256(), default_backend())
+ )
+
+ with certfile_path.open("wb") as cert_file:
+ cert_file.write(cert.public_bytes(serialization.Encoding.PEM))
+
+ with keyfile_path.open("wb") as key_file:
+ key_file.write(
+ key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.TraditionalOpenSSL,
+ encryption_algorithm=serialization.NoEncryption(),
+ )
+ )
diff --git a/litestar/cli/commands/core.py b/litestar/cli/commands/core.py
--- a/litestar/cli/commands/core.py
+++ b/litestar/cli/commands/core.py
@@ -9,7 +9,15 @@
from rich.tree import Tree
-from litestar.cli._utils import RICH_CLICK_INSTALLED, UVICORN_INSTALLED, LitestarEnv, console, show_app_info
+from litestar.cli._utils import (
+ RICH_CLICK_INSTALLED,
+ UVICORN_INSTALLED,
+ LitestarEnv,
+ console,
+ create_ssl_files,
+ show_app_info,
+ validate_ssl_file_paths,
+)
from litestar.routes import HTTPRoute, WebSocketRoute
from litestar.utils.helpers import unwrap_partial
@@ -85,6 +93,13 @@ def info_command(app: Litestar) -> None:
@option("-U", "--uds", "--unix-domain-socket", help="Bind to a UNIX domain socket.", default=None, show_default=True)
@option("-d", "--debug", help="Run app in debug mode", is_flag=True)
@option("-P", "--pdb", "--use-pdb", help="Drop into PDB on an exception", is_flag=True)
+@option("--ssl-certfile", help="Location of the SSL cert file", default=None)
+@option("--ssl-keyfile", help="Location of the SSL key file", default=None)
+@option(
+ "--create-self-signed-cert",
+ help="If certificate and key are not found at specified locations, create a self-signed certificate and a key",
+ is_flag=True,
+)
def run_command(
reload: bool,
port: int,
@@ -95,6 +110,9 @@ def run_command(
debug: bool,
reload_dir: tuple[str, ...],
pdb: bool,
+ ssl_certfile: str | None,
+ ssl_keyfile: str | None,
+ create_self_signed_cert: bool,
ctx: Context,
) -> None:
"""Run a Litestar app; requires ``uvicorn``.
@@ -138,6 +156,16 @@ def run_command(
reload = env.reload or reload or bool(reload_dirs)
workers = env.web_concurrency or wc
+ ssl_certfile = ssl_certfile or env.certfile_path
+ ssl_keyfile = ssl_keyfile or env.keyfile_path
+ create_self_signed_cert = create_self_signed_cert or env.create_self_signed_cert
+
+ certfile_path, keyfile_path = (
+ create_ssl_files(ssl_certfile, ssl_keyfile, host)
+ if create_self_signed_cert
+ else validate_ssl_file_paths(ssl_certfile, ssl_keyfile)
+ )
+
console.rule("[yellow]Starting server process", align="left")
show_app_info(app)
@@ -153,6 +181,8 @@ def run_command(
fd=fd,
uds=uds,
factory=env.is_app_factory,
+ ssl_certfile=certfile_path,
+ ssl_keyfile=keyfile_path,
)
else:
# invoke uvicorn in a subprocess to be able to use the --reload flag. see
@@ -169,6 +199,8 @@ def run_command(
"port": port,
"workers": workers,
"factory": env.is_app_factory,
+ "ssl-certfile": certfile_path,
+ "ssl-keyfile": keyfile_path,
}
if fd is not None:
process_args["fd"] = fd
| diff --git a/tests/unit/test_cli/test_core_commands.py b/tests/unit/test_cli/test_core_commands.py
--- a/tests/unit/test_cli/test_core_commands.py
+++ b/tests/unit/test_cli/test_core_commands.py
@@ -116,11 +116,11 @@ def test_run_command(
if web_concurrency is None:
web_concurrency = 1
-
elif set_in_env:
monkeypatch.setenv("WEB_CONCURRENCY", str(web_concurrency))
else:
args.extend(["--web-concurrency", str(web_concurrency)])
+
if reload_dir is not None:
if set_in_env:
monkeypatch.setenv("LITESTAR_RELOAD_DIRS", ",".join(reload_dir))
@@ -142,6 +142,8 @@ def test_run_command(
f"{path.stem}:app",
f"--host={host}",
f"--port={port}",
+ "--ssl-certfile=None",
+ "--ssl-keyfile=None",
]
if fd is not None:
expected_args.append(f"--fd={fd}")
@@ -158,7 +160,14 @@ def test_run_command(
else:
mock_subprocess_run.assert_not_called()
mock_uvicorn_run.assert_called_once_with(
- app=f"{path.stem}:app", host=host, port=port, uds=uds, fd=fd, factory=False
+ app=f"{path.stem}:app",
+ host=host,
+ port=port,
+ uds=uds,
+ fd=fd,
+ factory=False,
+ ssl_certfile=None,
+ ssl_keyfile=None,
)
mock_show_app_info.assert_called_once()
@@ -190,7 +199,14 @@ def test_run_command_with_autodiscover_app_factory(
assert result.exit_code == 0
mock_uvicorn_run.assert_called_once_with(
- app=f"{path.stem}:{factory_name}", host="127.0.0.1", port=8000, factory=True, uds=None, fd=None
+ app=f"{path.stem}:{factory_name}",
+ host="127.0.0.1",
+ port=8000,
+ factory=True,
+ uds=None,
+ fd=None,
+ ssl_certfile=None,
+ ssl_keyfile=None,
)
@@ -205,7 +221,14 @@ def test_run_command_with_app_factory(
assert result.exit_code == 0
mock_uvicorn_run.assert_called_once_with(
- app=str(app_path), host="127.0.0.1", port=8000, factory=True, uds=None, fd=None
+ app=str(app_path),
+ host="127.0.0.1",
+ port=8000,
+ factory=True,
+ uds=None,
+ fd=None,
+ ssl_certfile=None,
+ ssl_keyfile=None,
)
diff --git a/tests/unit/test_cli/test_ssl.py b/tests/unit/test_cli/test_ssl.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/test_cli/test_ssl.py
@@ -0,0 +1,341 @@
+import sys
+from pathlib import Path
+from typing import Optional, Protocol, cast
+from unittest.mock import MagicMock
+
+import pytest
+from click import ClickException
+from click.testing import CliRunner
+from pytest_mock import MockerFixture
+
+from litestar.cli.main import litestar_group as cli_command
+
+
+class GetClickExceptionFixture(Protocol):
+ def __call__(self, exception: SystemExit) -> ClickException:
+ ...
+
+
[email protected]
+def get_click_exception() -> GetClickExceptionFixture:
+ def _get_click_exception(exception: SystemExit) -> ClickException:
+ exc = exception
+ while exc.__context__ is not None:
+ if isinstance(exc, ClickException):
+ break
+ exc = exc.__context__ # type: ignore[assignment]
+ return cast(ClickException, exc)
+
+ return _get_click_exception
+
+
[email protected]("create_self_signed_cert", (True, False))
[email protected]("mock_uvicorn_run")
+def test_both_files_provided(app_file: Path, runner: CliRunner, create_self_signed_cert: bool) -> None:
+ path = app_file
+ app_path = f"{path.stem}:app"
+
+ cert_path = path.parent / "cert.pem"
+ with cert_path.open("wb") as certfile:
+ certfile.write(b"certfile")
+
+ key_path = path.parent / "key.pem"
+ with key_path.open("wb") as keyfile:
+ keyfile.write(b"keyfile")
+
+ args = ["--app", app_path, "run", "--ssl-certfile", str(cert_path), "--ssl-keyfile", str(key_path)]
+
+ if create_self_signed_cert:
+ args.append("--create-self-signed-cert")
+
+ result = runner.invoke(cli_command, args)
+
+ assert result.exception is None
+ assert result.exit_code == 0
+
+ if create_self_signed_cert:
+ with cert_path.open("rb") as certfile:
+ assert certfile.read() == b"certfile"
+
+ with key_path.open("rb") as keyfile:
+ assert keyfile.read() == b"keyfile"
+
+
[email protected]("create_self_signed_cert", (True, False))
[email protected](
+ "ssl_certfile, ssl_keyfile",
+ [("directory", "exists.pem"), ("exists.pem", "directory")],
+)
+def test_path_is_a_directory(
+ app_file: Path,
+ runner: CliRunner,
+ ssl_certfile: str,
+ ssl_keyfile: str,
+ create_self_signed_cert: bool,
+ get_click_exception: GetClickExceptionFixture,
+) -> None:
+ path = app_file
+ app_path = f"{path.stem}:app"
+
+ (path.parent / "exists.pem").touch()
+ (path.parent / "directory").mkdir(exist_ok=True)
+
+ args = ["--app", app_path, "run", "--ssl-certfile", ssl_certfile, "--ssl-keyfile", ssl_keyfile]
+
+ if create_self_signed_cert:
+ args.append("--create-self-signed-cert")
+
+ result = runner.invoke(cli_command, args)
+
+ assert result.exit_code == 1
+
+ assert isinstance(result.exception, SystemExit)
+ exc = get_click_exception(result.exception)
+ assert "Path provided for" in exc.message
+ assert "is a directory" in exc.message
+
+
[email protected]("create_self_signed_cert", (True, False))
[email protected](
+ "ssl_certfile, ssl_keyfile",
+ [("exists.pem", None), (None, "exists.pem")],
+)
+def test_one_file_provided(
+ app_file: Path,
+ runner: CliRunner,
+ ssl_certfile: Optional[str],
+ ssl_keyfile: Optional[str],
+ create_self_signed_cert: bool,
+ get_click_exception: GetClickExceptionFixture,
+) -> None:
+ path = app_file
+ app_path = f"{path.stem}:app"
+
+ (path.parent / "exists.pem").touch()
+
+ args = ["--app", app_path, "run"]
+
+ if ssl_certfile is not None:
+ args.extend(["--ssl-certfile", str(ssl_certfile)])
+
+ if ssl_keyfile is not None:
+ args.extend(["--ssl-keyfile", str(ssl_keyfile)])
+
+ if create_self_signed_cert:
+ args.append("--create-self-signed-cert")
+
+ result = runner.invoke(cli_command, args)
+
+ assert result.exit_code == 1
+
+ assert isinstance(result.exception, SystemExit)
+ exc = get_click_exception(result.exception)
+ assert "No value provided for" in exc.message
+
+
[email protected]("create_self_signed_cert", (True, False))
[email protected](
+ "ssl_certfile, ssl_keyfile",
+ [("not_exists.pem", "exists.pem"), ("exists.pem", "not_exists.pem")],
+)
+def test_one_file_not_found(
+ app_file: Path,
+ runner: CliRunner,
+ ssl_certfile: str,
+ ssl_keyfile: str,
+ create_self_signed_cert: bool,
+ get_click_exception: GetClickExceptionFixture,
+) -> None:
+ path = app_file
+ app_path = f"{path.stem}:app"
+
+ (path.parent / "exists.pem").touch()
+
+ args = ["--app", app_path, "run"]
+
+ if ssl_certfile is not None:
+ args.extend(["--ssl-certfile", str(ssl_certfile)])
+
+ if ssl_keyfile is not None:
+ args.extend(["--ssl-keyfile", str(ssl_keyfile)])
+
+ if create_self_signed_cert:
+ args.append("--create-self-signed-cert")
+
+ result = runner.invoke(cli_command, args)
+
+ assert result.exit_code == 1
+
+ assert isinstance(result.exception, SystemExit)
+ exc = get_click_exception(result.exception)
+ if create_self_signed_cert:
+ assert (
+ "Both certificate and key file must exists or both must not exists when using --create-self-signed-cert"
+ in exc.message
+ )
+ else:
+ assert "File provided for" in exc.message
+ assert "was not found" in exc.message
+
+
[email protected](
+ "ssl_certfile, ssl_keyfile",
+ [("dir_exists/file.pem", "dir_not_exists/file.pem"), ("dir_not_exists/file.pem", "dir_exists/file.pem")],
+)
+def test_file_parent_doesnt_exist(
+ app_file: Path,
+ runner: CliRunner,
+ ssl_certfile: str,
+ ssl_keyfile: str,
+ get_click_exception: GetClickExceptionFixture,
+) -> None:
+ path = app_file
+ app_path = f"{path.stem}:app"
+
+ (path.parent / "dir_exists").mkdir(exist_ok=True)
+
+ args = [
+ "--app",
+ app_path,
+ "run",
+ "--ssl-certfile",
+ ssl_certfile,
+ "--ssl-keyfile",
+ ssl_keyfile,
+ "--create-self-signed-cert",
+ ]
+
+ result = runner.invoke(cli_command, args)
+
+ assert result.exit_code == 1
+
+ assert isinstance(result.exception, SystemExit)
+ exc = get_click_exception(result.exception)
+ assert "Could not create file, parent directory for" in exc.message
+ assert "doesn't exist" in exc.message
+
+
+def test_without_cryptography_installed(
+ app_file: Path,
+ runner: CliRunner,
+ get_click_exception: GetClickExceptionFixture,
+ mocker: MockerFixture,
+) -> None:
+ mocker.patch.dict("sys.modules", {"cryptography": None})
+
+ path = app_file
+ app_path = f"{path.stem}:app"
+
+ args = [
+ "--app",
+ app_path,
+ "run",
+ "--ssl-certfile",
+ "certfile.pem",
+ "--ssl-keyfile",
+ "keyfile.pem",
+ "--create-self-signed-cert",
+ ]
+
+ result = runner.invoke(cli_command, args)
+
+ assert result.exit_code == 1
+
+ assert isinstance(result.exception, SystemExit)
+ exc = get_click_exception(result.exception)
+ assert "Cryptogpraphy must be installed when using --create-self-signed-cert" in exc.message
+
+
[email protected]("mock_uvicorn_run")
+def test_create_certificates(app_file: Path, runner: CliRunner) -> None:
+ path = app_file
+ app_path = f"{path.stem}:app"
+
+ certfile_path = path.parent / "certificate.pem"
+ keyfile_path = path.parent / "key.pem"
+
+ args = [
+ "--app",
+ app_path,
+ "run",
+ "--ssl-certfile",
+ str(certfile_path),
+ "--ssl-keyfile",
+ str(keyfile_path),
+ "--create-self-signed-cert",
+ ]
+
+ result = runner.invoke(cli_command, args)
+
+ assert result.exit_code == 0
+ assert result.exception is None
+
+ assert certfile_path.exists()
+ assert keyfile_path.exists()
+
+
[email protected](
+ "ssl_certfile, ssl_keyfile, create_self_signed_cert", [(None, None, False), ("cert.pem", "key.pem", True)]
+)
[email protected]("run_as_subprocess", (True, False))
+def test_arguments_passed(
+ app_file: Path,
+ runner: CliRunner,
+ mock_subprocess_run: MagicMock,
+ mock_uvicorn_run: MagicMock,
+ ssl_certfile: Optional[str],
+ ssl_keyfile: Optional[str],
+ create_self_signed_cert: bool,
+ run_as_subprocess: bool,
+) -> None:
+ path = app_file
+ app_path = f"{path.stem}:app"
+
+ project_path = path.parent
+
+ args = ["--app", app_path, "run"]
+
+ if run_as_subprocess:
+ args.extend(["--web-concurrency", "2"])
+
+ if ssl_certfile is not None:
+ args.extend(["--ssl-certfile", str(ssl_certfile)])
+
+ if ssl_keyfile is not None:
+ args.extend(["--ssl-keyfile", str(ssl_keyfile)])
+
+ if create_self_signed_cert:
+ args.append("--create-self-signed-cert")
+
+ result = runner.invoke(cli_command, args)
+
+ assert result.exit_code == 0
+ assert result.exception is None
+
+ if run_as_subprocess:
+ expected_args = [
+ sys.executable,
+ "-m",
+ "uvicorn",
+ f"{path.stem}:app",
+ "--host=127.0.0.1",
+ "--port=8000",
+ "--workers=2",
+ f"--ssl-certfile={None if ssl_certfile is None else str(project_path / ssl_certfile)}",
+ f"--ssl-keyfile={None if ssl_keyfile is None else str(project_path / ssl_keyfile)}",
+ ]
+ mock_subprocess_run.assert_called_once()
+ assert sorted(mock_subprocess_run.call_args_list[0].args[0]) == sorted(expected_args)
+
+ else:
+ mock_subprocess_run.assert_not_called()
+ mock_uvicorn_run.assert_called_once_with(
+ app=f"{path.stem}:app",
+ host="127.0.0.1",
+ port=8000,
+ factory=False,
+ fd=None,
+ uds=None,
+ ssl_certfile=(None if ssl_certfile is None else str(project_path / ssl_certfile)),
+ ssl_keyfile=(None if ssl_keyfile is None else str(project_path / ssl_keyfile)),
+ )
| Enhancement: Self-signed certificate generation for CLI
### Summary
This is along the lines what Flask (actually Werkzeug) and Django-extensions have. A new CLI option (or two) would be added to the `run` command
- `--ssl-certfile` to specify the location of the certificate
- `--ssl-keyfile` to specify the location of the keyfile
- If only one of them is provided, the second file is assumed to be in the same directory
- If the files are not found, they are automatically generated
The logic is taken from [`runserver_plus` in Django Extensions](https://django-extensions.readthedocs.io/en/latest/runserver_plus.html#ssl) and the names are taken from [Uvicorn](https://www.uvicorn.org/settings/#https)
The paths would be then forwarded to Uvicorn.
It would require the `cryptography` extras (which are already used for client sessions) and the `cryptography` module would be used to generate the self-signed certificates.
[HERE](https://github.com/pallets/werkzeug/blob/main/src/werkzeug/serving.py#L540) is how Werkzeug handles the cert generation and [HERE](https://github.com/django-extensions/django-extensions/blob/main/django_extensions/management/commands/runserver_plus.py#L404) is how Django-Extensions handles the logic.
It is only meant to be used for development purposes on a HTTPS connection of course and would only generate a self-signed certificate.
### Basic Example
`litestar run --ssl-certfile=cert/server.crt` - looks for `server.key` inside of the `cert/` directory
`litestar run --ssl-keyfile=cert/server.key` - looks for `server.crt` inside of the `cert/` directory
`litestar run --ssl-cerfile=cert/server.crt --ssl-keyfile=security/keys/server.key`
- if both files exist, use them
- otherwise generate new ones using `cryptography`
- if `cryptography` extras are not installed, terminate and inform user
### Drawbacks and Impact
_No response_
### Unresolved questions
The exact logic and option names are open for discussion.
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2335">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2335/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2335/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| I like this idea, but I want to make on additional suggestion.
Even though we don't recommend it, I know people use this to deploy their apps, and we might want to "officially" support that option in the future. The presence of cert flags implies they might be used to deploy proper certs, so having them autogenerate certs if they're missing by default could lead to some serious issues.
To prevent this, we could add an additional flag `--generate-dev-certs` (or a better name) that enables this explicitly.
@litestar-org/maintainers?
> I like this idea, but I want to make on additional suggestion.
>
> Even though we don't recommend it, I know people use this to deploy their apps, and we might want to "officially" support that option in the future. The presence of cert flags implies they might be used to deploy proper certs, so having them autogenerate certs if they're missing by default could lead to some serious issues.
>
> To prevent this, we could add an additional flag `--generate-dev-certs` (or a better name) that enables this explicitly.
>
> @litestar-org/maintainers?
Yeah - erring on the side of caution sounds reasonable to me.
I'd imagine there are few non-dev scenarios where having a self-signed cert might also be desirable (although I can't think of one right now). I do agree that it needs to an extra flag to do this.
I can't think of anything better than `--generate-dev-certs` or `--generate-self-signed-certs` either, so no strong opinions on that one.
How about something like [trustme](https://github.com/python-trio/trustme) instead?
> How about something like [trustme](https://github.com/python-trio/trustme) instead?
I like this approach as well. @geeshta can you elaborate on your specific use case for self-signed certs? Is it specifically for local development with SSL enabled? Integration with `trustme` may be the easiest way to bake this functionality in.
> > How about something like [trustme](https://github.com/python-trio/trustme) instead?
>
> I like this approach as well. @geeshta can you elaborate on your specific use case for self-signed certs? Is it specifically for local development with SSL enabled? Integration with `trustme` may be the easiest way to bake this functionality in.
Yeah it's just to enable serving with HTTPS during development (I use some client side JavaScript that requires HTTPS).
I haven't heard about trustme before but I really like how django-extensions handles that.
I personally never needed the certificate to be actually signed by a CA as trustme provides though and saw that Werkzeug uses `cryptography` to generate self-signed certs. | 2023-10-28T14:53:51 |
litestar-org/litestar | 2,570 | litestar-org__litestar-2570 | [
"2563"
] | 57a84113f75ccb21e472af5661f3da8473c1891f | diff --git a/litestar/_openapi/schema_generation/schema.py b/litestar/_openapi/schema_generation/schema.py
--- a/litestar/_openapi/schema_generation/schema.py
+++ b/litestar/_openapi/schema_generation/schema.py
@@ -42,9 +42,6 @@
create_numerical_constrained_field_schema,
create_string_constrained_field_schema,
)
-from litestar._openapi.schema_generation.utils import (
- sort_schemas_and_references,
-)
from litestar.datastructures.upload_file import UploadFile
from litestar.exceptions import ImproperlyConfiguredException
from litestar.openapi.spec import Reference
@@ -365,9 +362,9 @@ def for_union_field(self, field_definition: FieldDefinition) -> Schema:
Returns:
A schema instance.
"""
- inner_types = [f for f in (field_definition.inner_types or []) if not self.is_undefined(f.annotation)]
+ inner_types = (f for f in (field_definition.inner_types or []) if not self.is_undefined(f.annotation))
values = list(map(self.for_field_definition, inner_types))
- return Schema(one_of=sort_schemas_and_references(values))
+ return Schema(one_of=values)
def for_object_type(self, field_definition: FieldDefinition) -> Schema:
"""Create schema for object types (dict, Mapping, list, Sequence etc.) types.
@@ -394,7 +391,7 @@ def for_object_type(self, field_definition: FieldDefinition) -> Schema:
items = list(map(self.for_field_definition, inner_types or ()))
return Schema(
type=OpenAPIType.ARRAY,
- items=Schema(one_of=sort_schemas_and_references(items)) if len(items) > 1 else items[0],
+ items=Schema(one_of=items) if len(items) > 1 else items[0],
)
if field_definition.is_literal:
@@ -613,10 +610,7 @@ def for_collection_constrained_field(self, field_definition: FieldDefinition) ->
item_creator = self.not_generating_examples
if field_definition.inner_types:
items = list(map(item_creator.for_field_definition, field_definition.inner_types))
- if len(items) > 1:
- schema.items = Schema(one_of=sort_schemas_and_references(items))
- else:
- schema.items = items[0]
+ schema.items = Schema(one_of=items) if len(items) > 1 else items[0]
else:
schema.items = item_creator.for_field_definition(
FieldDefinition.from_kwarg(
diff --git a/litestar/_openapi/schema_generation/utils.py b/litestar/_openapi/schema_generation/utils.py
deleted file mode 100644
--- a/litestar/_openapi/schema_generation/utils.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from __future__ import annotations
-
-from litestar.openapi.spec import Reference, Schema
-
-__all__ = ("sort_schemas_and_references",)
-
-
-def sort_schemas_and_references(values: list[Schema | Reference]) -> list[Schema | Reference]:
- """Sort schemas and references alphabetically
-
- Args:
- values: A list of schemas or references.
-
- Returns:
- A sorted list of schemas or references
- """
- return sorted(values, key=lambda value: value.type if isinstance(value, Schema) else value.ref) # type: ignore
| diff --git a/tests/unit/test_contrib/test_pydantic/test_openapi.py b/tests/unit/test_contrib/test_pydantic/test_openapi.py
--- a/tests/unit/test_contrib/test_pydantic/test_openapi.py
+++ b/tests/unit/test_contrib/test_pydantic/test_openapi.py
@@ -163,17 +163,21 @@ def test_create_collection_constrained_field_schema_sub_fields(
field_definition = FieldDefinition.from_annotation(annotation)
schema = SchemaCreator().for_collection_constrained_field(field_definition)
assert schema.type == OpenAPIType.ARRAY
- expected = {
- "items": {"oneOf": [{"type": "integer"}, {"type": "string"}]},
- "maxItems": 10,
- "minItems": 1,
- "type": "array",
- }
+ assert schema.max_items == 10
+ assert schema.min_items == 1
+ assert isinstance(schema.items, Schema)
+ assert schema.items.one_of is not None
+
+ def _get_schema_type(s: Any) -> OpenAPIType:
+ assert isinstance(s, Schema)
+ assert isinstance(s.type, OpenAPIType)
+ return s.type
+
+ # https://github.com/litestar-org/litestar/pull/2570#issuecomment-1788122570
+ assert {_get_schema_type(s) for s in schema.items.one_of} == {OpenAPIType.STRING, OpenAPIType.INTEGER}
if pydantic_fn is conset:
# set should have uniqueItems always
- expected["uniqueItems"] = True
-
- assert schema.to_schema() == expected
+ assert schema.unique_items
@pytest.mark.parametrize("annotation", constrained_string_v1)
diff --git a/tests/unit/test_openapi/test_parameters.py b/tests/unit/test_openapi/test_parameters.py
--- a/tests/unit/test_openapi/test_parameters.py
+++ b/tests/unit/test_openapi/test_parameters.py
@@ -13,7 +13,7 @@
from litestar.enums import ParamType
from litestar.exceptions import ImproperlyConfiguredException
from litestar.openapi import OpenAPIConfig
-from litestar.openapi.spec import Example, OpenAPI
+from litestar.openapi.spec import Example, OpenAPI, Schema
from litestar.openapi.spec.enums import OpenAPIType
from litestar.params import Dependency, Parameter
from litestar.testing import create_test_client
@@ -101,26 +101,26 @@ def test_create_parameters(person_controller: Type[Controller]) -> None:
assert gender.param_in == ParamType.QUERY
assert gender.name == "gender"
assert is_schema_value(gender.schema)
- assert gender.schema.to_schema() == {
- "oneOf": [
- {"type": "null"},
- {
- "items": {
- "type": "string",
- "enum": ["M", "F", "O", "A"],
- "examples": [{"description": "Example value", "value": "F"}],
- },
- "type": "array",
- "examples": [{"description": "Example value", "value": ["A"]}],
- },
- {
- "type": "string",
- "enum": ["M", "F", "O", "A"],
- "examples": [{"description": "Example value", "value": "M"}],
- },
+ assert gender.schema == Schema(
+ one_of=[
+ Schema(type=OpenAPIType.NULL),
+ Schema(
+ type=OpenAPIType.STRING,
+ enum=["M", "F", "O", "A"],
+ examples=[Example(description="Example value", value="M")],
+ ),
+ Schema(
+ type=OpenAPIType.ARRAY,
+ items=Schema(
+ type=OpenAPIType.STRING,
+ enum=["M", "F", "O", "A"],
+ examples=[Example(description="Example value", value="F")],
+ ),
+ examples=[Example(description="Example value", value=["A"])],
+ ),
],
- "examples": [{"value": "M"}, {"value": ["M", "O"]}],
- }
+ examples=[Example(value="M"), Example(value=["M", "O"])],
+ )
assert not gender.required
assert secret_header.param_in == ParamType.HEADER
diff --git a/tests/unit/test_openapi/test_schema.py b/tests/unit/test_openapi/test_schema.py
--- a/tests/unit/test_openapi/test_schema.py
+++ b/tests/unit/test_openapi/test_schema.py
@@ -366,12 +366,12 @@ def test_schema_generation_with_generic_classes_constrained() -> None:
assert properties["constrained"] == Schema(
one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING)]
)
- assert properties["union"] == Schema(one_of=[Schema(type=OpenAPIType.BOOLEAN), Schema(type=OpenAPIType.OBJECT)])
+ assert properties["union"] == Schema(one_of=[Schema(type=OpenAPIType.OBJECT), Schema(type=OpenAPIType.BOOLEAN)])
assert properties["union_constrained"] == Schema(
- one_of=[Schema(type=OpenAPIType.BOOLEAN), Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING)]
+ one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING), Schema(type=OpenAPIType.BOOLEAN)]
)
assert properties["union_bound"] == Schema(
- one_of=[Schema(type=OpenAPIType.BOOLEAN), Schema(type=OpenAPIType.INTEGER)]
+ one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.BOOLEAN)]
)
@@ -404,3 +404,13 @@ def test_schema_generation_with_ellipsis() -> None:
assert isinstance(schema, Schema)
assert isinstance(schema.items, Schema)
assert schema.items.type == OpenAPIType.INTEGER
+
+
+def test_schema_tuple_with_union() -> None:
+ schema = SchemaCreator().for_field_definition(FieldDefinition.from_annotation(Tuple[int, Union[int, str]]))
+ assert isinstance(schema, Schema)
+ assert isinstance(schema.items, Schema)
+ assert schema.items.one_of == [
+ Schema(type=OpenAPIType.INTEGER),
+ Schema(one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING)]),
+ ]
| Bug: OpenAPI schema generation fails for arrays with "oneOf" items
### Description
OpenAPI array schema generation fails when the "items" field contains a "oneOf" schema and more than one element.
### URL to code causing the issue
_No response_
### MCVE
```python
from typing import Tuple
from litestar import get, Litestar
@get("/")
async def route() -> Tuple[str, str | int]:
return "", 1
app = Litestar(route_handlers=[route])
```
### Steps to reproduce
```bash
1. Run the litestar app in debug mode
2. Send a `GET` request to `/schema/openapi.json`
3. See error
```
### Screenshots
_No response_
### Logs
```bash
❯ litestar run --debug
Using Litestar app from app:app
Starting server process ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌──────────────────────────────┬──────────────────────┐
│ Litestar version │ 2.2.1 │
│ Debug mode │ Enabled │
│ Python Debugger on exception │ Disabled │
│ CORS │ Disabled │
│ CSRF │ Disabled │
│ OpenAPI │ Enabled path=/schema │
│ Compression │ Disabled │
└──────────────────────────────┴──────────────────────┘
INFO: Started server process [7290]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
ERROR - 2023-10-30 13:28:42,217 - litestar - config - exception raised on http connection to route /schema/openapi.json
Traceback (most recent call last):
File "**/.venv/lib/python3.10/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "**/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 81, in handle
response = await self._get_response_for_request(
File "**/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 133, in _get_response_for_request
return await self._call_handler_function(
File "**/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 153, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
File "**/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 199, in _get_response_data
data = route_handler.fn.value(**parsed_kwargs)
File "**/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 173, in retrieve_schema_json
body=self._get_schema_as_json(request),
File "**/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 435, in _get_schema_as_json
schema = self.get_schema_from_request(request).to_schema()
File "**/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 85, in get_schema_from_request
return request.app.openapi_schema
File "**/.venv/lib/python3.10/site-packages/litestar/app.py", line 584, in openapi_schema
self.update_openapi_schema()
File "**/.venv/lib/python3.10/site-packages/litestar/app.py", line 842, in update_openapi_schema
path_item, created_operation_ids = create_path_item(
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/path_item.py", line 129, in create_path_item
responses=create_responses(
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/responses.py", line 259, in create_responses
str(route_handler.status_code): create_success_response(route_handler, schema_creator),
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/responses.py", line 106, in create_success_response
result = schema_creator.for_field_definition(FieldDefinition.from_annotation(return_annotation))
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/schema_generation/schema.py", line 283, in for_field_definition
result = self.for_object_type(field_definition)
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/schema_generation/schema.py", line 353, in for_object_type
items=Schema(one_of=sort_schemas_and_references(items)) if len(items) > 1 else items[0],
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/schema_generation/utils.py", line 17, in sort_schemas_and_references
return sorted(values, key=lambda value: value.type if isinstance(value, Schema) else value.ref) # type: ignore
TypeError: '<' not supported between instances of 'NoneType' and 'OpenAPIType'
Traceback (most recent call last):
File "**/.venv/lib/python3.10/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "**/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 81, in handle
response = await self._get_response_for_request(
File "**/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 133, in _get_response_for_request
return await self._call_handler_function(
File "**/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 153, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
File "**/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 199, in _get_response_data
data = route_handler.fn.value(**parsed_kwargs)
File "**/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 173, in retrieve_schema_json
body=self._get_schema_as_json(request),
File "**/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 435, in _get_schema_as_json
schema = self.get_schema_from_request(request).to_schema()
File "**/.venv/lib/python3.10/site-packages/litestar/openapi/controller.py", line 85, in get_schema_from_request
return request.app.openapi_schema
File "**/.venv/lib/python3.10/site-packages/litestar/app.py", line 584, in openapi_schema
self.update_openapi_schema()
File "**/.venv/lib/python3.10/site-packages/litestar/app.py", line 842, in update_openapi_schema
path_item, created_operation_ids = create_path_item(
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/path_item.py", line 129, in create_path_item
responses=create_responses(
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/responses.py", line 259, in create_responses
str(route_handler.status_code): create_success_response(route_handler, schema_creator),
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/responses.py", line 106, in create_success_response
result = schema_creator.for_field_definition(FieldDefinition.from_annotation(return_annotation))
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/schema_generation/schema.py", line 283, in for_field_definition
result = self.for_object_type(field_definition)
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/schema_generation/schema.py", line 353, in for_object_type
items=Schema(one_of=sort_schemas_and_references(items)) if len(items) > 1 else items[0],
File "**/.venv/lib/python3.10/site-packages/litestar/_openapi/schema_generation/utils.py", line 17, in sort_schemas_and_references
return sorted(values, key=lambda value: value.type if isinstance(value, Schema) else value.ref) # type: ignore
TypeError: '<' not supported between instances of 'NoneType' and 'OpenAPIType'
INFO: 127.0.0.1:45006 - "GET /schema/openapi.json HTTP/1.1" 500 Internal Server Error
```
### Litestar Version
2.2.1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2563">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2563/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2563/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Confirmed, thanks for reporting the issue @vfos-github! | 2023-10-31T03:04:24 |
litestar-org/litestar | 2,581 | litestar-org__litestar-2581 | [
"2575"
] | 068905b5a532cff145856e89b84d0a87f7a78bfa | diff --git a/litestar/cli/commands/schema.py b/litestar/cli/commands/schema.py
--- a/litestar/cli/commands/schema.py
+++ b/litestar/cli/commands/schema.py
@@ -1,7 +1,7 @@
-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
@@ -9,6 +9,7 @@
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
@@ -31,6 +32,27 @@ def schema_group() -> None:
"""Manage server-side OpenAPI schemas."""
+def _generate_openapi_schema(app: Litestar, output: Path) -> None:
+ """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",
+ )
+ 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",
@@ -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
| diff --git a/tests/unit/test_cli/test_schema_commands.py b/tests/unit/test_cli/test_schema_commands.py
--- a/tests/unit/test_cli/test_schema_commands.py
+++ b/tests/unit/test_cli/test_schema_commands.py
@@ -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
@@ -19,7 +23,7 @@ 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
@@ -27,15 +31,35 @@ def test_openapi_schema_command(
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)
+
+
[email protected]("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(
| Bug: CLI Schema Export fails
### Description
Exporting the Litestar schema via CLI fails presumably because the `json.dumps` can't serialize certain field types such as `UUID` or `datetime`.
> [!IMPORTANT]
> This is only when `create_examples` is `True`
### URL to code causing the issue
_No response_
### MCVE
```python
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))
```
or
```python
from __future__ import annotations
from datetime import datetime
from uuid import UUID
from litestar import Litestar, get
from litestar.openapi import OpenAPIConfig
from pydantic import BaseModel, Field
class FileSchema(BaseModel):
id: UUID
updated: datetime
@get()
async def something() -> FileSchema | None:
return None
app = Litestar([something], openapi_config=OpenAPIConfig("example", "0.0.1", True))
```
### Steps to reproduce
```bash
1. Create mcve.py
2. `litestar schema openapi --output schema.json`
3. See error
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.x
### Platform
- [ ] Linux
- [ ] Mac
- [ ] Windows
- [X] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2575">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2575/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2575/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-10-31T23:57:27 |
|
litestar-org/litestar | 2,592 | litestar-org__litestar-2592 | [
"2588"
] | 2d63576751dc578e075b26d3f448a6b3bd02b6f6 | diff --git a/litestar/config/response_cache.py b/litestar/config/response_cache.py
--- a/litestar/config/response_cache.py
+++ b/litestar/config/response_cache.py
@@ -28,7 +28,8 @@ class CACHE_FOREVER: # noqa: N801
def default_cache_key_builder(request: Request[Any, Any, Any]) -> str:
- """Given a request object, returns a cache key by combining the path with the sorted query params.
+ """Given a request object, returns a cache key by combining
+ the request method and path with the sorted query params.
Args:
request: request used to generate cache key.
@@ -38,7 +39,7 @@ def default_cache_key_builder(request: Request[Any, Any, Any]) -> str:
"""
query_params: list[tuple[str, Any]] = list(request.query_params.dict().items())
query_params.sort(key=lambda x: x[0])
- return request.url.path + urlencode(query_params, doseq=True)
+ return request.method + request.url.path + urlencode(query_params, doseq=True)
def default_do_cache_predicate(_: HTTPScope, status_code: int) -> bool:
| diff --git a/tests/e2e/test_response_caching.py b/tests/e2e/test_response_caching.py
--- a/tests/e2e/test_response_caching.py
+++ b/tests/e2e/test_response_caching.py
@@ -8,12 +8,12 @@
import msgspec
import pytest
-from litestar import Litestar, Request, Response, get
+from litestar import Litestar, Request, Response, get, post
from litestar.config.compression import CompressionConfig
from litestar.config.response_cache import CACHE_FOREVER, ResponseCacheConfig
from litestar.enums import CompressionEncoding
from litestar.middleware.response_cache import ResponseCacheMiddleware
-from litestar.status_codes import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
+from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
from litestar.stores.base import Store
from litestar.stores.memory import MemoryStore
from litestar.testing import TestClient, create_test_client
@@ -111,9 +111,9 @@ def handler() -> None:
client.get("/cached")
if expected_expiration is None:
- assert memory_store._store["/cached"].expires_at is None
+ assert memory_store._store["GET/cached"].expires_at is None
else:
- assert memory_store._store["/cached"].expires_at
+ assert memory_store._store["GET/cached"].expires_at
def test_cache_forever(memory_store: MemoryStore) -> None:
@@ -126,7 +126,7 @@ async def handler() -> None:
with TestClient(app) as client:
client.get("/cached")
- assert memory_store._store["/cached"].expires_at is None
+ assert memory_store._store["GET/cached"].expires_at is None
@pytest.mark.parametrize("sync_to_thread", (True, False))
@@ -164,7 +164,7 @@ def handler() -> str:
assert mock.call_count == 1
- assert await app.stores.get("some_store").exists("/")
+ assert await app.stores.get("some_store").exists("GET/")
async def test_with_stores(store: Store, mock: MagicMock) -> None:
@@ -243,7 +243,7 @@ def handler_fn() -> str:
with TestClient(app) as client:
client.get("/", headers={"Accept-Encoding": str(CompressionEncoding.GZIP.value)})
- stored_value = await app.response_cache_config.get_store_from_app(app).get("/")
+ stored_value = await app.response_cache_config.get_store_from_app(app).get("GET/")
assert stored_value
stored_messages = msgspec.msgpack.decode(stored_value)
assert gzip.decompress(stored_messages[1]["body"]).decode() == return_value
@@ -286,3 +286,36 @@ def handler() -> str:
client.get("/")
client.get("/")
assert mock.call_count == 2
+
+
+def test_on_multiple_handlers(mock: MagicMock) -> None:
+ @get("/cached-local", cache=10)
+ async def handler() -> str:
+ mock()
+ return "get_response"
+
+ @post("/cached-local", cache=10)
+ async def handler_post() -> str:
+ mock()
+ return "post_response"
+
+ with create_test_client([handler, handler_post], after_request=after_request_handler) as client:
+ # POST request to have this cached
+ first_post_response = client.post("/cached-local")
+ assert first_post_response.status_code == HTTP_201_CREATED
+ assert first_post_response.text == "post_response"
+ assert mock.call_count == 1
+
+ # GET request to verify it doesn't use the cache created by the previous POST request
+ get_response = client.get("/cached-local")
+ assert get_response.status_code == HTTP_200_OK
+ assert get_response.text == "get_response"
+ assert first_post_response.headers["unique-identifier"] != get_response.headers["unique-identifier"]
+ assert mock.call_count == 2
+
+ # POST request to verify it uses the cache generated during the initial POST request
+ second_post_response = client.post("/cached-local")
+ assert second_post_response.status_code == HTTP_201_CREATED
+ assert second_post_response.text == "post_response"
+ assert first_post_response.headers["unique-identifier"] == second_post_response.headers["unique-identifier"]
+ assert mock.call_count == 2
| Bug: Caching route handlers with the same path but different methods leads to overwriting of cache
### Description
Caching route handlers with the same path (`/` in this example) but different methods (`GET` and `POST` in this example) leads to overwriting of cache. The comments above the assert statements illustrate the current vs expected behavior.
This is related to https://github.com/litestar-org/litestar/issues/2573 and is not restricted to just `OPTIONS` and `GET`
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import get, post
from litestar.testing import create_test_client
@get(cache=10)
async def something() -> str:
return "text"
@post(cache=10)
async def something_post() -> str:
return "text_post"
with create_test_client([something, something_post]) as client:
response = client.post("")
assert response.status_code == 201
assert response.text == "text_post"
# these shouldn't pass, but they do
response = client.get("")
assert response.status_code == 201
assert response.text == "text_post"
# these should pass, but they don't
response = client.get("")
assert response.status_code == 200
assert response.text == "text"
```
### Steps to reproduce
```bash
1. Run the code
2. The second set of asserts should fail, the third set of asserts should pass
```
### Screenshots
```bash
""
```
### Logs
_No response_
### Litestar Version
GitHub - main (fd06486e2ad4ed0a41636659fec4f093a09e3dd0) as of creating this issue
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2588">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2588/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2588/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-01T13:03:26 |
|
litestar-org/litestar | 2,596 | litestar-org__litestar-2596 | [
"2594"
] | d61ec81a37211d2dd628d373a0f9cf863cde6351 | diff --git a/litestar/_kwargs/kwargs_model.py b/litestar/_kwargs/kwargs_model.py
--- a/litestar/_kwargs/kwargs_model.py
+++ b/litestar/_kwargs/kwargs_model.py
@@ -34,6 +34,7 @@
from litestar.exceptions import ImproperlyConfiguredException
from litestar.params import BodyKwarg, ParameterKwarg
from litestar.typing import FieldDefinition
+from litestar.utils.helpers import get_exception_group
__all__ = ("KwargsModel",)
@@ -45,6 +46,8 @@
from litestar.dto import AbstractDTO
from litestar.utils.signature import ParsedSignature
+_ExceptionGroup = get_exception_group()
+
class KwargsModel:
"""Model required kwargs for a given RouteHandler and its dependencies.
@@ -390,9 +393,13 @@ async def resolve_dependencies(self, connection: ASGIConnection, kwargs: dict[st
if len(batch) == 1:
await resolve_dependency(next(iter(batch)), connection, kwargs, cleanup_group)
else:
- async with create_task_group() as task_group:
- for dependency in batch:
- task_group.start_soon(resolve_dependency, dependency, connection, kwargs, cleanup_group)
+ try:
+ async with create_task_group() as task_group:
+ for dependency in batch:
+ task_group.start_soon(resolve_dependency, dependency, connection, kwargs, cleanup_group)
+ except _ExceptionGroup as excgroup:
+ raise excgroup.exceptions[0] from excgroup # type: ignore[attr-defined]
+
return cleanup_group
@classmethod
diff --git a/litestar/utils/helpers.py b/litestar/utils/helpers.py
--- a/litestar/utils/helpers.py
+++ b/litestar/utils/helpers.py
@@ -91,3 +91,13 @@ def unique_name_for_scope(base_name: str, scope: Container[str]) -> str:
if (unique_name := f"{base_name}_{i}") not in scope:
return unique_name
i += 1
+
+
+def get_exception_group() -> type[BaseException]:
+ """Get the exception group class with version compatibility."""
+ try:
+ return cast("type[BaseException]", ExceptionGroup) # type:ignore[name-defined]
+ except NameError:
+ from exceptiongroup import ExceptionGroup as _ExceptionGroup
+
+ return cast("type[BaseException]", _ExceptionGroup)
| diff --git a/tests/helpers.py b/tests/helpers.py
--- a/tests/helpers.py
+++ b/tests/helpers.py
@@ -51,13 +51,3 @@ def maybe_async_cm(obj: ContextManager[T] | AsyncContextManager[T]) -> AsyncCont
if isinstance(obj, AbstractContextManager):
return cast(AsyncContextManager[T], _AsyncContextManagerWrapper(obj))
return obj
-
-
-def get_exception_group() -> type[BaseException]:
- """Get the exception group class with version compatibility."""
- try:
- return cast("type[BaseException]", ExceptionGroup) # type:ignore[name-defined]
- except NameError:
- from exceptiongroup import ExceptionGroup as _ExceptionGroup
-
- return _ExceptionGroup
diff --git a/tests/unit/test_asgi_router.py b/tests/unit/test_asgi_router.py
--- a/tests/unit/test_asgi_router.py
+++ b/tests/unit/test_asgi_router.py
@@ -11,7 +11,7 @@
from litestar._asgi.asgi_router import ASGIRouter
from litestar.exceptions import ImproperlyConfiguredException
from litestar.testing import TestClient, create_test_client
-from tests.helpers import get_exception_group
+from litestar.utils.helpers import get_exception_group
if TYPE_CHECKING:
from contextlib import AbstractAsyncContextManager
diff --git a/tests/unit/test_kwargs/test_dependency_batches.py b/tests/unit/test_kwargs/test_dependency_batches.py
--- a/tests/unit/test_kwargs/test_dependency_batches.py
+++ b/tests/unit/test_kwargs/test_dependency_batches.py
@@ -4,6 +4,10 @@
from litestar._kwargs.dependencies import Dependency, create_dependency_batches
from litestar.di import Provide
+from litestar.exceptions import HTTPException, ValidationException
+from litestar.handlers import get
+from litestar.status_codes import HTTP_400_BAD_REQUEST, HTTP_422_UNPROCESSABLE_ENTITY, HTTP_500_INTERNAL_SERVER_ERROR
+from litestar.testing import create_test_client
async def dummy() -> None:
@@ -56,3 +60,43 @@ async def dummy() -> None:
def test_dependency_batches(dependency_tree: Set[Dependency], expected_batches: List[Set[Dependency]]) -> None:
calculated_batches = create_dependency_batches(dependency_tree)
assert calculated_batches == expected_batches
+
+
[email protected](
+ "exception,status_code,text",
+ [
+ (ValueError("value_error"), HTTP_500_INTERNAL_SERVER_ERROR, "Exception Group Traceback"),
+ (
+ HTTPException(status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail="http_exception"),
+ HTTP_422_UNPROCESSABLE_ENTITY,
+ '{"status_code":422,"detail":"http_exception"}',
+ ),
+ (
+ ValidationException("validation_exception"),
+ HTTP_400_BAD_REQUEST,
+ '{"status_code":400,"detail":"validation_exception"}',
+ ),
+ ],
+)
+def test_dependency_batch_with_exception(exception: Exception, status_code: int, text: str) -> None:
+ def a() -> None:
+ raise exception
+
+ def c(a: None, b: None) -> None:
+ pass
+
+ @get(path="/")
+ def handler(c: None) -> None:
+ pass
+
+ with create_test_client(
+ route_handlers=handler,
+ dependencies={
+ "a": Provide(a),
+ "b": Provide(dummy),
+ "c": Provide(c),
+ },
+ ) as client:
+ response = client.get("/")
+ assert response.status_code == status_code
+ assert text in response.text
diff --git a/tests/unit/test_testing/test_test_client.py b/tests/unit/test_testing/test_test_client.py
--- a/tests/unit/test_testing/test_test_client.py
+++ b/tests/unit/test_testing/test_test_client.py
@@ -25,7 +25,8 @@
from litestar import Litestar, Request, get, post
from litestar.stores.base import Store
from litestar.testing import TestClient
-from tests.helpers import get_exception_group, maybe_async, maybe_async_cm
+from litestar.utils.helpers import get_exception_group
+from tests.helpers import maybe_async, maybe_async_cm
_ExceptionGroup = get_exception_group()
| Bug: HTTPExceptions are not being handled correctly when dependency processing is offloaded to a TaskGroup
### Description
I have an application which uses heavily nested dependencies. Many of those dependencies have validation logic which throws HTTPExceptions so that users can update their requests and try again.
I am upgrading this from Starlite v1 and have hit an issue with how dependencies are handled when nesting occurs. It appears nested dependencies are processed concurrently within an `anyio.TaskGroup` instance. If any exception occurs in [This instance of create_task_group](https://github.com/litestar-org/litestar/blob/v2.2.1/litestar/_kwargs/kwargs_model.py#L393), they all result in a `GroupException`. Because of this, any HTTPExceptions thrown from inside the dependency logic gets yeeted into the void and the requester never sees it.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar
from litestar.di import Provide
from litestar.handlers import get
from litestar.exceptions import HTTPException
def get_dependency_child1() -> str:
raise HTTPException(detail="No sir, I don't like it.", status_code=400)
def get_dependency_child2() -> str:
return "OK"
def get_dependency_parent(
dependency_child1: str,
dependency_child2: str,
) -> str:
return dependency_child1 + dependency_child2
@get(
path="/",
dependencies={
"dependency_child1": Provide(get_dependency_child1, sync_to_thread=False),
"dependency_child2": Provide(get_dependency_child2, sync_to_thread=False),
"dependency_parent": Provide(get_dependency_parent, sync_to_thread=False),
},
)
def route(dependency_parent: str) -> str:
return dependency_parent
app = Litestar(route_handlers=[route], debug=True)
```
### Steps to reproduce
_No response_
### Screenshots
```bash
""
```
### Logs
```bash
ERROR - 2023-11-01 15:58:04,508 - litestar - config - exception raised on http connection to route /
+ Exception Group Traceback (most recent call last):
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
| await self.app(scope, receive, send)
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 81, in handle
| response = await self._get_response_for_request(
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 133, in _get_response_for_request
| return await self._call_handler_function(
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 153, in _call_handler_function
| response_data, cleanup_group = await self._get_response_data(
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 185, in _get_response_data
| cleanup_group = await parameter_model.resolve_dependencies(request, kwargs)
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/_kwargs/kwargs_model.py", line 393, in resolve_dependencies
| async with create_task_group() as task_group:
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 664, in __aexit__
| raise BaseExceptionGroup(
| exceptiongroup.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/_kwargs/dependencies.py", line 66, in resolve_dependency
| value = await dependency.provide(**dependency_kwargs)
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/di.py", line 84, in __call__
| value = self.dependency.value(**kwargs)
| File "/tmp/litestarTest/di_test_app.py", line 8, in get_dependency_child1
| raise HTTPException(detail="No sir, I don't like it.", status_code=400)
| litestar.exceptions.http_exceptions.HTTPException: 400: No sir, I don't like it.
+------------------------------------
+ Exception Group Traceback (most recent call last):
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
| await self.app(scope, receive, send)
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 81, in handle
| response = await self._get_response_for_request(
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 133, in _get_response_for_request
| return await self._call_handler_function(
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 153, in _call_handler_function
| response_data, cleanup_group = await self._get_response_data(
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/routes/http.py", line 185, in _get_response_data
| cleanup_group = await parameter_model.resolve_dependencies(request, kwargs)
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/_kwargs/kwargs_model.py", line 393, in resolve_dependencies
| async with create_task_group() as task_group:
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 664, in __aexit__
| raise BaseExceptionGroup(
| exceptiongroup.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/_kwargs/dependencies.py", line 66, in resolve_dependency
| value = await dependency.provide(**dependency_kwargs)
| File "/tmp/litestarTest/.venv/lib/python3.10/site-packages/litestar/di.py", line 84, in __call__
| value = self.dependency.value(**kwargs)
| File "/tmp/litestarTest/di_test_app.py", line 8, in get_dependency_child1
| raise HTTPException(detail="No sir, I don't like it.", status_code=400)
| litestar.exceptions.http_exceptions.HTTPException: 400: No sir, I don't like it.
+------------------------------------
INFO: 127.0.0.1:54512 - "GET / HTTP/1.1" 500 Internal Server Error
```
### Litestar Version
2.2.1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2594">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2594/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2594/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| > yeeted into the void
😂
Thanks for reporting!
> > yeeted into the void
>
> 😂
>
> Thanks for reporting!
Yeah, we should avoid such void-yeeting.
Probably want to make sure things get properly re-raised.
| 2023-11-01T21:11:28 |
litestar-org/litestar | 2,602 | litestar-org__litestar-2602 | [
"2569"
] | 2bc85e34f438e0b870a49c4a8b012a9b732a0fdb | diff --git a/docs/examples/contrib/sqlalchemy/plugins/tutorial/full_app_with_plugin.py b/docs/examples/contrib/sqlalchemy/plugins/tutorial/full_app_with_plugin.py
--- a/docs/examples/contrib/sqlalchemy/plugins/tutorial/full_app_with_plugin.py
+++ b/docs/examples/contrib/sqlalchemy/plugins/tutorial/full_app_with_plugin.py
@@ -1,5 +1,6 @@
from typing import AsyncGenerator, List, Optional
+from advanced_alchemy.extensions.litestar.plugins.init.config.asyncio import autocommit_before_send_handler
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError, NoResultFound
from sqlalchemy.ext.asyncio import AsyncSession
@@ -71,7 +72,10 @@ async def update_item(item_title: str, data: TodoItem, transaction: AsyncSession
db_config = SQLAlchemyAsyncConfig(
- connection_string="sqlite+aiosqlite:///todo.sqlite", metadata=Base.metadata, create_all=True
+ connection_string="sqlite+aiosqlite:///todo.sqlite",
+ metadata=Base.metadata,
+ create_all=True,
+ before_send_handler=autocommit_before_send_handler,
)
app = Litestar(
| docs: update TODO app w/ sqlalchemy tutorial to use autocommitting before send handler.
> @AgarwalPragy You are correct. By default, the plugin session handler does not automatically commit on a successful response. You can easily change it by using the following `before_send` handler:
>
> ```python
> from advanced_alchemy.extensions.litestar.plugins.init.config.asyncio import autocommit_before_send_handler
>
> db_url = "sqlite+aiosqlite:///:memory:"
> app = Litestar(
> route_handlers=[hello],
> plugins=[
> SQLAlchemyPlugin(
> config=SQLAlchemyAsyncConfig(
> connection_string=db_url,
> session_dependency_key="transaction",
> create_all=True,
> alembic_config=AlembicAsyncConfig(target_metadata=orm_registry.metadata),
> before_send_handler=autocommit_before_send_handler,
> ),
> ),
> ],
> )
> ```
I'd say this is a documentation bug on our side now.
We should update https://docs.litestar.dev/latest/tutorials/sqlalchemy/3-init-plugin.html to do the same as this (it was written before the autocommit handler was a part of the plugin, IIRC).
_Originally posted by @peterschutt in https://github.com/litestar-org/litestar/issues/2556#issuecomment-1786287414_
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2569">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2569/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2569/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-02T13:57:14 |
||
litestar-org/litestar | 2,648 | litestar-org__litestar-2648 | [
"2635"
] | 0dd83fe07f8316914a6c8459c6430603f602381e | diff --git a/litestar/contrib/pydantic/utils.py b/litestar/contrib/pydantic/utils.py
--- a/litestar/contrib/pydantic/utils.py
+++ b/litestar/contrib/pydantic/utils.py
@@ -162,4 +162,4 @@ def is_pydantic_2_model(
def is_pydantic_undefined(value: Any) -> bool:
- return value in PYDANTIC_UNDEFINED_SENTINELS
+ return any(v is value for v in PYDANTIC_UNDEFINED_SENTINELS)
| diff --git a/tests/unit/test_contrib/test_pydantic/test_openapi.py b/tests/unit/test_contrib/test_pydantic/test_openapi.py
--- a/tests/unit/test_contrib/test_pydantic/test_openapi.py
+++ b/tests/unit/test_contrib/test_pydantic/test_openapi.py
@@ -547,3 +547,35 @@ class Foo(BaseModel):
)
schema = schemas["Foo"]
assert schema.properties and "foo" in schema.properties
+
+
+def test_create_schema_for_pydantic_model_with_unhashable_literal_default(
+ create_module: "Callable[[str], ModuleType]",
+) -> None:
+ """Test that a model with unhashable literal defaults is correctly handled."""
+ module = create_module(
+ """
+from pydantic import BaseModel, Field
+
+class Model(BaseModel):
+ id: int
+ dict_default: dict = {}
+ dict_default_in_field: dict = Field(default={})
+ dict_default_in_factory: dict = Field(default_factory=dict)
+ list_default: list = []
+ list_default_in_field: list = Field(default=[])
+ list_default_in_factory: list = Field(default_factory=list)
+"""
+ )
+ schemas: Dict[str, Schema] = {}
+ SchemaCreator(schemas=schemas, plugins=[PydanticSchemaPlugin()]).for_field_definition(
+ FieldDefinition.from_annotation(module.Model)
+ )
+ schema = schemas["Model"]
+ assert schema.properties
+ assert "dict_default" in schema.properties
+ assert "dict_default_in_field" in schema.properties
+ assert "dict_default_in_factory" in schema.properties
+ assert "list_default" in schema.properties
+ assert "list_default_in_field" in schema.properties
+ assert "list_default_in_factory" in schema.properties
| Bug: Schema generation partially broken since litestar version 2.3.0
### Description
2.2.1 is my last working version of litestar.
Before:
<img width="467" alt="image" src="https://github.com/litestar-org/litestar/assets/85191795/dc9594b1-4b09-4607-9061-dcd65bf0a09f">
After:
I first get this `internal server error` when i first try to go to my Swagger URL
<img width="436" alt="image" src="https://github.com/litestar-org/litestar/assets/85191795/90112884-907e-4ee0-a14c-a92c338ef761">
And then when i refresh once more, it goes to my swagger page, but only 2/3 of it.
<img width="217" alt="image" src="https://github.com/litestar-org/litestar/assets/85191795/74f16208-e80a-46de-b580-3dd566e0f14b">
With no changes in my code, the problems just start at version 2.3.0 and beyond. Just wanted to bring attention to this, as I will now be sticking to litestar 2.2.1 until this is resolved.
### URL to code causing the issue
_No response_
### MCVE
```python
How my app code looks like when passing in my controllers:
app = Litestar(
route_handlers=[
read_root,
refresh_templates,
LinuxPXEController,
WindowsPXEController,
ESXiPXEController
],
...
```
### Steps to reproduce
_No response_
### Screenshots
```bash
""
```
### Logs
_No response_
### Litestar Version
2.3.0
### Platform
- [X] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2635">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2635/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2635/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| @euthuppan could you please enable `debug` mode on the application and let us know if that gives you additional output?
```python
app = Litestar(
debug=True,
route_handlers=[
read_root,
refresh_templates,
LinuxPXEController,
WindowsPXEController,
ESXiPXEController
],
```
I've also started running into this issue with v2.3, find a screenshot of the error in debug mode below:

This also happens for ReDoc and Elements, so it's consistent across all OpenAPI renderers.
@timwedde @euthuppan could one of you provide an MCVE that reproduces this?
Also, which Pydantic version are you using?
Took me a little while to track this down, but here you go:
```py
# pip install pydantic==2.4.2 litestar==2.3.2
from litestar import Litestar, get
from pydantic import BaseModel, Field
class Model(BaseModel):
id: int
fail: dict = {} # fails
# fail: dict = Field(default={}) # fails
# fail: dict = Field(default_factory=dict) # works
@get("/")
async def mcve() -> Model:
return Model(id=1)
app = Litestar(
debug=True,
route_handlers=[mcve],
)
```
Seems that this may now be semi-intended behavior since the `default_factory` approach is likely the objectively correct one anyway, but it does somewhat smell like a breaking change in a minor version update. For reference, this does work properly on Litestar versions before 2.3.x, with the same pydantic version.
So things seems to have broken on 46ea14bf045f1804e0a1623407ec525179acbfb4 (#2553) for the MCVE above (`fail: dict = {}`). Bisected all the way from a7fe0f306e541253351fb1ad373bf6ff590eef9a (v2.2.0) to 0c6a57f8454838572aa6eaffd89123c778d638df (current main)
So change this https://github.com/litestar-org/litestar/blob/0c6a57f8454838572aa6eaffd89123c778d638df/litestar/contrib/pydantic/utils.py#L164-L165
```py
def is_pydantic_undefined(value: Any) -> bool:
return any(v is value for v in PYDANTIC_UNDEFINED_SENTINELS)
```
so that it is the same as this (avoid the hash)?
https://github.com/litestar-org/litestar/blob/0c6a57f8454838572aa6eaffd89123c778d638df/litestar/utils/predicates.py#L314-L323
Thanks for the effort @Alc-Alc! The proposed change looks good to me, do you want to implement it (and add a test case to reproduce)?
Also thanks @timwedde for the great mcve! This is really helpful! :) | 2023-11-11T04:14:55 |
litestar-org/litestar | 2,673 | litestar-org__litestar-2673 | [
"2672"
] | fe3c25e3778cab1254f7005bb47558531f369283 | diff --git a/litestar/contrib/pydantic/utils.py b/litestar/contrib/pydantic/utils.py
--- a/litestar/contrib/pydantic/utils.py
+++ b/litestar/contrib/pydantic/utils.py
@@ -158,7 +158,7 @@ def pydantic_get_unwrapped_annotation_and_type_hints(annotation: Any) -> tuple[A
def is_pydantic_2_model(
obj: type[pydantic_v1.BaseModel | pydantic_v2.BaseModel], # pyright: ignore
) -> TypeGuard[pydantic_v2.BaseModel]: # pyright: ignore
- return issubclass(obj, pydantic_v2.BaseModel) # pyright: ignore
+ return pydantic_v2 is not Empty and issubclass(obj, pydantic_v2.BaseModel) # type: ignore[comparison-overlap]
def is_pydantic_undefined(value: Any) -> bool:
| Bug: OpenAPI schema generation fails with pydantic < 2.0.0
### Description
When pydantic 1.* is installed, interactive API docs cannot be loaded.
It seems the problem is that a helper function is trying to access a `pydantic_v2` attribute without checking if it was imported correctly, the stack trace below provides more info.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, post
from litestar.testing import TestClient
from pydantic import BaseModel
class Order(BaseModel):
code: str
@post()
async def test_handler(data: Order) -> Order:
return data
app = Litestar(route_handlers=[test_handler], debug=True)
def test() -> None:
with TestClient(app=app) as client:
response = client.get(
"/schema/swagger",
)
assert response.is_success
if __name__ == "__main__":
test()
```
### Steps to reproduce
```bash
1. Install Litestar with Pydantic v1
2. Start up a server
3. Perform a request to /schema/swagger
```
### Screenshots
```bash
""
```
### Logs
```bash
Traceback (most recent call last):
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/routes/http.py", line 81, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/routes/http.py", line 133, in _get_response_for_request
return await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/routes/http.py", line 153, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/routes/http.py", line 199, in _get_response_data
data = route_handler.fn(**parsed_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/openapi/controller.py", line 231, in swagger_ui
return ASGIResponse(body=self.render_swagger_ui(request), media_type=MediaType.HTML)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/openapi/controller.py", line 391, in render_swagger_ui
schema = self.get_schema_from_request(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/openapi/controller.py", line 96, in get_schema_from_request
return request.app.openapi_schema
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/app.py", line 586, in openapi_schema
self.update_openapi_schema()
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/app.py", line 836, in update_openapi_schema
path_item, created_operation_ids = create_path_item(
^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/_openapi/path_item.py", line 109, in create_path_item
request_body = create_request_body(
^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/_openapi/request_body.py", line 32, in create_request_body
schema = schema_creator.for_field_definition(field_definition)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/_openapi/schema_generation/schema.py", line 301, in for_field_definition
result = self.for_plugin(field_definition, plugin_for_annotation)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/_openapi/schema_generation/schema.py", line 480, in for_plugin
schema = plugin.to_openapi_schema(field_definition=field_definition, schema_creator=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/contrib/pydantic/pydantic_schema_plugin.py", line 230, in to_openapi_schema
return self.for_pydantic_model(field_definition=field_definition, schema_creator=schema_creator)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/contrib/pydantic/pydantic_schema_plugin.py", line 250, in for_pydantic_model
if is_pydantic_2_model(annotation):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/thunder/work/litestar_mvce/litestar_venv/lib/python3.11/site-packages/litestar/contrib/pydantic/utils.py", line 161, in is_pydantic_2_model
return issubclass(obj, pydantic_v2.BaseModel) # pyright: ignore
^^^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Empty' has no attribute 'BaseModel'
```
### Litestar Version
2.3.2
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2672">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2672/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2672/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-14T10:10:37 |
||
litestar-org/litestar | 2,681 | litestar-org__litestar-2681 | [
"2680"
] | e86df8f5cfe84b642694929afa41308589b19619 | diff --git a/litestar/plugins/base.py b/litestar/plugins/base.py
--- a/litestar/plugins/base.py
+++ b/litestar/plugins/base.py
@@ -33,6 +33,7 @@ def on_app_init(self, app_config: AppConfig) -> AppConfig:
Examples:
.. code-block:: python
+
from litestar import Litestar, get
from litestar.di import Provide
from litestar.plugins import InitPluginProtocol
| Docs: Build errors
### Summary
```
/home/peter/PycharmProjects/litestar/litestar/plugins/base.py:docstring of litestar.plugins.base.InitPluginProtocol.on_app_init:5: ERROR: Error in "code-block" directive:
maximum 1 argument(s) allowed, 14 supplied.
.. code-block:: python
from litestar import Litestar, get
from litestar.di import Provide
from litestar.plugins import InitPluginProtocol
def get_name() -> str:
return "world"
@get("/my-path")
def my_route_handler(name: str) -> dict[str, str]:
return {"hello": name}
class MyPlugin(InitPluginProtocol):
def on_app_init(self, app_config: AppConfig) -> AppConfig:
app_config.dependencies["name"] = Provide(get_name)
app_config.route_handlers.append(my_route_handler)
return app_config
app = Litestar(plugins=[MyPlugin()])
```
And
```
/home/peter/PycharmProjects/litestar/docs/topics/deployment/manually-with-asgi-server.rst:2: WARNING: Title underline too short.
Manually with ASGI server
==========
```
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2680">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2680/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2680/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-16T04:46:03 |
||
litestar-org/litestar | 2,716 | litestar-org__litestar-2716 | [
"2714"
] | 115e97cff194598a66ab1e18fa389897ce3148b6 | diff --git a/litestar/_signature/model.py b/litestar/_signature/model.py
--- a/litestar/_signature/model.py
+++ b/litestar/_signature/model.py
@@ -198,7 +198,7 @@ def parse_values_from_connection_kwargs(cls, connection: ASGIConnection, **kwarg
for field_name, exc in cls._collect_errors(deserializer=deserializer, **kwargs): # type: ignore[assignment]
match = ERR_RE.search(str(exc))
keys = [field_name, str(match.group(1))] if match else [field_name]
- message = cls._build_error_message(keys=keys, exc_msg=str(e), connection=connection)
+ message = cls._build_error_message(keys=keys, exc_msg=str(exc), connection=connection)
messages.append(message)
raise cls._create_exception(messages=messages, connection=connection) from e
| diff --git a/tests/unit/test_signature/test_validation.py b/tests/unit/test_signature/test_validation.py
--- a/tests/unit/test_signature/test_validation.py
+++ b/tests/unit/test_signature/test_validation.py
@@ -3,11 +3,12 @@
import pytest
from attr import define
-from typing_extensions import TypedDict
+from typing_extensions import Annotated, TypedDict
from litestar import get, post
from litestar._signature import SignatureModel
from litestar.di import Provide
+from litestar.enums import ParamType
from litestar.exceptions import ImproperlyConfiguredException, ValidationException
from litestar.params import Dependency, Parameter
from litestar.status_codes import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
@@ -225,7 +226,7 @@ def test(
assert data["extra"] == [
{"message": "Expected `int`, got `str`", "key": "child.val", "source": "body"},
{"message": "Expected `int`, got `str`", "key": "int_param", "source": "query"},
- {"message": "Expected `int`, got `str`", "key": "length_param", "source": "query"},
+ {"message": "Expected `str` of length >= 2", "key": "length_param", "source": "query"},
{"message": "Expected `int`, got `str`", "key": "int_header", "source": "header"},
{"message": "Expected `int`, got `str`", "key": "int_cookie", "source": "cookie"},
]
@@ -270,7 +271,27 @@ def test(
assert data["extra"] == [
{"message": "Expected `int`, got `str`", "key": "child.val", "source": "body"},
{"message": "Expected `int`, got `str`", "key": "int_param", "source": "query"},
- {"message": "Expected `int`, got `str`", "key": "length_param", "source": "query"},
+ {"message": "Expected `str` of length >= 2", "key": "length_param", "source": "query"},
{"message": "Expected `int`, got `str`", "key": "int_header", "source": "header"},
{"message": "Expected `int`, got `str`", "key": "int_cookie", "source": "cookie"},
]
+
+
+def test_parse_values_from_connection_kwargs_with_multiple_errors() -> None:
+ def fn(a: Annotated[int, Parameter(gt=5)], b: Annotated[int, Parameter(lt=5)]) -> None:
+ pass
+
+ model = SignatureModel.create(
+ dependency_name_set=set(),
+ fn=fn,
+ data_dto=None,
+ parsed_signature=ParsedSignature.from_fn(fn, {}),
+ type_decoders=[],
+ )
+ with pytest.raises(ValidationException) as exc:
+ model.parse_values_from_connection_kwargs(connection=RequestFactory().get(), a=0, b=9)
+
+ assert exc.value.extra == [
+ {"message": "Expected `int` >= 6", "key": "a", "source": ParamType.QUERY},
+ {"message": "Expected `int` <= 4", "key": "b", "source": ParamType.QUERY},
+ ]
| Bug: incorrect message in ValidationException when multiple errors occured
### Description
When there is more than one validation issue detected, the message describing the problem for each parameter is the same.
In my case, I have rules as `a > 5` and `b < 5` but I get:
```json
{
"status_code": 400,
"detail": "Validation failed for GET http://127.0.0.1:8000/?a=0&b=9",
"extra": [
{
"message": "Expected `int` <= 4",
"key": "a",
"source": "query"
},
{
"message": "Expected `int` <= 4",
"key": "b",
"source": "query"
}
]
}
```
Single error (if only one parameter is invalid) is correctly displaying the message.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, get, Response
from litestar.params import Parameter
from typing import Annotated
@get("/")
async def default(
a: Annotated[int, Parameter(gt=5)],
b: Annotated[int, Parameter(lt=5)],
) -> Response:
return Response(content=f'{a} {b}\n')
app = Litestar(route_handlers=[default])
```
### Steps to reproduce
```bash
Run the app and access the URL `http://127.0.0.1:8000/?a=0&b=9`.
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
Litestar 2.3.2 on Python 3.11.2
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2714">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2714/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2714/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-20T00:07:12 |
|
litestar-org/litestar | 2,736 | litestar-org__litestar-2736 | [
"2727"
] | 27875eb58eb24a1430c529eca26278028216ab98 | diff --git a/litestar/connection/base.py b/litestar/connection/base.py
--- a/litestar/connection/base.py
+++ b/litestar/connection/base.py
@@ -81,15 +81,10 @@ def __init__(self, scope: Scope, receive: Receive = empty_receive, send: Send =
self.scope = scope
self.receive = receive
self.send = send
- self._base_url = cast("URL | EmptyType", get_litestar_scope_state(scope, SCOPE_STATE_BASE_URL_KEY, Empty))
- self._url = cast("URL | EmptyType", get_litestar_scope_state(scope, SCOPE_STATE_URL_KEY, Empty))
- self._parsed_query = cast(
- "tuple[tuple[str, str], ...] | EmptyType",
- get_litestar_scope_state(scope, SCOPE_STATE_PARSED_QUERY_KEY, Empty),
- )
- self._cookies = cast(
- "dict[str, str] | EmptyType", get_litestar_scope_state(scope, SCOPE_STATE_COOKIES_KEY, Empty)
- )
+ self._base_url: URL | EmptyType = Empty
+ self._url: URL | EmptyType = Empty
+ self._parsed_query: tuple[tuple[str, str], ...] | EmptyType = Empty
+ self._cookies: dict[str, str] | EmptyType = Empty
@property
def app(self) -> Litestar:
@@ -126,8 +121,11 @@ def url(self) -> URL:
A URL instance constructed from the request's scope.
"""
if self._url is Empty:
- self._url = URL.from_scope(self.scope)
- set_litestar_scope_state(self.scope, SCOPE_STATE_URL_KEY, self._url)
+ if url := get_litestar_scope_state(self.scope, SCOPE_STATE_URL_KEY):
+ self._url = cast("URL", url)
+ else:
+ self._url = URL.from_scope(self.scope)
+ set_litestar_scope_state(self.scope, SCOPE_STATE_URL_KEY, self._url)
return self._url
@@ -140,17 +138,20 @@ def base_url(self) -> URL:
(host + domain + prefix) of the request.
"""
if self._base_url is Empty:
- scope = cast(
- "Scope",
- {
- **self.scope,
- "path": "/",
- "query_string": b"",
- "root_path": self.scope.get("app_root_path") or self.scope.get("root_path", ""),
- },
- )
- self._base_url = URL.from_scope(scope)
- set_litestar_scope_state(self.scope, SCOPE_STATE_BASE_URL_KEY, self._base_url)
+ if base_url := get_litestar_scope_state(self.scope, SCOPE_STATE_BASE_URL_KEY):
+ self._base_url = cast("URL", base_url)
+ else:
+ scope = cast(
+ "Scope",
+ {
+ **self.scope,
+ "path": "/",
+ "query_string": b"",
+ "root_path": self.scope.get("app_root_path") or self.scope.get("root_path", ""),
+ },
+ )
+ self._base_url = URL.from_scope(scope)
+ set_litestar_scope_state(self.scope, SCOPE_STATE_BASE_URL_KEY, self._base_url)
return self._base_url
@property
@@ -170,8 +171,11 @@ def query_params(self) -> MultiDict[Any]:
A normalized dict of query parameters. Multiple values for the same key are returned as a list.
"""
if self._parsed_query is Empty:
- self._parsed_query = parse_query_string(self.scope.get("query_string", b""))
- set_litestar_scope_state(self.scope, SCOPE_STATE_PARSED_QUERY_KEY, self._parsed_query)
+ if (parsed_query := get_litestar_scope_state(self.scope, SCOPE_STATE_PARSED_QUERY_KEY, Empty)) is not Empty:
+ self._parsed_query = cast("tuple[tuple[str, str], ...]", parsed_query)
+ else:
+ self._parsed_query = parse_query_string(self.scope.get("query_string", b""))
+ set_litestar_scope_state(self.scope, SCOPE_STATE_PARSED_QUERY_KEY, self._parsed_query)
return MultiDict(self._parsed_query)
@property
@@ -191,8 +195,13 @@ def cookies(self) -> dict[str, str]:
Returns any cookies stored in the header as a parsed dictionary.
"""
if self._cookies is Empty:
- self._cookies = parse_cookie_string(cookie_header) if (cookie_header := self.headers.get("cookie")) else {}
- set_litestar_scope_state(self.scope, SCOPE_STATE_COOKIES_KEY, self._cookies)
+ if (cookies := get_litestar_scope_state(self.scope, SCOPE_STATE_COOKIES_KEY, Empty)) is not Empty:
+ self._cookies = cast("dict[str, str]", cookies)
+ else:
+ self._cookies = (
+ parse_cookie_string(cookie_header) if (cookie_header := self.headers.get("cookie")) else {}
+ )
+ set_litestar_scope_state(self.scope, SCOPE_STATE_COOKIES_KEY, self._cookies)
return self._cookies
diff --git a/litestar/connection/request.py b/litestar/connection/request.py
--- a/litestar/connection/request.py
+++ b/litestar/connection/request.py
@@ -34,6 +34,7 @@
if TYPE_CHECKING:
from litestar.handlers.http_handlers import HTTPRouteHandler # noqa: F401
from litestar.types.asgi_types import HTTPScope, Method, Receive, Scope, Send
+ from litestar.types.empty import EmptyType
SERVER_PUSH_HEADERS = {
@@ -67,12 +68,12 @@ def __init__(self, scope: Scope, receive: Receive = empty_receive, send: Send =
"""
super().__init__(scope, receive, send)
self.is_connected: bool = True
- self._body = get_litestar_scope_state(scope, SCOPE_STATE_BODY_KEY, Empty)
- self._form = get_litestar_scope_state(scope, SCOPE_STATE_FORM_KEY, Empty)
- self._json = get_litestar_scope_state(scope, SCOPE_STATE_JSON_KEY, Empty)
- self._msgpack = get_litestar_scope_state(scope, SCOPE_STATE_MSGPACK_KEY, Empty)
- self._content_type = get_litestar_scope_state(scope, SCOPE_STATE_CONTENT_TYPE_KEY, Empty)
- self._accept = get_litestar_scope_state(scope, SCOPE_STATE_ACCEPT_KEY, Empty)
+ self._body: bytes | EmptyType = Empty
+ self._form: dict[str, str | list[str]] | EmptyType = Empty
+ self._json: Any = Empty
+ self._msgpack: Any = Empty
+ self._content_type: tuple[str, dict[str, str]] | EmptyType = Empty
+ self._accept: Accept | EmptyType = Empty
@property
def method(self) -> Method:
@@ -91,9 +92,12 @@ def content_type(self) -> tuple[str, dict[str, str]]:
A tuple with the parsed value and a dictionary containing any options send in it.
"""
if self._content_type is Empty:
- self._content_type = parse_content_header(self.headers.get("Content-Type", ""))
- set_litestar_scope_state(self.scope, SCOPE_STATE_CONTENT_TYPE_KEY, self._content_type)
- return cast("tuple[str, dict[str, str]]", self._content_type)
+ if (content_type := get_litestar_scope_state(self.scope, SCOPE_STATE_CONTENT_TYPE_KEY, Empty)) is not Empty:
+ self._content_type = cast("tuple[str, dict[str, str]]", content_type)
+ else:
+ self._content_type = parse_content_header(self.headers.get("Content-Type", ""))
+ set_litestar_scope_state(self.scope, SCOPE_STATE_CONTENT_TYPE_KEY, self._content_type)
+ return self._content_type
@property
def accept(self) -> Accept:
@@ -103,9 +107,12 @@ def accept(self) -> Accept:
An :class:`Accept <litestar.datastructures.headers.Accept>` instance, representing the list of acceptable media types.
"""
if self._accept is Empty:
- self._accept = Accept(self.headers.get("Accept", "*/*"))
- set_litestar_scope_state(self.scope, SCOPE_STATE_ACCEPT_KEY, self._accept)
- return cast("Accept", self._accept)
+ if accept := get_litestar_scope_state(self.scope, SCOPE_STATE_ACCEPT_KEY):
+ self._accept = cast("Accept", accept)
+ else:
+ self._accept = Accept(self.headers.get("Accept", "*/*"))
+ set_litestar_scope_state(self.scope, SCOPE_STATE_ACCEPT_KEY, self._accept)
+ return self._accept
async def json(self) -> Any:
"""Retrieve the json request body from the request.
@@ -114,9 +121,12 @@ async def json(self) -> Any:
An arbitrary value
"""
if self._json is Empty:
- body = await self.body()
- self._json = decode_json(body or b"null", type_decoders=self.route_handler.resolve_type_decoders())
- set_litestar_scope_state(self.scope, SCOPE_STATE_JSON_KEY, self._json)
+ if (json_ := get_litestar_scope_state(self.scope, SCOPE_STATE_JSON_KEY, Empty)) is not Empty:
+ self._json = json_
+ else:
+ body = await self.body()
+ self._json = decode_json(body or b"null", type_decoders=self.route_handler.resolve_type_decoders())
+ set_litestar_scope_state(self.scope, SCOPE_STATE_JSON_KEY, self._json)
return self._json
async def msgpack(self) -> Any:
@@ -126,9 +136,14 @@ async def msgpack(self) -> Any:
An arbitrary value
"""
if self._msgpack is Empty:
- body = await self.body()
- self._msgpack = decode_msgpack(body or b"\xc0", type_decoders=self.route_handler.resolve_type_decoders())
- set_litestar_scope_state(self.scope, SCOPE_STATE_MSGPACK_KEY, self._msgpack)
+ if (msgpack := get_litestar_scope_state(self.scope, SCOPE_STATE_MSGPACK_KEY, Empty)) is not Empty:
+ self._msgpack = msgpack
+ else:
+ body = await self.body()
+ self._msgpack = decode_msgpack(
+ body or b"\xc0", type_decoders=self.route_handler.resolve_type_decoders()
+ )
+ set_litestar_scope_state(self.scope, SCOPE_STATE_MSGPACK_KEY, self._msgpack)
return self._msgpack
async def stream(self) -> AsyncGenerator[bytes, None]:
@@ -169,9 +184,12 @@ async def body(self) -> bytes:
A byte-string representing the body of the request.
"""
if self._body is Empty:
- self._body = b"".join([c async for c in self.stream()])
- set_litestar_scope_state(self.scope, SCOPE_STATE_BODY_KEY, self._body)
- return cast("bytes", self._body)
+ if (body := get_litestar_scope_state(self.scope, SCOPE_STATE_BODY_KEY)) is not None:
+ self._body = cast("bytes", body)
+ else:
+ self._body = b"".join([c async for c in self.stream()])
+ set_litestar_scope_state(self.scope, SCOPE_STATE_BODY_KEY, self._body)
+ return self._body
async def form(self) -> FormMultiDict:
"""Retrieve form data from the request. If the request is either a 'multipart/form-data' or an
@@ -182,21 +200,24 @@ async def form(self) -> FormMultiDict:
A FormMultiDict instance
"""
if self._form is Empty:
- content_type, options = self.content_type
- if content_type == RequestEncodingType.MULTI_PART:
- self._form = parse_multipart_form(
- body=await self.body(),
- boundary=options.get("boundary", "").encode(),
- multipart_form_part_limit=self.app.multipart_form_part_limit,
- )
- elif content_type == RequestEncodingType.URL_ENCODED:
- self._form = parse_url_encoded_form_data(
- await self.body(),
- )
+ if (form := get_litestar_scope_state(self.scope, SCOPE_STATE_FORM_KEY, Empty)) is not Empty:
+ self._form = cast("dict[str, str | list[str]]", form)
else:
- self._form = {}
-
- set_litestar_scope_state(self.scope, SCOPE_STATE_FORM_KEY, self._form)
+ content_type, options = self.content_type
+ if content_type == RequestEncodingType.MULTI_PART:
+ self._form = parse_multipart_form(
+ body=await self.body(),
+ boundary=options.get("boundary", "").encode(),
+ multipart_form_part_limit=self.app.multipart_form_part_limit,
+ )
+ elif content_type == RequestEncodingType.URL_ENCODED:
+ self._form = parse_url_encoded_form_data(
+ await self.body(),
+ )
+ else:
+ self._form = {}
+
+ set_litestar_scope_state(self.scope, SCOPE_STATE_FORM_KEY, self._form)
return FormMultiDict(self._form)
diff --git a/litestar/middleware/logging.py b/litestar/middleware/logging.py
--- a/litestar/middleware/logging.py
+++ b/litestar/middleware/logging.py
@@ -126,7 +126,7 @@ async def log_request(self, scope: Scope, receive: Receive) -> None:
Returns:
None
"""
- extracted_data = await self.extract_request_data(request=scope["app"].request_class(scope, receive=receive))
+ extracted_data = await self.extract_request_data(request=scope["app"].request_class(scope, receive))
self.log_message(values=extracted_data)
def log_response(self, scope: Scope) -> None:
| diff --git a/tests/unit/test_connection/test_connection_caching.py b/tests/unit/test_connection/test_connection_caching.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/test_connection/test_connection_caching.py
@@ -0,0 +1,196 @@
+from __future__ import annotations
+
+from typing import Any, Awaitable, Callable
+from unittest.mock import ANY, MagicMock, call
+
+import pytest
+
+from litestar import Request, constants
+from litestar.testing import RequestFactory
+from litestar.types import Empty, HTTPReceiveMessage, Scope
+from litestar.utils import get_litestar_scope_state, set_litestar_scope_state
+
+
+async def test_multiple_request_object_data_caching(create_scope: Callable[..., Scope], mock: MagicMock) -> None:
+ """Test that accessing the request data on multiple request objects only attempts to await `receive()` once.
+
+ https://github.com/litestar-org/litestar/issues/2727
+ """
+
+ async def test_receive() -> HTTPReceiveMessage:
+ mock()
+ return {"type": "http.request", "body": b"abc", "more_body": False}
+
+ scope = create_scope()
+ request_1 = Request[Any, Any, Any](scope, test_receive)
+ request_2 = Request[Any, Any, Any](scope, test_receive)
+ assert (await request_1.body()) == b"abc"
+ assert (await request_2.body()) == b"abc"
+ assert mock.call_count == 1
+
+
[email protected](name="get_mock")
+def get_mock_fixture() -> MagicMock:
+ return MagicMock()
+
+
[email protected](name="set_mock")
+def set_mock_fixture() -> MagicMock:
+ return MagicMock()
+
+
[email protected](name="create_connection")
+def create_connection_fixture(
+ get_mock: MagicMock, set_mock: MagicMock, monkeypatch: pytest.MonkeyPatch
+) -> Callable[..., Request]:
+ def create_connection(body_type: str = "json") -> Request:
+ def wrapped_get_litestar_scope_state(scope_: Scope, key: str, default: Any = None) -> Any:
+ get_mock(key)
+ return get_litestar_scope_state(scope_, key, default)
+
+ def wrapped_set_litestar_scope_state(scope_: Scope, key: str, value: Any) -> None:
+ set_mock(key, value)
+ set_litestar_scope_state(scope_, key, value)
+
+ monkeypatch.setattr("litestar.connection.base.get_litestar_scope_state", wrapped_get_litestar_scope_state)
+ monkeypatch.setattr("litestar.connection.base.set_litestar_scope_state", wrapped_set_litestar_scope_state)
+ monkeypatch.setattr("litestar.connection.request.get_litestar_scope_state", wrapped_get_litestar_scope_state)
+ monkeypatch.setattr("litestar.connection.request.set_litestar_scope_state", wrapped_set_litestar_scope_state)
+
+ connection = RequestFactory().get()
+
+ async def fake_receive() -> HTTPReceiveMessage:
+ if body_type == "msgpack":
+ return {"type": "http.request", "body": b"\x81\xa3abc\xa3def", "more_body": False}
+ return {"type": "http.request", "body": b'{"abc":"def"}', "more_body": False}
+
+ monkeypatch.setattr(connection, "receive", fake_receive)
+
+ return connection
+
+ return create_connection
+
+
[email protected](name="get_value")
+def get_value_fixture() -> Callable[[Request, str, bool], Awaitable[Any]]:
+ """Fixture to get the value of a connection cached property.
+
+ Returns:
+ A function to get the value of a connection cached property.
+ """
+
+ async def get_value_(connection: Request, prop_name: str, is_coro: bool) -> Any:
+ """Helper to get the value of the tested cached property."""
+ value = getattr(connection, prop_name)
+ if is_coro:
+ return await value()
+ return value
+
+ return get_value_
+
+
+caching_tests = [
+ (constants.SCOPE_STATE_URL_KEY, "url", "_url", False),
+ (constants.SCOPE_STATE_BASE_URL_KEY, "base_url", "_base_url", False),
+ (
+ constants.SCOPE_STATE_PARSED_QUERY_KEY,
+ "query_params",
+ "_parsed_query",
+ False,
+ ),
+ (constants.SCOPE_STATE_COOKIES_KEY, "cookies", "_cookies", False),
+ (constants.SCOPE_STATE_BODY_KEY, "body", "_body", True),
+ (constants.SCOPE_STATE_FORM_KEY, "form", "_form", True),
+ (constants.SCOPE_STATE_MSGPACK_KEY, "msgpack", "_msgpack", True),
+ (constants.SCOPE_STATE_JSON_KEY, "json", "_json", True),
+ (constants.SCOPE_STATE_ACCEPT_KEY, "accept", "_accept", False),
+ (constants.SCOPE_STATE_CONTENT_TYPE_KEY, "content_type", "_content_type", False),
+]
+
+
[email protected](("state_key", "prop_name", "cache_attr_name", "is_coro"), caching_tests)
+async def test_connection_cached_properties_no_scope_or_connection_caching(
+ state_key: str,
+ prop_name: str,
+ cache_attr_name: str,
+ is_coro: bool,
+ create_connection: Callable[..., Request],
+ get_mock: MagicMock,
+ set_mock: MagicMock,
+ get_value: Callable[[Request, str, bool], Awaitable[Any]],
+) -> None:
+ def check_get_mock() -> None:
+ """Helper to check the get mock.
+
+ For certain properties, we call `get_litestar_scope_state()` twice, once for the property and once for the
+ body. For these cases, we check that the mock was called twice.
+ """
+ if state_key in ("json", "msgpack"):
+ get_mock.assert_has_calls([call(state_key), call("body")])
+ elif state_key == "form":
+ get_mock.assert_has_calls([call(state_key), call("content_type")])
+ else:
+ get_mock.assert_called_once_with(state_key)
+
+ def check_set_mock() -> None:
+ """Helper to check the set mock.
+
+ For certain properties, we call `set_litestar_scope_state()` twice, once for the property and once for the
+ body. For these cases, we check that the mock was called twice.
+ """
+ if state_key in ("json", "msgpack"):
+ set_mock.assert_has_calls([call("body", ANY), call(state_key, ANY)])
+ elif state_key == "form":
+ set_mock.assert_has_calls([call("content_type", ANY), call("form", ANY)])
+ else:
+ set_mock.assert_called_once_with(state_key, ANY)
+
+ connection = create_connection("msgpack" if state_key == "msgpack" else "json")
+
+ assert get_litestar_scope_state(connection.scope, state_key, Empty) is Empty
+ setattr(connection, cache_attr_name, Empty)
+
+ await get_value(connection, prop_name, is_coro)
+ check_get_mock()
+ check_set_mock()
+
+
[email protected](("state_key", "prop_name", "cache_attr_name", "is_coro"), caching_tests)
+async def test_connection_cached_properties_cached_in_scope(
+ state_key: str,
+ prop_name: str,
+ cache_attr_name: str,
+ is_coro: bool,
+ create_connection: Callable[..., Request],
+ get_mock: MagicMock,
+ set_mock: MagicMock,
+ get_value: Callable[[Request, str, bool], Awaitable[Any]],
+) -> None:
+ # set the value in the scope and ensure empty on connection
+ connection = create_connection()
+
+ set_litestar_scope_state(connection.scope, state_key, {"a": "b"})
+ setattr(connection, cache_attr_name, Empty)
+
+ await get_value(connection, prop_name, is_coro)
+ get_mock.assert_called_once_with(state_key)
+ set_mock.assert_not_called()
+
+
[email protected](("state_key", "prop_name", "cache_attr_name", "is_coro"), caching_tests)
+async def test_connection_cached_properties_cached_on_connection(
+ state_key: str,
+ prop_name: str,
+ cache_attr_name: str,
+ is_coro: bool,
+ create_connection: Callable[..., Request],
+ get_mock: MagicMock,
+ set_mock: MagicMock,
+ get_value: Callable[[Request, str, bool], Awaitable[Any]],
+) -> None:
+ connection = create_connection()
+ # set the value on the connection
+ setattr(connection, cache_attr_name, {"a": "b"})
+ await get_value(connection, prop_name, is_coro)
+ get_mock.assert_not_called()
+ set_mock.assert_not_called()
| Bug: multiple connection objects can cause the app to hang
### Description
If multiple request objects are created before the first one calls one of the cached data access methods, e.g., `Request.json()` et. al, then the 2nd one to attempt to access the data will cause the request to block on `receive()` for a 2nd time, waiting for message that will never come.
The reason is that we only check whether the data has been cached upon instantiation of the connection objects, not when the connection object attempts to access the request data.
### URL to code causing the issue
_No response_
### MCVE
```python
from typing import Dict
from litestar import Litestar, Request, post
from litestar.types.asgi_types import ASGIApp, Message, Receive, Scope, Send
def some_middleware(app: ASGIApp) -> ASGIApp:
async def middleware(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive, send)
async def wrapped_send(message: Message) -> None:
await request.json()
# do something with data
await send(message)
await app(scope, receive, wrapped_send)
return middleware
@post(middleware=[some_middleware])
async def root(request: Request) -> Dict[str, str]:
return request.json()
app = Litestar(route_handlers=[root], debug=True)
```
### Steps to reproduce
```bash
1. run the above application
2. make any POST request to `/`
```
### Screenshots
```bash
""
```
### Logs
_No response_
### Litestar Version
main
### Platform
- [X] Linux
- [X] Mac
- [X] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2727">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2727/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2727/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-22T12:37:00 |
|
litestar-org/litestar | 2,745 | litestar-org__litestar-2745 | [
"2628"
] | 829ef470775e69c0afd8cd809d2321e93c78e155 | diff --git a/litestar/_openapi/schema_generation/schema.py b/litestar/_openapi/schema_generation/schema.py
--- a/litestar/_openapi/schema_generation/schema.py
+++ b/litestar/_openapi/schema_generation/schema.py
@@ -134,10 +134,6 @@
time: Schema(type=OpenAPIType.STRING, format=OpenAPIFormat.DURATION),
timedelta: Schema(type=OpenAPIType.STRING, format=OpenAPIFormat.DURATION),
tuple: Schema(type=OpenAPIType.ARRAY),
- UploadFile: Schema(
- type=OpenAPIType.STRING,
- content_media_type="application/octet-stream",
- ),
}
@@ -349,11 +345,47 @@ def for_field_definition(self, field_definition: FieldDefinition) -> Schema | Re
result = self.for_object_type(field_definition)
elif self.is_constrained_field(field_definition):
result = self.for_constrained_field(field_definition)
+ elif field_definition.is_subclass_of(UploadFile):
+ result = self.for_upload_file(field_definition)
else:
result = create_schema_for_annotation(field_definition.annotation)
return self.process_schema_result(field_definition, result) if isinstance(result, Schema) else result
+ def for_upload_file(self, field_definition: FieldDefinition) -> Schema:
+ """Create schema for UploadFile.
+
+ Args:
+ field_definition: A field definition instance.
+
+ Returns:
+ A Schema instance.
+ """
+
+ property_key = "file"
+ schema = Schema(
+ type=OpenAPIType.STRING,
+ content_media_type="application/octet-stream",
+ format=OpenAPIFormat.BINARY,
+ )
+
+ # If the type is `dict[str, UploadFile]`, then it's the same as a `list[UploadFile]`
+ # but we will internally convert that into a `dict[str, UploadFile]`.
+ if field_definition.is_non_string_sequence or field_definition.is_mapping:
+ property_key = "files"
+ schema = Schema(type=OpenAPIType.ARRAY, items=schema)
+
+ # If the uploadfile is annotated directly on the handler, then the
+ # 'properties' needs to be created. Else, the 'properties' will be
+ # created by the corresponding plugin.
+ is_defined_on_handler = field_definition.name == "data" and isinstance(
+ field_definition.kwarg_definition, BodyKwarg
+ )
+ if is_defined_on_handler:
+ return Schema(type=OpenAPIType.OBJECT, properties={property_key: schema})
+
+ return schema
+
def for_typevar(self) -> Schema:
"""Create a schema for a TypeVar.
@@ -408,6 +440,9 @@ def for_object_type(self, field_definition: FieldDefinition) -> Schema:
Returns:
A schema instance.
"""
+ if field_definition.has_inner_subclass_of(UploadFile):
+ return self.for_upload_file(field_definition)
+
if field_definition.is_mapping:
return Schema(
type=OpenAPIType.OBJECT,
@@ -422,6 +457,7 @@ def for_object_type(self, field_definition: FieldDefinition) -> Schema:
# filters out ellipsis from tuple[int, ...] type annotations
inner_types = (f for f in field_definition.inner_types if f.annotation is not Ellipsis)
items = list(map(self.for_field_definition, inner_types or ()))
+
return Schema(
type=OpenAPIType.ARRAY,
items=Schema(one_of=items) if len(items) > 1 else items[0],
| diff --git a/tests/unit/test_openapi/test_request_body.py b/tests/unit/test_openapi/test_request_body.py
--- a/tests/unit/test_openapi/test_request_body.py
+++ b/tests/unit/test_openapi/test_request_body.py
@@ -56,50 +56,83 @@ def test_create_request_body(person_controller: Type[Controller], create_request
assert request_body
-def test_upload_file_request_body_generation() -> None:
- @post(path="/form-upload")
- async def handle_form_upload(
- data: FormData = Body(media_type=RequestEncodingType.MULTI_PART),
- ) -> None:
- return None
-
+def test_upload_single_file_schema_generation() -> None:
@post(path="/file-upload")
async def handle_file_upload(
data: UploadFile = Body(media_type=RequestEncodingType.MULTI_PART),
) -> None:
return None
+ app = Litestar([handle_file_upload])
+ schema = app.openapi_schema.to_schema()
+
+ assert schema["paths"]["/file-upload"]["post"]["requestBody"]["content"]["multipart/form-data"]["schema"] == {
+ "properties": {"file": {"type": "string", "format": "binary", "contentMediaType": "application/octet-stream"}},
+ "type": "object",
+ }
+
+
+def test_upload_list_of_files_schema_generation() -> None:
@post(path="/file-list-upload")
async def handle_file_list_upload(
data: List[UploadFile] = Body(media_type=RequestEncodingType.MULTI_PART),
) -> None:
return None
- app = Litestar(route_handlers=[handle_form_upload, handle_file_upload, handle_file_list_upload])
- schema_dict = app.openapi_schema.to_schema()
- paths = schema_dict["paths"]
- components = schema_dict["components"]
- assert paths["/file-upload"]["post"]["requestBody"]["content"]["multipart/form-data"]["schema"] == {
- "type": "string",
- "contentMediaType": "application/octet-stream",
+ app = Litestar([handle_file_list_upload])
+ schema = app.openapi_schema.to_schema()
+
+ assert schema["paths"]["/file-list-upload"]["post"]["requestBody"]["content"]["multipart/form-data"]["schema"] == {
+ "type": "object",
+ "properties": {
+ "files": {
+ "items": {"type": "string", "contentMediaType": "application/octet-stream", "format": "binary"},
+ "type": "array",
+ }
+ },
}
- assert paths["/file-list-upload"]["post"]["requestBody"]["content"]["multipart/form-data"]["schema"] == {
- "items": {"type": "string", "contentMediaType": "application/octet-stream"},
- "type": "array",
+
+
+def test_upload_file_dict_schema_generation() -> None:
+ @post(path="/file-dict-upload")
+ async def handle_file_list_upload(
+ data: Dict[str, UploadFile] = Body(media_type=RequestEncodingType.MULTI_PART),
+ ) -> None:
+ return None
+
+ app = Litestar([handle_file_list_upload])
+ schema = app.openapi_schema.to_schema()
+
+ assert schema["paths"]["/file-dict-upload"]["post"]["requestBody"]["content"]["multipart/form-data"]["schema"] == {
+ "type": "object",
+ "properties": {
+ "files": {
+ "items": {"type": "string", "contentMediaType": "application/octet-stream", "format": "binary"},
+ "type": "array",
+ }
+ },
}
- assert components == {
+
+def test_upload_file_model_schema_generation() -> None:
+ @post(path="/form-upload")
+ async def handle_form_upload(
+ data: FormData = Body(media_type=RequestEncodingType.MULTI_PART),
+ ) -> None:
+ return None
+
+ app = Litestar([handle_form_upload])
+ schema = app.openapi_schema.to_schema()
+
+ assert schema["paths"]["/form-upload"]["post"]["requestBody"]["content"]["multipart/form-data"] == {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ assert schema["components"] == {
"schemas": {
"FormData": {
"properties": {
- "cv": {
- "type": "string",
- "contentMediaType": "application/octet-stream",
- },
- "image": {
- "type": "string",
- "contentMediaType": "application/octet-stream",
- },
+ "cv": {"type": "string", "contentMediaType": "application/octet-stream", "format": "binary"},
+ "image": {"type": "string", "contentMediaType": "application/octet-stream", "format": "binary"},
},
"type": "object",
"required": ["cv", "image"],
| Bug: File upload example doesn't work with Swagger
### Summary
The examples demonstrating file uploads in the docs don't work well with Swagger.
[Example from docs](https://docs.litestar.dev/2/usage/requests.html#file-uploads)
```py
from typing import Annotated
from litestar import Litestar, MediaType, post
from litestar.datastructures import UploadFile
from litestar.enums import RequestEncodingType
from litestar.params import Body
@post(path="/", media_type=MediaType.TEXT)
async def handle_file_upload(
data: Annotated[UploadFile, Body(media_type=RequestEncodingType.MULTI_PART)],
) -> str:
content = await data.read()
filename = data.filename
return f"{filename}, {content.decode()}"
app = Litestar(route_handlers=[handle_file_upload])
```
# Result
http://127.0.0.1:8000/schema/swagger#/default/HandleFileUpload
<img width="1401" alt="image" src="https://github.com/litestar-org/litestar/assets/7423639/b5b2b4e2-55c0-4edd-9c3d-f6a1561e3519">
# Expected

https://swagger.io/docs/specification/2-0/file-upload/
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2628">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2628/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2628/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-24T12:02:53 |
|
litestar-org/litestar | 2,764 | litestar-org__litestar-2764 | [
"2721"
] | 7414f7fd7d4782223502895e6a23b77ed635cd2d | diff --git a/litestar/dto/_backend.py b/litestar/dto/_backend.py
--- a/litestar/dto/_backend.py
+++ b/litestar/dto/_backend.py
@@ -4,7 +4,18 @@
from __future__ import annotations
from dataclasses import replace
-from typing import TYPE_CHECKING, AbstractSet, Any, Callable, ClassVar, Collection, Final, Mapping, Union, cast
+from typing import (
+ TYPE_CHECKING,
+ AbstractSet,
+ Any,
+ ClassVar,
+ Collection,
+ Final,
+ Mapping,
+ Protocol,
+ Union,
+ cast,
+)
from msgspec import UNSET, Struct, UnsetType, convert, defstruct, field
from typing_extensions import get_origin
@@ -37,6 +48,19 @@
__all__ = ("DTOBackend",)
+class CompositeTypeHandler(Protocol):
+ def __call__(
+ self,
+ field_definition: FieldDefinition,
+ exclude: AbstractSet[str],
+ include: AbstractSet[str],
+ rename_fields: dict[str, str],
+ unique_name: str,
+ nested_depth: int,
+ ) -> CompositeType:
+ ...
+
+
class DTOBackend:
__slots__ = (
"annotation",
@@ -70,7 +94,7 @@ def __init__(
dto_factory: The DTO factory class calling this backend.
field_definition: Parsed type.
handler_id: The name of the handler that this backend is for.
- is_data_field: Whether or not the field is a subclass of DTOData.
+ is_data_field: Whether the field is a subclass of DTOData.
model_type: Model type.
wrapper_attribute_name: If the data that DTO should operate upon is wrapped in a generic datastructure, this is the name of the attribute that the data is stored in.
"""
@@ -82,7 +106,10 @@ def __init__(
self.wrapper_attribute_name: Final[str | None] = wrapper_attribute_name
self.parsed_field_definitions = self.parse_model(
- model_type=model_type, exclude=self.dto_factory.config.exclude, include=self.dto_factory.config.include
+ model_type=model_type,
+ exclude=self.dto_factory.config.exclude,
+ include=self.dto_factory.config.include,
+ rename_fields=self.dto_factory.config.rename_fields,
)
self.transfer_model_type = self.create_transfer_model_type(
model_name=model_type.__name__, field_definitions=self.parsed_field_definitions
@@ -99,7 +126,12 @@ def __init__(
self.annotation = _maybe_wrap_in_generic_annotation(annotation, self.transfer_model_type)
def parse_model(
- self, model_type: Any, exclude: AbstractSet[str], include: AbstractSet[str], nested_depth: int = 0
+ self,
+ model_type: Any,
+ exclude: AbstractSet[str],
+ include: AbstractSet[str],
+ rename_fields: dict[str, str],
+ nested_depth: int = 0,
) -> tuple[TransferDTOFieldDefinition, ...]:
"""Reduce :attr:`model_type` to a tuple :class:`TransferDTOFieldDefinition` instances.
@@ -123,6 +155,7 @@ def parse_model(
field_definition=field_definition,
exclude=exclude,
include=include,
+ rename_fields=rename_fields,
field_name=field_definition.name,
unique_name=field_definition.model_name,
nested_depth=nested_depth,
@@ -130,7 +163,7 @@ def parse_model(
except RecursionError:
continue
- if rename := self.dto_factory.config.rename_fields.get(field_definition.name):
+ if rename := rename_fields.get(field_definition.name):
serialization_name = rename
elif self.dto_factory.config.rename_strategy:
serialization_name = _rename_field(
@@ -342,9 +375,7 @@ def encode_data(self, data: Any) -> LitestarEncodableType:
),
)
- def _get_handler_for_field_definition(
- self, field_definition: FieldDefinition
- ) -> Callable[[FieldDefinition, AbstractSet[str], AbstractSet[str], str, int], CompositeType] | None:
+ def _get_handler_for_field_definition(self, field_definition: FieldDefinition) -> CompositeTypeHandler | None:
if field_definition.is_union:
return self._create_union_type
@@ -365,15 +396,24 @@ def _create_transfer_type(
field_definition: FieldDefinition,
exclude: AbstractSet[str],
include: AbstractSet[str],
+ rename_fields: dict[str, str],
field_name: str,
unique_name: str,
nested_depth: int,
) -> CompositeType | SimpleType:
exclude = _filter_nested_field(exclude, field_name)
include = _filter_nested_field(include, field_name)
+ rename_fields = _filter_nested_field_mapping(rename_fields, field_name)
if composite_type_handler := self._get_handler_for_field_definition(field_definition):
- return composite_type_handler(field_definition, exclude, include, unique_name, nested_depth)
+ return composite_type_handler(
+ field_definition=field_definition,
+ exclude=exclude,
+ include=include,
+ rename_fields=rename_fields,
+ unique_name=unique_name,
+ nested_depth=nested_depth,
+ )
transfer_model: NestedFieldInfo | None = None
@@ -382,7 +422,11 @@ def _create_transfer_type(
raise RecursionError
nested_field_definitions = self.parse_model(
- model_type=field_definition.annotation, exclude=exclude, include=include, nested_depth=nested_depth + 1
+ model_type=field_definition.annotation,
+ exclude=exclude,
+ include=include,
+ rename_fields=rename_fields,
+ nested_depth=nested_depth + 1,
)
transfer_model = NestedFieldInfo(
@@ -397,6 +441,7 @@ def _create_collection_type(
field_definition: FieldDefinition,
exclude: AbstractSet[str],
include: AbstractSet[str],
+ rename_fields: dict[str, str],
unique_name: str,
nested_depth: int,
) -> CollectionType:
@@ -408,6 +453,7 @@ def _create_collection_type(
field_name="0",
unique_name=f"{unique_name}_0",
nested_depth=nested_depth,
+ rename_fields=rename_fields,
)
return CollectionType(
field_definition=field_definition, inner_type=inner_type, has_nested=inner_type.has_nested
@@ -418,6 +464,7 @@ def _create_mapping_type(
field_definition: FieldDefinition,
exclude: AbstractSet[str],
include: AbstractSet[str],
+ rename_fields: dict[str, str],
unique_name: str,
nested_depth: int,
) -> MappingType:
@@ -429,6 +476,7 @@ def _create_mapping_type(
field_name="0",
unique_name=f"{unique_name}_0",
nested_depth=nested_depth,
+ rename_fields=rename_fields,
)
value_type = self._create_transfer_type(
field_definition=inner_types[1] if inner_types else FieldDefinition.from_annotation(Any),
@@ -437,6 +485,7 @@ def _create_mapping_type(
field_name="1",
unique_name=f"{unique_name}_1",
nested_depth=nested_depth,
+ rename_fields=rename_fields,
)
return MappingType(
field_definition=field_definition,
@@ -450,6 +499,7 @@ def _create_tuple_type(
field_definition: FieldDefinition,
exclude: AbstractSet[str],
include: AbstractSet[str],
+ rename_fields: dict[str, str],
unique_name: str,
nested_depth: int,
) -> TupleType:
@@ -461,6 +511,7 @@ def _create_tuple_type(
field_name=str(i),
unique_name=f"{unique_name}_{i}",
nested_depth=nested_depth,
+ rename_fields=rename_fields,
)
for i, inner_type in enumerate(field_definition.inner_types)
)
@@ -475,6 +526,7 @@ def _create_union_type(
field_definition: FieldDefinition,
exclude: AbstractSet[str],
include: AbstractSet[str],
+ rename_fields: dict[str, str],
unique_name: str,
nested_depth: int,
) -> UnionType:
@@ -486,6 +538,7 @@ def _create_union_type(
field_name=str(i),
unique_name=f"{unique_name}_{i}",
nested_depth=nested_depth,
+ rename_fields=rename_fields,
)
for i, inner_type in enumerate(field_definition.inner_types)
)
@@ -521,6 +574,15 @@ def _filter_nested_field(field_name_set: AbstractSet[str], field_name: str) -> A
return {split[1] for s in field_name_set if (split := s.split(".", 1))[0] == field_name and len(split) > 1}
+def _filter_nested_field_mapping(field_name_mapping: Mapping[str, str], field_name: str) -> dict[str, str]:
+ """Filter a nested field name."""
+ return {
+ split[1]: v
+ for s, v in field_name_mapping.items()
+ if (split := s.split(".", 1))[0] == field_name and len(split) > 1
+ }
+
+
def _transfer_data(
destination_type: type[Any],
source_data: Any | Collection[Any],
| diff --git a/tests/unit/test_dto/test_factory/test_backends/test_base_dto.py b/tests/unit/test_dto/test_factory/test_backends/test_base_dto.py
--- a/tests/unit/test_dto/test_factory/test_backends/test_base_dto.py
+++ b/tests/unit/test_dto/test_factory/test_backends/test_base_dto.py
@@ -146,9 +146,16 @@ def create_transfer_type(
field_name: str = "name",
unique_name: str = "some_module.SomeModel.name",
nested_depth: int = 0,
+ rename_fields: dict[str, str] | None = None,
) -> TransferType:
return backend._create_transfer_type(
- field_definition, exclude or set(), include or set(), field_name, unique_name, nested_depth
+ field_definition=field_definition,
+ exclude=exclude or set(),
+ include=include or set(),
+ field_name=field_name,
+ unique_name=unique_name,
+ nested_depth=nested_depth,
+ rename_fields=rename_fields or {},
)
diff --git a/tests/unit/test_dto/test_factory/test_integration.py b/tests/unit/test_dto/test_factory/test_integration.py
--- a/tests/unit/test_dto/test_factory/test_integration.py
+++ b/tests/unit/test_dto/test_factory/test_integration.py
@@ -2,7 +2,8 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Dict, Generic, List, Optional, Sequence, TypeVar, cast
+from types import ModuleType
+from typing import TYPE_CHECKING, Callable, Dict, Generic, List, Optional, Sequence, TypeVar, cast
from unittest.mock import MagicMock
from uuid import UUID
@@ -91,6 +92,42 @@ def handler(data: Foo) -> Foo:
assert response.json() == {"baz": "hello"}
+def test_renamed_field_nested(use_experimental_dto_backend: bool, create_module: Callable[[str], ModuleType]) -> None:
+ # https://github.com/litestar-org/litestar/issues/2721
+ module = create_module(
+ """
+from dataclasses import dataclass
+from typing import List
+
+@dataclass
+class Bar:
+ id: str
+
+@dataclass
+class Foo:
+ id: str
+ bar: Bar
+ bars: List[Bar]
+"""
+ )
+
+ Foo = module.Foo
+
+ config = DTOConfig(
+ rename_fields={"id": "foo_id", "bar.id": "bar_id", "bars.0.id": "bars_id"},
+ experimental_codegen_backend=use_experimental_dto_backend,
+ )
+ dto = DataclassDTO[Annotated[Foo, config]] # type: ignore[valid-type]
+
+ @post(dto=dto, signature_types=[Foo])
+ def handler(data: Foo) -> Foo: # type: ignore[valid-type]
+ return data
+
+ with create_test_client(route_handlers=[handler]) as client:
+ response = client.post("/", json={"foo_id": "1", "bar": {"bar_id": "2"}, "bars": [{"bars_id": "3"}]})
+ assert response.json() == {"foo_id": "1", "bar": {"bar_id": "2"}, "bars": [{"bars_id": "3"}]}
+
+
@dataclass
class Spam:
main_id: str = "spam-id"
| Bug: Renaming in DTOs with nested fields will rename all occurrences.
### Description
In the example below, we have two models: 'Chat' and 'Message', each with an 'id' field. We also define a ResponseDTO for the Chat model, using DTOConfig to rename its 'id' field to 'chat_id'.
The intention is to only rename the 'id' of the Chat model. However, this configuration unexpectedly renames the 'id' field in the nested Message objects as well. As a result, the response output is
`{"chat_id":"1","messages":[{"chat_id":"1","created_at":"1","user_id":"1"}]}`,
where both Chat and Message 'id' fields are affected, contrary to the intended behavior.
### URL to code causing the issue
_No response_
### MCVE
```python
from typing_extensions import List
from litestar import get, Litestar
from pydantic import BaseModel
from litestar.dto import DTOConfig
from litestar.contrib.pydantic import PydanticDTO
class Message(BaseModel):
id: str
created_at: str
user_id: str
class Chat(BaseModel):
id: str
messages: List[Message]
class ResponseDTO(PydanticDTO[Chat]):
config = DTOConfig(rename_fields={"id": "chat_id"})
@get(return_dto=ResponseDTO)
async def get_chat() -> Chat:
return Chat(id="1", messages=[Message(id="1", created_at="1", user_id="1")])
app = Litestar([get_chat])
```
### Steps to reproduce
```bash
1. Start Litestar
2. Make API call `curl localhost:8000`
3. Observe :bug:
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.2.1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2721">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2721/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2721/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| @peterschutt Haven't really investigated yet, but it happens on both the regular and the codegen backend | 2023-11-26T14:51:21 |
litestar-org/litestar | 2,775 | litestar-org__litestar-2775 | [
"2737"
] | 389c7d732a4f8df22abc4672012351f2175d34ee | diff --git a/litestar/dto/_backend.py b/litestar/dto/_backend.py
--- a/litestar/dto/_backend.py
+++ b/litestar/dto/_backend.py
@@ -18,7 +18,6 @@
)
from msgspec import UNSET, Struct, UnsetType, convert, defstruct, field
-from typing_extensions import get_origin
from litestar.dto._types import (
CollectionType,
@@ -38,7 +37,6 @@
from litestar.types import Empty
from litestar.typing import FieldDefinition
from litestar.utils import unique_name_for_scope
-from litestar.utils.typing import safe_generic_origin_map
if TYPE_CHECKING:
from litestar.connection import ASGIConnection
@@ -119,11 +117,9 @@ def __init__(
self.override_serialization_name: bool = False
if field_definition.is_subclass_of(DTOData):
self.dto_data_type = field_definition.annotation
- annotation = self.field_definition.inner_types[0].annotation
- else:
- annotation = field_definition.annotation
+ field_definition = self.field_definition.inner_types[0]
- self.annotation = _maybe_wrap_in_generic_annotation(annotation, self.transfer_model_type)
+ self.annotation = build_annotation_for_backend(model_type, field_definition, self.transfer_model_type)
def parse_model(
self,
@@ -605,17 +601,32 @@ def _transfer_data(
Returns:
Data parsed into ``destination_type``.
"""
- if field_definition.is_non_string_collection and not field_definition.is_mapping:
+ if field_definition.is_non_string_collection:
+ if not field_definition.is_mapping:
+ return field_definition.instantiable_origin(
+ _transfer_data(
+ destination_type=destination_type,
+ source_data=item,
+ field_definitions=field_definitions,
+ field_definition=field_definition.inner_types[0],
+ is_data_field=is_data_field,
+ override_serialization_name=override_serialization_name,
+ )
+ for item in source_data
+ )
return field_definition.instantiable_origin(
- _transfer_data(
- destination_type=destination_type,
- source_data=item,
- field_definitions=field_definitions,
- field_definition=field_definition.inner_types[0],
- is_data_field=is_data_field,
- override_serialization_name=override_serialization_name,
+ (
+ key,
+ _transfer_data(
+ destination_type=destination_type,
+ source_data=value,
+ field_definitions=field_definitions,
+ field_definition=field_definition.inner_types[1],
+ is_data_field=is_data_field,
+ override_serialization_name=override_serialization_name,
+ ),
)
- for item in source_data
+ for key, value in source_data.items() # type: ignore[union-attr]
)
return _transfer_instance_data(
@@ -796,20 +807,30 @@ def _create_struct_for_field_definitions(
return defstruct(model_name, struct_fields, frozen=True, kw_only=True)
-def _maybe_wrap_in_generic_annotation(annotation: Any, model: Any) -> Any:
+def build_annotation_for_backend(
+ model_type: type[Any], field_definition: FieldDefinition, transfer_model: type[Struct]
+) -> Any:
"""A helper to re-build a generic outer type with new inner type.
Args:
- annotation: The original annotation on the handler signature
- model: The data container type
+ model_type: The original model type.
+ field_definition: The parsed type that represents the handler annotation for which the DTO is being applied.
+ transfer_model: The transfer model generated to represent the model type.
Returns:
Annotation with new inner type if applicable.
"""
- if (origin := get_origin(annotation)) and origin in safe_generic_origin_map:
- return safe_generic_origin_map[origin][model] # type: ignore[index]
+ if not field_definition.inner_types:
+ if field_definition.is_subclass_of(model_type):
+ return transfer_model
+ return field_definition.annotation
+
+ inner_types = tuple(
+ build_annotation_for_backend(model_type, inner_type, transfer_model)
+ for inner_type in field_definition.inner_types
+ )
- return origin[model] if (origin := get_origin(annotation)) else model
+ return field_definition.safe_generic_origin[inner_types]
def _should_mark_private(field_definition: DTOFieldDefinition, underscore_fields_private: bool) -> bool:
diff --git a/litestar/dto/_codegen_backend.py b/litestar/dto/_codegen_backend.py
--- a/litestar/dto/_codegen_backend.py
+++ b/litestar/dto/_codegen_backend.py
@@ -349,7 +349,7 @@ def create_transfer_data(
override_serialization_name: bool,
field_definition: FieldDefinition | None = None,
) -> Callable[[Any], Any]:
- if field_definition and field_definition.is_non_string_collection and not field_definition.is_mapping:
+ if field_definition and field_definition.is_non_string_collection:
factory = cls(
is_data_field=is_data_field,
override_serialization_name=override_serialization_name,
@@ -390,9 +390,14 @@ def _create_transfer_data_body_nested(
override_serialization_name=self.override_serialization_name,
)
transfer_func_name = self._add_to_fn_globals("transfer_data", transfer_func)
- self._add_stmt(
- f"{assignment_target} = {origin_name}({transfer_func_name}(item) for item in {source_data_name})"
- )
+ if field_definition.is_mapping:
+ self._add_stmt(
+ f"{assignment_target} = {origin_name}((key, {transfer_func_name}(item)) for key, item in {source_data_name}.items())"
+ )
+ else:
+ self._add_stmt(
+ f"{assignment_target} = {origin_name}({transfer_func_name}(item) for item in {source_data_name})"
+ )
def _create_transfer_instance_data(
self,
| diff --git a/tests/unit/test_dto/test_factory/test_integration.py b/tests/unit/test_dto/test_factory/test_integration.py
--- a/tests/unit/test_dto/test_factory/test_integration.py
+++ b/tests/unit/test_dto/test_factory/test_integration.py
@@ -805,3 +805,21 @@ def handler(data: Superuser) -> Superuser:
headers={"Content-Type": "application/json; charset=utf-8"},
)
assert msgspec.json.decode(received.content, type=Superuser) == data
+
+
+def test_dto_returning_mapping(use_experimental_dto_backend: bool) -> None:
+ @dataclass
+ class Lexeme:
+ id: int
+ name: str
+
+ class LexemeDTO(DataclassDTO[Lexeme]):
+ config = DTOConfig(exclude={"id"}, experimental_codegen_backend=use_experimental_dto_backend)
+
+ @get(return_dto=LexemeDTO, signature_types=[Lexeme])
+ async def get_definition() -> Dict[str, Lexeme]:
+ return {"hello": Lexeme(id=1, name="hello"), "world": Lexeme(id=2, name="world")}
+
+ with create_test_client(route_handlers=[get_definition]) as client:
+ response = client.get("/")
+ assert response.json() == {"hello": {"name": "hello"}, "world": {"name": "world"}}
diff --git a/tests/unit/test_openapi/conftest.py b/tests/unit/test_openapi/conftest.py
--- a/tests/unit/test_openapi/conftest.py
+++ b/tests/unit/test_openapi/conftest.py
@@ -61,7 +61,7 @@ def create_person(
@post(path="/bulk", dto=PartialDataclassPersonDTO)
def bulk_create_person(
- self, data: List[DTOData[DataclassPerson]], secret_header: str = Parameter(header="secret")
+ self, data: DTOData[List[DataclassPerson]], secret_header: str = Parameter(header="secret")
) -> List[DataclassPerson]:
return []
@@ -73,7 +73,7 @@ def bulk_update_person(
@patch(path="/bulk", dto=PartialDataclassPersonDTO)
def bulk_partial_update_person(
- self, data: List[DTOData[DataclassPerson]], secret_header: str = Parameter(header="secret")
+ self, data: DTOData[List[DataclassPerson]], secret_header: str = Parameter(header="secret")
) -> List[DataclassPerson]:
return []
| Bug: fail to register route with return DTO nested in dictionary
### Description
I'm trying to return an object nested inside a dictionary using DTO, but litestar failed to register the route.
Originally I was working with SQLAlchemy models, with return type `dict[str, list[Model]]` but later found out
that a simpler data types also didn't work.
### URL to code causing the issue
_No response_
### MCVE
```python
from typing import Dict
from dataclasses import dataclass
from litestar import Litestar, get
from litestar.dto import DataclassDTO
@dataclass
class Lexeme: ...
class ReadDTO(DataclassDTO[Lexeme]): ...
@get(return_dto=ReadDTO)
async def get_definition() -> Dict[str, Lexeme]:
return {}
app = Litestar(
route_handlers=[get_definition],
)
```
### Steps to reproduce
_No response_
### Screenshots
_No response_
### Logs
```bash
Traceback (most recent call last):
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/bin/litestar", line 8, in <module>
sys.exit(run_cli())
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/__main__.py", line 6, in run_cli
litestar_group()
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/click/core.py", line 1157, in __call__
return self.main(*args, **kwargs)
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/rich_click/rich_command.py", line 125, in main
with self.make_context(prog_name, args, **extra) as ctx:
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/cli/_utils.py", line 250, in make_context
self._prepare(ctx)
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/cli/_utils.py", line 232, in _prepare
env = ctx.obj = LitestarEnv.from_env(ctx.params.get("app_path"), ctx.params.get("app_dir"))
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/cli/_utils.py", line 127, in from_env
loaded_app = _autodiscover_app(cwd)
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/cli/_utils.py", line 340, in _autodiscover_app
module = importlib.import_module(import_path)
File "/nix/store/763kk6xg6vaslzh1hgvwgdk1h582b7s3-python3-3.10.12/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/home/kasuari/dev/repo/litestar-issue-repro/app.py", line 18, in <module>
app = Litestar(
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/app.py", line 446, in __init__
self.register(route_handler)
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/app.py", line 620, in register
route_handler.on_registration(self)
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/handlers/http_handlers/base.py", line 490, in on_registration
super().on_registration(app)
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/handlers/base.py", line 527, in on_registration
self.resolve_return_dto()
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/handlers/base.py", line 486, in resolve_return_dto
return_dto.create_for_field_definition(
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/dto/base_dto.py", line 185, in create_for_field_definition
backend_context[key] = backend_cls( # type: ignore[literal-required]
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/dto/_backend.py", line 99, in __init__
self.annotation = _maybe_wrap_in_generic_annotation(annotation, self.transfer_model_type)
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/litestar/dto/_backend.py", line 748, in _maybe_wrap_in_generic_annotation
return safe_generic_origin_map[origin][model] # type: ignore[index]
File "/nix/store/763kk6xg6vaslzh1hgvwgdk1h582b7s3-python3-3.10.12/lib/python3.10/typing.py", line 312, in inner
return func(*args, **kwds)
File "/nix/store/763kk6xg6vaslzh1hgvwgdk1h582b7s3-python3-3.10.12/lib/python3.10/typing.py", line 1144, in __getitem__
_check_generic(self, params, self._nparams)
File "/home/kasuari/dev/repo/litestar-issue-repro/venv/lib/python3.10/site-packages/typing_extensions.py", line 165, in _check_generic
raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
TypeError: Too few parameters for typing.Dict; actual 1, expected 2
```
### Litestar Version
2.3.2
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2737">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2737/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2737/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-27T08:56:59 |
|
litestar-org/litestar | 2,777 | litestar-org__litestar-2777 | [
"2770"
] | ce0d971f1646f8c7912b8a3c0583b7b872a042d4 | diff --git a/litestar/middleware/csrf.py b/litestar/middleware/csrf.py
--- a/litestar/middleware/csrf.py
+++ b/litestar/middleware/csrf.py
@@ -119,9 +119,12 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
):
token = connection_state.csrf_token = csrf_cookie or generate_csrf_token(secret=self.config.secret)
await self.app(scope, receive, self.create_send_wrapper(send=send, csrf_cookie=csrf_cookie, token=token))
- elif self._csrf_tokens_match(existing_csrf_token, csrf_cookie):
- # we haven't properly narrowed the type of `existing_csrf_token` to be non-None, but we know it is
- connection_state.csrf_token = existing_csrf_token # type: ignore[assignment]
+ elif (
+ existing_csrf_token is not None
+ and csrf_cookie is not None
+ and self._csrf_tokens_match(existing_csrf_token, csrf_cookie)
+ ):
+ connection_state.csrf_token = existing_csrf_token
await self.app(scope, receive, send)
else:
raise PermissionDeniedException("CSRF token verification failed")
@@ -177,11 +180,8 @@ def _decode_csrf_token(self, token: str) -> str | None:
expected_hash = generate_csrf_hash(token=token_secret, secret=self.config.secret)
return token_secret if compare_digest(existing_hash, expected_hash) else None
- def _csrf_tokens_match(self, request_csrf_token: str | None, cookie_csrf_token: str | None) -> bool:
+ def _csrf_tokens_match(self, request_csrf_token: str, cookie_csrf_token: str) -> bool:
"""Take the CSRF tokens from the request and the cookie and verify both are valid and identical."""
- if not (request_csrf_token and cookie_csrf_token):
- return False
-
decoded_request_token = self._decode_csrf_token(request_csrf_token)
decoded_cookie_token = self._decode_csrf_token(cookie_csrf_token)
if decoded_request_token is None or decoded_cookie_token is None:
| refactor: improve typing in CSRF middleware
https://github.com/litestar-org/litestar/blob/7414f7fd7d4782223502895e6a23b77ed635cd2d/litestar/middleware/csrf.py#L87-L127
At line 105, we use `dict.get()` to set the value of `existing_csrf_token` so it can be `None` if the header doesn't exist.
At line 123, that block is guarded by `self._csrf_tokens_match()` which will return `False` if it is `None`, so actually `existing_csrf_token` cannot be falsy in this block, its just that its value is not narrowed appropriately.
Fixing this would probably be as simple as using `request.cookies.get(..., "")` and `request.headers.get(..., "")` on lines 104 and 105 respectively, and re-type downstream methods to only accept `str` instead of `str | None`.
_Originally posted by @peterschutt in https://github.com/litestar-org/litestar/pull/2751#discussion_r1405515256_
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2770">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2770/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2770/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-27T12:56:31 |
||
litestar-org/litestar | 2,784 | litestar-org__litestar-2784 | [
"2782"
] | cbc60d271c929420a9d753ff4b076dc2f1aec73c | diff --git a/litestar/security/jwt/auth.py b/litestar/security/jwt/auth.py
--- a/litestar/security/jwt/auth.py
+++ b/litestar/security/jwt/auth.py
@@ -4,13 +4,13 @@
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any, Callable, Generic, Iterable, Literal, Sequence, TypeVar, cast
-from litestar.contrib.jwt.jwt_token import Token
-from litestar.contrib.jwt.middleware import JWTAuthenticationMiddleware, JWTCookieAuthenticationMiddleware
from litestar.datastructures import Cookie
from litestar.enums import MediaType
from litestar.middleware import DefineMiddleware
from litestar.openapi.spec import Components, OAuthFlow, OAuthFlows, SecurityRequirement, SecurityScheme
from litestar.security.base import AbstractSecurityConfig
+from litestar.security.jwt.middleware import JWTAuthenticationMiddleware, JWTCookieAuthenticationMiddleware
+from litestar.security.jwt.token import Token
from litestar.status_codes import HTTP_201_CREATED
from litestar.types import ControllerRouterHandler, Empty, Guard, Method, Scopes, SyncOrAsyncUnion, TypeEncodersMap
diff --git a/litestar/security/jwt/middleware.py b/litestar/security/jwt/middleware.py
--- a/litestar/security/jwt/middleware.py
+++ b/litestar/security/jwt/middleware.py
@@ -2,12 +2,12 @@
from typing import TYPE_CHECKING, Awaitable, Callable, Sequence
-from litestar.contrib.jwt.jwt_token import Token
from litestar.exceptions import NotAuthorizedException
from litestar.middleware.authentication import (
AbstractAuthenticationMiddleware,
AuthenticationResult,
)
+from litestar.security.jwt.token import Token
__all__ = ("JWTAuthenticationMiddleware", "JWTCookieAuthenticationMiddleware")
| Bug: Importing from litestar.security.jwt cause a circular import
### Description
Hello,
when upgrading from 2.3.2 to 2.4.0 version of litestar.
I got a message saying depreciation warning about the import of `litestar.contrib.jwt` that will be removed in 3.0 and that is deprecated in 2.4.0
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar.security.jwt import OAuth2Login
```
### Steps to reproduce
```bash
1. Just import `litestar.security.jwt`
2. See error
```
### Screenshots
_No response_
### Logs
```bash
ImportError: cannot import name 'BaseJWTAuth' from partially initialized module 'litestar.security.jwt.auth' (most likely due to a circular import)
```
### Litestar Version
2.4.0
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2782">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2782/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2782/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-28T08:58:53 |
||
litestar-org/litestar | 2,788 | litestar-org__litestar-2788 | [
"2662"
] | cb8afc2fa2a209ed75e65eb02a4cc7bff4529c91 | diff --git a/litestar/_openapi/parameters.py b/litestar/_openapi/parameters.py
--- a/litestar/_openapi/parameters.py
+++ b/litestar/_openapi/parameters.py
@@ -38,7 +38,7 @@ def __init__(self, route_handler: BaseRouteHandler) -> None:
route_handler: Associated route handler
"""
self.route_handler = route_handler
- self._parameters: dict[str, Parameter] = {}
+ self._parameters: dict[tuple[str, str], Parameter] = {}
def add(self, parameter: Parameter) -> None:
"""Add a ``Parameter`` to the collection.
@@ -50,18 +50,18 @@ def add(self, parameter: Parameter) -> None:
``ImproperlyConfiguredException``.
"""
- if parameter.name not in self._parameters:
+ if (parameter.name, parameter.param_in) not in self._parameters:
# because we are defining routes as unique per path, we have to handle here a situation when there is an optional
# path parameter. e.g. get(path=["/", "/{param:str}"]). When parsing the parameter for path, the route handler
# would still have a kwarg called param:
# def handler(param: str | None) -> ...
if parameter.param_in != ParamType.QUERY or all(
- "{" + parameter.name + ":" not in path for path in self.route_handler.paths
+ f"{{{parameter.name}:" not in path for path in self.route_handler.paths
):
- self._parameters[parameter.name] = parameter
+ self._parameters[(parameter.name, parameter.param_in)] = parameter
return
- pre_existing = self._parameters[parameter.name]
+ pre_existing = self._parameters[(parameter.name, parameter.param_in)]
if parameter == pre_existing:
return
@@ -206,13 +206,13 @@ def create_parameter_for_handler(
dependency_providers = route_handler.resolve_dependencies()
layered_parameters = route_handler.resolve_layered_parameters()
- unique_handler_fields = tuple(
+ unique_handler_fields = (
(k, v) for k, v in handler_fields.items() if k not in RESERVED_KWARGS and k not in layered_parameters
)
- unique_layered_fields = tuple(
+ unique_layered_fields = (
(k, v) for k, v in layered_parameters.items() if k not in RESERVED_KWARGS and k not in handler_fields
)
- intersection_fields = tuple(
+ intersection_fields = (
(k, v) for k, v in handler_fields.items() if k not in RESERVED_KWARGS and k in layered_parameters
)
| diff --git a/tests/unit/test_openapi/test_integration.py b/tests/unit/test_openapi/test_integration.py
--- a/tests/unit/test_openapi/test_integration.py
+++ b/tests/unit/test_openapi/test_integration.py
@@ -1,17 +1,19 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Generic, Optional, TypeVar
+from typing import Generic, Optional, TypeVar, cast
import msgspec
import pytest
import yaml
from typing_extensions import Annotated
-from litestar import Controller, get, post
+from litestar import Controller, Litestar, get, post
from litestar.app import DEFAULT_OPENAPI_CONFIG
from litestar.enums import MediaType, OpenAPIMediaType, ParamType
from litestar.openapi import OpenAPIConfig, OpenAPIController
+from litestar.openapi.spec import Parameter as OpenAPIParameter
+from litestar.params import Parameter
from litestar.serialization.msgspec_hooks import decode_json, encode_json, get_serializer
from litestar.status_codes import HTTP_200_OK, HTTP_404_NOT_FOUND
from litestar.testing import create_test_client
@@ -291,3 +293,32 @@ def handler_foo_int() -> Foo[int]:
}
},
}
+
+
+def test_allow_multiple_parameters_with_same_name_but_different_location() -> None:
+ """Test that we can support params with the same name if they are in different locations, e.g., cookie and header.
+
+ https://github.com/litestar-org/litestar/issues/2662
+ """
+
+ @post("/test")
+ async def route(
+ name: Annotated[Optional[str], Parameter(cookie="name")] = None, # noqa: UP007
+ name_header: Annotated[Optional[str], Parameter(header="name")] = None, # noqa: UP007
+ ) -> str:
+ return name or name_header or ""
+
+ app = Litestar(route_handlers=[route], debug=True)
+ assert app.openapi_schema.paths is not None
+ schema = app.openapi_schema
+ paths = schema.paths
+ assert paths is not None
+ path = paths["/test"]
+ assert path.post is not None
+ parameters = path.post.parameters
+ assert parameters is not None
+ assert len(parameters) == 2
+ assert all(isinstance(param, OpenAPIParameter) for param in parameters)
+ params = cast("list[OpenAPIParameter]", parameters)
+ assert all(param.name == "name" for param in params)
+ assert tuple(param.param_in for param in params) == ("cookie", "header")
| Bug: Routes with duplicate parameter names are not shown in OpenAPI rendering
### Description
OpenAPI schema fails to generate if there's 2 parameters present with identical name, route is subsequently removed from OpenAPI schema.
### URL to code causing the issue
_No response_
### MCVE
```python
from typing import Annotated
from litestar import Litestar, post
from litestar.params import Parameter
@post("/test")
async def route(
name: Annotated[str | None, Parameter(cookie="name")] = None,
name_header: Annotated[str | None, Parameter(header="name")] = None,
) -> str:
return name or name_header or ""
app = Litestar(
route_handlers=[route],
)
```
### Steps to reproduce
```bash
1. Launch uvicorn server `uvicorn app:app`
2. Go to http://127.0.0.1:8000/schema/swagger
3. See error
```
### Screenshots
_No response_
### Logs
```bash
$ uvicorn app:app
INFO: Started server process [8376]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:54807 - "GET /schema/swagger HTTP/1.1" 500 Internal Server Error
INFO: 127.0.0.1:54807 - "GET /schema/swagger HTTP/1.1" 200 OK
```
### Litestar Version
2.3.2
### Platform
- [ ] Linux
- [ ] Mac
- [X] Windows
- [ ] Other (Please specify in the description above)
| Changed the title to be more descriptive of the actual issue. The routes continue to work, it's just that they are not shown on any OpenAPI renderers (swagger, elements etc) after the first load which raises the following exception (not attaching the stack trace).
```
500: OpenAPI schema generation for handler `app.route` detected multiple parameters named 'name' with different types.
```
Related PR (???) - https://github.com/litestar-org/litestar/pull/129
I should have originally attached stacktrace, but I'm fairly new to litestar and didn't know how to configure debug/logging options 🙂
Also on first request `openapi.json` returns status code 500 🤔
> I should have originally attached stacktrace, but I'm fairly new to litestar and didn't know how to configure debug/logging options 🙂
No worries 🙂 I just do `app = Litestar(route_handlers=[route], debug=True)` and run the app.
> Also on first request `openapi.json` returns status code 500 🤔
This is not limited to your issue per se, most issues in the schema generation exhibit the same behavior, it sort of gets "cached" which is why you only see the error on the first try and only the "non erroneous" working schema from the second. | 2023-11-28T12:38:05 |
litestar-org/litestar | 2,789 | litestar-org__litestar-2789 | [
"2779"
] | 84710a1d657ccc95c9854eb6536eadd117642a6a | diff --git a/litestar/handlers/base.py b/litestar/handlers/base.py
--- a/litestar/handlers/base.py
+++ b/litestar/handlers/base.py
@@ -7,6 +7,7 @@
from litestar._signature import SignatureModel
from litestar.config.app import ExperimentalFeatures
from litestar.di import Provide
+from litestar.dto import DTOData
from litestar.exceptions import ImproperlyConfiguredException
from litestar.serialization import default_deserializer, default_serializer
from litestar.types import (
@@ -526,6 +527,15 @@ def on_registration(self, app: Litestar) -> None:
def _validate_handler_function(self) -> None:
"""Validate the route handler function once set by inspecting its return annotations."""
+ if (
+ self.parsed_data_field is not None
+ and self.parsed_data_field.is_subclass_of(DTOData)
+ and not self.resolve_data_dto()
+ ):
+ raise ImproperlyConfiguredException(
+ f"Handler function {self.handler_name} has a data parameter that is a subclass of DTOData but no "
+ "DTO has been registered for it."
+ )
def __str__(self) -> str:
"""Return a unique identifier for the route handler.
| diff --git a/tests/unit/test_handlers/test_base_handlers/test_validations.py b/tests/unit/test_handlers/test_base_handlers/test_validations.py
--- a/tests/unit/test_handlers/test_base_handlers/test_validations.py
+++ b/tests/unit/test_handlers/test_base_handlers/test_validations.py
@@ -1,5 +1,9 @@
+from dataclasses import dataclass
+
import pytest
+from litestar import Litestar, post
+from litestar.dto import DTOData
from litestar.exceptions import ImproperlyConfiguredException
from litestar.handlers.base import BaseRouteHandler
@@ -9,3 +13,19 @@ def test_raise_no_fn_validation() -> None:
with pytest.raises(ImproperlyConfiguredException):
handler.fn
+
+
+def test_dto_data_annotation_with_no_resolved_dto() -> None:
+ @dataclass
+ class Model:
+ """Example dataclass model."""
+
+ hello: str
+
+ @post("/")
+ async def async_hello_world(data: DTOData[Model]) -> Model:
+ """Route Handler that outputs hello world."""
+ return data.create_instance()
+
+ with pytest.raises(ImproperlyConfiguredException):
+ Litestar(route_handlers=[async_hello_world])
| Bug: late failure where `DTOData` is used without a DTO
### Description
Identified in this issue in fullstack: https://github.com/litestar-org/litestar-fullstack/issues/105#issue-2012835424
Where a `DTOData` annotation is applied to a route without a DTO, we should raise a configuration error.
The linked issue reported a cryptic error during typescript generation, but it also appears to fail with a 400 at request time upon POST request.
We should detect this early and raise an error.
### MCVE
```python
"""Minimal Litestar application."""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from litestar import Litestar, post
if TYPE_CHECKING:
from litestar.dto import DTOData
__all__ = ("async_hello_world",)
@dataclass
class Model:
"""Example dataclass model."""
hello: str
@post("/")
async def async_hello_world(data: DTOData[Model]) -> Model:
"""Route Handler that outputs hello world."""
return data.create_instance()
app = Litestar(route_handlers=[async_hello_world])
```
response from post request
```json
{
"status_code": 400,
"detail": "Validation failed for POST http://localhost:8000/",
"extra": [
{
"message": "Subscripted generics cannot be used with class and instance checks",
"key": "data",
"source": "body"
}
]
}
```
### Litestar Version
2.4
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2779">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2779/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2779/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-11-28T13:19:52 |
|
litestar-org/litestar | 2,810 | litestar-org__litestar-2810 | [
"2809"
] | b3de259cfc755b0f7411f35fcd8a41692f7eec6e | diff --git a/litestar/events/emitter.py b/litestar/events/emitter.py
--- a/litestar/events/emitter.py
+++ b/litestar/events/emitter.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import logging
import math
import sys
from abc import ABC, abstractmethod
@@ -17,9 +18,6 @@
from litestar.exceptions import ImproperlyConfiguredException
-__all__ = ("BaseEventEmitterBackend", "SimpleEventEmitter")
-
-
if TYPE_CHECKING:
from types import TracebackType
@@ -27,6 +25,10 @@
from litestar.events.listener import EventListener
+__all__ = ("BaseEventEmitterBackend", "SimpleEventEmitter")
+
+logger = logging.getLogger(__name__)
+
class BaseEventEmitterBackend(AsyncContextManager["BaseEventEmitterBackend"], ABC):
"""Abstract class used to define event emitter backends."""
@@ -77,19 +79,25 @@ def __init__(self, listeners: Sequence[EventListener]) -> None:
self._send_stream: MemoryObjectSendStream | None = None
self._exit_stack: AsyncExitStack | None = None
- @staticmethod
- async def _worker(receive_stream: MemoryObjectReceiveStream) -> None:
+ async def _worker(self, receive_stream: MemoryObjectReceiveStream) -> None:
"""Run items from ``receive_stream`` in a task group.
Returns:
None
"""
- async with receive_stream, anyio.create_task_group() as task_group:
+ async with receive_stream:
async for item in receive_stream:
- fn, args, kwargs = item
+ await self._run_listener_in_task_group(*item)
+
+ @staticmethod
+ async def _run_listener_in_task_group(fn: Any, args: tuple[Any], kwargs: dict[str, Any]) -> None:
+ try:
+ async with anyio.create_task_group() as task_group:
if kwargs:
fn = partial(fn, **kwargs)
task_group.start_soon(fn, *args)
+ except Exception as exc:
+ logger.exception("Error in event listener: %s", exc)
async def __aenter__(self) -> SimpleEventEmitter:
self._exit_stack = AsyncExitStack()
| diff --git a/tests/unit/test_events.py b/tests/unit/test_events.py
--- a/tests/unit/test_events.py
+++ b/tests/unit/test_events.py
@@ -109,3 +109,36 @@ async def test_raises_when_not_listener_are_registered_for_an_event_id(async_lis
with create_test_client(route_handlers=[], listeners=[async_listener]) as client:
with pytest.raises(ImproperlyConfiguredException):
client.app.emit("x")
+
+
+async def test_event_listener_raises_exception(async_listener: EventListener, mock: MagicMock) -> None:
+ """Test that an event listener that raises an exception does not prevent other listeners from being called.
+
+ https://github.com/litestar-org/litestar/issues/2809
+ """
+
+ error_mock = MagicMock()
+
+ @listener("error_event")
+ async def raising_listener(*args: Any, **kwargs: Any) -> None:
+ error_mock()
+ raise ValueError("test")
+
+ @get("/error")
+ def route_handler_1(request: Request[Any, Any, Any]) -> None:
+ request.app.emit("error_event")
+
+ @get("/no-error")
+ def route_handler_2(request: Request[Any, Any, Any]) -> None:
+ request.app.emit("test_event")
+
+ with create_test_client(
+ route_handlers=[route_handler_1, route_handler_2], listeners=[async_listener, raising_listener]
+ ) as client:
+ first_response = client.get("/error")
+ second_response = client.get("/no-error")
+ assert first_response.status_code == HTTP_200_OK
+ assert second_response.status_code == HTTP_200_OK
+
+ error_mock.assert_called()
+ mock.assert_called()
| Bug: Exception in event listener breaks listener
### Description
In a separate production code base, we encountered what I believe to be an issue/behavior that could be fixed/improved and did not find anything other references of it when searching the issues here.
Basically, if an exception occurs inside of an event listener you will then see
```log
INFO: ASGI 'lifespan' protocol appears unsupported.
```
and the listener stream is closed which then prevents any additional events from being picked up. Any time `request.app.emit` is then called you will get `ClosedResourceError`.
I don't think a single exception inside an event execution should prevent all future events from getting picked up or at least the error should be a little more obvious as to what is going on.
I've created an example repo that recreates the issue consistently.
### URL to code causing the issue
https://github.com/bnjmn/litestar-emit-fail-example
### MCVE
See [full example here](https://github.com/bnjmn/litestar-emit-fail-example/tree/main)
```python
from litestar import Litestar, get, Request
from litestar.events import listener
import logging
logger = logging.getLogger(__name__)
@listener("raise_exception")
async def raise_exception_if_odd(value) -> None:
"""Raise an exception to test Emit error."""
if value is not None and value % 2 != 0:
raise ValueError(f"{value} is odd")
else:
return "The value is even. No exception raised."
@get("/")
async def index() -> str:
return "Hello, world!"
@get("/check-value/{value:int}")
async def check_value(request: Request, value: int) -> str:
try:
request.app.emit("raise_exception", value)
return f"Checked {value}: No exception raised."
except ValueError as e:
return str(e)
app = Litestar([index, check_value], listeners=[raise_exception_if_odd])
```
### Steps to reproduce
1. Follow the steps outlined in the [README](https://github.com/bnjmn/litestar-emit-fail-example/blob/main/README.md#run-it)
```bash
pipenv install
litestar run -d
```
- Go to http://localhost:8000/check-value/2 to see a successful request
- Go to http://localhost:8000/check-value/3 to see an exception raised in the listener
- Attempt to go to http://localhost:8000/check-value/2 again, but you should get ClosedResourceError
### Litestar Version
Recreated on both 2.3.2 and 2.4.1
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [x] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2809">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2809/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2809/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| ```
INFO: Started server process [2169882]
INFO: Waiting for application startup.
TRACE: ASGI [1] Started scope={'type': 'lifespan', 'asgi': {'version': '3.0', 'spec_version': '2.0'}, 'state': {}}
TRACE: ASGI [1] Receive {'type': 'lifespan.startup'}
TRACE: ASGI [1] Send {'type': 'lifespan.startup.complete'}
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
TRACE: 127.0.0.1:58366 - HTTP connection made
TRACE: 127.0.0.1:58366 - ASGI [2] Started scope={'type': 'http', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'server': ('127.0.0.1', 8000), 'client': ('127.0.0.1', 58366), 'scheme': 'http', 'root_path': '', 'headers': '<...>', 'state': {}, 'method': 'GET', 'path': '/check-value/2', 'raw_path': b'/check-value/2', 'query_string': b''}
TRACE: 127.0.0.1:58366 - ASGI [2] Send {'type': 'http.response.start', 'status': 200, 'headers': '<...>'}
INFO: 127.0.0.1:58366 - "GET /check-value/2 HTTP/1.1" 200 OK
TRACE: 127.0.0.1:58366 - ASGI [2] Send {'type': 'http.response.body', 'body': '<31 bytes>', 'more_body': False}
TRACE: 127.0.0.1:58366 - ASGI [2] Completed
TRACE: 127.0.0.1:58366 - HTTP connection lost
TRACE: 127.0.0.1:41920 - HTTP connection made
TRACE: 127.0.0.1:41920 - ASGI [3] Started scope={'type': 'http', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'server': ('127.0.0.1', 8000), 'client': ('127.0.0.1', 41920), 'scheme': 'http', 'root_path': '', 'headers': '<...>', 'state': {}, 'method': 'GET', 'path': '/check-value/3', 'raw_path': b'/check-value/3', 'query_string': b''}
TRACE: 127.0.0.1:41920 - ASGI [3] Send {'type': 'http.response.start', 'status': 200, 'headers': '<...>'}
INFO: 127.0.0.1:41920 - "GET /check-value/3 HTTP/1.1" 200 OK
TRACE: 127.0.0.1:41920 - ASGI [3] Send {'type': 'http.response.body', 'body': '<31 bytes>', 'more_body': False}
TRACE: 127.0.0.1:41920 - ASGI [3] Completed
TRACE: ASGI [1] Send {'type': 'lifespan.startup.failed', 'message': 'Traceback (most recent call last):\n File "/home/peter/PycharmProjects/litestar/litestar/app.py", line 574, in lifespan\n yield\n File "/home/peter/PycharmProjects/litestar/litestar/_asgi/asgi_router.py", line 164, in lifespan\n message = await receive()\n File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/uvicorn/middleware/message_logger.py", line 60, in inner_receive\n message = await receive()\n File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/uvicorn/lifespan/on.py", line 137, in receive\n return await self.receive_queue.get()\n File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/asyncio/queues.py", line 163, in get\n await getter\nasyncio.exceptions.CancelledError\n\nDuring handling of the above exception, another exception occurred:\n\n + Exception Group Traceback (most recent call last):\n | File "/home/peter/PycharmProjects/litestar/litestar/_asgi/asgi_router.py", line 164, in lifespan\n | message = await receive()\n | File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 189, in __aexit__\n | await self.gen.athrow(typ, value, traceback)\n | File "/home/peter/PycharmProjects/litestar/litestar/app.py", line 574, in lifespan\n | yield\n | File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 679, in __aexit__\n | raise exc_details[1]\n | File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 662, in __aexit__\n | cb_suppress = await cb(*exc_details)\n | File "/home/peter/PycharmProjects/litestar/litestar/events/emitter.py", line 113, in __aexit__\n | await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)\n | File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 679, in __aexit__\n | raise exc_details[1]\n | File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 662, in __aexit__\n | cb_suppress = await cb(*exc_details)\n | File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 664, in __aexit__\n | raise BaseExceptionGroup(\n | exceptiongroup.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)\n +-+---------------- 1 ----------------\n | Traceback (most recent call last):\n | File "/home/peter/PycharmProjects/litestar/litestar/events/emitter.py", line 88, in _worker\n | async for item in receive_stream:\n | File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/abc/_streams.py", line 35, in __anext__\n | return await self.receive()\n | File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/streams/memory.py", line 105, in receive\n | await receive_event.wait()\n | File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 1621, in wait\n | await self._event.wait()\n | File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/asyncio/locks.py", line 309, in wait\n | await fut\n | asyncio.exceptions.CancelledError\n | \n | During handling of the above exception, another exception occurred:\n | \n | Exception Group Traceback (most recent call last):\n | File "/home/peter/PycharmProjects/litestar/litestar/events/emitter.py", line 92, in _worker\n | task_group.start_soon(fn, *args)\n | File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 664, in __aexit__\n | raise BaseExceptionGroup(\n | exceptiongroup.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)\n +-+---------------- 1 ----------------\n | Traceback (most recent call last):\n | File "/home/peter/PycharmProjects/litestar-hello-world/app.py", line 12, in raise_exception_if_odd\n | raise ValueError(f"{value} is odd")\n | ValueError: 3 is odd\n +------------------------------------\n'}
TRACE: ASGI [1] Raised exception
INFO: ASGI 'lifespan' protocol appears unsupported.
TRACE: 127.0.0.1:41920 - HTTP connection lost
```
Thanks for the excellent reproduction!
Nicer exception formatting:
```python
Traceback (most recent call last):
File "/home/peter/PycharmProjects/litestar/litestar/app.py", line 574, in lifespan
yield
File "/home/peter/PycharmProjects/litestar/litestar/_asgi/asgi_router.py", line 164, in lifespan
message = await receive()
File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/uvicorn/middleware/message_logger.py", line 60, in inner_receive
message = await receive()
File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/uvicorn/lifespan/on.py", line 137, in receive
return await self.receive_queue.get()
File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/asyncio/queues.py", line 163, in get
await getter
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
+ Exception Group Traceback (most recent call last):
| File "/home/peter/PycharmProjects/litestar/litestar/_asgi/asgi_router.py", line 164, in lifespan
| message = await receive()
| File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 189, in __aexit__
| await self.gen.athrow(typ, value, traceback)
| File "/home/peter/PycharmProjects/litestar/litestar/app.py", line 574, in lifespan
| yield
| File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 679, in __aexit__
| raise exc_details[1]
| File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 662, in __aexit__
| cb_suppress = await cb(*exc_details)
| File "/home/peter/PycharmProjects/litestar/litestar/events/emitter.py", line 113, in __aexit__
| await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
| File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 679, in __aexit__
| raise exc_details[1]
| File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/contextlib.py", line 662, in __aexit__
| cb_suppress = await cb(*exc_details)
| File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 664, in __aexit__
| raise BaseExceptionGroup(
| exceptiongroup.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "/home/peter/PycharmProjects/litestar/litestar/events/emitter.py", line 88, in _worker
| async for item in receive_stream:
| File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/abc/_streams.py", line 35, in __anext__
| return await self.receive()
| File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/streams/memory.py", line 105, in receive
| await receive_event.wait()
| File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 1621, in wait
| await self._event.wait()
| File "/home/peter/.pyenv/versions/3.8.18/lib/python3.8/asyncio/locks.py", line 309, in wait
| await fut
| asyncio.exceptions.CancelledError
|
| During handling of the above exception, another exception occurred:
|
| Exception Group Traceback (most recent call last):
| File "/home/peter/PycharmProjects/litestar/litestar/events/emitter.py", line 92, in _worker
| task_group.start_soon(fn, *args)
| File "/home/peter/.local/share/pdm/venvs/litestar-hello-world-qe1MW6VZ-3.8/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 664, in __aexit__
| raise BaseExceptionGroup(
| exceptiongroup.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "/home/peter/PycharmProjects/litestar-hello-world/app.py", line 12, in raise_exception_if_odd
| raise ValueError(f"{value} is odd")
| ValueError: 3 is odd
+------------------------------------
``` | 2023-11-30T23:08:18 |
litestar-org/litestar | 2,818 | litestar-org__litestar-2818 | [
"2812"
] | cbb54d0d8c555b1a08bca07bab05cd9a92254283 | diff --git a/litestar/_openapi/schema_generation/schema.py b/litestar/_openapi/schema_generation/schema.py
--- a/litestar/_openapi/schema_generation/schema.py
+++ b/litestar/_openapi/schema_generation/schema.py
@@ -58,6 +58,7 @@
from litestar.params import BodyKwarg, ParameterKwarg
from litestar.plugins import OpenAPISchemaPlugin
from litestar.types import Empty
+from litestar.types.builtin_types import NoneType
from litestar.typing import FieldDefinition
from litestar.utils.helpers import get_name
from litestar.utils.predicates import (
@@ -116,6 +117,7 @@
MutableMapping: Schema(type=OpenAPIType.OBJECT),
MutableSequence: Schema(type=OpenAPIType.ARRAY),
None: Schema(type=OpenAPIType.NULL),
+ NoneType: Schema(type=OpenAPIType.NULL),
OrderedDict: Schema(type=OpenAPIType.OBJECT),
Path: Schema(type=OpenAPIType.STRING, format=OpenAPIFormat.URI),
Pattern: Schema(type=OpenAPIType.STRING, format=OpenAPIFormat.REGEX),
@@ -146,6 +148,29 @@
}
+def _types_in_list(lst: list[Any]) -> list[OpenAPIType] | OpenAPIType:
+ """Extract unique OpenAPITypes present in the values of a list.
+
+ Args:
+ lst: A list of values
+
+ Returns:
+ OpenAPIType in the given list. If more then one exists, return
+ a list of OpenAPITypes.
+ """
+ schema_types: list[OpenAPIType] = []
+ for item in lst:
+ schema_type = TYPE_MAP[type(item)].type
+ if isinstance(schema_type, OpenAPIType):
+ schema_types.append(schema_type)
+ elif schema_type is None:
+ raise RuntimeError("Item in TYPE_MAP must have a type that is not None")
+ else:
+ schema_types.extend(schema_type)
+ schema_types = list(set(schema_types))
+ return schema_types[0] if len(schema_types) == 1 else schema_types
+
+
def _get_type_schema_name(field_definition: FieldDefinition) -> str:
"""Extract the schema name from a data container.
@@ -178,10 +203,9 @@ def create_enum_schema(annotation: EnumMeta, include_null: bool = False) -> Sche
A schema instance.
"""
enum_values: list[str | int | None] = [v.value for v in annotation] # type: ignore
- if include_null:
+ if include_null and None not in enum_values:
enum_values.append(None)
- openapi_type = OpenAPIType.STRING if isinstance(enum_values[0], str) else OpenAPIType.INTEGER
- return Schema(type=openapi_type, enum=enum_values)
+ return Schema(type=_types_in_list(enum_values), enum=enum_values)
def _iter_flat_literal_args(annotation: Any) -> Iterable[Any]:
@@ -211,9 +235,9 @@ def create_literal_schema(annotation: Any, include_null: bool = False) -> Schema
A schema instance.
"""
args = list(_iter_flat_literal_args(annotation))
- if include_null:
+ if include_null and None not in args:
args.append(None)
- schema = copy(TYPE_MAP[type(args[0])])
+ schema = Schema(type=_types_in_list(args))
if len(args) > 1:
schema.enum = args
else:
| diff --git a/tests/unit/test_openapi/test_schema.py b/tests/unit/test_openapi/test_schema.py
--- a/tests/unit/test_openapi/test_schema.py
+++ b/tests/unit/test_openapi/test_schema.py
@@ -466,14 +466,16 @@ class Foo(Enum):
schema = SchemaCreator().for_field_definition(FieldDefinition.from_annotation(Optional[Foo]))
assert isinstance(schema, Schema)
- assert schema.type == OpenAPIType.INTEGER
+ assert schema.type is not None
+ assert set(schema.type) == {OpenAPIType.INTEGER, OpenAPIType.NULL}
assert schema.enum == [1, 2, None]
def test_optional_literal() -> None:
schema = SchemaCreator().for_field_definition(FieldDefinition.from_annotation(Optional[Literal[1]]))
assert isinstance(schema, Schema)
- assert schema.type == OpenAPIType.INTEGER
+ assert schema.type is not None
+ assert set(schema.type) == {OpenAPIType.INTEGER, OpenAPIType.NULL}
assert schema.enum == [1, None]
| Bug: Incorrect OpenAPI Generated For Optional Literal Types
### Description
Incorrect OpenAPI schema is generated when any Optional[Literal[<types>]] annotation is present on any route interface, even on a nested member of a struct. For example,
``` py
type: Literal["sink", "source"] | None
```
converts into
``` json
{
"name": "type",
"in": "query",
"schema": {
"type": "string",
"enum": [
"sink",
"source",
null
]
},
"required": false,
"deprecated": false,
"allowEmptyValue": false,
"allowReserved": false
}
```
which does not support the null type, and
``` py
include_properties: Literal["sink", "source", None] = None
```
generates
``` json
{
"name": "include_properties",
"in": "query",
"schema": {
"type": "string",
"enum": [
"sink",
"source",
null,
null
]
},
"required": false,
"deprecated": false,
"allowEmptyValue": false,
"allowReserved": false
}
```
### URL to code causing the issue
_No response_
### MCVE
```python
from typing import Literal
import msgspec
from litestar import get, Litestar
class AudioDevice(msgspec.Struct):
form_factor: Literal[
"car",
"computer",
"hands-free",
"handset",
"headphone",
"headset",
"hifi",
"internal",
"microphone",
"portable",
"speaker",
"tv",
"webcam",
None,
]
@get("/api1", sync_to_thread=False)
def api1(
type: Literal["sink", "source"] | None, include_properties: Literal["sink", "source", None] = None
) -> AudioDevice:
pass
app = Litestar(route_handlers=[api1])
```
### Steps to reproduce
```bash
1. Run MCVE
2. View generated JSON Schema, attached below for convenience
{
"info": {
"title": "Litestar API",
"version": "1.0.0"
},
"openapi": "3.1.0",
"servers": [
{
"url": "/"
}
],
"paths": {
"/api1": {
"get": {
"summary": "Api1",
"operationId": "Api1Api1",
"parameters": [
{
"name": "type",
"in": "query",
"schema": {
"type": "string",
"enum": [
"sink",
"source",
null
]
},
"required": false,
"deprecated": false,
"allowEmptyValue": false,
"allowReserved": false
},
{
"name": "include_properties",
"in": "query",
"schema": {
"type": "string",
"enum": [
"sink",
"source",
null,
null
]
},
"required": false,
"deprecated": false,
"allowEmptyValue": false,
"allowReserved": false
}
],
"responses": {
"200": {
"description": "Request fulfilled, document follows",
"headers": {},
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/app_AudioDevice"
}
}
}
},
"400": {
"description": "Bad request syntax or unsupported method",
"content": {
"application/json": {
"schema": {
"properties": {
"status_code": {
"type": "integer"
},
"detail": {
"type": "string"
},
"extra": {
"additionalProperties": {},
"type": [
"null",
"object",
"array"
]
}
},
"type": "object",
"required": [
"detail",
"status_code"
],
"description": "Validation Exception",
"examples": {
"ValidationException": {
"value": {
"status_code": 400,
"detail": "Bad Request",
"extra": {}
}
}
}
}
}
}
}
},
"deprecated": false
}
}
},
"components": {
"schemas": {
"app_AudioDevice": {
"properties": {
"form_factor": {
"type": "string",
"enum": [
"car",
"computer",
"hands-free",
"handset",
"headphone",
"headset",
"hifi",
"internal",
"microphone",
"portable",
"speaker",
"tv",
"webcam",
null
]
}
},
"type": "object",
"required": [
"form_factor"
],
"title": "AudioDevice"
}
}
}
}
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.4.1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2812">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2812/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2812/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| This seems relatively easy to fix, I'll open a PR?
Sure thing @hzhou0 - be sure to include tests please. | 2023-12-02T01:09:03 |
litestar-org/litestar | 2,854 | litestar-org__litestar-2854 | [
"2149"
] | 8f2cbe630ad9d71521f0477c6f0a3c0ed1c9a4a5 | diff --git a/litestar/_signature/model.py b/litestar/_signature/model.py
--- a/litestar/_signature/model.py
+++ b/litestar/_signature/model.py
@@ -252,6 +252,7 @@ def create(
field_definition=field_definition,
type_decoders=[*(type_decoders or []), *DEFAULT_TYPE_DECODERS],
meta_data=meta_data,
+ data_dto=data_dto,
)
default = field_definition.default if field_definition.has_default else NODEFAULT
@@ -277,7 +278,12 @@ def _create_annotation(
field_definition: FieldDefinition,
type_decoders: TypeDecodersSequence,
meta_data: Meta | None = None,
+ data_dto: type[AbstractDTO] | None = None,
) -> Any:
+ # DTOs have already validated their data, so we can just use Any here
+ if field_definition.name == "data" and data_dto:
+ return Any
+
annotation = _normalize_annotation(field_definition=field_definition)
if annotation is Any:
| diff --git a/tests/unit/test_signature/test_parsing.py b/tests/unit/test_signature/test_parsing.py
--- a/tests/unit/test_signature/test_parsing.py
+++ b/tests/unit/test_signature/test_parsing.py
@@ -1,12 +1,15 @@
+from dataclasses import dataclass
from types import ModuleType
from typing import Any, Callable, Iterable, List, Optional, Sequence, Union
from unittest.mock import MagicMock
+import msgspec
import pytest
from typing_extensions import Annotated
from litestar import get
from litestar._signature import SignatureModel
+from litestar.dto import DataclassDTO
from litestar.params import Body, Parameter
from litestar.status_codes import HTTP_200_OK, HTTP_204_NO_CONTENT
from litestar.testing import TestClient, create_test_client
@@ -181,3 +184,30 @@ def handler(param: annotation) -> None: # pyright: ignore
response = client.get("/?param=foo¶m=bar¶m=123")
assert response.status_code == 500
assert "TypeError: Type unions may not contain more than one array-like" in response.text
+
+
+def test_dto_data_typed_as_any() -> None:
+ """DTOs already validate the payload, we don't need the signature model to do it too.
+
+ https://github.com/litestar-org/litestar/issues/2149
+ """
+
+ @dataclass
+ class Test:
+ a: str
+
+ dto = DataclassDTO[Test]
+
+ def fn(data: Test) -> None:
+ pass
+
+ model = SignatureModel.create(
+ dependency_name_set=set(),
+ fn=fn,
+ data_dto=dto,
+ parsed_signature=ParsedSignature.from_fn(fn, signature_namespace={"Test": Test}),
+ type_decoders=[],
+ )
+ (field,) = msgspec.structs.fields(model)
+ assert field.name == "data"
+ assert field.type is Any
| Bug: SQA MappedAsDataclass breaks DTO for request body?
### Description
Started encountering undefined name errors with the SQA DTO when using the `MappedAsDataclass` mixin, but only for routes where the DTO annotated type is the request data.
Only having the type in the return annotation works fine.
(Excerpt from my reproduction repo) With an ORM such as this
```python
from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass
class Base(MappedAsDataclass, DeclarativeBase):
...
class Post(Base):
...
```
Routes without a DTO base request body work fine:
```python
@get( "{id:int}", return_dto=PostDTOs.one)
async def fetch_one(id: int, *, session: Session) -> Post:
...
```
But routes like a create or update do not:
```python
@post("/create" dto=PostDTOs.partial, return_dto=PostDTOs.one)
async def create(*, data: Post, session: Session) -> Post:
...
@patch("/update", dto=PostDTOs.partial, return_dto=PostDTOs.one)
async def update(id: int, *, data: Post, session: Session) -> Post:
...
```
```
File "/Users/.../.pyenv/versions/3.11.1/lib/python3.11/typing.py", line 854, in _evaluate
eval(self.__forward_code__, globalns, localns),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 1, in <module>
NameError: name 'User' is not defined
```
I've created a minimalish repo for testing that reproduces this but thought I'd check here before opening an issue.
https://github.com/nilsso/litestar-test-repro/blob/main/litestar_test/orm/base.py#L7-L12
### URL to code causing the issue
https://github.com/nilsso/litestar-test-repro
### MCVE
_No response_
### Steps to reproduce
- Clone the reproduction repo
- `poetry install`
- `poetry shell`
- `litestar --app litestar_test.app:app run --reload --debug`
- Navigate to <http://localhost:8000/schema/elements#/operations/PostUpdateUpdate>
- Try updating a post
- ID: `1`
- Body: `{ "title": "foo" }`
### Screenshots
_No response_
### Logs
```
ERROR - 2023-08-11 13:29:26,190 - litestar - config - exception raised on http connection to route /post/update
Traceback (most recent call last):
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 174, in __call__
await self.app(scope, receive, send)
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/msgspec/_utils.py", line 209, in get_dataclass_info
hints = get_class_annotations(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/msgspec/_utils.py", line 131, in get_class_annotations
value = typing._eval_type(value, cls_locals, cls_globals)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../.pyenv/versions/3.11.1/lib/python3.11/typing.py", line 359, in _eval_type
return t._evaluate(globalns, localns, recursive_guard)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../.pyenv/versions/3.11.1/lib/python3.11/typing.py", line 854, in _evaluate
eval(self.__forward_code__, globalns, localns),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 1, in <module>
NameError: name 'User' is not defined
Traceback (most recent call last):
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/middleware/exceptions/middleware.py", line 174, in __call__
await self.app(scope, receive, send)
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/routes/http.py", line 79, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/routes/http.py", line 131, in _get_response_for_request
response = await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/routes/http.py", line 160, in _call_handler_function
response_data, cleanuINFO: 127.0.0.1:62502 - "PATCH /post/update?id=1 HTTP/1.1" 500 Internal Server Error
p_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/routes/http.py", line 194, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/msgspec/_utils.py", line 209, in get_dataclass_info
hints = get_class_annotations(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/msgspec/_utils.py", line 131, in get_class_annotations
value = typing._eval_type(value, cls_locals, cls_globals)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../.pyenv/versions/3.11.1/lib/python3.11/typing.py", line 359, in _eval_type
return t._evaluate(globalns, localns, recursive_guard)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../.pyenv/versions/3.11.1/lib/python3.11/typing.py", line 854, in _evaluate
eval(self.__forward_code__, globalns, localns),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 1, in <module>
NameError: name 'User' is not defined
```
### Litestar Version
2.0.0rc1 (directly from main branch)
### Platform
- [X] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
## Funding
* If you would like to see an issue prioritized, make a pledge towards it!
* We receive the pledge once the issue is completed & verified
<a href="https://polar.sh/litestar-org/litestar/issues/2149">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2149/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2149/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Can you provide a stripped down MCVE for this?
The repository you posted is rather involved and does a lot of things that could potentially affect this behaviour. Ideally this would be a single SQLAlchemy model, DTO and route handler which reproduce the behaviour you're encountering.
> Can you provide a stripped down MCVE for this? The repository you posted is rather involved and does a lot of things that could potentially affect this behaviour. Ideally this would be a single SQLAlchemy model, DTO and route handler which reproduce the behaviour you're encountering.
Sorry yeah I'll try to come up with a more minimal example. I'm having a tough time coming up with the sort of partial update route that I'd want, so I'll try to replicate with just a create route.
Okay I think I've got it as stripped down as possible, in two branches. The problem seems to be related to msgspec, forward reference/import related, and only with regards to submodels. So the most minimal I can get it is a `User` model with a `Post` posts relationship.
- [Minimal without imports *works fine*](https://github.com/nilsso/litestar-test-repro/tree/min_no_imports)
- [Minimal *with* imports *breaks*](https://github.com/nilsso/litestar-test-repro/tree/min_with_imports)
To replicate:
1. Clone and checkout branch "min_with_imports"/"min_no_imports".
1. `poetry install`, `poetry shell`
1. Run `litestar --app litestar_test.app:app run --reload --debug`.
[An SQLite database "test.sqlite" will be initialized with a User and a Post.](https://github.com/nilsso/litestar-test-repro/blob/min_no_imports/litestar_test/app.py#L45-L52)
1. Navigate to `http://localhost:8000/schema/elements#/operations/PostCreateCreate`
1. Send API request attempting to create a new Post with user ID 1 (body as follows)
```json
{
"user_id": 1,
"title": "foo"
}
```
In the "without imports" branch works fine. Can go to [fetch many](http://localhost:8000/schema/elements#/operations/PostFetchMany) to check.
In the "with imports" branch breaks with the following error
```
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/litestar/_signature/model.py", line 190, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/msgspec/_utils.py", line 209, in get_dataclass_info
hints = get_class_annotations(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../Library/Caches/pypoetry/virtualenvs/litestar-test-repro-ZjCOeTJE-py3.11/lib/python3.11/site-packages/msgspec/_utils.py", line 131, in get_class_annotations
value = typing._eval_type(value, cls_locals, cls_globals)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../.pyenv/versions/3.11.1/lib/python3.11/typing.py", line 359, in _eval_type
return t._evaluate(globalns, localns, recursive_guard)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/.../.pyenv/versions/3.11.1/lib/python3.11/typing.py", line 854, in _evaluate
eval(self.__forward_code__, globalns, localns),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 1, in <module>
NameError: name 'User' is not defined
```
Can also test the [fetch many](http://localhost:8000/schema/elements#/operations/PostFetchMany) route while in the "with imports" branch to see that it works. Failure seems to be with the create route.
https://docs.litestar.dev/2/usage/routing/handlers.html#signature-namespace
You'll need to add `User` to the signature namespace so the forward reference can be resolved.
Doesn't seem to resolve the issue. I get the same error. It seems to be unique to dataclasses (via `MappedAsDataclass`).
Probably has to do with generated `__init__` from `MappedAsDataclass`, even with `init=False`?
> Doesn't seem to resolve the issue. I get the same error. It seems to be unique to dataclasses (via `MappedAsDataclass`).
>
> Probably has to do with generated `__init__` from `MappedAsDataclass`, even with `init=False`?
Is this an issue on our end of sqla? @nilsso
The error raises when we use `msgspec.convert()` to convert the connection data into the signature model instance.
I haven't confirmed all details of this - particularly the parts pertaining to msgspec internals, but here's my best guess.
https://github.com/litestar-org/litestar/blob/737a45a60e416ff1d96ce1e75b0b97b8f0247d5c/litestar/_signature/model.py#L173-L191
In this function, `kwargs` is the data that has originated from the client which we are parsing/validating per the signature of the handler. Inspecting, we can see:
```py
kwargs.get('data') = Post(title='foo', user_id=1, id=None, user=None)
```
This is as we expect - because the DTO operates before the signature model and has already transformed the raw data into the SQLAlchemy `Post` instance.
Next, I inspected the type of the `data` keyword arg in the signature models fields:
```py
cls.__annotations__.get('data') = <class 'litestar_test.orm.post.Post'>
```
On the signature model we have annotated the type of `data` to `Post` and when `Post` is a dataclass (as in when inheriting from `MappedAsDataclass`) this sends msgspec on a different path to when `Post` is a plain sqlalchemy model, and that path includes inspecting the types of the dataclass. One can only access names that are available in the module scope of the object to be inspected, and given that the `User` name is imported in the `post.py` module in a type checking block:
```py
if TYPE_CHECKING:
from .user import User
```
...that error is thrown from `msgspec._utils.get_class_annotations()`.
In previous incarnations of the signature model, if a handler's `data` kwarg was managed by a DTO, we'd type it as `Any` on the signature model, b/c there is little to gain by having it typed otherwise. The data is already validated and parsed into an instance, so we really just want the signature model to give us back exactly what we gave it.
> In previous incarnations of the signature model, if a handler's `data` kwarg was managed by a DTO, we'd type it as `Any` on the signature model, b/c there is little to gain by having it typed otherwise. The data is already validated and parsed into an instance, so we really just want the signature model to give us back exactly what we gave it.
This is what I'm talking about here: https://github.com/litestar-org/litestar/commit/b9814c2564b25569b59d962e816126347ac4d286#diff-3bd2004653c6a335364eb4f668cab0283ea1c9bffdfc52ae1537f2dbb9e248a3L53-L60
Before https://github.com/litestar-org/litestar/pull/2088 we would type the data parameter on the signature as `Any` if it was managed by a DTO because the DTO is doing the validation, we don't need the signature model to double up on this.. For whatever reason, it was removed.
The exact specifics of this issue is that we leverage sqlalchemy's mapper registry to inject names into the namespace when we resolve type annotations to build the DTO transfer models (happens in advanced-alchemy now days: https://github.com/jolt-org/advanced-alchemy/blob/5da93a2d22ee70777be11a5e27d205d6699cbfae/advanced_alchemy/extensions/litestar/dto.py#L227).
This allows related models to be imported inside `if TYPE_CHECKING:` without error, however, msgspec doesn't have that same luxury.
I.e., in this module from the reproduction repo:
```py
from __future__ import annotations
from typing import TYPE_CHECKING
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
if TYPE_CHECKING:
from .user import User
class Post(Base):
__tablename__ = "post"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True, default=None)
title: Mapped[str]
user_id: Mapped[int] = mapped_column(ForeignKey("user.id"), default=None,)
user: Mapped[User] = relationship(back_populates="posts")
```
...even though the `User` model isn't imported at runtime, we have it in the namespace for resolving type annotations at runtime via the mapper registry.
However, when msgspec tries to inspect the annotations as it validates the `Post` that we pass to `convert()` as part of the signature model instantiation, it cannot find `User` in the module scope b/c it doesn't exist, and we get the failure as above.
The thing is, we already know that the `Post` instance is valid, because we've already validated it with the DTO, and if this wasn't a dataclass, msgspec would just do an `isinstance()` test on it and wave it through. But, because it is a dataclass and msgspec does rich validation on them, it tries to parse the types, and we get the error.
So, if we type `data` as `Any` on the signature model when it is covered by a DTO, then this issue is fixed, but more than that, we should type `data` as `Any` on the signature model because we don't need to validate it twice. | 2023-12-08T10:11:33 |
litestar-org/litestar | 2,864 | litestar-org__litestar-2864 | [
"2863"
] | b02e65e675d8a29d86be90be79b997c79588823c | diff --git a/litestar/_openapi/plugin.py b/litestar/_openapi/plugin.py
--- a/litestar/_openapi/plugin.py
+++ b/litestar/_openapi/plugin.py
@@ -27,7 +27,7 @@ class OpenAPIPlugin(InitPluginProtocol, ReceiveRoutePlugin):
def __init__(self, app: Litestar) -> None:
self.app = app
- self.included_routes: list[HTTPRoute] = []
+ self.included_routes: dict[str, HTTPRoute] = {}
self._openapi_config: OpenAPIConfig | None = None
self._openapi_schema: OpenAPI | None = None
@@ -35,7 +35,8 @@ def _build_openapi_schema(self) -> OpenAPI:
openapi = self.openapi_config.to_openapi_schema()
context = OpenAPIContext(openapi_config=self.openapi_config, plugins=self.app.plugins.openapi)
openapi.paths = {
- route.path_format or "/": create_path_item_for_route(context, route) for route in self.included_routes
+ route.path_format or "/": create_path_item_for_route(context, route)
+ for route in self.included_routes.values()
}
openapi.components.schemas = context.schema_registry.generate_components_schemas()
return openapi
@@ -64,4 +65,4 @@ def receive_route(self, route: BaseRoute) -> None:
if any(route_handler.resolve_include_in_schema() for route_handler, _ in route.route_handler_map.values()):
# Force recompute the schema if a new route is added
self._openapi_schema = None
- self.included_routes.append(route)
+ self.included_routes[route.path] = route
| diff --git a/tests/unit/test_openapi/test_integration.py b/tests/unit/test_openapi/test_integration.py
--- a/tests/unit/test_openapi/test_integration.py
+++ b/tests/unit/test_openapi/test_integration.py
@@ -352,3 +352,22 @@ def handler_b() -> module_b.Model: # type: ignore[name-defined]
f"{module_b.__name__}_Model",
}
# TODO: expand this test to cover more cases
+
+
+def test_multiple_handlers_for_same_route() -> None:
+ @post("/", sync_to_thread=False)
+ def post_handler() -> None:
+ ...
+
+ @get("/", sync_to_thread=False)
+ def get_handler() -> None:
+ ...
+
+ app = Litestar([get_handler, post_handler])
+ openapi_plugin = app.plugins.get(OpenAPIPlugin)
+ openapi = openapi_plugin.provide_openapi()
+
+ assert openapi.paths is not None
+ path_item = openapi.paths["/"]
+ assert path_item.get is not None
+ assert path_item.post is not None
| Bug: OpenAPI schema generation fails due to same operation IDs
### Description
If two routes with the same path, but different methods are defined then the OpenAPI generation fails due to both of them having the same value for operation ID. After running `git bisect`, #2805 seems to have introduced this.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import get, post
from litestar.app import Litestar
from litestar.testing import create_test_client
@post("/")
async def post_handler() -> None:
...
@get("/")
async def get_handler() -> None:
...
with create_test_client([post_handler, get_handler]) as client:
response = client.get("/schema/openapi.json")
assert response.status_code == 200
```
### Steps to reproduce
_No response_
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
HEAD
### Platform
- [ ] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2863">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2863/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2863/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| The reason this is happening is because in the `receive_route` the routes are added to the `included_routes` of the plugin as seen [here](https://github.com/litestar-org/litestar/blob/b02e65e675d8a29d86be90be79b997c79588823c/litestar/_openapi/plugin.py#L60-L67).
However, this causes the creation of the path item for the same path multiple times since a single path may have multiple route handlers. When this happens, an operation ID is created for a route handler which was already processed and hence we get an error. | 2023-12-09T06:13:17 |
litestar-org/litestar | 2,885 | litestar-org__litestar-2885 | [
"2813"
] | ca3659a3db5d9197b3341a38f54b7e0420f07424 | diff --git a/docs/examples/channels/run_in_background.py b/docs/examples/channels/run_in_background.py
--- a/docs/examples/channels/run_in_background.py
+++ b/docs/examples/channels/run_in_background.py
@@ -7,13 +7,13 @@
async def handler(socket: WebSocket, channels: ChannelsPlugin) -> None:
await socket.accept()
- async with channels.subscribe(["some_channel"]) as subscriber, subscriber.run_in_background(socket.send_text):
+ async with await channels.subscribe(["some_channel"]) as subscriber, subscriber.run_in_background(socket.send_text):
while True:
- await socket.receive_text()
- # do something with the message here
+ response = await socket.receive_text()
+ await subscriber.send(response)
app = Litestar(
[handler],
- plugins=[ChannelsPlugin(backend=MemoryChannelsBackend())],
+ plugins=[ChannelsPlugin(backend=MemoryChannelsBackend(), channels=["some_channel"])],
)
| Docs: Channels run_in_background.py example does not work
### Summary
Hi,
i just tried to run the channels example "run_in_background.py" from the [website](https://docs.litestar.dev/2/usage/channels.html) (which translates to [run_in_background.py](https://github.com/litestar-org/litestar/blob/main/docs/examples/channels/run_in_background.py)) and found that it didn't work for me.
I'm running Python 3.8.10 in a virtual environment with Litestar 2.4.1.
The application contains exacly the same source code that is provided in the example file and was run using `uvicorn app:app --reload`
Log output:
```
INFO: Started reloader process [219108] using WatchFiles
Process SpawnProcess-1:
Traceback (most recent call last):
File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/home/.../venv/lib/python3.8/site-packages/uvicorn/_subprocess.py", line 76, in subprocess_started
target(sockets=sockets)
File "/home/.../venv/lib/python3.8/site-packages/uvicorn/server.py", line 61, in run
return asyncio.run(self.serve(sockets=sockets))
File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "uvloop/loop.pyx", line 1517, in uvloop.loop.Loop.run_until_complete
File "/home/.../venv/lib/python3.8/site-packages/uvicorn/server.py", line 68, in serve
config.load()
File "/home/.../venv/lib/python3.8/site-packages/uvicorn/config.py", line 467, in load
self.loaded_app = import_from_string(self.app)
File "/home/.../venv/lib/python3.8/site-packages/uvicorn/importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/.../source/app.py", line 18, in <module>
plugins=[ChannelsPlugin(backend=MemoryChannelsBackend())],
File "/home/.../venv/lib/python3.8/site-packages/litestar/channels/plugin.py", line 82, in __init__
raise ImproperlyConfiguredException("Must define either channels or set arbitrary_channels_allowed=True")
litestar.exceptions.http_exceptions.ImproperlyConfiguredException: 500: Must define either channels or set arbitrary_channels_allowed=True
```
This error is easy to resolve. I've changed
plugins=[ChannelsPlugin(backend=MemoryChannelsBackend())],
to
plugins=[ChannelsPlugin(backend=MemoryChannelsBackend(), channels=["general"])],
and the app started up successfully.
But there seems to be another problem. As soon as my browser connects to the websocket, I get the following warning:
```
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [219218] using WatchFiles
INFO: Started server process [219220]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: ('127.0.0.1', 33682) - "WebSocket /ws" [accepted]
/home/...../source/app.py:10: RuntimeWarning: coroutine 'ChannelsPlugin.subscribe' was never awaited
async with channels.subscribe(["some_channel"]) as subscriber, subscriber.run_in_background(socket.send_text):
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
INFO: connection open
INFO: connection closed
```
I'm not sure how to resolve this problem. Probably the documentation does not refect the current state of Litestar? Could you check if the example is still valid? Thank you :-)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2813">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2813/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2813/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| > Probably the documentation does not refect the current state of Litestar? Could you check if the example is still valid?
Your assessment is correct here, the documentation is out of date. We'll have to update this! | 2023-12-12T10:28:25 |
|
litestar-org/litestar | 2,903 | litestar-org__litestar-2903 | [
"2902"
] | 3aa93bd8a2924d3c9fb282b298bd99a42087cc63 | diff --git a/litestar/_kwargs/extractors.py b/litestar/_kwargs/extractors.py
--- a/litestar/_kwargs/extractors.py
+++ b/litestar/_kwargs/extractors.py
@@ -295,6 +295,8 @@ async def json_extractor(connection: Request[Any, Any, Any]) -> Any:
Returns:
The JSON value.
"""
+ if not await connection.body():
+ return Empty
return await connection.json()
@@ -310,6 +312,8 @@ async def msgpack_extractor(connection: Request[Any, Any, Any]) -> Any:
Returns:
The MessagePack value.
"""
+ if not await connection.body():
+ return Empty
return await connection.msgpack()
@@ -454,7 +458,8 @@ def create_dto_extractor(
"""
async def dto_extractor(connection: Request[Any, Any, Any]) -> Any:
- body = await connection.body()
+ if not (body := await connection.body()):
+ return Empty
return data_dto(connection).decode_bytes(body)
return dto_extractor # type:ignore[return-value]
diff --git a/litestar/routes/http.py b/litestar/routes/http.py
--- a/litestar/routes/http.py
+++ b/litestar/routes/http.py
@@ -14,6 +14,7 @@
from litestar.response import Response
from litestar.routes.base import BaseRoute
from litestar.status_codes import HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST
+from litestar.types.empty import Empty
from litestar.utils.scope.state import ScopeState
if TYPE_CHECKING:
@@ -174,10 +175,15 @@ async def _get_response_data(
if "data" in kwargs:
try:
- kwargs["data"] = await kwargs["data"]
+ data = await kwargs["data"]
except SerializationException as e:
raise ClientException(str(e)) from e
+ if data is Empty:
+ del kwargs["data"]
+ else:
+ kwargs["data"] = data
+
if "body" in kwargs:
kwargs["body"] = await kwargs["body"]
| diff --git a/tests/unit/test_dto/test_factory/test_integration.py b/tests/unit/test_dto/test_factory/test_integration.py
--- a/tests/unit/test_dto/test_factory/test_integration.py
+++ b/tests/unit/test_dto/test_factory/test_integration.py
@@ -829,3 +829,22 @@ async def get_definition() -> Dict[str, Lexeme]:
with create_test_client(route_handlers=[get_definition]) as client:
response = client.get("/")
assert response.json() == {"hello": {"name": "hello"}, "world": {"name": "world"}}
+
+
+def test_data_dto_with_default() -> None:
+ """A POST request without Body should inject the default value.
+
+ https://github.com/litestar-org/litestar/issues/2902
+ """
+
+ @dataclass
+ class Foo:
+ foo: str
+
+ @post(path="/", dto=DataclassDTO[Foo], signature_types=[Foo])
+ def test(data: Optional[Foo] = None) -> dict:
+ return {"foo": data}
+
+ with create_test_client([test]) as client:
+ response = client.post("/")
+ assert response.json() == {"foo": None}
diff --git a/tests/unit/test_kwargs/test_json_data.py b/tests/unit/test_kwargs/test_json_data.py
--- a/tests/unit/test_kwargs/test_json_data.py
+++ b/tests/unit/test_kwargs/test_json_data.py
@@ -1,5 +1,7 @@
from dataclasses import asdict
+from msgspec import Struct
+
from litestar import post
from litestar.params import Body
from litestar.status_codes import HTTP_201_CREATED
@@ -26,3 +28,19 @@ def test_method(data: dict) -> None:
with create_test_client(test_method) as client:
response = client.post("/test", json={})
assert response.status_code == HTTP_201_CREATED
+
+
+def test_no_body_with_default() -> None:
+ class Test(Struct, frozen=True):
+ name: str
+
+ default = Test(name="default")
+
+ @post(path="/test", signature_types=[Test])
+ def test_method(data: Test = default) -> Test:
+ return data
+
+ with create_test_client(test_method) as client:
+ response = client.post("/test")
+ assert response.status_code == HTTP_201_CREATED
+ assert response.json() == {"name": "default"}
diff --git a/tests/unit/test_kwargs/test_msgpack_data.py b/tests/unit/test_kwargs/test_msgpack_data.py
--- a/tests/unit/test_kwargs/test_msgpack_data.py
+++ b/tests/unit/test_kwargs/test_msgpack_data.py
@@ -1,3 +1,6 @@
+from msgspec import Struct
+from typing_extensions import Annotated
+
from litestar import post
from litestar.enums import RequestEncodingType
from litestar.params import Body
@@ -22,3 +25,19 @@ def test_annotated(data: dict = Body(media_type=RequestEncodingType.MESSAGEPACK)
with create_test_client([test_header, test_annotated]) as client:
response = client.post("/annotated", content=encode_msgpack(test_data))
assert response.status_code == HTTP_201_CREATED
+
+
+def test_no_body_with_default() -> None:
+ class Test(Struct, frozen=True):
+ name: str
+
+ default = Test(name="default")
+
+ @post(path="/test", signature_types=[Test])
+ def test_method(data: Annotated[Test, Body(media_type=RequestEncodingType.MESSAGEPACK)] = default) -> Test:
+ return data
+
+ with create_test_client(test_method) as client:
+ response = client.post("/test")
+ assert response.status_code == HTTP_201_CREATED
+ assert response.json() == {"name": "default"}
| Bug: DTO support empty payload
### Description
DTO supported data fails if no body is sent with the request, even if a default value is provided for the parameter.
### URL to code causing the issue
_No response_
### MCVE
```python
from dataclasses import dataclass
from typing import Optional
from litestar import Litestar, post
from litestar.contrib.pydantic import PydanticPlugin
from litestar.dto import DataclassDTO
from litestar.logging import LoggingConfig
@dataclass
class Foo:
foo: str
@post(path="/", dto=DataclassDTO[Foo])
def test(data: Optional[Foo] = None) -> dict:
return {"foo": data}
app = Litestar(
route_handlers=[test],
logging_config=LoggingConfig(),
middleware=[],
plugins=[PydanticPlugin(prefer_alias=True)],
)
```
### Steps to reproduce
```bash
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
```
### Screenshots
```bash
""
```
### Logs
```bash
FO: 127.0.0.1:38110 - "POST / HTTP/1.1" 400 Bad Request
ERROR - 2023-12-15 02:27:22,851 - litestar - config - exception raised on http connection to route /
Traceback (most recent call last):
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 187, in decode_json
return msgspec.json.decode(
msgspec.DecodeError: Input data was truncated
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 177, in _get_response_data
kwargs["data"] = await kwargs["data"]
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/_kwargs/extractors.py", line 450, in dto_extractor
return data_dto(connection).decode_bytes(body)
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/dto/base_dto.py", line 97, in decode_bytes
return backend.populate_data_from_raw(value, self.asgi_connection)
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/dto/_backend.py", line 301, in populate_data_from_raw
source_data=self.parse_raw(raw, asgi_connection),
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/dto/_backend.py", line 208, in parse_raw
result = decode_json(value=raw, target_type=self.annotation, type_decoders=type_decoders)
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 191, in decode_json
raise SerializationException(str(msgspec_error)) from msgspec_error
litestar.exceptions.base_exceptions.SerializationException: Input data was truncated
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 81, in handle
response = await self._get_response_for_request(
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 133, in _get_response_for_request
return await self._call_handler_function(
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 153, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 179, in _get_response_data
raise ClientException(str(e)) from e
litestar.exceptions.http_exceptions.ClientException: 400: Input data was truncated
Traceback (most recent call last):
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 187, in decode_json
return msgspec.json.decode(
msgspec.DecodeError: Input data was truncated
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 177, in _get_response_data
kwargs["data"] = await kwargs["data"]
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/_kwargs/extractors.py", line 450, in dto_extractor
return data_dto(connection).decode_bytes(body)
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/dto/base_dto.py", line 97, in decode_bytes
return backend.populate_data_from_raw(value, self.asgi_connection)
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/dto/_backend.py", line 301, in populate_data_from_raw
source_data=self.parse_raw(raw, asgi_connection),
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/dto/_backend.py", line 208, in parse_raw
result = decode_json(value=raw, target_type=self.annotation, type_decoders=type_decoders)
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/serialization/msgspec_hooks.py", line 191, in decode_json
raise SerializationException(str(msgspec_error)) from msgspec_error
litestar.exceptions.base_exceptions.SerializationException: Input data was truncated
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 81, in handle
response = await self._get_response_for_request(
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 133, in _get_response_for_request
return await self._call_handler_function(
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 153, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
File "/home/simon/miniconda3/envs/resonance/lib/python3.10/site-packages/litestar/routes/http.py", line 179, in _get_response_data
raise ClientException(str(e)) from e
litestar.exceptions.http_exceptions.ClientException: 400: Input data was truncated
```
### Litestar Version
main
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2902">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2902/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2902/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-12-15T04:07:39 |
|
litestar-org/litestar | 2,915 | litestar-org__litestar-2915 | [
"2914"
] | 21ab23545c755f89a0270544196556df183695c5 | diff --git a/litestar/handlers/http_handlers/_utils.py b/litestar/handlers/http_handlers/_utils.py
--- a/litestar/handlers/http_handlers/_utils.py
+++ b/litestar/handlers/http_handlers/_utils.py
@@ -6,14 +6,15 @@
from litestar.enums import HttpMethod
from litestar.exceptions import ValidationException
+from litestar.response import Response
from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT
+from litestar.types.builtin_types import NoneType
if TYPE_CHECKING:
from litestar.app import Litestar
from litestar.background_tasks import BackgroundTask, BackgroundTasks
from litestar.connection import Request
from litestar.datastructures import Cookie, ResponseHeader
- from litestar.response import Response
from litestar.types import (
AfterRequestHookHandler,
ASGIApp,
@@ -22,12 +23,14 @@
ResponseType,
TypeEncodersMap,
)
+ from litestar.typing import FieldDefinition
__all__ = (
"create_data_handler",
"create_generic_asgi_response_handler",
"create_response_handler",
"get_default_status_code",
+ "is_empty_response_annotation",
"normalize_headers",
"normalize_http_method",
)
@@ -206,4 +209,20 @@ def get_default_status_code(http_methods: set[Method]) -> int:
return HTTP_200_OK
+def is_empty_response_annotation(return_annotation: FieldDefinition) -> bool:
+ """Return whether the return annotation is an empty response.
+
+ Args:
+ return_annotation: A return annotation.
+
+ Returns:
+ Whether the return annotation is an empty response.
+ """
+ return (
+ return_annotation.is_subclass_of(NoneType)
+ or return_annotation.is_subclass_of(Response)
+ and return_annotation.has_inner_subclass_of(NoneType)
+ )
+
+
HTTP_METHOD_NAMES = {m.value for m in HttpMethod}
diff --git a/litestar/handlers/http_handlers/base.py b/litestar/handlers/http_handlers/base.py
--- a/litestar/handlers/http_handlers/base.py
+++ b/litestar/handlers/http_handlers/base.py
@@ -17,6 +17,7 @@
create_generic_asgi_response_handler,
create_response_handler,
get_default_status_code,
+ is_empty_response_annotation,
normalize_http_method,
)
from litestar.openapi.spec import Operation
@@ -41,7 +42,6 @@
ResponseType,
TypeEncodersMap,
)
-from litestar.types.builtin_types import NoneType
from litestar.utils import ensure_async_callable
from litestar.utils.predicates import is_async_callable
from litestar.utils.warnings import warn_implicit_sync_to_thread, warn_sync_to_thread_with_async_callable
@@ -552,7 +552,7 @@ def _validate_handler_function(self) -> None:
if (
self.status_code < 200 or self.status_code in {HTTP_204_NO_CONTENT, HTTP_304_NOT_MODIFIED}
- ) and not return_type.is_subclass_of(NoneType):
+ ) and not is_empty_response_annotation(return_type):
raise ImproperlyConfiguredException(
"A status code 204, 304 or in the range below 200 does not support a response body. "
"If the function should return a value, change the route handler status code to an appropriate value.",
| diff --git a/tests/unit/test_handlers/test_http_handlers/test_validations.py b/tests/unit/test_handlers/test_http_handlers/test_validations.py
--- a/tests/unit/test_handlers/test_http_handlers/test_validations.py
+++ b/tests/unit/test_handlers/test_http_handlers/test_validations.py
@@ -1,5 +1,6 @@
from pathlib import Path
-from typing import Dict
+from types import ModuleType
+from typing import Callable, Dict
import pytest
@@ -110,3 +111,36 @@ def test_function_2(self, data: DataclassPerson) -> None: # type: ignore
Litestar(route_handlers=[test_function_2])
test_function_2.on_registration(Litestar())
+
+
[email protected](
+ ("return_annotation", "should_raise"),
+ [
+ ("None", False),
+ ("Response[None]", False),
+ ("int", True),
+ ("Response[int]", True),
+ ("Response", True),
+ ],
+)
+def test_204_response_annotations(
+ return_annotation: str, should_raise: bool, create_module: Callable[[str], ModuleType]
+) -> None:
+ module = create_module(
+ f"""
+from litestar import get
+from litestar.response import Response
+from litestar.status_codes import HTTP_204_NO_CONTENT
+
+@get(path="/", status_code=HTTP_204_NO_CONTENT)
+def no_response_handler() -> {return_annotation}:
+ pass
+"""
+ )
+
+ if should_raise:
+ with pytest.raises(ImproperlyConfiguredException):
+ Litestar(route_handlers=[module.no_response_handler])
+ return
+
+ Litestar(route_handlers=[module.no_response_handler])
| Bug: Can't use `Response[None]` as return annotation when status code is `204`
### Description
As per the [docs](https://docs.litestar.dev/2/usage/responses.html#status-codes):
> For status codes < 100 or 204, 304 statuses, no response body is allowed. If you specify a return annotation other than None, an [ImproperlyConfiguredException](https://docs.litestar.dev/2/reference/exceptions.html#litestar.exceptions.ImproperlyConfiguredException) will be raised.
But sometimes you want to return a `Response`, even without content. For example, to add some headers dynamically:
```py
return Response(None, headers={"FOO": "BAR"})
```
Then to satisfy the types, the return type should be `Response[None]`. But in this case, `ImproperlyConfiguredException` is raised. I guess it shouldn't be.
### URL to code causing the issue
_No response_
### MCVE
```python
from litestar import Litestar, Response, get
from litestar.status_codes import HTTP_204_NO_CONTENT
@get("/", status_code=HTTP_204_NO_CONTENT)
async def index() -> Response[None]:
return Response(None)
app = Litestar([index])
```
### Steps to reproduce
_No response_
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
`2.4.4`
### Platform
- [ ] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2914">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2914/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2914/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2023-12-18T00:21:15 |
|
litestar-org/litestar | 2,941 | litestar-org__litestar-2941 | [
"2867"
] | 11b4353c44c80d10478656033ba2be719cf99902 | diff --git a/litestar/middleware/exceptions/_debug_response.py b/litestar/middleware/exceptions/_debug_response.py
--- a/litestar/middleware/exceptions/_debug_response.py
+++ b/litestar/middleware/exceptions/_debug_response.py
@@ -26,6 +26,7 @@
from inspect import FrameInfo
from litestar.connection import Request
+ from litestar.types import TypeEncodersMap
tpl_dir = Path(__file__).parent / "templates"
@@ -191,4 +192,19 @@ def create_debug_response(request: Request, exc: Exception) -> Response:
content = create_plain_text_response_content(exc)
media_type = MediaType.TEXT
- return Response(content=content, media_type=media_type, status_code=HTTP_500_INTERNAL_SERVER_ERROR)
+ return Response(
+ content=content,
+ media_type=media_type,
+ status_code=HTTP_500_INTERNAL_SERVER_ERROR,
+ type_encoders=_get_type_encoders_for_request(request) if request is not None else None,
+ )
+
+
+def _get_type_encoders_for_request(request: Request) -> TypeEncodersMap | None:
+ try:
+ return request.route_handler.resolve_type_encoders()
+ # we might be in a 404, or before we could resolve the handler, so this
+ # could potentially error out. In this case we fall back on the application
+ # type encoders
+ except (KeyError, AttributeError):
+ return request.app.type_encoders
diff --git a/litestar/middleware/exceptions/middleware.py b/litestar/middleware/exceptions/middleware.py
--- a/litestar/middleware/exceptions/middleware.py
+++ b/litestar/middleware/exceptions/middleware.py
@@ -11,7 +11,7 @@
from litestar.enums import MediaType, ScopeType
from litestar.exceptions import WebSocketException
from litestar.middleware.cors import CORSMiddleware
-from litestar.middleware.exceptions._debug_response import create_debug_response
+from litestar.middleware.exceptions._debug_response import _get_type_encoders_for_request, create_debug_response
from litestar.serialization import encode_json
from litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
from litestar.utils.deprecation import warn_deprecation
@@ -85,7 +85,7 @@ class ExceptionResponseContent:
extra: dict[str, Any] | list[Any] | None = field(default=None)
"""An extra mapping to attach to the exception."""
- def to_response(self) -> Response:
+ def to_response(self, request: Request | None = None) -> Response:
"""Create a response from the model attributes.
Returns:
@@ -103,6 +103,7 @@ def to_response(self) -> Response:
headers=self.headers,
status_code=self.status_code,
media_type=self.media_type,
+ type_encoders=_get_type_encoders_for_request(request) if request is not None else None,
)
@@ -139,7 +140,7 @@ def create_exception_response(request: Request[Any, Any, Any], exc: Exception) -
extra=getattr(exc, "extra", None),
media_type=media_type,
)
- return content.to_response()
+ return content.to_response(request=request)
class ExceptionHandlerMiddleware:
| diff --git a/tests/unit/test_middleware/test_exception_handler_middleware.py b/tests/unit/test_middleware/test_exception_handler_middleware.py
--- a/tests/unit/test_middleware/test_exception_handler_middleware.py
+++ b/tests/unit/test_middleware/test_exception_handler_middleware.py
@@ -362,3 +362,20 @@ def method(self) -> None:
if exc is not None and exc.__traceback__ is not None:
frame = getinnerframes(exc.__traceback__, 2)[-1]
assert get_symbol_name(frame) == "Test.method"
+
+
+def test_serialize_custom_types() -> None:
+ # ensure type encoders are passed down to the created response so custom types that
+ # might end up as part of a ValidationException are handled properly
+ # https://github.com/litestar-org/litestar/issues/2867
+ class Foo:
+ def __init__(self, value: str) -> None:
+ self.value = value
+
+ @get()
+ def handler() -> None:
+ raise ValidationException(extra={"foo": Foo("bar")})
+
+ with create_test_client([handler], type_encoders={Foo: lambda f: f.value}) as client:
+ res = client.get("/")
+ assert res.json()["extra"] == {"foo": "bar"}
| Bug: Long cryptic error when excluding a required field from a DTO
### Description
As mentioned on Discord, excluding a required field from a DTO triggers a 500 Internal Server Error at runtime. This is hard to troubleshoot even at debug mode because the traceback is too long and ends with `litestar.exceptions.base_exceptions.SerializationException: Unsupported type: <class '...'>`, which is rather misleading
### URL to code causing the issue
_No response_
### MCVE
```python
from typing import Annotated
from litestar import Litestar, post
from litestar.contrib.pydantic import PydanticDTO
from litestar.dto import DTOConfig
from pydantic import BaseModel
class Parent(BaseModel):
id: int
class Child(BaseModel):
name: str
parent: Parent
ChildDTO1 = PydanticDTO[Annotated[Child, DTOConfig(exclude={"name"})]]
class ChildDTO2(PydanticDTO[Child]):
config = DTOConfig(exclude={"name"})
@post(path="/child1", dto=ChildDTO1, return_dto=None)
async def post_child1(data: Child) -> Child:
return data
@post(path="/child2", dto=ChildDTO2, return_dto=None)
async def post_child2(data: Child) -> Child:
return data
app = Litestar(route_handlers=[post_child1, post_child2])
```
### Steps to reproduce
```bash
1. Start the server
2. Run `curl -X POST http://localhost:8508/child1 -d '{"parent": {"id": 1}}'` (same with `/child2`)
```
### Screenshots
```bash
""
```
### Logs
_No response_
### Litestar Version
2.4.3
### Platform
- [ ] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2867">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2867/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2867/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Thanks for opening @gsakkis! | 2024-01-03T18:48:05 |
litestar-org/litestar | 2,950 | litestar-org__litestar-2950 | [
"2939"
] | e62cd3afcec1a8df00268655664c663112732308 | diff --git a/litestar/_kwargs/extractors.py b/litestar/_kwargs/extractors.py
--- a/litestar/_kwargs/extractors.py
+++ b/litestar/_kwargs/extractors.py
@@ -15,6 +15,7 @@
from litestar.exceptions import ValidationException
from litestar.params import BodyKwarg
from litestar.types import Empty
+from litestar.utils.predicates import is_non_string_sequence
from litestar.utils.scope.state import ScopeState
if TYPE_CHECKING:
@@ -355,7 +356,7 @@ async def extract_multipart(
if field_definition.is_non_string_sequence:
values = list(form_values.values())
- if field_definition.inner_types[0].annotation is UploadFile and isinstance(values[0], list):
+ if field_definition.has_inner_subclass_of(UploadFile) and isinstance(values[0], list):
return values[0]
return values
@@ -366,7 +367,15 @@ async def extract_multipart(
if not form_values and is_data_optional:
return None
- return data_dto(connection).decode_builtins(form_values) if data_dto else form_values
+ if data_dto:
+ return data_dto(connection).decode_builtins(form_values)
+
+ for name, tp in field_definition.get_type_hints().items():
+ value = form_values.get(name)
+ if value is not None and is_non_string_sequence(tp) and not isinstance(value, list):
+ form_values[name] = [value]
+
+ return form_values
return cast("Callable[[ASGIConnection[Any, Any, Any, Any]], Coroutine[Any, Any, Any]]", extract_multipart)
| diff --git a/tests/unit/test_kwargs/test_multipart_data.py b/tests/unit/test_kwargs/test_multipart_data.py
--- a/tests/unit/test_kwargs/test_multipart_data.py
+++ b/tests/unit/test_kwargs/test_multipart_data.py
@@ -410,6 +410,27 @@ async def handler(data: List[UploadFile] = Body(media_type=RequestEncodingType.M
assert response.status_code == HTTP_201_CREATED
+@dataclass
+class Files:
+ file_list: List[UploadFile]
+
+
[email protected]("file_count", (1, 2))
+def test_upload_multiple_files_in_model(file_count: int) -> None:
+ @post("/")
+ async def handler(data: Files = Body(media_type=RequestEncodingType.MULTI_PART)) -> None:
+ assert len(data.file_list) == file_count
+
+ for file in data.file_list:
+ assert await file.read() == b"1"
+
+ with create_test_client([handler]) as client:
+ files_to_upload = [("file_list", b"1") for _ in range(file_count)]
+ response = client.post("/", files=files_to_upload)
+
+ assert response.status_code == HTTP_201_CREATED
+
+
def test_optional_formdata() -> None:
@post("/", signature_types=[UploadFile])
async def hello_world(data: Optional[UploadFile] = Body(media_type=RequestEncodingType.MULTI_PART)) -> None:
| Bug: Uploading list of files via an object fails validation if there's only a single file
### Description
If there's some model like the one below and only one file is provided by the client, then the validation fails.
```python
class FileModel(Struct):
files: list[UploadFile]
```
This is the same issue as in #2753. That PR, unfortunately, only handled this scenario for `data: list[FileUpload]` defined directly on the handlers. We'll have to go through all the fields of the `FieldDefinition` and do that same check that was introduced in that PR. I don't think this has to be done recursively though since complex objects aren't supported.
### URL to code causing the issue
_No response_
### MCVE
```python
from __future__ import annotations
from msgspec import Struct
from litestar import post
from litestar.datastructures import UploadFile
from litestar.enums import RequestEncodingType
from litestar.params import Body
from litestar.status_codes import HTTP_201_CREATED
from litestar.testing.helpers import create_test_client
class FileUpload(Struct):
files: list[UploadFile]
@post(path="/")
async def upload_files_object(data: FileUpload = Body(media_type=RequestEncodingType.MULTI_PART)) -> list[str]:
return [f.filename for f in data.files]
with create_test_client([upload_files_object], debug=True) as client:
# Works if more than 1 file is provided.
# files = [("files", b"1"), ("files", b"2")]
# Fails if only 1 file is provided.
files = [("files", b"1")]
response = client.post("/", files=files)
```
### Steps to reproduce
```bash
1. Run the MCVE
```
### Screenshots
_No response_
### Logs
```bash
Traceback (most recent call last):
File "/home/guacs/open-source/litestar/litestar/_signature/model.py", line 189, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `array`, got `UploadFile` - at `$.data.files`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/guacs/open-source/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/guacs/open-source/litestar/litestar/routes/http.py", line 82, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/guacs/open-source/litestar/litestar/routes/http.py", line 134, in _get_response_for_request
return await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/guacs/open-source/litestar/litestar/routes/http.py", line 154, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/guacs/open-source/litestar/litestar/routes/http.py", line 193, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/guacs/open-source/litestar/litestar/_signature/model.py", line 202, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://testserver.local/
Traceback (most recent call last):
File "/home/guacs/open-source/litestar/litestar/_signature/model.py", line 189, in parse_values_from_connection_kwargs
return convert(kwargs, cls, strict=False, dec_hook=deserializer, str_keys=True).to_dict()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
msgspec.ValidationError: Expected `array`, got `UploadFile` - at `$.data.files`
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/guacs/open-source/litestar/litestar/middleware/exceptions/middleware.py", line 191, in __call__
await self.app(scope, receive, send)
File "/home/guacs/open-source/litestar/litestar/routes/http.py", line 82, in handle
response = await self._get_response_for_request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/guacs/open-source/litestar/litestar/routes/http.py", line 134, in _get_response_for_request
return await self._call_handler_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/guacs/open-source/litestar/litestar/routes/http.py", line 154, in _call_handler_function
response_data, cleanup_group = await self._get_response_data(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/guacs/open-source/litestar/litestar/routes/http.py", line 193, in _get_response_data
parsed_kwargs = route_handler.signature_model.parse_values_from_connection_kwargs(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/guacs/open-source/litestar/litestar/_signature/model.py", line 202, in parse_values_from_connection_kwargs
raise cls._create_exception(messages=messages, connection=connection) from e
litestar.exceptions.http_exceptions.ValidationException: 400: Validation failed for POST http://testserver.local/
```
### Litestar Version
HEAD
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2939">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2939/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2939/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| 2024-01-05T13:23:41 |
|
litestar-org/litestar | 2,982 | litestar-org__litestar-2982 | [
"2971"
] | 93b7db61f3f41fcaa09ec311f23c0b08f3046006 | diff --git a/litestar/_openapi/schema_generation/plugins/struct.py b/litestar/_openapi/schema_generation/plugins/struct.py
--- a/litestar/_openapi/schema_generation/plugins/struct.py
+++ b/litestar/_openapi/schema_generation/plugins/struct.py
@@ -19,7 +19,7 @@
class StructSchemaPlugin(OpenAPISchemaPlugin):
def is_plugin_supported_field(self, field_definition: FieldDefinition) -> bool:
- return field_definition.is_subclass_of(Struct)
+ return not field_definition.is_union and field_definition.is_subclass_of(Struct)
def to_openapi_schema(self, field_definition: FieldDefinition, schema_creator: SchemaCreator) -> Schema:
def is_field_required(field: FieldInfo) -> bool:
| diff --git a/tests/unit/test_openapi/test_schema.py b/tests/unit/test_openapi/test_schema.py
--- a/tests/unit/test_openapi/test_schema.py
+++ b/tests/unit/test_openapi/test_schema.py
@@ -491,3 +491,61 @@ def test_process_schema_result_with_unregistered_object_schema() -> None:
schema = Schema(title="has title", type=OpenAPIType.OBJECT)
field_definition = FieldDefinition.from_annotation(dict)
assert SchemaCreator().process_schema_result(field_definition, schema) is schema
+
+
[email protected]("base_type", [msgspec.Struct, TypedDict, dataclass])
+def test_type_union(base_type: type) -> None:
+ if base_type is dataclass: # type: ignore[comparison-overlap]
+
+ @dataclass
+ class ModelA: # pyright: ignore
+ pass
+
+ @dataclass
+ class ModelB: # pyright: ignore
+ pass
+ else:
+
+ class ModelA(base_type): # type: ignore[no-redef, misc]
+ pass
+
+ class ModelB(base_type): # type: ignore[no-redef, misc]
+ pass
+
+ schema = get_schema_for_field_definition(
+ FieldDefinition.from_kwarg(name="Lookup", annotation=Union[ModelA, ModelB])
+ )
+ assert schema.one_of == [
+ Reference(ref="#/components/schemas/tests_unit_test_openapi_test_schema_test_type_union.ModelA"),
+ Reference(ref="#/components/schemas/tests_unit_test_openapi_test_schema_test_type_union.ModelB"),
+ ]
+
+
[email protected]("base_type", [msgspec.Struct, TypedDict, dataclass])
+def test_type_union_with_none(base_type: type) -> None:
+ # https://github.com/litestar-org/litestar/issues/2971
+ if base_type is dataclass: # type: ignore[comparison-overlap]
+
+ @dataclass
+ class ModelA: # pyright: ignore
+ pass
+
+ @dataclass
+ class ModelB: # pyright: ignore
+ pass
+ else:
+
+ class ModelA(base_type): # type: ignore[no-redef, misc]
+ pass
+
+ class ModelB(base_type): # type: ignore[no-redef, misc]
+ pass
+
+ schema = get_schema_for_field_definition(
+ FieldDefinition.from_kwarg(name="Lookup", annotation=Union[ModelA, ModelB, None])
+ )
+ assert schema.one_of == [
+ Schema(type=OpenAPIType.NULL),
+ Reference(ref="#/components/schemas/tests_unit_test_openapi_test_schema_test_type_union_with_none.ModelA"),
+ Reference("#/components/schemas/tests_unit_test_openapi_test_schema_test_type_union_with_none.ModelB"),
+ ]
| Bug: openapi schema generation fails for Union of/in msgspec.Struct models
### Description
Hello!
In the latest versions(s) (I think this originates from the changes regarding nested models in openapi generation) we cannot use Unions of `msgspec.Struct`s anymore. Neither as direct return types for routes nor nested within return types.
The result is a 500 Error. The MCVE below raises `'types.UnionType' object has no attribute '__qualname__'` internally. In our production app I get `typing.Union is not a module, class, method, or function.` instead.
Cheers
### URL to code causing the issue
_No response_
### MCVE
```python
import msgspec
import uvicorn
from litestar import Litestar, get
class SubStructA(msgspec.Struct):
a: int
class SubStructB(msgspec.Struct):
a: int
class StructyStruct(msgspec.Struct):
sub: SubStructA | SubStructB
@get("/subunion")
async def testSubUnion() -> StructyStruct:
return StructyStruct(SubStructA(0))
@get("/union")
async def testUnion() -> SubStructA | SubStructB:
return SubStructA(0)
app = Litestar(route_handlers=[test2]) # or test
uvicorn.run(app)
```
### Steps to reproduce
```bash
Run the example and browse to `localhost:8000/schema`
```
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.5.0
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2971">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2971/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2971/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Thanks for report @aedify-swi, confirmed.
Guessing that you are using 3.8 or 3.9 in prod app with `Union` instead of ` | `?
Issue is with our internal schema generation plugin for `Struct` types (actually, other plugin types are likely vulnerable to this also).
https://github.com/litestar-org/litestar/blob/cc45c1132584210250dd725595612c9c95c4bf68/litestar/_openapi/schema_generation/plugins/struct.py#L21-L22
`FieldDefinition.is_subclass_of()` will return `True` if all elements of the union are subclasses of `Struct`, however the plugin doesn't make any effort to handle unions, nor should it b/c the schema generation scaffolding above it manages that. So if it receives a union, irrespective of the member types, it should return `False`.
Changing that to:
```py
def is_plugin_supported_field(self, field_definition: FieldDefinition) -> bool:
return not field_definition.is_union and field_definition.is_subclass_of(Struct)
```
seems to sort it:

Thanks for your quick reply @peterschutt!
>Guessing that you are using 3.8 or 3.9 in prod app with Union instead of |?
Nope. 3.12 and exclusively `|`s. Your fix works regardless for our project even though the error message is a little different. ;)
> Nope. 3.12
Any chance you can provide a traceback for your prod issue please?
Even better, I was able to reproduce it.
```python
import msgspec
import uvicorn
from litestar import Litestar, get
class SubStructA(msgspec.Struct):
a: int
class SubStructB(msgspec.Struct):
a: int
@get("/union")
async def testOptionalUnion() -> SubStructA | SubStructB | None:
return SubStructA(0)
app = Litestar(route_handlers=[testOptionalUnion]) # or test
uvicorn.run(app)
```
This raises `typing.Union is not a module, class, method, or function.` in `litestar.utils.typing.get_type_hints_with_generics_resolved` | 2024-01-13T11:25:34 |
litestar-org/litestar | 3,009 | litestar-org__litestar-3009 | [
"2549"
] | 1cc4b5e8807df81b7e53b6651603ff6236c6519e | diff --git a/litestar/datastructures/multi_dicts.py b/litestar/datastructures/multi_dicts.py
--- a/litestar/datastructures/multi_dicts.py
+++ b/litestar/datastructures/multi_dicts.py
@@ -1,13 +1,17 @@
from __future__ import annotations
from abc import ABC
-from typing import Any, Generator, Generic, Iterable, Mapping, TypeVar
+from typing import TYPE_CHECKING, Any, Generator, Generic, Iterable, Mapping, TypeVar
from multidict import MultiDict as BaseMultiDict
from multidict import MultiDictProxy, MultiMapping
from litestar.datastructures.upload_file import UploadFile
+if TYPE_CHECKING:
+ from typing_extensions import Self
+
+
__all__ = ("FormMultiDict", "ImmutableMultiDict", "MultiDict", "MultiMixin")
@@ -40,7 +44,8 @@ class MultiDict(BaseMultiDict[T], MultiMixin[T], Generic[T]):
"""MultiDict, using :class:`MultiDict <multidict.MultiDictProxy>`."""
def __init__(self, args: MultiMapping | Mapping[str, T] | Iterable[tuple[str, T]] | None = None) -> None:
- """Initialize ``MultiDict`` from a`MultiMapping``, :class:`Mapping <typing.Mapping>` or an iterable of tuples.
+ """Initialize ``MultiDict`` from a`MultiMapping``,
+ :class:`Mapping <typing.Mapping>` or an iterable of tuples.
Args:
args: Mapping-like structure to create the ``MultiDict`` from
@@ -57,14 +62,17 @@ def immutable(self) -> ImmutableMultiDict[T]:
"""
return ImmutableMultiDict[T](self) # pyright: ignore
+ def copy(self) -> Self:
+ """Return a shallow copy"""
+ return type(self)(list(self.multi_items()))
+
class ImmutableMultiDict(MultiDictProxy[T], MultiMixin[T], Generic[T]):
"""Immutable MultiDict, using class:`MultiDictProxy <multidict.MultiDictProxy>`."""
def __init__(self, args: MultiMapping | Mapping[str, Any] | Iterable[tuple[str, Any]] | None = None) -> None:
- """Initialize ``ImmutableMultiDict`` from a.
-
- ``MultiMapping``, :class:`Mapping <typing.Mapping>` or an iterable of tuples.
+ """Initialize ``ImmutableMultiDict`` from a `MultiMapping``,
+ :class:`Mapping <typing.Mapping>` or an iterable of tuples.
Args:
args: Mapping-like structure to create the ``ImmutableMultiDict`` from
@@ -72,15 +80,17 @@ def __init__(self, args: MultiMapping | Mapping[str, Any] | Iterable[tuple[str,
super().__init__(BaseMultiDict(args or {}))
def mutable_copy(self) -> MultiDict[T]:
- """Create a mutable copy as a.
-
- :class:`MultiDict`
+ """Create a mutable copy as a :class:`MultiDict`
Returns:
A mutable multi dict
"""
return MultiDict(list(self.multi_items()))
+ def copy(self) -> Self: # type: ignore[override]
+ """Return a shallow copy"""
+ return type(self)(self.items())
+
class FormMultiDict(ImmutableMultiDict[Any]):
"""MultiDict for form data."""
| diff --git a/tests/unit/test_datastructures/test_multi_dicts.py b/tests/unit/test_datastructures/test_multi_dicts.py
--- a/tests/unit/test_datastructures/test_multi_dicts.py
+++ b/tests/unit/test_datastructures/test_multi_dicts.py
@@ -1,4 +1,4 @@
-from typing import Type, Union
+from __future__ import annotations
import pytest
from pytest_mock import MockerFixture
@@ -8,14 +8,14 @@
@pytest.mark.parametrize("multi_class", [MultiDict, ImmutableMultiDict])
-def test_multi_to_dict(multi_class: Type[Union[MultiDict, ImmutableMultiDict]]) -> None:
+def test_multi_to_dict(multi_class: type[MultiDict | ImmutableMultiDict]) -> None:
multi = multi_class([("key", "value"), ("key", "value2"), ("key2", "value3")])
assert multi.dict() == {"key": ["value", "value2"], "key2": ["value3"]}
@pytest.mark.parametrize("multi_class", [MultiDict, ImmutableMultiDict])
-def test_multi_multi_items(multi_class: Type[Union[MultiDict, ImmutableMultiDict]]) -> None:
+def test_multi_multi_items(multi_class: type[MultiDict | ImmutableMultiDict]) -> None:
data = [("key", "value"), ("key", "value2"), ("key2", "value3")]
multi = multi_class(data)
@@ -47,3 +47,11 @@ async def test_form_multi_dict_close(mocker: MockerFixture) -> None:
await multi.close()
assert close.call_count == 2
+
+
[email protected]("type_", [MultiDict, ImmutableMultiDict])
+def test_copy(type_: type[MultiDict | ImmutableMultiDict]) -> None:
+ d = type_([("foo", "bar"), ("foo", "baz")])
+ copy = d.copy()
+ assert set(d.multi_items()) == set(copy.multi_items())
+ assert isinstance(d, type_)
| Bug: `litestar.datastructures.MultiDict.copy` returns `multidict._multidict.MultiDict` instance.
### Description
Seems the object returned by `litestar.datastructures.MultiDict.copy` is actually a `multidict._multidict.MultiDict` instance.
```py
from litestar.datastructures import MultiDict
a = MultiDict()
b = a.copy()
print(type(a))
# litestar.datastructures.multi_dicts.MultiDict
print(type(b))
# multidict._multidict.MultiDict
```
Is this intentional?
### URL to code causing the issue
_No response_
### MCVE
```python
See description.
```
### Steps to reproduce
_No response_
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.2.1
### Platform
- [ ] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/2549">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2549/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2549/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| @litestar-org/members curious on this.
@Alc-Alc did we hit this yesterday in our OIDC testing?
I don't think this is anything we are doing:
```python-console
>>> from multidict import MultiDict
>>> class MyMD(MultiDict): ...
...
>>> my_md = MyMD()
>>> my_md_copy = my_md.copy()
>>> type(my_md)
<class '__main__.MyMD'>
>>> type(my_md_copy)
<class 'multidict._multidict.MultiDict'>
>>>
```
It seems that `MultiDict.copy()` doesn't support sub-classes.
Opened an issue here: https://github.com/aio-libs/multidict/issues/901
This is how inheritance works, typically:
```pycon
>>> class MyDict(dict): ...
...
>>> my_dict = MyDict()
>>> my_dict_copy = my_dict.copy()
>>> type(my_dict)
<class '__main__.MyDict'>
>>> type(my_dict_copy)
<class 'dict'>
```
If you want a custom class, make override the method.
> This is how inheritance works, typically:
>
> ```
> >>> class MyDict(dict): ...
> ...
> >>> my_dict = MyDict()
> >>> my_dict_copy = my_dict.copy()
> >>> type(my_dict)
> <class '__main__.MyDict'>
> >>> type(my_dict_copy)
> <class 'dict'>
> ```
>
> If you want a custom class, make override the method.
Makes sense, thanks @webknjaz | 2024-01-21T13:47:04 |
litestar-org/litestar | 3,095 | litestar-org__litestar-3095 | [
"3090"
] | 1e42fa2737906dfab690af65f6b571cfa24a1ed4 | diff --git a/litestar/middleware/session/client_side.py b/litestar/middleware/session/client_side.py
--- a/litestar/middleware/session/client_side.py
+++ b/litestar/middleware/session/client_side.py
@@ -108,7 +108,10 @@ def get_cookie_keys(self, connection: ASGIConnection) -> list[str]:
return sorted(key for key in connection.cookies if self.cookie_re.fullmatch(key))
def _create_session_cookies(self, data: list[bytes], cookie_params: dict[str, Any] | None = None) -> list[Cookie]:
- """Create a list of cookies containing the session data."""
+ """Create a list of cookies containing the session data.
+ If the data is split into multiple cookies, the key will be of the format ``session-{segment number}``,
+ however if only one cookie is needed, the key will be ``session``.
+ """
if cookie_params is None:
cookie_params = dict(
extract_dataclass_items(
@@ -117,6 +120,16 @@ def _create_session_cookies(self, data: list[bytes], cookie_params: dict[str, An
include={f for f in Cookie.__dict__ if f not in ("key", "secret")},
)
)
+
+ if len(data) == 1:
+ return [
+ Cookie(
+ value=data[0].decode("utf-8"),
+ key=self.config.key,
+ **cookie_params,
+ )
+ ]
+
return [
Cookie(
value=datum.decode("utf-8"),
| diff --git a/tests/unit/test_middleware/test_session/test_client_side_backend.py b/tests/unit/test_middleware/test_session/test_client_side_backend.py
--- a/tests/unit/test_middleware/test_session/test_client_side_backend.py
+++ b/tests/unit/test_middleware/test_session/test_client_side_backend.py
@@ -113,16 +113,28 @@ def handler(request: Request) -> None:
# Then you only need to check if number of cookies set are more than the multiplying number.
request.session.update(create_session(size=CHUNK_SIZE * chunks_multiplier))
+ @get(path="/test_short_cookie")
+ def handler_short_cookie(request: Request) -> None:
+ # Check the naming of a cookie that's short enough to not get broken into chunks
+ request.session.update(create_session())
+
with create_test_client(
route_handlers=[handler],
middleware=[cookie_session_backend_config.middleware],
) as client:
response = client.get("/test")
- assert len(response.cookies) > chunks_multiplier
- # If it works for the multiple chunks of session, it works for the single chunk too. So, just check if "session-0"
- # exists.
- assert "session-0" in response.cookies
+ assert len(response.cookies) > chunks_multiplier
+ assert "session-0" in response.cookies
+
+ with create_test_client(
+ route_handlers=[handler_short_cookie],
+ middleware=[cookie_session_backend_config.middleware],
+ ) as client:
+ response = client.get("/test_short_cookie")
+
+ assert len(response.cookies) == 1
+ assert "session" in response.cookies
def test_session_cookie_name_matching(cookie_session_backend_config: "CookieBackendConfig") -> None:
| Bug: session middleware cookies always include segment number
### Description
The docstring of [litestar.middleware.session.client_side.CookieBackendConfig](https://github.com/litestar-org/litestar/blob/04a9501d719c26ff4ef8451d216707a1b72a1c77/litestar/middleware/session/client_side.py#L209) suggests that key for the cookie inside the header is of the form `session=<data>`, unless the cookie is over 4KB in which case it's split into segments named e.g. `session-0=<data-0>`, etc.
However, even when the cookie is under 4KB, the segment number is present in the key, i.e. it's impossible to specify that the key be named `session` -- it will always turn into `session-0`. The reason for this is that
`litestar.middleware.session.client_side.ClientSideSessionBackend._create_session_cookies` returns the result of the list comprehension which includes `[Cookie(..., key=f"{self.config.key}-{i}", ...) for i, datum in enumerate(data)]`.
### URL to code causing the issue
_No response_
### MCVE
_No response_
### Steps to reproduce
_No response_
### Screenshots
_No response_
### Logs
_No response_
### Litestar Version
2.6.0
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/3090">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/3090/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/3090/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| @betaprior since you seem to have figured out the issue, would you like to raise a PR with a fix? | 2024-02-12T09:43:31 |
litestar-org/litestar | 3,098 | litestar-org__litestar-3098 | [
"3069"
] | 468e3295edcf3365c38a91349d6fc830421d2bf1 | diff --git a/litestar/_openapi/responses.py b/litestar/_openapi/responses.py
--- a/litestar/_openapi/responses.py
+++ b/litestar/_openapi/responses.py
@@ -240,14 +240,21 @@ def create_additional_responses(self) -> Iterator[tuple[str, OpenAPIResponse]]:
prefer_alias=False,
generate_examples=additional_response.generate_examples,
)
- schema = schema_creator.for_field_definition(
- FieldDefinition.from_annotation(additional_response.data_container)
- )
+
+ content: dict[str, OpenAPIMediaType] | None
+ if additional_response.data_container is not None:
+ schema = schema_creator.for_field_definition(
+ FieldDefinition.from_annotation(additional_response.data_container)
+ )
+ content = {additional_response.media_type: OpenAPIMediaType(schema=schema)}
+ else:
+ content = None
+
yield (
str(status_code),
OpenAPIResponse(
description=additional_response.description,
- content={additional_response.media_type: OpenAPIMediaType(schema=schema)},
+ content=content,
),
)
diff --git a/litestar/openapi/datastructures.py b/litestar/openapi/datastructures.py
--- a/litestar/openapi/datastructures.py
+++ b/litestar/openapi/datastructures.py
@@ -16,7 +16,7 @@
class ResponseSpec:
"""Container type of additional responses."""
- data_container: DataContainerType
+ data_container: DataContainerType | None
"""A model that describes the content of the response."""
generate_examples: bool = field(default=True)
"""Generate examples for the response content."""
| diff --git a/tests/unit/test_openapi/test_responses.py b/tests/unit/test_openapi/test_responses.py
--- a/tests/unit/test_openapi/test_responses.py
+++ b/tests/unit/test_openapi/test_responses.py
@@ -11,7 +11,7 @@
import pytest
from typing_extensions import TypeAlias
-from litestar import Controller, Litestar, MediaType, Response, get, post
+from litestar import Controller, Litestar, MediaType, Response, delete, get, post
from litestar._openapi.datastructures import OpenAPIContext
from litestar._openapi.responses import (
ResponseFactory,
@@ -35,6 +35,7 @@
from litestar.routes import HTTPRoute
from litestar.status_codes import (
HTTP_200_OK,
+ HTTP_204_NO_CONTENT,
HTTP_307_TEMPORARY_REDIRECT,
HTTP_400_BAD_REQUEST,
HTTP_406_NOT_ACCEPTABLE,
@@ -282,6 +283,29 @@ def redirect_handler() -> Redirect:
assert location.description
+def test_create_success_response_no_content_explicit_responsespec(
+ create_factory: CreateFactoryFixture,
+) -> None:
+ @delete(
+ path="/test",
+ responses={HTTP_204_NO_CONTENT: ResponseSpec(None, description="Custom description")},
+ name="test",
+ )
+ def handler() -> None:
+ return None
+
+ handler = get_registered_route_handler(handler, "test")
+ factory = create_factory(handler)
+ responses = factory.create_additional_responses()
+ status, response = next(responses)
+ assert status == "204"
+ assert response.description == "Custom description"
+ assert not response.content
+
+ with pytest.raises(StopIteration):
+ next(responses)
+
+
def test_create_success_response_file_data(create_factory: CreateFactoryFixture) -> None:
@get(path="/test", name="test")
def file_handler() -> File:
diff --git a/tests/unit/test_openapi/test_spec_generation.py b/tests/unit/test_openapi/test_spec_generation.py
--- a/tests/unit/test_openapi/test_spec_generation.py
+++ b/tests/unit/test_openapi/test_spec_generation.py
@@ -5,7 +5,10 @@
import pytest
from msgspec import Struct
-from litestar import post
+from litestar import delete, post
+from litestar.openapi import ResponseSpec
+from litestar.openapi.spec import OpenAPI
+from litestar.status_codes import HTTP_204_NO_CONTENT
from litestar.testing import create_test_client
from tests.models import DataclassPerson, MsgSpecStructPerson, TypedDictPerson
@@ -48,6 +51,33 @@ def handler(data: cls) -> cls:
}
+def test_spec_generation_no_content() -> None:
+ @delete(
+ "/",
+ status_code=HTTP_204_NO_CONTENT,
+ responses={204: ResponseSpec(None, description="Custom response")},
+ )
+ def handler() -> None:
+ return None
+
+ with create_test_client(handler) as client:
+ schema: OpenAPI = client.app.openapi_schema
+ assert schema.to_schema()["paths"] == {
+ "/": {
+ "delete": {
+ "summary": "Handler",
+ "deprecated": False,
+ "operationId": "Handler",
+ "responses": {
+ "204": {
+ "description": "Custom response",
+ }
+ },
+ },
+ },
+ }
+
+
def test_msgspec_schema() -> None:
class CamelizedStruct(Struct, rename="camel"):
field_one: int
| Bug: `null` type OpenAPI response generated for ResponseSpec(None) / 204
### Description
Attempting to document (empty) error response description something like:
```py
responses={
204: ResponseSpec(None, description="Data successfully wiped")
}
```
`None` is the required `data_container` argument.
This leads to:
```json
"responses": {
"204": {
"description": "Data successfully wiped",
"content": {
"application/json": {
"schema": {
"type": "null",
"examples": {
"nonetype-example-1": {
"description": "Example value"
}
}
}
}
}
}
```
It:
- Generates `content`, which should rather be missing
- Generates example withing the `content`, even though `create_examples` was not enabled (false by default). This is likely related with https://github.com/litestar-org/litestar/issues/3058#issuecomment-1924015790
The `content` should not be there. https://swagger.io/docs/specification/describing-responses/:
> **Response Body**
> Some responses, such as `204 No Content`, have no body. To indicate the response body is empty, do not specify a content for the response:
>
> responses:
> '204':
> description: The resource was deleted successfully.
If `None` is incorrect value to pass here, what would be the right one, to adjust the 204 response?
### MCVE
```python
import uvicorn
from litestar import Litestar, delete
from litestar.openapi import ResponseSpec
@delete(
responses={
204: ResponseSpec(None, description="Data successfully deleted")
}
)
async def delete_user_data() -> None:
pass
app = Litestar(
route_handlers=[delete_user_data],
)
uvicorn.run(app)
```
### Steps to reproduce
```bash
curl http://localhost:8000/schema/openapi.json
```
```json
{
"info": {
"title": "Litestar API",
"version": "1.0.0"
},
"openapi": "3.1.0",
"servers": [
{
"url": "/"
}
],
"paths": {
"/": {
"delete": {
"summary": "DeleteUserData",
"operationId": "DeleteUserData",
"responses": {
"204": {
"description": "Data successfully deleted",
"content": { # <--------- this shouldn't be here
"application/json": {
"schema": {
"type": "null",
"examples": {
"nonetype-example-1": {
"description": "Example value"
}
}
}
}
}
}
},
"deprecated": false
}
}
},
"components": {
"schemas": {}
}
}
```
### Litestar Version
2.5.1
### Platform
- [X] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.
<a href="https://polar.sh/litestar-org/litestar/issues/3069">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/3069/pledge.svg?darkmode=1">
<img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/3069/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
| Seems like a reasonable assessment. Would you be interested in submitting a fix for this?
Yeah, I can try have a look in the coming week. | 2024-02-12T20:22:33 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.