企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 概述 go>1.8 官方支持模糊测试 Fuzzing 是一种自动化测试,它不断地操纵程序的输入以查找错误。Go fuzzing 使用覆盖率指导来智能地遍历被模糊测试的代码,以发现并向用户报告故障。由于它可以达到人类经常错过的边缘情况,因此模糊测试对于发现安全漏洞和漏洞特别有价值 ![](https://img.kancloud.cn/b3/eb/b3eb2511c3e3996368e9e02f6e804b64_1090x408.png) 模糊测试参数只能是以下类型: * `string`,`[]byte` * `int`,`int8`,`int16`,`int32`/`rune`,`int64` * `uint`,`uint8`/`byte`,`uint16`,`uint32`,`uint64` * `float32`,`float64` * `bool` ## 实例 以 xxx_test.go 中添加 fuzzing 测试 ``` func Foo(a int, b string) (string, error) { if b == "a" { return "", errors.New("get error") } return b, nil } func FuzzFoo(f *testing.F) { f.Add(5, "hello") f.Fuzz(func(t *testing.T, i int, s string) { out, err := Foo(i, s) if err != nil && out != "" { t.Errorf("%q,%v", out, err) } }) } ``` 运行 ``` > go test -fuzz=FuzzFoo fuzz: elapsed: 0s, gathering baseline coverage: 0/128 completed fuzz: elapsed: 0s, gathering baseline coverage: 128/128 completed, now fuzzing with 12 workers fuzz: elapsed: 3s, execs: 1239647 (412614/sec), new interesting: 1 (total: 129) fuzz: elapsed: 6s, execs: 2546315 (435266/sec), new interesting: 1 (total: 129) fuzz: elapsed: 9s, execs: 3839784 (431412/sec), new interesting: 1 (total: 129) fuzz: elapsed: 12s, execs: 5107204 (423114/sec), new interesting: 1 (total: 129) ```