Skip to content

Commit f825938

Browse files
committed
fix: add test for it
Signed-off-by: yihong0618 <zouzou0208@gmail.com>
1 parent 125c570 commit f825938

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

Lib/test/test_profiling/test_sampling_profiler/test_profiler.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,46 @@ def test_sample_profiler_missed_samples_warning(self):
224224
self.assertIn("Warning: missed", result)
225225
self.assertIn("samples from the expected total", result)
226226

227+
def test_sample_profiler_keyboard_interrupt(self):
228+
mock_unwinder = mock.MagicMock()
229+
mock_unwinder.get_stack_trace.side_effect = [
230+
[
231+
(
232+
1,
233+
[
234+
mock.MagicMock(
235+
filename="test.py", lineno=10, funcname="test_func"
236+
)
237+
],
238+
)
239+
],
240+
KeyboardInterrupt(),
241+
]
242+
243+
with mock.patch(
244+
"_remote_debugging.RemoteUnwinder"
245+
) as mock_unwinder_class:
246+
mock_unwinder_class.return_value = mock_unwinder
247+
profiler = SampleProfiler(
248+
pid=12345, sample_interval_usec=10000, all_threads=False
249+
)
250+
mock_collector = mock.MagicMock()
251+
times = [0.0, 0.01, 0.02, 0.03, 0.04]
252+
with mock.patch("time.perf_counter", side_effect=times):
253+
with io.StringIO() as output:
254+
with mock.patch("sys.stdout", output):
255+
try:
256+
profiler.sample(mock_collector, duration_sec=1.0)
257+
except KeyboardInterrupt:
258+
self.fail(
259+
"KeyboardInterrupt was not handled by the profiler"
260+
)
261+
result = output.getvalue()
262+
self.assertIn("Interrupted by user.", result)
263+
self.assertIn("Captured", result)
264+
self.assertIn("samples", result)
265+
self.assertNotIn("Warning: missed", result)
266+
227267

228268
@force_not_colorized_test_class
229269
class TestPrintSampledStats(unittest.TestCase):
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
Correctly allow :exc:`KeyboardInterrupt` to stop the process when using
2-
:mod:`profiling.sampling`.
2+
:mod:`!profiling.sampling`.

0 commit comments

Comments
 (0)