3

I want to get the test coverage and compare with user defined threshold. I tried below code in makefile I am referring this link. It is written in .yml file but I am trying to write it in a Makefile.

.PHONY: lint    
testcoverage=$(go tool cover -func coverage.out | grep total | grep -Eo '[0-9]+\.[0-9]+')
echo ${testcoverage}
if (${testcoverage} -lt 50 ); then \
  echo "Please add more unit tests or adjust threshold to a lower value."; \
  echo "Failed"
  exit 1
else \
  echo "OK"; \
fi

It does not print anything on echo ${totaltestcoverage} and gives answer OK even if my totaltestcoverage is 40.

Can anyone please help me with a better way to get the test coverage and compare with user defined threshold?

Thanks in advance.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Panda
  • 513
  • 2
  • 11

1 Answers1

1

You can try this

.PHONY: lint

testcoverage := $(shell go tool cover -func=coverage.out | grep total | grep -Eo '[0-9]+\.[0-9]+')
threshold = 50

test:
    @go test -coverprofile=coverage.out -covermode=count  ./...

check-coverage:
    @echo "Test coverage: $(testcoverage)"
    @echo "Test Threshold: $(threshold)"
    @echo "-----------------------"

    @if [ "$(shell echo "$(testcoverage) < $(threshold)" | bc -l)" -eq 1 ]; then \
        echo "Please add more unit tests or adjust the threshold to a lower value."; \
        echo "Failed"; \
        exit 1; \
    else \
        echo "OK"; \
    fi

PRATHEESH PC
  • 1,461
  • 1
  • 3
  • 15
  • Hi @PRATHEESH PC thank you so much for you help. I am getting this output `/bin/bash: line 1: bc: command not found ok github.XXXXX.com/org/repo 0.027s coverage: 47.2% of statements Test coverage: Test Threshold: /bin/bash: line 1: [: : integer expression expected OK` – Panda Jun 30 '23 at 05:24
  • I get this output on github while running in CI – Panda Jun 30 '23 at 05:37
  • How did your `yaml` look like ? Which `os` you are using ? See the demo at here https://github.com/pcpratheesh/unite-test-coverage – PRATHEESH PC Jun 30 '23 at 06:27
  • I have this in yml file jobs: ci: runs-on: [self-hosted, docker, internet] – Panda Jun 30 '23 at 06:42
  • Hoping you are running the pipline with your own runner, and you may need to install the `bc`. Hope this will help https://askubuntu.com/questions/550985/installing-bc-and-any-maths-extension – PRATHEESH PC Jun 30 '23 at 08:01
  • I dont have ubuntu-latest in my runs-on[] I can not use it. – Panda Jun 30 '23 at 08:05