Skip to content

Commit f3a7936

Browse files
test(pydantic-ai): Create event loop before invoking sync methods (#6475)
Pydantic AI creates an event loop when synchronous agent methods run without an active loop, but does not close it. Manually create and manage an event loop in tests that do not rely on `pytest-asyncio`.
1 parent 6bee147 commit f3a7936

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

tests/integrations/pydantic_ai/test_pydantic_ai.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,20 @@ def inner():
5555
return inner
5656

5757

58+
@pytest.fixture
59+
def sync_event_loop():
60+
# Pydantic AI creates an event loop if there is none and doesn't close it in synchronous methods.
61+
# Run with "-X tracemalloc=25 -W default::ResourceWarning" to reproduce.
62+
# https://github.com/pydantic/pydantic-ai/commit/a58dd47f9cd6494665e47bf7cf71fccbfce2c0dd
63+
loop = asyncio.new_event_loop()
64+
asyncio.set_event_loop(loop)
65+
try:
66+
yield loop
67+
finally:
68+
loop.close()
69+
asyncio.set_event_loop(None)
70+
71+
5872
@pytest.mark.parametrize("span_streaming", [True, False])
5973
@pytest.mark.parametrize("stream_gen_ai_spans", [True, False])
6074
@pytest.mark.asyncio
@@ -284,6 +298,7 @@ def test_agent_run_sync(
284298
get_test_agent,
285299
stream_gen_ai_spans,
286300
span_streaming,
301+
sync_event_loop,
287302
):
288303
"""
289304
Test that the integration creates spans for sync agent runs.
@@ -381,6 +396,7 @@ def test_agent_run_sync_model_error(
381396
capture_items,
382397
stream_gen_ai_spans,
383398
span_streaming,
399+
sync_event_loop,
384400
):
385401
sentry_init(
386402
integrations=[PydanticAIIntegration()],
@@ -1985,7 +2001,7 @@ async def test_context_cleanup_after_run(sentry_init, get_test_agent):
19852001
assert "pydantic_ai_agent" not in scope._contexts
19862002

19872003

1988-
def test_context_cleanup_after_run_sync(sentry_init, get_test_agent):
2004+
def test_context_cleanup_after_run_sync(sentry_init, get_test_agent, sync_event_loop):
19892005
"""
19902006
Test that the pydantic_ai_agent context is properly cleaned up after sync agent execution.
19912007
"""

0 commit comments

Comments
 (0)