• Introduction to the
  • Unit testing
  • The performance test
  • Performance analysis
  • Test coverage
  • conclusion
  • Code for the current section

Introduction to the

In daily development, testing is indispensable.

The Go library includes a testing framework called Testing that can be used for both unit and performance testing. It is integrated with the go test command.

The test files are named after the _test.go suffix and are usually placed in the same package as the file being tested.

Unit testing

Unit tests are formatted like this:

func TestAbs(t *testing.T) {
  got := Abs(- 1)
  ifgot ! =1 {
    t.Errorf("Abs(-1) = %d; want 1", got)
  }
}
Copy the code

Create a file util_test.go in the util directory and add a unit test:

package util

import "testing"

// Normal tests
func TestGenShortID(t *testing.T) {
	shortID, err := GenShortID()
	if shortID == ""|| err ! =nil {
		t.Error("GenShortID failed")}}Copy the code

Then run go test -v./util/ in the root directory.

root@592402321ce7:/workspace# go test -v ./util/=== RUN TestGenShortID -- PASS: TestGenShortID (0.00s) PASS OK tzh.com/web/util 0.006sCopy the code

The performance test

The results of the performance test are as follows:

func BenchmarkHello(b *testing.B) {
  for i := 0; i < b.N; i++ {
    fmt.Sprintf("hello")}}Copy the code

Add a performance test in util_test.go:

// Performance test
func BenchmarkGenShortID(b *testing.B) {
	for i := 0; i < b.N; i++ {
		GenShortID()
	}
}
Copy the code

The result is as follows (use –run= None to avoid running normal test functions, since it is generally impossible for a function name to match None):

root@592402321ce7:/workspace# go test -v -bench="BenchmarkGenShortID$" --run=none ./util/Goos: Linux Goarch: AMD64 PKG: tzh.com/web/util benchmarkGenshortiD-2 507237 2352 ns/op PASS OK tzh.com/web/util 1.229sCopy the code

This shows that, on average, each run of GenShortID() takes 2352 nanoseconds.

Performance analysis

When you run a test, you can specify parameters to generate a performance profile.

-blockprofile block.out Write a goroutine blocking profile to the specified file when all tests are complete. Writes test binary as -c would. -blockprofilerate n Control the detail provided in goroutine blocking profiles by calling runtime.SetBlockProfileRate with n. See 'go doc runtime.SetBlockProfileRate'. The profiler aims to sample, on average, one blocking event every n nanoseconds the program spends blocked. By default, if -test.blockprofile is set without this flag, all blocking events are recorded, equivalent to -test.blockprofilerate=1. -coverprofile cover.out Write a coverage profile to the file after all tests have passed. Sets -cover. -cpuprofile cpu.out Write a CPU profile to the specified file before exiting. Writes test binary as -c would. -memprofile mem.out Write an allocation profile to the file after all tests have passed. Writes test  binary as -c would. -memprofilerate n Enable more precise (and expensive) memory allocation profiles by setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'. To profile all memory allocations, use -test.memprofilerate=1. -mutexprofile mutex.out Write a mutex contention profile to the specified file when all tests are complete. Writes test binary as -c would. -mutexprofilefraction n Sample 1 in n stack traces of goroutines holding a contended mutex.Copy the code

Generate a PROFILE for the CPU using the following command:

go test -v -bench="BenchmarkGenShortID$" --run=none -cpuprofile cpu.out ./util/
Copy the code

In the current directory, the cpu.out file and util.test file should be generated.

Use the following command to observe time-consuming operations:

Enter interactive mode
go tool pprof cpu.out
top
Copy the code

After installing Graphviz, you can generate a visual analysis graph.

apt install graphviz
go tool pprof -http=":" cpu.out
Copy the code

Test coverage

root@592402321ce7:/workspace# go test -v -coverprofile=cover.out ./util/=== RUN TestGenShortID -- PASS: TestGenShortID (0.00s) PASS coverage: 9.1% of statements OK tzh.com/web/util 0.005s coverage: 9.1% of statements root@592402321ce7:/workspace# go tool cover -func=cover.outTzh.com/web/util/util.go:12: GenShortID 100.0% tzh.com/web/util/util.go:17: GetReqID tzh.com/web/util/util.go:22: 0.0% TimeToStr 0.0% tzh.com/web/util/util.go:30: GetTag 0.0% total: 9.1% (statements)Copy the code

Use the -coverProfile =cover.out option to count test coverage. Use go Tool cover-func =cover.out to view more detailed test coverage results and count the test coverage for each function.

conclusion

Testing is a very important link in development, used to ensure the quality of software, must not be lazy.

Code for the current section

As version V0.15.0