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
33
34
from typing import TextIO
34
35
from typing import Type
35
36
from typing import TYPE_CHECKING
37
+ from typing import TypeVar
36
38
import warnings
37
39
38
40
import pluggy
73
75
from _pytest .cacheprovider import Cache
74
76
from _pytest .terminal import TerminalReporter
75
77
78
+ _T_callback = TypeVar ("_T_callback" , bound = Callable [[], None ])
79
+
76
80
77
81
_PluggyPlugin = object
78
82
"""A type to represent plugin objects.
@@ -1077,7 +1081,7 @@ def __init__(
1077
1081
self ._inicache : dict [str , Any ] = {}
1078
1082
self ._override_ini : Sequence [str ] = ()
1079
1083
self ._opt2dest : dict [str , str ] = {}
1080
- self ._cleanup : list [ Callable [[], None ]] = []
1084
+ self ._exit_stack = contextlib . ExitStack ()
1081
1085
self .pluginmanager .register (self , "pytestconfig" )
1082
1086
self ._configured = False
1083
1087
self .hook .pytest_addoption .call_historic (
@@ -1104,10 +1108,11 @@ def inipath(self) -> pathlib.Path | None:
1104
1108
"""
1105
1109
return self ._inipath
1106
1110
1107
- def add_cleanup (self , func : Callable [[], None ] ) -> None :
1111
+ def add_cleanup (self , func : _T_callback ) -> _T_callback :
1108
1112
"""Add a function to be called when the config object gets out of
1109
1113
use (usually coinciding with pytest_unconfigure)."""
1110
- self ._cleanup .append (func )
1114
+ self ._exit_stack .callback (func )
1115
+ return func
1111
1116
1112
1117
def _do_configure (self ) -> None :
1113
1118
assert not self ._configured
@@ -1117,13 +1122,18 @@ def _do_configure(self) -> None:
1117
1122
self .hook .pytest_configure .call_historic (kwargs = dict (config = self ))
1118
1123
1119
1124
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 ()
1125
+ try :
1126
+ if self ._configured :
1127
+ self ._configured = False
1128
+ try :
1129
+ self .hook .pytest_unconfigure (config = self )
1130
+ finally :
1131
+ self .hook .pytest_configure ._call_history = []
1132
+ finally :
1133
+ try :
1134
+ self ._exit_stack .close ()
1135
+ finally :
1136
+ self ._exit_stack = contextlib .ExitStack ()
1127
1137
1128
1138
def get_terminal_writer (self ) -> TerminalWriter :
1129
1139
terminalreporter : TerminalReporter | None = self .pluginmanager .get_plugin (
0 commit comments