|
| 1 | +import pytest |
| 2 | +from . import current_context, Context |
| 3 | +from .set_tenant_id import set_tenant_id |
| 4 | + |
| 5 | + |
| 6 | +@pytest.fixture(autouse=True) |
| 7 | +def run_around_tests(): |
| 8 | + yield |
| 9 | + current_context.set(None) |
| 10 | + |
| 11 | + |
| 12 | +def _create_context(): |
| 13 | + wsgi_request = { |
| 14 | + "REQUEST_METHOD": "GET", |
| 15 | + "HTTP_HEADER_1": "header 1 value", |
| 16 | + "wsgi.url_scheme": "http", |
| 17 | + "HTTP_HOST": "localhost:8080", |
| 18 | + "PATH_INFO": "/hello", |
| 19 | + "QUERY_STRING": "", |
| 20 | + "CONTENT_TYPE": "application/json", |
| 21 | + "REMOTE_ADDR": "198.51.100.23", |
| 22 | + } |
| 23 | + context = Context(req=wsgi_request, body=None, source="flask") |
| 24 | + context.set_as_current_context() |
| 25 | + return context |
| 26 | + |
| 27 | + |
| 28 | +def test_set_tenant_id_string(): |
| 29 | + ctx = _create_context() |
| 30 | + set_tenant_id("tenant_123") |
| 31 | + assert ctx.tenant_id == "tenant_123" |
| 32 | + |
| 33 | + |
| 34 | +def test_set_tenant_id_integer(): |
| 35 | + ctx = _create_context() |
| 36 | + set_tenant_id(42) |
| 37 | + assert ctx.tenant_id == "42" |
| 38 | + |
| 39 | + |
| 40 | +def test_set_tenant_id_empty_string(caplog): |
| 41 | + ctx = _create_context() |
| 42 | + set_tenant_id("") |
| 43 | + assert ctx.tenant_id is None |
| 44 | + assert "non-empty" in caplog.text |
| 45 | + |
| 46 | + |
| 47 | +def test_set_tenant_id_invalid_type(caplog): |
| 48 | + ctx = _create_context() |
| 49 | + set_tenant_id(12.34) |
| 50 | + assert ctx.tenant_id is None |
| 51 | + assert "expects a string or integer" in caplog.text |
| 52 | + |
| 53 | + |
| 54 | +def test_set_tenant_id_none(caplog): |
| 55 | + ctx = _create_context() |
| 56 | + set_tenant_id(None) |
| 57 | + assert ctx.tenant_id is None |
| 58 | + assert "expects a string or integer" in caplog.text |
| 59 | + |
| 60 | + |
| 61 | +def test_set_tenant_id_dict(caplog): |
| 62 | + ctx = _create_context() |
| 63 | + set_tenant_id({"id": 1}) |
| 64 | + assert ctx.tenant_id is None |
| 65 | + assert "expects a string or integer" in caplog.text |
| 66 | + |
| 67 | + |
| 68 | +def test_set_tenant_id_no_context(caplog): |
| 69 | + import logging |
| 70 | + |
| 71 | + # No context set — should not raise, tenant_id is not applied anywhere |
| 72 | + with caplog.at_level(logging.DEBUG, logger="Zen"): |
| 73 | + set_tenant_id("tenant_123") |
| 74 | + assert "No context set" in caplog.text |
| 75 | + |
| 76 | + |
| 77 | +def test_set_tenant_id_overwrites(): |
| 78 | + ctx = _create_context() |
| 79 | + set_tenant_id("first") |
| 80 | + assert ctx.tenant_id == "first" |
| 81 | + set_tenant_id("second") |
| 82 | + assert ctx.tenant_id == "second" |
0 commit comments