This repository has been archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 646
/
Copy pathgo.test.ts
1342 lines (1213 loc) · 59.4 KB
/
go.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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------*/
import * as assert from 'assert';
import * as fs from 'fs-extra';
import * as path from 'path';
import * as vscode from 'vscode';
import { GoHoverProvider } from '../src/goExtraInfo';
import { GoCompletionItemProvider } from '../src/goSuggest';
import { GoSignatureHelpProvider } from '../src/goSignature';
import { GoDefinitionProvider } from '../src/goDeclaration';
import { getWorkspaceSymbols } from '../src/goSymbol';
import { check } from '../src/goCheck';
import cp = require('child_process');
import { getEditsFromUnifiedDiffStr, getEdits } from '../src/diffUtils';
import { testCurrentFile } from '../src/goTest';
import { getBinPath, getGoVersion, isVendorSupported } from '../src/util';
import { documentSymbols, GoDocumentSymbolProvider, GoOutlineImportsOptions } from '../src/goOutline';
import { listPackages, getTextEditForAddImport } from '../src/goImport';
import { generateTestCurrentFile, generateTestCurrentFunction, generateTestCurrentPackage } from '../src/goGenerateTests';
import { getAllPackages } from '../src/goPackages';
import { getImportPath } from '../src/util';
import { goPlay } from '../src/goPlayground';
import { runFillStruct } from '../src/goFillStruct';
suite('Go Extension Tests', () => {
let gopath = process.env['GOPATH'];
if (!gopath) {
assert.ok(gopath, 'Cannot run tests if GOPATH is not set as environment variable');
return;
}
let repoPath = path.join(gopath, 'src', 'test');
let fixturePath = path.join(repoPath, 'testfixture');
let fixtureSourcePath = path.join(__dirname, '..', '..', 'test', 'fixtures');
let generateTestsSourcePath = path.join(repoPath, 'generatetests');
let generateFunctionTestSourcePath = path.join(repoPath, 'generatefunctiontest');
let generatePackageTestSourcePath = path.join(repoPath, 'generatePackagetest');
let testPath = path.join(__dirname, 'tests');
suiteSetup(() => {
fs.removeSync(repoPath);
fs.removeSync(testPath);
fs.copySync(path.join(fixtureSourcePath, 'test.go'), path.join(fixturePath, 'test.go'));
fs.copySync(path.join(fixtureSourcePath, 'errorsTest', 'errors.go'), path.join(fixturePath, 'errorsTest', 'errors.go'));
fs.copySync(path.join(fixtureSourcePath, 'sample_test.go'), path.join(fixturePath, 'sample_test.go'));
fs.copySync(path.join(fixtureSourcePath, 'gogetdocTestData', 'test.go'), path.join(fixturePath, 'gogetdocTestData', 'test.go'));
fs.copySync(path.join(fixtureSourcePath, 'generatetests', 'generatetests.go'), path.join(generateTestsSourcePath, 'generatetests.go'));
fs.copySync(path.join(fixtureSourcePath, 'generatetests', 'generatetests.go'), path.join(generateFunctionTestSourcePath, 'generatetests.go'));
fs.copySync(path.join(fixtureSourcePath, 'generatetests', 'generatetests.go'), path.join(generatePackageTestSourcePath, 'generatetests.go'));
fs.copySync(path.join(fixtureSourcePath, 'diffTestData', 'file1.go'), path.join(fixturePath, 'diffTest1Data', 'file1.go'));
fs.copySync(path.join(fixtureSourcePath, 'diffTestData', 'file2.go'), path.join(fixturePath, 'diffTest1Data', 'file2.go'));
fs.copySync(path.join(fixtureSourcePath, 'diffTestData', 'file1.go'), path.join(fixturePath, 'diffTest2Data', 'file1.go'));
fs.copySync(path.join(fixtureSourcePath, 'diffTestData', 'file2.go'), path.join(fixturePath, 'diffTest2Data', 'file2.go'));
fs.copySync(path.join(fixtureSourcePath, 'linterTest', 'linter_1.go'), path.join(fixturePath, 'linterTest', 'linter_1.go'));
fs.copySync(path.join(fixtureSourcePath, 'linterTest', 'linter_2.go'), path.join(fixturePath, 'linterTest', 'linter_2.go'));
fs.copySync(path.join(fixtureSourcePath, 'errorsTest', 'errors.go'), path.join(testPath, 'errorsTest', 'errors.go'));
fs.copySync(path.join(fixtureSourcePath, 'linterTest', 'linter_1.go'), path.join(testPath, 'linterTest', 'linter_1.go'));
fs.copySync(path.join(fixtureSourcePath, 'linterTest', 'linter_2.go'), path.join(testPath, 'linterTest', 'linter_2.go'));
fs.copySync(path.join(fixtureSourcePath, 'buildTags', 'hello.go'), path.join(fixturePath, 'buildTags', 'hello.go'));
fs.copySync(path.join(fixtureSourcePath, 'testTags', 'hello_test.go'), path.join(fixturePath, 'testTags', 'hello_test.go'));
fs.copySync(path.join(fixtureSourcePath, 'completions', 'unimportedPkgs.go'), path.join(fixturePath, 'completions', 'unimportedPkgs.go'));
fs.copySync(path.join(fixtureSourcePath, 'completions', 'unimportedMultiplePkgs.go'), path.join(fixturePath, 'completions', 'unimportedMultiplePkgs.go'));
fs.copySync(path.join(fixtureSourcePath, 'completions', 'snippets.go'), path.join(fixturePath, 'completions', 'snippets.go'));
fs.copySync(path.join(fixtureSourcePath, 'completions', 'nosnippets.go'), path.join(fixturePath, 'completions', 'nosnippets.go'));
fs.copySync(path.join(fixtureSourcePath, 'completions', 'exportedMemberDocs.go'), path.join(fixturePath, 'completions', 'exportedMemberDocs.go'));
fs.copySync(path.join(fixtureSourcePath, 'importTest', 'noimports.go'), path.join(fixturePath, 'importTest', 'noimports.go'));
fs.copySync(path.join(fixtureSourcePath, 'importTest', 'groupImports.go'), path.join(fixturePath, 'importTest', 'groupImports.go'));
fs.copySync(path.join(fixtureSourcePath, 'importTest', 'singleImports.go'), path.join(fixturePath, 'importTest', 'singleImports.go'));
fs.copySync(path.join(fixtureSourcePath, 'fillStruct', 'input_1.go'), path.join(fixturePath, 'fillStruct', 'input_1.go'));
fs.copySync(path.join(fixtureSourcePath, 'fillStruct', 'golden_1.go'), path.join(fixturePath, 'fillStruct', 'golden_1.go'));
fs.copySync(path.join(fixtureSourcePath, 'fillStruct', 'input_2.go'), path.join(fixturePath, 'fillStruct', 'input_2.go'));
fs.copySync(path.join(fixtureSourcePath, 'fillStruct', 'golden_2.go'), path.join(fixturePath, 'fillStruct', 'golden_2.go'));
fs.copySync(path.join(fixtureSourcePath, 'fillStruct', 'input_2.go'), path.join(fixturePath, 'fillStruct', 'input_3.go'));
fs.copySync(path.join(fixtureSourcePath, 'outlineTest', 'test.go'), path.join(fixturePath, 'outlineTest', 'test.go'));
});
suiteTeardown(() => {
fs.removeSync(repoPath);
fs.removeSync(testPath);
});
function testDefinitionProvider(goConfig: vscode.WorkspaceConfiguration): Thenable<any> {
let provider = new GoDefinitionProvider(goConfig);
let uri = vscode.Uri.file(path.join(fixturePath, 'test.go'));
let position = new vscode.Position(10, 3);
return vscode.workspace.openTextDocument(uri).then((textDocument) => {
return provider.provideDefinition(textDocument, position, null).then(definitionInfo => {
assert.equal(definitionInfo.uri.path.toLowerCase(), uri.path.toLowerCase(), `${definitionInfo.uri.path} is not the same as ${uri.path}`);
assert.equal(definitionInfo.range.start.line, 6);
assert.equal(definitionInfo.range.start.character, 5);
});
}, (err) => {
assert.ok(false, `error in OpenTextDocument ${err}`);
return Promise.reject(err);
});
}
function testSignatureHelpProvider(goConfig: vscode.WorkspaceConfiguration, testCases: [vscode.Position, string, string, string[]][]): Thenable<any> {
let provider = new GoSignatureHelpProvider(goConfig);
let uri = vscode.Uri.file(path.join(fixturePath, 'gogetdocTestData', 'test.go'));
return vscode.workspace.openTextDocument(uri).then((textDocument) => {
let promises = testCases.map(([position, expected, expectedDoc, expectedParams]) =>
provider.provideSignatureHelp(textDocument, position, null).then(sigHelp => {
assert.equal(sigHelp.signatures.length, 1, 'unexpected number of overloads');
assert.equal(sigHelp.signatures[0].label, expected);
assert.equal(sigHelp.signatures[0].documentation, expectedDoc);
assert.equal(sigHelp.signatures[0].parameters.length, expectedParams.length);
for (let i = 0; i < expectedParams.length; i++) {
assert.equal(sigHelp.signatures[0].parameters[i].label, expectedParams[i]);
}
})
);
return Promise.all(promises);
}, (err) => {
assert.ok(false, `error in OpenTextDocument ${err}`);
return Promise.reject(err);
});
}
function testHoverProvider(goConfig: vscode.WorkspaceConfiguration, testCases: [vscode.Position, string, string][]): Thenable<any> {
let provider = new GoHoverProvider(goConfig);
let uri = vscode.Uri.file(path.join(fixturePath, 'gogetdocTestData', 'test.go'));
return vscode.workspace.openTextDocument(uri).then((textDocument) => {
let promises = testCases.map(([position, expectedSignature, expectedDocumentation]) =>
provider.provideHover(textDocument, position, null).then(res => {
if (expectedSignature === null && expectedDocumentation === null) {
assert.equal(res, null);
return;
}
assert.equal(expectedSignature, (<{ language: string; value: string }>res.contents[0]).value);
if (expectedDocumentation === null) {
return;
}
assert.equal(res.contents.length, 2);
assert.equal(expectedDocumentation, <string>(res.contents[1]));
})
);
return Promise.all(promises);
}, (err) => {
assert.ok(false, `error in OpenTextDocument ${err}`);
return Promise.reject(err);
});
}
test('Test Definition Provider using godoc', (done) => {
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'docsTool': { value: 'godoc' }
});
testDefinitionProvider(config).then(() => done(), done);
});
test('Test Definition Provider using gogetdoc', (done) => {
const gogetdocPath = getBinPath('gogetdoc');
if (gogetdocPath === 'gogetdoc') {
return done();
}
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'docsTool': { value: 'gogetdoc' }
});
getGoVersion().then(version => {
if (!version || version.major > 1 || (version.major === 1 && version.minor > 8)) {
return testDefinitionProvider(config);
}
return Promise.resolve();
}).then(() => done(), done);
}).timeout(10000);
test('Test SignatureHelp Provider using godoc', (done) => {
let printlnDoc = `Println formats using the default formats for its operands and writes to
standard output. Spaces are always added between operands and a newline is
appended. It returns the number of bytes written and any write error
encountered.
`;
let testCases: [vscode.Position, string, string, string[]][] = [
[new vscode.Position(19, 13), 'Println(a ...interface{}) (n int, err error)', printlnDoc, ['a ...interface{}']],
[new vscode.Position(23, 7), 'print(txt string)', 'This is an unexported function so couldn\'t get this comment on hover :( Not\nanymore!!\n', ['txt string']],
[new vscode.Position(41, 19), 'Hello(s string, exclaim bool) string', 'Hello is a method on the struct ABC. Will signature help understand this\ncorrectly\n', ['s string', 'exclaim bool']],
[new vscode.Position(41, 47), 'EmptyLine(s string) string', 'EmptyLine has docs\n\nwith a blank line in the middle\n', ['s string']]
];
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'docsTool': { value: 'godoc' }
});
testSignatureHelpProvider(config, testCases).then(() => done(), done);
});
test('Test SignatureHelp Provider using gogetdoc', (done) => {
const gogetdocPath = getBinPath('gogetdoc');
if (gogetdocPath === 'gogetdoc') {
return done();
}
let printlnDoc = `Println formats using the default formats for its operands and writes to standard output.
Spaces are always added between operands and a newline is appended.
It returns the number of bytes written and any write error encountered.
`;
let testCases: [vscode.Position, string, string, string[]][] = [
[new vscode.Position(19, 13), 'Println(a ...interface{}) (n int, err error)', printlnDoc, ['a ...interface{}']],
[new vscode.Position(23, 7), 'print(txt string)', 'This is an unexported function so couldn\'t get this comment on hover :(\nNot anymore!!\n', ['txt string']],
[new vscode.Position(41, 19), 'Hello(s string, exclaim bool) string', 'Hello is a method on the struct ABC. Will signature help understand this correctly\n', ['s string', 'exclaim bool']],
[new vscode.Position(41, 47), 'EmptyLine(s string) string', 'EmptyLine has docs\n\nwith a blank line in the middle\n', ['s string']]
];
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'docsTool': { value: 'gogetdoc' }
});
getGoVersion().then(version => {
if (!version || version.major > 1 || (version.major === 1 && version.minor > 8)) {
return testSignatureHelpProvider(config, testCases);
}
return Promise.resolve();
}).then(() => done(), done);
}).timeout(10000);
test('Test Hover Provider using godoc', (done) => {
let printlnDoc = `Println formats using the default formats for its operands and writes to
standard output. Spaces are always added between operands and a newline is
appended. It returns the number of bytes written and any write error
encountered.
`;
let testCases: [vscode.Position, string, string][] = [
// [new vscode.Position(3,3), '/usr/local/go/src/fmt'],
[new vscode.Position(0, 3), null, null], // keyword
[new vscode.Position(23, 14), null, null], // inside a string
[new vscode.Position(20, 0), null, null], // just a }
[new vscode.Position(28, 16), null, null], // inside a number
[new vscode.Position(22, 5), 'main func()', null],
[new vscode.Position(40, 23), 'import (math "math")', null],
[new vscode.Position(19, 6), 'Println func(a ...interface{}) (n int, err error)', printlnDoc],
[new vscode.Position(23, 4), 'print func(txt string)', null]
];
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'docsTool': { value: 'godoc' }
});
testHoverProvider(config, testCases).then(() => done(), done);
});
test('Test Hover Provider using gogetdoc', (done) => {
const gogetdocPath = getBinPath('gogetdoc');
if (gogetdocPath === 'gogetdoc') {
return done();
}
let printlnDoc = `Println formats using the default formats for its operands and writes to standard output.
Spaces are always added between operands and a newline is appended.
It returns the number of bytes written and any write error encountered.
`;
let testCases: [vscode.Position, string, string][] = [
[new vscode.Position(0, 3), null, null], // keyword
[new vscode.Position(23, 11), null, null], // inside a string
[new vscode.Position(20, 0), null, null], // just a }
[new vscode.Position(28, 16), null, null], // inside a number
[new vscode.Position(22, 5), 'func main()', ''],
[new vscode.Position(23, 4), 'func print(txt string)', 'This is an unexported function so couldn\'t get this comment on hover :(\nNot anymore!!\n'],
[new vscode.Position(40, 23), 'package math', 'Package math provides basic constants and mathematical functions.\n\nThis package does not guarantee bit-identical results across architectures.\n'],
[new vscode.Position(19, 6), 'func Println(a ...interface{}) (n int, err error)', printlnDoc],
[new vscode.Position(27, 14), 'type ABC struct {\n a int\n b int\n c int\n}', 'ABC is a struct, you coudn\'t use Goto Definition or Hover info on this before\nNow you can due to gogetdoc and go doc\n'],
[new vscode.Position(28, 6), 'func CIDRMask(ones, bits int) IPMask', 'CIDRMask returns an IPMask consisting of `ones\' 1 bits\nfollowed by 0s up to a total length of `bits\' bits.\nFor a mask of this form, CIDRMask is the inverse of IPMask.Size.\n']
];
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'docsTool': { value: 'gogetdoc' }
});
getGoVersion().then(version => {
if (!version || version.major > 1 || (version.major === 1 && version.minor > 8)) {
return testHoverProvider(config, testCases);
}
return Promise.resolve();
}).then(() => done(), done);
}).timeout(10000);
test('Error checking', (done) => {
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'vetOnSave': { value: 'package' },
'vetFlags': { value: ['-all'] },
'lintOnSave': { value: 'package' },
'lintTool': { value: 'golint' },
'lintFlags': { value: [] }
});
let expected = [
{ line: 7, severity: 'warning', msg: 'exported function Print2 should have comment or be unexported' },
{ line: 11, severity: 'error', msg: 'undefined: prin' },
];
getGoVersion().then(version => {
if (version && version.major === 1 && version.minor < 9) {
// golint supports only latest 3 versions, so skip the test
return Promise.resolve();
}
return check(vscode.Uri.file(path.join(fixturePath, 'errorsTest', 'errors.go')), config).then(diagnostics => {
let sortedDiagnostics = diagnostics.sort((a, b) => a.line - b.line);
assert.equal(sortedDiagnostics.length > 0, true, `Failed to get linter results`);
let matchCount = 0;
for (let i in expected) {
for (let j in sortedDiagnostics) {
if (expected[i].line
&& (expected[i].line === sortedDiagnostics[j].line)
&& (expected[i].severity === sortedDiagnostics[j].severity)
&& (expected[i].msg === sortedDiagnostics[j].msg)) {
matchCount++;
}
}
}
assert.equal(matchCount >= expected.length, true, `Failed to match expected errors`);
});
}).then(() => done(), done);
});
test('Test Generate unit tests skeleton for file', (done) => {
const gotestsPath = getBinPath('gotests');
if (gotestsPath === 'gotests') {
return done();
}
getGoVersion().then(version => {
if (version && version.major === 1 && version.minor < 6) {
// gotests is not supported in Go 1.5, so skip the test
return Promise.resolve();
}
let uri = vscode.Uri.file(path.join(generateTestsSourcePath, 'generatetests.go'));
return vscode.workspace.openTextDocument(uri).then(document => {
return vscode.window.showTextDocument(document).then(editor => {
return generateTestCurrentFile().then((result: boolean) => {
assert.equal(result, true);
return Promise.resolve();
});
});
}).then(() => {
vscode.commands.executeCommand('workbench.action.closeActiveEditor');
if (fs.existsSync(path.join(generateTestsSourcePath, 'generatetests_test.go'))) {
return Promise.resolve();
} else {
return Promise.reject('generatetests_test.go not found');
}
});
}).then(() => done(), done);
});
test('Test Generate unit tests skeleton for a function', (done) => {
const gotestsPath = getBinPath('gotests');
if (gotestsPath === 'gotests') {
return done();
}
getGoVersion().then(version => {
if (version && version.major === 1 && version.minor < 6) {
// gotests is not supported in Go 1.5, so skip the test
return Promise.resolve();
}
let uri = vscode.Uri.file(path.join(generateFunctionTestSourcePath, 'generatetests.go'));
return vscode.workspace.openTextDocument(uri).then(document => {
return vscode.window.showTextDocument(document).then((editor: vscode.TextEditor) => {
assert(vscode.window.activeTextEditor, 'No active editor');
let selection = new vscode.Selection(5, 0, 6, 0);
editor.selection = selection;
return generateTestCurrentFunction().then((result: boolean) => {
assert.equal(result, true);
return Promise.resolve();
});
});
}).then(() => {
vscode.commands.executeCommand('workbench.action.closeActiveEditor');
if (fs.existsSync(path.join(generateTestsSourcePath, 'generatetests_test.go'))) {
return Promise.resolve();
} else {
return Promise.reject('generatetests_test.go not found');
}
});
}).then(() => done(), done);
});
test('Test Generate unit tests skeleton for package', (done) => {
const gotestsPath = getBinPath('gotests');
if (gotestsPath === 'gotests') {
return done();
}
getGoVersion().then(version => {
if (version && version.major === 1 && version.minor < 6) {
// gotests is not supported in Go 1.5, so skip the test
return Promise.resolve();
}
let uri = vscode.Uri.file(path.join(generatePackageTestSourcePath, 'generatetests.go'));
return vscode.workspace.openTextDocument(uri).then(document => {
return vscode.window.showTextDocument(document).then(editor => {
return generateTestCurrentPackage().then((result: boolean) => {
assert.equal(result, true);
return Promise.resolve();
});
});
}).then(() => {
vscode.commands.executeCommand('workbench.action.closeActiveEditor');
if (fs.existsSync(path.join(generateTestsSourcePath, 'generatetests_test.go'))) {
return Promise.resolve();
} else {
return Promise.reject('generatetests_test.go not found');
}
});
}).then(() => done(), done);
});
test('Gometalinter error checking', (done) => {
getGoVersion().then(version => {
if (version && version.major === 1 && version.minor < 6) {
// golint in gometalinter is not supported in Go 1.5, so skip the test
return Promise.resolve();
}
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'lintOnSave': { value: 'package' },
'lintTool': { value: 'gometalinter' },
'lintFlags': { value: ['--disable-all', '--enable=varcheck', '--enable=errcheck'] },
'vetOnSave': { value: 'off' },
'buildOnSave': { value: 'off' }
});
let expected = [
{ line: 11, severity: 'warning', msg: 'error return value not checked (undeclared name: prin) (errcheck)' },
{ line: 11, severity: 'warning', msg: 'unused variable or constant undeclared name: prin (varcheck)' },
];
let errorsTestPath = path.join(fixturePath, 'errorsTest', 'errors.go');
return check(vscode.Uri.file(errorsTestPath), config).then(diagnostics => {
let sortedDiagnostics = diagnostics.sort((a, b) => {
if (a.msg < b.msg)
return -1;
if (a.msg > b.msg)
return 1;
return 0;
});
assert.equal(sortedDiagnostics.length > 0, true, `Failed to get linter results`);
let matchCount = 0;
for (let i in expected) {
for (let j in sortedDiagnostics) {
if ((expected[i].line === sortedDiagnostics[j].line)
&& (expected[i].severity === sortedDiagnostics[j].severity)
&& (expected[i].msg === sortedDiagnostics[j].msg)) {
matchCount++;
}
}
}
assert.equal(matchCount >= expected.length, true, `Failed to match expected errors`);
return Promise.resolve();
});
}).then(() => done(), done);
});
test('Test diffUtils.getEditsFromUnifiedDiffStr', (done) => {
let file1path = path.join(fixturePath, 'diffTest1Data', 'file1.go');
let file2path = path.join(fixturePath, 'diffTest1Data', 'file2.go');
let file1uri = vscode.Uri.file(file1path);
let file2contents = fs.readFileSync(file2path, 'utf8');
let diffPromise = new Promise((resolve, reject) => {
cp.exec(`diff -u ${file1path} ${file2path}`, (err, stdout, stderr) => {
let filePatches = getEditsFromUnifiedDiffStr(stdout);
if (!filePatches && filePatches.length !== 1) {
assert.fail(null, null, 'Failed to get patches for the test file', '');
return reject();
}
if (!filePatches[0].fileName) {
assert.fail(null, null, 'Failed to parse the file path from the diff output', '');
return reject();
}
if (!filePatches[0].edits) {
assert.fail(null, null, 'Failed to parse edits from the diff output', '');
return reject();
}
resolve(filePatches);
});
});
diffPromise.then((filePatches) => {
return vscode.workspace.openTextDocument(file1uri).then((textDocument) => {
return vscode.window.showTextDocument(textDocument).then(editor => {
return editor.edit((editBuilder) => {
filePatches[0].edits.forEach(edit => {
edit.applyUsingTextEditorEdit(editBuilder);
});
}).then(() => {
assert.equal(editor.document.getText(), file2contents);
return Promise.resolve();
});
});
});
}).then(() => done(), done);
});
test('Test diffUtils.getEdits', (done) => {
let file1path = path.join(fixturePath, 'diffTest2Data', 'file1.go');
let file2path = path.join(fixturePath, 'diffTest2Data', 'file2.go');
let file1uri = vscode.Uri.file(file1path);
let file1contents = fs.readFileSync(file1path, 'utf8');
let file2contents = fs.readFileSync(file2path, 'utf8');
let fileEdits = getEdits(file1path, file1contents, file2contents);
if (!fileEdits) {
assert.fail(null, null, 'Failed to get patches for the test file', '');
done();
return;
}
if (!fileEdits.fileName) {
assert.fail(null, null, 'Failed to parse the file path from the diff output', '');
done();
return;
}
if (!fileEdits.edits) {
assert.fail(null, null, 'Failed to parse edits from the diff output', '');
done();
return;
}
vscode.workspace.openTextDocument(file1uri).then((textDocument) => {
return vscode.window.showTextDocument(textDocument).then(editor => {
return editor.edit((editBuilder) => {
fileEdits.edits.forEach(edit => {
edit.applyUsingTextEditorEdit(editBuilder);
});
}).then(() => {
assert.equal(editor.document.getText(), file2contents);
return Promise.resolve();
});
}).then(() => done(), done);
});
});
test('Test Env Variables are passed to Tests', (done) => {
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'testEnvVars': { value: { 'dummyEnvVar': 'dummyEnvValue', 'dummyNonString': 1 } }
});
let uri = vscode.Uri.file(path.join(fixturePath, 'sample_test.go'));
vscode.workspace.openTextDocument(uri).then(document => {
return vscode.window.showTextDocument(document).then(editor => {
return testCurrentFile(config, false, []).then((result: boolean) => {
assert.equal(result, true);
return Promise.resolve();
});
});
}).then(() => done(), done);
});
test('Test Outline', (done) => {
let filePath = path.join(fixturePath, 'outlineTest', 'test.go');
let options = { fileName: filePath, importsOption: GoOutlineImportsOptions.Include, skipRanges: true };
documentSymbols(options, null).then(outlines => {
let packageSymbols = outlines.filter(x => x.kind === vscode.SymbolKind.Package);
let imports = outlines.filter(x => x.kind === vscode.SymbolKind.Namespace);
let functions = outlines.filter(x => x.kind === vscode.SymbolKind.Function);
assert.equal(packageSymbols.length, 1);
assert.equal(packageSymbols[0].name, 'main');
assert.equal(imports.length, 1);
assert.equal(imports[0].name, '"fmt"');
assert.equal(functions.length, 2);
assert.equal(functions[0].name, 'print');
assert.equal(functions[1].name, 'main');
done();
}, done);
});
test('Test Outline imports only', (done) => {
let filePath = path.join(fixturePath, 'outlineTest', 'test.go');
let options = { fileName: filePath, importsOption: GoOutlineImportsOptions.Only, skipRanges: true };
documentSymbols(options, null).then(outlines => {
let packageSymbols = outlines.filter(x => x.kind === vscode.SymbolKind.Package);
let imports = outlines.filter(x => x.kind === vscode.SymbolKind.Namespace);
let functions = outlines.filter(x => x.kind === vscode.SymbolKind.Function);
assert.equal(packageSymbols.length, 1);
assert.equal(packageSymbols[0].name, 'main');
assert.equal(imports.length, 1);
assert.equal(imports[0].name, '"fmt"');
assert.equal(functions.length, 0);
done();
}, done);
});
test('Test Outline document symbols', (done) => {
let uri = vscode.Uri.file(path.join(fixturePath, 'outlineTest', 'test.go'));
vscode.workspace.openTextDocument(uri).then(document => {
new GoDocumentSymbolProvider().provideDocumentSymbols(document, null).then(symbols => {
let groupedSymbolNames = symbols.reduce(function (map, symbol) {
map[symbol.kind] = (map[symbol.kind] || []).concat([symbol.name]);
return map;
}, {});
let packageNames = groupedSymbolNames[vscode.SymbolKind.Package];
let variableNames = groupedSymbolNames[vscode.SymbolKind.Variable];
let functionNames = groupedSymbolNames[vscode.SymbolKind.Function];
assert.equal(packageNames[0], 'main');
assert.equal(variableNames, undefined);
assert.equal(functionNames[0], 'print');
assert.equal(functionNames[1], 'main');
});
}).then(() => done(), done);
});
test('Test listPackages', (done) => {
let uri = vscode.Uri.file(path.join(fixturePath, 'test.go'));
vscode.workspace.openTextDocument(uri).then(document => {
return vscode.window.showTextDocument(document).then(editor => {
let includeImportedPkgs = listPackages(false);
let excludeImportedPkgs = listPackages(true);
return Promise.all([includeImportedPkgs, excludeImportedPkgs]).then(([pkgsInclude, pkgsExclude]) => {
assert.equal(pkgsInclude.indexOf('fmt') > -1, true);
assert.equal(pkgsExclude.indexOf('fmt') > -1, false);
});
});
}).then(() => done(), done);
});
test('Replace vendor packages with relative path', (done) => {
// This test needs a go project that has vendor folder and vendor packages
// Since the Go extension takes a dependency on the godef tool at github.com/rogpeppe/godef
// which has vendor packages, we are using it here to test the "replace vendor packages with relative path" feature.
// If the extension ever stops depending on godef tool or if godef ever stops having vendor packages, then this test
// will fail and will have to be replaced with any other go project with vendor packages
let vendorSupportPromise = isVendorSupported();
let filePath = path.join(process.env['GOPATH'], 'src', 'github.com', 'rogpeppe', 'godef', 'go', 'ast', 'ast.go');
let workDir = path.dirname(filePath);
let vendorPkgsFullPath = [
'github.com/rogpeppe/godef/vendor/9fans.net/go/acme',
'github.com/rogpeppe/godef/vendor/9fans.net/go/plan9',
'github.com/rogpeppe/godef/vendor/9fans.net/go/plan9/client'
];
let vendorPkgsRelativePath = [
'9fans.net/go/acme',
'9fans.net/go/plan9',
'9fans.net/go/plan9/client'
];
vendorSupportPromise.then((vendorSupport: boolean) => {
let gopkgsPromise = getAllPackages(workDir).then(pkgMap => {
let pkgs = Array.from(pkgMap.keys());
pkgs = pkgs.filter(p => pkgMap.get(p) !== 'main');
if (vendorSupport) {
vendorPkgsFullPath.forEach(pkg => {
assert.equal(pkgs.indexOf(pkg) > -1, true, `Package not found by goPkgs: ${pkg}`);
});
vendorPkgsRelativePath.forEach(pkg => {
assert.equal(pkgs.indexOf(pkg), -1, `Relative path to vendor package ${pkg} should not be returned by gopkgs command`);
});
}
return Promise.resolve(pkgs);
});
let listPkgPromise: Thenable<string[]> = vscode.workspace.openTextDocument(vscode.Uri.file(filePath)).then(document => {
return vscode.window.showTextDocument(document).then(editor => {
return listPackages().then(pkgs => {
if (vendorSupport) {
vendorPkgsRelativePath.forEach(pkg => {
assert.equal(pkgs.indexOf(pkg) > -1, true, `Relative path for vendor package ${pkg} not found`);
});
vendorPkgsFullPath.forEach(pkg => {
assert.equal(pkgs.indexOf(pkg), -1, `Full path for vendor package ${pkg} should be shown by listPackages method`);
});
}
return Promise.resolve(pkgs);
});
});
});
return Promise.all<string[]>([gopkgsPromise, listPkgPromise]).then((values: string[][]) => {
if (!vendorSupport) {
let originalPkgs = values[0].sort();
let updatedPkgs = values[1].sort();
assert.equal(originalPkgs.length, updatedPkgs.length);
for (let index = 0; index < originalPkgs.length; index++) {
assert.equal(updatedPkgs[index], originalPkgs[index]);
}
}
});
}).then(() => done(), done);
});
test('Vendor pkgs from other projects should not be allowed to import', (done) => {
// This test needs a go project that has vendor folder and vendor packages
// Since the Go extension takes a dependency on the godef tool at github.com/rogpeppe/godef
// which has vendor packages, we are using it here to test the "replace vendor packages with relative path" feature.
// If the extension ever stops depending on godef tool or if godef ever stops having vendor packages, then this test
// will fail and will have to be replaced with any other go project with vendor packages
let vendorSupportPromise = isVendorSupported();
let filePath = path.join(process.env['GOPATH'], 'src', 'github.com', 'ramya-rao-a', 'go-outline', 'main.go');
let vendorPkgs = [
'github.com/rogpeppe/godef/vendor/9fans.net/go/acme',
'github.com/rogpeppe/godef/vendor/9fans.net/go/plan9',
'github.com/rogpeppe/godef/vendor/9fans.net/go/plan9/client'
];
vendorSupportPromise.then((vendorSupport: boolean) => {
let gopkgsPromise = new Promise<void>((resolve, reject) => {
let cmd = cp.spawn(getBinPath('gopkgs'), ['-format', '{{.ImportPath}}'], { env: process.env });
let chunks = [];
cmd.stdout.on('data', (d) => chunks.push(d));
cmd.on('close', () => {
let pkgs = chunks.join('').split('\n').filter((pkg) => pkg).sort();
if (vendorSupport) {
vendorPkgs.forEach(pkg => {
assert.equal(pkgs.indexOf(pkg) > -1, true, `Package not found by goPkgs: ${pkg}`);
});
}
return resolve();
});
});
let listPkgPromise: Thenable<void> = vscode.workspace.openTextDocument(vscode.Uri.file(filePath)).then(document => {
return vscode.window.showTextDocument(document).then(editor => {
return listPackages().then(pkgs => {
if (vendorSupport) {
vendorPkgs.forEach(pkg => {
assert.equal(pkgs.indexOf(pkg), -1, `Vendor package ${pkg} should not be shown by listPackages method`);
});
}
return Promise.resolve();
});
});
});
return Promise.all<void>([gopkgsPromise, listPkgPromise]);
}).then(() => done(), done);
});
test('Workspace Symbols', () => {
// This test needs a go project that has vendor folder and vendor packages
// Since the Go extension takes a dependency on the godef tool at github.com/rogpeppe/godef
// which has vendor packages, we are using it here to test the "replace vendor packages with relative path" feature.
// If the extension ever stops depending on godef tool or if godef ever stops having vendor packages, then this test
// will fail and will have to be replaced with any other go project with vendor packages
let workspacePath = path.join(process.env['GOPATH'], 'src', 'github.com', 'rogpeppe', 'godef');
let configWithoutIgnoringFolders = Object.create(vscode.workspace.getConfiguration('go'), {
'gotoSymbol': {
value: {
'ignoreFolders': []
}
}
});
let configWithIgnoringFolders = Object.create(vscode.workspace.getConfiguration('go'), {
'gotoSymbol': {
value: {
'ignoreFolders': ['vendor']
}
}
});
let configWithIncludeGoroot = Object.create(vscode.workspace.getConfiguration('go'), {
'gotoSymbol': {
value: {
'includeGoroot': true
}
}
});
let configWithoutIncludeGoroot = Object.create(vscode.workspace.getConfiguration('go'), {
'gotoSymbol': {
value: {
'includeGoroot': false
}
}
});
let withoutIgnoringFolders = getWorkspaceSymbols(workspacePath, 'WinInfo', null, configWithoutIgnoringFolders).then(results => {
assert.equal(results[0].name, 'WinInfo');
assert.equal(results[0].path, path.join(workspacePath, 'vendor/9fans.net/go/acme/acme.go'));
});
let withIgnoringFolders = getWorkspaceSymbols(workspacePath, 'WinInfo', null, configWithIgnoringFolders).then(results => {
assert.equal(results.length, 0);
});
let withoutIncludingGoroot = getWorkspaceSymbols(workspacePath, 'Mutex', null, configWithoutIncludeGoroot).then(results => {
assert.equal(results.length, 0);
});
let withIncludingGoroot = getWorkspaceSymbols(workspacePath, 'Mutex', null, configWithIncludeGoroot).then(results => {
assert(results.some(result => result.name === 'Mutex'));
});
return Promise.all([withIgnoringFolders, withoutIgnoringFolders, withIncludingGoroot, withoutIncludingGoroot]);
});
test('Test Completion', (done) => {
let printlnDoc = `Println formats using the default formats for its operands and writes to
standard output. Spaces are always added between operands and a newline is
appended. It returns the number of bytes written and any write error
encountered.
`;
let provider = new GoCompletionItemProvider();
let testCases: [vscode.Position, string, string, string][] = [
[new vscode.Position(7, 4), 'fmt', 'fmt', null],
[new vscode.Position(7, 6), 'Println', 'func(a ...interface{}) (n int, err error)', printlnDoc]
];
let uri = vscode.Uri.file(path.join(fixturePath, 'test.go'));
vscode.workspace.openTextDocument(uri).then((textDocument) => {
return vscode.window.showTextDocument(textDocument).then(editor => {
let promises = testCases.map(([position, expectedLabel, expectedDetail, expectedDoc]) =>
provider.provideCompletionItems(editor.document, position, null).then(items => {
let item = items.items.find(x => x.label === expectedLabel);
assert.equal(!!item, true, 'missing expected item in competion list');
assert.equal(item.detail, expectedDetail);
const resolvedItemResult: vscode.ProviderResult<vscode.CompletionItem> = provider.resolveCompletionItem(item, null);
if (!resolvedItemResult) {
return;
}
if (resolvedItemResult instanceof vscode.CompletionItem) {
if (resolvedItemResult.documentation) {
assert.equal((<vscode.MarkdownString>resolvedItemResult.documentation).value, expectedDoc);
}
return;
}
return resolvedItemResult.then(resolvedItem => {
if (resolvedItem) {
assert.equal((<vscode.MarkdownString>resolvedItem.documentation).value, expectedDoc);
}
});
})
);
return Promise.all(promises);
}).then(() => {
vscode.commands.executeCommand('workbench.action.closeActiveEditor');
return Promise.resolve();
});
}, (err) => {
assert.ok(false, `error in OpenTextDocument ${err}`);
}).then(() => done(), done);
});
test('Test Completion Snippets For Functions', (done) => {
let provider = new GoCompletionItemProvider();
let uri = vscode.Uri.file(path.join(fixturePath, 'completions', 'snippets.go'));
let testCases: [vscode.Position, string[]][] = [
[new vscode.Position(5, 6), ['Print']]
];
let baseConfig = vscode.workspace.getConfiguration('go');
vscode.workspace.openTextDocument(uri).then((textDocument) => {
return vscode.window.showTextDocument(textDocument).then(editor => {
let noFunctionSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(9, 6), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggest': { value: false } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item = items.find(x => x.label === 'Print');
assert.equal(!item.insertText, true);
});
let withFunctionSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(9, 6), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggest': { value: true } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item = items.find(x => x.label === 'Print');
assert.equal((<vscode.SnippetString>item.insertText).value, 'Print(${1:a ...interface{\\}})');
});
let withFunctionSnippetNotype = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(9, 6), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggestWithoutType': { value: true } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item = items.find(x => x.label === 'Print');
assert.equal((<vscode.SnippetString>item.insertText).value, 'Print(${1:a})');
});
let noFunctionAsVarSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(11, 3), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggest': { value: false } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item = items.find(x => x.label === 'funcAsVariable');
assert.equal(!item.insertText, true);
});
let withFunctionAsVarSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(11, 3), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggest': { value: true } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item = items.find(x => x.label === 'funcAsVariable');
assert.equal((<vscode.SnippetString>item.insertText).value, 'funcAsVariable(${1:k string})');
});
let withFunctionAsVarSnippetNoType = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(11, 3), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggestWithoutType': { value: true } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item = items.find(x => x.label === 'funcAsVariable');
assert.equal((<vscode.SnippetString>item.insertText).value, 'funcAsVariable(${1:k})');
});
let noFunctionAsTypeSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(14, 0), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggest': { value: false } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item1 = items.find(x => x.label === 'HandlerFunc');
let item2 = items.find(x => x.label === 'HandlerFuncWithArgNames');
let item3 = items.find(x => x.label === 'HandlerFuncNoReturnType');
assert.equal(!item1.insertText, true);
assert.equal(!item2.insertText, true);
assert.equal(!item3.insertText, true);
});
let withFunctionAsTypeSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(14, 0), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggest': { value: true } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item1 = items.find(x => x.label === 'HandlerFunc');
let item2 = items.find(x => x.label === 'HandlerFuncWithArgNames');
let item3 = items.find(x => x.label === 'HandlerFuncNoReturnType');
assert.equal((<vscode.SnippetString>item1.insertText).value, 'HandlerFunc(func(${1:arg1} string, ${2:arg2} string) {\n\t$3\n}) (string, string)');
assert.equal((<vscode.SnippetString>item2.insertText).value, 'HandlerFuncWithArgNames(func(${1:w} string, ${2:r} string) {\n\t$3\n}) int');
assert.equal((<vscode.SnippetString>item3.insertText).value, 'HandlerFuncNoReturnType(func(${1:arg1} string, ${2:arg2} string) {\n\t$3\n})');
});
return Promise.all([
noFunctionSnippet, withFunctionSnippet, withFunctionSnippetNotype,
noFunctionAsVarSnippet, withFunctionAsVarSnippet, withFunctionAsVarSnippetNoType,
noFunctionAsTypeSnippet, withFunctionAsTypeSnippet]).then(() => vscode.commands.executeCommand('workbench.action.closeActiveEditor'));
});
}, (err) => {
assert.ok(false, `error in OpenTextDocument ${err}`);
}).then(() => done(), done);
});
test('Test No Completion Snippets For Functions', (done) => {
let provider = new GoCompletionItemProvider();
let uri = vscode.Uri.file(path.join(fixturePath, 'completions', 'nosnippets.go'));
let baseConfig = vscode.workspace.getConfiguration('go');
vscode.workspace.openTextDocument(uri).then((textDocument) => {
return vscode.window.showTextDocument(textDocument).then(editor => {
let symbolFollowedByBrackets = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(5, 10), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggest': { value: true } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item = items.find(x => x.label === 'Print');
assert.equal(!item.insertText, true, 'Unexpected snippet when symbol is followed by ().');
});
let symbolAsLastParameter = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(7, 13), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggest': { value: true } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item = items.find(x => x.label === 'funcAsVariable');
assert.equal(!item.insertText, true, 'Unexpected snippet when symbol is a parameter inside func call');
});
let symbolsAsNonLastParameter = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(8, 11), null, Object.create(baseConfig, { 'useCodeSnippetsOnFunctionSuggest': { value: true } })).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let item = items.find(x => x.label === 'funcAsVariable');
assert.equal(!item.insertText, true, 'Unexpected snippet when symbol is one of the parameters inside func call.');
});
return Promise.all([
symbolFollowedByBrackets, symbolAsLastParameter, symbolsAsNonLastParameter]).then(() => vscode.commands.executeCommand('workbench.action.closeActiveEditor'));
});
}, (err) => {
assert.ok(false, `error in OpenTextDocument ${err}`);
}).then(() => done(), done);
});
test('Test Completion on unimported packages', (done) => {
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'autocompleteUnimportedPackages': { value: true }
});
let provider = new GoCompletionItemProvider();
let testCases: [vscode.Position, string[]][] = [
[new vscode.Position(10, 3), ['bytes']],
[new vscode.Position(11, 6), ['Abs', 'Acos', 'Asin']]
];
let uri = vscode.Uri.file(path.join(fixturePath, 'completions', 'unimportedPkgs.go'));
vscode.workspace.openTextDocument(uri).then((textDocument) => {
return vscode.window.showTextDocument(textDocument).then(editor => {
let promises = testCases.map(([position, expected]) =>
provider.provideCompletionItemsInternal(editor.document, position, null, config).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let labels = items.map(x => x.label);
for (let entry of expected) {
assert.equal(labels.indexOf(entry) > -1, true, `missing expected item in completion list: ${entry} Actual: ${labels}`);
}
})
);
return Promise.all(promises).then(() => vscode.commands.executeCommand('workbench.action.closeActiveEditor'));
});
}, (err) => {
assert.ok(false, `error in OpenTextDocument ${err}`);
}).then(() => done(), done);
});
test('Test Completion on unimported packages (multiple)', (done) => {
let config = Object.create(vscode.workspace.getConfiguration('go'), {});
let provider = new GoCompletionItemProvider();
let position = new vscode.Position(3, 14);
let expectedItems = [
{
label: 'template (html/template)',
import: '\nimport (\n\t"html/template"\n)\n'
},
{
label: 'template (text/template)',
import: '\nimport (\n\t"text/template"\n)\n'
}
];
let uri = vscode.Uri.file(path.join(fixturePath, 'completions', 'unimportedMultiplePkgs.go'));
vscode.workspace.openTextDocument(uri).then((textDocument) => {
return vscode.window.showTextDocument(textDocument).then(editor => {
return provider.provideCompletionItemsInternal(editor.document, position, null, config).then(items => {
items = items instanceof vscode.CompletionList ? items.items : items;
let labels = items.map(x => x.label);
expectedItems.forEach(expectedItem => {
items = items instanceof vscode.CompletionList ? items.items : items;
const actualItem: vscode.CompletionItem = items.filter(item => item.label === expectedItem.label)[0];
if (!actualItem) {