1// Copyright 2022 The Bazel Authors. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package lcov_test_main_coverage_test 16 17import ( 18 "io/ioutil" 19 "path/filepath" 20 "strings" 21 "testing" 22 23 "github.com/bazelbuild/rules_go/go/tools/bazel_testing" 24) 25 26func TestMain(m *testing.M) { 27 bazel_testing.TestMain(m, bazel_testing.Args{ 28 Main: ` 29-- src/BUILD.bazel -- 30load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") 31 32go_library( 33 name = "lib", 34 srcs = ["lib.go"], 35 importpath = "example.com/lib", 36) 37 38go_test( 39 name = "lib_test", 40 srcs = ["lib_test.go"], 41 deps = [":lib"], 42) 43-- src/lib.go -- 44package lib 45 46func HelloFromLib(informal bool) string { 47 if informal { 48 return "Hey there, lib!" 49 } else { 50 return "Good morning, lib!" 51 } 52} 53-- src/lib_test.go -- 54package lib_test 55 56import ( 57 "strings" 58 "testing" 59 "os" 60 61 "example.com/lib" 62) 63 64func TestMain(m *testing.M) { 65 os.Exit(m.Run()) 66} 67 68func TestLib(t *testing.T) { 69 if !strings.Contains(lib.HelloFromLib(false), "lib!") { 70 t.Error("Expected 'lib!' in the output") 71 } 72} 73`, 74 }) 75} 76 77func TestLcovCoverageWithTestMain(t *testing.T) { 78 if err := bazel_testing.RunBazel("coverage", "--combined_report=lcov", "//src:lib_test"); err != nil { 79 t.Fatal(err) 80 } 81 82 individualCoveragePath := filepath.FromSlash("bazel-testlogs/src/lib_test/coverage.dat") 83 individualCoverageData, err := ioutil.ReadFile(individualCoveragePath) 84 if err != nil { 85 t.Fatal(err) 86 } 87 if string(individualCoverageData) != string(expectedIndividualCoverage) { 88 t.Errorf( 89 "%s: expected content:\n\n%s\nactual content:\n\n%s", 90 individualCoveragePath, 91 expectedIndividualCoverage, 92 string(individualCoverageData), 93 ) 94 } 95 96 combinedCoveragePath := filepath.FromSlash("bazel-out/_coverage/_coverage_report.dat") 97 combinedCoverageData, err := ioutil.ReadFile(combinedCoveragePath) 98 if err != nil { 99 t.Fatal(err) 100 } 101 for _, include := range []string{ 102 "SF:src/lib.go\n", 103 } { 104 if !strings.Contains(string(combinedCoverageData), include) { 105 t.Errorf("%s: does not contain %q\n", combinedCoverageData, include) 106 } 107 } 108} 109 110const expectedIndividualCoverage = `SF:src/lib.go 111FNF:0 112FNH:0 113DA:3,1 114DA:4,1 115DA:5,0 116DA:6,1 117DA:7,1 118DA:8,1 119LH:5 120LF:6 121end_of_record 122` 123