1"""Name a child that ended on a console control event, and who shared the console.
3Registered through livery-workshop's ``pytest11`` entry point, so every
4pytest this venv starts carries it. A process on Windows that receives
5a console control event, Ctrl+C or Ctrl+Break or the console closing,
6exits with ``STATUS_CONTROL_C_EXIT`` (``0xC000013A``, 3221225786 as
7Python reads it). A test whose git child ends that way fails with the
8bare number, and one sighting in a run of thousands of tests leaves
9nothing to bisect. When a failed test's exception carries that status,
10this plugin adds a section to the failure report: the command, the
11process and its worker, the run, every control event this process's
12own handler saw in the session with the time it arrived, and every
13process attached to the console at the moment of the report, by id
14and image name. On another platform the section says so and carries
15what it can.
17The handler this plugin installs records events and passes them on: it
18returns false to the console, so the interpreter's own handling is
19untouched.
20"""
43 0: "CTRL_C_EVENT",
44 1: "CTRL_BREAK_EVENT",
45 2: "CTRL_CLOSE_EVENT",
46 5: "CTRL_LOGOFF_EVENT",
47 6: "CTRL_SHUTDOWN_EVENT",
48}
52 """Whether *code* is ``STATUS_CONTROL_C_EXIT``, as Python or the shell spells it."""
53 return code in (STATUS_CONTROL_C_EXIT, _SIGNED)
57 """Every exit code a failure carries: a called process's, down its cause chain."""
58 codes: list[int] = []
59 seen = 0
60 current = error
61 while current is not None and seen < 10:
62 code = getattr(current, "returncode", None)
63 if isinstance(code, int) and not isinstance(code, bool):
64 codes.append(code)
65 text = str(current)
66 if str(STATUS_CONTROL_C_EXIT) in text and STATUS_CONTROL_C_EXIT not in codes:
67 codes.append(STATUS_CONTROL_C_EXIT)
68 current = current.__cause__ or current.__context__
69 seen += 1
70 return codes
74 """Install the recording handler on Windows; elsewhere there is no console."""
75 del config
76 if sys.platform != "win32":
77 return
78 _install_handler()
82 global _HANDLER
83 if sys.platform != "win32" or _HANDLER is not None:
84 return
90 _EVENTS.append((time.time(), event))
91 return False # recorded, never consumed
99 """The processes attached to this console, by id and image; None off Windows."""
100 if sys.platform != "win32":
101 return None
102 import ctypes
104 kernel32 = ctypes.windll.kernel32
105 room = 64
106 while True:
107 ids = (ctypes.c_uint * room)()
108 count = kernel32.GetConsoleProcessList(ids, room)
109 if count == 0:109 ↛ 110line 109 didn't jump to line 110 because the condition on line 109 was never true
110 return []
111 if count <= room:111 ↛ 113line 111 didn't jump to line 113 because the condition on line 111 was always true
112 break
113 room = count
114 found: list[tuple[int, str]] = []
115 for pid in list(ids)[:count]:
116 found.append((int(pid), _image_name(int(pid))))
117 return found
121 """The executable behind *pid*, or a word for why it cannot be read."""
122 if sys.platform != "win32":122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true
123 return "unreadable"
124 import ctypes
126 kernel32 = ctypes.windll.kernel32
127 query_limited = 0x1000
128 handle = kernel32.OpenProcess(query_limited, False, pid)
129 if not handle:129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true
130 return "unreadable"
131 try:
132 size = ctypes.c_uint(1024)
133 buffer = ctypes.create_unicode_buffer(size.value)
134 if not kernel32.QueryFullProcessImageNameW(134 ↛ 137line 134 didn't jump to line 137 because the condition on line 134 was never true
135 handle, 0, buffer, ctypes.byref(size)
136 ):
137 return "unnamed"
138 return os.path.basename(buffer.value)
139 finally:
140 kernel32.CloseHandle(handle)
144 """The section's text for a failure that carries the control-exit status."""
145 lines = [
146 "a child ended with STATUS_CONTROL_C_EXIT (0xC000013A, 3221225786): a"
147 " console control event reached it; the exit is not the child's own",
148 ]
149 command = getattr(error, "cmd", None)
150 if command is not None:
151 lines.append(f"command: {command!r}")
152 lines.append(f"cwd: {os.getcwd()}")
153 lines.append(
154 f"this process: pid {os.getpid()}, parent {os.getppid()}, worker"
155 f" {os.environ.get('PYTEST_XDIST_WORKER', 'none')}"
156 )
157 run = {
158 key: os.environ[key]
159 for key in ("GITHUB_RUN_ID", "GITHUB_JOB", "RUNNER_NAME", "RUNNER_OS")
160 if os.environ.get(key)
161 }
162 lines.append(f"run: {run or 'not a CI run'}")
163 if _EVENTS:
164 lines.append("control events this process saw:")
165 lines.extend(
166 f" {time.strftime('%H:%M:%S', time.gmtime(when))}Z"
167 f" {_EVENT_NAMES.get(kind, str(kind))}"
168 for when, kind in _EVENTS
169 )
170 else:
171 lines.append("control events this process saw: none")
172 attached = console_processes()
173 if attached is None:
174 lines.append("console processes: not a Windows console")
175 elif not attached:175 ↛ 176line 175 didn't jump to line 176 because the condition on line 175 was never true
176 lines.append("console processes: none, this process has no console")
177 else:
178 lines.append("console processes:")
179 lines.extend(f" {pid} {name}" for pid, name in attached)
180 lines.append(f"reported at: {time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime())}Z")
181 return "\n".join(lines)
186 """Add the section to a failed report whose exception carries the status."""
187 del item
188 outcome = yield
189 report = outcome.get_result()
190 if not report.failed or call.excinfo is None:
191 return
192 error = call.excinfo.value
193 if not any(control_exit(code) for code in exit_codes(error)):193 ↛ 195line 193 didn't jump to line 195 because the condition on line 193 was always true
194 return
195 report.sections.append(("console control event", diagnosis(error)))