-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
116 lines (104 loc) · 2.39 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
106
107
108
109
110
111
112
113
114
115
116
package main_test
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"testing"
"github.com/whytheplatypus/reagent/experiment"
)
var (
things = []map[string]interface{}{}
ts *httptest.Server
)
func TestCRUD(t *testing.T) {
vars := map[string]string{
"host": ts.URL,
}
trial, err := experiment.NewTrial("crud", vars, "examples/crud.yaml")
if err != nil {
t.Fatal(err)
}
if err := trial.Run(); err != nil {
t.Fatal(err)
}
}
func TestMain(m *testing.M) {
ts = configureServer()
defer ts.Close()
// call flag.Parse() here if TestMain uses flags
live := flag.Bool("live", false, "keep the test server alive")
flag.Parse()
if *live {
fmt.Println(ts.URL)
waitFor(syscall.SIGINT, syscall.SIGTERM)
}
os.Exit(m.Run())
}
func waitFor(calls ...os.Signal) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, calls...)
<-sigs
}
func handleThings(rw http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
d := json.NewDecoder(r.Body)
defer r.Body.Close()
var t map[string]interface{}
if err := d.Decode(&t); err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
things = append(things, t)
rw.Header().Set("Content-Type", "application/json")
fmt.Fprintf(rw, "{\"id\": %d}", len(things)-1)
default:
http.Error(rw, "unsupported", http.StatusMethodNotAllowed)
}
}
func handleThing(rw http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(strings.Split(r.URL.Path, "/")[2])
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if len(things) < id+1 {
http.NotFound(rw, r)
return
}
t := things[id]
switch r.Method {
case http.MethodGet:
res, err := json.Marshal(t)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(rw, "%s", string(res))
case http.MethodDelete:
things = append(things[:id], things[id+1:]...)
rw.WriteHeader(http.StatusCreated)
default:
http.Error(rw, "unsupported", http.StatusMethodNotAllowed)
}
}
func configureServer() *httptest.Server {
r := http.NewServeMux()
r.HandleFunc("/things/", func(rw http.ResponseWriter, r *http.Request) {
switch idPart := strings.Split(r.URL.Path, "/")[2]; idPart {
case "":
handleThings(rw, r)
default:
handleThing(rw, r)
}
})
ts := httptest.NewServer(r)
return ts
}