-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_backup_multi_bucket.py
More file actions
1785 lines (1338 loc) · 74 KB
/
test_backup_multi_bucket.py
File metadata and controls
1785 lines (1338 loc) · 74 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
# mypy: disable-error-code="no-untyped-def"
import gc
import os
import sys
import tempfile
import threading
from io import BytesIO
from pathlib import Path, PurePosixPath
from typing import Any, BinaryIO
from unittest import TestCase
import psutil
if sys.version_info < (3, 11):
from exceptiongroup import ExceptionGroup
from minio import Minio
from bucketbase import MemoryBucket, MinioBucket, ShallowListing
from bucketbase.backup_multi_bucket import BackupMultiBucket
TestBucket = MemoryBucket
class MockFailingBucket(MemoryBucket):
"""Mock bucket that can be configured to fail on specific operations"""
def __init__(
self,
fail_on_open_write=False,
fail_on_get=False,
fail_on_exists=False,
fail_on_get_stream=False,
fail_on_list=False,
fail_on_put_stream=False,
fail_on_get_size=False,
):
super().__init__()
self.fail_on_open_write = fail_on_open_write
self.fail_on_get = fail_on_get
self.fail_on_exists = fail_on_exists
self.fail_on_get_stream = fail_on_get_stream
self.fail_on_list = fail_on_list
self.fail_on_put_stream = fail_on_put_stream
self.fail_on_get_size = fail_on_get_size
def open_write(self, name, timeout_sec=1.0):
if self.fail_on_open_write:
raise RuntimeError("Failed to open write")
return super().open_write(name, timeout_sec)
def put_object_stream(self, name, stream):
if self.fail_on_put_stream:
raise RuntimeError("Failed to put object stream")
return super().put_object_stream(name, stream)
def get_object(self, name):
if self.fail_on_get:
raise RuntimeError("Failed to get object")
return super().get_object(name)
def get_object_stream(self, name):
if self.fail_on_get_stream:
raise RuntimeError("Failed to get object stream")
return super().get_object_stream(name)
def exists(self, name):
if self.fail_on_exists:
raise RuntimeError("Failed to check exists")
return super().exists(name)
def shallow_list_objects(self, prefix=""):
if self.fail_on_list:
raise RuntimeError("Failed to list objects")
return super().shallow_list_objects(prefix)
def get_size(self, name):
if self.fail_on_get_size:
raise RuntimeError("Failed to get object size")
return super().get_size(name)
class MockWriteFailingBucket(MemoryBucket):
"""Mock bucket that fails during write operations after opening"""
def __init__(self, fail_after_writes=0):
super().__init__()
self.fail_after_writes = fail_after_writes
self.write_count = 0
def open_write(self, name, timeout_sec=1.0):
return MockWriter(self, name, self.fail_after_writes)
class MockWriter:
"""Mock writer that fails after specified number of writes"""
def __init__(self, bucket, name, fail_after_writes):
self.bucket = bucket
self.name = name
self.fail_after_writes = fail_after_writes
self.write_count = 0
self.buffer = BytesIO()
def write(self, data):
if self.write_count >= self.fail_after_writes:
raise RuntimeError(f"Write failed after {self.write_count} writes")
self.write_count += 1
self.buffer.write(data)
def __enter__(self):
return self
def __exit__(self, *args) -> None:
if self.write_count <= self.fail_after_writes:
# Only save if we didn't fail
self.bucket.put_object_stream(self.name, BytesIO(self.buffer.getvalue()))
class TestBackupMultiBucketPutOperations(TestCase):
"""Test put operations - functional tests only"""
def setUp(self):
self.bucket1 = TestBucket()
self.bucket2 = TestBucket()
self.bucket3 = TestBucket()
self.multi_bucket = BackupMultiBucket([self.bucket1, self.bucket2, self.bucket3], timeout_sec=1.0)
self.test_name = "test/object.txt"
self.test_content = b"test content for streaming"
def test_put_object_stream_success_all_buckets(self):
"""Test successful put_object_stream to all buckets"""
stream = BytesIO(self.test_content)
self.multi_bucket.put_object_stream(self.test_name, stream)
# Verify content in all buckets
self.assertEqual(self.bucket1.get_object(self.test_name), self.test_content)
self.assertEqual(self.bucket2.get_object(self.test_name), self.test_content)
self.assertEqual(self.bucket3.get_object(self.test_name), self.test_content)
def test_put_object_stream_empty_content(self):
"""Test put_object_stream with empty content"""
empty_stream = BytesIO(b"")
self.multi_bucket.put_object_stream(self.test_name, empty_stream)
# Verify empty content in all buckets
self.assertEqual(self.bucket1.get_object(self.test_name), b"")
self.assertEqual(self.bucket2.get_object(self.test_name), b"")
self.assertEqual(self.bucket3.get_object(self.test_name), b"")
def test_put_object_stream_large_content(self):
"""Test put_object_stream with content larger than buffer size"""
# Create content larger than default buffer size (5MB)
large_content = b"x" * (6 * 1024 * 1024) # 6MB
stream = BytesIO(large_content)
self.multi_bucket.put_object_stream(self.test_name, stream)
# Verify content in all buckets
self.assertEqual(self.bucket1.get_object(self.test_name), large_content)
self.assertEqual(self.bucket2.get_object(self.test_name), large_content)
self.assertEqual(self.bucket3.get_object(self.test_name), large_content)
def test_put_object_stream_single_bucket_fails(self):
"""Test when one bucket fails to open write, others succeed"""
failing_bucket = MockFailingBucket(fail_on_open_write=True)
multi_bucket = BackupMultiBucket([failing_bucket, self.bucket2, self.bucket3], timeout_sec=1.0)
stream = BytesIO(self.test_content)
# Should raise ExceptionGroup since not all buckets succeeded
with self.assertRaises(RuntimeError) as ctx:
multi_bucket.put_object_stream(self.test_name, stream)
self.assertIn("Failed to open write", str(ctx.exception))
# Verify content was written to successful buckets
self.assertEqual(self.bucket2.get_object(self.test_name), self.test_content)
self.assertEqual(self.bucket3.get_object(self.test_name), self.test_content)
def test_put_object_stream_all_buckets_fail(self):
"""Test when all buckets fail to open write"""
failing_bucket1 = MockFailingBucket(fail_on_open_write=True)
failing_bucket2 = MockFailingBucket(fail_on_open_write=True)
multi_bucket = BackupMultiBucket([failing_bucket1, failing_bucket2], timeout_sec=1.0)
stream = BytesIO(self.test_content)
with self.assertRaises(ExceptionGroup) as ctx:
multi_bucket.put_object_stream(self.test_name, stream)
self.assertIn("Failed to open write", str(ctx.exception.exceptions[0]))
self.assertIn("Failed to open write", str(ctx.exception.exceptions[1]))
def test_put_object_stream_writer_fails_during_streaming(self):
"""Test when writer fails during streaming - covers exception handling in streaming loop"""
# Use a bucket that fails during write operations
failing_bucket = MockWriteFailingBucket(fail_after_writes=0) # Fail immediately on first write
multi_bucket = BackupMultiBucket([failing_bucket, self.bucket2, self.bucket3], timeout_sec=1.0)
# Use large content to ensure multiple writes and trigger the exception path
large_content = b"x" * (6 * 1024 * 1024) # 6MB
stream = BytesIO(large_content)
# Should raise ExceptionGroup since one writer fails during streaming
with self.assertRaises(RuntimeError) as ctx:
multi_bucket.put_object_stream(self.test_name, stream)
self.assertIn("Write failed after 0 writes", str(ctx.exception))
# Verify content was written to successful buckets
self.assertEqual(self.bucket2.get_object(self.test_name), large_content)
self.assertEqual(self.bucket3.get_object(self.test_name), large_content)
def test_put_object_stream_all_writers_fail_during_streaming(self):
"""Test when all writers fail during streaming - covers no active writers path"""
failing_bucket1 = MockWriteFailingBucket(fail_after_writes=0)
failing_bucket2 = MockWriteFailingBucket(fail_after_writes=0)
multi_bucket = BackupMultiBucket([failing_bucket1, failing_bucket2], timeout_sec=1.0)
# Use large content to trigger streaming
large_content = b"x" * (6 * 1024 * 1024) # 6MB
stream = BytesIO(large_content)
# Should raise ExceptionGroup when all writers fail
with self.assertRaises(ExceptionGroup) as ctx:
multi_bucket.put_object_stream(self.test_name, stream)
self.assertIn("Failed to write to one or more writers", str(ctx.exception))
def test_put_object_stream_empty_content_with_failed_writers(self):
"""Test edge case: empty content with some writers that would fail - covers line 34-35 check"""
# This is a tricky case: if we have empty content (0 bytes), the while loop
# might not execute, or execute once with empty buffer, potentially reaching line 34-35
# Create a scenario where some writers open successfully but would fail if used
failing_during_stream = MockWriteFailingBucket(fail_after_writes=0)
multi_bucket = BackupMultiBucket([failing_during_stream, self.bucket2], timeout_sec=1.0)
# Use empty content - this might cause the loop to behave differently
empty_stream = BytesIO(b"")
# This should succeed because empty content doesn't trigger write failures
multi_bucket.put_object_stream(self.test_name, empty_stream)
# Verify empty content was written to successful bucket
self.assertEqual(self.bucket2.get_object(self.test_name), b"")
class TestBackupMultiBucketFileOperations(TestCase):
"""Test file operations"""
def setUp(self):
self.bucket1 = TestBucket()
self.bucket2 = TestBucket()
self.bucket3 = TestBucket()
self.multi_bucket = BackupMultiBucket([self.bucket1, self.bucket2, self.bucket3], timeout_sec=1.0)
self.test_name = "test/file.txt"
self.test_content = b"test file content"
self.test_files: list[Path] = []
def tearDown(self):
for temp_file in self.test_files:
temp_file.unlink(missing_ok=True)
def create_temp_file(self, content=None):
"""Helper to create a temporary file; adds it to cleanup list"""
if content is None:
content = self.test_content
temp_file = Path(tempfile.mktemp())
temp_file.write_bytes(content)
self.test_files.append(temp_file)
return temp_file
def test_fput_object_success_all_buckets(self):
"""Test successful fput_object to all buckets"""
temp_file = self.create_temp_file()
self.multi_bucket.fput_object(self.test_name, temp_file)
# Verify content in all buckets
self.assertEqual(self.bucket1.get_object(self.test_name), self.test_content)
self.assertEqual(self.bucket2.get_object(self.test_name), self.test_content)
self.assertEqual(self.bucket3.get_object(self.test_name), self.test_content)
def test_fput_object_empty_file(self):
"""Test fput_object with empty file"""
temp_file = self.create_temp_file(b"")
self.multi_bucket.fput_object(self.test_name, temp_file)
# Verify empty content in all buckets
self.assertEqual(self.bucket1.get_object(self.test_name), b"")
self.assertEqual(self.bucket2.get_object(self.test_name), b"")
self.assertEqual(self.bucket3.get_object(self.test_name), b"")
def test_fput_object_file_not_found(self):
"""Test fput_object with non-existent file"""
non_existent_file = Path("/non/existent/file.txt")
with self.assertRaises(FileNotFoundError) as ctx:
self.multi_bucket.fput_object(self.test_name, non_existent_file)
self.assertIn("Source file not found", str(ctx.exception))
def test_fput_object_skip_upload_same_size(self):
"""Test skip upload when file already exists with same size"""
temp_file = self.create_temp_file()
# First upload
self.multi_bucket.fput_object(self.test_name, temp_file)
# Verify first upload worked
self.assertEqual(self.bucket1.get_object(self.test_name), self.test_content)
# Second upload with same content should succeed (skip logic)
self.multi_bucket.fput_object(self.test_name, temp_file)
# Content should still be there
self.assertEqual(self.bucket1.get_object(self.test_name), self.test_content)
def test_fput_object_reject_different_size(self):
"""Test rejection when file exists with different size"""
temp_file1 = self.create_temp_file(b"original content")
temp_file2 = self.create_temp_file(b"different content with different size")
# First upload
self.multi_bucket.fput_object(self.test_name, temp_file1)
# Second upload with different size should raise FileExistsError
with self.assertRaises(FileExistsError) as ctx:
self.multi_bucket.fput_object(self.test_name, temp_file2)
self.assertIn("already exists with different size", str(ctx.exception))
def test_fput_object_all_buckets_fail(self):
"""Test fput_object when all buckets fail - covers last_exc raising path"""
failing_bucket1 = MockFailingBucket(fail_on_put_stream=True)
failing_bucket2 = MockFailingBucket(fail_on_put_stream=True)
multi_bucket = BackupMultiBucket([failing_bucket1, failing_bucket2], timeout_sec=0.5)
temp_file = self.create_temp_file()
# Should raise ExceptionGroup when all buckets fail
with self.assertRaises(ExceptionGroup) as ctx:
multi_bucket.fput_object(self.test_name, temp_file)
# Check that the exception group contains the expected error messages
exception_messages = [str(exc) for exc in ctx.exception.exceptions]
self.assertTrue(any("Failed to put object stream" in msg for msg in exception_messages))
def test_fput_object_get_size_fails_during_skip_check(self):
"""Test fput_object when get_size fails during skip check - covers _should_skip_upload exception handling"""
# Create a bucket that has an object but fails when checking its size
self.bucket1.put_object_stream(self.test_name, BytesIO(self.test_content))
# Create a failing bucket that fails on get_size
failing_bucket = MockFailingBucket(fail_on_get_size=True)
# Put the same object in the failing bucket so it exists (to trigger size check)
failing_bucket.put_object_stream(self.test_name, BytesIO(self.test_content))
multi_bucket = BackupMultiBucket([self.bucket1, failing_bucket], timeout_sec=1.0)
temp_file = self.create_temp_file()
# Should raise IOError when get_size fails during skip check
with self.assertRaises(IOError) as ctx:
multi_bucket.fput_object(self.test_name, temp_file)
self.assertIn("Failed to get object size", str(ctx.exception))
def test_fput_object_large_file(self):
"""Test fput_object with file larger than buffer size"""
large_content = b"x" * (BackupMultiBucket._DEFAULT_BUF_SIZE + 1000)
self.temp_file = self.create_temp_file(large_content)
self.multi_bucket.fput_object(self.test_name, self.temp_file)
for bucket in [self.bucket1, self.bucket2, self.bucket3]:
self.assertEqual(bucket.get_object(self.test_name), large_content)
def test_fput_object_partial_upload_success_raises_on_check(self):
"""Test fput_object when upload succeeds to some buckets but fails to others"""
test_file = self.create_temp_file()
failing_bucket = MockFailingBucket(fail_on_open_write=True)
multi_bucket = BackupMultiBucket([self.bucket1, failing_bucket, self.bucket3], timeout_sec=1.0)
with self.assertRaises(RuntimeError) as ctx:
multi_bucket.fput_object(self.test_name, test_file)
self.assertIn("Failed to open write", str(ctx.exception))
self.assertEqual(self.bucket1.get_object(self.test_name), self.test_content)
self.assertEqual(self.bucket3.get_object(self.test_name), self.test_content)
with self.assertRaises(FileNotFoundError):
failing_bucket.get_object(self.test_name)
def test_fput_object_upload_needed_subset_of_buckets(self):
"""Test fput_object when only some buckets need the file uploaded"""
test_file = self.create_temp_file()
self.bucket2.put_object_stream(self.test_name, BytesIO(self.test_content))
self.bucket3.put_object_stream(self.test_name, BytesIO(self.test_content))
self.multi_bucket.fput_object(self.test_name, test_file)
for bucket in [self.bucket1, self.bucket2, self.bucket3]:
self.assertEqual(bucket.get_object(self.test_name), self.test_content)
class TestBackupMultiBucketGetOperations(TestCase):
"""Test get operations with fallback logic"""
def setUp(self):
self.bucket1 = TestBucket()
self.bucket2 = TestBucket()
self.bucket3 = TestBucket()
self.multi_bucket = BackupMultiBucket([self.bucket1, self.bucket2, self.bucket3], timeout_sec=1.0)
self.test_name = "test/object.txt"
self.test_content = b"test content for get operations"
def test_get_object_from_first_bucket(self):
"""Test get_object returns content from first available bucket"""
# Put content in all buckets
self.bucket1.put_object_stream(self.test_name, BytesIO(self.test_content))
self.bucket2.put_object_stream(self.test_name, BytesIO(b"different content"))
self.bucket3.put_object_stream(self.test_name, BytesIO(b"yet another content"))
# Should return content from first bucket
result = self.multi_bucket.get_object(self.test_name)
self.assertEqual(result, self.test_content)
def test_get_object_fallback_to_second_bucket(self):
"""Test get_object falls back when first bucket fails"""
# Put content only in second and third buckets
self.bucket2.put_object_stream(self.test_name, BytesIO(self.test_content))
self.bucket3.put_object_stream(self.test_name, BytesIO(b"different content"))
# Should return content from second bucket
result = self.multi_bucket.get_object(self.test_name)
self.assertEqual(result, self.test_content)
def test_get_object_fallback_through_all_buckets(self):
"""Test get_object falls back through all buckets"""
# Put content only in third bucket
self.bucket3.put_object_stream(self.test_name, BytesIO(self.test_content))
# Should return content from third bucket
result = self.multi_bucket.get_object(self.test_name)
self.assertEqual(result, self.test_content)
def test_get_object_not_found_in_any_bucket(self):
"""Test get_object when object not found in any bucket"""
with self.assertRaises(FileNotFoundError):
self.multi_bucket.get_object("non/existent/object.txt")
def test_get_object_first_bucket_generic_error(self):
"""Test get_object when first bucket has generic error"""
# Put content in second bucket
self.bucket2.put_object_stream(self.test_name, BytesIO(self.test_content))
# Make first bucket fail with generic error
failing_bucket = MockFailingBucket(fail_on_get=True)
multi_bucket = BackupMultiBucket([failing_bucket, self.bucket2, self.bucket3], timeout_sec=1.0)
# Should fall back to second bucket
result = multi_bucket.get_object(self.test_name)
self.assertEqual(result, self.test_content)
def test_get_object_stream_functionality(self):
"""Test get_object_stream returns proper stream"""
self.bucket1.put_object_stream(self.test_name, BytesIO(self.test_content))
with self.multi_bucket.get_object_stream(self.test_name) as stream:
result = stream.read()
self.assertEqual(result, self.test_content)
def test_get_object_stream_fallback(self):
"""Test get_object_stream falls back when first bucket fails"""
# Put content only in second bucket
self.bucket2.put_object_stream(self.test_name, BytesIO(self.test_content))
# Make first bucket fail
failing_bucket = MockFailingBucket(fail_on_get=True)
multi_bucket = BackupMultiBucket([failing_bucket, self.bucket2], timeout_sec=1.0)
# Should fall back to second bucket
with multi_bucket.get_object_stream(self.test_name) as stream:
result = stream.read()
self.assertEqual(result, self.test_content)
def test_get_object_all_buckets_fail_with_generic_error(self):
"""Test get_object when all buckets fail with generic errors - covers last_exception raising"""
failing_bucket1 = MockFailingBucket(fail_on_get=True)
failing_bucket2 = MockFailingBucket(fail_on_get=True)
multi_bucket = BackupMultiBucket([failing_bucket1, failing_bucket2], timeout_sec=1.0)
# Should raise the last exception when all buckets fail with generic errors
with self.assertRaises(RuntimeError) as ctx:
multi_bucket.get_object(self.test_name)
self.assertIn("Failed to get object", str(ctx.exception))
def test_get_object_stream_all_buckets_fail_with_generic_error(self):
"""Test get_object_stream when all buckets fail - covers assertion and exception paths"""
failing_bucket1 = MockFailingBucket(fail_on_get_stream=True)
failing_bucket2 = MockFailingBucket(fail_on_get_stream=True)
multi_bucket = BackupMultiBucket([failing_bucket1, failing_bucket2], timeout_sec=1.0)
# Should raise the last exception when all buckets fail
with self.assertRaises(RuntimeError) as ctx:
multi_bucket.get_object_stream(self.test_name)
self.assertIn("Failed to get object stream", str(ctx.exception))
def test_get_object_stream_mixed_errors(self):
"""Test get_object_stream with FileNotFoundError and generic error - covers last_not_found path"""
failing_bucket = MockFailingBucket(fail_on_get_stream=True)
multi_bucket = BackupMultiBucket([failing_bucket, self.bucket2], timeout_sec=1.0) # bucket2 has no content
# Should raise FileNotFoundError (last_not_found) over generic error
with self.assertRaises(FileNotFoundError):
multi_bucket.get_object_stream("non/existent/file.txt")
class TestBackupMultiBucketListOperations(TestCase):
"""Test list operations with merging"""
def setUp(self):
self.bucket1 = TestBucket()
self.bucket2 = TestBucket()
self.bucket3 = TestBucket()
self.multi_bucket = BackupMultiBucket([self.bucket1, self.bucket2, self.bucket3], timeout_sec=1.0)
def test_shallow_list_objects_merge_from_all_buckets(self):
"""Test shallow_list_objects merges results from all buckets"""
# Add different objects to different buckets
self.bucket1.put_object_stream("test/file1.txt", BytesIO(b"content1"))
self.bucket1.put_object_stream("test/file2.txt", BytesIO(b"content2"))
self.bucket2.put_object_stream("test/file2.txt", BytesIO(b"content2")) # Duplicate
self.bucket2.put_object_stream("test/file3.txt", BytesIO(b"content3"))
self.bucket3.put_object_stream("test/file4.txt", BytesIO(b"content4"))
result = self.multi_bucket.shallow_list_objects("test/")
# FSBucket strips the prefix, so we expect just the filenames
object_names = [obj.name for obj in result.objects]
self.assertIn("file1.txt", object_names)
self.assertIn("file2.txt", object_names)
self.assertIn("file3.txt", object_names)
self.assertIn("file4.txt", object_names)
# Should not have duplicates (though this depends on implementation)
self.assertEqual(len(object_names), 4) # 4 unique files
def test_shallow_list_objects_empty_prefix(self):
"""Test shallow_list_objects with empty prefix"""
# Put files in root directory for empty prefix test
self.bucket1.put_object_stream("file1.txt", BytesIO(b"content1"))
self.bucket2.put_object_stream("file2.txt", BytesIO(b"content2"))
result = self.multi_bucket.shallow_list_objects("")
object_names = [obj.name for obj in result.objects]
self.assertIn("file1.txt", object_names)
self.assertIn("file2.txt", object_names)
def test_shallow_list_objects_specific_prefix(self):
"""Test shallow_list_objects with specific prefix"""
self.bucket1.put_object_stream("test/file1.txt", BytesIO(b"content1"))
self.bucket1.put_object_stream("other/file2.txt", BytesIO(b"content2"))
self.bucket2.put_object_stream("test/file3.txt", BytesIO(b"content3"))
result = self.multi_bucket.shallow_list_objects("test/")
# FSBucket strips the prefix, so we expect just the filenames
object_names = [obj.name for obj in result.objects]
self.assertIn("file1.txt", object_names)
self.assertIn("file3.txt", object_names)
# file2.txt should not be in the test/ prefix results
self.assertNotIn("file2.txt", object_names)
def test_shallow_list_objects_all_buckets_fail(self):
"""Test shallow_list_objects when all buckets fail - covers last_exc raising path"""
failing_bucket1 = MockFailingBucket(fail_on_list=True)
failing_bucket2 = MockFailingBucket(fail_on_list=True)
multi_bucket = BackupMultiBucket([failing_bucket1, failing_bucket2], timeout_sec=1.0)
# Should raise the last exception when all buckets fail
with self.assertRaises(RuntimeError) as ctx:
multi_bucket.shallow_list_objects("")
self.assertIn("Failed to list objects", str(ctx.exception))
class TestBackupMultiBucketExistsOperations(TestCase):
"""Test exists operations"""
def setUp(self):
self.bucket1 = TestBucket()
self.bucket2 = TestBucket()
self.bucket3 = TestBucket()
self.multi_bucket = BackupMultiBucket([self.bucket1, self.bucket2, self.bucket3], timeout_sec=1.0)
self.test_name = "test/exists.txt"
self.test_content = b"test content for exists"
def test_exists_true_in_first_bucket(self):
"""Test exists returns True when object exists in first bucket"""
self.bucket1.put_object_stream(self.test_name, BytesIO(self.test_content))
self.assertTrue(self.multi_bucket.exists(self.test_name))
def test_exists_true_in_later_bucket(self):
"""Test exists returns True when object exists in later bucket"""
# Put object only in third bucket
self.bucket3.put_object_stream(self.test_name, BytesIO(self.test_content))
# The exists method should return True if object exists in ANY bucket
self.assertTrue(self.multi_bucket.exists(self.test_name))
def test_exists_false_not_in_any_bucket(self):
"""Test exists returns False when object not in any bucket"""
self.assertFalse(self.multi_bucket.exists("non/existent/file.txt"))
def test_exists_first_bucket_failure(self):
"""Test exists when first bucket fails"""
# Put object in second bucket
self.bucket2.put_object_stream(self.test_name, BytesIO(self.test_content))
# Make first bucket fail
failing_bucket = MockFailingBucket(fail_on_exists=True)
multi_bucket = BackupMultiBucket([failing_bucket, self.bucket2, self.bucket3], timeout_sec=1.0)
# Should fall back to second bucket and return True
self.assertTrue(multi_bucket.exists(self.test_name))
def test_exists_all_buckets_fail(self):
"""Test exists when all buckets fail - covers last_exc raising path"""
failing_bucket1 = MockFailingBucket(fail_on_exists=True)
failing_bucket2 = MockFailingBucket(fail_on_exists=True)
multi_bucket = BackupMultiBucket([failing_bucket1, failing_bucket2], timeout_sec=1.0)
# Should raise the last exception when all buckets fail
with self.assertRaises(RuntimeError) as ctx:
multi_bucket.exists(self.test_name)
self.assertIn("Failed to check exists", str(ctx.exception))
class TestBackupMultiBucketNotImplementedMethods(TestCase):
"""Test methods that are not implemented"""
def setUp(self):
self.bucket1 = TestBucket()
self.multi_bucket = BackupMultiBucket([self.bucket1], timeout_sec=1.0)
def test_put_object_not_implemented(self):
"""Test put_object raises NotImplementedError"""
with self.assertRaises(NotImplementedError):
self.multi_bucket.put_object("test.txt", b"content")
def test_get_size_not_implemented(self):
"""Test get_size raises NotImplementedError"""
with self.assertRaises(NotImplementedError):
self.multi_bucket.get_size("test.txt")
def test_list_objects_not_implemented(self):
"""Test list_objects raises NotImplementedError"""
with self.assertRaises(NotImplementedError):
self.multi_bucket.list_objects()
def test_remove_objects_not_implemented(self):
"""Test remove_objects raises NotImplementedError"""
with self.assertRaises(NotImplementedError):
self.multi_bucket.remove_objects(["test.txt"])
class TestBackupMultiBucketEdgeCases(TestCase):
"""Test edge cases and boundary conditions"""
def setUp(self):
self.bucket1 = TestBucket()
self.bucket2 = TestBucket()
def test_empty_buckets_list_operations(self):
"""Test operations with empty buckets list"""
multi_bucket = BackupMultiBucket([], timeout_sec=1.0)
# get_object should raise AssertionError when no buckets (last_exception is None)
with self.assertRaises(AssertionError):
multi_bucket.get_object("test.txt")
# exists should return False when no buckets
self.assertFalse(multi_bucket.exists("test.txt"))
def test_single_bucket_operations(self):
"""Test operations with single bucket"""
multi_bucket = BackupMultiBucket([self.bucket1], timeout_sec=1.0)
test_content = b"single bucket test"
# Should work normally with single bucket
stream = BytesIO(test_content)
multi_bucket.put_object_stream("test.txt", stream)
self.assertEqual(multi_bucket.get_object("test.txt"), test_content)
self.assertTrue(multi_bucket.exists("test.txt"))
result = multi_bucket.shallow_list_objects()
self.assertEqual(len(result.objects), 1)
def test_buffer_size_boundary_conditions(self):
"""Test content at buffer size boundaries"""
multi_bucket = BackupMultiBucket([self.bucket1, self.bucket2], timeout_sec=1.0)
buffer_size = BackupMultiBucket._DEFAULT_BUF_SIZE
# Test content exactly at buffer size
exact_content = b"x" * buffer_size
stream = BytesIO(exact_content)
multi_bucket.put_object_stream("test/exact.txt", stream)
self.assertEqual(multi_bucket.get_object("test/exact.txt"), exact_content)
# Test content one byte more than buffer size
over_content = b"x" * (buffer_size + 1)
stream = BytesIO(over_content)
multi_bucket.put_object_stream("test/over.txt", stream)
self.assertEqual(multi_bucket.get_object("test/over.txt"), over_content)
class TestBackupMultiBucketIntegrationScenarios(TestCase):
"""Test real-world integration scenarios"""
def setUp(self):
self.bucket1 = TestBucket()
self.bucket2 = TestBucket()
self.bucket3 = TestBucket()
self.multi_bucket = BackupMultiBucket([self.bucket1, self.bucket2, self.bucket3], timeout_sec=1.0)
def test_partial_bucket_failures_during_operations(self):
"""Test mixed success/failure scenarios across operations"""
test_content = b"integration test content"
# Initial successful upload to all buckets
stream = BytesIO(test_content)
self.multi_bucket.put_object_stream("test/file.txt", stream)
# Verify all buckets have the content
self.assertEqual(self.bucket1.get_object("test/file.txt"), test_content)
self.assertEqual(self.bucket2.get_object("test/file.txt"), test_content)
self.assertEqual(self.bucket3.get_object("test/file.txt"), test_content)
# Should still be able to read from any bucket
result = self.multi_bucket.get_object("test/file.txt")
self.assertEqual(result, test_content)
# Should still be able to check existence
self.assertTrue(self.multi_bucket.exists("test/file.txt"))
# Should still be able to list
listing = self.multi_bucket.shallow_list_objects("test/")
self.assertEqual(len(listing.objects), 1)
def test_large_scale_operations(self):
"""Test operations with many files"""
file_count = 10 # Reduced for faster testing
base_content = b"test content for file "
# Upload many files
for i in range(file_count):
content = base_content + str(i).encode()
stream = BytesIO(content)
self.multi_bucket.put_object_stream(f"test/file_{i:03d}.txt", stream)
# Verify all files exist
for i in range(file_count):
self.assertTrue(self.multi_bucket.exists(f"test/file_{i:03d}.txt"))
# Verify listing returns all files
listing = self.multi_bucket.shallow_list_objects("test/")
self.assertEqual(len(listing.objects), file_count)
# Verify content of random files
for i in [0, file_count // 2, file_count - 1]:
expected_content = base_content + str(i).encode()
actual_content = self.multi_bucket.get_object(f"test/file_{i:03d}.txt")
self.assertEqual(actual_content, expected_content)
class TestBackupMultiBucketMemoryMemLeak(TestCase):
@staticmethod
def _get_current_process_memory_MB() -> float:
process = psutil.Process(os.getpid())
return process.memory_info().rss / 1024 / 1024
class MockMinioClient(Minio):
def __init__(self, do_fail: bool, part_size: int):
self._do_fail = do_fail
self._part_size = part_size
self._chunks_written = [0]
def put_object(self, bucket_name: str, object_name: str, data: BinaryIO, length: int, **kwargs: Any) -> None:
if self._do_fail:
while data.read(self._part_size):
self._chunks_written[0] += 1
if self._chunks_written[0] > 1:
raise TimeoutError("test: timeout error after 1 chunk")
else:
while data.read(self._part_size):
pass
return None
def test_regression_fput_object_memory_leak_with_minio_timeout(self) -> None:
"""
Regression test for memory leak in BackupMultiBucket.
Issue summary:
- One of the clients in the BackupMultiBucket timed out repeatedly
- The memory usage of the process grew linearly with each retry
Investiagtion results:
- when using MagicMock objects instead of Minio Clients (extending Minio class), like in this test, the leak is reproduced through
the _put_object_stream_to_missing() which sends to the context.__exit__(e.__class__, e, e.__traceback__)
the __traceback__ object with the buffer from the while loop in _put_object_stream_to_missing(), since the tracebacks contain references to locals
The buffers gets accumulated in the MagicMock calls (calls are registered in a list in MagicMock).
If MagickMock was reset between calls to put, the leak was not reproducing.
This test just ensures that we won't have a memory leak in the future, which might be induced by BackupMultiBucket methods,
and ensures that ALL active threads after put_object_stream() returns.
"""
part_size = 5 * 1024 * 1024
file_size = 3 * part_size
file_content = b"x" * file_size
test_obj_path = PurePosixPath("test.bin")
mock_client_success = self.MockMinioClient(do_fail=False, part_size=part_size)
mock_minio_timeout = self.MockMinioClient(do_fail=True, part_size=part_size)
bucket_success = MinioBucket("test-bucket-success", mock_client_success)
bucket_timeout = MinioBucket("test-bucket-timeout", mock_minio_timeout)
multi_bucket = BackupMultiBucket([bucket_success, bucket_timeout], timeout_sec=1.5)
num_retries = 5
gc.collect()
baseline_memory = self._get_current_process_memory_MB()
memory_samples = [("baseline", baseline_memory)]
thread_ids_before = {t.ident for t in threading.enumerate()}
for i in range(1, num_retries + 1):
with self.assertRaises(TimeoutError):
current_memory = self._get_current_process_memory_MB()
print(f" retry_{i}: {current_memory:6.1f}MB (growth: {current_memory - baseline_memory:+6.1f}MB)")
stream = BytesIO(file_content)
multi_bucket.put_object_stream(test_obj_path, stream)
gc.collect()
current_memory = self._get_current_process_memory_MB()
memory_samples.append((f"retry_{i}", current_memory))
active_thread_ids = {t.ident for t in threading.enumerate()}
new_threads = active_thread_ids - thread_ids_before
self.assertEqual(0, len(new_threads))
final_memory = self._get_current_process_memory_MB()
final_growth = final_memory - baseline_memory
print("\n{'=' * 70}\nFPUT_OBJECT MEMORY LEAK TEST (production scenario)\n{'=' * 70}")
print(f"Total memory growth: {final_growth:.1f}MB ({final_growth / num_retries:.1f}MB per retry)")
for label, memory in memory_samples:
growth = memory - baseline_memory
print(f" {label:10s}: {memory:6.1f}MB (growth: {growth:+6.1f}MB)")
print(f"Final: {final_memory:6.1f}MB (growth: {final_growth:+6.1f}MB)")
threshold_mb = part_size * (num_retries - 1) / 1024 / 1024
leaks_present = final_growth > threshold_mb
self.assertFalse(leaks_present, f"regression: we have mem-leaks; {final_growth:.1f}MB > {threshold_mb:.1f}MB threshold")
print(f" [OK] NO LEAK: {final_growth:.1f}MB <= {threshold_mb:.1f}MB threshold\n{'=' * 70}\n")
class TestBackupMultiBucketComprehensive(TestCase):
"""
Note!!!
These tests were created by Claude 4.5, and have not been reviewed by human yet. They just pass
"""
class FailingMemoryBucket(MemoryBucket):
"""MemoryBucket that can be configured to fail on specific operations"""
def __init__(self, fail_on_open_write: bool = False, fail_on_write: bool = False, fail_after_bytes: int = -1, fail_on_exit: bool = False):
super().__init__()
self.fail_on_open_write = fail_on_open_write
self.fail_on_write = fail_on_write
self.fail_after_bytes = fail_after_bytes
self.fail_on_exit = fail_on_exit
self.bytes_written = 0
self.open_write_called = False
self.write_called = False
self.exit_called = False
def open_write(self, name: PurePosixPath | str, timeout_sec: float | None = None):
self.open_write_called = True
if self.fail_on_open_write:
raise RuntimeError("Simulated open_write failure")
# Return a custom context manager that tracks writes
parent_self = self
original_context = super().open_write(name, timeout_sec)
class FailingContextManager:
def __enter__(self):
self.writer = original_context.__enter__()
return self
def write(self, data: bytes) -> int:
parent_self.write_called = True
parent_self.bytes_written += len(data)
if parent_self.fail_on_write:
raise RuntimeError("Simulated write failure")
if parent_self.fail_after_bytes >= 0 and parent_self.bytes_written > parent_self.fail_after_bytes:
raise RuntimeError(f"Simulated write failure after {parent_self.fail_after_bytes} bytes")
return self.writer.write(data)
def __exit__(self, exc_type, exc_val, exc_tb):
parent_self.exit_called = True
if parent_self.fail_on_exit:
raise RuntimeError("Simulated exit failure")
return self.writer.__exit__(exc_type, exc_val, exc_tb)
return FailingContextManager()
def test_put_object_stream_success_all_buckets(self):
"""Test successful write to all buckets"""
bucket1 = MemoryBucket()
bucket2 = MemoryBucket()
bucket3 = MemoryBucket()
multi_bucket = BackupMultiBucket([bucket1, bucket2, bucket3], timeout_sec=1.0)
content = b"Hello, World!" * 1000
stream = BytesIO(content)
multi_bucket.put_object_stream("test.txt", stream)
# Verify all buckets have the content
self.assertEqual(content, bucket1.get_object("test.txt"))
self.assertEqual(content, bucket2.get_object("test.txt"))
self.assertEqual(content, bucket3.get_object("test.txt"))
def test_put_object_stream_one_bucket_fails_on_open(self):
"""Test write continues when one bucket fails on open_write, but raises exception at end"""
bucket1 = MemoryBucket()
bucket2 = self.FailingMemoryBucket(fail_on_open_write=True)
bucket3 = MemoryBucket()
multi_bucket = BackupMultiBucket([bucket1, bucket2, bucket3], timeout_sec=1.0)
content = b"Hello, World!" * 1000
stream = BytesIO(content)
# Should raise exception because one bucket failed, but successful buckets should have content
with self.assertRaises(RuntimeError) as ctx:
multi_bucket.put_object_stream("test.txt", stream)
self.assertIn("Simulated open_write failure", str(ctx.exception))
# Verify successful buckets have the content
self.assertEqual(content, bucket1.get_object("test.txt"))
self.assertEqual(content, bucket3.get_object("test.txt"))
# Verify failed bucket doesn't have the content
with self.assertRaises(FileNotFoundError):
bucket2.get_object("test.txt")
def test_put_object_stream_one_bucket_fails_on_write(self):
"""Test write continues when one bucket fails during write, but raises exception at end"""
bucket1 = MemoryBucket()
bucket2 = self.FailingMemoryBucket(fail_on_write=True)
bucket3 = MemoryBucket()
multi_bucket = BackupMultiBucket([bucket1, bucket2, bucket3], timeout_sec=1.0)
content = b"Hello, World!" * 1000
stream = BytesIO(content)
# Should raise exception because one bucket failed, but successful buckets should have content
with self.assertRaises(RuntimeError) as ctx:
multi_bucket.put_object_stream("test.txt", stream)
self.assertIn("Simulated write failure", str(ctx.exception))
# Verify successful buckets have the content
self.assertEqual(content, bucket1.get_object("test.txt"))
self.assertEqual(content, bucket3.get_object("test.txt"))
# Verify failed bucket doesn't have the content
with self.assertRaises(FileNotFoundError):
bucket2.get_object("test.txt")
def test_put_object_stream_all_buckets_fail_on_open(self):
"""Test exception raised when all buckets fail on open_write"""
bucket1 = self.FailingMemoryBucket(fail_on_open_write=True)