Skip to content

fix: support GLib event loop policy in scoped runner (#1233) - #1555

Closed
sunilkumarvalmiki wants to merge 1 commit into
pytest-dev:mainfrom
sunilkumarvalmiki:contrib/lane-b-glib-1233
Closed

fix: support GLib event loop policy in scoped runner (#1233)#1555
sunilkumarvalmiki wants to merge 1 commit into
pytest-dev:mainfrom
sunilkumarvalmiki:contrib/lane-b-glib-1233

Conversation

@sunilkumarvalmiki

Copy link
Copy Markdown

Description

Fixes #1233: pytest-asyncio failed with a RuntimeError whenever a test was collected under GLibEventLoopPolicy, because the scoped runner's asyncio.Runner._lazy_init() calls events.set_event_loop(loop) and GLib's set_event_loop() rejects any loop attached on the main thread (it already owns the main GLib.MainContext).

Fix

When the user hasn't supplied an explicit loop_factory, pass the policy's existing event loop as loop_factory to asyncio.Runner. The runner then uses the policy's loop and skips the rejecting set_event_loop() call entirely. The policy's loop already lives in the GLib main context, so this is the lifecycle-correct attachment rather than a workaround.

GLib detection is done by policy.__class__.__module__ == "gi.events" — no gi import is performed, so non-GLib environments see no change.

Tests

New test_event_loop_fixture_supports_glib_policy regression test in tests/test_event_loop_fixture.py runs in a subprocess for isolation.

Gate Result
Reproduction (task-2-repro.py) before fix RED — RuntimeError
Reproduction after fix GREEN — 1 passed
New regression test without fix RED
New regression test with fix PASSED
44 focused event-loop tests 44 passed
Broader gate (235 tests across all event-loop and loop-factory tests) 235 passed, 3 skipped

The pre-existing baseline failure in test_set_event_loop.py is unrelated and was not touched.

Fixes: #1233

Issue pytest-dev#1233: avoid setting a managed loop when GLib's main-context
loop is already attached. Preserves non-GLib behavior and avoids
the existing baseline test_set_event_loop.py failure.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@tjkuson

tjkuson commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Thank you for the PR, but I am against solving this issue by treating the GLib event loop policy as privileged within the plugin itself. I would rather solve the issue at its root. Also, please ensure the tox checks are passing before marking a PR as ready for review.

@tjkuson tjkuson closed this Sep 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

"RuntimeError: Thread 'MainThread' already has a main context" when used with glib event loop

3 participants