feat: add tenant_context module — ContextVar, transaction listener, tenant_filter

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
chihlasm
2026-04-10 03:48:34 +00:00
parent 6f1becf21f
commit b4f8694f6b
2 changed files with 135 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
import asyncio
from uuid import UUID
import pytest
from unittest.mock import MagicMock
from app.core.tenant_context import (
set_current_account_id,
clear_current_account_id,
get_current_account_id,
)
def test_contextvar_is_none_by_default():
assert get_current_account_id() is None
def test_set_and_clear():
account_id = UUID("aaaaaaaa-0000-0000-0000-000000000001")
token = set_current_account_id(account_id)
assert get_current_account_id() == str(account_id)
clear_current_account_id(token)
assert get_current_account_id() is None
def test_tasks_are_isolated():
"""Each asyncio task has its own ContextVar value."""
results = {}
async def set_in_task(name: str, value: str):
token = set_current_account_id(UUID(value))
await asyncio.sleep(0)
results[name] = get_current_account_id()
clear_current_account_id(token)
async def run():
await asyncio.gather(
set_in_task("a", "aaaaaaaa-0000-0000-0000-000000000001"),
set_in_task("b", "bbbbbbbb-0000-0000-0000-000000000002"),
)
asyncio.run(run())
assert results["a"] == "aaaaaaaa-0000-0000-0000-000000000001"
assert results["b"] == "bbbbbbbb-0000-0000-0000-000000000002"