BlueMagma
BlueMagma

Reputation: 2495

How to get a global test coverage for a folder

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.

Upvotes: 5

Views: 5919

Answers (3)

hutabalian
hutabalian

Reputation: 3484

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

Upvotes: 8

nvcnvn
nvcnvn

Reputation: 5175

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

Upvotes: -1

BlueMagma
BlueMagma

Reputation: 2495

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 }")

Upvotes: 3

Related Questions