55
66import argparse
77import collections .abc
8+ import contextlib
89import copy
910import dataclasses
1011import enum
3334from typing import TextIO
3435from typing import Type
3536from typing import TYPE_CHECKING
37+ from typing import TypeVar
3638import warnings
3739
3840import pluggy
7375 from _pytest .cacheprovider import Cache
7476 from _pytest .terminal import TerminalReporter
7577
78+ _T_callback = TypeVar ("_T_callback" , bound = Callable [[], None ])
79+
7680
7781_PluggyPlugin = object
7882"""A type to represent plugin objects.
@@ -1085,6 +1089,7 @@ def __init__(
10851089 )
10861090 self .args_source = Config .ArgsSource .ARGS
10871091 self .args : list [str ] = []
1092+ self ._exit_stack = contextlib .ExitStack ()
10881093
10891094 @property
10901095 def rootpath (self ) -> pathlib .Path :
@@ -1104,10 +1109,11 @@ def inipath(self) -> pathlib.Path | None:
11041109 """
11051110 return self ._inipath
11061111
1107- def add_cleanup (self , func : Callable [[], None ] ) -> None :
1112+ def add_cleanup (self , func : _T_callback ) -> _T_callback :
11081113 """Add a function to be called when the config object gets out of
11091114 use (usually coinciding with pytest_unconfigure)."""
1110- self ._cleanup .append (func )
1115+ self ._exit_stack .callback (func )
1116+ return func
11111117
11121118 def _do_configure (self ) -> None :
11131119 assert not self ._configured
@@ -1117,13 +1123,18 @@ def _do_configure(self) -> None:
11171123 self .hook .pytest_configure .call_historic (kwargs = dict (config = self ))
11181124
11191125 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 ()
1126+ try :
1127+ if self ._configured :
1128+ self ._configured = False
1129+ try :
1130+ self .hook .pytest_unconfigure (config = self )
1131+ finally :
1132+ self .hook .pytest_configure ._call_history = []
1133+ finally :
1134+ try :
1135+ self ._exit_stack .close ()
1136+ finally :
1137+ self ._exit_stack = contextlib .ExitStack ()
11271138
11281139 def get_terminal_writer (self ) -> TerminalWriter :
11291140 terminalreporter : TerminalReporter | None = self .pluginmanager .get_plugin (
0 commit comments