Browse code

fix racy test in pkg/plugins

Signed-off-by: Akihiro Suda <suda.akihiro@lab.ntt.co.jp>

Akihiro Suda authored on 2016/09/13 11:38:41
Showing 1 changed files
... ...
@@ -31,24 +31,30 @@ func teardownRemotePluginServer() {
31 31
 	}
32 32
 }
33 33
 
34
-func TestHttpTimeout(t *testing.T) {
34
+func testHTTPTimeout(t *testing.T, timeout, epsilon time.Duration) {
35 35
 	addr := setupRemotePluginServer()
36 36
 	defer teardownRemotePluginServer()
37
-	stop := false // we need this variable to stop the http server
37
+	stop := make(chan struct{}) // we need this variable to stop the http server
38 38
 	mux.HandleFunc("/hang", func(w http.ResponseWriter, r *http.Request) {
39
-		for {
40
-			if stop {
41
-				break
42
-			}
43
-			time.Sleep(5 * time.Second)
44
-		}
39
+		<-stop
45 40
 	})
46 41
 	c, _ := NewClient(addr, &tlsconfig.Options{InsecureSkipVerify: true})
42
+	c.http.Timeout = timeout
43
+	begin := time.Now()
47 44
 	_, err := c.callWithRetry("hang", nil, false)
48
-	stop = true
45
+	close(stop)
49 46
 	if err == nil || !strings.Contains(err.Error(), "request canceled") {
50 47
 		t.Fatalf("The request should be canceled %v", err)
51 48
 	}
49
+	elapsed := time.Now().Sub(begin)
50
+	if elapsed < timeout || elapsed > timeout+epsilon {
51
+		t.Fatalf("elapsed time: got %v, expected %v (epsilon=%v)",
52
+			elapsed, timeout, epsilon)
53
+	}
54
+}
55
+
56
+func TestHTTPTimeout(t *testing.T) {
57
+	testHTTPTimeout(t, 5*time.Second, 1*time.Second)
52 58
 }
53 59
 
54 60
 func TestFailedConnection(t *testing.T) {