Unit test with go

Time:2019-12-2
  • brief introduction
  • unit testing
  • performance testing
  • performance analysis
  • Test coverage
  • summary
  • Code of current part

brief introduction

In daily development, testing is indispensable

One of the go standard libraries is calledtestingIt can be used in unit test and performance test
It’s a commandgo testIntegrated

Test files are suffixed with_test.goNamed, usually in the same package as the file being tested

unit testing

The format of unit test is as follows:

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

stayutilCreate a file in the directoryutil_test.go, add a unit test:

package util

import "testing"

//Common test
func TestGenShortID(t *testing.T) {
    shortID, err := GenShortID()
    if shortID == "" || err != nil {
        t.Error("GenShortID failed")
    }
}

Then, run it in the root directorygo test -v ./util/, the test results are as follows:

[email protected]:/workspace# go test -v ./util/
=== RUN   TestGenShortID
--- PASS: TestGenShortID (0.00s)
PASS
ok      tzh.com/web/util        0.006s

performance testing

The results of performance test are as follows:

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

stayutil_test.goAdd performance test:

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

The results are as follows (using--run=noneAvoid running normal test functions because there is usually no match for function namesnone):

[email protected]:/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.229s

This means that the average operationGenShortID()It takes 2352 nanoseconds

performance analysis

When running the test, you can specify some parameters to generate the performance file 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.

Use the following command to generate the CPU profile:

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

Under the current directory, it should generatecpu.outDocument andutil.testDocuments.

Use the following command to observe the time-consuming operation:

#Enter interactive mode
go tool pprof cpu.out
top

After you install graphviz, you can generate a visual analysis diagram

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

Test coverage

[email protected]:/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

[email protected]:/workspace# go tool cover -func=cover.out
tzh.com/web/util/util.go:12:    GenShortID      100.0%
tzh.com/web/util/util.go:17:    GetReqID        0.0%
tzh.com/web/util/util.go:22:    TimeToStr       0.0%
tzh.com/web/util/util.go:30:    GetTag          0.0%
total:                          (statements)    9.1%

Use-coverprofile=cover.outOption to count test coverage
Usego tool cover -func=cover.outYou can view more detailed test coverage results,
Count the test coverage of each function

summary

Testing is a very important part of development, to ensure the quality of software, must not be lazy

Code of current part

As version v0.15.0

Recommended Today

Docker learning (5) basic command of dockerfile

To learn dockerfile, you need to understand its basic commands From – base image Try to use the official reference image [x] From Tomcat: 8.5.50-jdk8-openjdk 񖓿 make reference image (based on Tomcat: 8.5.50-jdk8-openjdk) [x] From CentOS ා make a base image based on CentOS: latest [x] From scratch? Does not depend on any reference image […]