Golang实践:代码单元测试
测试
单元测试
示例:
go test -v -cover -short -bench .
go test -run x -bench .
常用参数:
-args:
Pass the remainder of the command line (everything after -args) to the test binary, uninterpreted and unchanged.
Because this flag consumes the remainder of the command line,
the package list (if present) must appear before this flag.
-json:
Convert test output to JSON suitable for automated processing.See ‘go doc test2json’ for the encoding details.
-o:
file Compile the test binary to the named file.The test still runs (unless -c or -i is specified).
指定生成的二进制可执行程序,并执行测试,测试结束不会删除该程序
-c:
Compile the test binary to pkg.test but do not run it(where pkg is the last element of the package’s import path).The file name can be changed with the -o flag.
-exec xprog:
Run the test binary using xprog. The behavior is the same as
in ‘go run’. See ‘go help run’ for details.
-i:
Install packages that are dependencies of the test.Do not run the test.
-v:
显示详细信息;
-cover:
测试覆盖率;
-bench regexp:
执行相应的benchmarks, go test默认不执行性能测试,使用-bench参数才可以运行,而且只运行性能测试函数;
-run regexp:
只运行regexp匹配的函数,例如 -run=xxx那么就执行包含有xxx开头的函数;
go help test
usage: go test [build/test flags] [packages] [build/test flags & test binary flags]
'Go test' automates testing the packages named by the import paths.
It prints a summary of the test results in the format:
ok archive/tar 0.011s
FAIL archive/zip 0.022s
ok compress/gzip 0.033s
...
followed by detailed output for each failed package.
'Go test' recompiles each package along with any files with names matching
the file pattern "*_test.go".
These additional files can contain test functions, benchmark functions, and
example functions. See 'go help testfunc' for more.
Each listed package causes the execution of a separate test binary.
Files whose names begin with "_" (including "_test.go") or "." are ignored.
Test files that declare a package with the suffix "_test" will be compiled as a
separate package, and then linked and run with the main test binary.
The go tool will ignore a directory named "testdata", making it available
to hold ancillary data needed by the tests.
As part of building a test binary, go test runs go vet on the package
and its test source files to identify significant problems. If go vet
finds any problems, go test reports those and does not run the test
binary. Only a high-confidence subset of the default go vet checks are
used. That subset is: 'atomic', 'bool', 'buildtags', 'nilfunc', and
'printf'. You can see the documentation for these and other vet tests
via "go doc cmd/vet". To disable the running of go vet, use the
-vet=off flag.
All test output and summary lines are printed to the go command's
standard output, even if the test printed them to its own standard
error. (The go command's standard error is reserved for printing
errors building the tests.)
Go test runs in two different modes:
The first, called local directory mode, occurs when go test is
invoked with no package arguments (for example, 'go test' or 'go
test -v'). In this mode, go test compiles the package sources and
tests found in the current directory and then runs the resulting
test binary. In this mode, caching (discussed below) is disabled.
After the package test finishes, go test prints a summary line
showing the test status ('ok' or 'FAIL'), package name, and elapsed
time.
The second, called package list mode, occurs when go test is invoked
with explicit package arguments (for example 'go test math', 'go
test ./...', and even 'go test .'). In this mode, go test compiles
and tests each of the packages listed on the command line. If a
package test passes, go test prints only the final 'ok' summary
line. If a package test fails, go test prints the full test output.
If invoked with the -bench or -v flag, go test prints the full
output even for passing package tests, in order to display the
requested benchmark results or verbose logging. After the package
tests for all of the listed packages finish, and their output is
printed, go test prints a final 'FAIL' status if any package test
has failed.
In package list mode only, go test caches successful package test
results to avoid unnecessary repeated running of tests. When the
result of a test can be recovered from the cache, go test will
redisplay the previous output instead of running the test binary
again. When this happens, go test prints '(cached)' in place of the
elapsed time in the summary line.
The rule for a match in the cache is that the run involves the same
test binary and the flags on the command line come entirely from a
restricted set of 'cacheable' test flags, defined as -cpu, -list,
-parallel, -run, -short, and -v. If a run of go test has any test
or non-test flags outside this set, the result is not cached. 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. Tests that open files within the package's source
root (usually $GOPATH) or that consult environment variables only
match future runs in which the files and environment variables are unchanged.
A cached test result is treated as executing in no time at all,
so a successful package test result will be cached and reused
regardless of -timeout setting.
In addition to the build flags, the flags handled by 'go test' itself are:
-args
Pass the remainder of the command line (everything after -args)
to the test binary, uninterpreted and unchanged.
Because this flag consumes the remainder of the command line,
the package list (if present) must appear before this flag.
-c
Compile the test binary to pkg.test but do not run it
(where pkg is the last element of the package's import path).
The file name can be changed with the -o flag.
-exec xprog
Run the test binary using xprog. The behavior is the same as
in 'go run'. See 'go help run' for details.
-i
Install packages that are dependencies of the test.
Do not run the test.
-json
Convert test output to JSON suitable for automated processing.
See 'go doc test2json' for the encoding details.
-o file
Compile the test binary to the named file.
The test still runs (unless -c or -i is specified).
The test binary also accepts flags that control execution of the test; these
flags are also accessible by 'go test'. See 'go help testflag' for details.
For more about build flags, see 'go help build'.
For more about specifying packages, see 'go help packages'.
ee also: go build, go vet.
测试覆盖率
确认覆盖率
go test -cover
输出html文件
go test -coverprofile=covprofile go tool cover -html=covprofile -o coverage.html
性能测试
命令
# go test -run=xxx -bench=. -benchtime="3s" -cpuprofile profile_cpu.out
# go test -run=xxx -bench=. -benchtime="3s" -cpuprofile profile_cpu.out
# go tool pprof -svg profile_cpu.out > profile_cpu.svg
# go tool pprof -pdf profile_cpu.out > profile_cpu.pdf
go test -run=xxx -bench=BenchmarkStringJoin2B$ -cpuprofile profile_2b.out
go test -run=xxx -bench=BenchmarkStringJoin2$ -cpuprofile profile_2.out
go tool pprof -svg profile_2b.out > profile_2b.svg
go tool pprof -svg profile_2.out > profile_2.svg
tset2json
go doc test2json
Test2json converts go test output to a machine-readable JSON stream.
Usage:
go tool test2json [-p pkg] [-t] [./pkg.test -test.v]
Test2json runs the given test command and converts its output to JSON; with
no command specified, test2json expects test output on standard input. It
writes a corresponding stream of JSON events to standard output. There is no
unnecessary input or output buffering, so that the JSON stream can be read
for “live updates” of test status.
The -p flag sets the package reported in each test event.
The -t flag requests that time stamps be added to each test event.
Note that test2json is only intended for converting a single test binary's
output. To convert the output of a "go test" command, use "go test -json"
instead of invoking test2json directly.
Output Format
The JSON stream is a newline-separated sequence of TestEvent objects
corresponding to the Go struct:
type TestEvent struct {
Time time.Time // encodes as an RFC3339-format string
Action string
Package string
Test string
Elapsed float64 // seconds
Output string
}
The Time field holds the time the event happened. It is conventionally
omitted for cached test results.
The Action field is one of a fixed set of action descriptions:
run - the test has started running
pause - the test has been paused
cont - the test has continued running
pass - the test passed
bench - the benchmark printed log output but did not fail
fail - the test or benchmark failed
output - the test printed output
skip - the test was skipped or the package contained no tests
The Package field, if present, specifies the package being tested. When the
go command runs parallel tests in -json mode, events from different tests
are interlaced; the Package field allows readers to separate them.
The Test field, if present, specifies the test, example, or benchmark
function that caused the event. Events for the overall package test do not
set Test.
The Elapsed field is set for "pass" and "fail" events. It gives the time
elapsed for the specific test or the overall package test that passed or
failed.
The Output field is set for Action == "output" and is a portion of the
test's output (standard output and standard error merged together). The
output is unmodified except that invalid UTF-8 output from a test is coerced
into valid UTF-8 by use of replacement characters. With that one exception,
the concatenation of the Output fields of all output events is the exact
output of the test execution.
When a benchmark runs, it typically produces a single line of output giving
timing results. That line is reported in an event with Action == "output"
and no Test field. If a benchmark logs output or reports a failure (for
example, by using b.Log or b.Error), that extra output is reported as a
sequence of events with Test set to the benchmark name, terminated by a
final event with Action == "bench" or "fail". Benchmarks have no events with
Action == "run", "pause", or "cont".
goconvey
是一款针对Golang的测试框架,可以管理和运行测试用例,同时提供了丰富的断言函数,并支持很多 Web 界面特性。
GoConvey 网站 : http://smartystreets.github.io/goconvey/
GoConvey 是个相当不错的 Go 测试工具,支持 go test。可直接在终端窗口和浏览器上使用。
特点:
直接与 go test 集成
巨大的回归测试套件
可读性强的色彩控制台输出
完全自动化的 Web UI
测试代码生成器
桌面提醒(可选)
自动在终端中运行自动测试脚本
可立即在 Sublime Text 中打开测试问题对应的代码行 (some assembly required)