-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
105 lines (86 loc) · 2.29 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"regexp"
"testing"
"time"
"github.com/fsnotify/fsnotify"
)
func TestServerSideEvent(t *testing.T) {
log.SetOutput(io.Discard)
req := httptest.NewRequest(http.MethodGet, "/.servus", nil)
res := httptest.NewRecorder()
events := make(chan fsnotify.Event, 1)
handler := serverSideEvent(log.Default(), &fsnotify.Watcher{Events: events})
go func() {
time.Sleep(250 * time.Millisecond)
events <- fsnotify.Event{
Op: fsnotify.Write,
Name: "test.html",
}
}()
handler(res, req)
if actual := res.Result().Status; actual != "200 OK" {
t.Logf("Wrong status; expected='200 OK', actual='%s'", actual)
t.Fail()
}
for key, expected := range map[string]string{
"Content-Type": "text/event-stream",
"Connection": "keep-alive",
"Cache-Control": "no-cache",
} {
if actual := res.Result().Header[key][0]; actual != expected {
t.Logf("Wrong header '%s'; expected='%s',actual='%s'", key, expected, actual)
t.Fail()
}
}
body, err := io.ReadAll(res.Result().Body)
if err != nil {
t.Fatal(err)
}
match, err := regexp.Match("data: servus pid=\\d+ WRITE \"test\\.html\"", body)
if err != nil {
t.Fatal(err)
}
if match == false {
t.Logf("Unexpected body: %s", body)
t.Fail()
}
}
func TestServeFile(t *testing.T) {
testhtml, err := os.Create("test.html")
if err != nil {
t.Log(err)
t.FailNow()
}
defer func() {
testhtml.Close()
os.Remove(testhtml.Name())
}()
htmlcontent := "<p>test.html</p>"
testhtml.Write([]byte(htmlcontent))
req := httptest.NewRequest(http.MethodGet, "/test.html", nil)
req.SetPathValue("file", "test.html")
res := httptest.NewRecorder()
handler := serveFile(log.Default())
handler(res, req)
if actual := res.Result().Status; actual != "200 OK" {
t.Logf("Wrong status; expected='200 OK', actual='%s'", actual)
t.Fail()
}
body, err := io.ReadAll(res.Result().Body)
if err != nil {
t.Logf("Cannot read response body, err=%s", err)
t.FailNow()
}
expectedBody := fmt.Sprintf(`%s<script> new EventSource(".servus").onmessage = function(ev){ console.log(ev); window.location.reload();}</script>`, htmlcontent)
if string(body) != expectedBody {
t.Logf("Wrong response body\nexpected:\n%s\n=====\nactual:\n%s", expectedBody, body)
t.FailNow()
}
}