-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsettings_test.go
More file actions
952 lines (757 loc) · 29.6 KB
/
Copy pathsettings_test.go
File metadata and controls
952 lines (757 loc) · 29.6 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
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
// SPDX-FileCopyrightText: 2021 Lightmeter <hello@lightmeter.io>
//
// SPDX-License-Identifier: AGPL-3.0-only
package httpsettings
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/rs/zerolog/log"
slackAPI "github.com/slack-go/slack"
. "github.com/smartystreets/goconvey/convey"
"gitlab.com/lightmeter/controlcenter/dashboard"
"gitlab.com/lightmeter/controlcenter/deliverydb"
"gitlab.com/lightmeter/controlcenter/domainmapping"
"gitlab.com/lightmeter/controlcenter/httpmiddleware"
"gitlab.com/lightmeter/controlcenter/i18n/translator"
"gitlab.com/lightmeter/controlcenter/insights"
"gitlab.com/lightmeter/controlcenter/insights/core"
"gitlab.com/lightmeter/controlcenter/insights/highrate"
"gitlab.com/lightmeter/controlcenter/insights/mailinactivity"
"gitlab.com/lightmeter/controlcenter/lmsqlite3"
"gitlab.com/lightmeter/controlcenter/metadata"
_ "gitlab.com/lightmeter/controlcenter/metadata/migrations"
"gitlab.com/lightmeter/controlcenter/notification"
notificationCore "gitlab.com/lightmeter/controlcenter/notification/core"
"gitlab.com/lightmeter/controlcenter/notification/email"
"gitlab.com/lightmeter/controlcenter/notification/slack"
"gitlab.com/lightmeter/controlcenter/pkg/runner"
"gitlab.com/lightmeter/controlcenter/settings"
"gitlab.com/lightmeter/controlcenter/settings/globalsettings"
insightsSettings "gitlab.com/lightmeter/controlcenter/settings/insights"
"gitlab.com/lightmeter/controlcenter/settings/walkthrough"
"gitlab.com/lightmeter/controlcenter/util/testutil"
"gitlab.com/lightmeter/controlcenter/util/timeutil"
"golang.org/x/text/message/catalog"
)
var (
dummyContext = context.Background()
)
type dummySubscriber struct{}
func (*dummySubscriber) Subscribe(ctx context.Context, email string) error {
log.Info().Msgf("A dummy call that would otherwise subscribe email %v to Lightmeter newsletter :-)", email)
return nil
}
type fakeFetcher struct{}
func (f *fakeFetcher) FetchInsights(c context.Context, o core.FetchOptions, t timeutil.Clock) ([]core.FetchedInsight, error) {
return nil, nil
}
type fakeNotifier struct {
}
func (c *fakeNotifier) ValidateSettings(notificationCore.Settings) error {
return nil
}
func (c *fakeNotifier) Notify(notification.Notification, translator.Translator) error {
log.Info().Msg("send notification")
return nil
}
func init() {
lmsqlite3.Initialize(lmsqlite3.Options{})
}
type fakeSlackPoster struct {
err error
}
var fakeSlackError = errors.New(`Some Slack Error`)
func (p *fakeSlackPoster) PostMessage(channelID string, options ...slackAPI.MsgOption) (string, string, error) {
return "", "", p.err
}
func buildTestSetup(t *testing.T) (*Settings, *metadata.AsyncWriter, metadata.Reader, *notification.Center, *fakeSlackPoster, *insights.Engine, func()) {
conn, closeConn := testutil.TempDBConnectionMigrated(t, "master")
connInsights, closeConnInsights := testutil.TempDBConnectionMigrated(t, "insights")
connLogs, closeConnLogs := testutil.TempDBConnectionMigrated(t, "logs")
// NOTE: finish migration of logs
_, err := deliverydb.New(connLogs, &domainmapping.DefaultMapping, deliverydb.Options{RetentionDuration: (time.Hour * 24 * 30 * 3)})
So(err, ShouldBeNil)
m, err := metadata.NewHandler(conn)
So(err, ShouldBeNil)
writeRunner := metadata.NewSerialWriteRunner(m)
done, cancel := runner.Run(writeRunner)
writer := writeRunner.Writer()
initialSetupSettings := settings.NewInitialSetupSettings(&dummySubscriber{})
fakeNotifier := &fakeNotifier{}
slackNotifier := slack.New(notification.PassPolicy, m.Reader)
fakeSlackPoster := &fakeSlackPoster{}
// don't use slack api, mocking the PostMessage call
slackNotifier.MessagePosterBuilder = func(client *slackAPI.Client) slack.MessagePoster {
return fakeSlackPoster
}
emailNotifier := email.New(notification.PassPolicy, m.Reader)
notifiers := map[string]notification.Notifier{
slack.SettingsKey: slackNotifier,
email.SettingsKey: emailNotifier,
"fake": fakeNotifier,
}
center := notification.New(m.Reader, translator.New(catalog.NewBuilder()), notification.PassPolicy, notifiers)
insightsAccessor, err := insights.NewAccessor(connInsights)
So(err, ShouldBeNil)
dashboard, err := dashboard.New(connLogs.RoConnPool)
So(err, ShouldBeNil)
insightsEngine, err := insights.NewCustomEngine(
&m.Reader,
insightsAccessor,
&fakeFetcher{},
center,
core.Options{
"dashboard": dashboard,
"logsConnPool": connLogs.RoConnPool,
},
insights.SettingsDetectors,
insights.NoAdditionalActions,
)
So(err, ShouldBeNil)
setup := NewSettings(writer, m.Reader, initialSetupSettings, center, insightsEngine)
return setup, writer, m.Reader, center, fakeSlackPoster, insightsEngine, func() {
cancel()
done()
closeConn()
closeConnInsights()
closeConnLogs()
}
}
func TestInitialSetup(t *testing.T) {
Convey("Initial Setup", t, func() {
setup, _, _, _, _, _, clear := buildTestSetup(t)
defer clear()
chain := httpmiddleware.New()
handler := chain.WithEndpoint(httpmiddleware.CustomHTTPHandler(setup.SettingsForward))
s := httptest.NewServer(handler)
c := &http.Client{}
querySettingsParameter := "?setting=initSetup"
settingsURL := s.URL + querySettingsParameter
Convey("Fails", func() {
Convey("Invalid Form data", func() {
r, err := c.Post(settingsURL, "application/x-www-form-urlencoded", strings.NewReader(`^^%`))
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusInternalServerError)
})
Convey("Invalid mime type", func() {
r, err := c.Post(settingsURL, "ksajdhfk*I&^&*^87678 $$343", nil)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusInternalServerError)
})
Convey("Subscribe is not a boolean", func() {
r, err := c.PostForm(settingsURL, url.Values{"subscribe_newsletter": {"Falsch"}})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
Convey("Unsupported multiple subscribe options", func() {
r, err := c.PostForm(settingsURL, url.Values{"subscribe_newsletter": {"on", "on"}})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
Convey("Incompatible mime type", func() {
r, err := c.Post(settingsURL, "application/json", nil)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusInternalServerError)
})
Convey("Incompatible Method", func() {
r, err := c.Head(settingsURL)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusMethodNotAllowed)
})
Convey("Subscribe without email", func() {
r, err := c.PostForm(settingsURL, url.Values{"subscribe_newsletter": {"on"}})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
Convey("Subscribe with zero email", func() {
r, err := c.PostForm(settingsURL, url.Values{"email": {}, "subscribe_newsletter": {"on"}})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
Convey("invalid ip", func() {
r, err := c.PostForm(settingsURL, url.Values{
"email": {"user@example.com"},
"subscribe_newsletter": {"on"},
"app_language": {"en"},
"postfix_public_ip": {"9.9.9.X"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
})
Convey("Success", func() {
Convey("Do subscribe", func() {
r, err := c.PostForm(settingsURL, url.Values{
"email": {"user@example.com"},
"subscribe_newsletter": {"on"},
"app_language": {"en"},
"postfix_public_ip": {"9.9.9.9"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
})
Convey("Do not subscribe", func() {
r, err := c.PostForm(settingsURL, url.Values{
"postfix_public_ip": {"9.9.9.9"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
})
})
})
}
func TestAppSettings(t *testing.T) {
Convey("Settings Setup", t, func() {
setup, writer, reader, _, _, _, clear := buildTestSetup(t)
defer clear()
chain := httpmiddleware.New()
handler := chain.WithEndpoint(httpmiddleware.CustomHTTPHandler(setup.SettingsForward))
s := httptest.NewServer(handler)
c := &http.Client{}
Convey("Do not clean IP settings when updating the language", func() {
// First set an IP address manually
writer.StoreJson(globalsettings.SettingsKey, &globalsettings.Settings{
LocalIP: globalsettings.IP{net.ParseIP(`127.0.0.1`)},
AppLanguage: "en",
}).Wait()
// Set the app language via http, not posting the ip address
r, err := c.PostForm(s.URL+"?setting=general", url.Values{
"app_language": {"de"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
// The IP address must be intact
settings := globalsettings.Settings{}
err = reader.RetrieveJson(context.Background(), globalsettings.SettingsKey, &settings)
So(err, ShouldBeNil)
So(settings.AppLanguage, ShouldEqual, "de")
So(settings.LocalIP.String(), ShouldEqual, "127.0.0.1")
})
})
Convey("Clear general settings", t, func() {
setup, writer, reader, _, _, _, clear := buildTestSetup(t)
defer clear()
chain := httpmiddleware.New()
handler := chain.WithEndpoint(httpmiddleware.CustomHTTPHandler(setup.SettingsForward))
s := httptest.NewServer(handler)
c := &http.Client{}
Convey("Do not reset language when we clear general settings", func() {
writer.StoreJson(globalsettings.SettingsKey, &globalsettings.Settings{
LocalIP: globalsettings.IP{net.ParseIP(`127.0.0.1`)},
PublicURL: "http://localhost:8080",
AppLanguage: "de",
}).Wait()
// Check that the settings are set
settings := globalsettings.Settings{}
err := reader.RetrieveJson(context.Background(), globalsettings.SettingsKey, &settings)
So(err, ShouldBeNil)
So(settings.LocalIP.String(), ShouldEqual, `127.0.0.1`)
So(settings.PublicURL, ShouldEqual, "http://localhost:8080")
So(settings.AppLanguage, ShouldEqual, "de")
// Clear general settings
r, err := c.PostForm(s.URL+"?setting=general", url.Values{"action": {"clear"}})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
// The IP address and postfix URL must be cleared, but the language should stay
settings = globalsettings.Settings{}
err = reader.RetrieveJson(context.Background(), globalsettings.SettingsKey, &settings)
So(err, ShouldBeNil)
So(settings.LocalIP.IP, ShouldBeNil)
So(settings.PublicURL, ShouldEqual, "")
So(settings.AppLanguage, ShouldEqual, "de")
})
})
}
type fakeContentComponent string
func (c fakeContentComponent) String() string {
return string(c)
}
func (c fakeContentComponent) Args() []interface{} {
return nil
}
func (c fakeContentComponent) TplString() string {
return c.String()
}
type fakeContent struct {
}
func (c fakeContent) Title() notificationCore.ContentComponent {
return fakeContentComponent("some fake content")
}
func (c fakeContent) Description() notificationCore.ContentComponent {
return fakeContentComponent("some fake description")
}
func (c fakeContent) Metadata() notificationCore.ContentMetadata {
return nil
}
func TestSlackNotifications(t *testing.T) {
Convey("Integration Settings Setup", t, func() {
setup, _, reader, center, fakeSlackPoster, _, clear := buildTestSetup(t)
defer clear()
chain := httpmiddleware.New()
handler := chain.WithEndpoint(httpmiddleware.CustomHTTPHandler(setup.SettingsForward))
c := &http.Client{}
s := httptest.NewServer(handler)
querySettingsParameter := "?setting=notification"
settingsURL := s.URL + querySettingsParameter
Convey("Settings", func() {
querySettingsParameter := "?setting=notification"
settingsURL := s.URL + querySettingsParameter
Convey("Fails", func() {
Convey("Invalid Form data", func() {
r, err := c.Post(settingsURL, "application/x-www-form-urlencoded", strings.NewReader(`^^%`))
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusInternalServerError)
})
Convey("Invalid mime type", func() {
r, err := c.Post(settingsURL, "ksajdhfk*I&^&*^87678 $$343", nil)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusInternalServerError)
})
Convey("Incompatible Method", func() {
r, err := c.Head(settingsURL)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusMethodNotAllowed)
})
})
Convey("Success", func() {
Convey("send valid values", func() {
r, err := c.PostForm(settingsURL, url.Values{
"messenger_kind": {"slack"},
"messenger_token": {"sjdfklsjdfkljfs"},
"messenger_channel": {"donutloop"},
"messenger_enabled": {"true"},
"messenger_language": {"de"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
mo := new(slack.Settings)
err = reader.RetrieveJson(dummyContext, slack.SettingsKey, mo)
So(err, ShouldBeNil)
So(mo.Channel, ShouldEqual, "donutloop")
So(*mo.BearerToken, ShouldEqual, "sjdfklsjdfkljfs")
})
})
})
Convey("Success", func() {
Convey("send valid values", func() {
r, err := c.PostForm(settingsURL, url.Values{
"messenger_kind": {"slack"},
"messenger_token": {"some_valid_key"},
"messenger_channel": {"general"},
"messenger_enabled": {"true"},
"messenger_language": {"de"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
r, err = c.PostForm(settingsURL, url.Values{
"messenger_kind": {"slack"},
"messenger_token": {"some_valid_key"},
"messenger_channel": {"general"},
"messenger_enabled": {"true"},
"messenger_language": {"en"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
mo := new(slack.Settings)
err = reader.RetrieveJson(dummyContext, slack.SettingsKey, mo)
So(err, ShouldBeNil)
So(mo.Channel, ShouldEqual, "general")
So(*mo.BearerToken, ShouldEqual, "some_valid_key")
content := new(fakeContent)
notification := notification.Notification{
ID: 0,
Content: content,
}
err = center.Notify(notification)
So(err, ShouldBeNil)
})
Convey("Fails if slack validations fail", func() {
fakeSlackPoster.err = fakeSlackError
r, err := c.PostForm(settingsURL, url.Values{
"messenger_kind": {"slack"},
"messenger_token": {"some_invalid_key"},
"messenger_channel": {"donutloop"},
"messenger_enabled": {"true"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
mo := new(slack.Settings)
err = reader.RetrieveJson(dummyContext, slack.SettingsKey, mo)
So(errors.Is(err, metadata.ErrNoSuchKey), ShouldBeTrue)
})
})
})
Convey("Reset slack settings", t, func() {
setup, _, reader, _, _, _, clear := buildTestSetup(t)
defer clear()
chain := httpmiddleware.New()
handler := chain.WithEndpoint(httpmiddleware.CustomHTTPHandler(setup.SettingsForward))
c := &http.Client{}
s := httptest.NewServer(handler)
querySettingsParameter := "?setting=notification"
settingsURL := s.URL + querySettingsParameter
Convey("Reset slack settings should clear all fields", func() {
r, err := c.PostForm(settingsURL, url.Values{
"messenger_kind": {"slack"},
"messenger_token": {"some_valid_key"},
"messenger_channel": {"general"},
"messenger_enabled": {"true"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
mo := new(slack.Settings)
err = reader.RetrieveJson(dummyContext, slack.SettingsKey, mo)
So(err, ShouldBeNil)
So(mo.Channel, ShouldEqual, "general")
So(*mo.BearerToken, ShouldEqual, "some_valid_key")
// Reset slack settings
r, err = c.PostForm(s.URL+"?setting=notification", url.Values{"action": {"clear"}, "subsection": {"slack"}})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
// The slack fields should be cleared
mo = new(slack.Settings)
err = reader.RetrieveJson(dummyContext, slack.SettingsKey, mo)
So(err, ShouldBeNil)
So(mo.Channel, ShouldEqual, "")
So(mo.BearerToken, ShouldBeNil)
})
})
}
func TestEmailNotifications(t *testing.T) {
Convey("Email Notifications", t, func() {
setup, w, _, center, _, _, clear := buildTestSetup(t)
defer clear()
// set some basic global settings required by the email notifier
err := globalsettings.SetSettings(dummyContext, w, globalsettings.Settings{
PublicURL: "https://example.com/lightmeter",
})
So(err, ShouldBeNil)
emailBackend := &email.FakeMailBackend{ExpectedUser: "user@example.com", ExpectedPassword: "super_password"}
stop := email.StartFakeServer(emailBackend, ":10027")
defer stop()
chain := httpmiddleware.New()
handler := chain.WithEndpoint(httpmiddleware.CustomHTTPHandler(setup.SettingsForward))
c := &http.Client{}
s := httptest.NewServer(handler)
querySettingsParameter := "?setting=notification"
settingsURL := s.URL + querySettingsParameter
Convey("Fail due wrong configuration (username)", func() {
r, err := c.PostForm(settingsURL, url.Values{
"email_notification_enabled": {"true"},
"email_notification_skip_cert_check": {"false"},
"email_notification_server_name": {"localhost"},
"email_notification_port": {"10027"},
"email_notification_security_type": {"none"},
"email_notification_auth_method": {"password"},
"email_notification_username": {"wronguser@example.com"},
"email_notification_password": {"super_password"},
"email_notification_sender": {"sender@example.com"},
"email_notification_recipients": {"Some Person <some.person@example.com>, Someone Else <someone@else.example.com>"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
So(len(emailBackend.Messages), ShouldEqual, 0)
})
Convey("Succeeds, but it's disabled", func() {
r, err := c.PostForm(settingsURL, url.Values{
"email_notification_enabled": {"false"},
"email_notification_skip_cert_check": {"false"},
"email_notification_server_name": {"localhost"},
"email_notification_port": {"10027"},
"email_notification_security_type": {"none"},
"email_notification_auth_method": {"password"},
"email_notification_username": {"user@example.com"},
"email_notification_password": {"super_password"},
"email_notification_sender": {"sender@example.com"},
"email_notification_recipients": {"Some Person <some.person@example.com>, Someone Else <someone@else.example.com>"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
err = center.Notify(notification.Notification{
ID: 0,
Content: &fakeContent{},
})
So(err, ShouldBeNil)
So(len(emailBackend.Messages), ShouldEqual, 0)
})
Convey("Succeeds to setup and sends one notification", func() {
r, err := c.PostForm(settingsURL, url.Values{
"email_notification_enabled": {"true"},
"email_notification_skip_cert_check": {"false"},
"email_notification_server_name": {"localhost"},
"email_notification_port": {"10027"},
"email_notification_security_type": {"none"},
"email_notification_auth_method": {"password"},
"email_notification_username": {"user@example.com"},
"email_notification_password": {"super_password"},
"email_notification_sender": {"sender@example.com"},
"email_notification_recipients": {"Some Person <some.person@example.com>, Someone Else <someone@else.example.com>"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
err = center.Notify(notification.Notification{
ID: 0,
Content: &fakeContent{},
})
So(err, ShouldBeNil)
So(len(emailBackend.Messages), ShouldEqual, 1)
msg := emailBackend.Messages[0]
So(msg.Header.Get("From"), ShouldEqual, "sender@example.com")
So(msg.Header.Get("To"), ShouldEqual, "Some Person <some.person@example.com>, Someone Else <someone@else.example.com>")
})
})
Convey("Reset email settings", t, func() {
setup, _, reader, _, _, _, clear := buildTestSetup(t)
defer clear()
emailBackend := &email.FakeMailBackend{ExpectedUser: "user@example.com", ExpectedPassword: "super_password"}
stop := email.StartFakeServer(emailBackend, ":10027")
defer stop()
chain := httpmiddleware.New()
handler := chain.WithEndpoint(httpmiddleware.CustomHTTPHandler(setup.SettingsForward))
c := &http.Client{}
s := httptest.NewServer(handler)
querySettingsParameter := "?setting=notification"
settingsURL := s.URL + querySettingsParameter
Convey("Reset email settings", func() {
r, err := c.PostForm(settingsURL, url.Values{
"email_notification_enabled": {"true"},
"email_notification_skip_cert_check": {"false"},
"email_notification_server_name": {"localhost"},
"email_notification_port": {"10027"},
"email_notification_security_type": {"none"},
"email_notification_auth_method": {"password"},
"email_notification_username": {"user@example.com"},
"email_notification_password": {"super_password"},
"email_notification_sender": {"sender@example.com"},
"email_notification_recipients": {"Some Person <some.person@example.com>, Someone Else <someone@else.example.com>"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
settings, err := email.GetSettings(context.Background(), reader)
So(err, ShouldBeNil)
err = reader.RetrieveJson(context.Background(), email.SettingsKey, &settings)
So(err, ShouldBeNil)
So(settings.Sender, ShouldEqual, "sender@example.com")
So(settings.Recipients, ShouldEqual, "Some Person <some.person@example.com>, Someone Else <someone@else.example.com>")
// Reset email settings
r, err = c.PostForm(s.URL+"?setting=notification", url.Values{"action": {"clear"}, "subsection": {"email"}})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
settings, err = email.GetSettings(context.Background(), reader)
So(err, ShouldBeNil)
So(settings.Sender, ShouldEqual, "")
So(settings.Recipients, ShouldEqual, "")
})
})
}
func TestWalkthroughSettings(t *testing.T) {
Convey("Integration Settings Setup", t, func() {
setup, _, reader, _, _, _, clear := buildTestSetup(t)
defer clear()
chain := httpmiddleware.New()
handler := chain.WithEndpoint(httpmiddleware.CustomHTTPHandler(setup.SettingsForward))
w := &walkthrough.Settings{}
So(errors.Is(reader.RetrieveJson(dummyContext, walkthrough.SettingsKey, w), metadata.ErrNoSuchKey), ShouldBeTrue)
c := &http.Client{}
s := httptest.NewServer(handler)
Convey("Save", func() {
querySettingsParameter := "?setting=walkthrough"
settingsURL := s.URL + querySettingsParameter
Convey("Fails", func() {
Convey("Invalid Form data", func() {
r, err := c.Post(settingsURL, "application/x-www-form-urlencoded", strings.NewReader(`^^%`))
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
Convey("Invalid mime type", func() {
r, err := c.Post(settingsURL, "ksajdhfk*I&^&*^87678 $$343", nil)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
Convey("Incompatible Method", func() {
r, err := c.Head(settingsURL)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusMethodNotAllowed)
})
Convey("Invalid option", func() {
r, err := c.PostForm(settingsURL, url.Values{
"completed": {"banana"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
})
Convey("Success", func() {
Convey("set as completed", func() {
r, err := c.PostForm(settingsURL, url.Values{
"completed": {"true"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
w := &walkthrough.Settings{}
So(reader.RetrieveJson(dummyContext, walkthrough.SettingsKey, w), ShouldBeNil)
So(w.Completed, ShouldBeTrue)
Convey("Retrieve", func() {
r, err := c.Get(s.URL)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
body, err := decodeBodyAsJson(r.Body)
So(err, ShouldBeNil)
asMap, ok := body.(map[string]interface{})
So(ok, ShouldBeTrue)
So(asMap["walkthrough"], ShouldResemble, map[string]interface{}{"completed": true})
})
})
})
})
})
}
func TestInsightsSettings(t *testing.T) {
Convey("Insights Settings", t, func() {
setup, _, reader, _, _, insightsEngine, clear := buildTestSetup(t)
defer clear()
chain := httpmiddleware.New()
handler := chain.WithEndpoint(httpmiddleware.CustomHTTPHandler(setup.SettingsForward))
w := &insightsSettings.Settings{}
So(errors.Is(reader.RetrieveJson(dummyContext, insightsSettings.SettingsKey, w), metadata.ErrNoSuchKey), ShouldBeTrue)
c := &http.Client{}
s := httptest.NewServer(handler)
Convey("Save", func() {
querySettingsParameter := "?setting=insights"
settingsURL := s.URL + querySettingsParameter
Convey("Fails", func() {
Convey("Invalid Form data", func() {
r, err := c.Post(settingsURL, "application/x-www-form-urlencoded", strings.NewReader(`^^%`))
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
Convey("Invalid mime type", func() {
r, err := c.Post(settingsURL, "ksajdhfk*I&^&*^87678 $$343", nil)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
Convey("Incompatible Method", func() {
r, err := c.Head(settingsURL)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusMethodNotAllowed)
})
Convey("Invalid option for bounce_rate_threshold", func() {
r, err := c.PostForm(settingsURL, url.Values{
"bounce_rate_threshold": {"abc"},
"mail_inactivity_lookup_range": {"12"},
"mail_inactivity_min_interval": {"8"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
r, err = c.PostForm(settingsURL, url.Values{
"bounce_rate_threshold": {"1000"},
"mail_inactivity_lookup_range": {"12"},
"mail_inactivity_min_interval": {"8"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
r, err = c.PostForm(settingsURL, url.Values{
"bounce_rate_threshold": {"-1"},
"mail_inactivity_lookup_range": {"12"},
"mail_inactivity_min_interval": {"8"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
r, err = c.PostForm(settingsURL, url.Values{
"bounce_rate_threshold": {"0.5"},
"mail_inactivity_lookup_range": {"12"},
"mail_inactivity_min_interval": {"8"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
Convey("Invalid option for mail_inactivity", func() {
r, err := c.PostForm(settingsURL, url.Values{
"bounce_rate_threshold": {"50"},
"mail_inactivity_lookup_range": {"12"},
"mail_inactivity_min_interval": {"abc"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
r, err = c.PostForm(settingsURL, url.Values{
"bounce_rate_threshold": {"50"},
"mail_inactivity_lookup_range": {"12"},
"mail_inactivity_min_interval": {"0"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
r, err = c.PostForm(settingsURL, url.Values{
"bounce_rate_threshold": {"50"},
"mail_inactivity_lookup_range": {"12"},
"mail_inactivity_min_interval": {"1000"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
r, err = c.PostForm(settingsURL, url.Values{
"bounce_rate_threshold": {"50"},
"mail_inactivity_lookup_range": {"12"},
"mail_inactivity_min_interval": {"10.12"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusBadRequest)
})
})
Convey("Success", func() {
Convey("Set to 53%", func() {
r, err := c.PostForm(settingsURL, url.Values{
"bounce_rate_threshold": {"53"},
"mail_inactivity_lookup_range": {"12"},
"mail_inactivity_min_interval": {"8"},
})
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
i := &insightsSettings.Settings{}
So(reader.RetrieveJson(dummyContext, insightsSettings.SettingsKey, i), ShouldBeNil)
So(i.BounceRateThreshold, ShouldEqual, 53)
Convey("Retrieve", func() {
r, err := c.Get(s.URL)
So(err, ShouldBeNil)
So(r.StatusCode, ShouldEqual, http.StatusOK)
body, err := decodeBodyAsJson(r.Body)
So(err, ShouldBeNil)
asMap, ok := body.(map[string]interface{})
So(ok, ShouldBeTrue)
So(asMap["insights"], ShouldResemble, map[string]interface{}{
"bounce_rate_threshold": float64(53),
"mail_inactivity_lookup_range": float64(12),
"mail_inactivity_min_interval": float64(8),
})
})
Convey("Detectors should be updated", func() {
foundDetectors := map[string]int{
"hrd": 0,
"mi": 0,
}
detectors := insightsEngine.GetCoreDetectors()
So(len(detectors), ShouldEqual, 2)
for _, d := range detectors {
if hrd, ok := d.(*highrate.Detector); ok {
So(hrd.GetBounceRateThreshold(), ShouldEqual, 0.53)
foundDetectors["hrd"]++
}
if mi, ok := d.(*mailinactivity.Detector); ok {
So(mi.GetOptions().LookupRange, ShouldEqual, time.Hour*12)
So(mi.GetOptions().MinTimeGenerationInterval, ShouldEqual, time.Hour*8)
foundDetectors["mi"]++
}
}
So(foundDetectors["hrd"], ShouldEqual, 1)
So(foundDetectors["mi"], ShouldEqual, 1)
})
})
})
})
})
}