GO·NOTE

一份 Go 开发工程师的学习笔记

0%

测试代码如何写的更好?

1、结果输出在代码下面

1
2
3
4
5
6
7
8
9
func ExampleHasPrefix() {
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
// Output:
// true
// false
// true
}

2、方法、参数、错误都打印出来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func TestNonpollableDeadline(t *testing.T) {
// On BSD systems regular files seem to be pollable,
// so just run this test on Linux.
if runtime.GOOS != "linux" {
t.Skipf("skipping on %s", runtime.GOOS)
}

f, err := ioutil.TempFile("", "ostest")
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
defer f.Close()
deadline := time.Now().Add(10 * time.Second)
if err := f.SetDeadline(deadline); err != os.ErrNoDeadline {
t.Errorf("SetDeadline on file returned %v, wanted %v", err, os.ErrNoDeadline)
}
if err := f.SetReadDeadline(deadline); err != os.ErrNoDeadline {
t.Errorf("SetReadDeadline on file returned %v, wanted %v", err, os.ErrNoDeadline)
}
if err := f.SetWriteDeadline(deadline); err != os.ErrNoDeadline {
t.Errorf("SetWriteDeadline on file returned %v, wanted %v", err, os.ErrNoDeadline)
}
}

WaitGroup() 的wait 可以直接用defer实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

// TestRacyRead tests that it is safe to mutate the input Read buffer
// immediately after cancellation has occurred.
func TestRacyRead(t *testing.T) {
t.Parallel()

r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer r.Close()
defer w.Close()

var wg sync.WaitGroup
defer wg.Wait()

go io.Copy(w, rand.New(rand.NewSource(0)))

r.SetReadDeadline(time.Now().Add(time.Millisecond))
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()

b1 := make([]byte, 1024)
b2 := make([]byte, 1024)
for j := 0; j < 100; j++ {
_, err := r.Read(b1)
copy(b1, b2) // Mutate b1 to trigger potential race
if err != nil {
if !os.IsTimeout(err) {
t.Error(err)
}
r.SetReadDeadline(time.Now().Add(time.Millisecond))
}
}
}()
}
}