Home >Backend Development >Golang >How to Exclude Generated Files from Go Test Coverage?

How to Exclude Generated Files from Go Test Coverage?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-12 12:11:11833browse

How to Exclude Generated Files from Go Test Coverage?

Excluding Generated Files from Go Test Coverage

When running tests for a Go package with go test -coverprofile=cover.out , the generated files are included in the coverage calculation. To exclude these generated files, consider the following approach:

Stripping Generated Code from Coverage Profiles

  1. Run the tests and generate a temporary coverage profile using go test . -coverprofile cover.out.tmp.
  2. Parse the temporary profile using grep to filter out lines containing "_generated.go", which represents generated files.
  3. Create the final coverage profile cover.out by redirecting the filtered output. Use the command cat cover.out.tmp | grep -v "_generated.go" > cover.out.
  4. Generate the coverage report using tool cover -func cover.out.

Pipeline Integration

Depending on the tools used, this process can be easily integrated into your build/test pipeline. For example, if using Make, you could include the following steps:

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

By excluding generated files from the coverage calculation, you can obtain more accurate coverage metrics that focus on your manually written code.

The above is the detailed content of How to Exclude Generated Files from Go Test Coverage?. 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