5
5
6
6
import argparse
7
7
import collections .abc
8
+ import contextlib
8
9
import copy
9
10
import dataclasses
10
11
import enum
73
74
from _pytest .cacheprovider import Cache
74
75
from _pytest .terminal import TerminalReporter
75
76
76
-
77
77
_PluggyPlugin = object
78
78
"""A type to represent plugin objects.
79
79
@@ -1077,7 +1077,7 @@ def __init__(
1077
1077
self ._inicache : dict [str , Any ] = {}
1078
1078
self ._override_ini : Sequence [str ] = ()
1079
1079
self ._opt2dest : dict [str , str ] = {}
1080
- self ._cleanup : list [ Callable [[], None ]] = []
1080
+ self ._cleanup_stack = contextlib . ExitStack ()
1081
1081
self .pluginmanager .register (self , "pytestconfig" )
1082
1082
self ._configured = False
1083
1083
self .hook .pytest_addoption .call_historic (
@@ -1106,8 +1106,9 @@ def inipath(self) -> pathlib.Path | None:
1106
1106
1107
1107
def add_cleanup (self , func : Callable [[], None ]) -> None :
1108
1108
"""Add a function to be called when the config object gets out of
1109
- use (usually coinciding with pytest_unconfigure)."""
1110
- self ._cleanup .append (func )
1109
+ use (usually coinciding with pytest_unconfigure).
1110
+ """
1111
+ self ._cleanup_stack .callback (func )
1111
1112
1112
1113
def _do_configure (self ) -> None :
1113
1114
assert not self ._configured
@@ -1117,13 +1118,18 @@ def _do_configure(self) -> None:
1117
1118
self .hook .pytest_configure .call_historic (kwargs = dict (config = self ))
1118
1119
1119
1120
def _ensure_unconfigure (self ) -> None :
1120
- if self ._configured :
1121
- self ._configured = False
1122
- self .hook .pytest_unconfigure (config = self )
1123
- self .hook .pytest_configure ._call_history = []
1124
- while self ._cleanup :
1125
- fin = self ._cleanup .pop ()
1126
- fin ()
1121
+ try :
1122
+ if self ._configured :
1123
+ self ._configured = False
1124
+ try :
1125
+ self .hook .pytest_unconfigure (config = self )
1126
+ finally :
1127
+ self .hook .pytest_configure ._call_history = []
1128
+ finally :
1129
+ try :
1130
+ self ._cleanup_stack .close ()
1131
+ finally :
1132
+ self ._cleanup_stack = contextlib .ExitStack ()
1127
1133
1128
1134
def get_terminal_writer (self ) -> TerminalWriter :
1129
1135
terminalreporter : TerminalReporter | None = self .pluginmanager .get_plugin (
0 commit comments