1.単体テスト
コマンドに応じて、パッケージ ディレクトリ内のサフィックスが付いたすべてのソース コード ファイルがテストの一部になります。go test
test.go
go test
タイプ | フォーマット | 効果 |
---|---|---|
テスト機能 | 関数名には「Test」という接頭辞が付きます。 | プログラムの論理的な動作が正しいかどうかをテストする |
ベンチマーク関数 | 関数名には Benchmark という接頭辞が付きます | テスト機能のパフォーマンス |
関数の例 | 関数名には Example という接頭辞が付きます。 | ドキュメントのサンプルドキュメントを提供する |
1. 定期テスト
package calc
import (
"testing"
)
func Test1Add(t *testing.T) {
ret := Add(1, 2) //程序输出结果
want := 3 //期望结果
if ret != want {
t.Errorf("测试用例执行失败![期望值:%v 实际值:%v]\n", want, ret)
}
}
func Test2Add(t *testing.T) {
ret := Add(2, 2) //程序输出结果
want := 4 //期望结果
if ret != want {
t.Errorf("测试用例执行失败![期望值:%v 实际值:%v]\n", want, ret)
}
}
2. テストグループ
package calc
import (
"testing"
)
func TestAdd(t *testing.T) {
type testCase struct {
a int
b int
ret int
}
testGroup := []testCase{
testCase{
1, 2, 3},
testCase{
-1, 2, 1},
testCase{
0, 2, 2},
}
for _, tc := range testGroup {
ret := Add(tc.a, tc.b)
if ret != tc.ret {
t.Errorf("测试用例执行失败![期望值:%v 实际值:%v]\n", tc.ret, ret)
}
}
}
3. サブテスト
package calc
import (
"testing"
)
func TestAdd(t *testing.T) {
type testCase struct {
a int
b int
ret int
}
testGroup := map[string]testCase{
"case_1": testCase{
1, 2, 3},
"case_2": testCase{
-1, 2, 1},
"case_3": testCase{
0, 2, 2},
}
for name, tc := range testGroup {
t.Run(name, func(t *testing.T) {
ret := Add(tc.a, tc.b)
if ret != tc.ret {
t.Errorf("测试用例执行失败![期望值:%v 实际值:%v]\n", tc.ret, ret)
}
})
}
}
2. ベンチマークテスト
一定の負荷下でプログラムのパフォーマンスをテストする方法
package calc
import (
"testing"
)
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(1, 2)
}
}
go test -bench=Add
出力結果:
goos: windows
goarch: amd64
pkg: zyz.test.com/calc
cpu: AMD Ryzen 5 5600X 6-Core Processor
BenchmarkAdd-12 1000000000 0.2230 ns/op
PASS
ok zyz.test.com/calc 0.741s
3. パフォーマンスチューニング
func main() {
cpufile, err := os.Create("./cpu.pprof")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
pprof.StartCPUProfile(cpufile)
pprof.WriteHeapProfile(cpufile)
defer pprof.StopCPUProfile()
defer cpufile.Close()
}
pprof は以下を使用します。
# go tool pprof .\cpu.pprof
Type: inuse_space
Time: Mar 21, 2022 at 10:57pm (CST)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top3
Showing nodes accounting for 2787.64kB, 100% of 2787.64kB total
Showing top 3 nodes out of 16
flat flat% sum% cum cum%
1762.94kB 63.24% 63.24% 1762.94kB 63.24% runtime/pprof.StartCPUProfile
512.50kB 18.38% 81.63% 512.50kB 18.38% runtime.allocm
512.20kB 18.37% 100% 512.20kB 18.37% runtime.malg
(pprof)
拡大:
1. インストールgraphviz
ツールをグラフィカルに表示可能
2. go-torchとFlameGraphでフレームグラフを描画可能
3.血圧測定ツール