import asyncio import gc import inspect import pytest from app.core import background_tasks as bt @pytest.mark.asyncio async def test_spawn_tracked_holds_strong_ref_and_discards(): ev = asyncio.Event() async def work(): await ev.wait() t = bt.spawn_tracked_v2(work()) gc.collect() assert t in bt._tracked ev.set() await t await asyncio.sleep(0) assert t not in bt._tracked @pytest.mark.asyncio async def test_registered_in_main_drain_set(): import app.main as main ev = asyncio.Event() async def work(): await ev.wait() t = bt.spawn_tracked_v2(work()) assert t in main._background_tasks ev.set() await t await asyncio.sleep(0) assert t not in main._background_tasks def test_manual_buy_uses_tracked_spawn(): from app.api.endpoints import manual_buy src = inspect.getsource(manual_buy) assert "asyncio.create_task(_delayed_sync_portfolio" not in src assert "spawn_tracked_v2(_delayed_sync_portfolio" in src