2
2
import os
3
3
import sys
4
4
from typing import Generator
5
- from typing import TextIO
6
5
7
6
import pytest
8
7
from _pytest .config import Config
11
10
from _pytest .stash import StashKey
12
11
13
12
14
- fault_handler_stderr_key = StashKey [TextIO ]()
13
+ fault_handler_stderr_fd_key = StashKey [int ]()
15
14
fault_handler_originally_enabled_key = StashKey [bool ]()
16
15
17
16
@@ -26,22 +25,19 @@ def pytest_addoption(parser: Parser) -> None:
26
25
def pytest_configure (config : Config ) -> None :
27
26
import faulthandler
28
27
29
- stderr_fd_copy = os .dup (get_stderr_fileno ())
30
- config .stash [fault_handler_stderr_key ] = open (
31
- stderr_fd_copy , "w" , encoding = sys .stderr .encoding
32
- )
28
+ config .stash [fault_handler_stderr_fd_key ] = os .dup (get_stderr_fileno ())
33
29
config .stash [fault_handler_originally_enabled_key ] = faulthandler .is_enabled ()
34
- faulthandler .enable (file = config .stash [fault_handler_stderr_key ])
30
+ faulthandler .enable (file = config .stash [fault_handler_stderr_fd_key ])
35
31
36
32
37
33
def pytest_unconfigure (config : Config ) -> None :
38
34
import faulthandler
39
35
40
36
faulthandler .disable ()
41
37
# Close the dup file installed during pytest_configure.
42
- if fault_handler_stderr_key in config .stash :
43
- config .stash [fault_handler_stderr_key ]. close ( )
44
- del config .stash [fault_handler_stderr_key ]
38
+ if fault_handler_stderr_fd_key in config .stash :
39
+ os . close ( config .stash [fault_handler_stderr_fd_key ] )
40
+ del config .stash [fault_handler_stderr_fd_key ]
45
41
if config .stash .get (fault_handler_originally_enabled_key , False ):
46
42
# Re-enable the faulthandler if it was originally enabled.
47
43
faulthandler .enable (file = get_stderr_fileno ())
@@ -69,10 +65,10 @@ def get_timeout_config_value(config: Config) -> float:
69
65
@pytest .hookimpl (hookwrapper = True , trylast = True )
70
66
def pytest_runtest_protocol (item : Item ) -> Generator [None , None , None ]:
71
67
timeout = get_timeout_config_value (item .config )
72
- stderr = item .config .stash [fault_handler_stderr_key ]
73
- if timeout > 0 and stderr is not None :
68
+ if timeout > 0 :
74
69
import faulthandler
75
70
71
+ stderr = item .config .stash [fault_handler_stderr_fd_key ]
76
72
faulthandler .dump_traceback_later (timeout , file = stderr )
77
73
try :
78
74
yield
0 commit comments