Debian Codegraph @

stack/stack_test.go

raw
1 // Copyright 2015 Marc-Antoine Ruel. All rights reserved.
2 // Use of this source code is governed under the Apache License, Version 2.0
3 // that can be found in the LICENSE file.
4
5 package stack
6
7 import (
8 "flag"
9 "fmt"
10 "io"
11 "log"
12 "os"
13 "runtime"
14 "strings"
15 "testing"
16
17 "github.com/google/go-cmp/cmp"
18 )
19
20 func TestFuncInit(t *testing.T) {
21 t.Parallel()
22 data := []struct {
23 raw string
24 want Func
25 }{
26 {
27 "github.com/maruel/panicparse/cmd/panic/internal/%c3%b9tf8.(*Strùct).Pànic",
28 Func{
29 Complete: "github.com/maruel/panicparse/cmd/panic/internal/ùtf8.(*Strùct).Pànic",
30 ImportPath: "github.com/maruel/panicparse/cmd/panic/internal/ùtf8",
31 DirName: "ùtf8",
32 Name: "(*Strùct).Pànic",
33 IsExported: true,
34 },
35 },
36 {
37 "gopkg.in/yaml%2ev2.handleErr",
38 Func{
39 Complete: "gopkg.in/yaml.v2.handleErr",
40 ImportPath: "gopkg.in/yaml.v2",
41 DirName: "yaml.v2",
42 Name: "handleErr",
43 },
44 },
45 {
46 "github.com/maruel/panicparse/vendor/golang.org/x/sys/unix.Nanosleep",
47 Func{
48 Complete: "github.com/maruel/panicparse/vendor/golang.org/x/sys/unix.Nanosleep",
49 ImportPath: "github.com/maruel/panicparse/vendor/golang.org/x/sys/unix",
50 DirName: "unix",
51 Name: "Nanosleep",
52 IsExported: true,
53 },
54 },
55 {
56 "main.func·001",
57 Func{
58 Complete: "main.func·001",
59 ImportPath: "main",
60 DirName: "main",
61 Name: "func·001",
62 IsPkgMain: true,
63 },
64 },
65 {
66 "gc",
67 Func{
68 Complete: "gc",
69 Name: "gc",
70 },
71 },
72 }
73 for _, line := range data {
74 got := newFunc(line.raw)
75 if diff := cmp.Diff(line.want, got); diff != "" {
76 t.Fatalf("Call mismatch (-want +got):\n%s", diff)
77 }
78 }
79 }
80
81 func TestCallPkg(t *testing.T) {
82 t.Parallel()
83 data := []struct {
84 name string
85 f string
86 s string
87 // Expectations
88 DirSrc string
89 SrcName string
90 LocalSrcPath string
91 RelSrcPath string
92 ImportPath string
93 Location Location
94 }{
95 {
96 name: "Pkg",
97 f: "gopkg.in/yaml%2ev2.handleErr",
98 s: "/gpremote/src/gopkg.in/yaml.v2/yaml.go",
99 DirSrc: pathJoin("yaml.v2", "yaml.go"),
100 SrcName: "yaml.go",
101 LocalSrcPath: "/gplocal/src/gopkg.in/yaml.v2/yaml.go",
102 RelSrcPath: "gopkg.in/yaml.v2/yaml.go",
103 ImportPath: "gopkg.in/yaml.v2",
104 Location: GOPATH,
105 },
106 {
107 name: "PkgMod",
108 f: "gopkg.in/yaml%2ev2.handleErr",
109 s: "/gpremote/pkg/mod/gopkg.in/[email protected]/yaml.go",
110 DirSrc: pathJoin("[email protected]", "yaml.go"),
111 SrcName: "yaml.go",
112 LocalSrcPath: "/gplocal/pkg/mod/gopkg.in/[email protected]/yaml.go",
113 RelSrcPath: "gopkg.in/[email protected]/yaml.go",
114 ImportPath: "gopkg.in/[email protected]",
115 Location: GoPkg,
116 },
117 {
118 name: "PkgMethod",
119 f: "gopkg.in/yaml%2ev2.(*decoder).unmarshal",
120 s: "/gpremote/src/gopkg.in/yaml.v2/yaml.go",
121 DirSrc: pathJoin("yaml.v2", "yaml.go"),
122 SrcName: "yaml.go",
123 LocalSrcPath: "/gplocal/src/gopkg.in/yaml.v2/yaml.go",
124 RelSrcPath: "gopkg.in/yaml.v2/yaml.go",
125 ImportPath: "gopkg.in/yaml.v2",
126 Location: GOPATH,
127 },
128 {
129 name: "Stdlib",
130 f: "reflect.Value.assignTo",
131 s: "/grremote/src/reflect/value.go",
132 DirSrc: pathJoin("reflect", "value.go"),
133 SrcName: "value.go",
134 LocalSrcPath: "/grlocal/src/reflect/value.go",
135 RelSrcPath: "reflect/value.go",
136 ImportPath: "reflect",
137 Location: Stdlib,
138 },
139 {
140 name: "Main",
141 f: "main.main",
142 s: "/gpremote/src/github.com/maruel/panicparse/cmd/pp/main.go",
143 DirSrc: pathJoin("pp", "main.go"),
144 SrcName: "main.go",
145 LocalSrcPath: "/gplocal/src/github.com/maruel/panicparse/cmd/pp/main.go",
146 RelSrcPath: "github.com/maruel/panicparse/cmd/pp/main.go",
147 ImportPath: "github.com/maruel/panicparse/cmd/pp",
148 Location: GOPATH,
149 },
150 {
151 // See testPanicMismatched in context_test.go.
152 name: "Mismatched",
153 f: "github.com/maruel/panicparse/cmd/panic/internal/incorrect.Panic",
154 s: "/gpremote/src/github.com/maruel/panicparse/cmd/panic/internal/incorrect/correct.go",
155 DirSrc: pathJoin("incorrect", "correct.go"),
156 SrcName: "correct.go",
157 LocalSrcPath: "/gplocal/src/github.com/maruel/panicparse/cmd/panic/internal/incorrect/correct.go",
158 RelSrcPath: "github.com/maruel/panicparse/cmd/panic/internal/incorrect/correct.go",
159 ImportPath: "github.com/maruel/panicparse/cmd/panic/internal/incorrect",
160 Location: GOPATH,
161 },
162 {
163 // See testPanicUTF8 in context_test.go.
164 name: "UTF8",
165 f: "github.com/maruel/panicparse/cmd/panic/internal/%c3%b9tf8.(*Strùct).Pànic",
166 s: "/gpremote/src/github.com/maruel/panicparse/cmd/panic/internal/ùtf8/utf8.go",
167 DirSrc: pathJoin("ùtf8", "utf8.go"),
168 SrcName: "utf8.go",
169 LocalSrcPath: "/gplocal/src/github.com/maruel/panicparse/cmd/panic/internal/ùtf8/utf8.go",
170 RelSrcPath: "github.com/maruel/panicparse/cmd/panic/internal/ùtf8/utf8.go",
171 ImportPath: "github.com/maruel/panicparse/cmd/panic/internal/ùtf8",
172 Location: GOPATH,
173 },
174 {
175 name: "C",
176 f: "findrunnable",
177 s: "/grremote/src/runtime/proc.c",
178 DirSrc: pathJoin("runtime", "proc.c"),
179 SrcName: "proc.c",
180 LocalSrcPath: "/grlocal/src/runtime/proc.c",
181 RelSrcPath: "runtime/proc.c",
182 ImportPath: "runtime",
183 Location: Stdlib,
184 },
185 {
186 name: "Gomod",
187 f: "example.com/foo/bar.Func",
188 s: "/gomod/bar/baz.go",
189 DirSrc: "bar/baz.go",
190 SrcName: "baz.go",
191 LocalSrcPath: "/gomod/bar/baz.go",
192 RelSrcPath: "bar/baz.go",
193 ImportPath: "example.com/foo/bar",
194 Location: GoMod,
195 },
196 {
197 name: "GomodMain",
198 f: "main.main",
199 s: "/gomod/cmd/panic/main.go",
200 DirSrc: "panic/main.go",
201 SrcName: "main.go",
202 LocalSrcPath: "/gomod/cmd/panic/main.go",
203 RelSrcPath: "cmd/panic/main.go",
204 ImportPath: "example.com/foo/cmd/panic",
205 Location: GoMod,
206 },
207 }
208 for i, line := range data {
209 line := line
210 t.Run(fmt.Sprintf("%d-%s", i, line.name), func(t *testing.T) {
211 t.Parallel()
212 c := newCall(line.f, Args{}, line.s, 153)
213 compareString(t, line.DirSrc, c.DirSrc)
214 compareString(t, line.SrcName, c.SrcName)
215 // Equivalent of calling GuessPaths().
216 gp := map[string]string{"/gpremote": "/gplocal"}
217 gm := map[string]string{"/gomod": "example.com/foo"}
218 if !c.updateLocations("/grremote", "/grlocal", gm, gp) {
219 t.Error("Unexpected")
220 }
221 compareString(t, line.ImportPath, c.ImportPath)
222 if line.Location != c.Location {
223 t.Errorf("want %s, got %s", line.Location, c.Location)
224 }
225 compareString(t, line.LocalSrcPath, c.LocalSrcPath)
226 compareString(t, line.RelSrcPath, c.RelSrcPath)
227 })
228 }
229 }
230
231 func TestArgs(t *testing.T) {
232 t.Parallel()
233 a := Args{
234 Values: []Arg{
235 {Value: 0x4},
236 {Value: 0x7fff671c7118},
237 {Value: 0xffffffff00000080},
238 {},
239 {Value: 0xffffffff0028c1be},
240 {Name: "foo"},
241 {},
242 {},
243 {IsOffsetTooLarge: true},
244 {IsAggregate: true},
245 {IsAggregate: true, Fields: Args{
246 Values: []Arg{{IsAggregate: true, Fields: Args{
247 Values: []Arg{{IsAggregate: true}},
248 }}},
249 }},
250 {IsAggregate: true, Fields: Args{
251 Values: []Arg{{Value: 0x1}, {Value: 0x7fff671c7118}},
252 }},
253 {IsAggregate: true, Fields: Args{
254 Values: []Arg{{IsAggregate: true, Fields: Args{
255 Values: []Arg{{Value: 0x5}}, Elided: true,
256 }}},
257 }},
258 {IsAggregate: true, Fields: Args{Elided: true}},
259 {IsAggregate: true, Fields: Args{
260 Values: []Arg{{IsAggregate: true, Fields: Args{
261 Values: []Arg{{IsOffsetTooLarge: true}, {IsOffsetTooLarge: true}},
262 }}},
263 }},
264 },
265 Elided: true,
266 }
267 compareString(t, "4, 0x7fff671c7118, 0xffffffff00000080, 0, 0xffffffff0028c1be, foo, "+
268 "0, 0, _, {}, {{{}}}, {1, 0x7fff671c7118}, {{5, ...}}, {...}, {{_, _}}, ...", a.String())
269
270 a = Args{Processed: []string{"yo"}}
271 compareString(t, "yo", a.String())
272 }
273
274 func TestSignature(t *testing.T) {
275 t.Parallel()
276 s := getSignature()
277 compareString(t, "", s.SleepString())
278 s.SleepMax = 10
279 compareString(t, "0~10 minutes", s.SleepString())
280 s.SleepMin = 10
281 compareString(t, "10 minutes", s.SleepString())
282 }
283
284 func TestSignature_Equal(t *testing.T) {
285 t.Parallel()
286 s1 := getSignature()
287 s2 := getSignature()
288 if !s1.equal(s2) {
289 t.Fatal("equal")
290 }
291 s2.State = "foo"
292 if s1.equal(s2) {
293 t.Fatal("inequal")
294 }
295 }
296
297 func TestSignature_Similar(t *testing.T) {
298 t.Parallel()
299 s1 := getSignature()
300 s2 := getSignature()
301 if !s1.similar(s2, ExactFlags) {
302 t.Fatal("equal")
303 }
304 s2.State = "foo"
305 if s1.similar(s2, ExactFlags) {
306 t.Fatal("inequal")
307 }
308 }
309
310 func TestSignature_Less(t *testing.T) {
311 t.Parallel()
312 s1 := getSignature()
313 s2 := getSignature()
314 if s1.less(s2) || s2.less(s1) {
315 t.Fatal("less")
316 }
317 s2.State = "foo"
318 if !s1.less(s2) || s2.less(s1) {
319 t.Fatal("not less")
320 }
321 s2 = getSignature()
322 s2.Stack.Calls = s2.Stack.Calls[:1]
323 if !s1.less(s2) || s2.less(s1) {
324 t.Fatal("not less")
325 }
326 }
327
328 //
329
330 var (
331 goroot string
332 gopaths map[string]string
333 gopath string
334 gomods map[string]string
335 isInGOPATH bool
336 )
337
338 func init() {
339 goroot = strings.Replace(runtime.GOROOT(), "\\", "/", -1)
340 gopaths = map[string]string{}
341 for i, p := range getGOPATHs() {
342 gopaths[p] = p
343 if i == 0 {
344 gopath = p
345 }
346 }
347
348 // Assumes pwd == this directory.
349 pwd, err := os.Getwd()
350 if err != nil {
351 panic(err)
352 }
353 // Our internal functions work with '/' as path separator.
354 pwd = strings.Replace(pwd, "\\", "/", -1)
355 gomods = map[string]string{}
356 gmc := gomodCache{}
357 if prefix, path := gmc.isGoModule(splitPath(pwd)); prefix != "" {
358 gomods[prefix] = path
359 }
360
361 // When inside GOPATH, no version is added. When outside, the version path is
362 // added from the reading of module statement in go.mod.
363 for _, p := range getGOPATHs() {
364 if strings.HasPrefix(pwd, p) {
365 isInGOPATH = true
366 break
367 }
368 }
369 }
370
371 func newFunc(s string) Func {
372 f := Func{}
373 if s != "" {
374 if err := f.Init(s); err != nil {
375 panic(err)
376 }
377 }
378 return f
379 }
380
381 func newCall(f string, a Args, s string, l int) Call {
382 c := Call{Func: newFunc(f), Args: a}
383 c.init(s, l)
384 return c
385 }
386
387 func newCallLocal(f string, a Args, s string, l int) Call {
388 c := newCall(f, a, s, l)
389 r := c.updateLocations(goroot, goroot, gomods, gopaths)
390 if !r {
391 panic("Unexpected")
392 }
393 if c.LocalSrcPath == "" || c.RelSrcPath == "" {
394 panic(fmt.Sprintf("newCallLocal(%q, %q): invariant failed; gomods=%v, GOPATHs=%v", f, s, gomods, gopaths))
395 }
396 return c
397 }
398
399 func compareErr(t *testing.T, want, got error) {
400 if want == nil && got == nil {
401 return
402 }
403 if want == nil || got == nil {
404 t.Helper()
405 t.Errorf("want: %v, got: %v", want, got)
406 } else if want.Error() != got.Error() {
407 t.Helper()
408 t.Errorf("want: %q, got: %q", want.Error(), got.Error())
409 }
410 }
411
412 func compareString(t *testing.T, want, got string) {
413 if want != got {
414 t.Helper()
415 t.Fatalf("%q != %q", want, got)
416 }
417 }
418
419 // similarGoroutines compares slice of Goroutine to be similar enough.
420 //
421 // Warning: it mutates inputs.
422 func similarGoroutines(t *testing.T, want, got []*Goroutine) {
423 zapGoroutines(t, want, got)
424 if diff := cmp.Diff(want, got); diff != "" {
425 t.Helper()
426 t.Fatalf("Goroutine mismatch (-want +got):\n%s", diff)
427 }
428 }
429
430 func zapGoroutines(t *testing.T, want, got []*Goroutine) {
431 if len(want) != len(got) {
432 t.Helper()
433 t.Error("different []*Goroutine length")
434 return
435 }
436 for i := range want {
437 // &(*Goroutine).Signature
438 zapSignatures(t, &want[i].Signature, &got[i].Signature)
439 }
440 }
441
442 // similarSignatures compares Signature to be similar enough.
443 //
444 // Warning: it mutates inputs.
445 func similarSignatures(t *testing.T, want, got *Signature) {
446 zapSignatures(t, want, got)
447 if diff := cmp.Diff(want, got); diff != "" {
448 t.Helper()
449 t.Fatalf("Signature mismatch (-want +got):\n%s", diff)
450 }
451 }
452
453 func zapSignatures(t *testing.T, want, got *Signature) {
454 // Signature.Stack.([]Call)
455 t.Helper()
456 if len(want.Stack.Calls) != len(got.Stack.Calls) {
457 t.Error("different call length")
458 return
459 }
460 if len(want.CreatedBy.Calls) != 0 && len(got.CreatedBy.Calls) != 0 {
461 if want.CreatedBy.Calls[0].Line != 0 && got.CreatedBy.Calls[0].Line != 0 {
462 want.CreatedBy.Calls[0].Line = 42
463 got.CreatedBy.Calls[0].Line = 42
464 }
465 }
466 zapStacks(t, &want.Stack, &got.Stack)
467 }
468
469 func zapStacks(t *testing.T, want, got *Stack) {
470 if len(want.Calls) != len(got.Calls) {
471 t.Helper()
472 t.Error("different Stack.[]Call length")
473 return
474 }
475 if len(want.Calls) != 0 {
476 t.Helper()
477 }
478 for i := range want.Calls {
479 zapCalls(t, &want.Calls[i], &got.Calls[i])
480 }
481 }
482
483 func zapCalls(t *testing.T, want, got *Call) {
484 t.Helper()
485 if want.Line != 0 && got.Line != 0 {
486 want.Line = 42
487 got.Line = 42
488 }
489 zapArgs(t, &want.Args, &got.Args)
490 }
491
492 func zapArgs(t *testing.T, want, got *Args) {
493 if len(want.Values) != len(got.Values) {
494 t.Helper()
495 t.Error("different Args.Values length")
496 return
497 }
498 if len(want.Values) != 0 {
499 t.Helper()
500 }
501 for i := range want.Values {
502 if want.Values[i].Value != 0 && got.Values[i].Value != 0 {
503 want.Values[i].Value = 42
504 got.Values[i].Value = 42
505 }
506 if want.Values[i].IsAggregate && got.Values[i].IsAggregate {
507 zapArgs(t, &want.Values[i].Fields, &got.Values[i].Fields)
508 }
509 if want.Values[i].Name != "" && got.Values[i].Name != "" {
510 want.Values[i].Name = "foo"
511 got.Values[i].Name = "foo"
512 }
513 if want.Values[i].IsInaccurate && !got.Values[i].IsInaccurate {
514 want.Values[i].IsInaccurate = false
515 }
516 }
517 }
518
519 func compareGoroutines(t *testing.T, want, got []*Goroutine) {
520 if diff := cmp.Diff(want, got); diff != "" {
521 t.Helper()
522 t.Fatalf("Goroutine mismatch (-want +got):\n%s", diff)
523 }
524 }
525
526 func compareStacks(t *testing.T, want, got *Stack) {
527 if diff := cmp.Diff(want, got); diff != "" {
528 t.Helper()
529 t.Fatalf("Stack mismatch (-want +got):\n%s", diff)
530 }
531 }
532
533 func getSignature() *Signature {
534 return &Signature{
535 State: "chan receive",
536 Stack: Stack{
537 Calls: []Call{
538 {
539 Func: newFunc("main.func·001"),
540 Args: Args{Values: []Arg{{Value: 0x11000000}, {Value: 2}}},
541 RemoteSrcPath: "/gopath/src/github.com/maruel/panicparse/stack/stack.go",
542 Line: 72,
543 },
544 {
545 Func: newFunc("sliceInternal"),
546 Args: Args{Values: []Arg{{Value: 0x11000000}, {Value: 2}}},
547 RemoteSrcPath: "/golang/src/sort/slices.go",
548 Line: 72,
549 Location: Stdlib,
550 },
551 {
552 Func: newFunc("Slice"),
553 Args: Args{Values: []Arg{{Value: 0x11000000}, {Value: 2}}},
554 RemoteSrcPath: "/golang/src/sort/slices.go",
555 Line: 72,
556 Location: Stdlib,
557 },
558 {
559 Func: newFunc("DoStuff"),
560 Args: Args{Values: []Arg{{Value: 0x11000000}, {Value: 2}}},
561 RemoteSrcPath: "/gopath/src/foo/bar.go",
562 Line: 72,
563 },
564 {
565 Func: newFunc("doStuffInternal"),
566 Args: Args{
567 Values: []Arg{{Value: 0x11000000}, {Value: 2}},
568 Elided: true,
569 },
570 RemoteSrcPath: "/gopath/src/foo/bar.go",
571 Line: 72,
572 },
573 },
574 },
575 }
576 }
577
578 // TestMain manages a temporary directory to build on first use ../cmd/panic
579 // and clean up at the end.
580 func TestMain(m *testing.M) {
581 flag.Parse()
582 if !testing.Verbose() {
583 log.SetOutput(io.Discard)
584 }
585 os.Exit(m.Run())
586 }