Repository navigation
Expand file tree
/
Copy pathapi_test.go
More file actions
121 lines (89 loc) · 2.09 KB
/
Copy pathapi_test.go
File metadata and controls
121 lines (89 loc) · 2.09 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package api
import (
"bytes"
"encoding/json"
"github.com/labstack/echo"
"net/http"
"net/http/httptest"
"testing"
)
type JobsAPI struct{}
type Job struct {
Name string
}
type JobResp struct {
Jobs []Job
}
type JobReq struct {
Limit int
}
func (JobsAPI) List(c Context, r *JobReq) (*JobResp, error) {
jobs := []Job{Job{"One"}, Job{"Two"}}
return &JobResp{jobs}, nil
}
func TestServer(t *testing.T) {
e := echo.New()
s, err := NewService(&JobsAPI{})
if err != nil {
t.Error(err)
}
s.Get("/", "List")
s.Run("/jobs", e)
resp := httptest.NewRecorder()
j := JobReq{1}
b, err := json.Marshal(&j)
if err != nil {
t.Error(err)
}
data := bytes.NewReader(b)
req, err := http.NewRequest("GET", "/jobs/", data)
if err != nil {
t.Error(err)
}
e.ServeHTTP(resp, req)
if resp.Code != 200 {
t.Errorf("Response should generate status OK but got: %d", resp.Code)
}
if resp.Body == nil {
t.Error("response body was nil")
}
jResp := new(JobResp)
if err := json.NewDecoder(resp.Body).Decode(jResp); err != nil {
t.Errorf("Response should reply with jobs. Error when decoding JSON response body: %s", err.Error())
}
if len(jResp.Jobs) != 2 {
t.Error("Reponse does not match expected")
}
//fmt.Println(resp)
//fmt.Printf("%+v", resp)
}
type JobsAPIFail struct{}
func (JobsAPIFail) ListFail(c Context, r *JobReq) {
}
func TestServerFail(t *testing.T) {
_, err := NewService(&JobsAPIFail{})
if err == nil {
t.Error("Should not let method without any return values")
}
}
type JobsAPIFail2 struct{}
func (JobsAPIFail2) ListFail(c Context, r *JobReq) *JobResp {
jobs := []Job{Job{"One"}, Job{"Two"}}
return &JobResp{jobs}
}
func TestServiceIncorrectReturnSignature(t *testing.T) {
_, err := NewService(&JobsAPIFail2{})
if err == nil {
t.Error("Should not let method without return error")
}
}
type JobsAPIFail3 struct{}
func (JobsAPIFail3) ListFail(r *JobReq) error {
return nil
}
func TestServiceIncorrectMethodArgs(t *testing.T) {
_, err := NewService(&JobsAPIFail3{})
if err == nil {
t.Error("Should not allow service method without context type argument")
}
}