forked from RevathiManiraj/example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
87 lines (69 loc) · 2.08 KB
/
main_test.go
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// statusHandler is an http.Handler that writes an empty response using itself
// as the response status code.
type statusHandler int
func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(int(*h))
}
func TestIsTagged(t *testing.T) {
// Set up a fake "Google Code" web server reporting 404 not found.
status := statusHandler(http.StatusNotFound)
s := httptest.NewServer(&status)
defer s.Close()
if isTagged(s.URL) {
t.Fatal("isTagged == true, want false")
}
// Change fake server status to 200 OK and try again.
status = http.StatusOK
if !isTagged(s.URL) {
t.Fatal("isTagged == false, want true")
}
}
func TestIntegration(t *testing.T) {
status := statusHandler(http.StatusNotFound)
ts := httptest.NewServer(&status)
defer ts.Close()
// Replace the pollSleep with a closure that we can block and unblock.
sleep := make(chan bool)
pollSleep = func(time.Duration) {
sleep <- true
sleep <- true
}
// Replace pollDone with a closure that will tell us when the poller is
// exiting.
done := make(chan bool)
pollDone = func() { done <- true }
// Put things as they were when the test finishes.
defer func() {
pollSleep = time.Sleep
pollDone = func() {}
}()
s := NewServer("1.x", ts.URL, 1*time.Millisecond)
<-sleep // Wait for poll loop to start sleeping.
// Make first request to the server.
r, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
if b := w.Body.String(); !strings.Contains(b, "No.") {
t.Fatalf("body = %s, want no", b)
}
status = http.StatusOK
<-sleep // Permit poll loop to stop sleeping.
<-done // Wait for poller to see the "OK" status and exit.
// Make second request to the server.
w = httptest.NewRecorder()
s.ServeHTTP(w, r)
if b := w.Body.String(); !strings.Contains(b, "YES!") {
t.Fatalf("body = %q, want yes", b)
}
}