1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
|
from __future__ import annotations
import importlib.util
import logging
import os
import random
import shutil
import string
import sys
from datetime import datetime
from os import urandom
from pathlib import Path
from typing import TYPE_CHECKING, Any, AsyncGenerator, Callable, Generator, cast
from unittest.mock import AsyncMock, MagicMock
import pytest
from pytest_lazy_fixtures import lf
from redis.asyncio import Redis as AsyncRedis
from redis.client import Redis
from time_machine import Coordinates, travel
#from valkey.asyncio import Valkey as AsyncValkey
#from valkey.client import Valkey
from litestar.logging import LoggingConfig
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.openapi.config import OpenAPIConfig
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.stores.valkey import ValkeyStore
from litestar.testing import RequestFactory
from tests.helpers import not_none
if TYPE_CHECKING:
from types import ModuleType
from pytest import FixtureRequest, MonkeyPatch
from time_machine import Coordinates
from litestar import Litestar
from litestar.types import (
AnyIOBackend,
ASGIApp,
ASGIVersion,
GetLogger,
Receive,
RouteHandlerType,
Scope,
ScopeSession,
Send,
)
# pytest_plugins = ["tests.docker_service_fixtures"]
@pytest.fixture
def mock() -> MagicMock:
return MagicMock()
@pytest.fixture()
def async_mock() -> AsyncMock:
return AsyncMock()
@pytest.fixture(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]
@pytest.fixture()
def mock_asgi_app() -> ASGIApp:
async def asgi_app(scope: Scope, receive: Receive, send: Send) -> None: ...
return asgi_app
@pytest.fixture()
def redis_store(redis_client: AsyncRedis) -> RedisStore:
return RedisStore(redis=redis_client)
@pytest.fixture()
def valkey_store(valkey_client: AsyncValkey) -> ValkeyStore:
return ValkeyStore(valkey=valkey_client)
@pytest.fixture()
def memory_store() -> MemoryStore:
return MemoryStore()
@pytest.fixture()
def file_store(tmp_path: Path) -> FileStore:
return FileStore(path=tmp_path)
@pytest.fixture()
def file_store_create_directories(tmp_path: Path) -> FileStore:
path = tmp_path / "subdir1" / "subdir2"
return FileStore(path=path, create_directories=True)
@pytest.fixture()
def file_store_create_directories_flag_false(tmp_path: Path) -> FileStore:
shutil.rmtree(tmp_path, ignore_errors=True) # in case the path was already created by different tests - we clean it
return FileStore(path=tmp_path.joinpath("subdir"), create_directories=False)
@pytest.fixture(
params=[
pytest.param("redis_store", marks=pytest.mark.xdist_group("redis")),
pytest.param("valkey_store", marks=pytest.mark.xdist_group("valkey")),
"memory_store",
"file_store",
]
)
def store(request: FixtureRequest) -> Store:
return cast("Store", request.getfixturevalue(request.param))
@pytest.fixture
def cookie_session_backend_config() -> CookieBackendConfig:
return CookieBackendConfig(secret=urandom(16))
@pytest.fixture()
def cookie_session_backend(cookie_session_backend_config: CookieBackendConfig) -> ClientSideSessionBackend:
return ClientSideSessionBackend(config=cookie_session_backend_config)
@pytest.fixture(
params=[
pytest.param(lf("cookie_session_backend_config"), id="cookie"),
pytest.param(lf("server_side_session_config"), id="server-side"),
]
)
def session_backend_config(request: pytest.FixtureRequest) -> ServerSideSessionConfig | CookieBackendConfig:
return cast("ServerSideSessionConfig | CookieBackendConfig", request.param)
@pytest.fixture()
def server_side_session_config() -> ServerSideSessionConfig:
return ServerSideSessionConfig()
@pytest.fixture()
def server_side_session_backend(server_side_session_config: ServerSideSessionConfig) -> ServerSideSessionBackend:
return ServerSideSessionBackend(config=server_side_session_config)
@pytest.fixture(
params=[
pytest.param("cookie_session_backend", id="cookie"),
pytest.param("server_side_session_backend", id="server-side"),
]
)
def session_backend(request: pytest.FixtureRequest) -> BaseSessionBackend:
return cast("BaseSessionBackend", request.getfixturevalue(request.param))
@pytest.fixture()
def session_backend_config_memory(memory_store: MemoryStore) -> ServerSideSessionConfig:
return ServerSideSessionConfig()
@pytest.fixture
def session_middleware(session_backend: BaseSessionBackend, mock_asgi_app: ASGIApp) -> SessionMiddleware[Any]:
return SessionMiddleware(app=mock_asgi_app, backend=session_backend)
@pytest.fixture
def cookie_session_middleware(
cookie_session_backend: ClientSideSessionBackend, mock_asgi_app: ASGIApp
) -> SessionMiddleware[ClientSideSessionBackend]:
return SessionMiddleware(app=mock_asgi_app, backend=cookie_session_backend)
@pytest.fixture
def test_client_backend(anyio_backend_name: str) -> AnyIOBackend:
return cast("AnyIOBackend", anyio_backend_name)
@pytest.fixture
def create_scope() -> Callable[..., Scope]:
def inner(
*,
type: str = "http",
app: Litestar | None = None,
asgi: ASGIVersion | None = None,
auth: Any = None,
client: tuple[str, int] | None = ("testclient", 50000),
extensions: dict[str, dict[object, object]] | None = None,
http_version: str = "1.1",
path: str = "/",
path_params: dict[str, str] | None = None,
query_string: str = "",
root_path: str = "",
route_handler: RouteHandlerType | None = None,
scheme: str = "http",
server: tuple[str, int | None] | None = ("testserver", 80),
session: ScopeSession | None = None,
state: dict[str, Any] | None = None,
user: Any = None,
**kwargs: dict[str, Any],
) -> Scope:
scope = {
"app": app,
"litestar_app": app,
"asgi": asgi or {"spec_version": "2.0", "version": "3.0"},
"auth": auth,
"type": type,
"path": path,
"raw_path": path.encode(),
"root_path": root_path,
"scheme": scheme,
"query_string": query_string.encode(),
"client": client,
"server": server,
"method": "GET",
"http_version": http_version,
"extensions": extensions or {"http.response.template": {}},
"state": state or {},
"path_params": path_params or {},
"route_handler": route_handler,
"user": user,
"session": session,
"headers": [],
**kwargs,
}
return cast("Scope", scope)
return inner
@pytest.fixture
def scope(create_scope: Callable[..., Scope]) -> Scope:
return create_scope()
@pytest.fixture
def create_module(tmp_path: Path, monkeypatch: MonkeyPatch) -> Callable[[str], ModuleType]:
"""Utility fixture for dynamic module creation."""
def wrapped(source: str) -> ModuleType:
"""
Args:
source: Source code as a string.
Returns:
An imported module.
"""
def module_name_generator() -> str:
letters = string.ascii_lowercase
return "".join(random.choice(letters) for _ in range(10))
module_name = module_name_generator()
path = tmp_path / f"{module_name}.py"
path.write_text(source)
# https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
spec = not_none(importlib.util.spec_from_file_location(module_name, path))
module = not_none(importlib.util.module_from_spec(spec))
monkeypatch.setitem(sys.modules, module_name, module)
not_none(spec.loader).exec_module(module)
return module
return wrapped
@pytest.fixture()
def frozen_datetime() -> Generator[Coordinates, None, None]:
with travel(datetime.utcnow, tick=False) as frozen:
yield frozen
@pytest.fixture()
def request_factory() -> RequestFactory:
return RequestFactory()
@pytest.fixture()
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
@pytest.fixture(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
@pytest.fixture()
def disable_warn_sync_to_thread_with_async(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setenv("LITESTAR_WARN_SYNC_TO_THREAD_WITH_ASYNC", "0")
@pytest.fixture()
def enable_warn_implicit_sync_to_thread(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setenv("LITESTAR_WARN_IMPLICIT_SYNC_TO_THREAD", "1")
@pytest.fixture
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(
logging_module="logging",
loggers={
"litestar": {"level": "INFO", "handlers": ["queue_listener"], "propagate": True},
},
).configure()
@pytest.fixture()
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
Redis(host=docker_ip, port=6397).flushall()
client: AsyncRedis = AsyncRedis(host=docker_ip, port=6397)
yield client
try:
await client.aclose() # type: ignore[attr-defined]
except RuntimeError:
pass
@pytest.fixture()
async def valkey_client(docker_ip: str, valkey_service: None) -> AsyncGenerator[AsyncValkey, None]:
# this is to get around some weirdness with pytest-asyncio and valkey interaction
# on 3.8 and 3.9
Valkey(host=docker_ip, port=6381).flushall()
client: AsyncValkey = AsyncValkey(host=docker_ip, port=6381)
yield client
try:
await client.aclose()
except RuntimeError:
pass
@pytest.fixture(autouse=True)
def _patch_openapi_config(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("litestar.app.DEFAULT_OPENAPI_CONFIG", OpenAPIConfig(title="Litestar API", version="1.0.0"))
|