forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_remote_pdb.py
More file actions
1634 lines (1412 loc) · 58.3 KB
/
test_remote_pdb.py
File metadata and controls
1634 lines (1412 loc) · 58.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import itertools
import json
import os
import re
import signal
import socket
import subprocess
import sys
import textwrap
import unittest
import unittest.mock
from contextlib import closing, contextmanager, redirect_stdout, redirect_stderr, ExitStack
from test.support import is_wasi, cpython_only, force_color, requires_subprocess, SHORT_TIMEOUT, subTests
from test.support.os_helper import TESTFN, unlink
from typing import List
import pdb
from pdb import _PdbServer, _PdbClient
if not sys.is_remote_debug_enabled():
raise unittest.SkipTest('remote debugging is disabled')
@contextmanager
def kill_on_error(proc):
"""Context manager killing the subprocess if a Python exception is raised."""
with proc:
try:
yield proc
except:
proc.kill()
raise
class MockSocketFile:
"""Mock socket file for testing _PdbServer without actual socket connections."""
def __init__(self):
self.input_queue = []
self.output_buffer = []
def write(self, data: bytes) -> None:
"""Simulate write to socket."""
self.output_buffer.append(data)
def flush(self) -> None:
"""No-op flush implementation."""
pass
def readline(self) -> bytes:
"""Read a line from the prepared input queue."""
if not self.input_queue:
return b""
return self.input_queue.pop(0)
def close(self) -> None:
"""Close the mock socket file."""
pass
def add_input(self, data: dict) -> None:
"""Add input that will be returned by readline."""
self.input_queue.append(json.dumps(data).encode() + b"\n")
def get_output(self) -> List[dict]:
"""Get the output that was written by the object being tested."""
results = []
for data in self.output_buffer:
if isinstance(data, bytes) and data.endswith(b"\n"):
try:
results.append(json.loads(data.decode().strip()))
except json.JSONDecodeError:
pass # Ignore non-JSON output
self.output_buffer = []
return results
class PdbClientTestCase(unittest.TestCase):
"""Tests for the _PdbClient class."""
def do_test(
self,
*,
incoming,
simulate_send_failure=False,
simulate_sigint_during_stdout_write=False,
use_interrupt_socket=False,
expected_outgoing=None,
expected_outgoing_signals=None,
expected_completions=None,
expected_exception=None,
expected_stdout="",
expected_stdout_substring="",
expected_state=None,
):
if expected_outgoing is None:
expected_outgoing = []
if expected_outgoing_signals is None:
expected_outgoing_signals = []
if expected_completions is None:
expected_completions = []
if expected_state is None:
expected_state = {}
expected_state.setdefault("write_failed", False)
messages = [m for source, m in incoming if source == "server"]
prompts = [m["prompt"] for source, m in incoming if source == "user"]
input_iter = (m for source, m in incoming if source == "user")
completions = []
def mock_input(prompt):
message = next(input_iter, None)
if message is None:
raise EOFError
if req := message.get("completion_request"):
readline_mock = unittest.mock.Mock()
readline_mock.get_line_buffer.return_value = req["line"]
readline_mock.get_begidx.return_value = req["begidx"]
readline_mock.get_endidx.return_value = req["endidx"]
unittest.mock.seal(readline_mock)
with unittest.mock.patch.dict(sys.modules, {"readline": readline_mock}):
for param in itertools.count():
prefix = req["line"][req["begidx"] : req["endidx"]]
completion = client.complete(prefix, param)
if completion is None:
break
completions.append(completion)
reply = message["input"]
if isinstance(reply, BaseException):
raise reply
if isinstance(reply, str):
return reply
return reply()
with ExitStack() as stack:
client_sock, server_sock = socket.socketpair()
stack.enter_context(closing(client_sock))
stack.enter_context(closing(server_sock))
server_sock = unittest.mock.Mock(wraps=server_sock)
client_sock.sendall(
b"".join(
(m if isinstance(m, bytes) else json.dumps(m).encode()) + b"\n"
for m in messages
)
)
client_sock.shutdown(socket.SHUT_WR)
if simulate_send_failure:
server_sock.sendall = unittest.mock.Mock(
side_effect=OSError("sendall failed")
)
client_sock.shutdown(socket.SHUT_RD)
stdout = io.StringIO()
if simulate_sigint_during_stdout_write:
orig_stdout_write = stdout.write
def sigint_stdout_write(s):
signal.raise_signal(signal.SIGINT)
return orig_stdout_write(s)
stdout.write = sigint_stdout_write
input_mock = stack.enter_context(
unittest.mock.patch("pdb.input", side_effect=mock_input)
)
stack.enter_context(redirect_stdout(stdout))
if use_interrupt_socket:
interrupt_sock = unittest.mock.Mock(spec=socket.socket)
mock_kill = None
else:
interrupt_sock = None
mock_kill = stack.enter_context(
unittest.mock.patch("os.kill", spec=os.kill)
)
client = _PdbClient(
pid=12345,
server_socket=server_sock,
interrupt_sock=interrupt_sock,
)
if expected_exception is not None:
exception = expected_exception["exception"]
msg = expected_exception["msg"]
stack.enter_context(self.assertRaises(exception, msg=msg))
client.cmdloop()
sent_msgs = [msg.args[0] for msg in server_sock.sendall.mock_calls]
for msg in sent_msgs:
assert msg.endswith(b"\n")
actual_outgoing = [json.loads(msg) for msg in sent_msgs]
self.assertEqual(actual_outgoing, expected_outgoing)
self.assertEqual(completions, expected_completions)
if expected_stdout_substring and not expected_stdout:
self.assertIn(expected_stdout_substring, stdout.getvalue())
else:
self.assertEqual(stdout.getvalue(), expected_stdout)
input_mock.assert_has_calls([unittest.mock.call(p) for p in prompts])
actual_state = {k: getattr(client, k) for k in expected_state}
self.assertEqual(actual_state, expected_state)
if use_interrupt_socket:
outgoing_signals = [
signal.Signals(int.from_bytes(call.args[0]))
for call in interrupt_sock.sendall.call_args_list
]
else:
assert mock_kill is not None
outgoing_signals = []
for call in mock_kill.call_args_list:
pid, signum = call.args
self.assertEqual(pid, 12345)
outgoing_signals.append(signal.Signals(signum))
self.assertEqual(outgoing_signals, expected_outgoing_signals)
def test_remote_immediately_closing_the_connection(self):
"""Test the behavior when the remote closes the connection immediately."""
incoming = []
expected_outgoing = []
self.do_test(
incoming=incoming,
expected_outgoing=expected_outgoing,
)
def test_handling_command_list(self):
"""Test handling the command_list message."""
incoming = [
("server", {"command_list": ["help", "list", "continue"]}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[],
expected_state={
"pdb_commands": {"help", "list", "continue"},
},
)
def test_handling_info_message(self):
"""Test handling a message payload with type='info'."""
incoming = [
("server", {"message": "Some message or other\n", "type": "info"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[],
expected_stdout="Some message or other\n",
)
def test_handling_error_message(self):
"""Test handling a message payload with type='error'."""
incoming = [
("server", {"message": "Some message or other.", "type": "error"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[],
expected_stdout="*** Some message or other.\n",
)
def test_handling_other_message(self):
"""Test handling a message payload with an unrecognized type."""
incoming = [
("server", {"message": "Some message.\n", "type": "unknown"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[],
expected_stdout="Some message.\n",
)
@unittest.skipIf(sys.flags.optimize >= 2, "Help not available for -OO")
@subTests(
"help_request,expected_substring",
[
# a request to display help for a command
({"help": "ll"}, "Usage: ll | longlist"),
# a request to display a help overview
({"help": ""}, "type help <topic>"),
# a request to display the full PDB manual
({"help": "pdb"}, ">>> import pdb"),
],
)
def test_handling_help_when_available(self, help_request, expected_substring):
"""Test handling help requests when help is available."""
incoming = [
("server", help_request),
]
self.do_test(
incoming=incoming,
expected_outgoing=[],
expected_stdout_substring=expected_substring,
)
@unittest.skipIf(sys.flags.optimize < 2, "Needs -OO")
@subTests(
"help_request,expected_substring",
[
# a request to display help for a command
({"help": "ll"}, "No help for 'll'"),
# a request to display a help overview
({"help": ""}, "Undocumented commands"),
# a request to display the full PDB manual
({"help": "pdb"}, "No help for 'pdb'"),
],
)
def test_handling_help_when_not_available(self, help_request, expected_substring):
"""Test handling help requests when help is not available."""
incoming = [
("server", help_request),
]
self.do_test(
incoming=incoming,
expected_outgoing=[],
expected_stdout_substring=expected_substring,
)
def test_handling_pdb_prompts(self):
"""Test responding to pdb's normal prompts."""
incoming = [
("server", {"command_list": ["b"]}),
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
("user", {"prompt": "(Pdb) ", "input": "lst ["}),
("user", {"prompt": "... ", "input": "0 ]"}),
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
("user", {"prompt": "(Pdb) ", "input": ""}),
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
("user", {"prompt": "(Pdb) ", "input": "b ["}),
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
("user", {"prompt": "(Pdb) ", "input": "! b ["}),
("user", {"prompt": "... ", "input": "b ]"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{"reply": "lst [\n0 ]"},
{"reply": ""},
{"reply": "b ["},
{"reply": "!b [\nb ]"},
],
expected_state={"state": "pdb"},
)
def test_handling_interact_prompts(self):
"""Test responding to pdb's interact mode prompts."""
incoming = [
("server", {"command_list": ["b"]}),
("server", {"prompt": ">>> ", "state": "interact"}),
("user", {"prompt": ">>> ", "input": "lst ["}),
("user", {"prompt": "... ", "input": "0 ]"}),
("server", {"prompt": ">>> ", "state": "interact"}),
("user", {"prompt": ">>> ", "input": ""}),
("server", {"prompt": ">>> ", "state": "interact"}),
("user", {"prompt": ">>> ", "input": "b ["}),
("user", {"prompt": "... ", "input": "b ]"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{"reply": "lst [\n0 ]"},
{"reply": ""},
{"reply": "b [\nb ]"},
],
expected_state={"state": "interact"},
)
def test_retry_pdb_prompt_on_syntax_error(self):
"""Test re-prompting after a SyntaxError in a Python expression."""
incoming = [
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
("user", {"prompt": "(Pdb) ", "input": " lst ["}),
("user", {"prompt": "(Pdb) ", "input": "lst ["}),
("user", {"prompt": "... ", "input": " 0 ]"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{"reply": "lst [\n 0 ]"},
],
expected_stdout_substring="*** IndentationError",
expected_state={"state": "pdb"},
)
def test_retry_interact_prompt_on_syntax_error(self):
"""Test re-prompting after a SyntaxError in a Python expression."""
incoming = [
("server", {"prompt": ">>> ", "state": "interact"}),
("user", {"prompt": ">>> ", "input": "!lst ["}),
("user", {"prompt": ">>> ", "input": "lst ["}),
("user", {"prompt": "... ", "input": " 0 ]"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{"reply": "lst [\n 0 ]"},
],
expected_stdout_substring="*** SyntaxError",
expected_state={"state": "interact"},
)
def test_handling_unrecognized_prompt_type(self):
"""Test fallback to "dumb" single-line mode for unknown states."""
incoming = [
("server", {"prompt": "Do it? ", "state": "confirm"}),
("user", {"prompt": "Do it? ", "input": "! ["}),
("server", {"prompt": "Do it? ", "state": "confirm"}),
("user", {"prompt": "Do it? ", "input": "echo hello"}),
("server", {"prompt": "Do it? ", "state": "confirm"}),
("user", {"prompt": "Do it? ", "input": ""}),
("server", {"prompt": "Do it? ", "state": "confirm"}),
("user", {"prompt": "Do it? ", "input": "echo goodbye"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{"reply": "! ["},
{"reply": "echo hello"},
{"reply": ""},
{"reply": "echo goodbye"},
],
expected_state={"state": "dumb"},
)
def test_sigint_at_prompt(self):
"""Test signaling when a prompt gets interrupted."""
incoming = [
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
(
"user",
{
"prompt": "(Pdb) ",
"input": lambda: signal.raise_signal(signal.SIGINT),
},
),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{"signal": "INT"},
],
expected_state={"state": "pdb"},
)
def test_sigint_at_continuation_prompt(self):
"""Test signaling when a continuation prompt gets interrupted."""
incoming = [
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
("user", {"prompt": "(Pdb) ", "input": "if True:"}),
(
"user",
{
"prompt": "... ",
"input": lambda: signal.raise_signal(signal.SIGINT),
},
),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{"signal": "INT"},
],
expected_state={"state": "pdb"},
)
def test_sigint_when_writing(self):
"""Test siginaling when sys.stdout.write() gets interrupted."""
incoming = [
("server", {"message": "Some message or other\n", "type": "info"}),
]
for use_interrupt_socket in [False, True]:
with self.subTest(use_interrupt_socket=use_interrupt_socket):
self.do_test(
incoming=incoming,
simulate_sigint_during_stdout_write=True,
use_interrupt_socket=use_interrupt_socket,
expected_outgoing=[],
expected_outgoing_signals=[signal.SIGINT],
expected_stdout="Some message or other\n",
)
def test_eof_at_prompt(self):
"""Test signaling when a prompt gets an EOFError."""
incoming = [
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
("user", {"prompt": "(Pdb) ", "input": EOFError()}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{"signal": "EOF"},
],
expected_state={"state": "pdb"},
)
def test_unrecognized_json_message(self):
"""Test failing after getting an unrecognized payload."""
incoming = [
("server", {"monty": "python"}),
("server", {"message": "Some message or other\n", "type": "info"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[],
expected_exception={
"exception": RuntimeError,
"msg": 'Unrecognized payload b\'{"monty": "python"}\'',
},
)
def test_continuing_after_getting_a_non_json_payload(self):
"""Test continuing after getting a non JSON payload."""
incoming = [
("server", b"spam"),
("server", {"message": "Something", "type": "info"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[],
expected_stdout="\n".join(
[
"*** Invalid JSON from remote: b'spam\\n'",
"Something",
]
),
)
def test_write_failing(self):
"""Test terminating if write fails due to a half closed socket."""
incoming = [
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
("user", {"prompt": "(Pdb) ", "input": KeyboardInterrupt()}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[{"signal": "INT"}],
simulate_send_failure=True,
expected_state={"write_failed": True},
)
def test_completion_in_pdb_state(self):
"""Test requesting tab completions at a (Pdb) prompt."""
# GIVEN
incoming = [
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
(
"user",
{
"prompt": "(Pdb) ",
"completion_request": {
"line": " mod._",
"begidx": 8,
"endidx": 9,
},
"input": "print(\n mod.__name__)",
},
),
("server", {"completions": ["__name__", "__file__"]}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{
"complete": {
"text": "_",
"line": "mod._",
"begidx": 4,
"endidx": 5,
}
},
{"reply": "print(\n mod.__name__)"},
],
expected_completions=["__name__", "__file__"],
expected_state={"state": "pdb"},
)
def test_multiline_completion_in_pdb_state(self):
"""Test requesting tab completions at a (Pdb) continuation prompt."""
# GIVEN
incoming = [
("server", {"prompt": "(Pdb) ", "state": "pdb"}),
("user", {"prompt": "(Pdb) ", "input": "if True:"}),
(
"user",
{
"prompt": "... ",
"completion_request": {
"line": " b",
"begidx": 4,
"endidx": 5,
},
"input": " bool()",
},
),
("server", {"completions": ["bin", "bool", "bytes"]}),
("user", {"prompt": "... ", "input": ""}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{
"complete": {
"text": "b",
"line": "! b",
"begidx": 2,
"endidx": 3,
}
},
{"reply": "if True:\n bool()\n"},
],
expected_completions=["bin", "bool", "bytes"],
expected_state={"state": "pdb"},
)
def test_completion_in_interact_state(self):
"""Test requesting tab completions at a >>> prompt."""
incoming = [
("server", {"prompt": ">>> ", "state": "interact"}),
(
"user",
{
"prompt": ">>> ",
"completion_request": {
"line": " mod.__",
"begidx": 8,
"endidx": 10,
},
"input": "print(\n mod.__name__)",
},
),
("server", {"completions": ["__name__", "__file__"]}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{
"complete": {
"text": "__",
"line": "mod.__",
"begidx": 4,
"endidx": 6,
}
},
{"reply": "print(\n mod.__name__)"},
],
expected_completions=["__name__", "__file__"],
expected_state={"state": "interact"},
)
def test_completion_in_unknown_state(self):
"""Test requesting tab completions at an unrecognized prompt."""
incoming = [
("server", {"command_list": ["p"]}),
("server", {"prompt": "Do it? ", "state": "confirm"}),
(
"user",
{
"prompt": "Do it? ",
"completion_request": {
"line": "_",
"begidx": 0,
"endidx": 1,
},
"input": "__name__",
},
),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{"reply": "__name__"},
],
expected_state={"state": "dumb"},
)
def test_write_failure_during_completion(self):
"""Test failing to write to the socket to request tab completions."""
incoming = [
("server", {"prompt": ">>> ", "state": "interact"}),
(
"user",
{
"prompt": ">>> ",
"completion_request": {
"line": "xy",
"begidx": 0,
"endidx": 2,
},
"input": "xyz",
},
),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{
"complete": {
"text": "xy",
"line": "xy",
"begidx": 0,
"endidx": 2,
}
},
{"reply": "xyz"},
],
simulate_send_failure=True,
expected_completions=[],
expected_state={"state": "interact", "write_failed": True},
)
def test_read_failure_during_completion(self):
"""Test failing to read tab completions from the socket."""
incoming = [
("server", {"prompt": ">>> ", "state": "interact"}),
(
"user",
{
"prompt": ">>> ",
"completion_request": {
"line": "xy",
"begidx": 0,
"endidx": 2,
},
"input": "xyz",
},
),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{
"complete": {
"text": "xy",
"line": "xy",
"begidx": 0,
"endidx": 2,
}
},
{"reply": "xyz"},
],
expected_completions=[],
expected_state={"state": "interact"},
)
def test_reading_invalid_json_during_completion(self):
"""Test receiving invalid JSON when getting tab completions."""
incoming = [
("server", {"prompt": ">>> ", "state": "interact"}),
(
"user",
{
"prompt": ">>> ",
"completion_request": {
"line": "xy",
"begidx": 0,
"endidx": 2,
},
"input": "xyz",
},
),
("server", b'{"completions": '),
("user", {"prompt": ">>> ", "input": "xyz"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{
"complete": {
"text": "xy",
"line": "xy",
"begidx": 0,
"endidx": 2,
}
},
{"reply": "xyz"},
],
expected_stdout_substring="*** json.decoder.JSONDecodeError",
expected_completions=[],
expected_state={"state": "interact"},
)
def test_reading_empty_json_during_completion(self):
"""Test receiving an empty JSON object when getting tab completions."""
incoming = [
("server", {"prompt": ">>> ", "state": "interact"}),
(
"user",
{
"prompt": ">>> ",
"completion_request": {
"line": "xy",
"begidx": 0,
"endidx": 2,
},
"input": "xyz",
},
),
("server", {}),
("user", {"prompt": ">>> ", "input": "xyz"}),
]
self.do_test(
incoming=incoming,
expected_outgoing=[
{
"complete": {
"text": "xy",
"line": "xy",
"begidx": 0,
"endidx": 2,
}
},
{"reply": "xyz"},
],
expected_stdout=(
"*** RuntimeError: Failed to get valid completions."
" Got: {}\n"
),
expected_completions=[],
expected_state={"state": "interact"},
)
class RemotePdbTestCase(unittest.TestCase):
"""Tests for the _PdbServer class."""
def setUp(self):
self.sockfile = MockSocketFile()
self.pdb = _PdbServer(self.sockfile)
# Mock some Bdb attributes that are lazily created when tracing starts
self.pdb.botframe = None
self.pdb.quitting = False
# Create a frame for testing
self.test_globals = {'a': 1, 'b': 2, '__pdb_convenience_variables': {'x': 100}}
self.test_locals = {'c': 3, 'd': 4}
# Create a simple test frame
frame_info = unittest.mock.Mock()
frame_info.f_globals = self.test_globals
frame_info.f_locals = self.test_locals
frame_info.f_lineno = 42
frame_info.f_code = unittest.mock.Mock()
frame_info.f_code.co_filename = "test_file.py"
frame_info.f_code.co_name = "test_function"
self.pdb.curframe = frame_info
def test_message_and_error(self):
"""Test message and error methods send correct JSON."""
self.pdb.message("Test message")
self.pdb.error("Test error")
outputs = self.sockfile.get_output()
self.assertEqual(len(outputs), 2)
self.assertEqual(outputs[0], {"message": "Test message\n", "type": "info"})
self.assertEqual(outputs[1], {"message": "Test error", "type": "error"})
def test_read_command(self):
"""Test reading commands from the socket."""
# Add test input
self.sockfile.add_input({"reply": "help"})
# Read the command
cmd = self.pdb._read_reply()
self.assertEqual(cmd, "help")
def test_read_command_EOF(self):
"""Test reading EOF command."""
# Simulate socket closure
self.pdb._write_failed = True
with self.assertRaises(EOFError):
self.pdb._read_reply()
def test_completion(self):
"""Test handling completion requests."""
# Mock completenames to return specific values
with unittest.mock.patch.object(self.pdb, 'completenames',
return_value=["continue", "clear"]):
# Add a completion request
self.sockfile.add_input({
"complete": {
"text": "c",
"line": "c",
"begidx": 0,
"endidx": 1
}
})
# Add a regular command to break the loop
self.sockfile.add_input({"reply": "help"})
# Read command - this should process the completion request first
cmd = self.pdb._read_reply()
# Verify completion response was sent
outputs = self.sockfile.get_output()
self.assertEqual(len(outputs), 1)
self.assertEqual(outputs[0], {"completions": ["continue", "clear"]})
# The actual command should be returned
self.assertEqual(cmd, "help")
def test_do_help(self):
"""Test that do_help sends the help message."""
self.pdb.do_help("break")
outputs = self.sockfile.get_output()
self.assertEqual(len(outputs), 1)
self.assertEqual(outputs[0], {"help": "break"})
def test_interact_mode(self):
"""Test interaction mode setup and execution."""
# First set up interact mode
self.pdb.do_interact("")
# Verify _interact_state is properly initialized
self.assertIsNotNone(self.pdb._interact_state)
self.assertIsInstance(self.pdb._interact_state, dict)
# Test running code in interact mode
with unittest.mock.patch.object(self.pdb, '_error_exc') as mock_error:
self.pdb._run_in_python_repl("print('test')")
mock_error.assert_not_called()
# Test with syntax error
self.pdb._run_in_python_repl("if:")
mock_error.assert_called_once()
def test_registering_commands(self):
"""Test registering breakpoint commands."""
# Mock get_bpbynumber
with unittest.mock.patch.object(self.pdb, 'get_bpbynumber'):
# Queue up some input to send
self.sockfile.add_input({"reply": "commands 1"})
self.sockfile.add_input({"reply": "silent"})
self.sockfile.add_input({"reply": "print('hi')"})
self.sockfile.add_input({"reply": "end"})
self.sockfile.add_input({"signal": "EOF"})
# Run the PDB command loop
self.pdb.cmdloop()
outputs = self.sockfile.get_output()
self.assertIn('command_list', outputs[0])
self.assertEqual(outputs[1], {"prompt": "(Pdb) ", "state": "pdb"})
self.assertEqual(outputs[2], {"prompt": "(com) ", "state": "commands"})
self.assertEqual(outputs[3], {"prompt": "(com) ", "state": "commands"})
self.assertEqual(outputs[4], {"prompt": "(com) ", "state": "commands"})
self.assertEqual(outputs[5], {"prompt": "(Pdb) ", "state": "pdb"})
self.assertEqual(outputs[6], {"message": "\n", "type": "info"})
self.assertEqual(len(outputs), 7)
self.assertEqual(
self.pdb.commands[1],
["_pdbcmd_silence_frame_status", "print('hi')"],
)
def test_detach(self):
"""Test the detach method."""
with unittest.mock.patch.object(self.sockfile, 'close') as mock_close:
self.pdb.detach()
mock_close.assert_called_once()
self.assertFalse(self.pdb.quitting)
def test_cmdloop(self):
"""Test the command loop with various commands."""
# Mock onecmd to track command execution
with unittest.mock.patch.object(self.pdb, 'onecmd', return_value=False) as mock_onecmd:
# Add commands to the queue
self.pdb.cmdqueue = ['help', 'list']
# Add a command from the socket for when cmdqueue is empty
self.sockfile.add_input({"reply": "next"})
# Add a second command to break the loop
self.sockfile.add_input({"reply": "quit"})
# Configure onecmd to exit the loop on "quit"
def side_effect(line):
return line == 'quit'
mock_onecmd.side_effect = side_effect
# Run the command loop
self.pdb.quitting = False # Set this by hand because we don't want to really call set_trace()
self.pdb.cmdloop()
# Should have processed 4 commands: 2 from cmdqueue, 2 from socket
self.assertEqual(mock_onecmd.call_count, 4)
mock_onecmd.assert_any_call('help')