File: test_asyncio.py

package info (click to toggle)
python-advanced-alchemy 1.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 3,708 kB
  • sloc: python: 25,811; makefile: 162; javascript: 123; sh: 4
file content (414 lines) | stat: -rw-r--r-- 17,699 bytes parent folder | download | duplicates (2)
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
from __future__ import annotations

import random
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch

import pytest
from asgi_lifespan import LifespanManager
from litestar import Litestar, Request, Response, get
from litestar.status_codes import (
    HTTP_404_NOT_FOUND,
    HTTP_409_CONFLICT,
    HTTP_500_INTERNAL_SERVER_ERROR,
)
from litestar.testing import RequestFactory, create_test_client
from litestar.types.asgi_types import HTTPResponseStartEvent
from pytest import MonkeyPatch
from sqlalchemy.ext.asyncio import AsyncSession

from advanced_alchemy.exceptions import (
    DuplicateKeyError,
    ForeignKeyError,
    ImproperConfigurationError,
    IntegrityError,
    InvalidRequestError,
    NotFoundError,
    RepositoryError,
)
from advanced_alchemy.extensions.litestar._utils import set_aa_scope_state
from advanced_alchemy.extensions.litestar.exception_handler import exception_to_http_response
from advanced_alchemy.extensions.litestar.plugins import SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin
from advanced_alchemy.extensions.litestar.plugins.init.config.asyncio import (
    autocommit_before_send_handler,
    autocommit_handler_maker,
)

if TYPE_CHECKING:
    from typing import Any, Callable

    from litestar.types import Scope


def test_default_before_send_handler() -> None:
    """Test default_before_send_handler."""

    captured_scope_state: dict[str, Any] | None = None
    config = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite://")
    plugin = SQLAlchemyInitPlugin(config=config)

    @get()
    async def test_handler(db_session: AsyncSession, scope: Scope) -> None:
        nonlocal captured_scope_state
        captured_scope_state = scope["state"]
        assert db_session is captured_scope_state[config.session_dependency_key]

    with create_test_client(route_handlers=[test_handler], plugins=[plugin]) as client:
        client.get("/")
        assert captured_scope_state is not None
        assert config.session_dependency_key not in captured_scope_state  # pyright: ignore


def test_default_before_send_handle_multi() -> None:
    """Test default_before_send_handler."""

    captured_scope_state: dict[str, Any] | None = None
    config1 = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite://")
    config2 = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        session_dependency_key="other_session",
        session_scope_key="_sqlalchemy_state_2",
        engine_dependency_key="other_engine",
    )
    plugin = SQLAlchemyInitPlugin(config=[config1, config2])

    @get()
    async def test_handler(db_session: AsyncSession, scope: Scope) -> None:
        nonlocal captured_scope_state
        captured_scope_state = scope["state"]
        assert db_session is captured_scope_state[config1.session_dependency_key]

    with create_test_client(route_handlers=[test_handler], plugins=[plugin]) as client:
        client.get("/")
        assert captured_scope_state is not None
        assert config1.session_dependency_key not in captured_scope_state


async def test_create_all_default(monkeypatch: MonkeyPatch) -> None:
    """Test default_before_send_handler."""

    config = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite://")
    plugin = SQLAlchemyInitPlugin(config=config)
    app = Litestar(route_handlers=[], plugins=[plugin])
    with patch.object(
        config,
        "create_all_metadata",
    ) as create_all_metadata_mock:
        async with LifespanManager(app):  # type: ignore[arg-type]  # pyright: ignore[reportArgumentType]
            create_all_metadata_mock.assert_not_called()


async def test_create_all(monkeypatch: MonkeyPatch) -> None:
    """Test default_before_send_handler."""
    config = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite://", create_all=True)
    plugin = SQLAlchemyInitPlugin(config=config)
    app = Litestar(route_handlers=[], plugins=[plugin])
    with patch.object(
        config,
        "create_all_metadata",
    ) as create_all_metadata_mock:
        async with LifespanManager(app):  # type: ignore[arg-type]   # pyright: ignore[reportArgumentType]
            create_all_metadata_mock.assert_called_once()


async def test_before_send_handler_success_response(create_scope: Callable[..., Scope]) -> None:
    """Test that the session is committed given a success response."""
    config = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        before_send_handler=autocommit_before_send_handler,
    )
    app = Litestar(route_handlers=[], plugins=[SQLAlchemyInitPlugin(config)])
    mock_session = MagicMock(spec=AsyncSession)
    http_scope = create_scope(app=app)
    set_aa_scope_state(http_scope, config.session_scope_key, mock_session)
    http_response_start: HTTPResponseStartEvent = {
        "type": "http.response.start",
        "status": random.randint(200, 299),
        "headers": {},
    }
    await autocommit_before_send_handler(http_response_start, http_scope)
    mock_session.commit.assert_awaited_once()


async def test_before_send_handler_success_response_autocommit(create_scope: Callable[..., Scope]) -> None:
    """Test that the session is committed given a success response."""
    config = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        before_send_handler="autocommit",
    )
    app = Litestar(route_handlers=[], plugins=[SQLAlchemyInitPlugin(config)])
    mock_session = MagicMock(spec=AsyncSession)
    http_scope = create_scope(app=app)
    set_aa_scope_state(http_scope, config.session_scope_key, mock_session)
    http_response_start: HTTPResponseStartEvent = {
        "type": "http.response.start",
        "status": random.randint(200, 299),
        "headers": {},
    }
    await autocommit_before_send_handler(http_response_start, http_scope)
    mock_session.commit.assert_awaited_once()


async def test_before_send_handler_error_response(create_scope: Callable[..., Scope]) -> None:
    """Test that the session is rolled back given an error response."""
    config = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        before_send_handler=autocommit_before_send_handler,
    )
    app = Litestar(route_handlers=[], plugins=[SQLAlchemyInitPlugin(config)])
    mock_session = MagicMock(spec=AsyncSession)
    http_scope = create_scope(app=app)
    set_aa_scope_state(http_scope, config.session_scope_key, mock_session)
    http_response_start: HTTPResponseStartEvent = {
        "type": "http.response.start",
        "status": random.randint(300, 599),
        "headers": {},
    }
    await autocommit_before_send_handler(http_response_start, http_scope)
    mock_session.rollback.assert_awaited_once()


async def test_autocommit_handler_maker_redirect_response(create_scope: Callable[..., Scope]) -> None:
    """Test that the handler created by the handler maker commits on redirect"""
    autocommit_redirect_handler = autocommit_handler_maker(commit_on_redirect=True)
    config = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        before_send_handler=autocommit_redirect_handler,
    )
    app = Litestar(route_handlers=[], plugins=[SQLAlchemyInitPlugin(config)])
    mock_session = MagicMock(spec=AsyncSession)
    http_scope = create_scope(app=app)
    set_aa_scope_state(http_scope, config.session_scope_key, mock_session)
    http_response_start: HTTPResponseStartEvent = {
        "type": "http.response.start",
        "status": random.randint(300, 399),
        "headers": {},
    }
    await autocommit_redirect_handler(http_response_start, http_scope)
    mock_session.commit.assert_awaited_once()


async def test_autocommit_handler_maker_commit_statuses(create_scope: Callable[..., Scope]) -> None:
    """Test that the handler created by the handler maker commits on explicit statuses"""
    custom_autocommit_handler = autocommit_handler_maker(extra_commit_statuses={302, 303})
    config = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        before_send_handler=custom_autocommit_handler,
    )
    app = Litestar(route_handlers=[], plugins=[SQLAlchemyInitPlugin(config)])
    mock_session = MagicMock(spec=AsyncSession)
    http_scope = create_scope(app=app)
    set_aa_scope_state(http_scope, config.session_scope_key, mock_session)
    http_response_start: HTTPResponseStartEvent = {
        "type": "http.response.start",
        "status": random.randint(302, 303),
        "headers": {},
    }
    await custom_autocommit_handler(http_response_start, http_scope)
    mock_session.commit.assert_awaited_once()


async def test_autocommit_handler_maker_rollback_statuses(create_scope: Callable[..., Scope]) -> None:
    """Test that the handler created by the handler maker rolls back on explicit statuses"""
    custom_autocommit_handler = autocommit_handler_maker(commit_on_redirect=True, extra_rollback_statuses={307, 308})
    config = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        before_send_handler=custom_autocommit_handler,
    )
    app = Litestar(route_handlers=[], plugins=[SQLAlchemyInitPlugin(config)])
    mock_session = MagicMock(spec=AsyncSession)
    http_scope = create_scope(app=app)
    set_aa_scope_state(http_scope, config.session_scope_key, mock_session)
    http_response_start: HTTPResponseStartEvent = {
        "type": "http.response.start",
        "status": random.randint(307, 308),
        "headers": {},
    }
    await custom_autocommit_handler(http_response_start, http_scope)
    mock_session.rollback.assert_awaited_once()


async def test_autocommit_handler_maker_rollback_statuses_multi(create_scope: Callable[..., Scope]) -> None:
    """Test that the handler created by the handler maker rolls back on explicit statuses"""
    custom_autocommit_handler = autocommit_handler_maker(
        session_scope_key="_sqlalchemy_state_2",
        commit_on_redirect=True,
        extra_rollback_statuses={307, 308},
    )
    config1 = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
    )
    config2 = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        before_send_handler=custom_autocommit_handler,
        session_dependency_key="other_session",
        engine_dependency_key="other_engine",
        session_scope_key="_sqlalchemy_state_2",
    )
    app = Litestar(route_handlers=[], plugins=[SQLAlchemyInitPlugin(config=[config1, config2])])
    mock_session1 = MagicMock(spec=AsyncSession)
    mock_session2 = MagicMock(spec=AsyncSession)
    http_scope = create_scope(app=app)
    set_aa_scope_state(http_scope, config1.session_scope_key, mock_session1)
    set_aa_scope_state(http_scope, config2.session_scope_key, mock_session2)
    http_response_start: HTTPResponseStartEvent = {
        "type": "http.response.start",
        "status": random.randint(307, 308),
        "headers": {},
    }
    await custom_autocommit_handler(http_response_start, http_scope)

    mock_session2.rollback.assert_called_once()
    mock_session1.rollback.assert_not_called()


async def test_autocommit_handler_maker_rollback_statuses_multi_bad_config(create_scope: Callable[..., Scope]) -> None:
    """Test that the handler created by the handler maker rolls back on explicit statuses"""
    with pytest.raises(ImproperConfigurationError):
        custom_autocommit_handler = autocommit_handler_maker(
            session_scope_key="_sqlalchemy_state_2",
            commit_on_redirect=True,
            extra_rollback_statuses={307, 308},
        )
        config1 = SQLAlchemyAsyncConfig(
            connection_string="sqlite+aiosqlite://",
        )
        config2 = SQLAlchemyAsyncConfig(
            connection_string="sqlite+aiosqlite://",
            before_send_handler=custom_autocommit_handler,
            session_dependency_key="other_session",
            session_scope_key="_sqlalchemy_state_2",
        )
        app = Litestar(route_handlers=[], plugins=[SQLAlchemyInitPlugin(config=[config1, config2])])
        mock_session1 = MagicMock(spec=AsyncSession)
        mock_session2 = MagicMock(spec=AsyncSession)
        http_scope = create_scope(app=app)
        set_aa_scope_state(http_scope, config1.session_scope_key, mock_session1)
        set_aa_scope_state(http_scope, config2.session_scope_key, mock_session2)
        http_response_start: HTTPResponseStartEvent = {
            "type": "http.response.start",
            "status": random.randint(307, 308),
            "headers": {},
        }
        await custom_autocommit_handler(http_response_start, http_scope)

        mock_session2.rollback.assert_called_once()
        mock_session1.rollback.assert_not_called()


async def test_autocommit_handler_maker_multi(create_scope: Callable[..., Scope]) -> None:
    """Test that the handler created by the handler maker rolls back on explicit statuses"""

    config1 = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        before_send_handler="autocommit",
    )
    config2 = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        before_send_handler="autocommit",
        session_dependency_key="other_session",
        engine_dependency_key="other_engine",
    )
    app = Litestar(route_handlers=[], plugins=[SQLAlchemyInitPlugin(config=[config1, config2])])
    mock_session1 = MagicMock(spec=AsyncSession)
    mock_session2 = MagicMock(spec=AsyncSession)
    http_scope = create_scope(app=app)
    set_aa_scope_state(http_scope, config1.session_scope_key, mock_session1)
    set_aa_scope_state(http_scope, config2.session_scope_key, mock_session2)
    http_response_start: HTTPResponseStartEvent = {
        "type": "http.response.start",
        "status": random.randint(307, 308),
        "headers": {},
    }
    await config2.before_send_handler(http_response_start, http_scope)  # type: ignore
    mock_session2.rollback.assert_called_once()
    mock_session1.rollback.assert_not_called()


@pytest.mark.parametrize(
    ("exc", "status"),
    [
        (IntegrityError, HTTP_409_CONFLICT),
        (ForeignKeyError, HTTP_409_CONFLICT),
        (DuplicateKeyError, HTTP_409_CONFLICT),
        (InvalidRequestError, HTTP_500_INTERNAL_SERVER_ERROR),
        (NotFoundError, HTTP_404_NOT_FOUND),
    ],
)
def test_repository_exception_to_http_response(exc: type[RepositoryError], status: int) -> None:
    """Test default exception handler."""

    config1 = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite://")
    config2 = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        session_dependency_key="other_session",
        session_scope_key="_sqlalchemy_state_2",
        engine_dependency_key="other_engine",
    )
    plugin = SQLAlchemyInitPlugin(config=[config1, config2])
    app = Litestar(route_handlers=[], plugins=[plugin])
    request = RequestFactory(app=app, server="testserver").get("/wherever")
    response = exception_to_http_response(request, exc())
    assert app.exception_handlers.get(exc) is None
    assert app.exception_handlers.get(RepositoryError) is not None
    assert response.status_code == status


@pytest.mark.parametrize(
    ("exc", "status"),
    [
        (IntegrityError, HTTP_409_CONFLICT),
        (ForeignKeyError, HTTP_409_CONFLICT),
        (DuplicateKeyError, HTTP_409_CONFLICT),
        (InvalidRequestError, HTTP_500_INTERNAL_SERVER_ERROR),
        (NotFoundError, HTTP_404_NOT_FOUND),
    ],
)
def test_existing_repository_exception_to_http_response(exc: type[RepositoryError], status: int) -> None:
    """Test default exception handler."""

    def handler(request: Request[Any, Any, Any], exc: RepositoryError) -> Response[Any]:
        return Response(status_code=200, content="OK")

    config1 = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite://")
    config2 = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        session_dependency_key="other_session",
        session_scope_key="_sqlalchemy_state_2",
        engine_dependency_key="other_engine",
    )
    plugin = SQLAlchemyInitPlugin(config=[config1, config2])
    app = Litestar(route_handlers=[], plugins=[plugin], exception_handlers={RepositoryError: handler})
    request = RequestFactory(app=app, server="testserver").get("/wherever")
    response = handler(request, exc())
    assert app.exception_handlers.get(exc) is None
    assert app.exception_handlers.get(RepositoryError) is not None
    assert app.exception_handlers.get(RepositoryError) == handler
    assert response.status_code == 200


@pytest.mark.parametrize(
    ("exc", "status"),
    [
        (IntegrityError, HTTP_409_CONFLICT),
        (ForeignKeyError, HTTP_409_CONFLICT),
        (DuplicateKeyError, HTTP_409_CONFLICT),
        (InvalidRequestError, HTTP_500_INTERNAL_SERVER_ERROR),
        (NotFoundError, HTTP_404_NOT_FOUND),
    ],
)
def test_repository_disabled_exception_to_http_response(exc: type[RepositoryError], status: int) -> None:
    """Test default exception handler."""

    config1 = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite://", set_default_exception_handler=False)
    config2 = SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite://",
        session_dependency_key="other_session",
        session_scope_key="_sqlalchemy_state_2",
        engine_dependency_key="other_engine",
        set_default_exception_handler=False,
    )
    plugin = SQLAlchemyInitPlugin(config=[config1, config2])
    app = Litestar(route_handlers=[], plugins=[plugin])
    assert app.exception_handlers.get(exc) is None
    assert app.exception_handlers.get(RepositoryError) is None