|
|
|
|
package goSyntax
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"os"
|
|
|
|
|
"testing"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Add的单元测试
|
|
|
|
|
func TestAdd(t *testing.T) {
|
|
|
|
|
// 定义测试用例
|
|
|
|
|
type item struct {
|
|
|
|
|
a, b, s uint8
|
|
|
|
|
}
|
|
|
|
|
items := []item{
|
|
|
|
|
{1, 1, 2},
|
|
|
|
|
{10, 56, 66},
|
|
|
|
|
{100, 101, 201},
|
|
|
|
|
{123, 1, 124},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 执行测试(若有错误,报告)
|
|
|
|
|
for _, v := range items {
|
|
|
|
|
s := Add(v.a, v.b)
|
|
|
|
|
if s != v.s {
|
|
|
|
|
t.Errorf("a: %d, b: %d, s: %d", v.a, v.b, s)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add 的模糊测试
|
|
|
|
|
func FuzzAdd(f *testing.F) {
|
|
|
|
|
// 一,添加测试用例种子(到语料库中)
|
|
|
|
|
// 要与测试函数Add保持一致,值随意
|
|
|
|
|
f.Add(uint8(2), uint8(3))
|
|
|
|
|
|
|
|
|
|
// 额外:将生成的模糊测试用例,写入到文件中
|
|
|
|
|
file, _ := os.OpenFile("./fuzz_input.txt", os.O_CREATE|os.O_TRUNC, 0644)
|
|
|
|
|
defer file.Close()
|
|
|
|
|
// 二,执行测试,基于模糊数据完成测试
|
|
|
|
|
f.Fuzz(func(t *testing.T, a, b uint8) {
|
|
|
|
|
// 额外,记录下a,b的值
|
|
|
|
|
|
|
|
|
|
// 实现测试
|
|
|
|
|
s := Add(a, b)
|
|
|
|
|
fmt.Fprintf(file, "a:%d, b:%d, s:%d\n", a, b, s)
|
|
|
|
|
// 模糊测试,由于数据随机生成,因此结果也是随机的
|
|
|
|
|
// 必须要找到可以判定是否结果正确的方法。
|
|
|
|
|
if s-a != b {
|
|
|
|
|
|
|
|
|
|
// 模拟可能错误的检测逻辑
|
|
|
|
|
//if int(s)-int(a) != int(b) {
|
|
|
|
|
t.Errorf("a: %d, b: %d, s: %d", a, b, s)
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
func FuzzSeed(f *testing.F) {
|
|
|
|
|
// 添加string类型的种子
|
|
|
|
|
f.Add("mashibing")
|
|
|
|
|
file, _ := os.OpenFile("./fuzz_input.txt", os.O_CREATE|os.O_TRUNC, 0666)
|
|
|
|
|
defer file.Close()
|
|
|
|
|
f.Fuzz(func(t *testing.T, s string) {
|
|
|
|
|
fmt.Fprintf(file, "%s\n", s)
|
|
|
|
|
})
|
|
|
|
|
}
|