-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthorization_test.go
95 lines (86 loc) · 2.57 KB
/
authorization_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
94
95
package http_handlers
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
http_common "github.com/surahman/mcq-platform/pkg/http"
"github.com/surahman/mcq-platform/pkg/mocks"
)
func TestAuthMiddleware(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockAuth := mocks.NewMockAuth(mockCtrl)
handler := AuthMiddleware(mockAuth, "Authorization")
require.NotNil(t, handler)
}
func TestAuthMiddleware_Handler(t *testing.T) {
router := http_common.GetTestRouter()
testCases := []struct {
name string
path string
token string
expectedStatus int
authValidateJWTData *http_common.MockAuthData
}{
// ----- test cases start ----- //
{
name: "no token",
path: "/no-token",
token: "",
expectedStatus: http.StatusUnauthorized,
authValidateJWTData: &http_common.MockAuthData{
OutputParam1: "",
OutputParam2: int64(-1),
OutputErr: nil,
Times: 0,
},
}, {
name: "invalid token",
path: "/invalid-token",
token: "invalid-token",
expectedStatus: http.StatusForbidden,
authValidateJWTData: &http_common.MockAuthData{
OutputParam1: "",
OutputParam2: int64(-1),
OutputErr: errors.New("JWT validation failure"),
Times: 1,
},
}, {
name: "valid token",
path: "/valid-token",
token: "valid-token",
expectedStatus: http.StatusOK,
authValidateJWTData: &http_common.MockAuthData{
OutputParam1: "",
OutputParam2: int64(-1),
OutputErr: nil,
Times: 1,
},
},
// ----- test cases end ----- //
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
// Mock configurations.
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockAuth := mocks.NewMockAuth(mockCtrl)
mockAuth.EXPECT().ValidateJWT(gomock.Any()).Return(
testCase.authValidateJWTData.OutputParam1,
testCase.authValidateJWTData.OutputParam2,
testCase.authValidateJWTData.OutputErr,
).Times(testCase.authValidateJWTData.Times)
// Endpoint setup for test.
router.POST(testCase.path, AuthMiddleware(mockAuth, "Authorization"))
req, _ := http.NewRequest("POST", testCase.path, nil)
req.Header.Set("Authorization", testCase.token)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
// Verify responses
require.Equal(t, testCase.expectedStatus, w.Code, "expected status codes do not match")
})
}
}