0

Using the -cover option of go test, eg

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

coverage.out contains lots of output for each file, but I want a single number for overall coverage (which can be used to pass/fail coverage).

I found a reasonable (although erroneous!) script solution in this article:

cat coverage.out | \
awk 'BEGIN {cov=0; stat=0;} \
    $3!="" { cov+=($3==1?$2:0); stat+=$2; } \
    END {printf("Total coverage: %.2f%% of statements\n", (cov/stat)*100);}'

but is there a non-script, go way to do this?

Bohemian
  • 412,405
  • 93
  • 575
  • 722

1 Answers1

0

We us gotestsum for this purpose. It is a replacement for go test with additional features, like outputting in JUnit XML format.

https://github.com/gotestyourself/gotestsum

The disadvantage of using a third party tool like this is, that your developers and CI need to have it installed.

Jens
  • 20,533
  • 11
  • 60
  • 86
  • I don't want to be mean, but this doesn't really answer the question. Given the option of the tiny script or importing a GitHub project, the script wins IMHO. – Bohemian Mar 16 '22 at 08:17
  • No problem @Bohemian. I get that a script is preferable. I just provided _a_ solution. Maybe others might prefer it. In the end the constraints you provided ("but is there a non-script, go way to do this?") let me to believe that you are not looking for a script. And `gotestsum` is written in Go etc. But anyway. – Jens Mar 16 '22 at 11:48
  • 1
    "The disadvantage of using a third party tool like this is, that your developers and CI need to have it installed." The way I get around this is to us a Makefile and use a `go run` command to run the package without installing. E.g. `go run gotest.tools/gotestsum@latest -- -coverprofile=coverage/coverage.out ./...` – Lewsmith Mar 17 '23 at 14:49
  • @Lewsmith That is a very interesting comment. I did not know about this possibility. Since we also use a `Makefile` I will definitely give this a try. Thank you. – Jens Mar 18 '23 at 15:35