Skip to content

New: Ensure code coverage is met #651

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/pre-submit.units.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ jobs:

# Build Generic builder.
go build -mod=vendor ./internal/builders/generic
- name: Verify coverage
run: |
set -euo pipefail
make coverage

check-verifier:
name: verify slsa-verifier is latest
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
coverage

# Dependency directories (remove the comment below to include it)
vendor/
Expand Down
7 changes: 7 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
SHELL := /bin/bash
OUTPUT_FORMAT = $(shell if [ "${GITHUB_ACTIONS}" == "true" ]; then echo "github"; else echo ""; fi)
TEST_COVERAGE_PERCENTAGE=70
COVERAGE_THRESHOLD_FILE=coveragethreshold.json


.PHONY: help
help: ## Shows all targets and help from the Makefile (this message).
Expand Down Expand Up @@ -30,6 +33,10 @@ unit-test: ## Runs all unit tests.
go mod vendor
go test -mod=vendor -v ./...

coverage: ## Runs all unit tests and generates a coverage report.
echo "Ensuring the code coverage is met"
go mod vendor
go test -mod=vendor -coverprofile=coverage ./... | go run ./hack/codecoverage/main.go $(COVERAGE_THRESHOLD_FILE) $(TEST_COVERAGE_PERCENTAGE)

## Linters
#####################################################################
Expand Down
9 changes: 9 additions & 0 deletions coveragethreshold.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"github.com/slsa-framework/slsa-github-generator/github":70.4,
"github.com/slsa-framework/slsa-github-generator/internal/builders/generic": 52.3,
"github.com/slsa-framework/slsa-github-generator/internal/builders/go":17.1,
"github.com/slsa-framework/slsa-github-generator/internal/errors":100.0,
"github.com/slsa-framework/slsa-github-generator/internal/utils":72.1,
"github.com/slsa-framework/slsa-github-generator/signing/envelope":82.4,
"github.com/slsa-framework/slsa-github-generator/slsa":54.6
}
34 changes: 34 additions & 0 deletions hack/codecoverage/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Go Coverage tool
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is the folder called "hack"?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A coverage percentage is not very actionable for developers. Would it not be better to provide more actionable information in a PR for both reviewers and PR author? For example, annotation / information about functions added in a PR that are not hit by unit tests, that would be really useful to start with.

That is way harder, and there are existing tools like VSCode, and Go compiler which can do that.

The config file is going to go out-of-sync as soon as we add files, etc.

Yes, if we don't meet 70% coverage.

Should this feature live in an external GHA rather than in this repo?

As a dev, I would like to run the checks locally, and this gives that option

Making this blocking on PRs is probably just going to lead to the PR author reducing the threshold, since it's hard to tell which lines / functions are not tested.

The goal is to figure out the code coverage without using external dependencies. The code coverage is provided by VSCode and Go compiler. This isn't the design of this tool. Only then the code coverage is met. High-quality tests are critical for having confidence.

Right now, we are flying blind without knowing what the coverage of the project is. Any time new code gets added/updated, the project or the PR reviewer isn't aware of the test coverage.

What would be your suggestion to address this concern? Something like codecov would also suffice. Do you think we should enable an online tool?

Copy link
Collaborator

@laurentsimon laurentsimon Aug 1, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a dev, I would like to run the checks locally, and this gives that option

any reason why running go test locally does not suffice?

What would be your suggestion to address this concern? Something like codecov would also suffice. Do you think we should enable an online tool?

If codecov does it and they don't require write permissions, that sounds like an easy win, no?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If codecov does it and they don't require write permissions, that sounds like an easy win, no?

@bobcallaway Do you have thoughts on codecov or similar other online tools?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing we can do is open an HTML report of code coverage per file using the native go tools. Generate the coverage profile with go test, and then run go tool cover. We can make this a non-gating CI that allows reviewers (who ultimately should decide what can/cant be testable) to see if newly added code was tested.

The CI job can also add a comment decomenting coverage % in each pkg. If all of this can be done without new code to maintain, that would be great.

e.g.

go test -v -coverprofile cover.out ./YOUR_CODE_FOLDER/...
go tool cover -html=cover.out -o cover.html
open cover.html

Copy link
Collaborator

@laurentsimon laurentsimon Aug 1, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A high code coverage percentage does not guarantee high quality in the test coverage
More important than the percentage of lines covered is human judgment over the actual lines of code (and behaviors) that aren’t being covered

Qualitative feedback is nice. Imposing threshold does not help IMO. I've seen this in scorecard: when the coverage goes down in a PR, we just let the PR go thru because that's the best we can do. Over time we don't even look at it because it's just noise and not actionable.

Having a general view of code coverage is great. Having it in a (blocking) PR as a percentage number provides no benefits and is not actionable.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK cool! I understand if you have strong opinions on this 👍. I will close this PR.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand your argument @laurentsimon - we just let the PR go thru because thats the best we can do - why not ask the contributor to add unit test coverage for what they're proposing to not erode the baseline percentage?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. I think having a floor is ok. Maybe somewhere around 50% minimum (though the 60% Google number is also fine)? But not necessarily any targets.
  2. We should strive to ask for tests on PRs when appropriate.

I can go either way on making this a blocking pre-submit, but I agree there are merits either way.

I'm not sure I understand your argument @laurentsimon - we just let the PR go thru because thats the best we can do - why not ask the contributor to add unit test coverage for what they're proposing to not erode the baseline percentage?-

I think that the biggest problem would be for a change that doesn't necessarily merit unit-tests or where unit-tests are especially hard to write, it might make doing it on that particular PR overly expensive just to maintain an arbitrary coverage baseline. We also have e2e tests that might cover certain scenarios better than unit-tests.

A better rule might be that we need to hit a baseline coverage % before we do a release?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A better rule might be that we need to hit a baseline coverage % before we do a release?

This is a good thing to enforce on "pre-release" -- if we do this it would be good to have a report generated per PR because accumulating tests at the end is a lot harder than per-change.

why not ask the contributor to add unit test coverage for what they're proposing to not erode the baseline percentage?

I think the problem was that per-file doesn't give reviewer or author enough actionable guidance. I still like the HTML report generated to help the reviewer evaluate test coverage of any added lines.


The goal of the coverage tool is to measure the coverage of the code base for Golang.

## Usage
Execute the following command to get the coverage and store it in a file:
1. `go test -coverprofile=coverage ./... | run ./hack/codecoverage/main.go coverage.json 70`
2. The coverage.json contains the percentage of the code coverage that is required to pass for certain packages. This is usually because they don't match the desired coverage.
```json
{
"github.com/slsa-framework/slsa-github-generator/github":70.4,
"github.com/slsa-framework/slsa-github-generator/internal/builders/generic": 52.3,
"github.com/slsa-framework/slsa-github-generator/internal/builders/go":17.1,
"github.com/slsa-framework/slsa-github-generator/internal/errors":100.0,
"github.com/slsa-framework/slsa-github-generator/internal/utils":72.1,
"github.com/slsa-framework/slsa-github-generator/signing/envelope":82.4,
"github.com/slsa-framework/slsa-github-generator/slsa":54.6
}
```
3. The `COVERAGE_PERCENTAGE` is the percentage of the code coverage that is required to pass for all the packages except the ones that are mentioned in the `THRESHOLD_FILE`.
4. The coverage tool will fail if the coverage is below the threshold for any package.
``` shell
2022/07/29 16:14:41 github.com/slsa-framework/slsa-github-generator/pkg/foo is below the threshold of 71.000000
exit status 1
```

### Design choices

1. The coverage tool should not depend on any other tools. It should work of the results from the `go test` command.
2. Coverage threshold should be configurable for each repository - for example `70%` within the repository.
3. A setting file should override the coverage threshold for a given package within the repository. `github.com/foo/bar/xyz : 61`
4. The coverage tool should use native `go` tools and shouldn't depend on external vendors.
5. The coverage tool should be configurable as part of the PR to fail if the desired threshold is not met.
6. Contributors should be able to run it locally if desired before doing a PR.
3 changes: 3 additions & 0 deletions hack/codecoverage/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/slsa-framework/slsa-github-generator/hack/coverage

go 1.18
91 changes: 91 additions & 0 deletions hack/codecoverage/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright 2022 SLSA Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main

import (
"bufio"
"encoding/json"
"log"
"os"
"strconv"
"strings"
)

func main() {
if len(os.Args) != 3 {
log.Fatal("Usage: <threshold-file> <coverage-percent>")
}
thresholdFile := os.Args[1]
if thresholdFile == "" {
log.Fatalf("The thresholdfile cannot be empty.")
}
thresholdMap, err := parseCoverageThreshold(thresholdFile)
if err != nil {
log.Fatalf("Error parsing threshold file: %v", err)
}
coveragePercentage := os.Args[2]
if coveragePercentage == "" {
log.Fatalf("The coverage percentage cannot be empty.")
}
coveragePercentageFloat, err := strconv.ParseFloat(coveragePercentage, 64)
if err != nil {
log.Fatalf("Error parsing coverage percentage: %v", err)
}
// read stream from stdin
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, "coverage: ") {
parts := strings.Fields(line)
if len(parts) < 5 {
continue
}
percentage, err := strconv.ParseFloat(strings.Trim(parts[4], "%"), 64)
if err != nil {
log.Fatalf("invalid line: %s", line)
}
pack := parts[1]
if val, ok := thresholdMap[pack]; ok {
if percentage < val {
log.Fatalf("coverage for %s is below threshold: %f < %f", pack, percentage, val)
}
continue
}
// if the package is not in the threshold map, then we check if the coverage is below the threshold
if percentage < coveragePercentageFloat {
log.Fatalf("coverage for %s is below threshold: %f < %f", pack, percentage, coveragePercentageFloat)
}
}
}
}

// parseCoverageThreshold parses the threshold file and returns a map.
func parseCoverageThreshold(fileName string) (map[string]float64, error) {
// Here is an example of the threshold file:
/*
{
"github.com/foo/bar/pkg/cryptoutils": 71.2,
}
*/
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer f.Close()
thresholdMap := make(map[string]float64)
if err := json.NewDecoder(f).Decode(&thresholdMap); err != nil {
return nil, err
}
return thresholdMap, nil
}