Skip to content

Commit 1e736b6

Browse files
committed
Issue pytest-dev#362: Only unconfigure if configured
`pytest_unconfigure` can be called even if `pytest_configure` was not. In order to avoid errors during unconfigure only perform the unconfigure if the configure was performed. Add a counter which is incremented before configure to track the number of times pytest started initialization so that the config is not popped early from the stack.
1 parent 30ba3f7 commit 1e736b6

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/pytest_bdd/plugin.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@
2121
from .parser import Feature, Scenario, Step
2222

2323

24+
# Counter to track how many times pytest initialization was started
25+
_INIT_COUNT = 0
26+
27+
2428
def pytest_addhooks(pluginmanager: PytestPluginManager) -> None:
2529
"""Register plugin hooks."""
2630
from pytest_bdd import hooks
@@ -52,6 +56,8 @@ def _pytest_bdd_example() -> dict:
5256

5357
def pytest_addoption(parser: Parser) -> None:
5458
"""Add pytest-bdd options."""
59+
global _INIT_COUNT
60+
_INIT_COUNT += 1
5561
add_bdd_ini(parser)
5662
cucumber_json.add_options(parser)
5763
generation.add_options(parser)
@@ -66,14 +72,19 @@ def add_bdd_ini(parser: Parser) -> None:
6672
def pytest_configure(config: Config) -> None:
6773
"""Configure all subplugins."""
6874
CONFIG_STACK.append(config)
75+
assert _INIT_COUNT == len(CONFIG_STACK)
6976
cucumber_json.configure(config)
7077
gherkin_terminal_reporter.configure(config)
7178

7279

7380
def pytest_unconfigure(config: Config) -> None:
7481
"""Unconfigure all subplugins."""
75-
CONFIG_STACK.pop()
76-
cucumber_json.unconfigure(config)
82+
global _INIT_COUNT
83+
assert len(CONFIG_STACK) <= _INIT_COUNT
84+
if len(CONFIG_STACK) == _INIT_COUNT:
85+
CONFIG_STACK.pop()
86+
_INIT_COUNT -= 1
87+
cucumber_json.unconfigure(config)
7788

7889

7990
@pytest.hookimpl(hookwrapper=True)

tests/test_hooks.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,17 @@ def pytest_bdd_after_scenario(request, feature, scenario):
135135

136136
assert scenario_1.name == "Scenario 1"
137137
assert scenario_2.name == "Scenario 2"
138+
139+
140+
def test_pytest_unconfigure_without_configure(pytester):
141+
pytester.makeconftest(
142+
"""
143+
import pytest
144+
145+
def pytest_configure(config):
146+
pytest.exit("Exit during configure", 0)
147+
"""
148+
)
149+
150+
result = pytester.runpytest()
151+
assert result.ret == 0

0 commit comments

Comments
 (0)