-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathtest_unit.py
More file actions
1573 lines (1374 loc) · 60.9 KB
/
Copy pathtest_unit.py
File metadata and controls
1573 lines (1374 loc) · 60.9 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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# (C) Datadog, Inc. 2023-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import base64
import json
import logging
from contextlib import nullcontext as does_not_raise
import mock
import pytest
from confluent_kafka import TopicPartition
from google.protobuf import descriptor_pb2
from google.protobuf.message import DecodeError
from datadog_checks.kafka_consumer import KafkaCheck
from datadog_checks.kafka_consumer.client import KafkaClient
from datadog_checks.kafka_consumer.kafka_consumer import (
DATA_STREAMS_MESSAGES_CACHE_KEY,
_get_interpolated_timestamp,
_get_protobuf_message_class,
build_avro_schema,
build_protobuf_schema,
build_schema,
deserialize_message,
resolve_start_offsets,
)
pytestmark = [pytest.mark.unit]
def fake_consumer_offsets_for_times(partitions, offset=-1):
"""In our testing environment the offset is 80 for all partitions and topics."""
return [(t, p, 80) for t, p in partitions]
def seed_mock_client(cluster_id="cluster_id"):
"""Set some common defaults for the mock client to kafka."""
client = mock.create_autospec(KafkaClient)
client.list_consumer_groups.return_value = ["consumer_group1", "datadog-agent"]
client.get_partitions_for_topic.return_value = ['partition1']
client.list_consumer_group_offsets.return_value = [("consumer_group1", [("topic1", "partition1", 2)])]
client.describe_consumer_group.return_value = 'STABLE'
client.consumer_get_cluster_id_and_list_topics.return_value = (
cluster_id,
# topics
[
# Used in unit tets
('topic1', ["partition1"]),
('topic2', ["partition2"]),
# Copied from integration tests
('dc', [0, 1]),
('unconsumed_topic', [0, 1]),
('marvel', [0, 1]),
('__consumer_offsets', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
],
)
client.consumer_offsets_for_times = fake_consumer_offsets_for_times
return client
@pytest.mark.parametrize(
'legacy_config, kafka_client_config, value',
[
pytest.param("ssl_check_hostname", "_tls_validate_hostname", False, id='legacy validate_hostname param false'),
pytest.param("ssl_check_hostname", "_tls_validate_hostname", True, id='legacy validate_hostname param true'),
pytest.param("ssl_cafile", "_tls_ca_cert", "ca_file", id='legacy tls_ca_cert param'),
pytest.param("ssl_certfile", "_tls_cert", "cert", id='legacy tls_cert param'),
pytest.param("ssl_keyfile", "_tls_private_key", "private_key", id='legacy tls_private_key param'),
pytest.param(
"ssl_password",
"_tls_private_key_password",
"private_key_password",
id='legacy tls_private_key_password param',
),
],
)
def test_tls_config_legacy(legacy_config, kafka_client_config, value, check):
kafka_consumer_check = check({legacy_config: value})
assert getattr(kafka_consumer_check.config, kafka_client_config) == value
@pytest.mark.parametrize(
'ssl_check_hostname_value, tls_validate_hostname_value, expected_value',
[
pytest.param(True, True, True, id='Both true'),
pytest.param(False, False, False, id='Both false'),
pytest.param(False, True, True, id='only tls_validate_hostname_value true'),
pytest.param(True, False, False, id='only tls_validate_hostname_value false'),
pytest.param(False, "true", True, id='tls_validate_hostname true as string'),
pytest.param(False, "false", False, id='tls_validate_hostname false as string'),
],
)
def test_tls_validate_hostname_conflict(
ssl_check_hostname_value, tls_validate_hostname_value, expected_value, check, kafka_instance
):
kafka_instance.update(
{"ssl_check_hostname": ssl_check_hostname_value, "tls_validate_hostname": tls_validate_hostname_value}
)
kafka_consumer_check = check(kafka_instance)
assert kafka_consumer_check.config._tls_validate_hostname == expected_value
@pytest.mark.parametrize(
'tls_verify, expected',
[
pytest.param({}, "true", id='given empty tls_verify, expect default string true'),
pytest.param({'tls_verify': True}, "true", id='given True tls_verify, expect string true'),
pytest.param(
{
'tls_verify': False,
"tls_cert": None,
"tls_ca_cert": None,
"tls_private_key": None,
"tls_private_key_password": None,
},
"false",
id='given False tls_verify and other TLS options none, expect string false',
),
pytest.param(
{'tls_verify': False, "tls_private_key_password": "password"},
"true",
id='given False tls_verify but TLS password, expect string true',
),
],
)
def test_tls_verify_is_string(tls_verify, expected, check, kafka_instance):
kafka_instance.update(tls_verify)
kafka_consumer_check = check(kafka_instance)
config = kafka_consumer_check.config
assert config._tls_verify == expected
mock_client = mock.MagicMock()
mock_client.get_highwater_offsets.return_value = ({}, "")
mock_client.consumer_get_cluster_id_and_list_topics.return_value = (
"cluster_id",
# topics
[
# Used in unit tets
('topic1', ["partition1"]),
('topic2', ["partition2"]),
# Copied from integration tests
('dc', [0, 1]),
('unconsumed_topic', [0, 1]),
('marvel', [0, 1]),
('__consumer_offsets', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
],
)
@pytest.mark.parametrize(
'sasl_oauth_token_provider, expected_exception, mocked_admin_client',
[
pytest.param(
{},
pytest.raises(Exception, match="sasl_oauth_token_provider required for OAUTHBEARER sasl"),
None,
id="No sasl_oauth_token_provider",
),
pytest.param(
{'sasl_oauth_token_provider': {}},
pytest.raises(Exception, match="The `url` setting of `auth_token` reader is required"),
None,
id="Empty sasl_oauth_token_provider, url missing",
),
pytest.param(
{'sasl_oauth_token_provider': {'url': 'http://fake.url'}},
pytest.raises(Exception, match="The `client_id` setting of `auth_token` reader is required"),
None,
id="client_id missing",
),
pytest.param(
{'sasl_oauth_token_provider': {'url': 'http://fake.url', 'client_id': 'id'}},
pytest.raises(Exception, match="The `client_secret` setting of `auth_token` reader is required"),
None,
id="client_secret missing",
),
pytest.param(
{'sasl_oauth_token_provider': {'url': 'http://fake.url', 'client_id': 'id', 'client_secret': 'secret'}},
does_not_raise(),
mock_client,
id="valid config",
),
pytest.param(
{'sasl_oauth_token_provider': {'method': 'aws_msk_iam'}},
does_not_raise(),
mock_client,
id="valid AWS MSK IAM config",
),
pytest.param(
{'sasl_oauth_token_provider': {'method': 'invalid_method'}},
pytest.raises(
Exception,
match="Invalid method 'invalid_method' for sasl_oauth_token_provider. Must be 'aws_msk_iam' or 'oidc'",
),
None,
id="invalid method",
),
],
)
def test_oauth_config(
sasl_oauth_token_provider, expected_exception, mocked_admin_client, check, dd_run_check, kafka_instance
):
kafka_instance.update(
{
'monitor_unlisted_consumer_groups': True,
'security_protocol': 'SASL_PLAINTEXT',
'sasl_mechanism': 'OAUTHBEARER',
}
)
kafka_instance.update(sasl_oauth_token_provider)
with expected_exception:
with mock.patch(
'datadog_checks.kafka_consumer.kafka_consumer.KafkaClient',
return_value=mocked_admin_client,
):
dd_run_check(check(kafka_instance))
# TODO: After these tests are finished and the revamp is complete,
# the tests should be refactored to be parameters instead of separate tests
def test_when_consumer_lag_less_than_zero_then_emit_event(check, kafka_instance, dd_run_check, aggregator):
# Given
mock_client = seed_mock_client()
# We need the consumer offset to be higher than the highwater offset.
mock_client.list_consumer_group_offsets.return_value = [("consumer_group1", [("topic1", "partition1", 81)])]
kafka_consumer_check = check(kafka_instance)
kafka_consumer_check.client = mock_client
# When
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric(
"kafka.broker_offset",
count=1,
tags=['optional:tag1', 'partition:partition1', 'topic:topic1', 'kafka_cluster_id:cluster_id'],
)
aggregator.assert_metric(
"kafka.consumer_offset",
count=1,
tags=[
'consumer_group:consumer_group1',
'optional:tag1',
'partition:partition1',
'topic:topic1',
'kafka_cluster_id:cluster_id',
],
)
aggregator.assert_metric(
"kafka.consumer_lag",
value=0,
count=1,
tags=[
'consumer_group:consumer_group1',
'optional:tag1',
'partition:partition1',
'topic:topic1',
'kafka_cluster_id:cluster_id',
],
)
aggregator.assert_event(
"Consumer group: consumer_group1, "
"topic: topic1, partition: partition1 has negative consumer lag. "
"This should never happen and will result in the consumer skipping new messages "
"until the lag turns positive.",
count=1,
tags=[
'consumer_group:consumer_group1',
'optional:tag1',
'partition:partition1',
'topic:topic1',
'kafka_cluster_id:cluster_id',
],
)
def test_when_collect_consumer_group_state_is_enabled(check, kafka_instance, dd_run_check, aggregator):
mock_client = seed_mock_client()
kafka_instance["collect_consumer_group_state"] = True
kafka_consumer_check = check(kafka_instance)
kafka_consumer_check.client = mock_client
dd_run_check(kafka_consumer_check)
aggregator.assert_metric(
"kafka.consumer_offset",
count=1,
tags=[
'consumer_group:consumer_group1',
'optional:tag1',
'partition:partition1',
'topic:topic1',
'kafka_cluster_id:cluster_id',
'consumer_group_state:STABLE',
],
)
aggregator.assert_metric(
"kafka.consumer_lag",
count=1,
tags=[
'consumer_group:consumer_group1',
'optional:tag1',
'partition:partition1',
'topic:topic1',
'kafka_cluster_id:cluster_id',
'consumer_group_state:STABLE',
],
)
def test_when_no_partitions_then_emit_warning_log(check, kafka_instance, dd_run_check, aggregator, caplog):
# Given
caplog.set_level(logging.WARNING)
mock_client = seed_mock_client()
mock_client.get_partitions_for_topic.return_value = []
kafka_consumer_check = check(kafka_instance)
kafka_consumer_check.client = mock_client
# When
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric(
"kafka.broker_offset",
count=1,
tags=['optional:tag1', 'partition:partition1', 'topic:topic1', 'kafka_cluster_id:cluster_id'],
)
aggregator.assert_metric("kafka.consumer_offset", count=0)
aggregator.assert_metric("kafka.consumer_lag", count=0)
aggregator.assert_event(
"Consumer group: consumer_group1, "
"topic: topic1, partition: partition1 has negative consumer lag. "
"This should never happen and will result in the consumer skipping new messages "
"until the lag turns positive.",
count=0,
)
expected_warning = (
"Consumer group: consumer_group1 has offsets for topic: topic1, "
"partition: partition1, but that topic has no partitions "
"in the cluster, so skipping reporting these offsets"
)
assert expected_warning in caplog.text
def test_when_partition_not_in_partitions_then_emit_warning_log(
check, kafka_instance, dd_run_check, aggregator, caplog
):
# Given
caplog.set_level(logging.WARNING)
mock_client = seed_mock_client()
mock_client.get_partitions_for_topic.return_value = ['partition2']
kafka_consumer_check = check(kafka_instance)
kafka_consumer_check.client = mock_client
# When
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric(
"kafka.broker_offset",
count=1,
tags=['optional:tag1', 'partition:partition1', 'topic:topic1', 'kafka_cluster_id:cluster_id'],
)
aggregator.assert_metric("kafka.consumer_offset", count=0)
aggregator.assert_metric("kafka.consumer_lag", count=0)
aggregator.assert_event(
"Consumer group: consumer_group1, "
"topic: topic1, partition: partition1 has negative consumer lag. "
"This should never happen and will result in the consumer skipping new messages "
"until the lag turns positive.",
count=0,
)
expected_warning = (
"Consumer group: consumer_group1 has offsets for topic: topic1, partition: partition1, "
"but that topic partition isn't included in the cluster partitions, "
"so skipping reporting these offsets"
)
assert expected_warning in caplog.text
def test_when_highwater_metric_count_hit_context_limit_then_no_more_highwater_metrics(
check, kafka_instance, dd_run_check, aggregator, caplog
):
# Given
caplog.set_level(logging.WARNING)
mock_client = seed_mock_client()
kafka_consumer_check = check(kafka_instance, init_config={'max_partition_contexts': 2})
kafka_consumer_check.client = mock_client
# When
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric("kafka.broker_offset", count=1)
aggregator.assert_metric("kafka.consumer_offset", count=1)
aggregator.assert_metric("kafka.consumer_lag", count=0)
expected_warning = "Discovered 2 metric contexts"
assert expected_warning in caplog.text
def test_when_consumer_metric_count_hit_context_limit_then_no_more_consumer_metrics(
check, kafka_instance, dd_run_check, aggregator, caplog
):
# Given
caplog.set_level(logging.DEBUG)
mock_client = seed_mock_client()
mock_client.list_consumer_group_offsets.return_value = [
("consumer_group1", [("topic1", "partition1", 2)]),
("consumer_group1", [("topic2", "partition2", 2)]),
]
kafka_consumer_check = check(kafka_instance, init_config={'max_partition_contexts': 3})
kafka_consumer_check.client = mock_client
# When
dd_run_check(kafka_consumer_check)
# Then
aggregator.assert_metric("kafka.broker_offset", count=2)
aggregator.assert_metric("kafka.consumer_offset", count=1)
aggregator.assert_metric("kafka.consumer_lag", count=0)
expected_warning = "Discovered 4 metric contexts"
assert expected_warning in caplog.text
expected_debug = "Reported contexts number 1 greater than or equal to contexts limit of 1"
assert expected_debug in caplog.text
def test_when_empty_string_consumer_group_then_skip(kafka_instance):
kafka_instance["monitor_unlisted_consumer_groups"] = True
with mock.patch(
"datadog_checks.kafka_consumer.kafka_consumer.KafkaClient.list_consumer_groups",
return_value=["", "my_consumer"],
):
kafka_consumer_check = KafkaCheck('kafka_consumer', {}, [kafka_instance])
assert kafka_consumer_check._get_consumer_groups() == ["my_consumer"]
def test_get_interpolated_timestamp():
assert _get_interpolated_timestamp({0: 100, 10: 200}, 5) == 150
assert _get_interpolated_timestamp({10: 100, 20: 200}, 5) == 50
assert _get_interpolated_timestamp({0: 100, 10: 200}, 15) == 250
assert _get_interpolated_timestamp({10: 200}, 15) is None
@pytest.mark.parametrize(
'persistent_cache_contents, instance_overrides, consumer_lag_seconds_count',
[
pytest.param(
"",
{
'consumer_groups': {},
'data_streams_enabled': 'true',
'monitor_unlisted_consumer_groups': True,
},
0,
id='Read from cache failed',
),
],
)
def test_load_broker_timestamps_empty(
persistent_cache_contents,
instance_overrides,
consumer_lag_seconds_count,
kafka_instance,
dd_run_check,
caplog,
aggregator,
check,
):
kafka_instance.update(instance_overrides)
mock_client = seed_mock_client()
check = check(kafka_instance)
check.client = mock_client
check.read_persistent_cache = mock.Mock(return_value=persistent_cache_contents)
dd_run_check(check)
caplog.set_level(logging.WARN)
expected_warning = " Could not read broker timestamps from cache"
assert expected_warning in caplog.text
aggregator.assert_metric("kafka.estimated_consumer_lag", count=consumer_lag_seconds_count)
assert check.read_persistent_cache.mock_calls == [mock.call("broker_timestamps_")]
def test_client_init(kafka_instance, check, dd_run_check):
"""
We only open a connection to datadog-agent consumer once.
Doing so more often degrades performance, as described in this issue:
https://github.com/DataDog/integrations-core/issues/19564
"""
mock_client = seed_mock_client()
check = check(kafka_instance)
check.client = mock_client
dd_run_check(check)
assert check.client.open_consumer.mock_calls == [mock.call("datadog-agent")]
def test_add_broker_timestamps_purges_stale_offsets_on_reset(kafka_instance, check):
# When the highwater offset goes backwards (topic recreated / retention
# wipe / offset reset), cached (offset, timestamp) pairs with offsets
# above the new highwater are stale and must be purged — otherwise they
# poison interpolation and pin estimated_consumer_lag to a wall-clock
# offset equal to how long ago the reset happened.
check = check(kafka_instance)
broker_timestamps = {"topic1_0": {1_000_000: 100.0, 999_000: 99.0}}
check._add_broker_timestamps(broker_timestamps, {("topic1", 0): 170})
timestamps = broker_timestamps["topic1_0"]
assert 1_000_000 not in timestamps
assert 999_000 not in timestamps
assert 170 in timestamps
def test_add_broker_timestamps_evicts_by_oldest_timestamp(kafka_instance, check):
# Eviction must drop the entry with the oldest timestamp, not the smallest
# offset. Evicting by min(offset) would discard fresh post-reset entries
# and keep poisonous ones.
kafka_instance['timestamp_history_size'] = 2
check = check(kafka_instance)
broker_timestamps = {"topic1_0": {500: 50.0, 400: 999.0}}
check._add_broker_timestamps(broker_timestamps, {("topic1", 0): 600})
timestamps = broker_timestamps["topic1_0"]
assert 500 not in timestamps # oldest by timestamp
assert 400 in timestamps
assert 600 in timestamps
def test_resolve_start_offsets():
highwater_offsets = {
("topic1", 0): 100,
("topic1", 1): 200,
("topic2", 0): 150,
}
assert resolve_start_offsets(highwater_offsets, "topic1", 0, 80, 10) == [TopicPartition("topic1", 0, 80)]
assert resolve_start_offsets(highwater_offsets, "topic2", 0, -1, 10) == [TopicPartition("topic2", 0, 141)]
assert sorted(resolve_start_offsets(highwater_offsets, "topic1", -1, -1, 10)) == [
TopicPartition("topic1", 0, 81),
TopicPartition("topic1", 1, 191),
]
class MockedMessage:
def __init__(self, value, key=None, offset=0):
self.v = value
self.k = key
self.o = offset
def value(self):
return self.v
def key(self):
return self.k
def partition(self):
return 0
def offset(self):
return self.o
def test_deserialize_message():
message = b'{"name": "Peter Parker", "age": 18, "transaction_amount": 123, "currency": "dollar"}'
# schema ID is 350, which is 0x015E in hex.
# A magic byte (0x00) is added and the schema ID (4-byte big-endian integer).
message_with_schema = (
b'\x00\x00\x00\x01\x5e{"name": "Peter Parker", "age": 18, "transaction_amount": 123, "currency": "dollar"}'
)
key = b'{"name": "Peter Parker"}'
assert deserialize_message(MockedMessage(message, key), 'json', '', False, 'json', '', False) == (
'{"name": "Peter Parker", "age": 18, "transaction_amount": 123, "currency": "dollar"}',
None,
'{"name": "Peter Parker"}',
None,
)
assert deserialize_message(MockedMessage(message_with_schema), 'json', '', False, 'json', '', False) == (
'{"name": "Peter Parker", "age": 18, "transaction_amount": 123, "currency": "dollar"}',
350,
'',
None,
)
invalid_json = b'{"name": "Peter Parker", "age": 18, "transaction_amount": 123, "currency": "dollar"'
assert deserialize_message(MockedMessage(invalid_json, key), 'json', '', False, 'json', '', False) == (
None,
None,
None,
None,
)
invalid_utf8 = b'{"name": "Peter Parker", "age": 18, "transaction_amount": 123, "currency": "dollar"\xff'
assert deserialize_message(MockedMessage(invalid_utf8, key), 'json', '', False, 'json', '', False) == (
None,
None,
None,
None,
)
# Test Avro deserialization
avro_schema = (
'{"type": "record", "name": "Book", "namespace": "com.book", '
'"fields": [{"name": "isbn", "type": "long"}, {"name": "title", "type": "string"}, '
'{"name": "author", "type": "string"}]}'
)
avro_message = b'\xd0\xf5\xe4\xd6\xa3\xb9\x046The Go Programming Language\x18Alan Donovan'
parsed_avro_schema = build_schema('avro', avro_schema)
assert deserialize_message(
MockedMessage(avro_message, key), 'avro', parsed_avro_schema, False, 'json', '', False
) == (
'{"isbn": 9780134190440, "title": "The Go Programming Language", "author": "Alan Donovan"}',
None,
'{"name": "Peter Parker"}',
None,
)
# Test Protobuf deserialization
protobuf_schema = (
'CmoKDHNjaGVtYS5wcm90bxIIY29tLmJvb2siSAoEQm9vaxISCgRpc2JuGAEgASgDUgRpc2Ju'
'EhQKBXRpdGxlGAIgASgJUgV0aXRsZRIWCgZhdXRob3IYAyABKAlSBmF1dGhvcmIGcHJvdG8z'
)
protobuf_message = (
b'\x08\xe8\xba\xb2\xeb\xd1\x9c\x02\x12\x1b\x54\x68\x65\x20\x47\x6f\x20\x50\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x4c\x61\x6e\x67\x75\x61\x67\x65'
b'\x1a\x0c\x41\x6c\x61\x6e\x20\x44\x6f\x6e\x6f\x76\x61\x6e'
)
parsed_protobuf_schema = build_schema('protobuf', protobuf_schema)
assert deserialize_message(
MockedMessage(protobuf_message, key), 'protobuf', parsed_protobuf_schema, False, 'json', '', False
) == (
'{\n "isbn": "9780134190440",\n "title": "The Go Programming Language",\n "author": "Alan Donovan"\n}',
None,
'{"name": "Peter Parker"}',
None,
)
# Test invalid Avro messages
# Empty message (returns empty string, not None)
assert deserialize_message(MockedMessage(b'', key), 'avro', parsed_avro_schema, False, 'json', '', False) == (
'',
None,
'{"name": "Peter Parker"}',
None,
)
# Corrupted message (truncated)
corrupted_avro = b'\xd0\xf5\xe4\xd6\xa3\xb9\x046The Go Programming Language' # Missing author field
assert deserialize_message(
MockedMessage(corrupted_avro, key), 'avro', parsed_avro_schema, False, 'json', '', False
) == (
None,
None,
None,
None,
)
# Wrong data type (string instead of long for isbn)
wrong_type_avro = b'\x02\x12\x1bThe Go Programming Language\x18Alan Donovan' # Wrong encoding for isbn
assert deserialize_message(
MockedMessage(wrong_type_avro, key), 'avro', parsed_avro_schema, False, 'json', '', False
) == (
None,
None,
None,
None,
)
# Random bytes
random_avro = b'\xff\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf0'
assert deserialize_message(
MockedMessage(random_avro, key), 'avro', parsed_avro_schema, False, 'json', '', False
) == (
None,
None,
None,
None,
)
# Completely invalid Avro message (random bytes)
invalid_avro = b'\xff\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf0'
assert deserialize_message(
MockedMessage(invalid_avro, key), 'avro', parsed_avro_schema, False, 'json', '', False
) == (
None,
None,
None,
None,
)
# Avro message with wrong data types (string where long expected)
wrong_type_avro = b'\x02\x12\x1bThe Go Programming Language\x18Alan Donovan' # Wrong encoding for isbn
assert deserialize_message(
MockedMessage(wrong_type_avro, key), 'avro', parsed_avro_schema, False, 'json', '', False
) == (
None,
None,
None,
None,
)
# Test invalid Protobuf messages
# Empty message (returns empty string, not None)
assert deserialize_message(
MockedMessage(b'', key), 'protobuf', parsed_protobuf_schema, False, 'json', '', False
) == (
'',
None,
'{"name": "Peter Parker"}',
None,
)
# Random bytes
random_protobuf = b'\xff\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf0'
assert deserialize_message(
MockedMessage(random_protobuf, key), 'protobuf', parsed_protobuf_schema, False, 'json', '', False
) == (
None,
None,
None,
None,
)
# Completely invalid Protobuf message (random bytes)
invalid_protobuf = b'\xff\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf0'
assert deserialize_message(
MockedMessage(invalid_protobuf, key), 'protobuf', parsed_protobuf_schema, False, 'json', '', False
) == (None, None, None, None)
# Protobuf message with wrong field number (field 99 instead of 1)
wrong_field_protobuf = (
b'\x99\x01\xe8\xba\xb2\xeb\xd1\x9c\x02\x12\x1bThe Go Programming Language\x1a\x0cAlan Donovan'
)
assert deserialize_message(
MockedMessage(wrong_field_protobuf, key), 'protobuf', parsed_protobuf_schema, False, 'json', '', False
) == (None, None, None, None)
# Protobuf message with truncated varint
truncated_varint_protobuf = b'\x08\xff\xff\xff\xff\xff\xff\xff\xff\xff' # Incomplete varint
assert deserialize_message(
MockedMessage(truncated_varint_protobuf, key), 'protobuf', parsed_protobuf_schema, False, 'json', '', False
) == (None, None, None, None)
def test_strict_avro_validation():
"""Test that Avro deserialization fails when not all bytes are consumed."""
key = b'{"name": "Peter Parker"}'
# Test case 1: Simple primitive string schema with extra bytes
# A primitive string in Avro is encoded as: varint length + UTF-8 bytes
# An empty string is just: 0x00 (zero length)
# If we have 0x00 followed by extra bytes (e.g., magic byte + 4 bytes + stuff),
# the string decoder will read the empty string but leave bytes unconsumed
string_schema = '"string"'
parsed_string_schema = build_schema('avro', string_schema)
# Message: 0x00 (empty string) + 0x00 (magic byte) + 4 bytes + some random data
# The Avro string decoder will only consume the first 0x00, leaving the rest
message_with_extra_bytes = b'\x00\x00\x00\x00\x01\x5e\x12\x34\x56\x78'
# This should now fail because not all bytes are consumed
result = deserialize_message(
MockedMessage(message_with_extra_bytes, key), 'avro', parsed_string_schema, False, 'json', '', False
)
assert result == (None, None, None, None), "Expected deserialization to fail due to unconsumed bytes"
# Test case 2: Avro message with trailing garbage bytes after valid data
avro_schema = (
'{"type": "record", "name": "Book", "namespace": "com.book", '
'"fields": [{"name": "isbn", "type": "long"}, {"name": "title", "type": "string"}, '
'{"name": "author", "type": "string"}]}'
)
parsed_avro_schema = build_schema('avro', avro_schema)
# Valid Avro message + trailing garbage
valid_avro_message = b'\xd0\xf5\xe4\xd6\xa3\xb9\x046The Go Programming Language\x18Alan Donovan'
message_with_trailing_bytes = valid_avro_message + b'\xff\xfe\xfd\xfc'
# This should now fail because of the trailing bytes
result = deserialize_message(
MockedMessage(message_with_trailing_bytes, key), 'avro', parsed_avro_schema, False, 'json', '', False
)
assert result == (None, None, None, None), "Expected deserialization to fail due to trailing bytes"
# Test case 3: Simple int schema with extra bytes
int_schema = '"int"'
parsed_int_schema = build_schema('avro', int_schema)
# Message: 0x02 (int value 1) + extra bytes
message_int_with_extra = b'\x02\xde\xad\xbe\xef'
result = deserialize_message(
MockedMessage(message_int_with_extra, key), 'avro', parsed_int_schema, False, 'json', '', False
)
assert result == (None, None, None, None), "Expected deserialization to fail due to unconsumed bytes"
# Test case 4: Verify that valid messages still work
valid_string_message = b'\x0aHello' # Length 5 (encoded as 0x0a = 10/2 = 5) + "Hello"
result = deserialize_message(
MockedMessage(valid_string_message, key), 'avro', parsed_string_schema, False, 'json', '', False
)
assert result[0] == '"Hello"', "Expected valid string message to deserialize correctly"
assert result[1] is None
valid_int_message = b'\x02' # int value 1
result = deserialize_message(
MockedMessage(valid_int_message, key), 'avro', parsed_int_schema, False, 'json', '', False
)
assert result[0] == '1', "Expected valid int message to deserialize correctly"
def test_strict_protobuf_validation():
"""Test that Protobuf deserialization fails when not all bytes are consumed."""
key = b'{"name": "Peter Parker"}'
# Build the same Book schema used in other tests
protobuf_schema = (
'CmoKDHNjaGVtYS5wcm90bxIIY29tLmJvb2siSAoEQm9vaxISCgRpc2JuGAEgASgDUgRpc2Ju'
'EhQKBXRpdGxlGAIgASgJUgV0aXRsZRIWCgZhdXRob3IYAyABKAlSBmF1dGhvcmIGcHJvdG8z'
)
parsed_protobuf_schema = build_schema('protobuf', protobuf_schema)
# Test case 1: Valid Protobuf message with trailing garbage bytes
valid_protobuf_message = (
b'\x08\xe8\xba\xb2\xeb\xd1\x9c\x02\x12\x1b\x54\x68\x65\x20\x47\x6f\x20\x50\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x4c\x61\x6e\x67\x75\x61\x67\x65'
b'\x1a\x0c\x41\x6c\x61\x6e\x20\x44\x6f\x6e\x6f\x76\x61\x6e'
)
message_with_trailing_bytes = valid_protobuf_message + b'\xff\xfe\xfd\xfc'
# This should now fail because of the trailing bytes
result = deserialize_message(
MockedMessage(message_with_trailing_bytes, key), 'protobuf', parsed_protobuf_schema, False, 'json', '', False
)
assert result == (None, None, None, None), "Expected deserialization to fail due to trailing bytes"
# Test case 2: Message with extra fields that aren't in the schema
# Protobuf will parse this but leave bytes unconsumed if there are truly extra bytes beyond valid fields
# Adding a completely invalid trailing byte sequence
message_with_invalid_trailer = valid_protobuf_message + b'\x00\x00\x00\x01\x5e'
result = deserialize_message(
MockedMessage(message_with_invalid_trailer, key),
'protobuf',
parsed_protobuf_schema,
False,
'json',
'',
False,
)
assert result == (None, None, None, None), "Expected deserialization to fail due to unconsumed bytes"
# Test case 3: Verify that valid messages still work
result = deserialize_message(
MockedMessage(valid_protobuf_message, key), 'protobuf', parsed_protobuf_schema, False, 'json', '', False
)
assert result[0] is not None, "Expected valid protobuf message to deserialize correctly"
assert 'The Go Programming Language' in result[0]
def test_schema_registry_explicit_configuration():
"""Test that explicit schema registry configuration is enforced."""
key = b'{"name": "Peter Parker"}'
# Test Avro with value_uses_schema_registry=True
avro_schema = (
'{"type": "record", "name": "Book", "namespace": "com.book", '
'"fields": [{"name": "isbn", "type": "long"}, {"name": "title", "type": "string"}, '
'{"name": "author", "type": "string"}]}'
)
parsed_avro_schema = build_schema('avro', avro_schema)
# Valid Avro message WITHOUT schema registry format
avro_message_no_sr = b'\xd0\xf5\xe4\xd6\xa3\xb9\x046The Go Programming Language\x18Alan Donovan'
# When uses_schema_registry=False, this should work
result = deserialize_message(
MockedMessage(avro_message_no_sr, key), 'avro', parsed_avro_schema, False, 'json', '', False
)
assert result[0] is not None, "Should succeed when uses_schema_registry=False"
assert result[1] is None, "Should have no schema ID"
# When uses_schema_registry=True, this should fail (missing magic byte and schema ID)
result = deserialize_message(
MockedMessage(avro_message_no_sr, key), 'avro', parsed_avro_schema, True, 'json', '', False
)
assert result == (None, None, None, None), "Should fail when uses_schema_registry=True"
# Valid Avro message WITH schema registry format (schema ID 350 = 0x015E)
avro_message_with_sr = (
b'\x00\x00\x00\x01\x5e\xd0\xf5\xe4\xd6\xa3\xb9\x046The Go Programming Language\x18Alan Donovan'
)
# When uses_schema_registry=True, this should work
result = deserialize_message(
MockedMessage(avro_message_with_sr, key), 'avro', parsed_avro_schema, True, 'json', '', False
)
assert result[0] is not None, "Should succeed when uses_schema_registry=True"
assert result[1] == 350, "Should extract schema ID 350"
assert 'The Go Programming Language' in result[0]
# Test with wrong magic byte
wrong_magic_byte = b'\x01\x00\x00\x01\x5e\xd0\xf5\xe4\xd6\xa3\xb9\x046The Go Programming Language\x18Alan Donovan'
result = deserialize_message(
MockedMessage(wrong_magic_byte, key), 'avro', parsed_avro_schema, True, 'json', '', False
)
assert result == (None, None, None, None), "Should fail with wrong magic byte"
# Test with message too short (less than 5 bytes)
too_short = b'\x00\x00\x01'
result = deserialize_message(MockedMessage(too_short, key), 'avro', parsed_avro_schema, True, 'json', '', False)
assert result == (None, None, None, None), "Should fail when message too short for SR format"
# Test Protobuf with value_uses_schema_registry=True
protobuf_schema = (
'CmoKDHNjaGVtYS5wcm90bxIIY29tLmJvb2siSAoEQm9vaxISCgRpc2JuGAEgASgDUgRpc2Ju'
'EhQKBXRpdGxlGAIgASgJUgV0aXRsZRIWCgZhdXRob3IYAyABKAlSBmF1dGhvcmIGcHJvdG8z'
)
parsed_protobuf_schema = build_schema('protobuf', protobuf_schema)
# Valid Protobuf message WITHOUT schema registry format
protobuf_message_no_sr = (
b'\x08\xe8\xba\xb2\xeb\xd1\x9c\x02\x12\x1b\x54\x68\x65\x20\x47\x6f\x20\x50\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x4c\x61\x6e\x67\x75\x61\x67\x65'
b'\x1a\x0c\x41\x6c\x61\x6e\x20\x44\x6f\x6e\x6f\x76\x61\x6e'
)
# When uses_schema_registry=False, this should work
result = deserialize_message(
MockedMessage(protobuf_message_no_sr, key), 'protobuf', parsed_protobuf_schema, False, 'json', '', False
)
assert result[0] is not None, "Protobuf should succeed when uses_schema_registry=False"
assert result[1] is None, "Should have no schema ID"
# When uses_schema_registry=True, this should fail
result = deserialize_message(
MockedMessage(protobuf_message_no_sr, key), 'protobuf', parsed_protobuf_schema, True, 'json', '', False
)
assert result == (None, None, None, None), "Protobuf should fail when uses_schema_registry=True but no SR format"
# Valid Protobuf message WITH schema registry format
# Confluent Protobuf wire format:
# [magic_byte][schema_id:4bytes][array_length:varint][index:varint][protobuf_payload]
protobuf_message_with_sr = (
b'\x00\x00\x00\x01\x5e' # magic byte (0x00) + schema ID 350 (0x0000015e)
b'\x01' # message indices array length = 1
b'\x00' # message index = 0
b'\x08\xe8\xba\xb2\xeb\xd1\x9c\x02\x12\x1b\x54\x68\x65\x20\x47\x6f\x20\x50\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x4c\x61\x6e\x67\x75\x61\x67\x65'
b'\x1a\x0c\x41\x6c\x61\x6e\x20\x44\x6f\x6e\x6f\x76\x61\x6e'
)
# When uses_schema_registry=True, this should work
result = deserialize_message(
MockedMessage(protobuf_message_with_sr, key),
'protobuf',
parsed_protobuf_schema,
True,
'json',
'',
False,
)
assert result[0] is not None, "Protobuf should succeed when uses_schema_registry=True with SR format"
assert result[1] == 350, "Should extract schema ID 350"
assert 'The Go Programming Language' in result[0]
# Test key_uses_schema_registry=True
# When key has no schema registry format but key_uses_schema_registry=True, key decoding should fail
# but value should still succeed
result = deserialize_message(
MockedMessage(avro_message_no_sr, key), 'avro', parsed_avro_schema, False, 'json', '', True
)
# Value should succeed, but key should fail (returning None for key fields)
assert result[0] is not None, "Value should succeed"
assert result[2] is None, "Key should fail when key_uses_schema_registry=True but no SR format"
assert result[3] is None, "Key schema ID should be None when key fails"
def test_protobuf_message_indices_with_schema_registry():
"""Test Confluent Protobuf wire format with different message indices."""
key = b'{"test": "key"}'
# Schema with multiple message types and nested type
# message Book { int64 isbn = 1; string title = 2; }
# message Author { string name = 1; int32 age = 2; }
# message Library { message Section { string name = 1; } string name = 1; }
protobuf_schema = (
'CpMBCgxzY2hlbWEucHJvdG8SC2NvbS5leGFtcGxlIh8KBEJvb2sSCgoEaXNibhgBKAMSCwoFdGl0bGUY'
'AigJIh8KBkF1dGhvchIKCgRuYW1lGAEoCRIJCgNhZ2UYAigFIiwKB0xpYnJhcnkSCgoEbmFtZRgBKAka'
'FQoHU2VjdGlvbhIKCgRuYW1lGAEoCWIGcHJvdG8z'