File: smtp_test.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,432 kB
  • sloc: sh: 74; makefile: 5
file content (663 lines) | stat: -rw-r--r-- 22,506 bytes parent folder | download
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
package smtp

import (
	"context"
	"log"
	"net/smtp"
	"net/url"
	"os"
	"reflect"
	"testing"
	"time"
	"unsafe"

	"github.com/onsi/ginkgo/v2"
	"github.com/onsi/gomega"

	gomegaTypes "github.com/onsi/gomega/types"

	"github.com/nicholas-fedor/shoutrrr/internal/failures"
	"github.com/nicholas-fedor/shoutrrr/internal/testutils"
	"github.com/nicholas-fedor/shoutrrr/pkg/format"
	"github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
	"github.com/nicholas-fedor/shoutrrr/pkg/types"
)

var tt *testing.T

func TestSMTP(t *testing.T) {
	gomega.RegisterFailHandler(ginkgo.Fail)

	tt = t
	ginkgo.RunSpecs(t, "Shoutrrr SMTP Suite")
}

var (
	service    *Service
	envSMTPURL string
	logger     *log.Logger
	_          = ginkgo.BeforeSuite(func() {
		envSMTPURL = os.Getenv("SHOUTRRR_SMTP_URL")
		logger = testutils.TestLogger()
	})
	urlWithAllProps = "smtp://user:password@example.com:2225/?auth=None&clienthost=testhost&encryption=ExplicitTLS&fromaddress=sender%40example.com&fromname=Sender&subject=Subject&toaddresses=rec1%40example.com%2Crec2%40example.com&usehtml=Yes&usestarttls=No&timeout=10s"
	// BaseNoAuthURL is a minimal SMTP config without authentication.
	BaseNoAuthURL = "smtp://example.com:2225/?useStartTLS=no&auth=none&fromAddress=sender@example.com&toAddresses=rec1@example.com&useHTML=no&timeout=10s"
	// BaseAuthURL is a typical config with authentication.
	BaseAuthURL = "smtp://user:password@example.com:2225/?useStartTLS=no&fromAddress=sender@example.com&toAddresses=rec1@example.com,rec2@example.com&useHTML=yes&timeout=10s"
	// BasePlusURL is a config with plus signs in email addresses.
	BasePlusURL = "smtp://user:password@example.com:2225/?useStartTLS=no&fromAddress=sender+tag@example.com&toAddresses=rec1+tag@example.com,rec2@example.com&useHTML=yes&timeout=10s"
)

// modifyURL modifies a base URL by updating query parameters as specified.
func modifyURL(base string, params map[string]string) string {
	u := testutils.URLMust(base)

	q := u.Query()
	for k, v := range params {
		q.Set(k, v)
	}

	u.RawQuery = q.Encode()

	return u.String()
}

var _ = ginkgo.Describe("the SMTP service", func() {
	ginkgo.BeforeEach(func() {
		service = &Service{}
	})
	ginkgo.When("parsing the configuration URL", func() {
		ginkgo.It("should be identical after de-/serialization", func() {
			url := testutils.URLMust(urlWithAllProps)
			config := &Config{}
			pkr := format.NewPropKeyResolver(config)
			err := config.setURL(&pkr, url)
			gomega.Expect(err).NotTo(gomega.HaveOccurred(), "verifying")
			outputURL := config.GetURL()
			ginkgo.GinkgoT().Logf("\n\n%s\n%s\n\n-", outputURL, urlWithAllProps)
			gomega.Expect(outputURL.String()).To(gomega.Equal(urlWithAllProps))
		})
		ginkgo.When("resolving client host", func() {
			ginkgo.When("clienthost is set to auto", func() {
				ginkgo.It("should return the os hostname", func() {
					hostname, err := os.Hostname()
					gomega.Expect(err).ToNot(gomega.HaveOccurred())
					gomega.Expect(service.resolveClientHost(&Config{ClientHost: "auto"})).
						To(gomega.Equal(hostname))
				})
			})
			ginkgo.When("clienthost is set to a custom value", func() {
				ginkgo.It("should return that value", func() {
					gomega.Expect(service.resolveClientHost(&Config{ClientHost: "computah"})).
						To(gomega.Equal("computah"))
				})
			})
		})
		ginkgo.When("fromAddress is missing", func() {
			ginkgo.It("should return an error", func() {
				testURL := testutils.URLMust(
					"smtp://user:password@example.com:2225/?toAddresses=rec1@example.com,rec2@example.com",
				)
				gomega.Expect((&Config{}).SetURL(testURL)).ToNot(gomega.Succeed())
			})
		})
		ginkgo.When("toAddresses are missing", func() {
			ginkgo.It("should return an error", func() {
				testURL := testutils.URLMust(
					"smtp://user:password@example.com:2225/?fromAddress=sender@example.com",
				)
				gomega.Expect((&Config{}).SetURL(testURL)).ToNot(gomega.Succeed())
			})
		})
	})

	ginkgo.Context("basic service API methods", func() {
		var config *Config
		ginkgo.BeforeEach(func() {
			config = &Config{}
		})
		ginkgo.It("should not allow getting invalid query values", func() {
			testutils.TestConfigGetInvalidQueryValue(config)
		})
		ginkgo.It("should not allow setting invalid query values", func() {
			testutils.TestConfigSetInvalidQueryValue(
				config,
				"smtp://example.com/?fromAddress=s@example.com&toAddresses=r@example.com&foo=bar",
			)
		})
		ginkgo.It("should have the expected number of fields and enums", func() {
			testutils.TestConfigGetEnumsCount(config, 2)
			testutils.TestConfigGetFieldsCount(config, 15)
		})
	})

	ginkgo.When("cloning a config", func() {
		ginkgo.It("should be identical to the original", func() {
			config := &Config{}
			gomega.Expect(config.SetURL(testutils.URLMust(urlWithAllProps))).To(gomega.Succeed())
			gomega.Expect(config.Clone()).To(gomega.Equal(*config))
		})
	})

	ginkgo.When("sending a message", func() {
		ginkgo.When("the service is not configured correctly", func() {
			ginkgo.It("should fail to send messages", func() {
				service := Service{Config: &Config{}}
				gomega.Expect(service.Send("test message", nil)).To(matchFailure(FailGetSMTPClient))
				service.Config.Encryption = EncMethods.ImplicitTLS
				gomega.Expect(service.Send("test message", nil)).To(matchFailure(FailGetSMTPClient))
			})
		})
		ginkgo.When("an invalid param is passed", func() {
			ginkgo.It("should fail to send messages", func() {
				service := Service{Config: &Config{}}
				gomega.Expect(service.Send("test message", &types.Params{"invalid": "value"})).
					To(matchFailure(FailApplySendParams))
			})
		})
	})

	ginkgo.When("the underlying stream stops working", func() {
		var service Service
		var message string
		ginkgo.BeforeEach(func() {
			service = Service{}
			message = ""
		})
		ginkgo.It("should fail when writing multipart plain header", func() {
			writer := testutils.CreateFailWriter(1)
			err := service.writeMultipartMessage(writer, message)
			gomega.Expect(err).To(gomega.HaveOccurred())
			gomega.Expect(err).To(matchFailure(FailPlainHeader))
		})
		ginkgo.It("should fail when writing multipart plain message", func() {
			writer := testutils.CreateFailWriter(2)
			err := service.writeMultipartMessage(writer, message)
			gomega.Expect(err).To(gomega.HaveOccurred())
			gomega.Expect(err).To(matchFailure(FailMessageRaw))
		})
		ginkgo.It("should fail when writing multipart HTML header", func() {
			writer := testutils.CreateFailWriter(4)
			err := service.writeMultipartMessage(writer, message)
			gomega.Expect(err).To(gomega.HaveOccurred())
			gomega.Expect(err).To(matchFailure(FailHTMLHeader))
		})
		ginkgo.It("should fail when writing multipart HTML message", func() {
			writer := testutils.CreateFailWriter(5)
			err := service.writeMultipartMessage(writer, message)
			gomega.Expect(err).To(gomega.HaveOccurred())
			gomega.Expect(err).To(matchFailure(FailMessageRaw))
		})
		ginkgo.It("should fail when writing multipart end header", func() {
			writer := testutils.CreateFailWriter(6)
			err := service.writeMultipartMessage(writer, message)
			gomega.Expect(err).To(gomega.HaveOccurred())
			gomega.Expect(err).To(matchFailure(FailMultiEndHeader))
		})
		ginkgo.It("should fail when writing message template", func() {
			writer := testutils.CreateFailWriter(0)
			e := service.SetTemplateString("dummy", "dummy template content")
			gomega.Expect(e).ToNot(gomega.HaveOccurred())
			err := service.writeMessagePart(writer, message, "dummy")
			gomega.Expect(err).To(gomega.HaveOccurred())
			gomega.Expect(err).To(matchFailure(FailMessageTemplate))
		})
	})

	ginkgo.When("running E2E tests", func() {
		ginkgo.It("should work without errors", func() {
			if envSMTPURL == "" {
				ginkgo.Skip("environment not set up for E2E testing")

				return
			}
			serviceURL, err := url.Parse(envSMTPURL)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())
			err = service.Initialize(serviceURL, logger)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())
			err = service.Send("this is an integration test", nil)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())
		})
	})

	ginkgo.When("running integration tests", func() {
		ginkgo.When("given a typical usage case configuration URL", func() {
			ginkgo.It("should send notifications without any errors", func() {
				testURL := BaseAuthURL
				err := testIntegration(testURL, []string{
					"250-mx.google.com at your service",
					"250-SIZE 35651584",
					"250-AUTH LOGIN PLAIN",
					"250 8BITMIME",
					"235 Accepted",
					"250 Sender OK",
					"250 Receiver OK",
					"354 Go ahead",
					"250 Data OK",
					"250 Sender OK",
					"250 Receiver OK",
					"354 Go ahead",
					"250 Data OK",
					"221 OK",
				}, "<pre>{{ .message }}</pre>", "{{ .message }}")
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).NotTo(gomega.HaveOccurred())
			})
		})
		ginkgo.When("given e-mail addresses with pluses in the configuration URL", func() {
			ginkgo.It("should send notifications without any errors", func() {
				testURL := BasePlusURL
				err := testIntegration(testURL, []string{
					"250-mx.google.com at your service",
					"250-SIZE 35651584",
					"250-AUTH LOGIN PLAIN",
					"250 8BITMIME",
					"235 Accepted",
					"250 Sender OK",
					"250 Receiver OK",
					"354 Go ahead",
					"250 Data OK",
					"250 Sender OK",
					"250 Receiver OK",
					"354 Go ahead",
					"250 Data OK",
					"221 OK",
				}, "<pre>{{ .message }}</pre>", "{{ .message }}",
					"RCPT TO:<rec1+tag@example.com>",
					"To: rec1+tag@example.com",
					"From:  <sender+tag@example.com>")
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).NotTo(gomega.HaveOccurred())
			})
		})
		ginkgo.When("given a configuration URL with authentication disabled", func() {
			ginkgo.It("should send notifications without any errors", func() {
				testURL := BaseNoAuthURL
				err := testIntegration(testURL, []string{
					"250-mx.google.com at your service",
					"250-SIZE 35651584",
					"250-AUTH LOGIN PLAIN",
					"250 8BITMIME",
					"250 Sender OK",
					"250 Receiver OK",
					"354 Go ahead",
					"250 Data OK",
					"221 OK",
				}, "", "")
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).NotTo(gomega.HaveOccurred())
			})
		})
		ginkgo.When("given a configuration URL with StartTLS but it is not supported", func() {
			ginkgo.It("should send notifications without any errors", func() {
				testURL := modifyURL(BaseNoAuthURL, map[string]string{"useStartTLS": "yes"})
				err := testIntegration(testURL, []string{
					"250-mx.google.com at your service",
					"250-SIZE 35651584",
					"250-AUTH LOGIN PLAIN",
					"250 8BITMIME",
					"250 Sender OK",
					"250 Receiver OK",
					"354 Go ahead",
					"250 Data OK",
					"221 OK",
				}, "", "")
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).NotTo(gomega.HaveOccurred())
			})
		})
		ginkgo.When("server communication fails", func() {
			ginkgo.It("should fail when initial handshake is not accepted", func() {
				testURL := modifyURL(
					BaseNoAuthURL,
					map[string]string{"useStartTLS": "yes", "clienthost": "spammer"},
				)
				err := testIntegration(testURL, []string{
					"421 4.7.0 Try again later, closing connection. (EHLO) r20-20020a50d694000000b004588af8956dsm771862edi.9 - gsmtp",
				}, "", "")
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).To(matchFailure(FailHandshake))
			})
			ginkgo.It("should fail when not being able to enable StartTLS", func() {
				testURL := modifyURL(BaseNoAuthURL, map[string]string{"useStartTLS": "yes"})
				err := testIntegration(testURL, []string{
					"250-mx.google.com at your service",
					"250-SIZE 35651584",
					"250-STARTTLS",
					"250-AUTH LOGIN PLAIN",
					"250 8BITMIME",
					"502 That's too hard",
				}, "", "")
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).To(matchFailure(FailEnableStartTLS))
			})
			ginkgo.It("should fail when authentication type is invalid", func() {
				testURL := modifyURL(BaseNoAuthURL, map[string]string{"auth": "bad"})
				err := testIntegration(testURL, []string{}, "", "")
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).To(matchFailure(standard.FailServiceInit))
			})
			ginkgo.It("should fail when not being able to use authentication type", func() {
				testURL := modifyURL(BaseNoAuthURL, map[string]string{"auth": "crammd5"})
				err := testIntegration(testURL, []string{
					"250-mx.google.com at your service",
					"250-SIZE 35651584",
					"250-AUTH LOGIN PLAIN",
					"250 8BITMIME",
					"504 Liar",
				}, "", "")
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).To(matchFailure(FailAuthenticating))
			})
			ginkgo.It("should fail when not being able to send to recipient", func() {
				testURL := BaseNoAuthURL
				err := testIntegration(testURL, []string{
					"250-mx.google.com at your service",
					"250-SIZE 35651584",
					"250-AUTH LOGIN PLAIN",
					"250 8BITMIME",
					"551 I don't know you",
				}, "", "")
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).To(matchFailure(FailSendRecipient))
			})
			ginkgo.It("should fail when the recipient is not accepted", func() {
				testURL := BaseNoAuthURL
				err := testSendRecipient(testURL, []string{
					"250 mx.google.com at your service",
					"250 Sender OK",
					"553 She doesn't want to be disturbed",
				})
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).To(matchFailure(FailSetRecipient))
			})
			ginkgo.It("should fail when the server does not accept the data stream", func() {
				testURL := BaseNoAuthURL
				err := testSendRecipient(testURL, []string{
					"250 mx.google.com at your service",
					"250 Sender OK",
					"250 Receiver OK",
					"554 Nah I'm fine thanks",
				})
				if msg, test := standard.IsTestSetupFailure(err); test {
					ginkgo.Skip(msg)

					return
				}
				gomega.Expect(err).To(matchFailure(FailOpenDataStream))
			})
			ginkgo.It(
				"should fail when the server does not accept the data stream content",
				func() {
					testURL := BaseNoAuthURL
					err := testSendRecipient(testURL, []string{
						"250 mx.google.com at your service",
						"250 Sender OK",
						"250 Receiver OK",
						"354 Go ahead",
						"554 Such garbage!",
					})
					if msg, test := standard.IsTestSetupFailure(err); test {
						ginkgo.Skip(msg)

						return
					}
					gomega.Expect(err).To(matchFailure(FailCloseDataStream))
				},
			)
			ginkgo.It(
				"should fail when the server does not close the connection gracefully",
				func() {
					testURL := BaseNoAuthURL
					err := testIntegration(testURL, []string{
						"250-mx.google.com at your service",
						"250-SIZE 35651584",
						"250-AUTH LOGIN PLAIN",
						"250 8BITMIME",
						"250 Sender OK",
						"250 Receiver OK",
						"354 Go ahead",
						"250 Data OK",
						"502 You can't quit, you're fired!",
					}, "", "")
					if msg, test := standard.IsTestSetupFailure(err); test {
						ginkgo.Skip(msg)

						return
					}
					gomega.Expect(err).To(matchFailure(FailClosingSession))
				},
			)
			ginkgo.It("should fail when context is canceled during connection", func() {
				ctx, cancel := context.WithCancel(context.Background())
				cancel()
				config := &Config{
					Host:        "example.com",
					Port:        25,
					FromAddress: "sender@example.com",
					ToAddresses: []string{"rec@example.com"},
				}
				_, err := getClientConnection(ctx, config)
				gomega.Expect(err).To(gomega.MatchError(context.Canceled))
			})
			ginkgo.It("should attempt all recipients and collect errors", func() {
				testURL := BaseAuthURL
				serviceURL, _ := url.Parse(testURL)
				err := service.Initialize(serviceURL, logger)
				gomega.Expect(err).NotTo(gomega.HaveOccurred())
				responses := []string{
					"250-mx.google.com at your service",
					"250-SIZE 35651584",
					"250-AUTH LOGIN PLAIN",
					"250 8BITMIME",
					"235 Accepted",
					"250 Sender OK",
					"553 Recipient1 not found", // Fail first recipient
					"250 Sender OK",
					"250 Receiver OK",
					"354 Go ahead",
					"250 Data OK",
					"221 OK",
				}
				textCon, tcfaker := testutils.CreateTextConFaker(responses, "\r\n")
				client := &smtp.Client{Text: textCon}
				fakeTLSEnabled(client, serviceURL.Hostname())
				config := service.Config
				config.ToAddresses = []string{"rec1@example.com", "rec2@example.com"}
				err = service.doSend(client, "Test message", config)
				gomega.Expect(err).To(gomega.HaveOccurred())
				gomega.Expect(err).To(matchFailure(FailSendRecipient))
				gomega.Expect(err.Error()).
					To(gomega.ContainSubstring("error sending message to recipient \"rec1@example.com\""))
				received := tcfaker.GetClientSentences()
				gomega.Expect(received).
					To(gomega.ContainElement("RCPT TO:<rec2@example.com>"))
					// Verify second recipient attempted
				gomega.Expect(received).
					To(gomega.ContainElement("QUIT"))
					// Verify connection closed
				logger.Printf("\n%s", tcfaker.GetConversation(false))
			})
		})
	})

	ginkgo.When("writing headers and the output stream is closed", func() {
		ginkgo.When("it's closed during header content", func() {
			ginkgo.It("should fail with correct error", func() {
				fw := testutils.CreateFailWriter(0)
				gomega.Expect(writeHeaders(fw, map[string]string{"key": "value"})).
					To(matchFailure(FailWriteHeaders))
			})
		})
		ginkgo.When("it's closed after header content", func() {
			ginkgo.It("should fail with correct error", func() {
				fw := testutils.CreateFailWriter(1)
				gomega.Expect(writeHeaders(fw, map[string]string{"key": "value"})).
					To(matchFailure(FailWriteHeaders))
			})
		})
	})

	ginkgo.When("default port is not specified", func() {
		ginkgo.It("should use the default SMTP port when not specified", func() {
			testURL := "smtp://example.com/?fromAddress=sender@example.com&toAddresses=rec1@example.com"
			serviceURL := testutils.URLMust(testURL)
			err := service.Initialize(serviceURL, logger)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())
			gomega.Expect(service.Config.Port).To(gomega.Equal(uint16(DefaultSMTPPort)))
		})
	})

	ginkgo.When("configuring timeout via URL", func() {
		ginkgo.It("should use the specified timeout", func() {
			testURL := modifyURL(BaseNoAuthURL, map[string]string{"timeout": "5s"})
			serviceURL := testutils.URLMust(testURL)
			err := service.Initialize(serviceURL, logger)
			gomega.Expect(err).NotTo(gomega.HaveOccurred())
			gomega.Expect(service.Config.Timeout).To(gomega.Equal(5 * time.Second))
		})
	})

	ginkgo.It("returns the correct service identifier", func() {
		gomega.Expect(service.GetID()).To(gomega.Equal("smtp"))
	})
})

func testSendRecipient(testURL string, responses []string) failures.Failure {
	serviceURL, err := url.Parse(testURL)
	if err != nil {
		return standard.Failure(standard.FailParseURL, err)
	}

	err = service.Initialize(serviceURL, logger)
	if err != nil {
		return failures.Wrap("error parsing URL", standard.FailTestSetup, err)
	}

	if err := service.SetTemplateString("plain", "{{.message}}"); err != nil {
		return failures.Wrap("error setting plain template", standard.FailTestSetup, err)
	}

	textCon, tcfaker := testutils.CreateTextConFaker(responses, "\r\n")
	client := &smtp.Client{Text: textCon}
	fakeTLSEnabled(client, serviceURL.Hostname())

	config := &Config{}
	message := "message body"
	ferr := service.sendToRecipient(client, "r@example.com", config, message)

	logger.Printf("\n%s", tcfaker.GetConversation(false))

	if ferr != nil {
		return ferr
	}

	return nil
}

func testIntegration(
	testURL string,
	responses []string,
	htmlTemplate string,
	plainTemplate string,
	expectRec ...string,
) failures.Failure {
	serviceURL, err := url.Parse(testURL)
	if err != nil {
		return standard.Failure(standard.FailParseURL, err)
	}

	if err = service.Initialize(serviceURL, logger); err != nil {
		return standard.Failure(standard.FailServiceInit, err)
	}

	if htmlTemplate != "" {
		if err := service.SetTemplateString("HTML", htmlTemplate); err != nil {
			return failures.Wrap("error setting HTML template", standard.FailTestSetup, err)
		}
	}

	if plainTemplate != "" {
		if err := service.SetTemplateString("plain", plainTemplate); err != nil {
			return failures.Wrap("error setting plain template", standard.FailTestSetup, err)
		}
	}

	textCon, tcfaker := testutils.CreateTextConFaker(responses, "\r\n")
	client := &smtp.Client{Text: textCon}
	fakeTLSEnabled(client, serviceURL.Hostname())
	ferr := service.doSend(client, "Test message", service.Config)

	received := tcfaker.GetClientSentences()
	for _, expected := range expectRec {
		gomega.Expect(received).To(gomega.ContainElement(expected))
	}

	logger.Printf("\n%s", tcfaker.GetConversation(false))

	if ferr != nil {
		return ferr
	}

	return nil
}

// fakeTLSEnabled tricks a given client into believing that TLS is enabled even though it's not
// this is needed because the SMTP library won't allow plain authentication without TLS being turned on.
// having it turned on would of course mean that we cannot test the communication since it will be encrypted.
func fakeTLSEnabled(client *smtp.Client, hostname string) {
	// set the "tls" flag on the client which indicates that TLS encryption is enabled (even though it's not)
	cr := reflect.ValueOf(client).Elem().FieldByName("tls")
	cr = reflect.NewAt(cr.Type(), unsafe.Pointer(cr.UnsafeAddr())).Elem()
	cr.SetBool(true)
	// set the serverName field on the client which is used to identify the server and has to equal the hostname
	cr = reflect.ValueOf(client).Elem().FieldByName("serverName")
	cr = reflect.NewAt(cr.Type(), unsafe.Pointer(cr.UnsafeAddr())).Elem()
	cr.SetString(hostname)
}

// matchFailure is a simple wrapper around `fail` and `gomega.MatchError` to make it easier to use in tests.
func matchFailure(id failures.FailureID) gomegaTypes.GomegaMatcher {
	return gomega.MatchError(fail(id, nil))
}