pytest icon indicating copy to clipboard operation
pytest copied to clipboard

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

Open hjtran opened this issue 2 years ago • 0 comments

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

hjtran avatar May 19 '22 21:05 hjtran