-
Notifications
You must be signed in to change notification settings - Fork 782
/
Copy pathgoDebug.test.ts
2302 lines (2026 loc) · 70.4 KB
/
goDebug.test.ts
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
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable node/no-unsupported-features/node-builtins */
/* eslint-disable no-async-promise-executor */
/* eslint-disable node/no-unpublished-import */
import assert from 'assert';
import * as cp from 'child_process';
import * as fs from 'fs';
import * as readline from 'readline';
import * as http from 'http';
import { tmpdir } from 'os';
import * as net from 'net';
import * as path from 'path';
import * as sinon from 'sinon';
import * as proxy from '../../src/goDebugFactory';
import * as vscode from 'vscode';
import { DebugConfiguration, DebugProtocolMessage } from 'vscode';
import { DebugClient } from '@vscode/debugadapter-testsupport';
import { ILocation } from '@vscode/debugadapter-testsupport/lib/debugClient';
import { DebugProtocol } from 'vscode-debugprotocol';
import * as extConfig from '../../src/config';
import { GoDebugConfigurationProvider, parseDebugProgramArgSync } from '../../src/goDebugConfiguration';
import { getBinPath, rmdirRecursive } from '../../src/util';
import { killProcessTree } from '../../src/utils/processUtils';
import getPort = require('get-port');
import util = require('util');
import { affectedByIssue832 } from './testutils';
// For debugging test and streaming the trace instead of buffering, set this.
const DEBUG = process.env['DEBUG'] === '1';
function debugLog(msg: string) {
if (DEBUG) console.log(msg);
}
// Test suite adapted from:
// https://github.com/microsoft/vscode-mock-debug/blob/master/src/tests/adapter.test.ts
const testAll = (ctx: Mocha.Context, isDlvDap: boolean, withConsole?: string) => {
const debugConfigProvider = new GoDebugConfigurationProvider();
const DEBUG_ADAPTER = path.join('.', 'out', 'src', 'debugAdapter', 'goDebug.js');
const PROJECT_ROOT = path.normalize(path.join(__dirname, '..', '..', '..'));
const DATA_ROOT = path.join(PROJECT_ROOT, 'test', 'testdata');
const remoteAttachConfig = {
name: 'Attach',
type: 'go',
request: 'attach',
mode: 'remote', // This implies debugAdapter = legacy.
host: '127.0.0.1',
port: 3456
};
let dc: DebugClient;
let dlvDapAdapter: DelveDAPDebugAdapterOnSocket | null;
let dapTraced = false;
setup(async () => {
dapTraced = false;
if (isDlvDap) {
dc = new DebugClient('dlv', 'dap', 'go');
// dc.start will be called in initializeDebugConfig call,
// which creates a thin adapter for delve dap mode,
// runs it on a network port, and gets wired with this dc.
// Launching delve may take longer than the default timeout of 5000.
dc.defaultTimeout = 20_000;
return;
}
dc = new DebugClient('node', path.join(PROJECT_ROOT, DEBUG_ADAPTER), 'go', undefined, true);
// Launching delve may take longer than the default timeout of 5000.
dc.defaultTimeout = 20_000;
// To connect to a running debug server for debugging the tests, specify PORT.
await dc.start();
});
teardown(async () => {
if (dlvDapAdapter) {
const d = dlvDapAdapter;
dlvDapAdapter = null;
if (ctx.currentTest?.state === 'failed') {
console.log(`${ctx.currentTest?.title} FAILED: DAP Trace`);
d.printLog();
}
d.dispose();
} else {
if (ctx.currentTest?.state === 'failed' && dapTraced) {
console.log(`${ctx.currentTest?.title} FAILED: Debug Adapter Trace`);
try {
await new Promise<void>((resolve) => {
const rl = readline.createInterface({
input: fs.createReadStream(path.join(tmpdir(), 'vscode-go-debug.txt')),
crlfDelay: Infinity
});
rl.on('line', (line) => console.log(line));
rl.on('close', () => resolve());
});
} catch (e) {
console.log(`Failed to read trace: ${e}`);
}
}
dc?.stop();
}
sinon.restore();
});
/**
* This function sets up a server that returns helloworld on serverPort.
* The server will be started as a Delve remote headless instance
* that will listen on the specified dlvPort.
* We are using a server as opposed to a long-running program
* because we can use responses to better test when the program is
* running vs stopped/killed.
*/
async function setUpRemoteProgram(
dlvPort: number,
serverPort: number,
acceptMultiClient = true,
continueOnStart = true
): Promise<cp.ChildProcess> {
const serverFolder = path.join(DATA_ROOT, 'helloWorldServer');
const toolPath = getBinPath('dlv');
const args = [
'debug',
'--check-go-version=false',
'--api-version=2',
'--headless',
`--listen=127.0.0.1:${dlvPort}`
];
if (acceptMultiClient) {
args.push('--accept-multiclient');
}
if (continueOnStart) {
args.push('--continue');
}
const promise = new Promise<cp.ChildProcess>((resolve, reject) => {
const p = cp.spawn(toolPath, args, {
cwd: serverFolder,
env: { PORT: `${serverPort}`, ...process.env }
});
let started = false;
const timeoutToken: NodeJS.Timer = setTimeout(() => {
console.log(`dlv debug server (PID: ${p.pid}) is not responding`);
reject(new Error('timed out while waiting for DAP server to start'));
}, 30_000);
const stopWaitingForServerToStart = () => {
clearTimeout(timeoutToken);
started = true;
resolve(p);
};
if (continueOnStart) {
// wait till helloWorldServer starts and prints its log message to STDERR.
p.stderr.on('data', (chunk) => {
const msg = chunk.toString();
if (!started && msg.includes('helloWorldServer starting to listen on')) {
stopWaitingForServerToStart();
}
console.log(msg);
});
} else {
p.stdout.on('data', (chunk) => {
const msg = chunk.toString();
if (!started && msg.includes('listening at:')) {
stopWaitingForServerToStart();
}
console.log(msg);
});
}
});
return promise;
}
/**
* Helper function to set up remote attach configuration.
* This will issue an initializeRequest, followed by attachRequest.
* It will then wait for an initializedEvent before sending a breakpointRequest
* if breakpoints are provided. Lastly the configurationDoneRequest will be sent.
* NOTE: For simplicity, this function assumes the breakpoints are in the same file.
*/
async function setUpRemoteAttach(config: DebugConfiguration, breakpoints: ILocation[] = []): Promise<void> {
const debugConfig = await initializeDebugConfig(config);
const initializedResult = await dc.initializeRequest();
assert.ok(initializedResult.success);
// When the attach request is completed successfully, we should get
// an initialized event.
await Promise.all([
new Promise<void>(async (resolve) => {
const debugConfigCopy = Object.assign({}, debugConfig);
delete debugConfigCopy.env;
debugLog(`Setting up attach request for ${JSON.stringify(debugConfigCopy)}.`);
const attachResult = await dc.attachRequest(debugConfig as DebugProtocol.AttachRequestArguments);
assert.ok(attachResult.success);
resolve();
}),
dc.waitForEvent('initialized')
]);
if (breakpoints.length) {
debugLog('Sending set breakpoints request for remote attach setup.');
const breakpointsResult = await dc.setBreakpointsRequest({
source: { path: breakpoints[0].path },
breakpoints
});
assert.ok(breakpointsResult.success && breakpointsResult.body.breakpoints.length === breakpoints.length);
// Verify that there are no non-verified breakpoints.
breakpointsResult.body.breakpoints.forEach((breakpoint) => {
assert.ok(breakpoint.verified);
});
}
debugLog('Sending configuration done request for remote attach setup.');
const configurationDoneResult = await dc.configurationDoneRequest();
assert.ok(configurationDoneResult.success);
}
/**
* Helper function to retrieve a stopped event for a breakpoint.
* This function will keep calling action() until we receive a stoppedEvent.
* Will return undefined if the result of repeatedly calling action does not
* induce a stoppedEvent.
*/
async function waitForBreakpoint(action: () => void, breakpoint: ILocation): Promise<void> {
const assertStoppedLocation = dc.assertStoppedLocation('breakpoint', breakpoint);
await new Promise((res) => setTimeout(res, 1_000));
action();
await assertStoppedLocation;
}
/**
* Helper function to create a promise that's resolved when
* output event with any of the provided strings is observed.
*/
async function waitForOutputMessage(dc: DebugClient, ...patterns: string[]): Promise<DebugProtocol.Event> {
return await new Promise<DebugProtocol.Event>((resolve, reject) => {
dc.on('output', (event) => {
for (const pattern of patterns) {
if (event.body.output.includes(pattern)) {
// Resolve when we have found the event that we want.
resolve(event);
return;
}
}
});
});
}
/**
* Helper function to assert that a variable has a particular value.
* This should be called when the program is stopped.
*
* The following requests are issued by this function to determine the
* value of the variable:
* 1. threadsRequest
* 2. stackTraceRequest
* 3. scopesRequest
* 4. variablesRequest
*/
async function assertLocalVariableValue(name: string, val: string): Promise<void> {
const threadsResponse = await dc.threadsRequest();
assert(threadsResponse.success);
const stackTraceResponse = await dc.stackTraceRequest({ threadId: threadsResponse.body.threads[0].id });
assert(stackTraceResponse.success);
const scopesResponse = await dc.scopesRequest({ frameId: stackTraceResponse.body.stackFrames[0].id });
assert(scopesResponse.success);
const localScopeIndex = scopesResponse.body.scopes.findIndex((v) => v.name === 'Local' || v.name === 'Locals');
assert(localScopeIndex >= 0, "no scope named 'Local':");
const variablesResponse = await dc.variablesRequest({
variablesReference: scopesResponse.body.scopes[localScopeIndex].variablesReference
});
assert(variablesResponse.success);
// Locate the variable with the matching name.
const i = variablesResponse.body.variables.findIndex((v) => v.name === name);
assert(i >= 0, `no variable in scope named ${name}`);
// Check that the value of name is val.
assert.strictEqual(variablesResponse.body.variables[i].value, val);
}
suite('basic', () => {
test('unknown request should produce error', async () => {
// fake config that will be used to initialize fixtures.
const config = { name: 'Launch', type: 'go', request: 'launch', program: DATA_ROOT };
await initializeDebugConfig(config);
try {
await dc.send('illegal_request');
} catch {
return;
}
throw new Error('does not report error on unknown request');
});
});
suite('initialize', () => {
test('should return supported features', async () => {
const config = { name: 'Launch', type: 'go', request: 'launch', program: DATA_ROOT };
await initializeDebugConfig(config);
await dc.initializeRequest().then((response) => {
response.body = response.body || {};
assert.strictEqual(response.body.supportsConditionalBreakpoints, true);
assert.strictEqual(response.body.supportsConfigurationDoneRequest, true);
if (!isDlvDap) {
// not supported in dlv-dap
assert.strictEqual(response.body.supportsSetVariable, true);
}
});
});
test("should produce error for invalid 'pathFormat'", async () => {
const config = { name: 'Launch', type: 'go', request: 'launch', program: DATA_ROOT };
await initializeDebugConfig(config);
try {
await dc.initializeRequest({
adapterID: 'mock',
linesStartAt1: true,
columnsStartAt1: true,
pathFormat: 'url'
});
} catch (err) {
return; // want error
}
throw new Error("does not report error on invalid 'pathFormat' attribute");
});
});
suite('env', () => {
if (!isDlvDap) {
return;
}
let sandbox: sinon.SinonSandbox;
setup(() => {
sandbox = sinon.createSandbox();
});
teardown(async () => sandbox.restore());
test('env var from go.toolsEnvVars is respected', async () => {
const PROGRAM = path.join(DATA_ROOT, 'envTest');
const FILE = path.join(PROGRAM, 'main.go');
const BREAKPOINT_LINE = 10;
const goConfig = Object.create(vscode.workspace.getConfiguration('go'), {
toolsEnvVars: {
value: { FOO: 'BAR' }
}
});
const configStub = sandbox.stub(extConfig, 'getGoConfig').returns(goConfig);
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
args: ['FOO']
};
const debugConfig = await initializeDebugConfig(config);
await dc.hitBreakpoint(debugConfig, getBreakpointLocation(FILE, BREAKPOINT_LINE));
await assertLocalVariableValue('v', '"BAR"');
await dc.continueRequest({ threadId: 1 }); // continue until completion for cleanup.
});
test('env var from launch config is respected', async () => {
const PROGRAM = path.join(DATA_ROOT, 'envTest');
const FILE = path.join(PROGRAM, 'main.go');
const BREAKPOINT_LINE = 10;
const goConfig = Object.create(vscode.workspace.getConfiguration('go'), {
toolsEnvVars: {
value: { FOO: 'BAR' }
}
});
const configStub = sandbox.stub(extConfig, 'getGoConfig').returns(goConfig);
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
args: ['FOO'],
env: { FOO: 'BAZ' }
};
const debugConfig = await initializeDebugConfig(config);
await dc.hitBreakpoint(debugConfig, getBreakpointLocation(FILE, BREAKPOINT_LINE));
await assertLocalVariableValue('v', '"BAZ"');
await dc.continueRequest({ threadId: 1 }); // continue until completion for cleanup.
});
});
suite('launch', () => {
if (!isDlvDap) {
return;
}
test('should run program to the end', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([dc.configurationSequence(), dc.launch(debugConfig), dc.waitForEvent('terminated')]);
});
test('should stop on entry', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
stopOnEntry: true
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([
dc.configurationSequence(),
dc.launch(debugConfig),
// The debug adapter does not support a stack trace request
// when there are no goroutines running. Which is true when it is stopped
// on entry. Therefore we would need another method from dc.assertStoppedLocation
// to check the debugger is stopped on entry.
dc.waitForEvent('stopped').then((event) => {
const stevent = event as DebugProtocol.StoppedEvent;
assert.strictEqual(stevent.body.reason, 'entry');
})
]);
});
test('should debug a file', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest', 'test.go');
const config = {
name: 'Launch file',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([dc.configurationSequence(), dc.launch(debugConfig), dc.waitForEvent('terminated')]);
});
test('should debug a single test', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch file',
type: 'go',
request: 'launch',
mode: 'test',
program: PROGRAM,
args: ['-test.run', 'TestMe']
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([dc.configurationSequence(), dc.launch(debugConfig), dc.waitForEvent('terminated')]);
});
test('should debug a test package', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch file',
type: 'go',
request: 'launch',
mode: 'test',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([dc.configurationSequence(), dc.launch(debugConfig), dc.waitForEvent('terminated')]);
});
test('invalid flags are passed to dlv but should be caught by dlv (legacy)', async function () {
if (isDlvDap) {
this.skip();
}
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
dlvFlags: ['--invalid']
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([
dc.assertOutput('stderr', 'Error: unknown flag: --invalid\n', 5000),
dc.waitForEvent('terminated'),
dc.initializeRequest().then((response) => {
// The current debug adapter does not respond to launch request but,
// instead, sends error messages and TerminatedEvent as delve is closed.
// The promise from dc.launchRequest resolves when the launch response
// is received, so the promise will never get resolved.
dc.launchRequest(debugConfig as any);
})
]);
});
test('invalid flags are passed to dlv but should be caught by dlv', async function () {
if (!isDlvDap) {
this.skip(); // not working in dlv-dap.
}
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
dlvFlags: ['--invalid']
};
await initializeDebugConfig(config);
await Promise.race([
// send an initialize request, which triggers launchDelveDAP
// from the thin adapter. We expect no response.
dc.initializeRequest().then(() => Promise.reject('unexpected initialization success')),
// we expect the useful error message.
waitForOutputMessage(dc, 'Error: unknown flag: --invalid')
]);
});
test('should run program with showLog=false and logOutput specified', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
showLog: false,
logOutput: 'dap'
};
const debugConfig = await initializeDebugConfig(config, true);
await Promise.all([dc.configurationSequence(), dc.launch(debugConfig), dc.waitForEvent('terminated')]);
});
test('should handle threads request after initialization', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([
dc.configurationSequence().then(() => {
dc.threadsRequest().then((response) => {
assert.ok(response.success);
});
}),
dc.launch(debugConfig),
dc.waitForEvent('terminated')
]);
});
test('should handle delayed initial threads request', async () => {
// If the program exits very quickly, the initial threadsRequest
// will complete after it has exited.
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([dc.configurationSequence(), dc.launch(debugConfig), dc.waitForEvent('terminated')]);
const response = await dc.threadsRequest();
assert.ok(response.success);
});
test('user-specified --listen flag should be ignored', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
dlvFlags: ['--listen=127.0.0.1:80']
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([dc.configurationSequence(), dc.launch(debugConfig), dc.waitForEvent('terminated')]);
});
});
suite('set current working directory', () => {
if (!isDlvDap) {
return;
}
test('should debug program with cwd set', async () => {
const WD = path.join(DATA_ROOT, 'cwdTest');
const PROGRAM = path.join(WD, 'cwdTest');
const FILE = path.join(PROGRAM, 'main.go');
const BREAKPOINT_LINE = 11;
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
cwd: WD
};
const debugConfig = await initializeDebugConfig(config);
await dc.hitBreakpoint(debugConfig, getBreakpointLocation(FILE, BREAKPOINT_LINE));
await assertLocalVariableValue('strdat', '"Hello, World!"');
});
test('should debug program without cwd set', async () => {
const WD = path.join(DATA_ROOT, 'cwdTest');
const PROGRAM = path.join(WD, 'cwdTest');
const FILE = path.join(PROGRAM, 'main.go');
const BREAKPOINT_LINE = 11;
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await dc.hitBreakpoint(debugConfig, getBreakpointLocation(FILE, BREAKPOINT_LINE));
await assertLocalVariableValue('strdat', '"Goodbye, World."');
});
test('should debug file program with cwd set', async () => {
const WD = path.join(DATA_ROOT, 'cwdTest');
const PROGRAM = path.join(WD, 'cwdTest', 'main.go');
const FILE = PROGRAM;
const BREAKPOINT_LINE = 11;
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
cwd: WD
};
const debugConfig = await initializeDebugConfig(config);
await dc.hitBreakpoint(debugConfig, getBreakpointLocation(FILE, BREAKPOINT_LINE));
await assertLocalVariableValue('strdat', '"Hello, World!"');
});
test('should debug file program without cwd set', async () => {
const WD = path.join(DATA_ROOT, 'cwdTest');
const PROGRAM = path.join(WD, 'cwdTest', 'main.go');
const FILE = PROGRAM;
const BREAKPOINT_LINE = 11;
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await dc.hitBreakpoint(debugConfig, getBreakpointLocation(FILE, BREAKPOINT_LINE));
await assertLocalVariableValue('strdat', '"Goodbye, World."');
});
async function waitForHelloGoodbyeOutput(dc: DebugClient): Promise<DebugProtocol.Event> {
return waitForOutputMessage(dc, 'Hello, World!\n', 'Goodbye, World.\n');
}
test('should run program with cwd set (noDebug)', async () => {
const WD = path.join(DATA_ROOT, 'cwdTest');
const PROGRAM = path.join(WD, 'cwdTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
cwd: WD,
noDebug: true
};
const debugConfig = await initializeDebugConfig(config);
dc.launch(debugConfig);
const event = await waitForHelloGoodbyeOutput(dc);
assert.strictEqual(event.body.output, 'Hello, World!\n');
});
test('should run program without cwd set (noDebug)', async () => {
const WD = path.join(DATA_ROOT, 'cwdTest');
const PROGRAM = path.join(WD, 'cwdTest');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
noDebug: true
};
const debugConfig = await initializeDebugConfig(config);
dc.launch(debugConfig);
const event = await waitForHelloGoodbyeOutput(dc);
assert.strictEqual(event.body.output, 'Goodbye, World.\n');
});
test('should run file program with cwd set (noDebug)', async () => {
const WD = path.join(DATA_ROOT, 'cwdTest');
const PROGRAM = path.join(WD, 'cwdTest', 'main.go');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
cwd: WD,
noDebug: true
};
const debugConfig = await initializeDebugConfig(config);
dc.launch(debugConfig);
const event = await waitForHelloGoodbyeOutput(dc);
assert.strictEqual(event.body.output, 'Hello, World!\n');
});
test('should run file program without cwd set (noDebug)', async () => {
const WD = path.join(DATA_ROOT, 'cwdTest');
const PROGRAM = path.join(WD, 'cwdTest', 'main.go');
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM,
noDebug: true
};
const debugConfig = await initializeDebugConfig(config);
dc.launch(debugConfig);
const event = await waitForHelloGoodbyeOutput(dc);
assert.strictEqual(event.body.output, 'Goodbye, World.\n');
});
});
suite('remote attach', () => {
if (withConsole) {
return;
}
let childProcess: cp.ChildProcess;
let server: number;
let debugConfig: DebugConfiguration;
setup(async () => {
server = await getPort();
remoteAttachConfig.port = await getPort();
debugConfig = remoteAttachConfig;
});
teardown(async () => {
await dc.stop();
await killProcessTree(childProcess);
// Wait 2 seconds for the process to be killed.
await new Promise((resolve) => setTimeout(resolve, 2_000));
});
test('can connect and initialize using external dlv --headless --accept-multiclient=true --continue=true', async () => {
childProcess = await setUpRemoteProgram(remoteAttachConfig.port, server, true, true);
await setUpRemoteAttach(debugConfig);
});
test('can connect and initialize using external dlv --headless --accept-multiclient=false --continue=false', async () => {
childProcess = await setUpRemoteProgram(remoteAttachConfig.port, server, false, false);
await setUpRemoteAttach(debugConfig);
});
test('can connect and initialize using external dlv --headless --accept-multiclient=true --continue=false', async () => {
childProcess = await setUpRemoteProgram(remoteAttachConfig.port, server, true, false);
await setUpRemoteAttach(debugConfig);
});
test('connection to remote is terminated when external dlv process exits', async function () {
if (isDlvDap) {
this.skip(); // this test does not apply for dlv-dap.
}
const childProcess = await setUpRemoteProgram(remoteAttachConfig.port, server, true, false);
await setUpRemoteAttach(remoteAttachConfig);
killProcess(childProcess);
await dc.waitForEvent('terminated');
});
});
// The file paths returned from delve use '/' not the native path
// separator, so we can replace any instances of '\' with '/', which
// allows the hitBreakpoint check to match.
const getBreakpointLocation = (FILE: string, LINE: number) => {
return { path: FILE.replace(/\\/g, '/'), line: LINE };
};
suite('setBreakpoints', () => {
let server: number;
let remoteAttachDebugConfig: DebugConfiguration;
setup(async () => {
server = await getPort();
remoteAttachConfig.port = await getPort();
remoteAttachDebugConfig = remoteAttachConfig;
});
test('should stop on a breakpoint', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const FILE = path.join(DATA_ROOT, 'baseTest', 'test.go');
const BREAKPOINT_LINE = 11;
const config = {
name: 'Launch',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await dc.hitBreakpoint(debugConfig, getBreakpointLocation(FILE, BREAKPOINT_LINE));
});
test('should stop on a breakpoint in test file', async () => {
const PROGRAM = path.join(DATA_ROOT, 'baseTest');
const FILE = path.join(DATA_ROOT, 'baseTest', 'sample_test.go');
const BREAKPOINT_LINE = 15;
const config = {
name: 'Launch file',
type: 'go',
request: 'launch',
mode: 'test',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await dc.hitBreakpoint(debugConfig, getBreakpointLocation(FILE, BREAKPOINT_LINE));
});
// stop here for integrated terminal test mode.
if (withConsole) {
return;
}
test('stopped for a breakpoint set during initialization (remote attach)', async () => {
const FILE = path.join(DATA_ROOT, 'helloWorldServer', 'main.go');
const BREAKPOINT_LINE = 29;
const remoteProgram = await setUpRemoteProgram(remoteAttachConfig.port, server);
const breakpointLocation = getBreakpointLocation(FILE, BREAKPOINT_LINE);
// Setup attach with a breakpoint.
await setUpRemoteAttach(remoteAttachDebugConfig, [breakpointLocation]);
// Calls the helloworld server to make the breakpoint hit.
await waitForBreakpoint(
() => http.get(`http://localhost:${server}`).on('error', (data) => console.log(data)),
breakpointLocation
);
await dc.disconnectRequest({ restart: false });
await killProcessTree(remoteProgram);
await new Promise((resolve) => setTimeout(resolve, 2_000));
});
test('stopped for a breakpoint set after initialization (remote attach)', async () => {
const FILE = path.join(DATA_ROOT, 'helloWorldServer', 'main.go');
const BREAKPOINT_LINE = 29;
const remoteProgram = await setUpRemoteProgram(remoteAttachConfig.port, server);
// Setup attach without a breakpoint.
await setUpRemoteAttach(remoteAttachDebugConfig);
// Now sets a breakpoint.
const breakpointLocation = getBreakpointLocation(FILE, BREAKPOINT_LINE);
const breakpointsResult = await dc.setBreakpointsRequest({
source: { path: breakpointLocation.path },
breakpoints: [breakpointLocation]
});
assert.ok(breakpointsResult.success && breakpointsResult.body.breakpoints[0].verified);
// Calls the helloworld server to make the breakpoint hit.
await waitForBreakpoint(
() => http.get(`http://localhost:${server}`).on('error', (data) => console.log(data)),
breakpointLocation
);
await dc.disconnectRequest({ restart: false });
await killProcessTree(remoteProgram);
await new Promise((resolve) => setTimeout(resolve, 2_000));
});
test('should set breakpoints during continue', async () => {
const PROGRAM = path.join(DATA_ROOT, 'sleep');
const FILE = path.join(DATA_ROOT, 'sleep', 'sleep.go');
const HELLO_LINE = 10;
const helloLocation = getBreakpointLocation(FILE, HELLO_LINE);
const config = {
name: 'Launch file',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await Promise.all([dc.configurationSequence(), dc.launch(debugConfig)]);
await Promise.all([
dc.setBreakpointsRequest({
lines: [helloLocation.line],
breakpoints: [{ line: helloLocation.line, column: 0 }],
source: { path: helloLocation.path }
}),
dc.assertStoppedLocation('breakpoint', helloLocation)
]);
});
async function setBreakpointsWhileRunningStep(resumeFunc: () => Promise<void>) {
const PROGRAM = path.join(DATA_ROOT, 'sleep');
const FILE = path.join(DATA_ROOT, 'sleep', 'sleep.go');
const SLEEP_LINE = 11;
const setupBreakpoint = getBreakpointLocation(FILE, SLEEP_LINE);
const HELLO_LINE = 10;
const resumeBreakpoint = getBreakpointLocation(FILE, HELLO_LINE);
const config = {
name: 'Launch file',
type: 'go',
request: 'launch',
mode: 'debug',
program: PROGRAM
};
const debugConfig = await initializeDebugConfig(config);
await dc.hitBreakpoint(debugConfig, setupBreakpoint);
// The program is now stopped at the line containing time.Sleep().
// Issue a next request, followed by a setBreakpointsRequest.
await resumeFunc();
// Assert that the program completes the step request.
await Promise.all([
dc.setBreakpointsRequest({
lines: [resumeBreakpoint.line],
breakpoints: [{ line: resumeBreakpoint.line, column: 0 }],
source: { path: resumeBreakpoint.path }
}),
dc.assertStoppedLocation('step', {})
]);
// Once the 'step' has completed, continue the program and
// make sure the breakpoint set while the program was nexting
// is succesfully hit.
await Promise.all([
dc.continueRequest({ threadId: 1 }),
dc.assertStoppedLocation('breakpoint', resumeBreakpoint)
]);
}
// Skip this test because it is flaky.
test.skip('should set breakpoints during next', async () => {