user12406569
user12406569

Reputation:

Make the build failure when code coverage is less than x%

I'm working with github actions and in my tests I need to make myt build fail when my code coverage percentage is less than 80%. I looked up some github actions in github marketplace but dont find anything. Can I do it ? I'm linking my workflow file if it migth help

---
name: lint build and test
on:
  push:
    branches: [master]
  pull_request:
    branches: [master]

jobs:
  build-and-test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Code
        uses: actions/checkout@v2

      - name: Set up Go
        uses: actions/setup-go@v2
        with:
          go-version: 1.15
        env:
          GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}  

      - name: Super-Linter
        uses: github/[email protected]
        env:
          VALIDATE_GO: false
          VALIDATE_JSCPD: false
          VALIDATE_ALL_CODEBASE: true
          DEFAULT_BRANCH: master          
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}  

      - name: golangci-lint
        uses: golangci/golangci-lint-action@v2
        with:
          version: v1.29

      - name: Build
        run: go build -o apiDateTime -v ./...    

      - name: Test 
        run: go test ./... -coverprofile cover.out -covermode atomic

      - name: Coverage result
        run: go tool cover -func cover.out

Upvotes: 1

Views: 1569

Answers (1)

kostix
kostix

Reputation: 55463

I would replace invocation of go test with an invocation of a shell script as explained here.

The shell script would look something like this

#!/bin/sh

set -e -u

go test ./... -coverprofile cover.out -covermode atomic

perc=`go tool cover -func=cover.out | tail -n 1 | sed -Ee 's!^[^[:digit:]]+([[:digit:]]+(\.[[:digit:]]+)?)%$!\1!'`
res=`echo "$perc >= 80.0" | bc`
test "$res" -eq 1 && exit 0
echo "Insufficient coverage: $perc" >&2
exit 1

Where:

  1. The encantation involving sed extracts the coverage percentage (see here).
  2. The next line asks the calculator to compare the percentage with your configured threshold.
  3. Then the next line makes the script exit successfully if the test passed.
  4. The rest of the script blows up if the coverage requirements were not met.

This script expects the bc tool is installed in that ubuntu-latest package (which I don't know).
If it isn't, the whole thing can be scripted in any language available in the image—such as Perl or Python.

Upvotes: 1

Related Questions