-
Notifications
You must be signed in to change notification settings - Fork 31
/
mailjet_client_test.go
638 lines (576 loc) · 15.1 KB
/
mailjet_client_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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
package mailjet_test
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
mailjet "github.com/mailjet/mailjet-apiv3-go/v4"
"github.com/mailjet/mailjet-apiv3-go/v4/resources"
)
var (
letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// defaultMessages is the default message passed to the server when an email
// is sent.
defaultMessages = mailjet.MessagesV31{
Info: []mailjet.InfoMessagesV31{
{
From: &mailjet.RecipientV31{
Email: "passenger@mailjet.com",
Name: "passenger",
},
To: &mailjet.RecipientsV31{
mailjet.RecipientV31{
Email: "recipient@company.com",
},
},
Subject: "Send API testing",
TextPart: "SendMail is working!",
},
},
}
)
var (
mux *http.ServeMux
server *httptest.Server
client *mailjet.Client
)
func fakeServer() func() {
mux = http.NewServeMux()
server = httptest.NewServer(mux)
client = mailjet.NewMailjetClient("apiKeyPublic", "apiKeyPrivate", server.URL+"/v3")
return func() {
server.Close()
}
}
func handle(path, response string) {
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, response)
})
}
func randSeq(n int) string {
rand.Seed(time.Now().UnixNano())
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
// NewMockedMailjetClient returns an instance of `Client` with mocked http and smtp clients injected
func newMockedMailjetClient() *mailjet.Client {
httpClientMocked := mailjet.NewhttpClientMock(true)
smtpClientMocked := mailjet.NewSMTPClientMock(true)
client := mailjet.NewClient(httpClientMocked, smtpClientMocked)
return client
}
func TestCreateListrecipient(t *testing.T) {
teardown := fakeServer()
defer teardown()
mux.HandleFunc("/v3/REST/listrecipient", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusNotFound)
return
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Fatal("Unexpected error:", err)
}
body := make(map[string]interface{})
if err = json.Unmarshal(b, &body); err != nil {
t.Fatal("Invalid body:", err)
}
_, id := body["ContactID"]
_, alt := body["ContactALT"]
_, listID := body["ListID"]
if !id && !alt || !listID {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `{"ErrorMessage": "Missing required parameters"}`)
}
})
t.Run("successfully create list", func(t *testing.T) {
req := &mailjet.Request{
Resource: "listrecipient",
}
fullRequest := &mailjet.FullRequest{
Info: req,
Payload: resources.Listrecipient{
IsUnsubscribed: true,
ContactID: 124409882,
ContactALT: "joe.doe@mailjet.com",
ListID: 32964,
},
}
var resp []resources.Listrecipient
err := client.Post(fullRequest, &resp)
if err != nil {
t.Fatal(err)
}
})
t.Run("failure when required parameters missing", func(t *testing.T) {
req := &mailjet.Request{
Resource: "listrecipient",
}
fullRequest := &mailjet.FullRequest{
Info: req,
Payload: resources.Listrecipient{
IsUnsubscribed: true,
ListID: 32964,
},
}
var resp []resources.Listrecipient
err := client.Post(fullRequest, &resp)
if err == nil {
t.Fatal("Expected error")
}
})
}
func TestMessage(t *testing.T) {
teardown := fakeServer()
defer teardown()
handle("/v3/REST/message", `
{
"Count": 1,
"Data": [
{
"ArrivedAt": "2020-10-08T06:36:35Z",
"AttachmentCount": 0,
"AttemptCount": 0,
"CampaignID": 426400,
"ContactAlt": "",
"ContactID": 124409882,
"Delay": 0,
"DestinationID": 124879,
"FilterTime": 0,
"ID": 94294117474376580,
"IsClickTracked": false,
"IsHTMLPartIncluded": false,
"IsOpenTracked": true,
"IsTextPartIncluded": false,
"IsUnsubTracked": false,
"MessageSize": 810,
"SenderID": 52387,
"SpamassassinScore": 0,
"SpamassRules": "",
"StatePermanent": false,
"Status": "sent",
"Subject": "",
"UUID": "6f66806a-c4d6-4a33-99dc-bedbc7c4217f"
}
],
"Total": 1
}
`)
request := &mailjet.Request{
Resource: "message",
}
var data []resources.Message
err := client.Get(request, &data)
if err != nil {
t.Fatal(err)
}
}
func TestMessageinformation(t *testing.T) {
t.Run("empty SpamAssassinRules", func(t *testing.T) {
teardown := fakeServer()
defer teardown()
handle("/v3/REST/messageinformation", `
{
"Count": 1,
"Data": [
{
"CampaignID": 0,
"ClickTrackedCount": 0,
"ContactID": 124409882,
"CreatedAt": "2020-10-09T06:07:56Z",
"ID": 288230380871887400,
"MessageSize": 434,
"OpenTrackedCount": 0,
"QueuedCount": 0,
"SendEndAt": "2020-10-09T06:07:56Z",
"SentCount": 1602223677,
"SpamAssassinRules": {
"ALT": "",
"ID": -1
},
"SpamAssassinScore": 0
}
],
"Total": 1
}
`)
request := &mailjet.Request{
Resource: "messageinformation",
}
var data []resources.Messageinformation
err := client.Get(request, &data)
if err != nil {
t.Fatal(err)
}
})
t.Run("not empty SpamAssassinRules", func(t *testing.T) {
teardown := fakeServer()
defer teardown()
handle("/v3/REST/messageinformation", `
{
"Count": 1,
"Data": [
{
"CampaignID": 0,
"ClickTrackedCount": 0,
"ContactID": 124409882,
"CreatedAt": "2020-10-09T06:07:56Z",
"ID": 288230380871887400,
"MessageSize": 434,
"OpenTrackedCount": 0,
"QueuedCount": 0,
"SendEndAt": "2020-10-09T06:07:56Z",
"SentCount": 1602223677,
"SpamAssassinRules": {
"ALT": "",
"ID": -1,
"Items": [
{
"ALT": "MISSING_DATE",
"HitCount": 81115,
"ID": 1,
"Name": "MISSING_DATE",
"Score": 2.739
},
{
"ALT": "MISSING_HEADERS",
"HitCount": 48433743,
"ID": 2,
"Name": "MISSING_HEADERS",
"Score": 0.915
}
]
},
"SpamAssassinScore": 0
}
],
"Total": 1
}
`)
request := &mailjet.Request{
Resource: "messageinformation",
}
var data []resources.Messageinformation
err := client.Get(request, &data)
if err != nil {
t.Fatal(err)
}
})
}
func TestUnitList(t *testing.T) {
m := newMockedMailjetClient()
var data []resources.Sender
count, _, err := m.List("sender", &data)
if err != nil {
t.Fatal("Unexpected error:", err)
}
if count < 1 {
t.Fatal("At least one sender expected !")
}
httpClientMocked := mailjet.NewhttpClientMock(false)
smtpClientMocked := mailjet.NewSMTPClientMock(true)
cl := mailjet.NewClient(httpClientMocked, smtpClientMocked, "custom")
_, _, err = cl.List("sender", &data)
if err == nil {
t.Fail()
}
}
func TestUnitGet(t *testing.T) {
m := newMockedMailjetClient()
var data []resources.User
resource := "user"
count, _, err := m.List(resource, &data)
if err != nil {
t.Fatal("Unexpected error:", err)
}
if count < 1 {
t.Fatal("At least one user expected !")
}
if data == nil {
t.Fatal("Empty result")
}
mr := &mailjet.Request{Resource: resource, ID: data[0].ID}
data = make([]resources.User, 0)
err = m.Get(mr, &data)
if err != nil {
t.Fatal("Unexpected error:", err)
}
}
func TestUnitPost(t *testing.T) {
m := newMockedMailjetClient()
var data []resources.Contact
rstr := randSeq(10)
t.Logf("Create new contact: \"%s@mailjet.com\"\n", rstr)
fmr := &mailjet.FullRequest{
Info: &mailjet.Request{Resource: "contact"},
Payload: &resources.Contact{Name: rstr, Email: rstr + "@mailjet.com"},
}
err := m.Post(fmr, &data)
if err != nil {
t.Fatal("Unexpected error:", err)
}
if data == nil {
t.Fatal("Empty result")
}
t.Logf("Created contact: %+v\n", data[0])
}
func TestUnitPut(t *testing.T) {
m := newMockedMailjetClient()
var data []resources.Contactslist
resource := "contactslist"
count, _, err := m.List(resource, &data)
if err != nil {
t.Fatal("Unexpected error:", err)
}
if count < 1 {
t.Fatal("At least one contact list expected on test account!")
}
if data == nil {
t.Fatal("Empty result")
}
rstr := randSeq(10)
t.Logf("Update name of the contact list: %s -> %s\n", data[0].Name, rstr)
data[0].Name = randSeq(10)
fmr := &mailjet.FullRequest{
Info: &mailjet.Request{Resource: resource, AltID: data[0].Address},
Payload: data[0],
}
err = m.Put(fmr, []string{"Name"})
if err != nil {
t.Fatal("Unexpected error:", err)
}
}
func TestUnitDelete(t *testing.T) {
m := newMockedMailjetClient()
var data []resources.Listrecipient
resource := "listrecipient"
count, _, err := m.List(resource, &data)
if err != nil {
t.Fatal("Unexpected error:", err)
}
if count < 1 {
return
}
if data == nil {
t.Fatal("Empty result")
}
mr := &mailjet.Request{
ID: data[0].ID,
Resource: resource,
}
err = m.Delete(mr)
if err != nil {
t.Error(err)
}
}
func TestUnitSendMail(t *testing.T) {
m := newMockedMailjetClient()
var data []resources.Sender
count, _, err := m.List("sender", &data)
if err != nil {
t.Fatal("Unexpected error:", err)
}
if count < 1 || data == nil {
t.Fatal("At least one sender expected in the test account!")
}
param := &mailjet.InfoSendMail{
FromEmail: data[0].Email,
FromName: data[0].Name,
Recipients: []mailjet.Recipient{
{
Email: data[0].Email,
},
},
Subject: "Send API testing",
TextPart: "SendMail is working !",
}
_, err = m.SendMail(param)
if err != nil {
t.Fatal("Unexpected error:", err)
}
}
func TestSendMailV31(t *testing.T) {
tests := []struct {
name string
messages mailjet.MessagesV31
mockResponse interface{}
mockStatusCode int
wantResponse *mailjet.ResultsV31
wantErr interface{}
}{
{
name: "sending successful",
messages: defaultMessages,
mockResponse: mailjet.ResultsV31{
ResultsV31: []mailjet.ResultV31{
{
To: []mailjet.GeneratedMessageV31{
{
Email: "recipient@company.com",
MessageUUID: "ac93d194-1432-4e25-a215-2cb450d4a818",
MessageID: 87,
},
},
},
},
},
mockStatusCode: 200,
wantResponse: &mailjet.ResultsV31{
ResultsV31: []mailjet.ResultV31{
{
To: []mailjet.GeneratedMessageV31{
{
Email: "recipient@company.com",
MessageUUID: "ac93d194-1432-4e25-a215-2cb450d4a818",
MessageID: 87,
},
},
},
},
},
wantErr: nil,
},
{
name: "authorization failed",
messages: defaultMessages,
mockResponse: mailjet.ErrorInfoV31{
Identifier: "ac93d194-1432-4e25-a215-2cb450d4a818",
StatusCode: 401,
Message: "API key authentication/authorization failure. You may be unauthorized to access the API or your API key may be expired. Visit API keys management section to check your keys.",
},
mockStatusCode: 401,
wantResponse: nil,
wantErr: &mailjet.ErrorInfoV31{
Identifier: "ac93d194-1432-4e25-a215-2cb450d4a818",
StatusCode: 401,
Message: "API key authentication/authorization failure. You may be unauthorized to access the API or your API key may be expired. Visit API keys management section to check your keys.",
},
},
{
name: "simple errors in request",
messages: messagesWithAdvancedErrorHandling(),
mockResponse: mailjet.APIFeedbackErrorsV31{
Messages: []mailjet.APIFeedbackErrorV31{
{
Errors: []mailjet.APIErrorDetailsV31{
{
ErrorCode: "mj-0013",
ErrorIdentifier: "ac93d194-1432-4e25-a215-2cb450d4a818",
StatusCode: 400,
// It is not, but let's suppose it is.
ErrorMessage: "\"recipient@company.com\" is an invalid email address.",
ErrorRelatedTo: []string{"To[0].Email"},
},
},
},
},
},
mockStatusCode: 400,
wantResponse: nil,
wantErr: &mailjet.APIFeedbackErrorsV31{
Messages: []mailjet.APIFeedbackErrorV31{
{
Errors: []mailjet.APIErrorDetailsV31{
{
ErrorCode: "mj-0013",
ErrorIdentifier: "ac93d194-1432-4e25-a215-2cb450d4a818",
StatusCode: 400,
// It is not, but let's suppose it is.
ErrorMessage: "\"recipient@company.com\" is an invalid email address.",
ErrorRelatedTo: []string{"To[0].Email"},
},
},
},
},
},
},
{
name: "advanced error handling failed",
messages: messagesWithAdvancedErrorHandling(),
mockResponse: mailjet.APIFeedbackErrorsV31{
Messages: []mailjet.APIFeedbackErrorV31{
{
Errors: []mailjet.APIErrorDetailsV31{
{
ErrorCode: "send-0008",
ErrorIdentifier: "ac93d194-1432-4e25-a215-2cb450d4a818",
StatusCode: 403,
ErrorMessage: "\"passenger@mailjet.com\" is not an authorized sender email address for your account.",
ErrorRelatedTo: []string{"From"},
},
},
},
},
},
mockStatusCode: 403,
wantResponse: nil,
wantErr: &mailjet.APIFeedbackErrorsV31{
Messages: []mailjet.APIFeedbackErrorV31{
{
Errors: []mailjet.APIErrorDetailsV31{
{
ErrorCode: "send-0008",
ErrorIdentifier: "ac93d194-1432-4e25-a215-2cb450d4a818",
StatusCode: 403,
ErrorMessage: "\"passenger@mailjet.com\" is not an authorized sender email address for your account.",
ErrorRelatedTo: []string{"From"},
},
},
},
},
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
httpClientMocked := mailjet.NewhttpClientMock(true)
httpClientMocked.SendMailV31Func = func(req *http.Request) (*http.Response, error) {
if req.Header.Get("Content-Type") != "application/json" {
t.Errorf("Wanted request content-type header to be: application/json, got: %s", req.Header.Get("Content-Type"))
}
user, pass, ok := req.BasicAuth()
if !ok || user != httpClientMocked.APIKeyPublic() || pass != httpClientMocked.APIKeyPrivate() {
t.Errorf("Wanted HTTP basic auth to be: %s/%s, got %s/%s", user, pass,
httpClientMocked.APIKeyPublic(), httpClientMocked.APIKeyPrivate())
}
var msgs mailjet.MessagesV31
err := json.NewDecoder(req.Body).Decode(&msgs)
if err != nil {
t.Fatalf("Could not decode request body and read message information: %v", err)
}
if !reflect.DeepEqual(test.messages, msgs) {
t.Errorf("Wanted request messages: %+v, got: %+v", test.messages, msgs)
}
rawBytes, _ := json.Marshal(test.mockResponse)
return &http.Response{
Body: ioutil.NopCloser(bytes.NewBuffer(rawBytes)),
StatusCode: test.mockStatusCode,
}, nil
}
m := mailjet.NewClient(httpClientMocked, mailjet.NewSMTPClientMock(true))
res, err := m.SendMailV31(&test.messages)
if !reflect.DeepEqual(err, test.wantErr) {
t.Fatalf("Wanted error: %+v, got: %+v", err, test.wantErr)
}
if !reflect.DeepEqual(test.wantResponse, res) {
t.Fatalf("Wanted response: %+v, got %+v", test.wantResponse, res)
}
})
}
}
func messagesWithAdvancedErrorHandling() mailjet.MessagesV31 {
withAdvancedErrorChecking := defaultMessages
withAdvancedErrorChecking.AdvanceErrorHandling = true
return withAdvancedErrorChecking
}