-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunitTest.py
More file actions
986 lines (859 loc) · 38 KB
/
unitTest.py
File metadata and controls
986 lines (859 loc) · 38 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
import sys
import time
import unittest
from unittest.mock import patch, mock_open, MagicMock
from datetime import datetime, timedelta
from FailureRecoveryManager import FailureRecoveryManager, ExecutionResult, Rows
import threading
from RecoverCriteria import RecoverCriteria
class ColoredTextTestResult(unittest.TextTestResult):
GREEN = "\033[92m"
RED = "\033[91m"
RESET = "\033[0m"
def addSuccess(self, test):
super().addSuccess(test)
print(f" {self.GREEN}SUCCESS: {test}{self.RESET}")
sys.stdout.flush()
def addFailure(self, test, err):
super().addFailure(test, err)
print(f" {self.RED}FAIL: {test}{self.RESET}")
sys.stdout.flush()
def addError(self, test, err):
super().addError(test, err)
print(f" {self.RED}ERROR: {test}{self.RESET}")
sys.stdout.flush()
class ColoredTextTestRunner(unittest.TextTestRunner):
resultclass = ColoredTextTestResult
class TestFailureRecoveryManager(unittest.TestCase):
def setUp(self):
# Reset class-level variables before each test
FailureRecoveryManager._checkpoint_thread_started = False
self.mock_file = "test.log"
self.manager = FailureRecoveryManager(log_file=self.mock_file)
@patch("builtins.open", new_callable=mock_open)
def test_write_log_commit(self, mocked_file):
"""Test writing a COMMIT log entry."""
# Arrange
execution_result = ExecutionResult(
transaction_id=1,
timestamp=datetime.now(),
type="COMMIT",
previous_data=Rows([{'id': 1, 'name': 'old_value'}], 1),
new_data=Rows([{'id': 1, 'name': 'new_value'}], 1),
query="UPDATE table_name SET name='new_value' WHERE id=1",
status=""
)
# Act
self.manager.write_log(execution_result)
# Assert
mocked_file.assert_called_once_with(self.manager.log_file, "a")
self.assertEqual(len(self.manager.memory_wal), 0) # Memory WAL should be cleared
handle = mocked_file()
handle.write.assert_called_once_with(
f"COMMIT,1,{execution_result.timestamp.isoformat()},UPDATE table_name SET name='new_value' WHERE id=1,Before: {repr(execution_result.previous_data.data)},After: {repr(execution_result.new_data.data)}\n"
)
@patch("builtins.open", new_callable=mock_open)
def test_write_log_active_with_full_memory_wal(self, mocked_file):
"""Test writing logs when memory WAL is full."""
# Arrange
self.manager.wal_size = 1 # Set WAL size to 1 to simulate it being full
execution_result = ExecutionResult(
transaction_id=2,
timestamp=datetime.now(),
type="ACTIVE",
previous_data=Rows([{'id': 2, 'name': 'temp_value'}], 1),
new_data=Rows([{'id': 2, 'name': 'final_value'}], 1),
query="UPDATE table_name SET name='final_value' WHERE id=2",
status=""
)
# Act
self.manager.write_log(execution_result)
# Assert
mocked_file.assert_called_once_with(self.manager.log_file, "a")
self.assertEqual(len(self.manager.memory_wal), 0) # Memory WAL should be cleared
handle = mocked_file()
handle.write.assert_called_once_with(
f"ACTIVE,2,{execution_result.timestamp.isoformat()},UPDATE table_name SET name='final_value' WHERE id=2,Before: {repr(execution_result.previous_data.data)},After: {repr(execution_result.new_data.data)}\n"
)
@patch("builtins.open", new_callable=mock_open)
def test_write_log_add_to_undo_list(self, mocked_file):
"""Test adding a transaction to the undo list when not committed."""
# Arrange
execution_result = ExecutionResult(
transaction_id=3,
timestamp=datetime.now(),
type="START",
previous_data=None,
new_data=None,
query=None,
status=""
)
# Act
self.manager.write_log(execution_result)
# Assert
self.assertIn(3, self.manager.undo_list) # Transaction ID should be added to undo list
mocked_file.assert_not_called() # No file operations should be performed for non-COMMIT actions
@patch("builtins.open", new_callable=mock_open)
def test_write_log_clear_undo_list_on_commit(self, mocked_file):
"""Test clearing the undo list when a transaction commits."""
# Arrange
self.manager.undo_list = [4]
execution_result = ExecutionResult(
transaction_id=4,
timestamp=datetime.now(),
type="COMMIT",
previous_data=Rows([{'id': 4, 'value': 'old'}], 1),
new_data=Rows([{'id': 4, 'value': 'new'}], 1),
query="UPDATE table_name SET value='new' WHERE id=4",
status=""
)
# Act
self.manager.write_log(execution_result)
# Assert
self.assertNotIn(4, self.manager.undo_list) # Transaction ID should be removed from undo list
mocked_file.assert_called_once_with(self.manager.log_file, "a")
@patch("builtins.open", new_callable=mock_open)
def test_write_log_multiple_entries(self, mocked_file):
"""Test writing multiple entries from the memory WAL."""
# Arrange
execution_result_1 = ExecutionResult(
transaction_id=5,
timestamp=datetime.now(),
type="ACTIVE",
previous_data=Rows([{'id': 5, 'value': 'temp'}], 1),
new_data=Rows([{'id': 5, 'value': 'final'}], 1),
query="UPDATE table_name SET value='final' WHERE id=5",
status=""
)
execution_result_2 = ExecutionResult(
transaction_id=6,
timestamp=datetime.now(),
type="COMMIT",
previous_data=Rows([{'id': 6, 'value': 'old'}], 1),
new_data=Rows([{'id': 6, 'value': 'new'}], 1),
query="UPDATE table_name SET value='new' WHERE id=6",
status=""
)
self.manager.memory_wal.extend([execution_result_1, execution_result_2])
# Act
self.manager.write_log(execution_result_2)
# Assert
mocked_file.assert_called_once_with(self.manager.log_file, "a")
self.assertEqual(len(self.manager.memory_wal), 0) # Memory WAL should be cleared
handle = mocked_file()
handle.write.assert_any_call(
f"ACTIVE,5,{execution_result_1.timestamp.isoformat()},UPDATE table_name SET value='final' WHERE id=5,Before: {repr(execution_result_1.previous_data.data)},After: {repr(execution_result_1.new_data.data)}\n"
)
handle.write.assert_any_call(
f"COMMIT,6,{execution_result_2.timestamp.isoformat()},UPDATE table_name SET value='new' WHERE id=6,Before: {repr(execution_result_2.previous_data.data)},After: {repr(execution_result_2.new_data.data)}\n"
)
@patch("builtins.open", new_callable=mock_open)
def test_write_log_with_full_memory_wal(self, mocked_file):
"""Test writing logs when memory WAL is full with 3 pre-appended entries."""
# Arrange
self.manager.wal_size = 4 # Set memory WAL size to 4
# Prepopulate memory WAL with 3 entries
execution_result_1 = ExecutionResult(
transaction_id=1,
timestamp=datetime.now(),
type="ACTIVE",
previous_data=Rows([{'id': 1, 'value': 'old_value_1'}], 1),
new_data=Rows([{'id': 1, 'value': 'new_value_1'}], 1),
query="UPDATE table_name SET value='new_value_1' WHERE id=1",
status=""
)
execution_result_2 = ExecutionResult(
transaction_id=2,
timestamp=datetime.now(),
type="ACTIVE",
previous_data=Rows([{'id': 2, 'value': 'old_value_2'}], 1),
new_data=Rows([{'id': 2, 'value': 'new_value_2'}], 1),
query="UPDATE table_name SET value='new_value_2' WHERE id=2",
status=""
)
execution_result_3 = ExecutionResult(
transaction_id=3,
timestamp=datetime.now(),
type="ACTIVE",
previous_data=Rows([{'id': 3, 'value': 'old_value_3'}], 1),
new_data=Rows([{'id': 3, 'value': 'new_value_3'}], 1),
query="UPDATE table_name SET value='new_value_3' WHERE id=3",
status=""
)
self.manager.memory_wal.extend([execution_result_1, execution_result_2, execution_result_3])
# New entry to write, making the memory full
execution_result_4 = ExecutionResult(
transaction_id=4,
timestamp=datetime.now(),
type="ACTIVE",
previous_data=Rows([{'id': 4, 'value': 'old_value_4'}], 1),
new_data=Rows([{'id': 4, 'value': 'new_value_4'}], 1),
query="UPDATE table_name SET value='new_value_4' WHERE id=4",
status=""
)
# Act
self.manager.write_log(execution_result_4)
# Assert
mocked_file.assert_called_once_with(self.manager.log_file, "a") # Log file opened for writing
self.assertEqual(len(self.manager.memory_wal), 0) # Memory WAL should be cleared
handle = mocked_file()
# Assert the log file writes 4 entries (3 pre-existing + 1 new)
handle.write.assert_any_call(
f"ACTIVE,1,{execution_result_1.timestamp.isoformat()},UPDATE table_name SET value='new_value_1' WHERE id=1,Before: {repr(execution_result_1.previous_data.data)},After: {repr(execution_result_1.new_data.data)}\n"
)
handle.write.assert_any_call(
f"ACTIVE,2,{execution_result_2.timestamp.isoformat()},UPDATE table_name SET value='new_value_2' WHERE id=2,Before: {repr(execution_result_2.previous_data.data)},After: {repr(execution_result_2.new_data.data)}\n"
)
handle.write.assert_any_call(
f"ACTIVE,3,{execution_result_3.timestamp.isoformat()},UPDATE table_name SET value='new_value_3' WHERE id=3,Before: {repr(execution_result_3.previous_data.data)},After: {repr(execution_result_3.new_data.data)}\n"
)
handle.write.assert_any_call(
f"ACTIVE,4,{execution_result_4.timestamp.isoformat()},UPDATE table_name SET value='new_value_4' WHERE id=4,Before: {repr(execution_result_4.previous_data.data)},After: {repr(execution_result_4.new_data.data)}\n"
)
self.assertEqual(handle.write.call_count, 4) # Ensure write was called 4 times
def test_save_checkpoint_with_memory_wal(self):
# Arrange
fixed_time = datetime(2024, 12, 10, 10, 0, 0)
self.manager.memory_wal = [
ExecutionResult(
transaction_id=1,
timestamp=fixed_time,
type="ACTIVE",
previous_data=Rows([{'id': 1, 'name': 'old_value'}], 1),
new_data=Rows([{'id': 1, 'name': 'new_value'}], 1),
query="UPDATE table_name SET name='new_value' WHERE id=1",
status=""
)
]
with patch("builtins.open", mock_open()) as mocked_file:
with patch("datetime.datetime") as mock_datetime:
# Mock datetime.now() to return fixed_time
mock_datetime.now.return_value = fixed_time
mock_datetime.side_effect = lambda *args, **kwargs: datetime(*args, **kwargs)
# Act
self.manager.save_checkpoint()
# Assert
# Ensure open was called twice: once for memory_wal entries, once for the checkpoint
self.assertEqual(mocked_file.call_count, 2)
# Verify the contents of the writes
handle = mocked_file()
handle.write.assert_any_call(
"ACTIVE,1,2024-12-10T10:00:00,UPDATE table_name SET name='new_value' WHERE id=1,"
"Before: [{'id': 1, 'name': 'old_value'}],After: [{'id': 1, 'name': 'new_value'}]\n"
)
handle.write.assert_any_call('CHECKPOINT,2024-12-10T10:00:00,[]\n')
def test_parse_log_file_with_valid_logs(self):
# Arrange
log_content = (
"ACTIVE,1,2024-12-10T10:00:00,UPDATE table_name SET name='new_value' WHERE id=1,"
"Before: [{'id': 1, 'name': 'old_value'}],After: [{'id': 1, 'name': 'new_value'}]\n"
"CHECKPOINT,2024-12-10T11:00:00,[1, 2, 3]\n"
)
with patch("builtins.open", mock_open(read_data=log_content)):
# Act
results, undo_list = self.manager.parse_log_file(self.mock_file)
# Assert
self.assertEqual(len(results), 2)
self.assertEqual(results[0].transaction_id, 1)
self.assertEqual(results[1].type, "CHECKPOINT")
@patch("builtins.open", new_callable=mock_open)
@patch("datetime.datetime")
def test_save_checkpoint(self, mock_datetime, mocked_file):
"""Test saving a checkpoint manually."""
# Arrange
fixed_time = datetime(2024, 12, 11, 12, 0, 0)
mock_datetime.now.return_value = fixed_time
log_entry = ExecutionResult(
transaction_id=1,
timestamp=fixed_time,
type="ACTIVE",
previous_data=Rows([{'id': 1, 'value': 'old_value'}], 1),
new_data=Rows([{'id': 1, 'value': 'new_value'}], 1),
query="UPDATE table_name SET value='new_value' WHERE id=1",
status=""
)
self.manager.memory_wal = [log_entry]
# Act
self.manager.save_checkpoint()
# Assert
self.assertEqual(mocked_file.call_count, 2) # Ensure file opened twice
handle = mocked_file()
handle.write.assert_any_call(
f"ACTIVE,1,{fixed_time.isoformat()},UPDATE table_name SET value='new_value' WHERE id=1,Before: {repr(log_entry.previous_data.data)},After: {repr(log_entry.new_data.data)}\n"
)
handle.write.assert_any_call(f"CHECKPOINT,{fixed_time.isoformat()},[]\n")
self.assertEqual(len(self.manager.memory_wal), 0) # Ensure memory WAL is cleared
@patch("builtins.open", new_callable=mock_open)
@patch("datetime.datetime")
def test_save_checkpoint_with_empty_memory_wal(self, mock_datetime, mocked_file):
"""Test saving a checkpoint with an empty memory WAL."""
# Arrange
fixed_time = datetime(2024, 12, 11, 12, 0, 0)
mock_datetime.now.return_value = fixed_time
self.manager.memory_wal = []
# Act
self.manager.save_checkpoint()
# Assert
self.assertEqual(mocked_file.call_count, 1) # Only checkpoint log is written
handle = mocked_file()
handle.write.assert_called_once_with(f"CHECKPOINT,{fixed_time.isoformat()},[]\n")
@patch("builtins.open", new_callable=mock_open)
@patch("datetime.datetime")
def test_save_checkpoint_with_undo_list(self, mock_datetime, mocked_file):
"""Test saving a checkpoint with an undo list."""
# Arrange
fixed_time = datetime(2024, 12, 11, 12, 0, 0)
mock_datetime.now.return_value = fixed_time
self.manager.undo_list = [1, 2, 3]
# Act
self.manager.save_checkpoint()
# Assert
self.assertEqual(mocked_file.call_count, 1) # Only checkpoint log is written
handle = mocked_file()
handle.write.assert_called_once_with(f"CHECKPOINT,{fixed_time.isoformat()},[1, 2, 3]\n")
def test_build_update_query(self):
# Arrange
table_name = "users"
before = Rows([{"id": 1, "name": "old_value"}], 1)
after = Rows([{"id": 1, "name": "new_value"}], 1)
# Act
queries = self.manager.build_update_query(table_name, before, after)
# Assert
expected_query = "UPDATE users SET id=1, name='old_value' WHERE id=1 AND name='new_value';"
self.assertEqual(queries[0], expected_query)
def test_build_delete_query(self):
# Arrange
table_name = "users"
after = Rows([{"id": 1, "name": "new_value"}], 1)
# Act
queries = self.manager.build_delete_query(table_name, after)
# Assert
expected_query = "DELETE FROM users WHERE id=1 AND name='new_value';"
self.assertEqual(queries[0], expected_query)
def test_build_insert_query(self):
# Arrange
table_name = "users"
before = Rows([{"id": 1, "name": "old_value"}], 1)
after = Rows([{"id": 1, "name": "new_value"}], 1)
# Act
queries = self.manager.build_insert_query(table_name, before, after)
# Assert
expected_query = "INSERT INTO users (id, name) VALUES (1, 'old_value');"
self.assertEqual(queries[0], expected_query)
@patch("builtins.print")
def test_recover_no_criteria(self, mock_print):
"""Test recover with no transaction IDs provided."""
# Arrange
criteria = RecoverCriteria(transaction_id=[])
# Act
undo_queries = self.manager.recover(criteria)
self.assertEqual(undo_queries, [])
@patch("builtins.print")
def test_recover_empty_undo_list(self, mock_print):
"""Test recover with transaction IDs not present in undo list."""
# Arrange
criteria = RecoverCriteria(transaction_id=[1, 2])
self.manager.undo_list = [3, 4] # Different transaction IDs
# Act
undo_queries = self.manager.recover(criteria)
# Assert
self.assertEqual(undo_queries, [])
@patch("FailureRecoveryManager.FailureRecoveryManager.parse_log_file")
def test_recover_stops_at_start(self, mock_parse_log_file):
"""Test that recovery stops when encountering a START log entry."""
# Arrange
criteria = RecoverCriteria(transaction_id=[1])
self.manager.undo_list = [1]
# Memory WAL has transaction 1 active and a START entry
exec_result_1 = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 10, 0, 0),
type="UPDATE",
status="",
query="UPDATE table_name SET name='new_value' WHERE id=1",
previous_data=Rows([{'id': 1, 'name': 'old_value'}], 1),
new_data=Rows([{'id': 1, 'name': 'new_value'}], 1)
)
exec_result_start = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 9, 59, 0),
type="START",
status="",
query=None,
previous_data=None,
new_data=None
)
self.manager.memory_wal.extend([exec_result_start, exec_result_1])
# Mock log file parsing to include no relevant entries
mock_parse_log_file.return_value = ([], [])
# Act
undo_queries = self.manager.recover(criteria)
# Assert
expected_queries = [
[1, "UPDATE table_name SET id=1, name='old_value' WHERE id=1 AND name='new_value';"]
]
self.assertEqual(undo_queries, expected_queries)
@patch("FailureRecoveryManager.FailureRecoveryManager.parse_log_file")
def test_recover_uses_log_file_if_needed(self, mock_parse_log_file):
"""Test that recovery uses the log file if memory WAL does not contain START."""
# Arrange
criteria = RecoverCriteria(transaction_id=[1])
self.manager.undo_list = [1]
# Memory WAL has transaction 1 active but no START entry
exec_result_1 = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 10, 0, 0),
type="UPDATE",
status="",
query="UPDATE table_name SET name='new_value' WHERE id=1",
previous_data=Rows([{'id': 1, 'name': 'old_value'}], 1),
new_data=Rows([{'id': 1, 'name': 'new_value'}], 1)
)
self.manager.memory_wal.append(exec_result_1)
# Mock log file parsing to include the START entry
exec_result_start = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 9, 59, 0),
type="START",
status="",
query=None,
previous_data=None,
new_data=None
)
mock_parse_log_file.return_value = ([exec_result_start], [1])
# Act
undo_queries = self.manager.recover(criteria)
# Assert
expected_queries = [
[1,"UPDATE table_name SET id=1, name='old_value' WHERE id=1 AND name='new_value';"]
]
self.assertEqual(undo_queries, expected_queries)
mock_parse_log_file.assert_called_once_with(self.mock_file)
@patch("FailureRecoveryManager.FailureRecoveryManager.parse_log_file")
def test_recover_handles_multiple_transactions(self, mock_parse_log_file):
"""Test recovery with multiple transactions in the undo list."""
# Arrange
criteria = RecoverCriteria(transaction_id=[1, 2])
self.manager.undo_list = [1, 2]
# Memory WAL has transaction 1 active and 2 without START
exec_result_1 = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 10, 0, 0),
type="UPDATE",
status="",
query="UPDATE table_name SET name='new_value' WHERE id=1;",
previous_data=Rows([{'id': 1, 'name': 'old_value'}], 1),
new_data=Rows([{'id': 1, 'name': 'new_value'}], 1)
)
exec_result_2 = ExecutionResult(
transaction_id=2,
timestamp=datetime(2024, 11, 22, 10, 5, 0),
type="INSERT",
status="",
query="INSERT INTO table_name (id, name) VALUES (2, 'new_entry');",
previous_data=Rows([], 0),
new_data=Rows([{'id': 2, 'name': 'new_entry'}], 1)
)
self.manager.memory_wal.extend([exec_result_1, exec_result_2])
# Mock log file parsing to include START for both transactions
exec_result_start_1 = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 9, 59, 0),
type="START",
status="",
query=None,
previous_data=None,
new_data=None
)
exec_result_start_2 = ExecutionResult(
transaction_id=2,
timestamp=datetime(2024, 11, 22, 9, 58, 0),
type="START",
status="",
query=None,
previous_data=None,
new_data=None
)
mock_parse_log_file.return_value = ([exec_result_start_1, exec_result_start_2],[])
# Act
undo_queries = self.manager.recover(criteria)
# Assert
expected_queries = [
[2,"DELETE FROM table_name WHERE id=2 AND name='new_entry';"],
[1,"UPDATE table_name SET id=1, name='old_value' WHERE id=1 AND name='new_value';"],
]
self.assertEqual(undo_queries, expected_queries)
mock_parse_log_file.assert_called_once_with(self.mock_file)
@patch("FailureRecoveryManager.FailureRecoveryManager.parse_log_file")
def test_recover_handles_delete(self, mock_parse_log_file):
"""Test recovery handles DELETE operation."""
# Arrange
criteria = RecoverCriteria(transaction_id=[3])
self.manager.undo_list = [3]
# Memory WAL has transaction 3 with a DELETE operation
exec_result_delete = ExecutionResult(
transaction_id=3,
timestamp=datetime(2024, 11, 22, 10, 10, 0),
type="DELETE",
status="",
query="DELETE FROM table_name WHERE id=3;",
previous_data=Rows([{'id': 3, 'name': 'deleted_entry'}], 1),
new_data=Rows([], 0)
)
self.manager.memory_wal.append(exec_result_delete)
# Mock log file parsing to include START entry for transaction 3
exec_result_start = ExecutionResult(
transaction_id=3,
timestamp=datetime(2024, 11, 22, 9, 55, 0),
type="START",
status="",
query=None,
previous_data=None,
new_data=None
)
mock_parse_log_file.return_value = ([exec_result_start],[])
# Act
undo_queries = self.manager.recover(criteria)
# Assert
expected_queries = [
[3,"INSERT INTO table_name (id, name) VALUES (3, 'deleted_entry');"]
]
self.assertEqual(undo_queries, expected_queries)
mock_parse_log_file.assert_called_once_with(self.mock_file)
@patch("FailureRecoveryManager.FailureRecoveryManager.parse_log_file")
@patch("builtins.print")
def test_recover_file_transactions(self, mock_print, mock_parse_log_file):
"""Test recover with aborted transactions present in the log file."""
# Arrange
criteria = RecoverCriteria(transaction_id=[1])
self.manager.undo_list = [1, 2]
# Memory WAL has transaction 1 active
exec_result_1 = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 10, 0, 0),
type="UPDATE",
status="",
query="UPDATE table_name SET name='new_value' WHERE id=1;",
previous_data=Rows([{'id': 1, 'name': 'old_value'}], 1),
new_data=Rows([{'id': 1, 'name': 'new_value'}], 1)
)
self.manager.memory_wal.append(exec_result_1)
# Mock log file parsing to include transaction 2 as aborted
exec_result_2 = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 10, 15, 0),
type="START",
status="",
query=None,
previous_data=Rows([], 0),
new_data=Rows([], 0)
)
mock_parse_log_file.return_value = ([exec_result_2],[])
# Act
undo_queries = self.manager.recover(criteria)
# Assert
expected_queries = [
[1, "UPDATE table_name SET id=1, name='old_value' WHERE id=1 AND name='new_value';"]
]
self.assertEqual(undo_queries, expected_queries)
mock_parse_log_file.assert_called_once_with(self.mock_file)
@patch("builtins.print")
def test_recover_partial_transactions_in_memory_wal(self, mock_print):
"""Test recover where some transactions are in memory_wal and some are not."""
# Arrange
criteria = RecoverCriteria(transaction_id=[1, 2, 3])
self.manager.undo_list = [1, 2, 3]
# Memory WAL has transaction 1 active
exec_result_1 = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 10, 0, 0),
type="UPDATE",
status="",
query="UPDATE table_name SET name='new_value1' WHERE id=1;",
previous_data=Rows([{'id': 1, 'name': 'old_value1'}], 1),
new_data=Rows([{'id': 1, 'name': 'new_value1'}], 1)
)
self.manager.memory_wal.append(exec_result_1)
# Mock parse_log_file to have transaction 2 in log file
exec_result_2 = ExecutionResult(
transaction_id=2,
timestamp=datetime(2024, 11, 22, 10, 5, 0),
type="INSERT",
status="",
query="INSERT INTO table_name (id, name) VALUES (2, 'value2');",
previous_data=Rows([], 0),
new_data=Rows([{'id': 2, 'name': 'value2'}], 1)
)
exec_result_3 = ExecutionResult(
transaction_id=3,
timestamp=datetime(2024, 11, 22, 10, 10, 0),
type="START",
status="",
query=None,
previous_data=Rows([], 0),
new_data=Rows([], 0)
)
with patch.object(self.manager, 'parse_log_file', return_value=([exec_result_2, exec_result_3],[])):
# Act
undo_queries = self.manager.recover(criteria)
# Assert
expected_queries = [
[1,"UPDATE table_name SET id=1, name='old_value1' WHERE id=1 AND name='new_value1';"],
[2,"DELETE FROM table_name WHERE id=2 AND name='value2';"]
]
self.assertEqual(undo_queries, expected_queries)
@patch("FailureRecoveryManager.FailureRecoveryManager.parse_log_file")
@patch("builtins.print")
def test_recover_no_log_file(self, mock_print, mock_parse_log_file):
"""Test recover when log file does not exist."""
# Arrange
criteria = RecoverCriteria(transaction_id=[1])
self.manager.undo_list = [1]
# Memory WAL has transaction 1 active
exec_result_1 = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 10, 0, 0),
type="ACTIVE",
status="DELETE",
query="DELETE FROM table_name WHERE id=1;",
previous_data=Rows([{'id': 1, 'name': 'value1'}], 1),
new_data=Rows([], 0)
)
self.manager.memory_wal.append(exec_result_1)
# Mock parse_log_file to raise an exception indicating missing log file
mock_parse_log_file.side_effect = Exception("No log file. Abort recovery.")
# Act
undo_queries = self.manager.recover(criteria)
# Assert
mock_print.assert_any_call("Error during recovery: No log file. Abort recovery.")
self.assertEqual(undo_queries, [])
@patch("FailureRecoveryManager.FailureRecoveryManager.parse_log_file")
@patch("builtins.print")
def test_recover_start_transaction_only(self, mock_print, mock_parse_log_file):
"""Test recover where a transaction has only a START log entry."""
# Arrange
criteria = RecoverCriteria(transaction_id=[1])
self.manager.undo_list = [1]
# Memory WAL has transaction 1 as START
exec_result_1 = ExecutionResult(
transaction_id=1,
timestamp=datetime(2024, 11, 22, 10, 0, 0),
type="START",
status="",
query=None,
previous_data=Rows([], 0),
new_data=Rows([], 0)
)
self.manager.memory_wal.append(exec_result_1)
# Act
undo_queries = self.manager.recover(criteria)
# Assert
expected_queries = []
self.assertEqual(undo_queries, expected_queries)
mock_parse_log_file.assert_not_called()
def test_recovery_scenario(self):
before_insert_data = Rows(data=[], rows_count=0)
after_insert_data = Rows(data=[{"id": 1, "name": "Alice"}], rows_count=1)
before_update_data = Rows(data=[{"id": 1, "name": "Alice"}], rows_count=1)
after_update_data = Rows(data=[{"id": 1, "name": "Alicia"}], rows_count=1)
before_delete_data = Rows(data=[{"id": 2, "name": "Bob"}], rows_count=1)
after_delete_data = Rows(data=[], rows_count=0)
# Transaction 100: Will be fully committed
# START
start_100 = ExecutionResult(
transaction_id=100,
timestamp=datetime.now(),
type="START",
status="",
query=None,
previous_data=before_insert_data,
new_data=after_insert_data
)
self.manager.write_log(start_100)
# INSERT
insert_100 = ExecutionResult(
transaction_id=100,
timestamp=datetime.now(),
type="INSERT",
status="",
query="INSERT INTO test (id, name) VALUES (1,'Alice');",
previous_data=before_insert_data,
new_data=after_insert_data
)
self.manager.write_log(insert_100)
# UPDATE
update_100 = ExecutionResult(
transaction_id=100,
timestamp=datetime.now(),
type="UPDATE",
status="",
query="UPDATE test SET name='Alicia' WHERE id=1;",
previous_data=before_update_data,
new_data=after_update_data
)
self.manager.write_log(update_100)
# COMMIT transaction 100
commit_100 = ExecutionResult(
transaction_id=100,
timestamp=datetime.now(),
type="COMMIT",
status="",
query="COMMIT;",
previous_data=before_insert_data,
new_data=after_insert_data
)
self.manager.write_log(commit_100)
# Transaction 101: Will not commit
start_101 = ExecutionResult(
transaction_id=101,
timestamp=datetime.now(),
type="START",
status="",
query="",
previous_data=before_insert_data,
new_data=after_insert_data
)
self.manager.write_log(start_101)
insert_101 = ExecutionResult(
transaction_id=101,
timestamp=datetime.now(),
type="INSERT",
status="",
query="INSERT INTO test (id, name) VALUES (3,'Charlie');",
previous_data=before_insert_data,
new_data=Rows(data=[{"id": 3, "name": "Charlie"}], rows_count=1)
)
self.manager.write_log(insert_101)
update_101 = ExecutionResult(
transaction_id=101,
timestamp=datetime.now(),
type="UPDATE",
status="",
query="UPDATE test SET name='Charles' WHERE id=3;",
previous_data=Rows(data=[{"id": 3, "name": "Charlie"}], rows_count=1),
new_data=Rows(data=[{"id": 3, "name": "Charles"}], rows_count=1)
)
self.manager.write_log(update_101)
# No COMMIT for transaction 101
# Transaction 102: Will not commit (DELETE case)
start_102 = ExecutionResult(
transaction_id=102,
timestamp=datetime.now(),
type="START",
status="",
query=None,
previous_data=before_delete_data,
new_data=after_delete_data
)
self.manager.write_log(start_102)
start_104 = ExecutionResult(
transaction_id=104,
timestamp=datetime.now(),
type="START",
status="",
query=None,
previous_data=before_delete_data,
new_data=after_delete_data
)
self.manager.write_log(start_104)
delete_102 = ExecutionResult(
transaction_id=102,
timestamp=datetime.now(),
type="DELETE",
status="",
query="DELETE FROM test WHERE id=2;",
previous_data=before_delete_data,
new_data=after_delete_data
)
self.manager.write_log(delete_102)
self.manager.save_checkpoint()
criteria = RecoverCriteria(transaction_id=[101, 102], timestamp=None)
undo_queries = self.manager.recover(criteria)
expected_101_update_undo = "UPDATE test SET id=3, name='Charlie' WHERE id=3 AND name='Charles';"
expected_101_insert_undo = "DELETE FROM test WHERE id=3 AND name='Charlie';"
expected_102_delete_undo = "INSERT INTO test (id, name) VALUES (2, 'Bob');"
received_101 = [q for (tid, q) in undo_queries if tid == 101]
received_102 = [q for (tid, q) in undo_queries if tid == 102]
self.assertEqual(len(received_101), 2)
self.assertEqual(len(received_102), 1)
self.assertIn(expected_101_update_undo, received_101)
self.assertIn(expected_101_insert_undo, received_101)
self.assertIn(expected_102_delete_undo, received_102)
@patch('FailureRecoveryManager.FailureRecoveryManager.parse_log_file')
def test_recoverSystem_checkpoint_redo_undo(self, mock_parse_log_file):
"""Test recovery system with checkpoint, redo, and undo operations."""
logs = [
ExecutionResult(
transaction_id=2,
timestamp=datetime.now() - timedelta(minutes=20),
type="START",
status="",
query=None,
previous_data=None,
new_data=None
),
ExecutionResult(
transaction_id=2,
timestamp=datetime.now() - timedelta(minutes=20),
type="DELETE",
status="",
query="DELETE FROM table1 where id=1;",
previous_data=Rows(data=[{"id": 1, "name": "Bob"}], rows_count=1),
new_data=None
),
ExecutionResult(
transaction_id=None,
timestamp=datetime.now() - timedelta(minutes=15),
type="CHECKPOINT",
status="",
query=None,
previous_data=None,
new_data=None
),
ExecutionResult(
transaction_id=1,
timestamp=datetime.now() - timedelta(minutes=10),
type="START",
status="",
query=None,
previous_data=None,
new_data=None
),
ExecutionResult(
transaction_id=1,
timestamp=datetime.now() - timedelta(minutes=9),
type="INSERT",
status="",
query="INSERT INTO table1 (id, name) VALUES (1, 'Alice');",
previous_data=None,
new_data=Rows(data=[{"id": 1, "name": "Alice"}], rows_count=1)
),
ExecutionResult(
transaction_id=2,
timestamp=datetime.now() - timedelta(minutes=8),
type="UPDATE",
status="",
query="UPDATE table2 SET age=30 WHERE id=2;",
previous_data=Rows(data=[{"id": 2, "age": 25}], rows_count=1),
new_data=Rows(data=[{"id": 2, "age": 30}], rows_count=1)
),
ExecutionResult(
transaction_id=1,
timestamp=datetime.now() - timedelta(minutes=7),
type="COMMIT",
status="",
query=None,
previous_data=None,
new_data=None
)
]
mock_parse_log_file.return_value = (logs, [2])
redo_query, undo_query = self.manager.recoverSystem()
self.assertEqual(len(redo_query), 2)
self.assertIn("INSERT INTO table1 (id, name) VALUES (1, 'Alice');", redo_query[0][1])
self.assertIn("UPDATE table2 SET age=30 WHERE id=2;", redo_query[1][1])
self.assertEqual(len(undo_query), 2)
self.assertIn("UPDATE table2 SET id=2, age=25 WHERE id=2 AND age=30;", undo_query[0][1])
self.assertIn("INSERT INTO table1 (id, name) VALUES (1, 'Bob');", undo_query[1][1])
if __name__ == "__main__":
unittest.main(testRunner=ColoredTextTestRunner())