1// Copyright 2019 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 binary_coverage_test 16 17import ( 18 "testing" 19 20 "github.com/bazelbuild/rules_go/go/tools/bazel_testing" 21) 22 23func TestMain(m *testing.M) { 24 bazel_testing.TestMain(m, bazel_testing.Args{ 25 Main: ` 26-- BUILD.bazel -- 27load("@io_bazel_rules_go//go:def.bzl", "go_binary") 28 29go_binary( 30 name = "hello", 31 srcs = ["hello.go"], 32 out = "hello", 33) 34-- hello.go -- 35package main 36 37import "fmt" 38 39func main() { 40 fmt.Println(A()) 41} 42 43func A() int { return 12 } 44 45func B() int { return 34 } 46`, 47 }) 48} 49 50func Test(t *testing.T) { 51 // Check that we can build a binary with coverage instrumentation enabled. 52 args := []string{ 53 "build", 54 "--collect_code_coverage", 55 "--instrumentation_filter=.*", 56 "//:hello", 57 } 58 if err := bazel_testing.RunBazel(args...); err != nil { 59 t.Fatal(err) 60 } 61 62 // Check that we can build with `bazel coverage`. It will fail because 63 // there are no tests. 64 args = []string{ 65 "coverage", 66 "//:hello", 67 } 68 if err := bazel_testing.RunBazel(args...); err == nil { 69 t.Fatal("got success; want failure") 70 } else if bErr, ok := err.(*bazel_testing.StderrExitError); !ok { 71 t.Fatalf("got %v; want StderrExitError", err) 72 } else if code := bErr.Err.ExitCode(); code != 4 { 73 t.Fatalf("got code %d; want code 4 (no tests found)", code) 74 } 75} 76