1
2
3
4
5 package race_test
6
7 import (
8 "fmt"
9 "net"
10 "net/http"
11 "os"
12 "path/filepath"
13 "sync"
14 "testing"
15 "time"
16 )
17
18 func TestNoRaceIOFile(t *testing.T) {
19 x := 0
20 path := t.TempDir()
21 fname := filepath.Join(path, "data")
22 go func() {
23 x = 42
24 f, _ := os.Create(fname)
25 f.Write([]byte("done"))
26 f.Close()
27 }()
28 for {
29 f, err := os.Open(fname)
30 if err != nil {
31 time.Sleep(1e6)
32 continue
33 }
34 buf := make([]byte, 100)
35 count, err := f.Read(buf)
36 if count == 0 {
37 time.Sleep(1e6)
38 continue
39 }
40 break
41 }
42 _ = x
43 }
44
45 var (
46 regHandler sync.Once
47 handlerData int
48 )
49
50 func TestNoRaceIOHttp(t *testing.T) {
51 regHandler.Do(func() {
52 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
53 handlerData++
54 fmt.Fprintf(w, "test")
55 handlerData++
56 })
57 })
58 ln, err := net.Listen("tcp", "127.0.0.1:0")
59 if err != nil {
60 t.Fatalf("net.Listen: %v", err)
61 }
62 defer ln.Close()
63 go http.Serve(ln, nil)
64 handlerData++
65 _, err = http.Get("http://" + ln.Addr().String())
66 if err != nil {
67 t.Fatalf("http.Get: %v", err)
68 }
69 handlerData++
70 _, err = http.Get("http://" + ln.Addr().String())
71 if err != nil {
72 t.Fatalf("http.Get: %v", err)
73 }
74 handlerData++
75 }
76
View as plain text