-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver_test.go
More file actions
97 lines (85 loc) · 2.19 KB
/
server_test.go
File metadata and controls
97 lines (85 loc) · 2.19 KB
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
// handlers_test.go
package main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
)
type Payload struct {
Fragment int
Index int
Contents string
Executing bool
Filename string
}
func defaultPayload() Payload {
return Payload{
Fragment: 0,
Index: 0,
Contents: "",
Executing: true,
Filename: "test.md",
}
}
func TestMultiply(t *testing.T) {
p := defaultPayload()
p.Contents = `fmt.Println(10 * 50)`
pm, _ := json.Marshal(p)
testHTTP(pm, t, "500")
}
func TestInlineFunc(t *testing.T) {
p := defaultPayload()
p.Contents = `fmt.Println(func() int {
return 5 + 10
}())`
pm, _ := json.Marshal(p)
testHTTP(pm, t, "15")
}
func TestMainFunc(t *testing.T) {
p := defaultPayload()
p.Contents = `
func main() {
fmt.Println("Should fail)
}`
pm, _ := json.Marshal(p)
testHTTP(pm, t, "exit status 3\nMain function is generated automatically. Please remove func main()")
}
func TestType(t *testing.T) {
p := defaultPayload()
p.Contents = `
type TestType struct {
x string
y int
}`
pm, _ := json.Marshal(p)
testHTTP(pm, t, "")
}
func testHTTP(requestBody []byte, t *testing.T, expected string) {
cells := make(map[int]*Cell)
p := &Program{TempFile: os.TempDir() + "/main.go", Cells: cells, ExecutedFilename: ""}
// Create a request to pass to our handler. We don't have any query parameters for now, so we'll
// pass 'nil' as the third parameter.
req, err := http.NewRequest("GET", "/", bytes.NewBuffer(requestBody))
if err != nil {
t.Fatal(err)
}
// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
rr := httptest.NewRecorder()
handler := http.HandlerFunc(p.ServeHTTP)
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
handler.ServeHTTP(rr, req)
// Check the status code is what we expect.
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
// Check the response body is what we expect.
if rr.Body.String() != expected {
t.Errorf("handler returned unexpected body: got %v want %v",
rr.Body.String(), expected)
}
}