internal/codescan/codescan_test.go
71 lines · 2767 bytes
1package codescan
2
3import (
4 "strconv"
5 "strings"
6 "testing"
7)
8
9func TestParse(t *testing.T) {
10 raw := []byte(`{"version":"2.1.0","runs":[
11 {"tool":{"driver":{"name":"opengrep"}},"results":[
12 {"ruleId":"r1","message":{"text":"first\nline"},
13 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///workspace/a/b.go"},"region":{"startLine":3}}}]},
14 {"ruleId":"r1","message":{"text":"first\nline"},
15 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"./a/b.go"},"region":{"startLine":3}}}]},
16 {"ruleId":"r2","level":"note","message":{"text":"second"},
17 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"a/a.go"},"region":{"startLine":9}}}]}
18 ]},
19 {"tool":{"driver":{"name":"other"}},"results":[{"ruleId":"x","level":"bogus","message":{"text":"no location"}}]}
20 ]}`)
21 got, truncated, err := Parse(raw)
22 if err != nil || truncated {
23 t.Fatalf("Parse: %v %v", err, truncated)
24 }
25 if len(got) != 3 {
26 t.Fatalf("findings = %+v", got)
27 }
28 // Sorted by path; the duplicate under two URI spellings folded; the
29 // default level applied; whitespace collapsed.
30 if got[0].Path != "" || got[0].Level != "warning" || got[0].Tool != "other" {
31 t.Errorf("got[0] = %+v", got[0])
32 }
33 if got[1].Path != "a/a.go" || got[1].Level != "note" {
34 t.Errorf("got[1] = %+v", got[1])
35 }
36 if got[2].Path != "a/b.go" || got[2].Line != 3 || got[2].Message != "first line" || got[2].Level != "warning" {
37 t.Errorf("got[2] = %+v", got[2])
38 }
39 if _, _, err := Parse([]byte(`{"nope":1}`)); err == nil {
40 t.Error("a document without runs parsed")
41 }
42}
43
44func TestParseTruncates(t *testing.T) {
45 var b strings.Builder
46 b.WriteString(`{"runs":[{"tool":{"driver":{"name":"t"}},"results":[`)
47 for i := 0; i < MaxFindings+5; i++ {
48 if i > 0 {
49 b.WriteString(",")
50 }
51 b.WriteString(`{"ruleId":"r","message":{"text":"m` + strings.Repeat("x", i%7) + itoa(i) + `"}}`)
52 }
53 b.WriteString(`]}]}`)
54 got, truncated, err := Parse([]byte(b.String()))
55 if err != nil || !truncated || len(got) != MaxFindings {
56 t.Fatalf("len %d truncated %v err %v", len(got), truncated, err)
57 }
58}
59
60func itoa(i int) string { return strconv.Itoa(i) }
61
62// A finding that moves is the same finding.
63func TestSameIgnoresLines(t *testing.T) {
64 a, _, _ := Parse([]byte(`{"runs":[{"tool":{"driver":{"name":"t"}},"results":[{"ruleId":"r","message":{"text":"m"},
65 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"x.go"},"region":{"startLine":1}}}]}]}]}`))
66 b, _, _ := Parse([]byte(`{"runs":[{"tool":{"driver":{"name":"t"}},"results":[{"ruleId":"r","message":{"text":"m"},
67 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"x.go"},"region":{"startLine":40}}}]}]}]}`))
68 if !Same(ByFingerprint(a), ByFingerprint(b)) {
69 t.Error("a moved finding counted as a change")
70 }
71}