forked from confluentinc/confluent-kafka-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_Wakeable.py
More file actions
1440 lines (1192 loc) · 49.8 KB
/
test_Wakeable.py
File metadata and controls
1440 lines (1192 loc) · 49.8 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 python
# -*- coding: utf-8 -*-
"""
Tests for wakeable poll/flush/consume functionality.
These tests verify the interruptibility of blocking operations (poll, flush, consume)
using the wakeable pattern with signal checking between chunks.
Includes:
- Utility function tests (calculate_chunk_timeout, check_signals_between_chunks)
- Producer wakeable tests (poll, flush)
- Consumer wakeable tests (poll, consume)
"""
import threading
import time
import pytest
from confluent_kafka import Producer
from tests.common import TestConsumer, TestUtils
# Timing constants for wakeable poll/flush/consume pattern tests
# For timeouts < 200ms, the wakeable pattern is NOT used (see Producer.c/Consumer.c),
# so those timeouts can complete faster. For timeouts >= 200ms, chunking is used.
CHUNK_TIMEOUT_MS = 200 # Chunk size in milliseconds
WAKEABLE_POLL_TIMEOUT_MIN = 0.2 # Minimum timeout for chunked operations (seconds)
WAKEABLE_POLL_TIMEOUT_MAX = 2.0 # Maximum timeout (seconds)
# ============================================================================
# Approach to Wakeability Testing
# ============================================================================
#
# The wakeable pattern is implemented using shared C utility functions that are
# used by both Producer and Consumer. Our testing strategy mirrors this architecture:
#
# High level Wakeability Implementation:
# ------------
# Shared Utilities (confluent_kafka.h):
# - calculate_chunk_timeout(): Splits long timeouts into 200ms chunks
# - check_signals_between_chunks(): Re-acquires GIL, checks signals, handles cleanup
#
# Producer Implementation (Producer.c):
# - Producer.poll() uses wakeable pattern for timeouts >= 200ms
# - Producer.flush() uses wakeable pattern for timeouts >= 200ms
#
# Consumer Implementation (Consumer.c):
# - Consumer.poll() uses wakeable pattern for timeouts >= 200ms
# - Consumer.consume() uses wakeable pattern for timeouts >= 200ms
#
# How We Test Wakeability:
# ------------------------
# Since Producer and Consumer share the same C utility functions but have different
# Python APIs, we test them using a layered approach:
#
# 1. Testing Producer Wakeability:
# - Create Producer instances and call poll()/flush() with various timeouts
# - Inject signals at different times (immediate, after chunks, during finite timeout)
# - Verify KeyboardInterrupt is raised and Producer-specific behavior (return types, cleanup)
# - Test both infinite and finite timeouts to cover all code paths
#
# 2. Testing Consumer Wakeability:
# - Create Consumer instances and call poll()/consume() with various timeouts
# - Inject signals at different times using the same pattern as Producer tests
# - Verify KeyboardInterrupt is raised and Consumer-specific behavior (return types, message handling)
# - Test both infinite and finite timeouts, including edge cases like num_messages=0
#
# 3. Testing Methodology:
# - Signal Injection: Use TestUtils.send_sigint_after_delay() in a background thread
# to simulate KeyboardInterrupt at specific times during blocking operations
# - Chunking Verification: Measure elapsed time to verify >= 200ms timeouts use chunking
# (multiple 200ms intervals) while < 200ms timeouts bypass chunking entirely
# - Interruptibility Verification: Wrap blocking calls in try/except to catch
# KeyboardInterrupt and verify operations abort cleanly
# - State Verification: Check that objects are properly cleaned up (closed state,
# no resource leaks) after interrupted operations
# ============================================================================
# Producer wakeable tests
# ============================================================================
def test_producer_wakeable_poll_utility_functions_interaction():
"""Test interaction between calculate_chunk_timeout() and check_signals_between_chunks()."""
# Assert: Chunk calculation and signal check work together
producer1 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.4))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
producer1.poll(timeout=1.0)
except KeyboardInterrupt:
interrupted = True
finally:
producer1.close()
assert interrupted, "Should have raised KeyboardInterrupt"
# Assert: Multiple chunks before signal detection
producer2 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.6))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
producer2.poll(timeout=WAKEABLE_POLL_TIMEOUT_MAX)
except KeyboardInterrupt:
interrupted = True
finally:
producer2.close()
assert interrupted, "Should have raised KeyboardInterrupt"
def test_producer_wakeable_poll_interruptibility_and_messages():
"""Test poll() interruptibility and message handling."""
# Assert: Infinite timeout can be interrupted
producer1 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.1))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
producer1.poll(timeout=WAKEABLE_POLL_TIMEOUT_MAX)
except KeyboardInterrupt:
interrupted = True
finally:
producer1.close()
assert interrupted, "Should have raised KeyboardInterrupt"
# Assert: Finite timeout can be interrupted before timeout expires
producer2 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.3))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
producer2.poll(timeout=WAKEABLE_POLL_TIMEOUT_MAX)
except KeyboardInterrupt:
interrupted = True
finally:
producer2.close()
assert interrupted, "Should have raised KeyboardInterrupt"
# Assert: Signal sent after multiple chunks still interrupts
producer3 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.6))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
producer3.poll(timeout=WAKEABLE_POLL_TIMEOUT_MAX)
except KeyboardInterrupt:
interrupted = True
finally:
producer3.close()
assert interrupted, "Should have raised KeyboardInterrupt"
# Assert: No signal - timeout works normally
producer4 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
start = time.time()
result = producer4.poll(timeout=0.5)
elapsed = time.time() - start
assert isinstance(result, int), "poll() should return int"
assert (
WAKEABLE_POLL_TIMEOUT_MIN <= elapsed <= WAKEABLE_POLL_TIMEOUT_MAX
), f"Timeout took {elapsed:.2f}s, expected ~0.5s"
producer4.close()
def test_producer_wakeable_poll_edge_cases():
"""Test poll() edge cases."""
# Assert: Zero timeout returns immediately
producer1 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
start = time.time()
result = producer1.poll(timeout=0.0)
elapsed = time.time() - start
assert elapsed < WAKEABLE_POLL_TIMEOUT_MAX, f"Zero timeout took {elapsed:.2f}s"
assert isinstance(result, int)
producer1.close()
# Assert: Closed producer raises RuntimeError
producer2 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
producer2.close()
with pytest.raises(RuntimeError) as exc_info:
producer2.poll(timeout=0.1)
assert 'Producer has been closed' in str(exc_info.value)
# Assert: Short timeout works correctly
producer3 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
start = time.time()
result = producer3.poll(timeout=0.1)
elapsed = time.time() - start
assert isinstance(result, int)
# Short timeouts don't use chunking
assert elapsed <= WAKEABLE_POLL_TIMEOUT_MAX, f"Short timeout took {elapsed:.2f}s"
producer3.close()
# Assert: Very short timeout works
producer4 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
start = time.time()
result = producer4.poll(timeout=0.05)
elapsed = time.time() - start
assert isinstance(result, int)
assert elapsed < WAKEABLE_POLL_TIMEOUT_MAX, f"Very short timeout took {elapsed:.2f}s"
producer4.close()
def test_producer_wakeable_flush_interruptibility_and_messages():
"""Test flush() interruptibility and message handling."""
# Assert: Infinite timeout can be interrupted
producer1 = Producer(
{
'bootstrap.servers': 'localhost:9092',
'socket.timeout.ms': 60000,
'message.timeout.ms': 30000,
'acks': 'all',
'batch.num.messages': 100,
'linger.ms': 100,
'queue.buffering.max.messages': 100000,
'queue.buffering.max.kbytes': 104857600,
'max.in.flight.requests.per.connection': 1,
'request.timeout.ms': 30000,
'delivery.timeout.ms': 30000,
}
)
messages_produced = False
stop_producing = threading.Event()
production_stats = {'count': 0, 'errors': 0}
def continuous_producer():
message_num = 0
while not stop_producing.is_set():
try:
producer1.produce(
'test-topic', value=f'continuous-{message_num}'.encode(), key=f'key-{message_num}'.encode()
)
production_stats['count'] += 1
message_num += 1
except Exception as e:
production_stats['errors'] += 1
if "QUEUE_FULL" in str(e):
time.sleep(0.001)
else:
time.sleep(0.01)
try:
for i in range(1000):
try:
producer1.produce('test-topic', value=f'initial-{i}'.encode())
messages_produced = True
except Exception as e:
if "QUEUE_FULL" in str(e):
time.sleep(0.01)
continue
break
if not messages_produced:
producer1.close()
pytest.skip("Broker not available, cannot test flush() interruptibility")
poll_start = time.time()
while time.time() - poll_start < 0.5:
producer1.poll(timeout=0.1)
producer_thread = threading.Thread(target=continuous_producer, daemon=True)
producer_thread.start()
time.sleep(0.1)
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.1))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
producer1.flush()
except KeyboardInterrupt:
interrupted = True
finally:
stop_producing.set()
time.sleep(0.1)
producer1.close()
assert interrupted, "Should have raised KeyboardInterrupt"
except Exception:
stop_producing.set()
producer1.close()
raise
# Assert: Finite timeout can be interrupted before timeout expires
producer2 = Producer(
{
'bootstrap.servers': 'localhost:9092',
'socket.timeout.ms': 60000,
'message.timeout.ms': 30000,
'acks': 'all',
'batch.num.messages': 100,
'linger.ms': 100,
'queue.buffering.max.messages': 100000,
'queue.buffering.max.kbytes': 104857600,
'max.in.flight.requests.per.connection': 1,
'request.timeout.ms': 30000,
'delivery.timeout.ms': 30000,
}
)
stop_producing2 = threading.Event()
production_stats2 = {'count': 0, 'errors': 0}
def continuous_producer2():
message_num = 0
while not stop_producing2.is_set():
try:
producer2.produce(
'test-topic', value=f'continuous2-{message_num}'.encode(), key=f'key2-{message_num}'.encode()
)
production_stats2['count'] += 1
message_num += 1
except Exception as e:
production_stats2['errors'] += 1
if "QUEUE_FULL" in str(e):
time.sleep(0.001)
else:
time.sleep(0.01)
try:
for i in range(1000):
try:
producer2.produce('test-topic', value=f'initial2-{i}'.encode())
except Exception as e:
if "QUEUE_FULL" in str(e):
time.sleep(0.01)
continue
break
poll_start = time.time()
while time.time() - poll_start < 0.5:
producer2.poll(timeout=0.1)
producer_thread2 = threading.Thread(target=continuous_producer2, daemon=True)
producer_thread2.start()
time.sleep(0.1)
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.3))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
producer2.flush(timeout=WAKEABLE_POLL_TIMEOUT_MAX)
except KeyboardInterrupt:
interrupted = True
finally:
stop_producing2.set()
time.sleep(0.1)
producer2.close()
assert interrupted, "Should have raised KeyboardInterrupt"
except Exception:
stop_producing2.set()
producer2.close()
raise
# Assert: Signal sent after multiple chunks still interrupts
producer3 = Producer(
{
'bootstrap.servers': 'localhost:9092',
'socket.timeout.ms': 60000,
'message.timeout.ms': 30000,
'acks': 'all',
'batch.num.messages': 100,
'linger.ms': 100,
'queue.buffering.max.messages': 100000,
'queue.buffering.max.kbytes': 104857600,
'max.in.flight.requests.per.connection': 1,
'request.timeout.ms': 30000,
'delivery.timeout.ms': 30000,
}
)
stop_producing3 = threading.Event()
production_stats3 = {'count': 0, 'errors': 0}
def continuous_producer3():
message_num = 0
while not stop_producing3.is_set():
try:
producer3.produce(
'test-topic', value=f'continuous3-{message_num}'.encode(), key=f'key3-{message_num}'.encode()
)
production_stats3['count'] += 1
message_num += 1
except Exception as e:
production_stats3['errors'] += 1
if "QUEUE_FULL" in str(e):
time.sleep(0.001)
else:
time.sleep(0.01)
try:
for i in range(1000):
try:
producer3.produce('test-topic', value=f'initial3-{i}'.encode())
except Exception as e:
if "QUEUE_FULL" in str(e):
time.sleep(0.01)
continue
break
poll_start = time.time()
while time.time() - poll_start < 0.5:
producer3.poll(timeout=0.1)
producer_thread3 = threading.Thread(target=continuous_producer3, daemon=True)
producer_thread3.start()
time.sleep(0.1)
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.6))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
producer3.flush()
except KeyboardInterrupt:
interrupted = True
finally:
stop_producing3.set()
time.sleep(0.1)
producer3.close()
assert interrupted, "Should have raised KeyboardInterrupt"
except Exception:
stop_producing3.set()
producer3.close()
raise
# Assert: No signal - timeout works normally
producer4 = Producer(
{
'bootstrap.servers': 'localhost:9092',
'socket.timeout.ms': 100,
'message.timeout.ms': 10,
'acks': 'all',
'max.in.flight.requests.per.connection': 1,
}
)
try:
for i in range(100):
producer4.produce('test-topic', value=f'timeout-test-{i}'.encode())
except Exception:
pass
start = time.time()
qlen = producer4.flush(timeout=0.5)
elapsed = time.time() - start
assert isinstance(qlen, int), "flush() should return int"
assert elapsed <= WAKEABLE_POLL_TIMEOUT_MAX, f"Timeout took {elapsed:.2f}s"
producer4.close()
def test_producer_wakeable_flush_edge_cases():
"""Test flush() edge cases."""
# Assert: Zero timeout returns immediately
producer1 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
start = time.time()
qlen = producer1.flush(timeout=0.0)
elapsed = time.time() - start
assert elapsed < WAKEABLE_POLL_TIMEOUT_MAX, f"Zero timeout took {elapsed:.2f}s"
assert isinstance(qlen, int)
producer1.close()
# Assert: Closed producer raises RuntimeError
producer2 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
producer2.close()
with pytest.raises(RuntimeError) as exc_info:
producer2.flush(timeout=0.1)
assert 'Producer has been closed' in str(exc_info.value)
# Assert: Short timeout works correctly
producer3 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
start = time.time()
qlen = producer3.flush(timeout=0.1)
elapsed = time.time() - start
assert isinstance(qlen, int)
# Short timeouts don't use chunking
assert elapsed <= WAKEABLE_POLL_TIMEOUT_MAX, f"Short timeout took {elapsed:.2f}s"
producer3.close()
# Assert: Very short timeout works
producer4 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
start = time.time()
qlen = producer4.flush(timeout=0.05)
elapsed = time.time() - start
assert isinstance(qlen, int)
assert elapsed < WAKEABLE_POLL_TIMEOUT_MAX, f"Very short timeout took {elapsed:.2f}s"
producer4.close()
# Assert: Empty queue flush returns immediately
producer5 = Producer({'socket.timeout.ms': 100, 'message.timeout.ms': 10})
start = time.time()
qlen = producer5.flush(timeout=1.0)
elapsed = time.time() - start
assert qlen == 0
assert elapsed < WAKEABLE_POLL_TIMEOUT_MAX, f"Empty flush took {elapsed:.2f}s"
producer5.close()
# ============================================================================
# Consumer wakeable tests
# ============================================================================
def test_consumer_wakeable_poll_utility_functions_interaction():
"""Test interaction between calculate_chunk_timeout() and check_signals_between_chunks()."""
# Assertion 1: Both functions work together - chunk calculation + signal check
consumer1 = TestConsumer(
{
'group.id': 'test-interaction-chunk-signal',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer1.subscribe(['test-topic'])
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.4))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
consumer1.poll(timeout=1.0) # 1 second timeout, interrupt after 0.4s
except KeyboardInterrupt:
interrupted = True
finally:
consumer1.close()
assert interrupted, "Assertion 1 failed: Should have raised KeyboardInterrupt"
# Assertion 2: Multiple chunks before signal - both functions work over multiple iterations
consumer2 = TestConsumer(
{
'group.id': 'test-interaction-multiple-chunks',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer2.subscribe(['test-topic'])
# Send signal after 0.6 seconds (3 chunks should have passed: 0.2s, 0.4s, 0.6s)
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.6))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
consumer2.poll() # Infinite timeout
except KeyboardInterrupt:
interrupted = True
finally:
consumer2.close()
assert interrupted, "Assertion 2 failed: Should have raised KeyboardInterrupt"
def test_consumer_wakeable_poll_interruptibility_and_messages():
"""Test poll() interruptibility (main fix) and message handling."""
topic = 'test-poll-interrupt-topic'
# Assertion 1: Infinite timeout can be interrupted immediately
consumer1 = TestConsumer(
{
'group.id': 'test-poll-infinite-immediate',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer1.subscribe([topic])
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.1))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
consumer1.poll() # Infinite timeout
except KeyboardInterrupt:
interrupted = True
finally:
consumer1.close()
assert interrupted, "Assertion 1 failed: Should have raised KeyboardInterrupt"
# Assertion 2: Finite timeout can be interrupted before timeout expires
consumer2 = TestConsumer(
{
'group.id': 'test-poll-finite-interrupt',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer2.subscribe([topic])
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.3))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
timeout_value = WAKEABLE_POLL_TIMEOUT_MAX # Use constant instead of hardcoded 2.0
try:
consumer2.poll(timeout=timeout_value) # Use constant for timeout
except KeyboardInterrupt:
interrupted = True
finally:
consumer2.close()
assert interrupted, "Assertion 2 failed: Should have raised KeyboardInterrupt"
# Assertion 3: Signal sent after multiple chunks still interrupts quickly
consumer3 = TestConsumer(
{
'group.id': 'test-poll-multiple-chunks',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer3.subscribe([topic])
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.6))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
consumer3.poll() # Infinite timeout
except KeyboardInterrupt:
interrupted = True
finally:
consumer3.close()
assert interrupted, "Assertion 3 failed: Should have raised KeyboardInterrupt"
# Assertion 4: No signal - timeout works normally
consumer4 = TestConsumer(
{
'group.id': 'test-poll-timeout-normal',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer4.subscribe([topic])
start = time.time()
msg = consumer4.poll(timeout=0.5) # 500ms, no signal
elapsed = time.time() - start
assert msg is None, "Assertion 4 failed: Expected None (timeout), no signal should not interrupt"
assert (
WAKEABLE_POLL_TIMEOUT_MIN <= elapsed <= WAKEABLE_POLL_TIMEOUT_MAX
), f"Assertion 4 failed: Normal timeout took {elapsed:.2f}s, expected ~0.5s"
consumer4.close()
def test_consumer_wakeable_poll_edge_cases():
"""Test poll() edge cases."""
topic = 'test-poll-edge-topic'
# Assertion 1: Zero timeout returns immediately (non-blocking)
consumer1 = TestConsumer(
{
'group.id': 'test-poll-zero-timeout',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer1.subscribe([topic])
start = time.time()
msg = consumer1.poll(timeout=0.0) # Zero timeout
elapsed = time.time() - start
assert (
elapsed < WAKEABLE_POLL_TIMEOUT_MAX
), f"Assertion 1 failed: Zero timeout took {elapsed:.2f}s, expected < {WAKEABLE_POLL_TIMEOUT_MAX}s"
assert msg is None, "Assertion 1 failed: Zero timeout with no messages should return None"
consumer1.close()
# Assertion 2: Closed consumer raises RuntimeError
consumer2 = TestConsumer({'group.id': 'test-poll-closed', 'socket.timeout.ms': 100, 'session.timeout.ms': 1000})
consumer2.close()
with pytest.raises(RuntimeError) as exc_info:
consumer2.poll(timeout=0.1)
msg = f"Assertion 2 failed: Expected 'Consumer closed' error, " f"got: {exc_info.value}"
assert 'Consumer closed' in str(exc_info.value), msg
# Assertion 3: Short timeout works correctly (no signal)
consumer3 = TestConsumer(
{
'group.id': 'test-poll-short-timeout',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer3.subscribe([topic])
start = time.time()
msg = consumer3.poll(timeout=0.1) # 100ms timeout
elapsed = time.time() - start
assert msg is None, "Assertion 3 failed: Short timeout with no messages should return None"
# Short timeouts (< 200ms) don't use chunking, so they can complete faster than WAKEABLE_POLL_TIMEOUT_MIN
# Only check upper bound to allow for actual timeout duration
assert (
elapsed <= WAKEABLE_POLL_TIMEOUT_MAX
), f"Assertion 3 failed: Short timeout took {elapsed:.2f}s, expected <= {WAKEABLE_POLL_TIMEOUT_MAX}s"
consumer3.close()
# Assertion 4: Very short timeout (less than chunk size) works
consumer4 = TestConsumer(
{
'group.id': 'test-poll-very-short',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer4.subscribe([topic])
start = time.time()
msg = consumer4.poll(timeout=0.05) # 50ms timeout (less than 200ms chunk)
elapsed = time.time() - start
assert msg is None, "Assertion 4 failed: Very short timeout should return None"
assert (
elapsed < WAKEABLE_POLL_TIMEOUT_MAX
), f"Assertion 4 failed: Very short timeout took {elapsed:.2f}s, expected < {WAKEABLE_POLL_TIMEOUT_MAX}s"
consumer4.close()
def test_consumer_wakeable_consume_interruptibility_and_messages():
"""Test consume() interruptibility (main fix) and message handling."""
topic = 'test-consume-interrupt-topic'
# Assertion 1: Infinite timeout can be interrupted immediately
consumer1 = TestConsumer(
{
'group.id': 'test-consume-infinite-immediate',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer1.subscribe([topic])
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.1))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
consumer1.consume() # Infinite timeout, default num_messages=1
except KeyboardInterrupt:
interrupted = True
finally:
consumer1.close()
assert interrupted, "Assertion 1 failed: Should have raised KeyboardInterrupt"
# Assertion 2: Finite timeout can be interrupted before timeout expires
consumer2 = TestConsumer(
{
'group.id': 'test-consume-finite-interrupt',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer2.subscribe([topic])
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.3))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
timeout_value = WAKEABLE_POLL_TIMEOUT_MAX # Use constant instead of hardcoded 2.0
try:
consumer2.consume(num_messages=10, timeout=timeout_value) # Use constant for timeout
except KeyboardInterrupt:
interrupted = True
finally:
consumer2.close()
assert interrupted, "Assertion 2 failed: Should have raised KeyboardInterrupt"
# Assertion 3: Signal sent after multiple chunks still interrupts quickly
consumer3 = TestConsumer(
{
'group.id': 'test-consume-multiple-chunks',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer3.subscribe([topic])
interrupt_thread = threading.Thread(target=lambda: TestUtils.send_sigint_after_delay(0.6))
interrupt_thread.daemon = True
interrupt_thread.start()
interrupted = False
try:
consumer3.consume(num_messages=5) # Infinite timeout
except KeyboardInterrupt:
interrupted = True
finally:
consumer3.close()
assert interrupted, "Assertion 3 failed: Should have raised KeyboardInterrupt"
# Assertion 4: No signal - timeout works normally, returns empty list
consumer4 = TestConsumer(
{
'group.id': 'test-consume-timeout-normal',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer4.subscribe([topic])
start = time.time()
msglist = consumer4.consume(num_messages=10, timeout=0.5) # 500ms, no signal
elapsed = time.time() - start
assert isinstance(msglist, list), "Assertion 4 failed: consume() should return a list"
assert len(msglist) == 0, f"Assertion 4 failed: Expected empty list (timeout), got {len(msglist)} messages"
assert (
WAKEABLE_POLL_TIMEOUT_MIN <= elapsed <= WAKEABLE_POLL_TIMEOUT_MAX
), f"Assertion 4 failed: Normal timeout took {elapsed:.2f}s, expected ~0.5s"
consumer4.close()
# Assertion 5: num_messages=0 returns empty list immediately
consumer5 = TestConsumer(
{
'group.id': 'test-consume-zero-messages',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer5.subscribe([topic])
start = time.time()
msglist = consumer5.consume(num_messages=0, timeout=1.0)
elapsed = time.time() - start
assert isinstance(msglist, list), "Assertion 5 failed: consume() should return a list"
assert len(msglist) == 0, "Assertion 5 failed: num_messages=0 should return empty list"
assert (
elapsed < WAKEABLE_POLL_TIMEOUT_MAX
), f"Assertion 5 failed: num_messages=0 took {elapsed:.2f}s, expected < {WAKEABLE_POLL_TIMEOUT_MAX}s"
consumer5.close()
def test_consumer_wakeable_consume_edge_cases():
"""Test consume() wakeable edge cases."""
topic = 'test-consume-edge-topic'
# Assertion 1: Zero timeout returns immediately (non-blocking)
consumer1 = TestConsumer(
{
'group.id': 'test-consume-zero-timeout',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer1.subscribe([topic])
start = time.time()
msglist = consumer1.consume(num_messages=10, timeout=0.0) # Zero timeout
elapsed = time.time() - start
assert (
elapsed < WAKEABLE_POLL_TIMEOUT_MAX
), f"Assertion 1 failed: Zero timeout took {elapsed:.2f}s, expected < {WAKEABLE_POLL_TIMEOUT_MAX}s"
assert isinstance(msglist, list), "Assertion 1 failed: consume() should return a list"
assert len(msglist) == 0, "Assertion 1 failed: Zero timeout with no messages should return empty list"
consumer1.close()
# Assertion 2: Closed consumer raises RuntimeError
consumer2 = TestConsumer({'group.id': 'test-consume-closed', 'socket.timeout.ms': 100, 'session.timeout.ms': 1000})
consumer2.close()
with pytest.raises(RuntimeError) as exc_info:
consumer2.consume(num_messages=10, timeout=0.1)
msg = f"Assertion 2 failed: Expected 'Consumer closed' error, " f"got: {exc_info.value}"
assert 'Consumer closed' in str(exc_info.value), msg
# Assertion 3: Invalid num_messages (negative) raises ValueError
consumer3 = TestConsumer(
{
'group.id': 'test-consume-invalid-negative',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer3.subscribe([topic])
with pytest.raises(ValueError) as exc_info:
consumer3.consume(num_messages=-1, timeout=0.1)
msg = f"Assertion 3 failed: Expected num_messages range error, " f"got: {exc_info.value}"
assert 'num_messages must be between 0 and 1000000' in str(exc_info.value), msg
consumer3.close()
# Assertion 4: Invalid num_messages (too large) raises ValueError
consumer4 = TestConsumer(
{
'group.id': 'test-consume-invalid-large',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer4.subscribe([topic])
with pytest.raises(ValueError) as exc_info:
consumer4.consume(num_messages=1000001, timeout=0.1)
msg = f"Assertion 4 failed: Expected num_messages range error, " f"got: {exc_info.value}"
assert 'num_messages must be between 0 and 1000000' in str(exc_info.value), msg
consumer4.close()
# Assertion 5: Short timeout works correctly (no signal)
consumer5 = TestConsumer(
{
'group.id': 'test-consume-short-timeout',
'socket.timeout.ms': 100,
'session.timeout.ms': 1000,
'auto.offset.reset': 'latest',
}
)
consumer5.subscribe([topic])
start = time.time()
msglist = consumer5.consume(num_messages=10, timeout=0.1) # 100ms timeout
elapsed = time.time() - start
assert isinstance(msglist, list), "Assertion 5 failed: consume() should return a list"
assert len(msglist) == 0, "Assertion 5 failed: Short timeout with no messages should return empty list"
# Only check upper bound to allow for actual timeout duration
assert (
elapsed <= WAKEABLE_POLL_TIMEOUT_MAX
), f"Assertion 5 failed: Short timeout took {elapsed:.2f}s, expected <= {WAKEABLE_POLL_TIMEOUT_MAX}s"