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
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
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!