How to ignore generated files from Go test coverage

You could strip the generated code from the cover profiles:

go test . -coverprofile cover.out.tmp
cat cover.out.tmp | grep -v "_generated.go" > cover.out
tool cover -func cover.out

Depending on the used tools this can be implemented easily in the pipeline/make.


Following the ways that I could solve this need.

By excluding dirs/pkgs

Since to run the test and generated the cover you will specify the pkgs where the go test command should look for the files out of this pkg will be ignored automatically. Following an example

project
|_______/pkg/web/app 
|_______/pkg/web/mock -> It will be ignored.

# Command:   
$go test -failfast -tags=integration -coverprofile=coverage.out -covermode=count github.com/aerogear/mobile-security-service/pkg/web/apps

However, it cannot be applied in all cases. For example, in the case of the files be mock routines of your interfaces it may not work very well because the imports which are required into the service, test and mock probably will be in a cycle and in this not allowed.

By using "_test" in the name definitions

If you would like to ignore files which are used in the tests then make sense use _test at the end of the name. For example, my_service_mock_test.go. The files with _test at the end of the name will be ignored by default.

By removing from the cover file as follows

go test . -coverprofile cover.out.tmp
cat cover.out.tmp | grep -v "_generated.go" > cover.out
tool cover -func cover.out

PS.: I could not find a comment or tag which would exclude them.