-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser_test.go
More file actions
107 lines (75 loc) · 2.52 KB
/
user_test.go
File metadata and controls
107 lines (75 loc) · 2.52 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
package main
import (
"net/http"
"testing"
"github.com/karthikbhandary2/Social/internal/store/cache"
"github.com/stretchr/testify/mock"
)
func TestGetUser(t *testing.T) {
withRedis := config{
redisCfg: redisConfig{
enabled: true,
},
}
app := newTestApplication(t, withRedis)
mux := app.mount()
testToken, err := app.authenticator.GenerateToken(nil)
if err != nil {
t.Fatal(err)
}
t.Run("should not allow unauthenticated requests", func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "/v1/users/1", nil)
if err != nil {
t.Fatal(err)
}
rr := executeRequest(req, mux)
checkResponseCode(t, http.StatusUnauthorized, rr.Code)
})
t.Run("should allow authenticated requests", func(t *testing.T) {
mockCacheStore := app.cacheStorage.Users.(*cache.MockUserStore)
mockCacheStore.On("Get", int64(1)).Return(nil, nil).Twice()
mockCacheStore.On("Set", mock.Anything).Return(nil)
req, err := http.NewRequest(http.MethodGet, "/v1/users/1", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+testToken)
rr := executeRequest(req, mux)
checkResponseCode(t, http.StatusOK, rr.Code)
mockCacheStore.Calls = nil // Reset mock expectations
})
t.Run("should hit the cache first and if not exists it sets the user on the cache", func(t *testing.T) {
mockCacheStore := app.cacheStorage.Users.(*cache.MockUserStore)
mockCacheStore.On("Get", int64(42)).Return(nil, nil)
mockCacheStore.On("Get", int64(1)).Return(nil, nil)
mockCacheStore.On("Set", mock.Anything, mock.Anything).Return(nil)
req, err := http.NewRequest(http.MethodGet, "/v1/users/1", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+testToken)
rr := executeRequest(req, mux)
checkResponseCode(t, http.StatusOK, rr.Code)
mockCacheStore.AssertNumberOfCalls(t, "Get", 2)
mockCacheStore.Calls = nil // Reset mock expectations
})
t.Run("should NOT hit the cache if it is not enabled", func(t *testing.T) {
withRedis := config{
redisCfg: redisConfig{
enabled: false,
},
}
app := newTestApplication(t, withRedis)
mux := app.mount()
mockCacheStore := app.cacheStorage.Users.(*cache.MockUserStore)
req, err := http.NewRequest(http.MethodGet, "/v1/users/1", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+testToken)
rr := executeRequest(req, mux)
checkResponseCode(t, http.StatusOK, rr.Code)
mockCacheStore.AssertNotCalled(t, "Get")
mockCacheStore.Calls = nil // Reset mock expectations
})
}