Skip to content

Implement get_code in AssertionRewritingHook so runpy can re-run modules - #14945

Closed
ump45nose wants to merge 3 commits into
pytest-dev:mainfrom
ump45nose:fix-9007-runpy-get-code
Closed

Implement get_code in AssertionRewritingHook so runpy can re-run modules#14945
ump45nose wants to merge 3 commits into
pytest-dev:mainfrom
ump45nose:fix-9007-runpy-get-code

Conversation

@ump45nose

Copy link
Copy Markdown

Problem

Calling runpy.run_module() on a test module that pytest is assert-rewriting
crashes with:

AttributeError: 'AssertionRewritingHook' object has no attribute 'get_code'

runpy obtains a module's code through the loader's get_code() method, but
pytest's AssertionRewritingHook only implemented the exec_module() path used
by normal imports, so re-running a test module via runpy failed.

Fix

Refactor the rewriting logic out of exec_module() into a private
_get_rewritten_code() helper, and implement get_code() on
AssertionRewritingHook to return the rewritten code object for a module.

Test

Added a regression test in testing/test_assertrewrite.py that re-runs a test
module with runpy.run_module() and asserts it passes.

Fixes #9007

@psf-chronographer psf-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Aug 27, 2026
runpy.run_module() calls the loader's get_code() method to obtain the
module's code. AssertionRewritingHook did not implement get_code(), so a
test module re-running itself via runpy crashed with:

    AttributeError: 'AssertionRewritingHook' object has no attribute 'get_code'

Refactor the rewriting logic from exec_module() into a private
_get_rewritten_code() helper and implement get_code() to return the
rewritten code object for a module.

Fixes pytest-dev#9007.
@RonnyPfannschmidt

Copy link
Copy Markdown
Member

how does this interact with nested pytest sessions

yuwk added 2 commits August 27, 2026 21:57
- 优先复用已重写模块的真实文件路径,支持包内测试模块再次执行
- 覆盖嵌套 pytest 会话中外层重写钩子的生命周期
- 补齐未知模块返回路径并消除补丁覆盖率缺口
- 构造可解析但尚未执行的测试模块\n- 覆盖 get_code 的有效 spec origin 分支\n- 补齐 Codecov 报告的缺失行与短路分支
@RonnyPfannschmidt

Copy link
Copy Markdown
Member

unattended ai

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Using stdlib runpy.run_module() causes AttributeError: 'AssertionRewritingHook' object has no attribute 'get_code'

2 participants