pytest-bdd
pytest-bdd copied to clipboard
Assertions not rewritten for steps in files with names that don't match Pytest's python_files setting
pytest-bdd steps in files with names that don't match pytest's patterns in thepython_files
settings, like steps.py, given.py, when.py then.py, are not picked up by pytests assertion rewriting.
Here's a simple setup to reproduce: https://github.com/blaise-io/pytest-bdd-assertion-rewrite-issue.
In most apps this can be fixed by using pytest.register_assert_rewrite
to register modules containing steps, but I'd expect pytest-bdd to either do that for me or for pytest-bdd to warn me about this limitation.
For pytest-bdd to register steps modules magically seemed only possible with heavy monkey patching, as pytest does not allow registering a module for rewriting when the module is already imported. The following code registers the module of a steps for assertion rewriting, which is to demonstrate why monkey patching is a bad idea:
# append to pytest_bdd.steps.contribute_to_module
from _pytest.assertion import rewrite
from six.moves import reload_module
for hook in sys.meta_path:
if isinstance(hook, rewrite.AssertionRewritingHook):
# Add module file name to python_files patterns
if module.__file__ not in hook.fnpats:
hook.fnpats.append(module.__file__)
# Remove module path from checks
if name in hook._rewritten_names:
hook._rewritten_names.remove(name)
# Force-reload the module after our rewrite in setattr
reload_module(module)
break