cover_test.go raw
1 package cover
2
3 import (
4 "os"
5 "path/filepath"
6 "testing"
7 )
8
9 // The fixture is shared with stage4: cmd/mxcover over these same two files must
10 // print the same text (see the cover-report check in tests/phase6). Keeping the
11 // expected report literal here is what pins the format across the two
12 // compilers' harnesses.
13 const coverSitesJSON = `[{"id":0,"name":"git.smesh.lol/smesh/pkg/demo.F@git.smesh.lol/smesh/pkg/demo/demo.mx:10"},` +
14 `{"id":1,"name":"git.smesh.lol/smesh/pkg/demo.G@git.smesh.lol/smesh/pkg/demo/demo.mx:20"},` +
15 `{"id":2,"name":"git.smesh.lol/smesh/other.H@git.smesh.lol/smesh/other/other.mx:5"}]`
16
17 const coverCountsText = "coversite 0 count=3\ncoversite 2 count=1\n"
18
19 const coverWantAll = `sites: 3 covered: 2 (66.6%)
20 100.0% 1/1 git.smesh.lol/smesh/other/other.mx
21 50.0% 1/2 git.smesh.lol/smesh/pkg/demo/demo.mx
22
23 uncovered sites: 1
24 git.smesh.lol/smesh/pkg/demo/demo.mx:20 git.smesh.lol/smesh/pkg/demo.G
25 `
26
27 const coverWantPkg = `sites: 2 covered: 1 (50.0%)
28 50.0% 1/2 git.smesh.lol/smesh/pkg/demo/demo.mx
29
30 uncovered sites: 1
31 git.smesh.lol/smesh/pkg/demo/demo.mx:20 git.smesh.lol/smesh/pkg/demo.G
32 `
33
34 func writeCoverFixture(t *testing.T) (string, string) {
35 t.Helper()
36 dir := t.TempDir()
37 sites := filepath.Join(dir, "sites.json")
38 counts := filepath.Join(dir, "counts")
39 if err := os.WriteFile(sites, []byte(coverSitesJSON), 0666); err != nil {
40 t.Fatal(err)
41 }
42 if err := os.WriteFile(counts, []byte(coverCountsText), 0666); err != nil {
43 t.Fatal(err)
44 }
45 return sites, counts
46 }
47
48 func TestCoverReport(t *testing.T) {
49 sites, counts := writeCoverFixture(t)
50 for _, tc := range []struct {
51 name string
52 prefix string
53 want string
54 }{
55 {"all", "git.smesh.lol/smesh/", coverWantAll},
56 {"package", "git.smesh.lol/smesh/pkg/", coverWantPkg},
57 } {
58 got, err := Report(sites, counts, tc.prefix)
59 if err != nil {
60 t.Fatalf("%s: %v", tc.name, err)
61 }
62 if got != tc.want {
63 t.Fatalf("%s report mismatch:\n got:\n%s\nwant:\n%s", tc.name, got, tc.want)
64 }
65 }
66 }
67
68 func TestCoverReportErrors(t *testing.T) {
69 sites, counts := writeCoverFixture(t)
70 if _, err := Report(sites+".missing", counts, ""); err == nil {
71 t.Fatal("missing site table must be an error")
72 }
73 if _, err := Report(sites, counts+".missing", ""); err == nil {
74 t.Fatal("missing counter dump must be an error")
75 }
76 if _, err := Report(sites, counts, "git.smesh.lol/nothing/"); err == nil {
77 t.Fatal("a prefix with no sites must be an error")
78 }
79 }
80