diff options
author | Steve Azzopardi <sazzopardi@gitlab.com> | 2019-06-03 13:51:25 +0200 |
---|---|---|
committer | Steve Azzopardi <sazzopardi@gitlab.com> | 2019-07-19 06:59:52 +0200 |
commit | 77247efa76376571480844e33e55ab29ca42af0c (patch) | |
tree | 143ee016913315322efbca13dca281ad6f0fd7ef | |
parent | 9e85a1889fa91ae6a61069400b15e5e0d3ca40df (diff) | |
download | gitlab-ce-77247efa76376571480844e33e55ab29ca42af0c.tar.gz |
Add Go test guidelines
-rw-r--r-- | doc/development/go_guide/index.md | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/doc/development/go_guide/index.md b/doc/development/go_guide/index.md index f827d240bf6..c78f10510b8 100644 --- a/doc/development/go_guide/index.md +++ b/doc/development/go_guide/index.md @@ -173,6 +173,45 @@ func Test(t *testing.T) { } ``` +### Table Driven Tests + +Using [Table Driven Tests](https://github.com/golang/go/wiki/TableDrivenTests) +is generally good practice when you have multiple entries of +inputs/outputs for the same function. Below are some guidelines one can +follow when writing table-driven test. These guidelines are mostly +extracted from Go standard library source code. Keep in mind it's OK not +to follow these guidelines when it makes sense. + +#### Defining test cases + +Each table entry is a complete test case with inputs and expected +results, and sometimes with additional information such as a test name +to make the test output easily readable. + +- [Define a slice of anonymous struct](https://github.com/golang/go/blob/50bd1c4d4eb4fac8ddeb5f063c099daccfb71b26/src/encoding/csv/reader_test.go#L16) + inside of the test. +- [Define a slice of anonymous struct](https://github.com/golang/go/blob/55d31e16c12c38d36811bdee65ac1f7772148250/src/cmd/go/internal/module/module_test.go#L9-L66) + outside of the test. +- [Named structs](https://github.com/golang/go/blob/2e0cd2aef5924e48e1ceb74e3d52e76c56dd34cc/src/cmd/go/internal/modfetch/coderepo_test.go#L54-L69) + for code reuse. +- [Using `map[string]struct{}`](https://github.com/golang/go/blob/6d5caf38e37bf9aeba3291f1f0b0081f934b1187/src/cmd/trace/annotations_test.go#L180-L235). + +#### Contents of the test case + +- Ideally, each test case should have a field with a unique identifier + to use for naming subtests. In the Go standard library, this is commonly the + `name string` field. +- Use `want`/`expect`/`actual` when you are specifcing something in the + test case that will be used for assertion. + +#### Variable names + +- Each table driven test map/slice of struct can be named `tests`. +- When looping through `tests` the anonymous struct can be referred + to as `tt` or `tc`. +- The description of the test can be referred to as + `name`/`testName`/`tn`. + ### Benchmarks Programs handling a lot of IO or complex operations should always include |