-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathemail_handler_test.go
More file actions
319 lines (288 loc) · 11.1 KB
/
Copy pathemail_handler_test.go
File metadata and controls
319 lines (288 loc) · 11.1 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// Copyright 2026-2030 Aptlogica Technologies Pvt Ltd
// Licensed under the Apache License, Version 2.0
// Websites: https://www.aptlogica.com | https://www.serenibase.com
// Support: support@aptlogica.com | support@serenibase.com
package test
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/aptlogica/sereni-email-smtp/internal/email"
"github.com/aptlogica/sereni-email-smtp/internal/handlers"
"github.com/gin-gonic/gin"
)
type fakeService struct {
sendErr error
}
func (f *fakeService) SendTransactionalEmail(req *email.EmailRequest) error { return f.sendErr }
func (f *fakeService) SendBulkEmail(recipients []string, subject, body string, isHTML bool) ([]string, error) {
// treat invalid emails as failed
var failed []string
for _, r := range recipients {
if !email.IsValidEmail(r) {
failed = append(failed, r)
}
}
return failed, nil
}
func (f *fakeService) GenerateAndSendOTP(to string, expiryMinutes int) (string, error) {
return "123456", nil
}
func (f *fakeService) VerifyOTP(emailAddr, otp string) bool { return otp == "good" }
func setupRouter(s *fakeService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
h := handlers.NewEmailHandler(&email.EmailService{})
// replace service with our fake via type assertion
h.Service = &email.EmailService{}
// But tests call handler methods directly with context, so we'll set Service to an email service wrapper
// Instead, set the methods via embedding - easiest is to assign the actual interface methods via closures
// For brevity, we'll construct handler and set Service to a minimal service and use function injection where needed
return r
}
func TestSendEmail_BadJSON(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
es.SendEmailFunc = func(to []string, subject, body string, isHTML bool) error { return nil }
h := handlers.NewEmailHandler(es)
// Provide invalid JSON body
req := httptest.NewRequest("POST", "/", bytes.NewBufferString("{bad json"))
c.Request = req
h.SendEmail(c)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("expected 400 got %d", recorder.Code)
}
}
func TestSendBulkEmail_WithInvalidEmails(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
es.SendEmailFunc = func(to []string, subject, body string, isHTML bool) error { return nil }
h := handlers.NewEmailHandler(es)
body := email.BulkEmailRequest{Recipients: []string{"a@b.com", "bad"}, Subject: "s", Body: "b"}
b, _ := json.Marshal(body)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.SendBulkEmail(c)
if recorder.Code != http.StatusOK {
t.Fatalf("expected 200 got %d", recorder.Code)
}
// decode and assert response contains failed emails
var resp map[string]interface{}
if err := json.Unmarshal(recorder.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to parse response: %v", err)
}
if fe, ok := resp["failed_emails"]; !ok || fe == nil {
t.Fatalf("expected failed_emails in response")
}
}
func TestGenerateOTPAndVerify(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
es.SendEmailFunc = func(to []string, subject, body string, isHTML bool) error { return nil }
h := handlers.NewEmailHandler(es)
// Generate OTP with valid JSON
genBody := map[string]interface{}{"to": "a@b.com", "expiry": 1}
b, _ := json.Marshal(genBody)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.GenerateOTP(c)
if recorder.Code != http.StatusOK {
t.Fatalf("expected 200 got %d", recorder.Code)
}
// Now test SendEmail via handler - transactional
recorder = httptest.NewRecorder()
c, _ = gin.CreateTestContext(recorder)
tr := email.EmailRequest{To: []string{"a@b.com"}, Subject: "s", Body: "b"}
tb, _ := json.Marshal(tr)
req = httptest.NewRequest("POST", "/", bytes.NewBuffer(tb))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.SendEmail(c)
if recorder.Code != http.StatusOK {
t.Fatalf("expected transactional handler 200 got %d", recorder.Code)
}
// Create OTP via service and verify via handler
otp, err := es.GenerateAndSendOTP("a@b.com", 1)
if err != nil {
t.Fatalf("generate otp failed: %v", err)
}
// Verify OTP
verifier := map[string]string{"email": "a@b.com", "otp": otp}
vb, _ := json.Marshal(verifier)
recorder = httptest.NewRecorder()
c, _ = gin.CreateTestContext(recorder)
req = httptest.NewRequest("POST", "/", bytes.NewBuffer(vb))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.VerifyOTP(c)
if recorder.Code != http.StatusOK {
t.Fatalf("expected verify 200 got %d", recorder.Code)
}
}
func TestHealthCheck(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
h := handlers.NewEmailHandler(&email.EmailService{})
h.HealthCheck(c)
if recorder.Code != http.StatusOK {
t.Fatalf("expected 200 got %d", recorder.Code)
}
}
func TestSendEmail_TemplateCausesServerError(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
// Make SendEmail return error so SendTransactionalEmail returns error
es.SendEmailFunc = func(to []string, subject, body string, isHTML bool) error { return errors.New("send failed") }
h := handlers.NewEmailHandler(es)
// Provide valid JSON with subject/body so binding succeeds and SendTransactionalEmail calls SendEmail
reqBody := map[string]interface{}{"to": []string{"a@b.com"}, "subject": "s", "body": "b"}
b, _ := json.Marshal(reqBody)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.SendEmail(c)
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 got %d", recorder.Code)
}
}
func TestSendBulkEmail_BadJSONReturns400(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
es.SendEmailFunc = func(to []string, subject, body string, isHTML bool) error { return nil }
h := handlers.NewEmailHandler(es)
req := httptest.NewRequest("POST", "/", bytes.NewBufferString("{badjson"))
c.Request = req
h.SendBulkEmail(c)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("expected 400 got %d", recorder.Code)
}
}
func TestGenerateOTP_DefaultExpiry(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
es.SendEmailFunc = func(to []string, subject, body string, isHTML bool) error { return nil }
h := handlers.NewEmailHandler(es)
// Omit expiry to rely on default
reqBody := map[string]interface{}{"to": "a@b.com"}
b, _ := json.Marshal(reqBody)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.GenerateOTP(c)
if recorder.Code != http.StatusOK {
t.Fatalf("expected 200 got %d", recorder.Code)
}
}
func TestVerifyOTP_Unauthorized(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
es.SendEmailFunc = func(to []string, subject, body string, isHTML bool) error { return nil }
h := handlers.NewEmailHandler(es)
// Verify with a non-existent OTP
reqBody := map[string]string{"email": "a@b.com", "otp": "wrong"}
b, _ := json.Marshal(reqBody)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.VerifyOTP(c)
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 got %d", recorder.Code)
}
// assert response message contains expected text
var resp map[string]interface{}
if err := json.Unmarshal(recorder.Body.Bytes(), &resp); err == nil {
if msg, ok := resp["message"]; !ok || msg == "" {
t.Fatalf("expected error message in response")
}
}
}
func TestSendBulkEmail_AllSuccess(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
es.SendEmailFunc = func(to []string, subject, body string, isHTML bool) error { return nil }
h := handlers.NewEmailHandler(es)
body := email.BulkEmailRequest{Recipients: []string{"a@b.com", "c@d.com"}, Subject: "s", Body: "b"}
b, _ := json.Marshal(body)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.SendBulkEmail(c)
if recorder.Code != http.StatusOK {
t.Fatalf("expected 200 got %d", recorder.Code)
}
var resp email.EmailResponse
if err := json.Unmarshal(recorder.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to parse response: %v", err)
}
if !resp.Success {
t.Fatalf("expected success true for all-success bulk")
}
if len(resp.FailedEmails) != 0 {
t.Fatalf("expected no failed emails, got: %v", resp.FailedEmails)
}
}
func TestSendEmail_SuccessResponseBody(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
es.SendEmailFunc = func(to []string, subject, body string, isHTML bool) error { return nil }
h := handlers.NewEmailHandler(es)
tr := email.EmailRequest{To: []string{"a@b.com"}, Subject: "s", Body: "b"}
tb, _ := json.Marshal(tr)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(tb))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.SendEmail(c)
if recorder.Code != http.StatusOK {
t.Fatalf("expected 200 got %d", recorder.Code)
}
var resp map[string]interface{}
if err := json.Unmarshal(recorder.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to parse response: %v", err)
}
if success, ok := resp["success"].(bool); !ok || !success {
t.Fatalf("expected success true in response")
}
}
func TestSendBulkEmail_ServiceErrorReturns500(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
es := email.NewEmailService("h", 25, "u", "p", "from@x", 5)
es.SendBulkEmailFunc = func(recipients []string, subject, body string, isHTML bool) ([]string, error) {
return nil, errors.New("bulk fail")
}
h := handlers.NewEmailHandler(es)
body := email.BulkEmailRequest{Recipients: []string{"a@b.com"}, Subject: "s", Body: "b"}
b, _ := json.Marshal(body)
req := httptest.NewRequest("POST", "/", bytes.NewBuffer(b))
req.Header.Set("Content-Type", "application/json")
c.Request = req
h.SendBulkEmail(c)
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 got %d", recorder.Code)
}
}