Skip to content

Commit 11c9772

Browse files
committed
Fix BlackSheep cross-task database access
BlackSheep initializes the ORM in its lifespan task, but request tasks could not see that context because the global fallback was disabled. Enable the same fallback used by the other ASGI integrations and add a regression test for the startup configuration.
1 parent 8c12adc commit 11c9772

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

tests/contrib/test_blacksheep.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from unittest.mock import AsyncMock, patch
2+
3+
import pytest
4+
from blacksheep.server import Application
5+
6+
from tortoise.contrib.blacksheep import register_tortoise
7+
8+
9+
@pytest.mark.asyncio
10+
async def test_register_tortoise_enables_global_fallback() -> None:
11+
with (
12+
patch("tortoise.contrib.blacksheep.Tortoise") as mocked_tortoise,
13+
patch("tortoise.contrib.blacksheep.get_connections"),
14+
):
15+
mocked_tortoise.init = AsyncMock()
16+
mocked_tortoise.close_connections = AsyncMock()
17+
app = Application()
18+
register_tortoise(
19+
app,
20+
db_url="sqlite://:memory:",
21+
modules={"models": ["__main__"]},
22+
)
23+
24+
await app.start()
25+
mocked_tortoise.init.assert_awaited_once_with(
26+
config=None,
27+
config_file=None,
28+
db_url="sqlite://:memory:",
29+
modules={"models": ["__main__"]},
30+
_enable_global_fallback=True,
31+
)
32+
33+
await app.stop()
34+
mocked_tortoise.close_connections.assert_awaited_once()

tortoise/contrib/blacksheep/__init__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,13 @@ def register_tortoise(
8989

9090
@app.on_start
9191
async def init_orm(context) -> None: # pylint: disable=W0612
92-
await Tortoise.init(config=config, config_file=config_file, db_url=db_url, modules=modules)
92+
await Tortoise.init(
93+
config=config,
94+
config_file=config_file,
95+
db_url=db_url,
96+
modules=modules,
97+
_enable_global_fallback=True,
98+
)
9399
logger.info("Tortoise-ORM started, %s, %s", get_connections()._get_storage(), Tortoise.apps)
94100
if generate_schemas:
95101
logger.info("Tortoise-ORM generating schema")

0 commit comments

Comments
 (0)