[Awesome Go] Use package testing to test, benchmark, example and coverage code in Golang (Go)
testing
Package testing provides support for automated testing of Go packages.
TestXxx
It is intended to be used in concert with the go test
command, which automates execution of any function of the form
1 | func TestXxx(*testing.T) |
where Xxx does not start with a lowercase letter. The function name serves to identify the test routine.
Within these functions, use the Error
, Fail
or related methods to signal failure.
To write a new test suite, create a file whose name ends _test.go
that contains the TestXxx
functions as described here. Put the file in the same package as the one being tested. The file will be excluded from regular package builds but will be included when the go test
command is run. For more detail, run go help test
and go help testflag
.
A simple test function looks like this:
1 | func TestAbs(t *testing.T) { |
Benchmarks
Functions of the form
1 | func BenchmarkXxx(*testing.B) |
are considered benchmarks, and are executed by the go test
command when its -bench
flag is provided. Benchmarks are run sequentially.
For a description of the testing flags, see https://golang.org/cmd/go/#hdr-Testing_flags
A sample benchmark function looks like this:
1 | func BenchmarkRandInt(b *testing.B) { |
The benchmark function must run the target code b.N
times. During benchmark execution, b.N
is adjusted until the benchmark function lasts long enough to be timed reliably. The output
1 | BenchmarkRandInt-8 68453040 17.8 ns/op |
means that the loop ran 68453040 times at a speed of 17.8 ns per loop.
If a benchmark needs some expensive setup before running, the timer may be reset:
1 | func BenchmarkBigLen(b *testing.B) { |
If a benchmark needs to test performance in a parallel setting, it may use the RunParallel
helper function; such benchmarks are intended to be used with the go test -cpu
flag:
1 | func BenchmarkTemplateParallel(b *testing.B) { |
Examples
The package also runs and verifies example code. Example functions may include a concluding line comment that begins with “Output:” and is compared with the standard output of the function when the tests are run. (The comparison ignores leading and trailing space.) These are examples of an example:
1 | func ExampleHello() { |
The comment prefix “Unordered output:” is like “Output:”, but matches any line order:
1 | func ExamplePerm() { |
Example functions without output comments are compiled but not executed.
The naming convention to declare examples for the package, a function F, a type T and method M on type T are:
1 | func Example() { ... } |
Multiple example functions for a package/type/function/method may be provided by appending a distinct suffix to the name. The suffix must start with a lower-case letter.
1 | func Example_suffix() { ... } |
The entire test file is presented as the example when it contains a single example function, at least one other function, type, variable, or constant declaration, and no test or benchmark functions.
Skipping
Tests or benchmarks may be skipped at run time with a call to the Skip method of *T or *B:
1 | func TestTimeConsuming(t *testing.T) { |
Subtests and Sub-benchmarks
The Run methods of T and B allow defining subtests and sub-benchmarks, without having to define separate functions for each. This enables uses like table-driven benchmarks and creating hierarchical tests. It also provides a way to share common setup and tear-down code:
1 | func TestFoo(t *testing.T) { |
Each subtest and sub-benchmark has a unique name: the combination of the name of the top-level test and the sequence of names passed to Run, separated by slashes, with an optional trailing sequence number for disambiguation.
The argument to the -run and -bench command-line flags is an unanchored regular expression that matches the test’s name. For tests with multiple slash-separated elements, such as subtests, the argument is itself slash-separated, with expressions matching each name element in turn. Because it is unanchored, an empty expression matches any string. For example, using “matching” to mean “whose name contains”:
1 | go test -run '' # Run all tests. |
Subtests can also be used to control parallelism. A parent test will only complete once all of its subtests complete. In this example, all tests are run in parallel with each other, and only with each other, regardless of other top-level tests that may be defined:
1 | func TestGroupedParallel(t *testing.T) { |
The race detector kills the program if it exceeds 8192 concurrent goroutines, so use care when running parallel tests with the -race flag set.
Run does not return until parallel subtests have completed, providing a way to clean up after a group of parallel tests:
1 | func TestTeardownParallel(t *testing.T) { |
TestMain / Test Suite
It is sometimes necessary for a test program to do extra setup or teardown before or after testing. It is also sometimes necessary for a test to control which code runs on the main thread. To support these and other cases, if a test file contains a function:
1 | func TestMain(m *testing.M) |
then go test
will call TestMain(m)
instead of running the tests directly. TestMain
runs in the main goroutine and can do whatever setup and teardown is necessary around a call to m.Run
. m.Run
will return an exit code that may be passed to os.Exit
. If TestMain
returns, the test wrapper will pass the result of m.Run
to os.Exit
itself.
When TestMain
is called, flag.Parse
has not been run. If TestMain
depends on command-line flags, including those of the testing package, it should call flag.Parse
explicitly. Command line flags are always parsed by the time test or benchmark functions run.
A simple implementation of TestMain
is:
1 | package main |
Testing flags
The go test
command takes both flags that apply to go test
itself and flags that apply to the resulting test binary.
Several of the flags control profiling and write an execution profile suitable for go tool pprof
; run go tool pprof -h
for more information. The --alloc_space
, --alloc_objects
, and --show_bytes
options of pprof control how the information is presented.
The following flags are recognized by the go test
command and control the execution of any test:
1 | -bench regexp |
Each of these flags is also recognized with an optional test.
prefix, as in -test.v
. When invoking the generated test binary (the result of go test -c
) directly, however, the prefix is mandatory.
The go test
command rewrites or removes recognized flags, as appropriate, both before and after the optional package list, before invoking the test binary.
For instance, the command
1 | go test -v -myflag testdata -cpuprofile=prof.out -x |
will compile the test binary and then run it as
1 | pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out |
(The -x
flag is removed because it applies only to the go command’s execution, not to the test itself.)
The test flags that generate profiles (other than for coverage) also leave the test binary in pkg.test for use when analyzing the profiles.
When go test
runs a test binary, it does so from within the corresponding package’s source code directory. Depending on the test, it may be necessary to do the same when invoking a generated test binary directly.
The command-line package list, if present, must appear before any flag not known to the go test command. Continuing the example above, the package list would have to appear before -myflag, but could appear on either side of -v.
When go test
runs in package list mode, go test
caches successful package test results to avoid unnecessary repeated running of tests. To disable test caching, use any test flag or argument other than the cacheable flags. The idiomatic way to disable test caching explicitly is to use -count=1.
To keep an argument for a test binary from being interpreted as a known flag or a package name, use -args (see go help test
) which passes the remainder of the command line through to the test binary uninterpreted and unaltered.
For instance, the command
1 | go test -v -args -x -v |
will compile the test binary and then run it as
1 | pkg.test -test.v -x -v |
Similarly,
1 | go test -args math |
will compile the test binary and then run it as
1 | pkg.test math |
In the first example, the -x
and the second -v
are passed through to the test binary unchanged and with no effect on the go command itself. In the second example, the argument math is passed through to the test binary, instead of being interpreted as the package list.
Run Test
There are two ways to run tests, first is local directory mode where we run test using go test which is what we used when our greeting package was inside $GOPATH. The second way is to run tests in the package list mode. This mode is activated when we list what packages to test, for example,
-
go test . to test package in the current directory.
-
go test package when package belongs to $GOPATH as long as you are not executing this command from inside a Go Module.
-
go test ./tranform to test package in ./tranform directory.
-
go test ./… to test all the package in the current directory.
In package list mode, Go caches the only successful test results to avoid repeated running of the same tests. Whenever Go run tests on a package, Go creates a test binary and runs it. You can output this binary using -c flag with go test command. This will output .test file but won’t run it. Additionally, rename this file using -o flag.
References
[1] testing - The Go Programming Language - https://golang.org/pkg/testing/
[2] Testing flags - https://golang.org/cmd/go/#hdr-Testing_flags