/
annict_server.go
83 lines (73 loc) · 1.86 KB
/
annict_server.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
package testutil
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
testing "github.com/mitchellh/go-testing-interface"
)
var root string
// RunAnnictServer runs a dummy Annict server for testing and returns the server address.
func RunAnnictServer(t testing.T, codeDecider map[string]int) (addr string) {
var buf bytes.Buffer
cmd := exec.Command("git", "rev-parse", "--show-cdup")
cmd.Stdout = &buf
if err := cmd.Run(); err != nil {
t.Fatal(err)
}
root = strings.TrimSpace(buf.String())
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
s := string(b)
for name, code := range codeDecider {
if strings.Contains(s, name) {
w.WriteHeader(code)
return
}
}
switch {
case strings.Contains(s, "GetWork"):
copyFile(t, w, "get_work_response")
case strings.Contains(s, "GetProfile"):
copyFile(t, w, "get_profile_response")
case strings.Contains(s, "ListWorks"):
copyFile(t, w, "list_works_response")
case strings.Contains(s, "listRecords"):
copyFile(t, w, "list_records_response")
case strings.Contains(s, "ListNextEpisodes"):
copyFile(t, w, "list_next_episodes_response")
case strings.Contains(s, "CreateRecordMutation"),
strings.Contains(s, "UpdateStatusMutation"):
if _, err := io.WriteString(w, `{"data": {}}`); err != nil {
t.Fatal(err)
}
default:
t.Error("unknown query")
}
})
srv := httptest.NewServer(h)
t.Cleanup(srv.Close)
return srv.URL
}
func copyFile(t testing.T, w io.Writer, fname string) {
f, err := os.Open(filepath.Join(root, "testutil", "testdata", fname))
if err != nil {
t.Error(err)
return
}
defer f.Close()
if _, err := io.Copy(w, f); err != nil {
t.Error(err)
return
}
}