Closed
Description
Sometimes it can be very useful to write tests for functions that rely on some data in the request context, but without using a full Starlette test client, as tests that are based on test clients are much less "lean" and do a lot of things beyond just running the code unit under test.
I think it would be very useful to document / add some helpers that enable a context manager that mocks a request / response cycle / middleware / etc. so it can be used in testing.
For now, I have done this in my tests (I'm using pytest fixtures, this is a very simplified example):
code under test
from starlette_context import context
def get_session_id():
"""Get the current session ID"""
return context['session_id']
in conftest.py
:
import pytest
from starlette_context import _request_scope_context_storage, context
@pytest.fixture()
def request_context():
token = _request_scope_context_storage.set({})
try:
yield context
finally:
_request_scope_context_storage.reset(token)
in tests:
from myapp.session_utils import get_session_id
def test_some_func_that_relies_on_context(request_context):
request_context['session_id'] = 'foobar'
assert get_session_id() == 'foobar'
Obviously, this is a bit hackish and it would be nice if there would be an official / documented way of doing this without accessing module internals.