-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathschema_test.py
More file actions
executable file
·1555 lines (1293 loc) · 51.9 KB
/
Copy pathschema_test.py
File metadata and controls
executable file
·1555 lines (1293 loc) · 51.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
#!/usr/bin/env python3
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
import base64
import math
import requests
from typing import List
from unittest import TestCase, main
import fastavro
import pulsar
from pulsar.schema import *
from enum import Enum
import json
from fastavro.schema import load_schema
from google.protobuf import descriptor_pb2, descriptor_pool, message_factory
def _add_protobuf_field(message, name, number, field_type, type_name=None):
field = message.field.add()
field.name = name
field.number = number
field.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
field.type = field_type
if type_name:
field.type_name = type_name
def _get_message_classes(pool, message_names):
if hasattr(message_factory, 'GetMessageClass'):
return tuple(
message_factory.GetMessageClass(pool.FindMessageTypeByName(message_name))
for message_name in message_names
)
factory = message_factory.MessageFactory(pool)
return tuple(
factory.GetPrototype(pool.FindMessageTypeByName(message_name))
for message_name in message_names
)
def _build_protobuf_test_messages():
file_proto = descriptor_pb2.FileDescriptorProto()
file_proto.name = 'test_schema.proto'
file_proto.package = 'test'
file_proto.syntax = 'proto3'
test_message = file_proto.message_type.add()
test_message.name = 'TestMessage'
_add_protobuf_field(test_message, 'name', 1, descriptor_pb2.FieldDescriptorProto.TYPE_STRING)
_add_protobuf_field(test_message, 'value', 2, descriptor_pb2.FieldDescriptorProto.TYPE_INT32)
nested_message = file_proto.message_type.add()
nested_message.name = 'TestMessageWithNested'
_add_protobuf_field(nested_message, 'str_field', 1, descriptor_pb2.FieldDescriptorProto.TYPE_STRING)
_add_protobuf_field(nested_message, 'int_field', 2, descriptor_pb2.FieldDescriptorProto.TYPE_INT32)
_add_protobuf_field(nested_message, 'double_field', 3, descriptor_pb2.FieldDescriptorProto.TYPE_DOUBLE)
_add_protobuf_field(
nested_message, 'nested', 4, descriptor_pb2.FieldDescriptorProto.TYPE_MESSAGE, '.test.TestInner'
)
inner_message = file_proto.message_type.add()
inner_message.name = 'TestInner'
_add_protobuf_field(inner_message, 'inner_str', 1, descriptor_pb2.FieldDescriptorProto.TYPE_STRING)
_add_protobuf_field(inner_message, 'inner_int', 2, descriptor_pb2.FieldDescriptorProto.TYPE_INT64)
pool = descriptor_pool.DescriptorPool()
pool.AddSerializedFile(file_proto.SerializeToString())
return _get_message_classes(
pool,
('test.TestMessage', 'test.TestMessageWithNested', 'test.TestInner'),
)
TestMessage, TestMessageWithNested, TestInner = _build_protobuf_test_messages()
class ExampleRecord(Record):
str_field = String()
int_field = Integer()
float_field = Float()
bytes_field = Bytes()
class SchemaTest(TestCase):
serviceUrl = 'pulsar://localhost:6650'
def test_simple(self):
class Color(Enum):
red = 1
green = 2
blue = 3
class Example(Record):
_sorted_fields = True
a = String()
b = Integer()
c = Array(String())
d = Color
e = Boolean()
f = Float()
g = Double()
h = Bytes()
i = Map(String())
j = CustomEnum(Color)
fastavro.parse_schema(Example.schema())
self.assertEqual(Example.schema(), {
"name": "Example",
"type": "record",
"fields": [
{"name": "a", "type": ["null", "string"]},
{"name": "b", "type": ["null", "int"]},
{"name": "c", "type": ["null", {
"type": "array",
"items": "string"}]
},
{"name": "d",
"type": ["null", {
"type": "enum",
"name": "Color",
"symbols": ["red", "green", "blue"]}]
},
{"name": "e", "type": ["null", "boolean"]},
{"name": "f", "type": ["null", "float"]},
{"name": "g", "type": ["null", "double"]},
{"name": "h", "type": ["null", "bytes"]},
{"name": "i", "type": ["null", {
"type": "map",
"values": "string"}]
},
{"name": "j", "type": ["null", "Color"]}
]
})
def test_type_promotion(self):
test_cases = [
(20, int, 20), # No promotion necessary: int => int
(20, float, 20.0), # Promotion: int => float
(20.0, float, 20.0), # No Promotion necessary: float => float
("Test text1", bytes, b"Test text1"), # Promotion: str => bytes
(b"Test text1", str, "Test text1"), # Promotion: bytes => str
]
for value_from, type_to, value_to in test_cases:
if type_to == int:
fieldType = Integer()
elif type_to == float:
fieldType = Double()
elif type_to == str:
fieldType = String()
elif type_to == bytes:
fieldType = Bytes()
else:
fieldType = String()
field_value = fieldType.validate_type("test_field", value_from)
self.assertEqual(value_to, field_value)
def test_complex(self):
class Color(Enum):
red = 1
green = 2
blue = 3
class MySubRecord(Record):
_sorted_fields = True
x = Integer()
y = Long()
z = String()
color = CustomEnum(Color)
class Example(Record):
_sorted_fields = True
a = String()
sub = MySubRecord # Test with class
sub2 = MySubRecord() # Test with instance
fastavro.parse_schema(Example.schema())
self.assertEqual(Example.schema(), {
"name": "Example",
"type": "record",
"fields": [
{"name": "a", "type": ["null", "string"]},
{"name": "sub",
"type": ["null", {
"name": "MySubRecord",
"type": "record",
"fields": [
{'name': 'color', 'type': ['null', {'type': 'enum', 'name': 'Color', 'symbols':
['red', 'green', 'blue']}]},
{"name": "x", "type": ["null", "int"]},
{"name": "y", "type": ["null", "long"]},
{"name": "z", "type": ["null", "string"]}]
}]
},
{"name": "sub2",
"type": ["null", 'MySubRecord']
}
]
})
def test_complex_with_required_fields(self):
class MySubRecord(Record):
x = Integer(required=True)
y = Long(required=True)
z = String()
class Example(Record):
a = String(required=True)
sub = MySubRecord(required=True)
self.assertEqual(Example.schema(), {
"name": "Example",
"type": "record",
"fields": [
{"name": "a", "type": "string"},
{"name": "sub",
"type": {
"name": "MySubRecord",
"type": "record",
"fields": [{"name": "x", "type": "int"},
{"name": "y", "type": "long"},
{"name": "z", "type": ["null", "string"]}]
}
},
]
})
def test_invalid_enum(self):
class Color:
red = 1
green = 2
blue = 3
class InvalidEnum(Record):
a = Integer()
b = Color
# Enum will be ignored
self.assertEqual(InvalidEnum.schema(),
{'name': 'InvalidEnum', 'type': 'record',
'fields': [{'name': 'a', 'type': ["null", 'int']}]})
def test_initialization(self):
class Example(Record):
a = Integer()
b = Integer()
r = Example(a=1, b=2)
self.assertEqual(r.a, 1)
self.assertEqual(r.b, 2)
r.b = 5
self.assertEqual(r.b, 5)
# Setting non-declared field should fail
try:
r.c = 3
self.fail('Should have failed')
except AttributeError:
# Expected
pass
try:
Record(a=1, c=8)
self.fail('Should have failed')
except AttributeError:
# Expected
pass
except TypeError:
# Expected
pass
def _expectTypeError(self, func):
try:
func()
self.fail('Should have failed')
except TypeError:
# Expected
pass
def test_field_type_check(self):
class Example(Record):
a = Integer()
b = String(required=False)
self._expectTypeError(lambda: Example(a=1, b=2))
class E2(Record):
a = Boolean()
E2(a=False) # ok
self._expectTypeError(lambda: E2(a=1))
class E3(Record):
a = Float()
E3(a=1.0) # Ok
E3(a=1) # Ok Type promotion: int -> float
class E4(Record):
a = Null()
E4(a=None) # Ok
self._expectTypeError(lambda: E4(a=1))
class E5(Record):
a = Long()
E5(a=1234) # Ok
self._expectTypeError(lambda: E5(a=1.12))
class E6(Record):
a = String()
E6(a="hello") # Ok
self._expectTypeError(lambda: E5(a=1.12))
class E6(Record):
a = Bytes()
E6(a="hello".encode('utf-8')) # Ok
self._expectTypeError(lambda: E5(a=1.12))
class E7(Record):
a = Double()
E7(a=1.0) # Ok
E7(a=1) # Ok Type promotion: int -> double
class Color(Enum):
red = 1
green = 2
blue = 3
class OtherEnum(Enum):
red = 1
green = 2
blue = 3
class E8(Record):
a = Color
e = E8(a=Color.red) # Ok
self.assertEqual(e.a, Color.red)
e = E8(a='red') # Ok
self.assertEqual(e.a, Color.red)
e = E8(a=1) # Ok
self.assertEqual(e.a, Color.red)
self._expectTypeError(lambda: E8(a='redx'))
self._expectTypeError(lambda: E8(a=OtherEnum.red))
self._expectTypeError(lambda: E8(a=5))
class E9(Record):
a = Array(String())
E9(a=['a', 'b', 'c']) # Ok
self._expectTypeError(lambda: E9(a=1))
self._expectTypeError(lambda: E9(a=[1, 2, 3]))
self._expectTypeError(lambda: E9(a=['1', '2', 3]))
class E10(Record):
a = Map(Integer())
E10(a={'a': 1, 'b': 2}) # Ok
self._expectTypeError(lambda: E10(a=1))
self._expectTypeError(lambda: E10(a={'a': '1', 'b': 2}))
self._expectTypeError(lambda: E10(a={1: 1, 'b': 2}))
class SubRecord1(Record):
s = Integer()
class SubRecord2(Record):
s = String()
class E11(Record):
a = SubRecord1
E11(a=SubRecord1(s=1)) # Ok
self._expectTypeError(lambda: E11(a=1))
self._expectTypeError(lambda: E11(a=SubRecord2(s='hello')))
def test_field_type_check_defaults(self):
try:
class Example(Record):
a = Integer(default="xyz")
self.fail("Class declaration should have failed")
except TypeError:
pass # Expected
def test_serialize_json(self):
class Example(Record):
a = Integer()
b = Integer()
self.assertEqual(Example.schema(), {
"name": "Example",
"type": "record",
"fields": [
{"name": "a", "type": ["null", "int"]},
{"name": "b", "type": ["null", "int"]},
]
})
s = JsonSchema(Example)
r = Example(a=1, b=2)
data = s.encode(r)
self.assertEqual(json.loads(data), {'a': 1, 'b': 2})
r2 = s.decode(data)
self.assertEqual(r2.__class__.__name__, 'Example')
self.assertEqual(r2, r)
def test_serialize_avro(self):
class Example(Record):
a = Integer()
b = Integer()
self.assertEqual(Example.schema(), {
"name": "Example",
"type": "record",
"fields": [
{"name": "a", "type": ["null", "int"]},
{"name": "b", "type": ["null", "int"]},
]
})
s = AvroSchema(Example)
r = Example(a=1, b=2)
data = s.encode(r)
r2 = s.decode(data)
self.assertEqual(r2.__class__.__name__, 'Example')
self.assertEqual(r2, r)
def test_non_sorted_fields(self):
class T1(Record):
a = Integer()
b = Integer()
c = Double()
d = String()
class T2(Record):
b = Integer()
a = Integer()
d = String()
c = Double()
self.assertNotEqual(T1.schema()['fields'], T2.schema()['fields'])
def test_sorted_fields(self):
class T1(Record):
_sorted_fields = True
a = Integer()
b = Integer()
class T2(Record):
_sorted_fields = True
b = Integer()
a = Integer()
self.assertEqual(T1.schema()['fields'], T2.schema()['fields'])
def test_schema_version(self):
class Example(Record):
a = Integer()
b = Integer()
client = pulsar.Client(self.serviceUrl)
producer = client.create_producer(
'my-avro-python-schema-version-topic',
schema=AvroSchema(Example))
consumer = client.subscribe('my-avro-python-schema-version-topic', 'sub-1',
schema=AvroSchema(Example))
r = Example(a=1, b=2)
producer.send(r)
msg = consumer.receive()
self.assertIsNotNone(msg.schema_version())
self.assertEqual(b'\x00\x00\x00\x00\x00\x00\x00\x00', msg.schema_version().encode())
self.assertEqual(r, msg.value())
client.close()
def test_serialize_wrong_types(self):
class Example(Record):
a = Integer()
b = Integer()
class Foo(Record):
x = Integer()
y = Integer()
s = JsonSchema(Example)
try:
data = s.encode(Foo(x=1, y=2))
self.fail('Should have failed')
except TypeError:
pass # expected
try:
data = s.encode('hello')
self.fail('Should have failed')
except TypeError:
pass # expected
def test_defaults(self):
class Example(Record):
a = Integer(default=5)
b = Integer()
c = String(default='hello')
r = Example()
self.assertEqual(r.a, 5)
self.assertEqual(r.b, None)
self.assertEqual(r.c, 'hello')
def test_none_value(self):
"""
The objective of the test is to check that if no value is assigned to the attribute, the validation is returning
the expect default value as defined in the Field class
"""
class Example(Record):
a = Null()
b = Boolean()
c = Integer()
d = Long()
e = Float()
f = Double()
g = Bytes()
h = String()
r = Example()
self.assertIsNone(r.a)
self.assertFalse(r.b)
self.assertIsNone(r.c)
self.assertIsNone(r.d)
self.assertIsNone(r.e)
self.assertIsNone(r.f)
self.assertIsNone(r.g)
self.assertIsNone(r.h)
####
def test_json_schema(self):
class Example(Record):
a = Integer()
b = Integer()
# Incompatible variation of the class
class BadExample(Record):
a = String()
b = Integer()
client = pulsar.Client(self.serviceUrl)
producer = client.create_producer(
'my-json-python-topic',
schema=JsonSchema(Example))
# Validate that incompatible schema is rejected
try:
client.subscribe('my-json-python-topic', 'sub-1',
schema=JsonSchema(BadExample))
self.fail('Should have failed')
except Exception as e:
pass # Expected
try:
client.subscribe('my-json-python-topic', 'sub-1',
schema=StringSchema(BadExample))
self.fail('Should have failed')
except Exception as e:
pass # Expected
try:
client.subscribe('my-json-python-topic', 'sub-1',
schema=AvroSchema(BadExample))
self.fail('Should have failed')
except Exception as e:
pass # Expected
consumer = client.subscribe('my-json-python-topic', 'sub-1',
schema=JsonSchema(Example))
r = Example(a=1, b=2)
producer.send(r)
msg = consumer.receive()
self.assertEqual(r, msg.value())
producer.close()
consumer.close()
client.close()
def test_string_schema(self):
client = pulsar.Client(self.serviceUrl)
producer = client.create_producer(
'my-string-python-topic',
schema=StringSchema())
# Validate that incompatible schema is rejected
try:
class Example(Record):
a = Integer()
b = Integer()
client.create_producer('my-string-python-topic',
schema=JsonSchema(Example))
self.fail('Should have failed')
except Exception as e:
pass # Expected
consumer = client.subscribe('my-string-python-topic', 'sub-1',
schema=StringSchema())
producer.send("Hello")
msg = consumer.receive()
self.assertEqual("Hello", msg.value())
self.assertEqual(b"Hello", msg.data())
client.close()
def test_bytes_schema(self):
client = pulsar.Client(self.serviceUrl)
producer = client.create_producer(
'my-bytes-python-topic',
schema=BytesSchema())
# Validate that incompatible schema is rejected
try:
class Example(Record):
a = Integer()
b = Integer()
client.create_producer('my-bytes-python-topic',
schema=JsonSchema(Example))
self.fail('Should have failed')
except Exception as e:
pass # Expected
consumer = client.subscribe('my-bytes-python-topic', 'sub-1',
schema=BytesSchema())
producer.send(b"Hello")
msg = consumer.receive()
self.assertEqual(b"Hello", msg.value())
client.close()
def test_avro_schema(self):
class Example(Record):
a = Integer()
b = Integer()
# Incompatible variation of the class
class BadExample(Record):
a = String()
b = Integer()
client = pulsar.Client(self.serviceUrl)
producer = client.create_producer(
'my-avro-python-topic',
schema=AvroSchema(Example))
# Validate that incompatible schema is rejected
try:
client.subscribe('my-avro-python-topic', 'sub-1',
schema=AvroSchema(BadExample))
self.fail('Should have failed')
except Exception as e:
pass # Expected
try:
client.subscribe('my-avro-python-topic', 'sub-2',
schema=JsonSchema(Example))
self.fail('Should have failed')
except Exception as e:
pass # Expected
consumer = client.subscribe('my-avro-python-topic', 'sub-3',
schema=AvroSchema(Example))
r = Example(a=1, b=2)
producer.send(r)
msg = consumer.receive()
self.assertEqual(r, msg.value())
producer.close()
consumer.close()
client.close()
def test_json_enum(self):
class MyEnum(Enum):
A = 1
B = 2
C = 3
class Example(Record):
name = String()
v = MyEnum
w = CustomEnum(MyEnum)
x = CustomEnum(MyEnum, required=True, default=MyEnum.A, required_default=True)
topic = 'my-json-enum-topic'
client = pulsar.Client(self.serviceUrl)
producer = client.create_producer(
topic=topic,
schema=JsonSchema(Example))
consumer = client.subscribe(topic, 'test',
schema=JsonSchema(Example))
r = Example(name='test', v=MyEnum.C, w=MyEnum.B)
producer.send(r)
msg = consumer.receive()
self.assertEqual('test', msg.value().name)
self.assertEqual(MyEnum.C, MyEnum(msg.value().v))
self.assertEqual(MyEnum.B, MyEnum(msg.value().w))
self.assertEqual(MyEnum.A, MyEnum(msg.value().x))
client.close()
def test_avro_enum(self):
class MyEnum(Enum):
A = 1
B = 2
C = 3
class Example(Record):
name = String()
v = MyEnum
w = CustomEnum(MyEnum)
x = CustomEnum(MyEnum, required=True, default=MyEnum.B, required_default=True)
topic = 'my-avro-enum-topic'
client = pulsar.Client(self.serviceUrl)
producer = client.create_producer(
topic=topic,
schema=AvroSchema(Example))
consumer = client.subscribe(topic, 'test',
schema=AvroSchema(Example))
r = Example(name='test', v=MyEnum.C, w=MyEnum.A)
producer.send(r)
msg = consumer.receive()
msg.value()
self.assertEqual(MyEnum.C, msg.value().v)
self.assertEqual(MyEnum.A, MyEnum(msg.value().w))
self.assertEqual(MyEnum.B, MyEnum(msg.value().x))
client.close()
def test_avro_map_array(self):
class MapArray(Record):
values = Map(Array(Integer()))
class MapMap(Record):
values = Map(Map(Integer()))
class ArrayMap(Record):
values = Array(Map(Integer()))
class ArrayArray(Record):
values = Array(Array(Integer()))
topic_prefix = "my-avro-map-array-topic-"
data_list = (
(topic_prefix + "0", AvroSchema(MapArray),
MapArray(values={"A": [1, 2], "B": [3]})),
(topic_prefix + "1", AvroSchema(MapMap),
MapMap(values={"A": {"B": 2},})),
(topic_prefix + "2", AvroSchema(ArrayMap),
ArrayMap(values=[{"A": 1}, {"B": 2}, {"C": 3}])),
(topic_prefix + "3", AvroSchema(ArrayArray),
ArrayArray(values=[[1, 2, 3], [4]])),
)
client = pulsar.Client(self.serviceUrl)
for data in data_list:
topic = data[0]
schema = data[1]
record = data[2]
producer = client.create_producer(topic, schema=schema)
consumer = client.subscribe(topic, 'sub', schema=schema)
producer.send(record)
msg = consumer.receive()
self.assertEqual(msg.value().values, record.values)
consumer.acknowledge(msg)
consumer.close()
producer.close()
client.close()
def test_avro_required_default(self):
class MySubRecord(Record):
_sorted_fields = True
x = Integer()
y = Long()
z = String()
class Example(Record):
a = Integer()
b = Boolean(required=True)
c = Long()
d = Float()
e = Double()
f = String()
g = Bytes()
h = Array(String())
i = Map(String())
j = MySubRecord()
class ExampleRequiredDefault(Record):
_sorted_fields = True
a = Integer(required_default=True)
b = Boolean(required=True, required_default=True)
c = Long(required_default=True)
d = Float(required_default=True)
e = Double(required_default=True)
f = String(required_default=True)
g = Bytes(required_default=True)
h = Array(String(), required_default=True)
i = Map(String(), required_default=True)
j = MySubRecord(required_default=True)
self.assertEqual(ExampleRequiredDefault.schema(), {
"name": "ExampleRequiredDefault",
"type": "record",
"fields": [
{
"name": "a",
"type": [
"null",
"int"
],
"default": None
},
{
"name": "b",
"type": "boolean",
"default": False
},
{
"name": "c",
"type": [
"null",
"long"
],
"default": None
},
{
"name": "d",
"type": [
"null",
"float"
],
"default": None
},
{
"name": "e",
"type": [
"null",
"double"
],
"default": None
},
{
"name": "f",
"type": [
"null",
"string"
],
"default": None
},
{
"name": "g",
"type": [
"null",
"bytes"
],
"default": None
},
{
"name": "h",
"type": [
"null",
{
"type": "array",
"items": "string"
}
],
"default": None
},
{
"name": "i",
"type": [
"null",
{
"type": "map",
"values": "string"
}
],
"default": None
},
{
"name": "j",
"type": [
"null",
{
"name": "MySubRecord",
"type": "record",
"fields": [
{
"name": "x",
"type": [
"null",
"int"
]
},
{
"name": "y",
"type": [
"null",
"long"
],
},
{
"name": "z",
"type": [
"null",
"string"
]
}
]
}
],
"default": None
}
]
})
client = pulsar.Client(self.serviceUrl)
producer = client.create_producer(
'my-avro-python-default-topic',
schema=AvroSchema(Example))
producer_default = client.create_producer(
'my-avro-python-default-topic',
schema=AvroSchema(ExampleRequiredDefault))
producer.close()
producer_default.close()
client.close()
def test_default_value(self):