File: integration_test.go

package info (click to toggle)
golang-golang-x-tools 1%3A0.25.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 22,724 kB
  • sloc: javascript: 2,027; asm: 1,645; sh: 166; yacc: 155; makefile: 49; ansic: 8
file content (1220 lines) | stat: -rw-r--r-- 29,096 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package cmdtest contains the test suite for the command line behavior of gopls.
package cmd_test

// This file defines integration tests of each gopls subcommand that
// fork+exec the command in a separate process.
//
// (Rather than execute 'go build gopls' during the test, we reproduce
// the main entrypoint in the test executable.)
//
// The purpose of this test is to exercise client-side logic such as
// argument parsing and formatting of LSP RPC responses, not server
// behavior; see lsp_test for that.
//
// All tests run in parallel.
//
// TODO(adonovan):
// - Use markers to represent positions in the input and in assertions.
// - Coverage of cross-cutting things like cwd, environ, span parsing, etc.
// - Subcommands that accept -write and -diff flags implement them
//   consistently; factor their tests.
// - Add missing test for 'vulncheck' subcommand.
// - Add tests for client-only commands: serve, bug, help, api-json, licenses.

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"testing"

	"golang.org/x/tools/gopls/internal/cmd"
	"golang.org/x/tools/gopls/internal/debug"
	"golang.org/x/tools/gopls/internal/protocol"
	"golang.org/x/tools/gopls/internal/util/bug"
	"golang.org/x/tools/gopls/internal/version"
	"golang.org/x/tools/internal/testenv"
	"golang.org/x/tools/internal/tool"
	"golang.org/x/tools/txtar"
)

// TestVersion tests the 'version' subcommand (../info.go).
func TestVersion(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, "")

	// There's not much we can robustly assert about the actual version.
	want := version.Version() // e.g. "master"

	// basic
	{
		res := gopls(t, tree, "version")
		res.checkExit(true)
		res.checkStdout(want)
	}

	// basic, with version override
	{
		res := goplsWithEnv(t, tree, []string{"TEST_GOPLS_VERSION=v1.2.3"}, "version")
		res.checkExit(true)
		res.checkStdout(`v1\.2\.3`)
	}

	// -json flag
	{
		res := gopls(t, tree, "version", "-json")
		res.checkExit(true)
		var v debug.ServerVersion
		if res.toJSON(&v) {
			if v.Version != want {
				t.Errorf("expected Version %q, got %q (%v)", want, v.Version, res)
			}
		}
	}
}

// TestCheck tests the 'check' subcommand (../check.go).
func TestCheck(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
import "fmt"
var _ = fmt.Sprintf("%s", 123)

-- b.go --
package a
import "fmt"
var _ = fmt.Sprintf("%d", "123")
-- c/c.go --
package c
var C int
-- c/c2.go --
package c
var C int
`)

	// no files
	{
		res := gopls(t, tree, "check")
		res.checkExit(true)
		if res.stdout != "" {
			t.Errorf("unexpected output: %v", res)
		}
	}

	// one file
	{
		res := gopls(t, tree, "check", "./a.go")
		res.checkExit(true)
		res.checkStdout("fmt.Sprintf format %s has arg 123 of wrong type int")
	}

	// two files
	{
		res := gopls(t, tree, "check", "./a.go", "./b.go")
		res.checkExit(true)
		res.checkStdout(`a.go:.* fmt.Sprintf format %s has arg 123 of wrong type int`)
		res.checkStdout(`b.go:.* fmt.Sprintf format %d has arg "123" of wrong type string`)
	}

	// diagnostic with related information spanning files
	{
		res := gopls(t, tree, "check", "./c/c2.go")
		res.checkExit(true)
		res.checkStdout(`c2.go:2:5-6: C redeclared in this block`)
		res.checkStdout(`c.go:2:5-6: - other declaration of C`)
	}
}

// TestCallHierarchy tests the 'call_hierarchy' subcommand (../call_hierarchy.go).
func TestCallHierarchy(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
func f() {}
func g() {
	f()
}
func h() {
	f()
	f()
}
`)
	// missing position
	{
		res := gopls(t, tree, "call_hierarchy")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// wrong place
	{
		res := gopls(t, tree, "call_hierarchy", "a.go:1")
		res.checkExit(false)
		res.checkStderr("identifier not found")
	}
	// f is called once from g and twice from h.
	{
		res := gopls(t, tree, "call_hierarchy", "a.go:2:6")
		res.checkExit(true)
		// We use regexp '.' as an OS-agnostic path separator.
		res.checkStdout("ranges 7:2-3, 8:2-3 in ..a.go from/to function h in ..a.go:6:6-7")
		res.checkStdout("ranges 4:2-3 in ..a.go from/to function g in ..a.go:3:6-7")
		res.checkStdout("identifier: function f in ..a.go:2:6-7")
	}
}

// TestCodeLens tests the 'codelens' subcommand (../codelens.go).
func TestCodeLens(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a/a.go --
package a
-- a/a_test.go --
package a_test
import "testing"
func TestPass(t *testing.T) {}
func TestFail(t *testing.T) { t.Fatal("fail") }
`)
	// missing position
	{
		res := gopls(t, tree, "codelens")
		res.checkExit(false)
		res.checkStderr("requires a file name")
	}
	// list code lenses
	{
		res := gopls(t, tree, "codelens", "./a/a_test.go")
		res.checkExit(true)
		res.checkStdout(`a_test.go:3: "run test" \[gopls.test\]`)
		res.checkStdout(`a_test.go:4: "run test" \[gopls.test\]`)
	}
	// no codelens with title/position
	{
		res := gopls(t, tree, "codelens", "-exec", "./a/a_test.go:1", "nope")
		res.checkExit(false)
		res.checkStderr(`no code lens at .* with title "nope"`)
	}
	// run the passing test
	{
		res := gopls(t, tree, "codelens", "-exec", "./a/a_test.go:3", "run test")
		res.checkExit(true)
		res.checkStderr(`PASS: TestPass`)         // from go test
		res.checkStderr("Info: all tests passed") // from gopls.test
	}
	// run the failing test
	{
		res := gopls(t, tree, "codelens", "-exec", "./a/a_test.go:4", "run test")
		res.checkExit(false)
		res.checkStderr(`FAIL	example.com/a`)
		res.checkStderr("Info: 1 / 1 tests failed")
	}
}

// TestDefinition tests the 'definition' subcommand (../definition.go).
func TestDefinition(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
import "fmt"
func f() {
	fmt.Println()
}
func g() {
	f()
}
`)
	// missing position
	{
		res := gopls(t, tree, "definition")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// intra-package
	{
		res := gopls(t, tree, "definition", "a.go:7:2") // "f()"
		res.checkExit(true)
		res.checkStdout("a.go:3:6-7: defined here as func f")
	}
	// cross-package
	{
		res := gopls(t, tree, "definition", "a.go:4:7") // "Println"
		res.checkExit(true)
		res.checkStdout("print.go.* defined here as func fmt.Println")
		res.checkStdout("Println formats using the default formats for its operands")
	}
	// -json and -markdown
	{
		res := gopls(t, tree, "definition", "-json", "-markdown", "a.go:4:7")
		res.checkExit(true)
		var defn cmd.Definition
		if res.toJSON(&defn) {
			if !strings.HasPrefix(defn.Description, "```go\nfunc fmt.Println") {
				t.Errorf("Description does not start with markdown code block. Got: %s", defn.Description)
			}
		}
	}
}

// TestExecute tests the 'execute' subcommand (../execute.go).
func TestExecute(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- hello.go --
package a
func main() {}

-- hello_test.go --
package a
import "testing"
func TestHello(t *testing.T) {
	t.Fatal("oops")
}
`)
	// missing command name
	{
		res := gopls(t, tree, "execute")
		res.checkExit(false)
		res.checkStderr("requires a command")
	}
	// bad command
	{
		res := gopls(t, tree, "execute", "gopls.foo")
		res.checkExit(false)
		res.checkStderr("unrecognized command: gopls.foo")
	}
	// too few arguments
	{
		res := gopls(t, tree, "execute", "gopls.run_tests")
		res.checkExit(false)
		res.checkStderr("expected 1 input arguments, got 0")
	}
	// too many arguments
	{
		res := gopls(t, tree, "execute", "gopls.run_tests", "null", "null")
		res.checkExit(false)
		res.checkStderr("expected 1 input arguments, got 2")
	}
	// argument is not JSON
	{
		res := gopls(t, tree, "execute", "gopls.run_tests", "hello")
		res.checkExit(false)
		res.checkStderr("argument 1 is not valid JSON: invalid character 'h'")
	}
	// add import, show diff
	hello := "file://" + filepath.ToSlash(tree) + "/hello.go"
	{
		res := gopls(t, tree, "execute", "-d", "gopls.add_import", `{"ImportPath": "fmt", "URI": "`+hello+`"}`)
		res.checkExit(true)
		res.checkStdout(`[+]import "fmt"`)
	}
	// list known packages (has a result)
	{
		res := gopls(t, tree, "execute", "gopls.list_known_packages", `{"URI": "`+hello+`"}`)
		res.checkExit(true)
		res.checkStdout(`"fmt"`)
		res.checkStdout(`"encoding/json"`)
	}
	// run tests
	{
		helloTest := "file://" + filepath.ToSlash(tree) + "/hello_test.go"
		res := gopls(t, tree, "execute", "gopls.run_tests", `{"URI": "`+helloTest+`", "Tests": ["TestHello"]}`)
		res.checkExit(false)
		res.checkStderr(`hello_test.go:4: oops`)
		res.checkStderr(`1 / 1 tests failed`)
	}
}

// TestFoldingRanges tests the 'folding_ranges' subcommand (../folding_range.go).
func TestFoldingRanges(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
func f(x int) {
	// hello
}
`)
	// missing filename
	{
		res := gopls(t, tree, "folding_ranges")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// success
	{
		res := gopls(t, tree, "folding_ranges", "a.go")
		res.checkExit(true)
		res.checkStdout("2:8-2:13") // params (x int)
		res.checkStdout("2:16-4:1") //   body { ... }
	}
}

// TestFormat tests the 'format' subcommand (../format.go).
func TestFormat(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- a.go --
package a ;  func f ( ) { }
`)
	const want = `package a

func f() {}
`

	// no files => nop
	{
		res := gopls(t, tree, "format")
		res.checkExit(true)
	}
	// default => print formatted result
	{
		res := gopls(t, tree, "format", "a.go")
		res.checkExit(true)
		if res.stdout != want {
			t.Errorf("format: got <<%s>>, want <<%s>>", res.stdout, want)
		}
	}
	// start/end position not supported (unless equal to start/end of file)
	{
		res := gopls(t, tree, "format", "a.go:1-2")
		res.checkExit(false)
		res.checkStderr("only full file formatting supported")
	}
	// -list: show only file names
	{
		res := gopls(t, tree, "format", "-list", "a.go")
		res.checkExit(true)
		res.checkStdout("a.go")
	}
	// -diff prints a unified diff
	{
		res := gopls(t, tree, "format", "-diff", "a.go")
		res.checkExit(true)
		// We omit the filenames as they vary by OS.
		want := `
-package a ;  func f ( ) { }
+package a
+
+func f() {}
`
		res.checkStdout(regexp.QuoteMeta(want))
	}
	// -write updates the file
	{
		res := gopls(t, tree, "format", "-write", "a.go")
		res.checkExit(true)
		res.checkStdout("^$") // empty
		checkContent(t, filepath.Join(tree, "a.go"), want)
	}
}

// TestHighlight tests the 'highlight' subcommand (../highlight.go).
func TestHighlight(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- a.go --
package a
import "fmt"
func f() {
	fmt.Println()
	fmt.Println()
}
`)

	// no arguments
	{
		res := gopls(t, tree, "highlight")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// all occurrences of Println
	{
		res := gopls(t, tree, "highlight", "a.go:4:7")
		res.checkExit(true)
		res.checkStdout("a.go:4:6-13")
		res.checkStdout("a.go:5:6-13")
	}
}

// TestImplementations tests the 'implementation' subcommand (../implementation.go).
func TestImplementations(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- a.go --
package a
import "fmt"
type T int
func (T) String() string { return "" }
`)

	// no arguments
	{
		res := gopls(t, tree, "implementation")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// T.String
	{
		res := gopls(t, tree, "implementation", "a.go:4:10")
		res.checkExit(true)
		// TODO(adonovan): extract and check the content of the reported ranges?
		// We use regexp '.' as an OS-agnostic path separator.
		res.checkStdout("fmt.print.go:")     // fmt.Stringer.String
		res.checkStdout("runtime.error.go:") // runtime.stringer.String
	}
}

// TestImports tests the 'imports' subcommand (../imports.go).
func TestImports(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- a.go --
package a
func _() {
	fmt.Println()
}
`)

	want := `
package a

import "fmt"
func _() {
	fmt.Println()
}
`[1:]

	// no arguments
	{
		res := gopls(t, tree, "imports")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// default: print with imports
	{
		res := gopls(t, tree, "imports", "a.go")
		res.checkExit(true)
		if res.stdout != want {
			t.Errorf("imports: got <<%s>>, want <<%s>>", res.stdout, want)
		}
	}
	// -diff: show a unified diff
	{
		res := gopls(t, tree, "imports", "-diff", "a.go")
		res.checkExit(true)
		res.checkStdout(regexp.QuoteMeta(`+import "fmt"`))
	}
	// -write: update file
	{
		res := gopls(t, tree, "imports", "-write", "a.go")
		res.checkExit(true)
		checkContent(t, filepath.Join(tree, "a.go"), want)
	}
}

// TestLinks tests the 'links' subcommand (../links.go).
func TestLinks(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- a.go --
// Link in package doc: https://pkg.go.dev/
package a

// Link in internal comment: https://go.dev/cl

// Doc comment link: https://blog.go.dev/
func f() {}
`)
	// no arguments
	{
		res := gopls(t, tree, "links")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// success
	{
		res := gopls(t, tree, "links", "a.go")
		res.checkExit(true)
		res.checkStdout("https://go.dev/cl")
		res.checkStdout("https://pkg.go.dev")
		res.checkStdout("https://blog.go.dev/")
	}
	// -json
	{
		res := gopls(t, tree, "links", "-json", "a.go")
		res.checkExit(true)
		res.checkStdout("https://pkg.go.dev")
		res.checkStdout("https://go.dev/cl")
		res.checkStdout("https://blog.go.dev/") // at 5:21-5:41
		var links []protocol.DocumentLink
		if res.toJSON(&links) {
			// Check just one of the three locations.
			if got, want := fmt.Sprint(links[2].Range), "5:21-5:41"; got != want {
				t.Errorf("wrong link location: got %v, want %v", got, want)
			}
		}
	}
}

// TestReferences tests the 'references' subcommand (../references.go).
func TestReferences(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
import "fmt"
func f() {
	fmt.Println()
}

-- b.go --
package a
import "fmt"
func g() {
	fmt.Println()
}
`)
	// no arguments
	{
		res := gopls(t, tree, "references")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// fmt.Println
	{
		res := gopls(t, tree, "references", "a.go:4:10")
		res.checkExit(true)
		res.checkStdout("a.go:4:6-13")
		res.checkStdout("b.go:4:6-13")
	}
}

// TestSignature tests the 'signature' subcommand (../signature.go).
func TestSignature(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
import "fmt"
func f() {
	fmt.Println(123)
}
`)
	// no arguments
	{
		res := gopls(t, tree, "signature")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// at 123 inside fmt.Println() call
	{
		res := gopls(t, tree, "signature", "a.go:4:15")
		res.checkExit(true)
		res.checkStdout("Println\\(a ...")
		res.checkStdout("Println formats using the default formats...")
	}
}

// TestPrepareRename tests the 'prepare_rename' subcommand (../prepare_rename.go).
func TestPrepareRename(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
func oldname() {}
`)
	// no arguments
	{
		res := gopls(t, tree, "prepare_rename")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// in 'package' keyword
	{
		res := gopls(t, tree, "prepare_rename", "a.go:1:3")
		res.checkExit(false)
		res.checkStderr("request is not valid at the given position")
	}
	// in 'package' identifier (not supported by client)
	{
		res := gopls(t, tree, "prepare_rename", "a.go:1:9")
		res.checkExit(false)
		res.checkStderr("can't rename package")
	}
	// in func oldname
	{
		res := gopls(t, tree, "prepare_rename", "a.go:2:9")
		res.checkExit(true)
		res.checkStdout("a.go:2:6-13") // all of "oldname"
	}
}

// TestRename tests the 'rename' subcommand (../rename.go).
func TestRename(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
func oldname() {}
`)
	// no arguments
	{
		res := gopls(t, tree, "rename")
		res.checkExit(false)
		res.checkStderr("expects 2 arguments")
	}
	// missing newname
	{
		res := gopls(t, tree, "rename", "a.go:1:3")
		res.checkExit(false)
		res.checkStderr("expects 2 arguments")
	}
	// in 'package' keyword
	{
		res := gopls(t, tree, "rename", "a.go:1:3", "newname")
		res.checkExit(false)
		res.checkStderr("no identifier found")
	}
	// in 'package' identifier
	{
		res := gopls(t, tree, "rename", "a.go:1:9", "newname")
		res.checkExit(false)
		res.checkStderr(`cannot rename package: module path .* same as the package path, so .* no effect`)
	}
	// success, func oldname (and -diff)
	{
		res := gopls(t, tree, "rename", "-diff", "a.go:2:9", "newname")
		res.checkExit(true)
		res.checkStdout(regexp.QuoteMeta("-func oldname() {}"))
		res.checkStdout(regexp.QuoteMeta("+func newname() {}"))
	}
}

// TestSymbols tests the 'symbols' subcommand (../symbols.go).
func TestSymbols(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
func f()
var v int
const c = 0
`)
	// no files
	{
		res := gopls(t, tree, "symbols")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// success
	{
		res := gopls(t, tree, "symbols", "a.go:123:456") // (line/col ignored)
		res.checkExit(true)
		res.checkStdout("f Function 2:6-2:7")
		res.checkStdout("v Variable 3:5-3:6")
		res.checkStdout("c Constant 4:7-4:8")
	}
}

// TestSemtok tests the 'semtok' subcommand (../semantictokens.go).
func TestSemtok(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
func f()
var v int
const c = 0
`)
	// no files
	{
		res := gopls(t, tree, "semtok")
		res.checkExit(false)
		res.checkStderr("expected one file name")
	}
	// success
	{
		res := gopls(t, tree, "semtok", "a.go")
		res.checkExit(true)
		got := res.stdout
		want := `
/*⇒7,keyword,[]*/package /*⇒1,namespace,[]*/a
/*⇒4,keyword,[]*/func /*⇒1,function,[definition]*/f()
/*⇒3,keyword,[]*/var /*⇒1,variable,[definition]*/v /*⇒3,type,[defaultLibrary number]*/int
/*⇒5,keyword,[]*/const /*⇒1,variable,[definition readonly]*/c = /*⇒1,number,[]*/0
`[1:]
		if got != want {
			t.Errorf("semtok: got <<%s>>, want <<%s>>", got, want)
		}
	}
}

func TestStats(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
-- b/b.go --
package b
-- testdata/foo.go --
package foo
`)

	// Trigger a bug report with a distinctive string
	// and check that it was durably recorded.
	oops := fmt.Sprintf("oops-%d", rand.Int())
	{
		env := []string{"TEST_GOPLS_BUG=" + oops}
		res := goplsWithEnv(t, tree, env, "bug")
		res.checkExit(true)
	}

	res := gopls(t, tree, "stats")
	res.checkExit(true)

	var stats cmd.GoplsStats
	if err := json.Unmarshal([]byte(res.stdout), &stats); err != nil {
		t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
	}

	// a few sanity checks
	checks := []struct {
		field string
		got   int
		want  int
	}{
		{
			"WorkspaceStats.Views[0].WorkspaceModules",
			stats.WorkspaceStats.Views[0].WorkspacePackages.Modules,
			1,
		},
		{
			"WorkspaceStats.Views[0].WorkspacePackages",
			stats.WorkspaceStats.Views[0].WorkspacePackages.Packages,
			2,
		},
		{"DirStats.Files", stats.DirStats.Files, 4},
		{"DirStats.GoFiles", stats.DirStats.GoFiles, 2},
		{"DirStats.ModFiles", stats.DirStats.ModFiles, 1},
		{"DirStats.TestdataFiles", stats.DirStats.TestdataFiles, 1},
	}
	for _, check := range checks {
		if check.got != check.want {
			t.Errorf("stats.%s = %d, want %d", check.field, check.got, check.want)
		}
	}

	// Check that we got a BugReport with the expected message.
	{
		got := fmt.Sprint(stats.BugReports)
		wants := []string{
			"cmd/info.go", // File containing call to bug.Report
			oops,          // Description
		}
		for _, want := range wants {
			if !strings.Contains(got, want) {
				t.Errorf("BugReports does not contain %q. Got:<<%s>>", want, got)
				break
			}
		}
	}

	// Check that -anon suppresses fields containing user information.
	{
		res2 := gopls(t, tree, "stats", "-anon")
		res2.checkExit(true)

		var stats2 cmd.GoplsStats
		if err := json.Unmarshal([]byte(res2.stdout), &stats2); err != nil {
			t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
		}
		if got := len(stats2.BugReports); got > 0 {
			t.Errorf("Got %d bug reports with -anon, want 0. Reports:%+v", got, stats2.BugReports)
		}
		var stats2AsMap map[string]any
		if err := json.Unmarshal([]byte(res2.stdout), &stats2AsMap); err != nil {
			t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
		}
		// GOPACKAGESDRIVER is user information, but is ok to print zero value.
		if v, ok := stats2AsMap["GOPACKAGESDRIVER"]; ok && v != "" {
			t.Errorf(`Got GOPACKAGESDRIVER=(%v, %v); want ("", true(found))`, v, ok)
		}
	}

	// Check that -anon suppresses fields containing non-zero user information.
	{
		res3 := goplsWithEnv(t, tree, []string{"GOPACKAGESDRIVER=off"}, "stats", "-anon")
		res3.checkExit(true)

		var statsAsMap3 map[string]interface{}
		if err := json.Unmarshal([]byte(res3.stdout), &statsAsMap3); err != nil {
			t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
		}
		// GOPACKAGESDRIVER is user information, want non-empty value to be omitted.
		if v, ok := statsAsMap3["GOPACKAGESDRIVER"]; ok {
			t.Errorf(`Got GOPACKAGESDRIVER=(%q, %v); want ("", false(not found))`, v, ok)
		}
	}
}

// TestCodeAction tests the 'codeaction' subcommand (../codeaction.go).
func TestCodeAction(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
type T int
func f() (int, string) { return }

-- b.go --
package a
import "io"
var _ io.Reader = C{}
type C struct{}
`)

	// no arguments
	{
		res := gopls(t, tree, "codeaction")
		res.checkExit(false)
		res.checkStderr("expects at least 1 argument")
	}
	// list code actions in file
	{
		res := gopls(t, tree, "codeaction", "a.go")
		res.checkExit(true)
		res.checkStdout(`edit	"Fill in return values" \[quickfix\]`)
		res.checkStdout(`command	"Browse documentation for package a" \[source.doc\]`)
	}
	// list code actions in file, filtering by title
	{
		res := gopls(t, tree, "codeaction", "-title=Browse.*doc", "a.go")
		res.checkExit(true)
		got := res.stdout
		want := `command	"Browse gopls feature documentation" [gopls.doc.features]` +
			"\n" +
			`command	"Browse documentation for package a" [source.doc]` +
			"\n"
		if got != want {
			t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
		}
	}
	// list code actions at position (of io.Reader)
	{
		res := gopls(t, tree, "codeaction", "b.go:#31")
		res.checkExit(true)
		res.checkStdout(`command	"Browse documentation for type io.Reader" \[source.doc]`)
	}
	// list quick fixes at position (of type T)
	{
		res := gopls(t, tree, "codeaction", "-kind=quickfix", "a.go:#15")
		res.checkExit(true)
		got := res.stdout
		want := `edit	"Fill in return values" [quickfix]` + "\n"
		if got != want {
			t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
		}
	}
	// success, with explicit CodeAction kind and diagnostics span.
	{
		res := gopls(t, tree, "codeaction", "-kind=quickfix", "-exec", "b.go:#40")
		res.checkExit(true)
		got := res.stdout
		want := `
package a

import "io"

var _ io.Reader = C{}

type C struct{}

// Read implements io.Reader.
func (c C) Read(p []byte) (n int, err error) {
	panic("unimplemented")
}
`[1:]
		if got != want {
			t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
		}
	}
}

// TestWorkspaceSymbol tests the 'workspace_symbol' subcommand (../workspace_symbol.go).
func TestWorkspaceSymbol(t *testing.T) {
	t.Parallel()

	tree := writeTree(t, `
-- go.mod --
module example.com
go 1.18

-- a.go --
package a
func someFunctionName()
`)
	// no files
	{
		res := gopls(t, tree, "workspace_symbol")
		res.checkExit(false)
		res.checkStderr("expects 1 argument")
	}
	// success
	{
		res := gopls(t, tree, "workspace_symbol", "meFun")
		res.checkExit(true)
		res.checkStdout("a.go:2:6-22 someFunctionName Function")
	}
}

// -- test framework --

func TestMain(m *testing.M) {
	switch os.Getenv("ENTRYPOINT") {
	case "goplsMain":
		goplsMain()
	default:
		os.Exit(m.Run())
	}
}

// This function is a stand-in for gopls.main in ../../../../main.go.
func goplsMain() {
	// Panic on bugs (unlike the production gopls command),
	// except in tests that inject calls to bug.Report.
	if os.Getenv("TEST_GOPLS_BUG") == "" {
		bug.PanicOnBugs = true
	}

	if v := os.Getenv("TEST_GOPLS_VERSION"); v != "" {
		version.VersionOverride = v
	}

	tool.Main(context.Background(), cmd.New(), os.Args[1:])
}

// writeTree extracts a txtar archive into a new directory and returns its path.
func writeTree(t *testing.T, archive string) string {
	root := t.TempDir()

	// This unfortunate step is required because gopls output
	// expands symbolic links in its input file names (arguably it
	// should not), and on macOS the temp dir is in /var -> private/var.
	root, err := filepath.EvalSymlinks(root)
	if err != nil {
		t.Fatal(err)
	}

	for _, f := range txtar.Parse([]byte(archive)).Files {
		filename := filepath.Join(root, f.Name)
		if err := os.MkdirAll(filepath.Dir(filename), 0777); err != nil {
			t.Fatal(err)
		}
		if err := os.WriteFile(filename, f.Data, 0666); err != nil {
			t.Fatal(err)
		}
	}
	return root
}

// gopls executes gopls in a child process.
func gopls(t *testing.T, dir string, args ...string) *result {
	return goplsWithEnv(t, dir, nil, args...)
}

func goplsWithEnv(t *testing.T, dir string, env []string, args ...string) *result {
	testenv.NeedsTool(t, "go")

	// Catch inadvertent use of dir=".", which would make
	// the ReplaceAll below unpredictable.
	if !filepath.IsAbs(dir) {
		t.Fatalf("dir is not absolute: %s", dir)
	}

	goplsCmd := exec.Command(os.Args[0], args...)
	goplsCmd.Env = append(os.Environ(), "ENTRYPOINT=goplsMain")
	goplsCmd.Env = append(goplsCmd.Env, "GOPACKAGESDRIVER=off")
	goplsCmd.Env = append(goplsCmd.Env, env...)
	goplsCmd.Dir = dir
	goplsCmd.Stdout = new(bytes.Buffer)
	goplsCmd.Stderr = new(bytes.Buffer)

	cmdErr := goplsCmd.Run()

	stdout := strings.ReplaceAll(fmt.Sprint(goplsCmd.Stdout), dir, ".")
	stderr := strings.ReplaceAll(fmt.Sprint(goplsCmd.Stderr), dir, ".")
	exitcode := 0
	if cmdErr != nil {
		if exitErr, ok := cmdErr.(*exec.ExitError); ok {
			exitcode = exitErr.ExitCode()
		} else {
			stderr = cmdErr.Error() // (execve failure)
			exitcode = -1
		}
	}
	res := &result{
		t:        t,
		command:  "gopls " + strings.Join(args, " "),
		exitcode: exitcode,
		stdout:   stdout,
		stderr:   stderr,
	}
	if false {
		t.Log(res)
	}
	return res
}

// A result holds the result of a gopls invocation, and provides assertion helpers.
type result struct {
	t              *testing.T
	command        string
	exitcode       int
	stdout, stderr string
}

func (res *result) String() string {
	return fmt.Sprintf("%s: exit=%d stdout=<<%s>> stderr=<<%s>>",
		res.command, res.exitcode, res.stdout, res.stderr)
}

// checkExit asserts that gopls returned the expected exit code.
func (res *result) checkExit(success bool) {
	res.t.Helper()
	if (res.exitcode == 0) != success {
		res.t.Errorf("%s: exited with code %d, want success: %t (%s)",
			res.command, res.exitcode, success, res)
	}
}

// checkStdout asserts that the gopls standard output matches the pattern.
func (res *result) checkStdout(pattern string) {
	res.t.Helper()
	res.checkOutput(pattern, "stdout", res.stdout)
}

// checkStderr asserts that the gopls standard error matches the pattern.
func (res *result) checkStderr(pattern string) {
	res.t.Helper()
	res.checkOutput(pattern, "stderr", res.stderr)
}

func (res *result) checkOutput(pattern, name, content string) {
	res.t.Helper()
	if match, err := regexp.MatchString(pattern, content); err != nil {
		res.t.Errorf("invalid regexp: %v", err)
	} else if !match {
		res.t.Errorf("%s: %s does not match [%s]; got <<%s>>",
			res.command, name, pattern, content)
	}
}

// toJSON decodes res.stdout as JSON into to *ptr and reports its success.
func (res *result) toJSON(ptr interface{}) bool {
	if err := json.Unmarshal([]byte(res.stdout), ptr); err != nil {
		res.t.Errorf("invalid JSON %v", err)
		return false
	}
	return true
}

// checkContent checks that the contents of the file are as expected.
func checkContent(t *testing.T, filename, want string) {
	data, err := os.ReadFile(filename)
	if err != nil {
		t.Error(err)
		return
	}
	if got := string(data); got != want {
		t.Errorf("content of %s is <<%s>>, want <<%s>>", filename, got, want)
	}
}