Home > Backend Development > Golang > How to Combine Code Coverage Results from Multiple Go Packages?

How to Combine Code Coverage Results from Multiple Go Packages?

Barbara Streisand
Release: 2024-12-24 11:44:17
Original
623 people have browsed it

How to Combine Code Coverage Results from Multiple Go Packages?

How to Consolidate Code Coverage Results for Multiple Packages in Go

When testing multiple packages in a Go library, it can be beneficial to obtain a comprehensive view of code coverage. By default, using the -cover flag with go test provides coverage information for individual packages.

To aggregate coverage data across all packages, you can employ one of two approaches:

Using -coverpkg in Go 1.10 and later:

In Go 1.10 and higher, the -coverpkg flag allows you to specify a comma-separated list of coverage targets. To cover all dependencies of the test package, use:

go test -v -coverpkg=./... -coverprofile=profile.cov ./...
go tool cover -func profile.cov
Copy after login

Using a Bash script in earlier Go versions:

For Go versions prior to 1.10, consider using a Bash script to collect and consolidate coverage data:

#!/bin/bash
set -e

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
Copy after login

This script iterates through directories with Go files, running tests with coverage enabled and appending the results to a consolidated profile file (profile.cov). You can then use go tool cover to generate a summary of the overall code coverage.

The above is the detailed content of How to Combine Code Coverage Results from Multiple Go Packages?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template