pytest-dev / pytest-dev/pytest
Request for function to import module directly from file with rewritten assertions
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 14.5k
- Forks
- 3.4k
- Avg merge
- 2d 9h
- Merged PRs (30d)
- 35
Description
What's the problem this feature will solve?
Currently (from what I gather), the only place assertion rewriting is exposed is from register_assert_rewrite. As far as I can tell, this function doesn't enable rewriting of modules that are imported directly from file. The only workaround is to do something like this:
def import_from_file(modulename, filename):
from _pytest.assertion import rewrite
# Copied from https://github.com/pytest-dev/pytest/blob/6247a956010855f227181ba6167c89bb500e9480/src/_pytest/assertion/__init__.py#L62
for hook in sys.meta_path:
if isinstance(hook, rewrite.AssertionRewritingHook):
importhook = hook
break
else:
raise RuntimeError
loader = importhook
spec = importlib.util.spec_from_file_location(modulename, filename, loader=loader)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
Describe the solution you'd like
It'd be nice if there was a function that enabled this workflow. Maybe something like import_test_module_from_file(modulename, filename)?
Alternative Solutions
Additional context
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the assertion-rewriting hook referenced in src/_pytest/assertion/init.py and the _pytest.assertion.rewrite workaround shown in the issue. Trace how direct-from-file imports are currently constructed, then determine the public API and tests needed for the requested workflow. Done means a supported function can import a module from a file with assertion rewriting enabled.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100