Home >Backend Development >Golang >How Can I Aggregate Go Package Coverage Results?

How Can I Aggregate Go Package Coverage Results?

DDD
DDDOriginal
2024-12-21 10:44:10879browse

How Can I Aggregate Go Package Coverage Results?

Aggregate Go Package Coverage

When executing tests in your Go library, you might encounter a need to obtain a consolidated coverage overview for all its packages. By default, the '-cover' flag only provides coverage information for each package individually.

Solution

Since Go 1.10, you can utilize the '-coverpkg' flag to address this issue. Simply run the following command:

go test -v -coverpkg=./... -coverprofile=profile.cov ./...

After running your tests, generate the aggregated coverage analysis using:

go tool cover -func profile.cov

Legacy Method (Pre-Go 1.10)

For Go versions prior to 1.10, you can employ the following bash script:

#!/bin/bash

echo 'mode: count' > profile.cov

for dir in $(find . -maxdepth 10 -not -path './.git*' -not -path '*/_*' -type d); do
  if ls $dir/*.go &>/dev/null; then
    go test -short -covermode=count -coverprofile=$dir/profile.tmp $dir
    if [ -f $dir/profile.tmp ]; then
      cat $dir/profile.tmp | tail -n +2 >> profile.cov
      rm $dir/profile.tmp
    fi
  fi
done

go tool cover -func profile.cov

The above is the detailed content of How Can I Aggregate Go Package Coverage Results?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn