16 소프트웨어 테스팅

1. 단위 테스트

명령go test 에 따라 패키지 디렉토리에서 접미사가 있는 모든 소스 코드 파일은 테스트의 일부 입니다.test.gogo 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.wrk 압력 측정 도구

추천

출처blog.csdn.net/pointerz_zyz/article/details/123649036