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