Skip to content

Repository files navigation

testableexamples
go minimal versiongo tested versionCICodecovGo Report CardLicenseGo Reference

Linter checks if examples are testable (have an expected output).

Author of idea is Jamie Tanna (see this issue).

Description

Example functions without output comments are compiled but not executed by go test, see doc.
It means that such examples are not validated. This can lead to outdated code.
That's why the linter complains on missing output.

funcExample_bad() { // <- linter will complain on missing outputfmt.Println("hello")
}
funcExample_good() {
fmt.Println("hello")
// Output: hello
}

Usage

The best way is to use golangci-lint.
It includes testableexamples and a lot of other great linters.

Install

See official site.

Enable

testableexamples is disabled by default.
To enable it, add the following to your .golangci.yml:

linters:
enable:
testableexamples

Run

golangci-lint run

Directive //nolint:testableexamples

Here is incorrect usage of //nolint directive.
golangci-lint understands it correctly, but godoc will include comment to the code.

// DescriptionfuncExample_nolintIncorrect() { //nolint:testableexamples // that's whyfmt.Println("hello")
}

Here are two examples of correct usage of //nolint directive.
godoc will ignore comment.

//nolint:testableexamples // that's whyfuncExample_nolintCorrect() {
fmt.Println("hello")
}
// Description////nolint:testableexamples // that's whyfuncExample_nolintCorrectWithDescription() {
fmt.Println("hello")
}

Usage as standalone linter

Install

go install github.com/maratori/testableexamples@latest

Run

testableexamples ./...

Nolint

Standalone linter doesn't support //nolint directive.
And there is no alternative for that, please use golangci-lint.

License

MIT License

About

Linter checks if examples are testable (have an expected output)

Topics

Resources

Contributing

Stars

6 stars

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages