Source file src/testing/newcover.go

     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  	_ "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.
    18  var cover2 struct {
    19  	mode        string
    20  	tearDown    func(coverprofile string, gocoverdir string) (string, error)
    21  	snapshotcov func() float64
    22  }
    23  
    24  // registerCover2 is injected in testmain.
    25  //go:linkname registerCover2
    26  
    27  // registerCover2 is invoked during "go test -cover" runs by the test harness
    28  // code in _testmain.go; it is used to record a 'tear down' function
    29  // (to be called when the test is complete) and the coverage mode.
    30  func registerCover2(mode string, tearDown func(coverprofile string, gocoverdir string) (string, error), snapcov func() float64) {
    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.
    39  func 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  // testGoCoverDir is used in runtime/coverage tests.
    50  //go:linkname testGoCoverDir
    51  
    52  // testGoCoverDir returns the value passed to the -test.gocoverdir
    53  // flag by the Go command, if goexperiment.CoverageRedesign is
    54  // in effect.
    55  func testGoCoverDir() string {
    56  	return *gocoverdir
    57  }
    58  
    59  // coverage2 returns a rough "coverage percentage so far"
    60  // number to support the testing.Coverage() function.
    61  func coverage2() float64 {
    62  	if cover2.mode == "" {
    63  		return 0.0
    64  	}
    65  	return cover2.snapshotcov()
    66  }
    67  

View as plain text