Debian Codegraph @

src/testing/newcover.go

raw
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Support for test coverage with redesigned coverage implementation.
6
7 package testing
8
9 import (
10 "fmt"
11 "os"
12 _ "unsafe" // for linkname
13 )
14
15 // cover variable stores the current coverage mode and a
16 // tear-down function to be called at the end of the testing run.
17 var cover struct {
18 mode string
19 tearDown func(coverprofile string, gocoverdir string) (string, error)
20 snapshotcov func() float64
21 }
22
23 // registerCover is invoked during "go test -cover" runs.
24 // It is used to record a 'tear down' function
25 // (to be called when the test is complete) and the coverage mode.
26 func registerCover(mode string, tearDown func(coverprofile string, gocoverdir string) (string, error), snapcov func() float64) {
27 if mode == "" {
28 return
29 }
30 cover.mode = mode
31 cover.tearDown = tearDown
32 cover.snapshotcov = snapcov
33 }
34
35 // coverReport reports the coverage percentage and
36 // writes a coverage profile if requested.
37 // This invokes a callback in _testmain.go that will
38 // emit coverage data at the point where test execution is complete,
39 // for "go test -cover" runs.
40 func coverReport() {
41 if errmsg, err := cover.tearDown(*coverProfile, *gocoverdir); err != nil {
42 fmt.Fprintf(os.Stderr, "%s: %v\n", errmsg, err)
43 os.Exit(2)
44 }
45 }
46
47 // Coverage reports the current code coverage as a fraction in the range [0, 1].
48 // If coverage is not enabled, Coverage returns 0.
49 //
50 // When running a large set of sequential test cases, checking Coverage after each one
51 // can be useful for identifying which test cases exercise new code paths.
52 // It is not a replacement for the reports generated by 'go test -cover' and
53 // 'go tool cover'.
54 func Coverage() float64 {
55 if cover.mode == "" {
56 return 0.0
57 }
58 return cover.snapshotcov()
59 }