Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixtures: fix crash when parametrize(scope="package") is used without a Package #11256

Merged
merged 1 commit into from
Jul 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/11255.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed crash on `parametrize(..., scope="package")` without a package present.
18 changes: 13 additions & 5 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,8 @@ def get_scope_node(
def add_funcarg_pseudo_fixture_def(
collector: nodes.Collector, metafunc: "Metafunc", fixturemanager: "FixtureManager"
) -> None:
import _pytest.python

# This function will transform all collected calls to functions
# if they use direct funcargs (i.e. direct parametrization)
# because we want later test execution to be able to rely on
Expand Down Expand Up @@ -192,11 +194,17 @@ def add_funcarg_pseudo_fixture_def(
if scope is not Scope.Function:
node = get_scope_node(collector, scope)
if node is None:
assert scope is Scope.Class and isinstance(
collector, _pytest.python.Module
)
# Use module-level collector for class-scope (for now).
node = collector
# If used class scope and there is no class, use module-level
# collector (for now).
if scope is Scope.Class:
assert isinstance(collector, _pytest.python.Module)
node = collector
# If used package scope and there is no package, use session
# (for now).
elif scope is Scope.Package:
node = collector.session
else:
assert False, f"Unhandled missing scope: {scope}"
if node is None:
name2pseudofixturedef = None
else:
Expand Down
17 changes: 17 additions & 0 deletions testing/python/metafunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1486,6 +1486,23 @@ def test_foo(x):
]
)

@pytest.mark.parametrize("scope", ["class", "package"])
def test_parametrize_missing_scope_doesnt_crash(
self, pytester: Pytester, scope: str
) -> None:
"""Doesn't crash when parametrize(scope=<scope>) is used without a
corresponding <scope> node."""
pytester.makepyfile(
f"""
import pytest

@pytest.mark.parametrize("x", [0], scope="{scope}")
def test_it(x): pass
"""
)
result = pytester.runpytest()
assert result.ret == 0


class TestMetafuncFunctionalAuto:
"""Tests related to automatically find out the correct scope for
Expand Down