File: test_session.py

package info (click to toggle)
python-advanced-alchemy 1.8.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,904 kB
  • sloc: python: 36,227; makefile: 153; sh: 4
file content (564 lines) | stat: -rw-r--r-- 20,870 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
"""Integration tests for Litestar session backend extensions.

These tests run against actual database instances to verify that session backends
work correctly across all supported database backends.
"""

import asyncio
import datetime
import uuid
from collections.abc import AsyncGenerator, Generator
from functools import partial
from typing import Optional
from unittest.mock import Mock

import pytest
from litestar import Litestar, Request, get, post
from litestar.middleware.session import SessionMiddleware
from litestar.middleware.session.server_side import ServerSideSessionConfig
from litestar.stores.base import Store
from litestar.testing import AsyncTestClient
from sqlalchemy import Engine, select
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from sqlalchemy.orm import DeclarativeBase, Session

from advanced_alchemy.extensions.litestar.plugins.init.config.asyncio import SQLAlchemyAsyncConfig
from advanced_alchemy.extensions.litestar.plugins.init.config.sync import SQLAlchemySyncConfig
from advanced_alchemy.extensions.litestar.session import (
    SessionModelMixin,
    SQLAlchemyAsyncSessionBackend,
    SQLAlchemySyncSessionBackend,
)
from tests.integration.helpers import cleanup_database, cleanup_database_async

pytestmark = [
    pytest.mark.integration,
    pytest.mark.xdist_group("litestar_session"),  # Isolate session tests to prevent interference
]


# Module-level cache for model classes to prevent recreation
_session_model_cache: "dict[str, type]" = {}


@pytest.fixture(scope="session")
def session_model_class(request: pytest.FixtureRequest) -> "type[SessionModelMixin]":
    """Create session model class once per session/worker.

    This fixture creates a unique model class per pytest session or xdist worker
    to prevent metadata conflicts while allowing table reuse across tests.
    """
    # Get worker ID for xdist parallel execution
    worker_id = getattr(request.config, "workerinput", {}).get("workerid", "master")
    cache_key = f"session_{worker_id}"

    if cache_key not in _session_model_cache:

        class TestSessionBase(DeclarativeBase):
            pass

        class IntegrationTestSessionModel(SessionModelMixin, TestSessionBase):
            """Test session model for integration tests."""

            __tablename__ = f"integration_test_sessions_{worker_id}"

        _session_model_cache[cache_key] = IntegrationTestSessionModel

    return _session_model_cache[cache_key]


@pytest.fixture
def session_tables_setup(
    engine: Engine, session_model_class: "type[SessionModelMixin]"
) -> "Generator[type[SessionModelMixin], None, None]":
    """Create session tables for each test run but reuse model classes.

    Tables are created per database engine type but model classes are cached
    to prevent recreation. Fast data cleanup is used between individual tests.
    """
    # Skip for Spanner - doesn't support UNIQUE constraints directly
    # Skip for MSSQL - doesn't support random() function used in session backends
    dialect_name = getattr(engine.dialect, "name", "")
    if dialect_name == "spanner+spanner":
        pytest.skip("Spanner doesn't support direct UNIQUE constraints creation")

    # Skip table creation for mock engines
    if dialect_name != "mock":
        session_model_class.metadata.create_all(engine)

    yield session_model_class

    # Clean up tables at end of test run for this engine
    if getattr(engine.dialect, "name", "") != "mock":
        try:
            with cleanup_database(engine) as cleaner:
                # Get table names from metadata
                tables_to_clean = [table.name for table in session_model_class.metadata.sorted_tables]
                cleaner.include_only = set(tables_to_clean) if tables_to_clean else None
                cleaner.cleanup()
        except Exception:
            # Ignore cleanup errors - they don't affect test results
            pass


@pytest.fixture
async def async_session_tables_setup(
    async_engine: AsyncEngine, session_model_class: "type[SessionModelMixin]"
) -> "AsyncGenerator[type[SessionModelMixin], None]":
    """Create async session tables for each test run but reuse model classes.

    Tables are created per database engine type but model classes are cached
    to prevent recreation. Fast data cleanup is used between individual tests.
    """
    # Skip for Spanner - doesn't support UNIQUE constraints directly
    # Skip for MSSQL - doesn't support random() function used in session backends
    dialect_name = getattr(async_engine.dialect, "name", "")
    if dialect_name == "spanner+spanner":
        pytest.skip("Spanner doesn't support direct UNIQUE constraints creation")

    # Skip table creation for mock engines
    if dialect_name != "mock":
        async with async_engine.begin() as conn:
            await conn.run_sync(session_model_class.metadata.create_all)

    yield session_model_class

    # Clean up tables at end of test run for this engine
    if getattr(async_engine.dialect, "name", "") != "mock":
        try:
            async with cleanup_database_async(async_engine) as cleaner:
                # Get table names from metadata
                tables_to_clean = [table.name for table in session_model_class.metadata.sorted_tables]
                cleaner.include_only = set(tables_to_clean) if tables_to_clean else None
                await cleaner.cleanup()
        except Exception:
            # Ignore cleanup errors - they don't affect test results
            pass


@pytest.fixture
def test_session_model(session_tables_setup: "type[SessionModelMixin]") -> "type[SessionModelMixin]":
    """Per-test fixture - no cleanup needed with session-scoped engines.

    Session-scoped engines are incompatible with per-test cleanup.
    Tables are cleaned up only at session end via session_tables_setup.
    """
    return session_tables_setup


@pytest.fixture
async def async_test_session_model(async_session_tables_setup: "type[SessionModelMixin]") -> "type[SessionModelMixin]":
    """Per-test async fixture - no cleanup needed with session-scoped engines.

    Session-scoped engines are incompatible with per-test cleanup.
    Tables are cleaned up only at session end via async_session_tables_setup.
    """
    return async_session_tables_setup


@pytest.fixture
def mock_store() -> Store:
    """Create a mock store for testing."""
    return Mock(spec=Store)


# Session backend fixtures
@pytest.fixture
def sync_session_config(engine: Engine) -> SQLAlchemySyncConfig:
    """Create sync config with test engine."""
    return SQLAlchemySyncConfig(
        engine_instance=engine,
        session_dependency_key="db_session",
    )


@pytest.fixture
async def async_session_config(async_engine: AsyncEngine) -> SQLAlchemyAsyncConfig:
    """Create async config with test engine."""
    return SQLAlchemyAsyncConfig(
        engine_instance=async_engine,
        session_dependency_key="db_session",
    )


@pytest.fixture
def sync_session_backend(
    sync_session_config: SQLAlchemySyncConfig, test_session_model: "type[SessionModelMixin]"
) -> SQLAlchemySyncSessionBackend:
    """Create sync session backend."""
    return SQLAlchemySyncSessionBackend(
        config=ServerSideSessionConfig(max_age=3600),
        alchemy_config=sync_session_config,
        model=test_session_model,
    )


@pytest.fixture
async def async_session_backend(
    async_session_config: SQLAlchemyAsyncConfig, async_test_session_model: "type[SessionModelMixin]"
) -> SQLAlchemyAsyncSessionBackend:
    """Create async session backend."""
    return SQLAlchemyAsyncSessionBackend(
        config=ServerSideSessionConfig(max_age=3600),
        alchemy_config=async_session_config,
        model=async_test_session_model,
    )


# Legacy database setup fixtures - now no-ops since tables are session-scoped
@pytest.fixture
def setup_sync_database() -> "Generator[None, None, None]":
    """Legacy fixture - tables are now session-scoped, no setup needed."""
    yield


@pytest.fixture
async def setup_async_database() -> "AsyncGenerator[None, None]":
    """Legacy fixture - tables are now session-scoped, no setup needed."""
    yield


def _handle_database_encoding(data: Optional[bytes], expected: bytes, dialect_name: str) -> None:
    """Handle database-specific encoding issues."""
    if dialect_name.startswith("spanner") and data != expected:
        import base64

        # Spanner base64 encodes binary data
        if data:
            try:
                decoded_data = base64.b64decode(data)
                assert decoded_data == expected, f"Expected {expected!r}, got decoded {decoded_data!r} from {data!r}"
            except Exception:
                assert data == expected, f"Spanner: Expected {expected!r}, got {data!r}"
        return

    assert data == expected, f"Expected {expected!r}, got {data!r}"


# Session Backend Tests
async def test_async_session_backend_complete_lifecycle(
    async_session_backend: SQLAlchemyAsyncSessionBackend,
    async_session: AsyncSession,
    mock_store: Store,
    setup_async_database: None,
) -> None:
    """Test complete session lifecycle: create, retrieve, update, delete."""

    # Skip mock engines - integration tests should test real databases
    engine_instance = async_session_backend.alchemy.engine_instance
    if engine_instance is not None and getattr(engine_instance.dialect, "name", "") == "mock":
        pytest.skip("Mock engine cannot test real database operations")

    # Skip Spanner - doesn't support direct UNIQUE constraints
    if async_session.bind is not None and getattr(async_session.bind.dialect, "name", "") == "spanner+spanner":
        pytest.skip("Spanner doesn't support direct UNIQUE constraints creation. Create UNIQUE indexes instead.")

    session_id = str(uuid.uuid4())
    original_data = b"test_data_123"
    updated_data = b"updated_data_456"

    dialect_name = getattr(async_session.bind.dialect, "name", "")

    # Create session
    await async_session_backend.set(session_id, original_data, mock_store)

    # Retrieve session
    retrieved_data = await async_session_backend.get(session_id, mock_store)
    _handle_database_encoding(retrieved_data, original_data, dialect_name)

    # Update session
    await async_session_backend.set(session_id, updated_data, mock_store)

    # Verify update
    retrieved_data = await async_session_backend.get(session_id, mock_store)
    _handle_database_encoding(retrieved_data, updated_data, dialect_name)

    # Delete session
    await async_session_backend.delete(session_id, mock_store)

    # Verify deletion
    retrieved_data = await async_session_backend.get(session_id, mock_store)
    assert retrieved_data is None


async def test_sync_session_backend_complete_lifecycle(
    sync_session_backend: SQLAlchemySyncSessionBackend,
    session: Session,
    mock_store: Store,
    setup_sync_database: None,
) -> None:
    """Test complete session lifecycle with sync backend."""
    session_id = str(uuid.uuid4())
    original_data = b"sync_test_data"
    updated_data = b"sync_updated_data"

    # Skip mock engines
    if session.bind is not None and getattr(session.bind.dialect, "name", "") == "mock":
        pytest.skip("Mock engine cannot test real database operations")

    # Skip Spanner - doesn't support direct UNIQUE constraints
    if session.bind is not None and getattr(session.bind.dialect, "name", "") == "spanner+spanner":
        pytest.skip("Spanner doesn't support direct UNIQUE constraints creation. Create UNIQUE indexes instead.")

    dialect_name = getattr(session.bind.dialect, "name", "") if session.bind is not None else ""

    # Create session
    await sync_session_backend.set(session_id, original_data, mock_store)

    # Retrieve session
    retrieved_data = await sync_session_backend.get(session_id, mock_store)
    _handle_database_encoding(retrieved_data, original_data, dialect_name)

    # Update session
    await sync_session_backend.set(session_id, updated_data, mock_store)

    # Verify update
    retrieved_data = await sync_session_backend.get(session_id, mock_store)
    _handle_database_encoding(retrieved_data, updated_data, dialect_name)

    # Delete session
    await sync_session_backend.delete(session_id, mock_store)

    # Verify deletion
    retrieved_data = await sync_session_backend.get(session_id, mock_store)
    assert retrieved_data is None


async def test_async_session_backend_expiration(
    async_engine: AsyncEngine,
    async_test_session_model: "type[SessionModelMixin]",
    mock_store: Store,
    setup_async_database: None,
) -> None:
    """Test session expiration handling."""
    # Skip mock engines
    if getattr(async_engine.dialect, "name", "") == "mock":
        pytest.skip("Mock engine cannot test real database operations")

    # Create config with very short expiration
    config = SQLAlchemyAsyncConfig(
        engine_instance=async_engine,
        session_dependency_key="db_session",
    )

    backend = SQLAlchemyAsyncSessionBackend(
        config=ServerSideSessionConfig(max_age=1),  # 1 second
        alchemy_config=config,
        model=async_test_session_model,
    )

    session_id = str(uuid.uuid4())
    data = b"expires_soon"

    # Create session
    await backend.set(session_id, data, mock_store)

    # Verify it exists
    retrieved_data = await backend.get(session_id, mock_store)
    dialect_name = getattr(async_engine.dialect, "name", "")

    # Oracle MERGE statements may not be immediately visible due to transaction isolation
    # The backend uses MERGE statements which require explicit commit for visibility
    if dialect_name == "oracle" and retrieved_data is None:
        # For Oracle, briefly wait and retry since MERGE may need transaction settle time
        await asyncio.sleep(0.2)
        retrieved_data = await backend.get(session_id, mock_store)

        # If still None, Oracle MERGE timing issue - this is a known limitation
        if retrieved_data is None:
            pytest.skip("Oracle MERGE statement visibility issue in test environment")

    _handle_database_encoding(retrieved_data, data, dialect_name)

    # Wait for expiration
    await asyncio.sleep(2)

    # Should return None and delete expired session
    assert await backend.get(session_id, mock_store) is None


async def test_async_session_backend_delete_all(
    async_session_backend: SQLAlchemyAsyncSessionBackend,
    mock_store: Store,
    setup_async_database: None,
) -> None:
    """Test deletion of all sessions."""
    # Skip mock engines
    engine_instance = async_session_backend.alchemy.engine_instance
    if engine_instance is not None and getattr(engine_instance.dialect, "name", "") == "mock":
        pytest.skip("Mock engine cannot test real database operations")

    # Create multiple sessions
    session_ids = [str(uuid.uuid4()) for _ in range(5)]
    for sid in session_ids:
        await async_session_backend.set(sid, b"data", mock_store)

    # Delete all
    await async_session_backend.delete_all(mock_store)

    # Verify all deleted
    for sid in session_ids:
        assert await async_session_backend.get(sid, mock_store) is None


async def test_async_session_backend_delete_expired(
    async_session_backend: SQLAlchemyAsyncSessionBackend,
    async_session: AsyncSession,
    mock_store: Store,
    setup_async_database: None,
) -> None:
    """Test bulk deletion of expired sessions."""
    # Skip mock engines
    if getattr(async_session.bind.dialect, "name", "") == "mock":
        pytest.skip("Mock engine cannot test real database operations")

    now = datetime.datetime.now(datetime.timezone.utc)
    test_session_model = async_session_backend.model

    # Create mix of expired and active sessions
    expired_ids = [str(uuid.uuid4()) for _ in range(3)]
    active_ids = [str(uuid.uuid4()) for _ in range(2)]

    # Insert expired sessions directly
    async with async_session_backend.alchemy.get_session() as db_session:
        for sid in expired_ids:
            session_obj = test_session_model(
                session_id=sid,
                data=b"expired",
                expires_at=now - datetime.timedelta(hours=1),
            )
            db_session.add(session_obj)
        await db_session.commit()

    # Create active sessions through backend
    for sid in active_ids:
        await async_session_backend.set(sid, b"active", mock_store)

    # Delete expired
    await async_session_backend.delete_expired()

    # Verify only active sessions remain
    async with async_session_backend.alchemy.get_session() as db_session:
        result = await db_session.execute(select(test_session_model.session_id))
        remaining_ids = {row[0] for row in result}
        assert remaining_ids == set(active_ids)


# Litestar Integration Tests
async def test_async_session_middleware_integration(
    async_engine: AsyncEngine,
    async_test_session_model: "type[SessionModelMixin]",
    setup_async_database: None,
) -> None:
    """Test async session backend with Litestar middleware."""
    # Skip mock engines
    if getattr(async_engine.dialect, "name", "") == "mock":
        pytest.skip("Mock engine cannot test real database operations")

    config = SQLAlchemyAsyncConfig(
        engine_instance=async_engine,
        session_dependency_key="db_session",
    )

    backend = SQLAlchemyAsyncSessionBackend(
        config=ServerSideSessionConfig(max_age=3600, key="test-session"),
        alchemy_config=config,
        model=async_test_session_model,
    )

    @get("/set")
    async def set_session(request: Request) -> "dict[str, str]":
        request.session["user_id"] = "123"
        request.session["username"] = "testuser"
        return {"status": "session set"}

    @get("/get")
    async def get_session(request: Request) -> "dict[str, Optional[str]]":
        return {
            "user_id": request.session.get("user_id"),
            "username": request.session.get("username"),
        }

    @post("/clear")
    async def clear_session(request: Request) -> "dict[str, str]":
        request.clear_session()
        return {"status": "session cleared"}

    app = Litestar(
        route_handlers=[set_session, get_session, clear_session],
        middleware=[partial(SessionMiddleware, backend=backend)],
    )

    async with AsyncTestClient(app=app) as client:
        # Set session data
        response = await client.get("/set")
        assert response.status_code == 200
        assert response.json() == {"status": "session set"}

        # Get session data
        response = await client.get("/get")
        assert response.status_code == 200
        assert response.json() == {"user_id": "123", "username": "testuser"}

        # Clear session
        response = await client.post("/clear")
        assert response.status_code == 201
        assert response.json() == {"status": "session cleared"}

        # Verify cleared
        response = await client.get("/get")
        assert response.status_code == 200
        assert response.json() == {"user_id": None, "username": None}


async def test_sync_session_middleware_integration(
    engine: Engine,
    test_session_model: "type[SessionModelMixin]",
    setup_sync_database: None,
) -> None:
    """Test sync session backend with Litestar middleware."""
    # Skip mock engines
    if getattr(engine.dialect, "name", "") == "mock":
        pytest.skip("Mock engine cannot test real database operations")

    config = SQLAlchemySyncConfig(
        engine_instance=engine,
        session_dependency_key="db_session",
    )

    backend = SQLAlchemySyncSessionBackend(
        config=ServerSideSessionConfig(max_age=3600, key="test-session"),
        alchemy_config=config,
        model=test_session_model,
    )

    @get("/set", sync_to_thread=False)
    def set_session(request: Request) -> "dict[str, int]":
        counter = request.session.get("counter", 0) + 1
        request.session["counter"] = counter
        return {"counter": counter}

    @get("/get", sync_to_thread=False)
    def get_session(request: Request) -> "dict[str, Optional[int]]":
        return {"counter": request.session.get("counter")}

    app = Litestar(
        route_handlers=[set_session, get_session],
        middleware=[partial(SessionMiddleware, backend=backend)],
    )

    async with AsyncTestClient(app=app) as client:
        # Initial set
        response = await client.get("/set")
        assert response.status_code == 200
        assert response.json() == {"counter": 1}

        # Increment counter
        response = await client.get("/set")
        assert response.status_code == 200
        assert response.json() == {"counter": 2}

        # Get current value
        response = await client.get("/get")
        assert response.status_code == 200
        assert response.json() == {"counter": 2}