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 7package testing 8 9import ( 10 "fmt" 11 "internal/goexperiment" 12 "os" 13 _ "unsafe" // for linkname 14) 15 16// cover2 variable stores the current coverage mode and a 17// tear-down function to be called at the end of the testing run. 18var cover2 struct { 19 mode string 20 tearDown func(coverprofile string, gocoverdir string) (string, error) 21 snapshotcov func() float64 22} 23 24// registerCover2 is invoked during "go test -cover" runs. 25// It is used to record a 'tear down' function 26// (to be called when the test is complete) and the coverage mode. 27func registerCover2(mode string, tearDown func(coverprofile string, gocoverdir string) (string, error), snapcov func() float64) { 28 if mode == "" { 29 return 30 } 31 cover2.mode = mode 32 cover2.tearDown = tearDown 33 cover2.snapshotcov = snapcov 34} 35 36// coverReport2 invokes a callback in _testmain.go that will 37// emit coverage data at the point where test execution is complete, 38// for "go test -cover" runs. 39func coverReport2() { 40 if !goexperiment.CoverageRedesign { 41 panic("unexpected") 42 } 43 if errmsg, err := cover2.tearDown(*coverProfile, *gocoverdir); err != nil { 44 fmt.Fprintf(os.Stderr, "%s: %v\n", errmsg, err) 45 os.Exit(2) 46 } 47} 48 49// coverage2 returns a rough "coverage percentage so far" 50// number to support the testing.Coverage() function. 51func coverage2() float64 { 52 if cover2.mode == "" { 53 return 0.0 54 } 55 return cover2.snapshotcov() 56} 57