Debian Codegraph @

tests/integration/schema_registry/_async/test_proto_serializers.py

raw symbols SCIP
1 #!/usr/bin/env python
2 #
3 # Copyright 2016 Confluent Inc.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 import pytest
18
19 from confluent_kafka import TopicPartition, KafkaException, KafkaError
20 from confluent_kafka.error import ConsumeError
21 from confluent_kafka.schema_registry.protobuf import AsyncProtobufSerializer, AsyncProtobufDeserializer
22 from tests.integration.schema_registry.data.proto import metadata_proto_pb2, NestedTestProto_pb2, TestProto_pb2, \
23 PublicTestProto_pb2
24 from tests.integration.schema_registry.data.proto.DependencyTestProto_pb2 import DependencyMessage
25 from tests.integration.schema_registry.data.proto.exampleProtoCriteo_pb2 import ClickCas
26
27
28 @pytest.mark.parametrize("pb2, data", [
29 (TestProto_pb2.TestMessage, {'test_string': "abc",
30 'test_bool': True,
31 'test_bytes': b'look at these bytes',
32 'test_double': 1.0,
33 'test_float': 12.0}),
34 (PublicTestProto_pb2.TestMessage, {'test_string': "abc",
35 'test_bool': True,
36 'test_bytes': b'look at these bytes',
37 'test_double': 1.0,
38 'test_float': 12.0}),
39 (NestedTestProto_pb2.NestedMessage, {'user_id':
40 NestedTestProto_pb2.UserId(
41 kafka_user_id='oneof_str'),
42 'is_active': True,
43 'experiments_active': ['x', 'y', '1'],
44 'status': NestedTestProto_pb2.INACTIVE,
45 'complex_type':
46 NestedTestProto_pb2.ComplexType(
47 one_id='oneof_str',
48 is_active=False)})
49 ])
50 async def test_protobuf_message_serialization(kafka_cluster, pb2, data):
51 """
52 Validates that we get the same message back that we put in.
53
54 """
55 topic = kafka_cluster.create_topic_and_wait_propogation("serialization-proto")
56 sr = kafka_cluster.async_schema_registry()
57
58 value_serializer = await AsyncProtobufSerializer(pb2, sr, {'use.deprecated.format': False})
59 value_deserializer = await AsyncProtobufDeserializer(pb2, {'use.deprecated.format': False})
60
61 producer = kafka_cluster.async_producer(value_serializer=value_serializer)
62 consumer = kafka_cluster.async_consumer(value_deserializer=value_deserializer)
63 consumer.assign([TopicPartition(topic, 0)])
64
65 expect = pb2(**data)
66 await producer.produce(topic, value=expect, partition=0)
67 producer.flush()
68
69 msg = await consumer.poll()
70 actual = msg.value()
71
72 assert [getattr(expect, k) == getattr(actual, k) for k in data.keys()]
73
74
75 @pytest.mark.parametrize("pb2, expected_refs", [
76 (TestProto_pb2.TestMessage, ['google/protobuf/descriptor.proto']),
77 (NestedTestProto_pb2.NestedMessage, ['google/protobuf/timestamp.proto']),
78 (DependencyMessage, ['NestedTestProto.proto', 'PublicTestProto.proto']),
79 (ClickCas, ['metadata_proto.proto', 'common_proto.proto'])
80 ])
81 async def test_protobuf_reference_registration(kafka_cluster, pb2, expected_refs):
82 """
83 Registers multiple messages with dependencies then queries the Schema
84 Registry to ensure the references match up.
85
86 """
87 sr = kafka_cluster.async_schema_registry()
88 topic = kafka_cluster.create_topic_and_wait_propogation("serialization-proto-refs")
89 serializer = await AsyncProtobufSerializer(pb2, sr, {'use.deprecated.format': False})
90 producer = kafka_cluster.async_producer(key_serializer=serializer)
91
92 await producer.produce(topic, key=pb2(), partition=0)
93 producer.flush()
94
95 registered_refs = (await sr.get_schema(serializer._schema_id.id)).references
96
97 assert expected_refs.sort() == [ref.name for ref in registered_refs].sort()
98
99
100 async def test_protobuf_serializer_type_mismatch(kafka_cluster):
101 """
102 Ensures an Exception is raised when deserializing an unexpected type.
103
104 """
105 pb2_1 = TestProto_pb2.TestMessage
106 pb2_2 = NestedTestProto_pb2.NestedMessage
107
108 sr = kafka_cluster.async_schema_registry()
109 topic = kafka_cluster.create_topic_and_wait_propogation("serialization-proto-refs")
110 serializer = await AsyncProtobufSerializer(pb2_1, sr, {'use.deprecated.format': False})
111
112 producer = kafka_cluster.async_producer(key_serializer=serializer)
113
114 with pytest.raises(KafkaException,
115 match=r"message must be of type <class"
116 r" 'tests.integration.schema_registry.data.proto.TestProto_pb2.TestMessage'\> not \<class"
117 r" 'tests.integration.schema_registry.data.proto.NestedTestProto_pb2.NestedMessage'\>"):
118 await producer.produce(topic, key=pb2_2())
119
120
121 async def test_protobuf_deserializer_type_mismatch(kafka_cluster):
122 """
123 Ensures an Exception is raised when deserializing an unexpected type.
124
125 """
126 pb2_1 = PublicTestProto_pb2.TestMessage
127 pb2_2 = metadata_proto_pb2.HDFSOptions
128
129 sr = kafka_cluster.async_schema_registry()
130 topic = kafka_cluster.create_topic_and_wait_propogation("serialization-proto-refs")
131 serializer = await AsyncProtobufSerializer(pb2_1, sr, {'use.deprecated.format': False})
132 deserializer = await AsyncProtobufDeserializer(pb2_2, {'use.deprecated.format': False})
133
134 producer = kafka_cluster.async_producer(key_serializer=serializer)
135 consumer = kafka_cluster.async_consumer(key_deserializer=deserializer)
136 consumer.assign([TopicPartition(topic, 0)])
137
138 def dr(err, msg):
139 print("dr msg {} {}".format(msg.key(), msg.value()))
140
141 await producer.produce(
142 topic,
143 key=pb2_1(test_string='abc', test_bool=True, test_bytes=b'def'),
144 partition=0
145 )
146 producer.flush()
147
148 with pytest.raises(ConsumeError) as e:
149 await consumer.poll()
150 assert e.value.code == KafkaError._KEY_DESERIALIZATION