4

When showing code coverage, go test show code coverage for each package (in percentage).

Is there a way to show a summary for a folder that is taking all subfolder (subpackage) into account?

What I want is a global code coverage percentage for the full project, one number that show code coverage of the folder and all subfolders.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
BlueMagma
  • 2,392
  • 1
  • 22
  • 46

3 Answers3

8

After running:

go test --coverprofile=coverage.out ./...

Run:

go tool cover -func=coverage.out

You will see the total percentage at the end of the result

hutabalian
  • 3,254
  • 2
  • 16
  • 13
  • 2
    you got to create a ***_test.go file for each ***.go file you have with the package declaration even if you don't have any tests for that given file. Otherwise your metrics will not consider the file with no test and the cover percentage will not reflect your project. – Totalys Jul 28 '20 at 17:39
2

I found a solution to my problem.

I first run the test on all package and store the test result in a file :

go test --coverprofile=coverage.out ./...

I then run a bash script to calculate my result

#!/usr/bin/env bash

covered=0
total=0
while IFS='' read -r line || [[ -n "$line" ]]; do
    IFS=' ' read -r -a array <<< "$line"
    total=$(($total+${array[1]}))
    if [ "${array[2]}" = "1" ]; then
        covered=$(($covered+${array[1]}))
    fi 
done < "$1"
echo $(awk "BEGIN { pc=100*${covered}/${total}; i=int(pc); print (pc-i<0.5)?i:i+1 }")
BlueMagma
  • 2,392
  • 1
  • 22
  • 46
-1

You can have the coverage of all sub-packages without any external tools/ with:

go test --coverprofile=coverage.out -coverpkg=./your/package/... ./your/package
-coverpkg pattern1,pattern2,pattern3
    Apply coverage analysis in each test to packages matching the patterns.
    The default is for each test to analyze only the package being tested.
    See 'go help packages' for a description of package patterns.
    Sets -cover.

https://golang.org/cmd/go/#hdr-Testing_flags

nvcnvn
  • 4,991
  • 8
  • 49
  • 77