pytest-dev / pytest-dev/pytest

Request for function to import module directly from file with rewritten assertions

Open
#9,977 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: rewrite type: proposal
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.