-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathconsumer_test.go
973 lines (794 loc) · 32.1 KB
/
consumer_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
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
/*
Copyright © 2021, 2022, 2023 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main_test
// Unit test definitions for functions and methods defined in source file
// consumer.go
//
// Documentation in literate-programming-style is available at:
// https://redhatinsights.github.io/ccx-notification-writer/packages/consumer_test.html
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"github.com/Shopify/sarama"
"github.com/stretchr/testify/assert"
main "github.com/RedHatInsights/ccx-notification-writer"
types "github.com/RedHatInsights/insights-results-types"
)
// Constants used by unit tests
const (
ConsumerReport = `{
"fingerprints": [],
"info": [],
"reports": [],
"skips": [],
"system": {}
}`
)
// Variables used by unit tests
var (
ExpectedOrgID = types.OrgID(1)
ExpectedAccountNumber = types.AccountNumber(1234)
ExpectedClusterName = types.ClusterName("84f7eedc-0dd8-49cd-9d4d-f6646df3a5bc")
LastCheckedAt = time.Unix(25, 0).UTC()
)
// TestNewConsumerBadBroker function checks the consumer creation by
// using a non-accessible Kafka broker.
func TestNewConsumerBadBrokerNonAccessibleBroker(t *testing.T) {
// expected error message
const expectedErr = "kafka: client has run out of available brokers to talk to: dial tcp: missing address"
// invalid broker configuration
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "",
Topic: "whatever",
Group: "whatever",
Enabled: true,
}
// dummy storage not really usable as the driver is not specified
dummyStorage := main.NewFromConnection(nil, 1)
// try to construct new consumer
mockConsumer, err := main.NewConsumer(&brokerConfiguration, dummyStorage)
// check that error is really reported
assert.Contains(t, err.Error(), expectedErr)
// test the return value
assert.Equal(
t,
(*main.KafkaConsumer)(nil),
mockConsumer,
"consumer.New should return nil instead of Consumer implementation",
)
}
// TestNewConsumerLocalBroker function checks the consumer creation by using a
// non-accessible Kafka broker. This test assumes there is no local Kafka
// instance currently running
func TestNewConsumerLocalBrokerNonAccessibleBroker(t *testing.T) {
// expected error message
const expectedErr = "kafka: client has run out of available brokers to talk to"
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "",
Enabled: true,
}
// dummy storage not really usable as the driver is not specified
dummyStorage := main.NewFromConnection(nil, 1)
// try to construct new consumer
mockConsumer, err := main.NewConsumer(&brokerConfiguration, dummyStorage)
// check that error is really reported
assert.Contains(t, err.Error(), expectedErr)
// test the return value
assert.Equal(
t,
(*main.KafkaConsumer)(nil),
mockConsumer,
"consumer.New should return nil instead of Consumer implementation",
)
}
// TestNewConsumerConsumerGroup function checks the consumer creation by using a
// non-accesible Kafka broker. This test assumes there is no local Kafka
// instance currently running. Consumer group is enabled and setup for this test.
func TestNewConsumerSaramaConfigNonAccessibleBroker(t *testing.T) {
// expected error message
const expectedErr = "kafka: client has run out of available brokers to talk to"
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "test-group",
Enabled: true,
}
// dummy storage not really usable as the driver is not specified
dummyStorage := main.NewFromConnection(nil, 1)
// try to construct new consumer
mockConsumer, err := main.NewConsumer(&brokerConfiguration, dummyStorage)
// check that error is really reported
assert.Contains(t, err.Error(), expectedErr)
// test the return value
assert.Equal(
t,
(*main.KafkaConsumer)(nil),
mockConsumer,
"consumer.New should return nil instead of Consumer implementation",
)
}
// TestNewConsumerTLSEnabled function checks the consumer creation by using a
// non-accesible Kafka broker. This test assumes there is no local Kafka
// instance currently running. TSL is enabled in broker configuration.
func TestNewConsumerTLSEnabledNonAccessibleBroker(t *testing.T) {
// expected error message
const expectedErr = "kafka: client has run out of available brokers to talk to"
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "",
Enabled: true,
SecurityProtocol: "SSL",
}
// dummy storage not really usable as the driver is not specified
dummyStorage := main.NewFromConnection(nil, 1)
// try to construct new consumer
mockConsumer, err := main.NewConsumer(&brokerConfiguration, dummyStorage)
// check that error is really reported
assert.Contains(t, err.Error(), expectedErr)
// test the return value
assert.Equal(
t,
(*main.KafkaConsumer)(nil),
mockConsumer,
"consumer.New should return nil instead of Consumer implementation",
)
}
// TestNewConsumerSASLEnabled function checks the consumer creation by using a
// non-accesible Kafka broker. This test assumes there is no local Kafka
// instance currently running. SASL is enabled in broker configuration.
func TestNewConsumerSASLEnabledNonAccessibleBroker(t *testing.T) {
// expected error message
const expectedErr = "kafka: client has run out of available brokers to talk to"
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "",
Enabled: true,
SecurityProtocol: "SASL_",
SaslUsername: "sasl_user",
SaslPassword: "sasl_password",
SaslMechanism: "",
}
// dummy storage not really usable as the driver is not specified
dummyStorage := main.NewFromConnection(nil, 1)
// try to construct new consumer
mockConsumer, err := main.NewConsumer(&brokerConfiguration, dummyStorage)
// check that error is really reported
assert.Contains(t, err.Error(), expectedErr)
// test the return value
assert.Equal(
t,
(*main.KafkaConsumer)(nil),
mockConsumer,
"consumer.New should return nil instead of Consumer implementation",
)
}
// TestSaramaConfigFromBrokerWithSASLEnabled function checks that the Sarama config returned
// for a broker configuration with SASL enabled contains the expected fields
func TestSaramaConfigFromBrokerWithSASLEnabledNoSASLMechanism(t *testing.T) {
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "",
Enabled: true,
SecurityProtocol: "SASL_",
SaslUsername: "sasl_user",
SaslPassword: "sasl_password",
SaslMechanism: "",
}
saramaConfig, err := main.SaramaConfigFromBrokerConfig(&brokerConfiguration)
assert.Nil(t, err)
assert.True(t, saramaConfig.Net.SASL.Enable)
assert.Equal(t, saramaConfig.Net.SASL.User, brokerConfiguration.SaslUsername)
assert.Equal(t, saramaConfig.Net.SASL.Password, brokerConfiguration.SaslPassword)
assert.Nil(t, saramaConfig.Net.SASL.SCRAMClientGeneratorFunc, "SCRAM client generator function should not be created with given config")
}
// TestSaramaConfigFromBrokerWithSASLEnabled function checks that the Sarama config returned
// for a broker configuration with SASL enabled using SCRAM authentication mechanism
// contains expected fields
func TestSaramaConfigFromBrokerWithSASLEnabledSCRAMAuth(t *testing.T) {
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "",
Enabled: true,
SecurityProtocol: "SASL_",
SaslUsername: "sasl_user",
SaslPassword: "sasl_password",
SaslMechanism: sarama.SASLTypeSCRAMSHA512,
}
saramaConfig, err := main.SaramaConfigFromBrokerConfig(&brokerConfiguration)
assert.Nil(t, err)
assert.True(t, saramaConfig.Net.SASL.Enable)
assert.Equal(t, saramaConfig.Net.SASL.User, brokerConfiguration.SaslUsername)
assert.Equal(t, saramaConfig.Net.SASL.Password, brokerConfiguration.SaslPassword)
assert.NotNil(t, saramaConfig.Net.SASL.SCRAMClientGeneratorFunc, "SCRAM client generator function should have been created with given config")
}
// TestSaramaConfigFromBrokerWithSASLEnabled function checks that the Sarama config returned
// for a broker configuration with SASL enabled using unhandled authentication mechanism
// contains expected fields
func TestSaramaConfigFromBrokerWithSASLEnabledUnexpectedAuthMechanism(t *testing.T) {
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "",
Enabled: true,
SecurityProtocol: "SASL_",
SaslUsername: "sasl_user",
SaslPassword: "sasl_password",
SaslMechanism: sarama.SASLTypeSCRAMSHA256,
}
saramaConfig, err := main.SaramaConfigFromBrokerConfig(&brokerConfiguration)
assert.Nil(t, err)
assert.True(t, saramaConfig.Net.SASL.Enable)
assert.Equal(t, saramaConfig.Net.SASL.User, brokerConfiguration.SaslUsername)
assert.Equal(t, saramaConfig.Net.SASL.Password, brokerConfiguration.SaslPassword)
assert.Nil(t, saramaConfig.Net.SASL.SCRAMClientGeneratorFunc, "SCRAM client generator function should not be created with given config")
}
// TestNewConsumerSASLEnabled function checks the consumer creation by using a
// non-accesible Kafka broker. This test assumes there is no local Kafka
// instance currently running. SASL is enabled in broker configuration.
func TestNewConsumerSASLEnabled(t *testing.T) {
// expected error message
const expectedErr = "kafka: client has run out of available brokers to talk to"
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "",
Enabled: true,
SecurityProtocol: "SASL_",
SaslUsername: "sasl_user",
SaslPassword: "sasl_password",
SaslMechanism: "",
}
// dummy storage not really usable as the driver is not specified
dummyStorage := main.NewFromConnection(nil, 1)
// try to construct new consumer
mockConsumer, err := main.NewConsumer(&brokerConfiguration, dummyStorage)
// check that error is really reported
assert.Contains(t, err.Error(), expectedErr)
// test the return value
assert.Equal(
t,
(*main.KafkaConsumer)(nil),
mockConsumer,
"consumer.New should return nil instead of Consumer implementation",
)
}
// TestNewConsumerCertPath function checks the consumer creation by using a
// non-accesible Kafka broker. This test assumes there is no local Kafka
// instance currently running. Valid cert. path is provided by tests.
func TestNewConsumerCertPathNonAccessibleBroker(t *testing.T) {
// expected error message
const expectedErr = "kafka: client has run out of available brokers to talk to"
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "",
Enabled: true,
CertPath: "testdata/cert.pem",
}
// dummy storage not really usable as the driver is not specified
dummyStorage := main.NewFromConnection(nil, 1)
// try to construct new consumer
mockConsumer, err := main.NewConsumer(&brokerConfiguration, dummyStorage)
// check that error is really reported
assert.Contains(t, err.Error(), expectedErr)
// test the return value
assert.Equal(
t,
(*main.KafkaConsumer)(nil),
mockConsumer,
"invalid cert path",
)
}
// TestNewConsumerInvalidCertPath function checks the consumer creation by using a
// non-accesible Kafka broker. This test assumes there is no local Kafka
// instance currently running. Invalid cert. path is provided by tests.
func TestNewConsumerInvalidCertPathNonAccessibleBroker(t *testing.T) {
// expected error message
const expectedErr = "open /foo/bar/baz: no such file or directory"
// valid broker configuration for local Kafka instance
var brokerConfiguration = main.BrokerConfiguration{
Addresses: "localhost:9092",
Topic: "platform.notifications.ingress",
Group: "",
Enabled: true,
SecurityProtocol: "SSL",
CertPath: "/foo/bar/baz",
}
// dummy storage not really usable as the driver is not specified
dummyStorage := main.NewFromConnection(nil, 1)
// try to construct new consumer
mockConsumer, err := main.NewConsumer(&brokerConfiguration, dummyStorage)
// check that error is really reported
assert.Contains(t, err.Error(), expectedErr)
// test the return value
assert.Equal(
t,
(*main.KafkaConsumer)(nil),
mockConsumer,
"invalid cert path",
)
}
// TestParseEmptyMessage checks how empty message is handled by
// consumer.
func TestParseEmptyMessage(t *testing.T) {
// empty message to be parsed
const emptyMessage = ""
// try to parse the message
_, err := main.ParseMessage([]byte(emptyMessage))
// check for error - it should be reported
assert.EqualError(t, err, "unexpected end of JSON input")
}
// TestParseMessageWithWrongContent checks how message with wrong
// (unexpected) content is handled by consumer.
func TestParseMessageWithWrongContent(t *testing.T) {
// JSON-encoded message with unexpected content
const message = `{"this":"is", "not":"expected content"}`
// try to parse the message
_, err := main.ParseMessage([]byte(message))
// check for error - it should be reported
assert.Error(t, err)
assert.Contains(t, err.Error(), "missing required attribute")
}
// TestParseMessageWithImproperJSON checks how message with wrong
// content which is not parseable as JSON is processed.
func TestParseMessageWithImproperJSON(t *testing.T) {
// message not in JSON format
const message = `"this_is_not_json_dude"`
// try to parse the message
_, err := main.ParseMessage([]byte(message))
// check for error - it should be reported
assert.EqualError(
t,
err,
"json: cannot unmarshal string into Go value of type main.IncomingMessage",
)
}
// TestParseProperMessage checks the parsing of properly declared
// message.
func TestParseProperMessage(t *testing.T) {
// message in JSON format with all required attributes
ConsumerMessage := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report":` + ConsumerReport + `,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
message, err := main.ParseMessage([]byte(ConsumerMessage))
// check for error - it should not be reported
assert.Nil(t, err)
// check returned values
assert.Equal(t, types.OrgID(1), *message.Organization)
assert.Equal(t, ExpectedClusterName, *message.ClusterName)
assert.Equal(t, ExpectedAccountNumber, *message.AccountNumber)
}
// TestParseProperMessageWrongOrgID checks the parsing of message
// with wrong organization ID.
func TestParseProperMessageWrongOrgID(t *testing.T) {
// message with wrong organization ID attribute.
message := `{
"OrgID": "foobar",
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report":` + ConsumerReport + `,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
_, err := main.ParseMessage([]byte(message))
// check for error - it should be reported
assert.EqualError(
t,
err,
"json: cannot unmarshal string into Go struct field IncomingMessage.OrgID of type types.OrgID",
)
}
// TestParseProperMessageWrongAccountNumber checks the parsing of message
// with wrong organization ID.
func TestParseProperMessageWrongAccountNumber(t *testing.T) {
// message with wrong account number attribute.
message := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": "foobar",
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report":` + ConsumerReport + `,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
_, err := main.ParseMessage([]byte(message))
// check for error - it should be reported
assert.EqualError(
t,
err,
"json: cannot unmarshal string into Go struct field IncomingMessage.AccountNumber of type types.AccountNumber",
)
}
// TestParseProperMessageWrongClusterName checks the parsing of message
// with wrong cluster name.
func TestParseProperMessageWrongClusterName(t *testing.T) {
// message with wrong cluster name
message := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "this is not an UUID",
"Report":` + ConsumerReport + `,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
_, err := main.ParseMessage([]byte(message))
// check for error - it should be reported
assert.EqualError(t, err, "cluster name is not a UUID")
}
// TestParseMessageWithoutOrgID checks the parsing of improperly
// declared message - OrgID attribute is missing.
func TestParseMessageWithoutOrgID(t *testing.T) {
// message without OrgID attribute
ConsumerMessage := `{
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report":` + ConsumerReport + `,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
_, err := main.ParseMessage([]byte(ConsumerMessage))
// check for error - it should be reported
assert.EqualError(t, err, "missing required attribute 'OrgID'")
}
// TestParseMessageWithoutAccountNumber checks the parsing of improperly
// declared message - AccountNumber attribute is missing.
func TestParseMessageWithoutAccountNumber(t *testing.T) {
// message without AccountNumber attribute
ConsumerMessage := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report":` + ConsumerReport + `,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
_, err := main.ParseMessage([]byte(ConsumerMessage))
// check for error - it should be reported
assert.EqualError(t, err, "missing required attribute 'AccountNumber'")
}
// TestParseMessageWithoutClusterName checks the parsing of improperly
// declared message - ClusterName attribute is missing.
func TestParseMessageWithoutClusterName(t *testing.T) {
// message without ClusterName attribute
ConsumerMessage := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"Report":` + ConsumerReport + `,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
_, err := main.ParseMessage([]byte(ConsumerMessage))
// check for error - it should be reported
assert.EqualError(t, err, "missing required attribute 'ClusterName'")
}
// TestParseMessageWithoutReport checks the parsing of improperly
// declared message - Report attribute is missing.
func TestParseMessageWithoutReport(t *testing.T) {
// message without Report attribute
ConsumerMessage := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
_, err := main.ParseMessage([]byte(ConsumerMessage))
// check for error - it should be reported
assert.EqualError(t, err, "missing required attribute 'Report'")
}
// TestParseMessageEmptyReport checks the parsing of improperly
// declared message - report attribute is empty.
func TestParseMessageEmptyReport(t *testing.T) {
// message with empty Report attribute
ConsumerMessage := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report": {},
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
_, err := main.ParseMessage([]byte(ConsumerMessage))
// check for error - it should be reported
assert.EqualError(t, err, "Improper report structure, missing key fingerprints")
}
// TestParseMessageNullReport checks the parsing of improperly
// declared message - Report attribute is null.
func TestParseMessageNullReport(t *testing.T) {
// message with empty Report attribute
ConsumerMessage := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report": null,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
// try to parse the message
_, err := main.ParseMessage([]byte(ConsumerMessage))
// check for error - it should be reported
assert.EqualError(t, err, "missing required attribute 'Report'")
}
// NewDummyConsumer function constructs new instance of (not running)
// KafkaConsumer.
func NewDummyConsumer(s main.Storage) *main.KafkaConsumer {
brokerCfg := main.BrokerConfiguration{
Addresses: "localhost:1234",
Topic: "topic",
Group: "group",
}
return &main.KafkaConsumer{
Configuration: brokerCfg,
Storage: s,
Ready: make(chan bool),
}
}
// TestProcessEmptyMessage check the behaviour of function ProcessMessage with
// empty message on input.
func TestProcessEmptyMessage(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
// prepare an empty message
message := sarama.ConsumerMessage{}
// try to process the message
_, err := dummyConsumer.ProcessMessage(&message)
// check for errors - it should be reported
assert.EqualError(t, err, "unexpected end of JSON input")
// nothing should be written into storage
assert.Equal(t, 0, mockStorage.writeReportCalled)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
}
// TestProcessMessageWithWrongDateFormat check the behaviour of function
// ProcessMessage with message with wrong date.
func TestProcessMessageWithWrongDateFormat(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
// prepare a message
message := sarama.ConsumerMessage{}
// fill in a message payload
ConsumerMessage := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report":` + ConsumerReport + `,
"LastChecked": "2020.01.23 16:15:59"
}`
message.Value = []byte(ConsumerMessage)
// try to process the message
_, err := dummyConsumer.ProcessMessage(&message)
// check for errors - it should be reported
assert.EqualError(t, err, "parsing time \"2020.01.23 16:15:59\" as \"2006-01-02T15:04:05.999999999Z07:00\": cannot parse \".01.23 16:15:59\" as \"-\"")
// nothing should be written into storage
assert.Equal(t, 0, mockStorage.writeReportCalled)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
}
// TestProcessMessageFromFuture check the behaviour of function ProcessMessage
// with message with wrong date.
func TestProcessMessageFromFuture(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
// prepare a message
message := sarama.ConsumerMessage{}
// fill in a message payload
ConsumerMessage := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report":` + ConsumerReport + `,
"LastChecked": "2099-01-01T23:59:59.999999999Z"
}`
message.Value = []byte(ConsumerMessage)
// try to process the message
_, err := dummyConsumer.ProcessMessage(&message)
// check for errors - it should be reported
assert.EqualError(t, err, "got a message from the future")
// nothing should be written into storage
assert.Equal(t, 0, mockStorage.writeReportCalled)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
}
// TestProcessCorrectMessage check the behaviour of function ProcessMessage for
// correct message.
func TestProcessCorrectMessage(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
// prepare a message
message := sarama.ConsumerMessage{}
// fill in a message payload
ConsumerMessage := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report":` + ConsumerReport + `,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
message.Value = []byte(ConsumerMessage)
// message is correct -> one record should be written into the database
_, err := dummyConsumer.ProcessMessage(&message)
// check for error - it should not be reported
assert.Nil(t, err)
// one record should be written into the storage
assert.Equal(t, 1, mockStorage.writeReportCalled)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
}
// TestConsumerSetup function checks the method KafkaConsumer.Setup().
func TestConsumerSetup(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
// channel that needs to be closed in Setup
dummyConsumer.Ready = make(chan bool)
// try to setup the consumer (without consumer group)
err := dummyConsumer.Setup(nil)
// and check for any error
assert.Nil(t, err)
}
// TestConsumerCleanup function checks the method KafkaConsumer.Cleanup().
func TestConsumerCleanup(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
// try to cleanup the consumer (without consumer group)
err := dummyConsumer.Cleanup(nil)
// and check for any error
assert.Nil(t, err)
}
// TestConsumerClose function checks the method KafkaConsumer.Close().
func TestConsumerClose(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
// try to close the consumer (without consumer group)
err := dummyConsumer.Close()
// and check for any error
assert.Nil(t, err)
}
// TestConsumerCloseCancel function checks the method KafkaConsumer.Close().
func TestConsumerCloseCancel(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
// setup cancel hook
_, cancel := context.WithCancel(context.Background())
dummyConsumer.Cancel = cancel
// try to close the consumer (without consumer group)
err := dummyConsumer.Close()
// and check for any error
assert.Nil(t, err)
}
// TestHandleNilMessage function checks the method
// KafkaConsumer.HandleMessage() for nil input.
func TestHandleNilMessage(_ *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
// nil message
dummyConsumer.HandleMessage(nil)
}
// TestHandleEmptyMessage function checks the method
// KafkaConsumer.HandleMessage() for empty message value.
func TestHandleEmptyMessage(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
message := sarama.ConsumerMessage{}
message.Value = []byte("")
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
// empty message
dummyConsumer.HandleMessage(&message)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(1), dummyConsumer.GetNumberOfErrorsConsumingMessages())
}
// TestHandleCorrectMessage function checks the method
// KafkaConsumer.HandleMessage() for correct input.
func TestHandleCorrectMessage(t *testing.T) {
// construct mock storage
mockStorage := NewMockStorage()
// construct dummy consumer
dummyConsumer := NewDummyConsumer(&mockStorage)
message := sarama.ConsumerMessage{}
value := `{
"OrgID": ` + fmt.Sprint(ExpectedOrgID) + `,
"AccountNumber": ` + fmt.Sprint(ExpectedAccountNumber) + `,
"ClusterName": "` + string(ExpectedClusterName) + `",
"Report":` + ConsumerReport + `,
"LastChecked": "` + LastCheckedAt.UTC().Format(time.RFC3339) + `"
}`
message.Value = []byte(value)
// counter checks
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
// correct message
dummyConsumer.HandleMessage(&message)
// counter checks
assert.Equal(t, uint64(1), dummyConsumer.GetNumberOfSuccessfullyConsumedMessages())
assert.Equal(t, uint64(0), dummyConsumer.GetNumberOfErrorsConsumingMessages())
}
func testShrinkedMessage(t *testing.T, inputMessage main.Report) {
assert.NotContains(t, inputMessage, "system")
assert.NotContains(t, inputMessage, "fingerprints")
assert.NotContains(t, inputMessage, "skips")
assert.NotContains(t, inputMessage, "info")
assert.NotContains(t, inputMessage, "pass")
assert.NotContains(t, inputMessage, "analysis_metadata")
}
// TestShrinkEmptyMessage tests the function to remove unneeded attributes from incoming message
func TestShrinkEmptyMessage(t *testing.T) {
var inputMessage main.Report = make(map[string]*json.RawMessage)
main.ShrinkMessage(&inputMessage)
testShrinkedMessage(t, inputMessage)
}
// TestShrinkMessageWithAnalysisMetadata tests the function to remove unneeded attributes from incoming message
func TestShrinkMessageWithAnalysisMetadata(t *testing.T) {
var inputMessage main.Report = make(map[string]*json.RawMessage)
analysisMetadata := json.RawMessage("{}")
inputMessage["analysis_metadata"] = &analysisMetadata
main.ShrinkMessage(&inputMessage)
testShrinkedMessage(t, inputMessage)
}