Hello,

First off, it's worth noting that I have come up with a solution to my 
problem. I'm mostly wondering if there is a better way as it feels a bit 
hacky. Thanks in advance for any help.

I want to get a percent of how many lines of code in an entire repository 
are covered by unit tests. The approaches I've seen which do this (many 
coming from here: https://github.com/golang/go/issues/6909) boil down to:

1. Generate one coverprofile for each package
2. Merge those coverprofiles into one
3. Analyze that single coverprofile to figure out the total percent of code 
coverage. This analysis could be done using "go tool cover" or sending it 
to coveralls.io among other things.

The problem with this approach is that "go test" does NOT generate a 
coverprofile if a package has no unit tests. So hypothetically if you had 
20 packages 19 of which had no unit tests and the other 1 had 100% coverage 
then your "total" coverage would be reported as 100% because those 19 other 
packages are not part of the calculation.

The solution I came up with is basically to generate an empty "*_test.go" 
file in each repository that has no tests then do 1,2,3 above. Is that 
overkill? Is there an easier way? Any recommendations for other solutions 
(even something like "make it part of your code process that each package 
has tests of some sort")? Here is the script:

#!/bin/bash -e

# Generates a coverprofile for each package and concatenates all those
# coverprofiles into one. It outputs a html file based off the
# coverprofile.

covfile=coverage.out
tmpcovfile="${covfile}.tmp"
emptytestfile=emptytestusedforcoverage_test.go
mode=count
test_prefix_cmd="go test -v -covermode=$mode -coverprofile=${covfile}.tmp"
concat_and_rm_cmd="tail -n +2 $tmpcovfile >> $covfile && rm $tmpcovfile"

# Build the coverage profile
echo "mode: $mode" > "$covfile"
go list ./... | \
    xargs go list -f "\
        '{{if not (or (len .TestGoFiles) (len .XTestGoFiles))}}\
             echo \"package {{.Name}}\" > {{.Dir}}/${emptytestfile} &&\
             $test_prefix_cmd {{.ImportPath}} && $concat_and_rm_cmd &&\
             rm {{.Dir}}/${emptytestfile}\
        {{else}}\
             $test_prefix_cmd {{.ImportPath}} && $concat_and_rm_cmd\
        {{end}}'" | \
    xargs -L 1 bash -c

# Output the percent
go tool cover -func=coverage.out | \
    tail -n 1 | \
    awk '{ print $3 }' | \
    sed -e 's/^\([0-9]*\).*$/\1/g'


Thanks!
Lucas

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to