Skip to content

Commit bf62cbb

Browse files
committed
fixtures: fix crash when parametrize(scope="package") is used without a Package
There as handling for `scope="class"` without a class, but not for `scope="package"` without a package. It would fail the assert.
1 parent 448563c commit bf62cbb

File tree

3 files changed

+29
-5
lines changed

3 files changed

+29
-5
lines changed

changelog/11255.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed crash on `parametrize(..., scope="package")` without a package present.

src/_pytest/fixtures.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ def get_scope_node(
155155
def add_funcarg_pseudo_fixture_def(
156156
collector: nodes.Collector, metafunc: "Metafunc", fixturemanager: "FixtureManager"
157157
) -> None:
158+
import _pytest.python
159+
158160
# This function will transform all collected calls to functions
159161
# if they use direct funcargs (i.e. direct parametrization)
160162
# because we want later test execution to be able to rely on
@@ -192,11 +194,17 @@ def add_funcarg_pseudo_fixture_def(
192194
if scope is not Scope.Function:
193195
node = get_scope_node(collector, scope)
194196
if node is None:
195-
assert scope is Scope.Class and isinstance(
196-
collector, _pytest.python.Module
197-
)
198-
# Use module-level collector for class-scope (for now).
199-
node = collector
197+
# If used class scope and there is no class, use module-level
198+
# collector (for now).
199+
if scope is Scope.Class:
200+
assert isinstance(collector, _pytest.python.Module)
201+
node = collector
202+
# If used package scope and there is no package, use session
203+
# (for now).
204+
elif scope is Scope.Package:
205+
node = collector.session
206+
else:
207+
assert False, f"Unhandled missing scope: {scope}"
200208
if node is None:
201209
name2pseudofixturedef = None
202210
else:

testing/python/metafunc.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1486,6 +1486,21 @@ def test_foo(x):
14861486
]
14871487
)
14881488

1489+
@pytest.mark.parametrize("scope", ["class", "package"])
1490+
def test_parametrize_missing_scope_doesnt_crash(
1491+
self, pytester: Pytester, scope: str
1492+
) -> None:
1493+
"""Doesn't crash when parametrize(scope=<scope>) is used without a
1494+
corresponding <scope> node."""
1495+
pytester.makepyfile(
1496+
f"""
1497+
import pytest
1498+
1499+
@pytest.mark.parametrize("x", [0], scope="{scope}")
1500+
def test_it(x): pass
1501+
"""
1502+
)
1503+
14891504

14901505
class TestMetafuncFunctionalAuto:
14911506
"""Tests related to automatically find out the correct scope for

0 commit comments

Comments
 (0)