| 1 |
""" |
| 2 |
Ducktape test for Confluent Kafka Python Consumer |
| 3 |
Assumes Kafka is already running on localhost:9092 |
| 4 |
""" |
| 5 |
|
| 6 |
import time |
| 7 |
import uuid |
| 8 |
from ducktape.tests.test import Test |
| 9 |
from ducktape.mark import matrix |
| 10 |
|
| 11 |
from tests.ducktape.services.kafka import KafkaClient |
| 12 |
from tests.ducktape.consumer_benchmark_metrics import ( |
| 13 |
ConsumerMetricsCollector, |
| 14 |
ConsumerMetricsBounds, |
| 15 |
validate_consumer_metrics, |
| 16 |
print_consumer_metrics_report, |
| 17 |
) |
| 18 |
from tests.ducktape.consumer_strategy import SyncConsumerStrategy, AsyncConsumerStrategy |
| 19 |
from confluent_kafka import Producer |
| 20 |
from confluent_kafka.schema_registry import SchemaRegistryClient |
| 21 |
from confluent_kafka.schema_registry.avro import AvroSerializer |
| 22 |
from confluent_kafka.schema_registry._sync.json_schema import JSONSerializer |
| 23 |
from confluent_kafka.schema_registry._sync.protobuf import ProtobufSerializer |
| 24 |
from confluent_kafka.serialization import ( |
| 25 |
StringSerializer, |
| 26 |
SerializationContext, |
| 27 |
MessageField, |
| 28 |
) |
| 29 |
from tests.integration.schema_registry.data.proto import PublicTestProto_pb2 |
| 30 |
import json |
| 31 |
import asyncio |
| 32 |
import pytest |
| 33 |
|
| 34 |
|
| 35 |
class SimpleConsumerTest(Test): |
| 36 |
"""Test basic consumer functionality with external Kafka""" |
| 37 |
|
| 38 |
def __init__(self, test_context): |
| 39 |
super(SimpleConsumerTest, self).__init__(test_context=test_context) |
| 40 |
|
| 41 |
|
| 42 |
self.kafka = KafkaClient(test_context, bootstrap_servers="localhost:9092") |
| 43 |
|
| 44 |
def setup(self): |
| 45 |
"""Set up test environment""" |
| 46 |
self.logger.info("Verifying connection to external Kafka at localhost:9092") |
| 47 |
|
| 48 |
if not self.kafka.verify_connection(): |
| 49 |
raise Exception( |
| 50 |
"Cannot connect to Kafka at localhost:9092. " |
| 51 |
"Please ensure Kafka is running." |
| 52 |
) |
| 53 |
|
| 54 |
self.logger.info("Successfully connected to Kafka") |
| 55 |
|
| 56 |
def create_consumer_strategy(self, consumer_type, group_id=None, batch_size=10): |
| 57 |
"""Create appropriate consumer strategy based on type""" |
| 58 |
if not group_id: |
| 59 |
group_id = f"test-group-{uuid.uuid4()}" |
| 60 |
|
| 61 |
if consumer_type == "sync": |
| 62 |
return SyncConsumerStrategy( |
| 63 |
self.kafka.bootstrap_servers(), group_id, self.logger, batch_size |
| 64 |
) |
| 65 |
else: |
| 66 |
return AsyncConsumerStrategy( |
| 67 |
self.kafka.bootstrap_servers(), group_id, self.logger, batch_size |
| 68 |
) |
| 69 |
|
| 70 |
def create_consumer(self, consumer_type, group_id=None, batch_size=10): |
| 71 |
return self.create_consumer_strategy( |
| 72 |
consumer_type, group_id, batch_size |
| 73 |
).create_consumer() |
| 74 |
|
| 75 |
def produce_test_messages(self, topic_name, num_messages, serialization_type=None): |
| 76 |
"""Produce messages to topic for consumer tests with optional Schema Registry serialization""" |
| 77 |
|
| 78 |
producer_config = { |
| 79 |
"bootstrap.servers": self.kafka.bootstrap_servers(), |
| 80 |
"client.id": "ducktape-test-producer", |
| 81 |
} |
| 82 |
producer = Producer(producer_config) |
| 83 |
|
| 84 |
|
| 85 |
if serialization_type: |
| 86 |
key_serializer, value_serializer = self.create_serializers( |
| 87 |
serialization_type |
| 88 |
) |
| 89 |
self.logger.info( |
| 90 |
f"Producing {num_messages} messages with {serialization_type} serialization to {topic_name}" |
| 91 |
) |
| 92 |
else: |
| 93 |
self.logger.info(f"Producing {num_messages} messages to {topic_name}") |
| 94 |
|
| 95 |
|
| 96 |
for i in range(num_messages): |
| 97 |
try: |
| 98 |
|
| 99 |
if serialization_type == "protobuf": |
| 100 |
message_value = PublicTestProto_pb2.TestMessage( |
| 101 |
test_string=f"User{i}", |
| 102 |
test_bool=i % 2 == 0, |
| 103 |
test_bytes=f"bytes{i}".encode("utf-8"), |
| 104 |
test_double=float(i), |
| 105 |
test_float=float(i), |
| 106 |
test_fixed32=i, |
| 107 |
test_fixed64=i, |
| 108 |
test_int32=i, |
| 109 |
test_int64=i, |
| 110 |
test_sfixed32=i, |
| 111 |
test_sfixed64=i, |
| 112 |
test_sint32=i, |
| 113 |
test_sint64=i, |
| 114 |
test_uint32=i, |
| 115 |
test_uint64=i, |
| 116 |
) |
| 117 |
elif serialization_type: |
| 118 |
|
| 119 |
|
| 120 |
if serialization_type == "json": |
| 121 |
test_bytes = f"bytes{i}" |
| 122 |
else: |
| 123 |
test_bytes = f"bytes{i}".encode( |
| 124 |
"utf-8" |
| 125 |
) |
| 126 |
|
| 127 |
message_value = { |
| 128 |
"test_string": f"User{i}", |
| 129 |
"test_bool": i % 2 == 0, |
| 130 |
"test_bytes": test_bytes, |
| 131 |
"test_double": float(i), |
| 132 |
"test_float": float(i), |
| 133 |
"test_fixed32": i, |
| 134 |
"test_fixed64": i, |
| 135 |
"test_int32": i, |
| 136 |
"test_int64": i, |
| 137 |
"test_sfixed32": i, |
| 138 |
"test_sfixed64": i, |
| 139 |
"test_sint32": i, |
| 140 |
"test_sint64": i, |
| 141 |
"test_uint32": i, |
| 142 |
"test_uint64": i, |
| 143 |
} |
| 144 |
else: |
| 145 |
|
| 146 |
message_value = None |
| 147 |
|
| 148 |
|
| 149 |
if serialization_type: |
| 150 |
serialized_key = key_serializer(f"key{i}") |
| 151 |
serialized_value = value_serializer( |
| 152 |
message_value, |
| 153 |
SerializationContext(topic_name, MessageField.VALUE), |
| 154 |
) |
| 155 |
else: |
| 156 |
serialized_key = f"key-{i}" |
| 157 |
serialized_value = f"User{i}" |
| 158 |
|
| 159 |
producer.produce( |
| 160 |
topic=topic_name, |
| 161 |
key=serialized_key, |
| 162 |
value=serialized_value, |
| 163 |
) |
| 164 |
|
| 165 |
|
| 166 |
if i % 50 == 0: |
| 167 |
producer.poll(0) |
| 168 |
if i % 1000 == 0: |
| 169 |
producer.flush(timeout=1) |
| 170 |
|
| 171 |
except Exception as e: |
| 172 |
self.logger.error(f"Failed to produce message {i}: {e}") |
| 173 |
|
| 174 |
|
| 175 |
producer.flush(timeout=60) |
| 176 |
self.logger.info(f"Successfully produced {num_messages} plain text messages") |
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
@matrix(consumer_type=["sync", "async"], batch_size=[1, 5, 20]) |
| 181 |
def test_basic_consume(self, consumer_type, batch_size): |
| 182 |
"""Test batch consumption with comprehensive metrics and bounds validation""" |
| 183 |
|
| 184 |
self._run_consumer_performance_benchmark( |
| 185 |
consumer_type=consumer_type, |
| 186 |
operation_type="consume", |
| 187 |
batch_size=batch_size, |
| 188 |
) |
| 189 |
|
| 190 |
@matrix(consumer_type=["sync", "async"]) |
| 191 |
def test_basic_poll(self, consumer_type): |
| 192 |
"""Test single message polling with comprehensive metrics and bounds validation""" |
| 193 |
|
| 194 |
self._run_consumer_performance_benchmark( |
| 195 |
consumer_type=consumer_type, |
| 196 |
operation_type="poll", |
| 197 |
) |
| 198 |
|
| 199 |
@matrix( |
| 200 |
consumer_type=["sync", "async"], serialization_type=["avro", "json", "protobuf"] |
| 201 |
) |
| 202 |
def test_basic_consume_with_schema_registry( |
| 203 |
self, consumer_type, serialization_type |
| 204 |
): |
| 205 |
""" |
| 206 |
Test batch consumption with Schema Registry deserialization with comprehensive metrics and bounds validation. |
| 207 |
|
| 208 |
Note: in this test, we are consuming messages with the same schema, |
| 209 |
a realistic high-throughput scenario. |
| 210 |
We cache the schema in the Schema Registry client, so only the first message |
| 211 |
makes HTTP calls to the Schema Registry server. |
| 212 |
Performance impact compared to test_basic_consume should come from per-message |
| 213 |
deserialization overhead. |
| 214 |
""" |
| 215 |
|
| 216 |
self._run_consumer_performance_benchmark( |
| 217 |
consumer_type=consumer_type, |
| 218 |
operation_type="consume", |
| 219 |
batch_size=20, |
| 220 |
serialization_type=serialization_type, |
| 221 |
num_messages_to_produce=500000, |
| 222 |
) |
| 223 |
|
| 224 |
@matrix( |
| 225 |
consumer_type=["sync", "async"], serialization_type=["avro", "json", "protobuf"] |
| 226 |
) |
| 227 |
def test_basic_poll_with_schema_registry(self, consumer_type, serialization_type): |
| 228 |
""" |
| 229 |
Test single message polling with Schema Registry deserialization with comprehensive metrics |
| 230 |
and bounds validation. |
| 231 |
|
| 232 |
Note: in this test, we are consuming messages with the same schema, |
| 233 |
a realistic high-throughput scenario. |
| 234 |
We cache the schema in the Schema Registry client, so only the first message |
| 235 |
makes HTTP calls to the Schema Registry server. |
| 236 |
Performance impact compared to test_basic_consume should come from per-message |
| 237 |
deserialization overhead. |
| 238 |
""" |
| 239 |
|
| 240 |
self._run_consumer_performance_benchmark( |
| 241 |
consumer_type=consumer_type, |
| 242 |
operation_type="poll", |
| 243 |
serialization_type=serialization_type, |
| 244 |
num_messages_to_produce=500000, |
| 245 |
) |
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
def test_async_consumer_joins_and_leaves_rebalance(self): |
| 250 |
"""Test rebalancing when consumer joins and then leaves the group""" |
| 251 |
|
| 252 |
async def async_rebalance_test(): |
| 253 |
topic_name = f"test-rebalance-{uuid.uuid4()}" |
| 254 |
group_id = f"rebalance-group-{uuid.uuid4()}" |
| 255 |
|
| 256 |
|
| 257 |
self._setup_topic_with_messages(topic_name, partitions=2, messages=10) |
| 258 |
|
| 259 |
|
| 260 |
consumer1 = self.create_consumer("async", group_id) |
| 261 |
consumer2 = self.create_consumer("async", group_id) |
| 262 |
|
| 263 |
|
| 264 |
rebalance_events = [] |
| 265 |
|
| 266 |
async def track_rebalance(consumer, partitions): |
| 267 |
rebalance_events.append(len(partitions)) |
| 268 |
await consumer.assign(partitions) |
| 269 |
|
| 270 |
try: |
| 271 |
|
| 272 |
await consumer1.subscribe([topic_name], on_assign=track_rebalance) |
| 273 |
await self._wait_for_assignment(consumer1, expected_partitions=2) |
| 274 |
assert len(rebalance_events) == 1 |
| 275 |
|
| 276 |
|
| 277 |
await consumer2.subscribe([topic_name], on_assign=track_rebalance) |
| 278 |
await self._wait_for_balanced_assignment( |
| 279 |
[consumer1, consumer2], total_partitions=2 |
| 280 |
) |
| 281 |
assert len(rebalance_events) >= 2 |
| 282 |
|
| 283 |
|
| 284 |
await consumer2.close() |
| 285 |
await self._wait_for_assignment(consumer1, expected_partitions=2) |
| 286 |
assert len(rebalance_events) >= 3 |
| 287 |
|
| 288 |
|
| 289 |
self.produce_test_messages(topic_name, num_messages=1) |
| 290 |
msg = await consumer1.poll(timeout=5.0) |
| 291 |
assert msg is not None, "Consumer should receive fresh message" |
| 292 |
|
| 293 |
finally: |
| 294 |
await consumer1.close() |
| 295 |
|
| 296 |
asyncio.run(async_rebalance_test()) |
| 297 |
|
| 298 |
def test_async_topic_partition_changes_rebalance(self): |
| 299 |
"""Test rebalancing when partitions are added to existing topic""" |
| 300 |
|
| 301 |
async def async_topic_change_test(): |
| 302 |
topic_name = f"test-topic-changes-{uuid.uuid4()}" |
| 303 |
group_id = f"topic-changes-group-{uuid.uuid4()}" |
| 304 |
|
| 305 |
|
| 306 |
self.kafka.create_topic(topic_name, partitions=2, replication_factor=1) |
| 307 |
topic_ready = self.kafka.wait_for_topic(topic_name, max_wait_time=30) |
| 308 |
assert topic_ready, f"Topic {topic_name} was not created" |
| 309 |
self.produce_test_messages(topic_name, num_messages=10) |
| 310 |
|
| 311 |
|
| 312 |
consumer1 = self.create_consumer("async", group_id) |
| 313 |
consumer2 = self.create_consumer("async", group_id) |
| 314 |
|
| 315 |
|
| 316 |
rebalance_events = [] |
| 317 |
|
| 318 |
async def track_rebalance(consumer, partitions): |
| 319 |
rebalance_events.append(len(partitions)) |
| 320 |
await consumer.assign(partitions) |
| 321 |
|
| 322 |
|
| 323 |
await consumer1.subscribe([topic_name], on_assign=track_rebalance) |
| 324 |
await consumer2.subscribe([topic_name], on_assign=track_rebalance) |
| 325 |
|
| 326 |
|
| 327 |
for attempt in range(10): |
| 328 |
await consumer1.poll(timeout=1.0) |
| 329 |
await consumer2.poll(timeout=1.0) |
| 330 |
|
| 331 |
assignment1 = await consumer1.assignment() |
| 332 |
assignment2 = await consumer2.assignment() |
| 333 |
|
| 334 |
if len(assignment1) > 0 and len(assignment2) > 0: |
| 335 |
break |
| 336 |
await asyncio.sleep(1.0) |
| 337 |
|
| 338 |
|
| 339 |
assignment1_initial = await consumer1.assignment() |
| 340 |
assignment2_initial = await consumer2.assignment() |
| 341 |
total_partitions_initial = len(assignment1_initial) + len( |
| 342 |
assignment2_initial |
| 343 |
) |
| 344 |
|
| 345 |
assert ( |
| 346 |
total_partitions_initial == 2 |
| 347 |
), f"Should have 2 total partitions initially, got {total_partitions_initial}" |
| 348 |
assert ( |
| 349 |
len(rebalance_events) >= 2 |
| 350 |
), f"Should have at least 2 rebalance events, got {len(rebalance_events)}" |
| 351 |
|
| 352 |
|
| 353 |
self.kafka.add_partitions(topic_name, new_partition_count=4) |
| 354 |
|
| 355 |
|
| 356 |
self.produce_test_messages(topic_name, num_messages=5) |
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
consumer3 = self.create_consumer("async", group_id) |
| 361 |
await consumer3.subscribe([topic_name], on_assign=track_rebalance) |
| 362 |
|
| 363 |
|
| 364 |
consumers = [consumer1, consumer2, consumer3] |
| 365 |
for _ in range(30): |
| 366 |
|
| 367 |
await asyncio.gather(*[c.poll(timeout=1.0) for c in consumers]) |
| 368 |
|
| 369 |
|
| 370 |
assignments = await asyncio.gather(*[c.assignment() for c in consumers]) |
| 371 |
total_partitions_current = sum( |
| 372 |
len(assignment) for assignment in assignments |
| 373 |
) |
| 374 |
|
| 375 |
|
| 376 |
if total_partitions_current == 4: |
| 377 |
break |
| 378 |
await asyncio.sleep(0.5) |
| 379 |
|
| 380 |
|
| 381 |
assignment1_final = await consumer1.assignment() |
| 382 |
assignment2_final = await consumer2.assignment() |
| 383 |
assignment3_final = await consumer3.assignment() |
| 384 |
total_partitions_final = ( |
| 385 |
len(assignment1_final) + len(assignment2_final) + len(assignment3_final) |
| 386 |
) |
| 387 |
|
| 388 |
assert ( |
| 389 |
total_partitions_final == 4 |
| 390 |
), f"Should have 4 total partitions after adding, got {total_partitions_final}" |
| 391 |
|
| 392 |
assert ( |
| 393 |
len(assignment1_final) >= 1 |
| 394 |
), f"Consumer 1 should have at least 1 partition, got {len(assignment1_final)}" |
| 395 |
assert ( |
| 396 |
len(assignment2_final) >= 1 |
| 397 |
), f"Consumer 2 should have at least 1 partition, got {len(assignment2_final)}" |
| 398 |
assert ( |
| 399 |
len(assignment3_final) >= 1 |
| 400 |
), f"Consumer 3 should have at least 1 partition, got {len(assignment3_final)}" |
| 401 |
assert len(rebalance_events) >= 5, ( |
| 402 |
"Should have at least 5 rebalance events after partition addition and consumer3 join, " |
| 403 |
f"got {len(rebalance_events)}" |
| 404 |
) |
| 405 |
|
| 406 |
|
| 407 |
msg1 = await consumer1.poll(timeout=5.0) |
| 408 |
msg2 = await consumer2.poll(timeout=5.0) |
| 409 |
msg3 = await consumer3.poll(timeout=5.0) |
| 410 |
messages_received = sum( |
| 411 |
[1 for msg in [msg1, msg2, msg3] if msg is not None] |
| 412 |
) |
| 413 |
assert ( |
| 414 |
messages_received > 0 |
| 415 |
), "Consumers should receive messages from new partitions" |
| 416 |
|
| 417 |
|
| 418 |
await consumer1.close() |
| 419 |
await consumer2.close() |
| 420 |
await consumer3.close() |
| 421 |
|
| 422 |
asyncio.run(async_topic_change_test()) |
| 423 |
|
| 424 |
def test_async_callback_exception_behavior(self): |
| 425 |
"""Test current behavior: callback exceptions propagate and fail the consumer""" |
| 426 |
|
| 427 |
async def async_callback_test(): |
| 428 |
topic_name = f"test-callback-exception-{uuid.uuid4()}" |
| 429 |
group_id = f"callback-exception-group-{uuid.uuid4()}" |
| 430 |
|
| 431 |
self._setup_topic_with_messages(topic_name, partitions=2, messages=10) |
| 432 |
consumer = self.create_consumer("async", group_id) |
| 433 |
|
| 434 |
|
| 435 |
callback_calls = [] |
| 436 |
|
| 437 |
async def failing_callback(consumer_obj, partitions): |
| 438 |
callback_calls.append("called") |
| 439 |
raise ValueError("Simulated callback failure") |
| 440 |
|
| 441 |
try: |
| 442 |
|
| 443 |
await consumer.subscribe([topic_name], on_assign=failing_callback) |
| 444 |
|
| 445 |
|
| 446 |
with pytest.raises(ValueError, match="Simulated callback failure"): |
| 447 |
await consumer.poll(timeout=10.0) |
| 448 |
|
| 449 |
|
| 450 |
assert ( |
| 451 |
len(callback_calls) == 1 |
| 452 |
), "Callback should have been called before crash" |
| 453 |
|
| 454 |
finally: |
| 455 |
|
| 456 |
try: |
| 457 |
await consumer.close() |
| 458 |
except Exception: |
| 459 |
pass |
| 460 |
|
| 461 |
asyncio.run(async_callback_test()) |
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
def _run_consumer_performance_benchmark( |
| 466 |
self, |
| 467 |
consumer_type, |
| 468 |
operation_type, |
| 469 |
batch_size=None, |
| 470 |
serialization_type=None, |
| 471 |
num_messages_to_produce=1500000, |
| 472 |
): |
| 473 |
""" |
| 474 |
Shared helper for consumer performance tests |
| 475 |
|
| 476 |
Args: |
| 477 |
consumer_type: "sync" or "async" |
| 478 |
operation_type: "consume" or "poll" |
| 479 |
batch_size: Number of messages per batch (default None). Only required for consume operation |
| 480 |
serialization_type: Schema Registry serialization type ("avro", "json", "protobuf") or None for plain text |
| 481 |
""" |
| 482 |
topic_name = f"performance-test-{consumer_type}-{operation_type}-{serialization_type or 'plain'}-topic" |
| 483 |
test_duration = 5.0 |
| 484 |
|
| 485 |
|
| 486 |
self.kafka.create_topic(topic_name, partitions=1, replication_factor=1) |
| 487 |
|
| 488 |
|
| 489 |
topic_ready = self.kafka.wait_for_topic(topic_name, max_wait_time=30) |
| 490 |
assert topic_ready, ( |
| 491 |
f"Topic {topic_name} was not created within timeout. " |
| 492 |
f"Available topics: {self.kafka.list_topics()}" |
| 493 |
) |
| 494 |
|
| 495 |
|
| 496 |
self.produce_test_messages( |
| 497 |
topic_name, num_messages_to_produce, serialization_type |
| 498 |
) |
| 499 |
|
| 500 |
|
| 501 |
metrics = ConsumerMetricsCollector( |
| 502 |
operation_type=operation_type, serialization_type=serialization_type |
| 503 |
) |
| 504 |
bounds = ConsumerMetricsBounds() |
| 505 |
|
| 506 |
|
| 507 |
strategy = self.create_consumer_strategy(consumer_type, batch_size=batch_size) |
| 508 |
|
| 509 |
|
| 510 |
strategy.metrics = metrics |
| 511 |
|
| 512 |
self.logger.info( |
| 513 |
f"Testing {consumer_type} consumer {operation_type}, with serialization type {serialization_type}, " |
| 514 |
f"for {test_duration} seconds" |
| 515 |
) |
| 516 |
|
| 517 |
|
| 518 |
metrics.start() |
| 519 |
|
| 520 |
|
| 521 |
consumed_messages = [] |
| 522 |
|
| 523 |
|
| 524 |
start_time = time.time() |
| 525 |
if operation_type == "consume": |
| 526 |
messages_consumed = strategy.consume_messages( |
| 527 |
topic_name, |
| 528 |
test_duration, |
| 529 |
start_time, |
| 530 |
consumed_messages, |
| 531 |
timeout=0.1, |
| 532 |
serialization_type=serialization_type, |
| 533 |
) |
| 534 |
else: |
| 535 |
messages_consumed = strategy.poll_messages( |
| 536 |
topic_name, |
| 537 |
test_duration, |
| 538 |
start_time, |
| 539 |
consumed_messages, |
| 540 |
timeout=0.1, |
| 541 |
serialization_type=serialization_type, |
| 542 |
) |
| 543 |
|
| 544 |
|
| 545 |
metrics.finalize() |
| 546 |
|
| 547 |
|
| 548 |
metrics_summary = metrics.get_summary() |
| 549 |
is_valid, violations = validate_consumer_metrics(metrics_summary, bounds) |
| 550 |
|
| 551 |
|
| 552 |
print_consumer_metrics_report( |
| 553 |
metrics_summary, |
| 554 |
is_valid, |
| 555 |
violations, |
| 556 |
consumer_type, |
| 557 |
batch_size, |
| 558 |
serialization_type, |
| 559 |
) |
| 560 |
|
| 561 |
|
| 562 |
assert messages_consumed > 0, "No messages were consumed" |
| 563 |
assert len(consumed_messages) > 0, "No messages were collected" |
| 564 |
assert ( |
| 565 |
metrics_summary["messages_consumed"] > 0 |
| 566 |
), "No messages were consumed (metrics)" |
| 567 |
assert ( |
| 568 |
metrics_summary["consumption_rate_msg_per_sec"] > 0 |
| 569 |
), f"Consumption rate too low: {metrics_summary['consumption_rate_msg_per_sec']:.2f} msg/s" |
| 570 |
|
| 571 |
|
| 572 |
if not is_valid: |
| 573 |
self.logger.error( |
| 574 |
"Performance bounds validation failed: %s", "; ".join(violations) |
| 575 |
) |
| 576 |
assert False, f"Performance bounds validation failed: {'; '.join(violations)}" |
| 577 |
|
| 578 |
self.logger.info( |
| 579 |
f"Successfully completed basic {operation_type} test with comprehensive metrics" |
| 580 |
) |
| 581 |
|
| 582 |
|
| 583 |
return consumed_messages |
| 584 |
|
| 585 |
def _setup_topic_with_messages(self, topic_name, partitions=2, messages=10): |
| 586 |
"""Helper: Create topic and produce test messages""" |
| 587 |
self.kafka.create_topic(topic_name, partitions=partitions, replication_factor=1) |
| 588 |
assert self.kafka.wait_for_topic(topic_name, max_wait_time=30) |
| 589 |
self.produce_test_messages(topic_name, num_messages=messages) |
| 590 |
|
| 591 |
async def _wait_for_assignment(self, consumer, expected_partitions, max_wait=15): |
| 592 |
"""Helper: Wait for consumer to get expected partition count""" |
| 593 |
for _ in range(max_wait): |
| 594 |
await consumer.poll(timeout=1.0) |
| 595 |
assignment = await consumer.assignment() |
| 596 |
if len(assignment) == expected_partitions: |
| 597 |
return |
| 598 |
await asyncio.sleep(1.0) |
| 599 |
|
| 600 |
assignment = await consumer.assignment() |
| 601 |
assert ( |
| 602 |
len(assignment) == expected_partitions |
| 603 |
), f"Expected {expected_partitions} partitions, got {len(assignment)}" |
| 604 |
|
| 605 |
async def _wait_for_balanced_assignment( |
| 606 |
self, consumers, total_partitions, max_wait=15 |
| 607 |
): |
| 608 |
"""Helper: Wait for consumers to split partitions evenly""" |
| 609 |
for _ in range(max_wait): |
| 610 |
for consumer in consumers: |
| 611 |
await consumer.poll(timeout=1.0) |
| 612 |
|
| 613 |
assignments = [await c.assignment() for c in consumers] |
| 614 |
assigned_count = sum(len(a) for a in assignments) |
| 615 |
|
| 616 |
if assigned_count == total_partitions and all( |
| 617 |
len(a) > 0 for a in assignments |
| 618 |
): |
| 619 |
return |
| 620 |
await asyncio.sleep(1.0) |
| 621 |
|
| 622 |
assignments = [await c.assignment() for c in consumers] |
| 623 |
assigned_count = sum(len(a) for a in assignments) |
| 624 |
assert ( |
| 625 |
assigned_count == total_partitions |
| 626 |
), f"Expected {total_partitions} total partitions, got {assigned_count}" |
| 627 |
|
| 628 |
def create_serializers(self, serialization_type): |
| 629 |
"""Create Schema Registry serializers for message production""" |
| 630 |
sr_client = SchemaRegistryClient( |
| 631 |
{ |
| 632 |
"url": "http://localhost:8081", |
| 633 |
} |
| 634 |
) |
| 635 |
|
| 636 |
key_serializer = StringSerializer("utf8") |
| 637 |
|
| 638 |
if serialization_type == "avro": |
| 639 |
|
| 640 |
avro_schema = { |
| 641 |
"type": "record", |
| 642 |
"name": "TestMessage", |
| 643 |
"fields": [ |
| 644 |
{"name": "test_string", "type": "string"}, |
| 645 |
{"name": "test_bool", "type": "boolean"}, |
| 646 |
{"name": "test_bytes", "type": "bytes"}, |
| 647 |
{"name": "test_double", "type": "double"}, |
| 648 |
{"name": "test_float", "type": "float"}, |
| 649 |
{"name": "test_fixed32", "type": "int"}, |
| 650 |
{"name": "test_fixed64", "type": "long"}, |
| 651 |
{"name": "test_int32", "type": "int"}, |
| 652 |
{"name": "test_int64", "type": "long"}, |
| 653 |
{"name": "test_sfixed32", "type": "int"}, |
| 654 |
{"name": "test_sfixed64", "type": "long"}, |
| 655 |
{"name": "test_sint32", "type": "int"}, |
| 656 |
{"name": "test_sint64", "type": "long"}, |
| 657 |
{"name": "test_uint32", "type": "int"}, |
| 658 |
{"name": "test_uint64", "type": "long"}, |
| 659 |
], |
| 660 |
} |
| 661 |
value_serializer = AvroSerializer( |
| 662 |
schema_registry_client=sr_client, schema_str=json.dumps(avro_schema) |
| 663 |
) |
| 664 |
elif serialization_type == "json": |
| 665 |
|
| 666 |
json_schema = { |
| 667 |
"type": "object", |
| 668 |
"properties": { |
| 669 |
"test_string": {"type": "string"}, |
| 670 |
"test_bool": {"type": "boolean"}, |
| 671 |
"test_bytes": {"type": "string"}, |
| 672 |
"test_double": {"type": "number"}, |
| 673 |
"test_float": {"type": "number"}, |
| 674 |
"test_fixed32": {"type": "integer"}, |
| 675 |
"test_fixed64": {"type": "integer"}, |
| 676 |
"test_int32": {"type": "integer"}, |
| 677 |
"test_int64": {"type": "integer"}, |
| 678 |
"test_sfixed32": {"type": "integer"}, |
| 679 |
"test_sfixed64": {"type": "integer"}, |
| 680 |
"test_sint32": {"type": "integer"}, |
| 681 |
"test_sint64": {"type": "integer"}, |
| 682 |
"test_uint32": {"type": "integer"}, |
| 683 |
"test_uint64": {"type": "integer"}, |
| 684 |
}, |
| 685 |
"required": [ |
| 686 |
"test_string", |
| 687 |
"test_bool", |
| 688 |
"test_bytes", |
| 689 |
"test_double", |
| 690 |
"test_float", |
| 691 |
"test_fixed32", |
| 692 |
"test_fixed64", |
| 693 |
"test_int32", |
| 694 |
"test_int64", |
| 695 |
"test_sfixed32", |
| 696 |
"test_sfixed64", |
| 697 |
"test_sint32", |
| 698 |
"test_sint64", |
| 699 |
"test_uint32", |
| 700 |
"test_uint64", |
| 701 |
], |
| 702 |
} |
| 703 |
value_serializer = JSONSerializer(json.dumps(json_schema), sr_client) |
| 704 |
elif serialization_type == "protobuf": |
| 705 |
value_serializer = ProtobufSerializer( |
| 706 |
PublicTestProto_pb2.TestMessage, sr_client |
| 707 |
) |
| 708 |
|
| 709 |
return key_serializer, value_serializer |
| 710 |
|
| 711 |
def teardown(self): |
| 712 |
"""Clean up test environment""" |
| 713 |
self.logger.info("Test completed - external Kafka service remains running") |