-
Notifications
You must be signed in to change notification settings - Fork 0
/
procedure_test.go
93 lines (79 loc) · 2.63 KB
/
procedure_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
package ferry
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func (t testService) TestProcedureWithoutParams(ctx context.Context, r *empty) (*testPayload, error) {
return &testPayload{Value: "test_data"}, nil
}
func (t testService) TestProcedureWithParams(ctx context.Context, r *jsonRequest) (*testPayload, error) {
return &testPayload{Value: r.Value}, nil
}
func TestProcedure(t *testing.T) {
t.Run("returns response without request params", func(t *testing.T) {
t.Parallel()
router := NewRouter()
svc := testService{}
router.Register(Procedure(svc.TestProcedureWithoutParams))
rr := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/TestProcedureWithoutParams", nil)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r = r.WithContext(ctx)
router.ServeHTTP(rr, r)
content := rr.Body.Bytes()
expected := `{"value":"test_data"}`
if string(content) != expected {
t.Errorf("unexpected response, got %s", content)
}
})
t.Run("returns response with request params", func(t *testing.T) {
t.Parallel()
router := NewRouter()
svc := testService{}
router.Register(Procedure(svc.TestProcedureWithParams))
payload, err := json.Marshal(&jsonRequest{Value: "test_data"})
if err != nil {
t.Errorf("unexpected error: %v", err)
}
rr := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/TestProcedureWithParams", bytes.NewReader(payload))
r.Header.Set("Content-Type", "application/json")
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r = r.WithContext(ctx)
router.ServeHTTP(rr, r)
if rr.Code != http.StatusOK {
t.Errorf("unexpected response code, got %d", rr.Code)
}
content := rr.Body.Bytes()
expected := `{"value":"test_data"}`
if string(content) != expected {
t.Errorf("unexpected response, got %s", content)
}
if rr.Header().Get("Content-Type") != "application/json; charset=utf-8" {
t.Errorf("unexpected content type, got %s", rr.Header().Get("Content-Type"))
}
})
t.Run("returns error if request params invalid", func(t *testing.T) {
t.Parallel()
router := NewRouter()
svc := testService{}
router.Register(Procedure(svc.TestProcedureWithParams))
rr := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/TestProcedureWithParams", nil)
r.Header.Set("Content-Type", "application/json")
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r = r.WithContext(ctx)
router.ServeHTTP(rr, r)
if rr.Code != http.StatusBadRequest {
t.Errorf("unexpected response code, got %d", rr.Code)
}
})
}