diff --git a/go/tools/bzltestutil/lcov.go b/go/tools/bzltestutil/lcov.go index 8b94b162a3..5150ae59f6 100644 --- a/go/tools/bzltestutil/lcov.go +++ b/go/tools/bzltestutil/lcov.go @@ -28,6 +28,9 @@ import ( "testing/internal/testdeps" ) +// Lock in the COVERAGE_DIR during test setup in case the test uses e.g. os.Clearenv. +var coverageDir = os.Getenv("COVERAGE_DIR") + // ConvertCoverToLcov converts the go coverprofile file coverage.dat.cover to // the expectedLcov format and stores it in coverage.dat, where it is picked up by // Bazel. @@ -42,8 +45,12 @@ func ConvertCoverToLcov() error { } defer in.Close() + if coverageDir == "" { + log.Printf("Not collecting coverage: COVERAGE_DIR is not set") + return nil + } // All *.dat files in $COVERAGE_DIR will be merged by Bazel's lcov_merger tool. - out, err := os.CreateTemp(os.Getenv("COVERAGE_DIR"), "go_coverage.*.dat") + out, err := os.CreateTemp(coverageDir, "go_coverage.*.dat") if err != nil { return err } diff --git a/tests/core/coverage/lcov_coverage_test.go b/tests/core/coverage/lcov_coverage_test.go index a46567ccc5..d882d1ee31 100644 --- a/tests/core/coverage/lcov_coverage_test.go +++ b/tests/core/coverage/lcov_coverage_test.go @@ -116,6 +116,7 @@ public class Tool { package lib_test import ( + "os" "os/exec" "path/filepath" "strings" @@ -125,6 +126,8 @@ import ( ) func TestLib(t *testing.T) { + // Test that coverage is collected even if this variable is corrupted by a test. + os.Setenv("COVERAGE_DIR", "invalid") if !strings.Contains(lib.HelloFromLib(false), "\n") { t.Error("Expected a newline in the output") }