-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
87 lines (70 loc) · 2.08 KB
/
server_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
package signup
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
type MockSignupService struct {
RegisterFunc func(context.Context, Signup) (Signup, error)
}
func (m *MockSignupService) register(ctx context.Context, signup Signup) (Signup, error) {
return m.RegisterFunc(ctx, signup)
}
func TestHandleSignup(t *testing.T) {
t.Run("can register valid users", func(t *testing.T) {
signup := Signup{
NameFirst: "Henri",
NameLast: "Testaroni",
Email: "[email protected]",
Cell: "555-123-4567",
Referrer: "instagram",
ReferrerResponse: "",
}
service := &MockSignupService{
RegisterFunc: func(ctx context.Context, su Signup) (Signup, error) {
return su, nil
},
}
server := &signupServer{service}
req := httptest.NewRequest(http.MethodPost, "/", signupToJson(t, signup))
req.Header.Set("Content-Type", "application/json")
res := httptest.NewRecorder()
server.HandleSignUp(res, req)
require.Equal(t, http.StatusCreated, res.Code)
})
t.Run("responds with the generated info URL", func(t *testing.T) {
signup := Signup{
NameFirst: "Henri",
NameLast: "Testaroni",
Email: "[email protected]",
Cell: "555-123-4567",
Referrer: "tiktok",
ReferrerResponse: "",
}
service := &MockSignupService{
RegisterFunc: func(ctx context.Context, su Signup) (Signup, error) {
su.ShortLink = "https://ospk.org/abcd1234"
return su, nil
},
}
server := &signupServer{service}
req := httptest.NewRequest(http.MethodPost, "/", signupToJson(t, signup))
req.Header.Set("Content-Type", "application/json")
res := httptest.NewRecorder()
server.HandleSignUp(res, req)
require.Equal(t, http.StatusCreated, res.Code)
require.JSONEq(t, `{"url":"https://ospk.org/abcd1234"}`, res.Body.String())
})
}
func signupToJson(t *testing.T, signup Signup) io.Reader {
b, err := json.Marshal(signup)
if err != nil {
t.Fatalf("marshall json: %v", err)
}
return bytes.NewReader(b)
}