Neither one nor Many

 
December 18 2018

Testing and coverage

Source: https://blog.alexellis.io/golang-writing-unit-tests/

  • go test
  • go test -cover

    go test -cover -coverprofile=c.out go tool cover -html=c.out -o coverage.html

If you have main.go, add main_test.go:

package main

import "testing"

func TestSum(t *testing.T) {
    total := Sum(5, 5)
    if total != 10 {
       t.Errorf("Sum was incorrect, got: %d, want: %d.", total, 10)
    }
}

More info here: https://golang.org/pkg/testing/

Profiling

Source: https://blog.golang.org/profiling-go-programs (by Ross Cox)

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func main() {
    flag.Parse()
    if *cpuprofile != "" {
        f, err := os.Create(*cpuprofile)
        if err != nil {
            log.Fatal(err)
        }
        pprof.StartCPUProfile(f)
        defer pprof.StopCPUProfile()
    }

Build an capture profiling data

  • go build && ./myprogram -cpuprofile=my.prof
  • go tool pprof myprogram my.prof

Commands available are:

  • top5
  • top10
  • top10 -cum
  • list main
  • list myfoobar.function.func1

There are also very similar flags for memory profiling. I didn't try this myself yet, check the blog I got this from in the first place.

Cheatsheets Comments (0)


Leave a Reply

Comment may not be visible immediately, because I process everything manually.**

**) I plan to automate this.., but it's on my ToDo since for ever..


Author:
Ray Burgemeestre
february 23th, 1984

Topics:
C++, Linux, Webdev

Other interests:
Music, Art, Zen