1
2 # Testcase inspired by issue #58770, intended to verify that we're
3 # doing the right thing when running "go test -coverpkg=./... ./..."
4 # on a collection of packages where some have init functions and some
5 # do not, some have tests and some do not.
6
7 [short] skip
8 [!GOEXPERIMENT:coverageredesign] skip
9
10 # Verify correct statements percentages. We have a total of 10
11 # statements in the packages matched by "./..."; package "a" (for
12 # example) has two statements so we expect 20.0% stmts covered. Go
13 # 1.19 would print 50% here (due to force importing of all ./...
14 # packages); prior to the fix for #58770 Go 1.20 would show 100%
15 # coverage. For packages "x" and "f" (which have no tests), check for
16 # 0% stmts covered (as opposed to "no test files").
17
18 go test -count=1 -coverprofile=cov.dat -coverpkg=./... ./...
19 stdout '^\s*\?\s+M/n\s+\[no test files\]'
20 stdout '^\s*M/x\s+coverage: 0.0% of statements'
21 stdout '^\s*M/f\s+coverage: 0.0% of statements'
22 stdout '^ok\s+M/a\s+\S+\s+coverage: 30.0% of statements in ./...'
23 stdout '^ok\s+M/b\s+\S+\s+coverage: 20.0% of statements in ./...'
24 stdout '^ok\s+M/main\s+\S+\s+coverage: 80.0% of statements in ./...'
25
26 # Check for selected elements in the collected coverprofile as well.
27
28 go tool cover -func=cov.dat
29 stdout '^M/x/x.go:3:\s+XFunc\s+0.0%'
30 stdout '^M/b/b.go:7:\s+BFunc\s+100.0%'
31 stdout '^total:\s+\(statements\)\s+80.0%'
32
33 -- go.mod --
34 module M
35
36 go 1.21
37 -- a/a.go --
38 package a
39
40 import "M/f"
41
42 func init() {
43 println("package 'a' init: launch the missiles!")
44 }
45
46 func AFunc() int {
47 return f.Id()
48 }
49 -- a/a_test.go --
50 package a
51
52 import "testing"
53
54 func TestA(t *testing.T) {
55 if AFunc() != 42 {
56 t.Fatalf("bad!")
57 }
58 }
59 -- b/b.go --
60 package b
61
62 func init() {
63 println("package 'b' init: release the kraken")
64 }
65
66 func BFunc() int {
67 return -42
68 }
69 -- b/b_test.go --
70 package b
71
72 import "testing"
73
74 func TestB(t *testing.T) {
75 if BFunc() != -42 {
76 t.Fatalf("bad!")
77 }
78 }
79 -- f/f.go --
80 package f
81
82 func Id() int {
83 return 42
84 }
85 -- main/main.go --
86 package main
87
88 import (
89 "M/a"
90 "M/b"
91 )
92
93 func MFunc() string {
94 return "42"
95 }
96
97 func M2Func() int {
98 return a.AFunc() + b.BFunc()
99 }
100
101 func init() {
102 println("package 'main' init")
103 }
104
105 func main() {
106 println(a.AFunc() + b.BFunc())
107 }
108 -- main/main_test.go --
109 package main
110
111 import "testing"
112
113 func TestMain(t *testing.T) {
114 if MFunc() != "42" {
115 t.Fatalf("bad!")
116 }
117 if M2Func() != 0 {
118 t.Fatalf("also bad!")
119 }
120 }
121 -- n/n.go --
122 package n
123
124 type N int
125 -- x/x.go --
126 package x
127
128 func XFunc() int {
129 return 2 * 2
130 }
131
View as plain text