如何在Golang中为cmd工具编写基准测试?

时间:2019-03-21 03:29:45

标签: go benchmarking

当我说cmd工具时,我的意思是这样的工具程序:

var (
    m           = flag.String("m", "GET", "")
    headers     = flag.String("h", "", "")
    body        = flag.String("d", "", "")
    contentType = flag.String("T", "text/html", "")
    ......
)

func main() {
    // Using args above, create complex logics
}

我不能只在我的Benchmark()中调用main()。

有什么办法吗?

还是我必须用args重写一个函数以供Benchmark()调用?

1 个答案:

答案 0 :(得分:3)

优良作法是使main()尽可能短,并将所有实际工作委托给一个函数/方法,这使得它可以进行测试和基准测试。可能看起来像

// main.go
// go run main.go -h "Content-Type: application/json" -h "X-Request-ID: 12345" -d "Hello"
package main

import (
    "flag"
    "fmt"
    "io"
    "log"
    "strings"
)

type headers map[string]string

func (h headers) String() string {
    hdr := make([]string, 0)
    for k, v := range map[string]string(h) {
        hdr = append(hdr, fmt.Sprintf("%s: %s", k, v))
    }
    return strings.Join(hdr, ",")
}
func (h headers) Set(value string) error {
    i := strings.Index(value, ":")
    if i < 1 {
        return fmt.Errorf("invalid header '%s'", value)
    }
    h[value[0:i]] = strings.TrimSpace(value[i+1:])
    return nil
}

var (
    method string
    hdrs   = make(headers)
    body   string
)

func init() {
    flag.StringVar(&method, "m", "GET", "Method")
    flag.Var(hdrs, "h", "Headers")
    flag.StringVar(&body, "d", "", "Body")
    flag.Parse()
}

func main() {
    err := run(method, hdrs, strings.NewReader(body))
    if err != nil {
        log.Fatal(err)
    }
}

func run(method string, headers headers, body io.Reader) error {
    // implement your logic here
    return nil
}

和您的基准

// main_test.go
package main

import (
    "strings"
    "testing"
)

func BenchmarkRun1(b *testing.B) {
    hdrs := headers{"Content-Type": "application/json", "Accept": "appication/json"}
    body := "Hello World"
    for i := 0; i < b.N; i++ {
        run("GET", hdrs, strings.NewReader(body))
    }
}