-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_suite.py
More file actions
2115 lines (1663 loc) · 75.7 KB
/
test_suite.py
File metadata and controls
2115 lines (1663 loc) · 75.7 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
"""
Comprehensive Test Suite for Dynamic Load Balancing Simulator
This module provides extensive unit tests, integration tests, and scenario
tests for all components of the load balancing simulation system.
Test Categories:
1. Unit Tests: Test individual classes and methods in isolation
2. Integration Tests: Test component interactions
3. Scenario Tests: Test realistic use cases with various configurations
4. Edge Case Tests: Test boundary conditions and error handling
5. Performance Tests: Basic performance benchmarks
Testing Framework: unittest (Python standard library)
Author: Student
Date: December 2024
"""
import unittest
import sys
import os
import time
import logging
import json
import random
import statistics
from unittest.mock import MagicMock, patch
from dataclasses import dataclass
from typing import List, Dict, Any
# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Import project modules
from config import (
ProcessState,
ProcessPriority,
LoadBalancingAlgorithm,
SimulationConfig,
GUIConfig,
DEFAULT_SIMULATION_CONFIG,
DEFAULT_GUI_CONFIG
)
from process import Process, ProcessGenerator
from processor import Processor, ProcessorManager, ProcessorStatistics
from load_balancer import (
LoadBalancer,
LoadBalancerFactory,
RoundRobinBalancer,
LeastLoadedBalancer,
ThresholdBasedBalancer,
MigrationRecord
)
from simulation import SimulationEngine, SimulationState, SimulationResult
from metrics import (
ProcessMetrics,
ProcessorMetrics,
SystemMetrics,
MetricsCalculator,
MetricsComparator
)
from utils import SimulationLogger, DataExporter
# Disable logging during tests unless debugging
logging.disable(logging.CRITICAL)
# =============================================================================
# TEST CONFIGURATION
# =============================================================================
class TestConfig(unittest.TestCase):
"""Test configuration module and data classes."""
def test_process_state_enum_values(self):
"""Test that all process states are defined."""
states = [ProcessState.NEW, ProcessState.READY, ProcessState.RUNNING,
ProcessState.WAITING, ProcessState.COMPLETED, ProcessState.MIGRATING]
self.assertEqual(len(states), 6)
def test_process_priority_enum_values(self):
"""Test priority ordering."""
self.assertLess(ProcessPriority.HIGH.value, ProcessPriority.MEDIUM.value)
self.assertLess(ProcessPriority.MEDIUM.value, ProcessPriority.LOW.value)
def test_load_balancing_algorithm_enum(self):
"""Test all load balancing algorithms are defined."""
self.assertEqual(LoadBalancingAlgorithm.ROUND_ROBIN.value, "Round Robin")
self.assertEqual(LoadBalancingAlgorithm.LEAST_LOADED.value, "Least Loaded First")
self.assertEqual(LoadBalancingAlgorithm.THRESHOLD_BASED.value, "Threshold Based")
self.assertEqual(LoadBalancingAlgorithm.Q_LEARNING.value, "AI (Q-Learning)")
def test_simulation_config_defaults(self):
"""Test default configuration values."""
config = SimulationConfig()
self.assertEqual(config.num_processors, 4)
self.assertGreaterEqual(config.num_processes, 1)
self.assertGreater(config.time_quantum, 0)
def test_simulation_config_validation(self):
"""Test configuration validation."""
config = SimulationConfig()
self.assertGreaterEqual(config.min_processors, 1)
self.assertLessEqual(config.max_processors, 16)
def test_gui_config_defaults(self):
"""Test GUI configuration defaults."""
config = GUIConfig()
self.assertIsNotNone(config.window_title)
self.assertGreater(config.window_width, 0)
self.assertGreater(config.window_height, 0)
# =============================================================================
# TEST PROCESS MODULE
# =============================================================================
class TestProcess(unittest.TestCase):
"""Test Process class and related functionality."""
def test_process_creation(self):
"""Test basic process creation."""
process = Process(pid=1, arrival_time=0, burst_time=10)
self.assertEqual(process.pid, 1)
self.assertEqual(process.arrival_time, 0)
self.assertEqual(process.burst_time, 10)
self.assertEqual(process.remaining_time, 10)
self.assertEqual(process.state, ProcessState.NEW)
def test_process_remaining_time_init(self):
"""Test remaining time initializes to burst time."""
process = Process(pid=1, burst_time=15)
self.assertEqual(process.remaining_time, process.burst_time)
def test_process_priority_levels(self):
"""Test different priority levels."""
high = Process(pid=1, priority=ProcessPriority.HIGH)
medium = Process(pid=2, priority=ProcessPriority.MEDIUM)
low = Process(pid=3, priority=ProcessPriority.LOW)
self.assertEqual(high.priority, ProcessPriority.HIGH)
self.assertEqual(medium.priority, ProcessPriority.MEDIUM)
self.assertEqual(low.priority, ProcessPriority.LOW)
def test_process_state_changes(self):
"""Test process state transitions."""
process = Process(pid=1)
# NEW -> READY
process.state = ProcessState.READY
self.assertEqual(process.state, ProcessState.READY)
# READY -> RUNNING
process.state = ProcessState.RUNNING
self.assertEqual(process.state, ProcessState.RUNNING)
# RUNNING -> COMPLETED
process.state = ProcessState.COMPLETED
self.assertEqual(process.state, ProcessState.COMPLETED)
def test_process_execution_history(self):
"""Test execution history tracking."""
process = Process(pid=1)
self.assertIsInstance(process.execution_history, list)
self.assertEqual(len(process.execution_history), 0)
def test_process_migration_count_init(self):
"""Test migration count initialization."""
process = Process(pid=1)
self.assertEqual(process.migration_count, 0)
def test_process_is_completed_property(self):
"""Test is_completed property if exists."""
process = Process(pid=1, burst_time=10)
process.remaining_time = 0
if hasattr(process, 'is_completed'):
self.assertTrue(process.is_completed)
def test_process_to_dict(self):
"""Test process serialization."""
process = Process(pid=1, arrival_time=5, burst_time=10)
if hasattr(process, 'to_dict'):
data = process.to_dict()
self.assertEqual(data['pid'], 1)
self.assertEqual(data['arrival_time'], 5)
class TestProcessGenerator(unittest.TestCase):
"""Test ProcessGenerator functionality."""
def test_generate_processes(self):
"""Test process generation."""
generator = ProcessGenerator()
processes = generator.generate_processes(10)
self.assertEqual(len(processes), 10)
for i, proc in enumerate(processes):
self.assertIsInstance(proc, Process)
self.assertGreater(proc.burst_time, 0)
def test_unique_pids(self):
"""Test that generated processes have unique PIDs."""
generator = ProcessGenerator()
processes = generator.generate_processes(20)
pids = [p.pid for p in processes]
self.assertEqual(len(pids), len(set(pids))) # All unique
def test_generate_with_reset(self):
"""Test process generation with reset."""
config = SimulationConfig()
gen1 = ProcessGenerator(config)
procs1 = gen1.generate_processes(5)
first_last_pid = procs1[-1].pid
# After generating more, PID should continue
procs2 = gen1.generate_processes(5)
# PIDs should continue incrementing
self.assertGreater(procs2[0].pid, first_last_pid)
def test_burst_time_bounds(self):
"""Test burst times are within configured bounds."""
config = SimulationConfig()
generator = ProcessGenerator(config)
processes = generator.generate_processes(50)
for proc in processes:
self.assertGreaterEqual(proc.burst_time, config.min_burst_time)
self.assertLessEqual(proc.burst_time, config.max_burst_time)
def test_arrival_time_generation(self):
"""Test arrival times are properly distributed."""
config = SimulationConfig()
generator = ProcessGenerator(config)
processes = generator.generate_processes(10)
for proc in processes:
self.assertGreaterEqual(proc.arrival_time, 0)
# =============================================================================
# TEST PROCESSOR MODULE
# =============================================================================
class TestProcessor(unittest.TestCase):
"""Test Processor class."""
def test_processor_creation(self):
"""Test processor initialization."""
processor = Processor(processor_id=0)
self.assertEqual(processor.processor_id, 0)
self.assertEqual(processor.get_queue_size(), 0)
def test_processor_add_process(self):
"""Test adding process to processor."""
processor = Processor(processor_id=0)
process = Process(pid=1, burst_time=10)
result = processor.add_process(process)
self.assertTrue(result)
self.assertGreaterEqual(processor.get_queue_size(), 1)
def test_processor_queue_size(self):
"""Test queue size tracking."""
processor = Processor(processor_id=0)
for i in range(5):
processor.add_process(Process(pid=i+1, burst_time=5))
self.assertGreaterEqual(processor.get_queue_size(), 1)
def test_processor_get_load(self):
"""Test load calculation."""
processor = Processor(processor_id=0)
# Empty processor should have low load
initial_load = processor.get_load()
self.assertGreaterEqual(initial_load, 0)
# Add processes
for i in range(3):
processor.add_process(Process(pid=i+1, burst_time=10))
# Load should increase
loaded = processor.get_load()
self.assertGreaterEqual(loaded, initial_load)
def test_processor_execute_step(self):
"""Test process execution."""
processor = Processor(processor_id=0)
process = Process(pid=1, burst_time=10)
processor.add_process(process)
# Execute should not raise
if hasattr(processor, 'execute_time_slice'):
processor.execute_time_slice(current_time=1)
elif hasattr(processor, 'execute_step'):
processor.execute_step(current_time=1)
def test_processor_is_idle(self):
"""Test idle state detection."""
processor = Processor(processor_id=0)
# Should be idle when empty
if hasattr(processor, 'is_idle'):
self.assertTrue(processor.is_idle())
if hasattr(processor, 'has_processes'):
self.assertFalse(processor.has_processes())
processor.add_process(Process(pid=1, burst_time=5))
if hasattr(processor, 'has_processes'):
self.assertTrue(processor.has_processes())
def test_processor_statistics(self):
"""Test statistics tracking."""
processor = Processor(processor_id=0)
if hasattr(processor, 'statistics'):
self.assertIsInstance(processor.statistics, ProcessorStatistics)
def test_processor_get_current_process(self):
"""Test getting current executing process."""
processor = Processor(processor_id=0)
process = Process(pid=1, burst_time=10)
processor.add_process(process)
# current_process may be None if not executing yet
self.assertTrue(hasattr(processor, 'current_process'))
class TestProcessorManager(unittest.TestCase):
"""Test ProcessorManager class."""
def test_manager_creation(self):
"""Test processor manager initialization."""
manager = ProcessorManager(num_processors=4)
self.assertEqual(len(manager.processors), 4)
def test_manager_get_processor(self):
"""Test getting specific processor."""
manager = ProcessorManager(num_processors=4)
proc0 = manager.get_processor(0)
self.assertIsNotNone(proc0)
self.assertEqual(proc0.processor_id, 0)
def test_manager_get_all_loads(self):
"""Test getting all processor loads."""
manager = ProcessorManager(num_processors=4)
if hasattr(manager, 'get_all_loads'):
loads = manager.get_all_loads()
self.assertEqual(len(loads), 4)
def test_manager_get_least_loaded(self):
"""Test finding least loaded processor."""
manager = ProcessorManager(num_processors=4)
# Add different loads
manager.processors[0].add_process(Process(pid=1, burst_time=20))
manager.processors[0].add_process(Process(pid=2, burst_time=20))
manager.processors[1].add_process(Process(pid=3, burst_time=5))
if hasattr(manager, 'get_least_loaded_processor'):
least = manager.get_least_loaded_processor()
self.assertIsNotNone(least)
def test_manager_total_processes(self):
"""Test counting total processes."""
manager = ProcessorManager(num_processors=4)
manager.processors[0].add_process(Process(pid=1, burst_time=5))
manager.processors[1].add_process(Process(pid=2, burst_time=5))
manager.processors[1].add_process(Process(pid=3, burst_time=5))
if hasattr(manager, 'get_total_processes'):
total = manager.get_total_processes()
self.assertEqual(total, 3)
# =============================================================================
# TEST LOAD BALANCER MODULE
# =============================================================================
class TestRoundRobinBalancer(unittest.TestCase):
"""Test Round Robin load balancing algorithm."""
def test_round_robin_creation(self):
"""Test Round Robin balancer creation."""
balancer = RoundRobinBalancer()
self.assertEqual(balancer.algorithm_type, LoadBalancingAlgorithm.ROUND_ROBIN)
def test_round_robin_cyclic_assignment(self):
"""Test cyclic assignment pattern."""
config = SimulationConfig(num_processors=4)
balancer = RoundRobinBalancer(config)
manager = ProcessorManager(num_processors=4)
assigned_processors = []
for i in range(8):
process = Process(pid=i, burst_time=5)
processor = balancer.assign_process(process, manager.processors)
if processor:
assigned_processors.append(processor.processor_id)
# Should cycle through processors
# Expect pattern like 0, 1, 2, 3, 0, 1, 2, 3
for i in range(min(4, len(assigned_processors))):
self.assertEqual(assigned_processors[i] % 4, i)
def test_round_robin_handles_empty_processors(self):
"""Test handling when processors list is empty."""
balancer = RoundRobinBalancer()
process = Process(pid=1, burst_time=5)
result = balancer.assign_process(process, [])
self.assertIsNone(result)
class TestLeastLoadedBalancer(unittest.TestCase):
"""Test Least Loaded First load balancing algorithm."""
def test_least_loaded_creation(self):
"""Test Least Loaded balancer creation."""
balancer = LeastLoadedBalancer()
self.assertEqual(balancer.algorithm_type, LoadBalancingAlgorithm.LEAST_LOADED)
def test_least_loaded_selects_minimum(self):
"""Test that it selects the least loaded processor."""
config = SimulationConfig(num_processors=4)
balancer = LeastLoadedBalancer(config)
manager = ProcessorManager(num_processors=4)
# Load processors differently
manager.processors[0].add_process(Process(pid=100, burst_time=50))
manager.processors[0].add_process(Process(pid=101, burst_time=50))
manager.processors[1].add_process(Process(pid=102, burst_time=30))
manager.processors[2].add_process(Process(pid=103, burst_time=10))
# Processor 3 is empty - should be selected
process = Process(pid=1, burst_time=5)
selected = balancer.assign_process(process, manager.processors)
# Should select processor 3 (least loaded)
self.assertIsNotNone(selected)
def test_least_loaded_load_balancing(self):
"""Test load balancing effectiveness."""
config = SimulationConfig(num_processors=4)
balancer = LeastLoadedBalancer(config)
manager = ProcessorManager(num_processors=4)
# Assign many processes
for i in range(20):
process = Process(pid=i, burst_time=random.randint(5, 15))
balancer.assign_process(process, manager.processors)
# Get loads
loads = [p.get_load() for p in manager.processors]
# Check load variance is reasonable (should be more balanced)
if any(loads):
load_variance = statistics.variance(loads) if len(loads) > 1 else 0
# Just verify it runs - variance check is informational
self.assertGreaterEqual(load_variance, 0)
class TestThresholdBasedBalancer(unittest.TestCase):
"""Test Threshold Based load balancing algorithm."""
def test_threshold_based_creation(self):
"""Test Threshold Based balancer creation."""
balancer = ThresholdBasedBalancer()
self.assertEqual(balancer.algorithm_type, LoadBalancingAlgorithm.THRESHOLD_BASED)
def test_threshold_based_migration_check(self):
"""Test migration decision based on threshold."""
config = SimulationConfig(num_processors=4, load_threshold=0.3)
balancer = ThresholdBasedBalancer(config)
manager = ProcessorManager(num_processors=4)
# Create imbalanced load
for _ in range(5):
manager.processors[0].add_process(
Process(pid=random.randint(100, 200), burst_time=20)
)
# Check for migrations
if hasattr(balancer, 'check_for_migration'):
migrations = balancer.check_for_migration(manager.processors, current_time=0)
# May or may not trigger migration depending on threshold
self.assertIsInstance(migrations, (list, type(None)))
class TestLoadBalancerFactory(unittest.TestCase):
"""Test LoadBalancerFactory."""
def test_factory_creates_round_robin(self):
"""Test factory creates Round Robin balancer."""
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.ROUND_ROBIN)
self.assertIsInstance(balancer, RoundRobinBalancer)
def test_factory_creates_least_loaded(self):
"""Test factory creates Least Loaded balancer."""
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.LEAST_LOADED)
self.assertIsInstance(balancer, LeastLoadedBalancer)
def test_factory_creates_threshold_based(self):
"""Test factory creates Threshold Based balancer."""
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.THRESHOLD_BASED)
self.assertIsInstance(balancer, ThresholdBasedBalancer)
def test_factory_creates_qlearning(self):
"""Test factory creates Q-Learning balancer."""
from ai_balancer import QLearningBalancer
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.Q_LEARNING, num_processors=4)
self.assertIsInstance(balancer, QLearningBalancer)
def test_factory_with_config(self):
"""Test factory passes configuration."""
config = SimulationConfig(num_processors=8)
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.ROUND_ROBIN, config)
self.assertEqual(balancer.config.num_processors, 8)
def test_factory_creates_fcfs(self):
"""Test factory creates FCFS balancer."""
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.FCFS)
self.assertEqual(balancer.name, "FCFS (First Come First Served)")
def test_factory_creates_sjf(self):
"""Test factory creates SJF balancer."""
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.SJF)
self.assertEqual(balancer.name, "SJF (Shortest Job First)")
def test_factory_creates_priority(self):
"""Test factory creates Priority balancer."""
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.PRIORITY)
self.assertIn("Priority", balancer.name)
def test_factory_creates_priority_preemptive(self):
"""Test factory creates Preemptive Priority balancer."""
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.PRIORITY_PREEMPTIVE)
self.assertIn("Preemptive", balancer.name)
def test_factory_creates_mlfq(self):
"""Test factory creates MLFQ balancer."""
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.MLFQ)
self.assertIn("MLFQ", balancer.name)
def test_factory_creates_edf(self):
"""Test factory creates EDF balancer."""
balancer = LoadBalancerFactory.create(LoadBalancingAlgorithm.EDF)
self.assertEqual(balancer.name, "EDF (Earliest Deadline First)")
def test_factory_all_algorithms_count(self):
"""Test that all 13 algorithms are available."""
all_algos = LoadBalancerFactory.get_all_algorithms()
self.assertEqual(len(all_algos), 13)
def test_factory_load_balancing_vs_scheduling(self):
"""Test separation of load balancing and scheduling algorithms."""
lb_algos = LoadBalancerFactory.get_load_balancing_algorithms()
sched_algos = LoadBalancerFactory.get_scheduling_algorithms()
self.assertEqual(len(lb_algos), 5) # RR, LL, Threshold, Q-Learn, DQN
self.assertEqual(len(sched_algos), 8) # FCFS, SJF, SRTF, Priority x2, MLQ, MLFQ, EDF
# =============================================================================
# TEST SCHEDULING ALGORITHMS
# =============================================================================
class TestSchedulingAlgorithms(unittest.TestCase):
"""Test advanced CPU scheduling algorithms."""
def setUp(self):
"""Set up test fixtures."""
from scheduling_algorithms import (
FCFSScheduler, SJFScheduler, SRTFScheduler,
PriorityScheduler, MultilevelQueueScheduler,
MLFQScheduler, EDFScheduler, ExtendedProcess
)
self.FCFSScheduler = FCFSScheduler
self.SJFScheduler = SJFScheduler
self.SRTFScheduler = SRTFScheduler
self.PriorityScheduler = PriorityScheduler
self.MultilevelQueueScheduler = MultilevelQueueScheduler
self.MLFQScheduler = MLFQScheduler
self.EDFScheduler = EDFScheduler
self.ExtendedProcess = ExtendedProcess
def _create_test_process(self, pid, burst_time, arrival_time=0, priority=ProcessPriority.MEDIUM):
"""Helper to create test process."""
return Process(pid=pid, burst_time=burst_time, arrival_time=arrival_time, priority=priority)
def test_fcfs_is_non_preemptive(self):
"""Test that FCFS is non-preemptive."""
scheduler = self.FCFSScheduler()
self.assertFalse(scheduler.is_preemptive)
def test_fcfs_fifo_order(self):
"""Test FCFS processes in arrival order."""
scheduler = self.FCFSScheduler()
p1 = self._create_test_process(1, burst_time=5, arrival_time=0)
p2 = self._create_test_process(2, burst_time=3, arrival_time=1)
p3 = self._create_test_process(3, burst_time=2, arrival_time=2)
scheduler.add_process(p1)
scheduler.add_process(p2)
scheduler.add_process(p3)
# First selected should be p1 (arrived first)
selected = scheduler.select_next_process()
self.assertEqual(selected.pid, 1)
def test_sjf_selects_shortest(self):
"""Test SJF selects shortest job."""
scheduler = self.SJFScheduler()
p1 = self._create_test_process(1, burst_time=10)
p2 = self._create_test_process(2, burst_time=3) # Shortest
p3 = self._create_test_process(3, burst_time=7)
scheduler.add_process(p1)
scheduler.add_process(p2)
scheduler.add_process(p3)
selected = scheduler.select_next_process()
self.assertEqual(selected.pid, 2) # Shortest job
def test_sjf_is_non_preemptive(self):
"""Test that SJF is non-preemptive."""
scheduler = self.SJFScheduler()
self.assertFalse(scheduler.is_preemptive)
def test_srtf_is_preemptive(self):
"""Test that SRTF is preemptive."""
scheduler = self.SRTFScheduler()
self.assertTrue(scheduler.is_preemptive)
def test_srtf_selects_shortest_remaining(self):
"""Test SRTF selects process with shortest remaining time."""
scheduler = self.SRTFScheduler()
p1 = self._create_test_process(1, burst_time=10)
p2 = self._create_test_process(2, burst_time=2) # Shortest remaining
p3 = self._create_test_process(3, burst_time=5)
scheduler.add_process(p1)
scheduler.add_process(p2)
scheduler.add_process(p3)
selected = scheduler.select_next_process()
self.assertEqual(selected.pid, 2)
def test_priority_scheduler_modes(self):
"""Test priority scheduler preemptive/non-preemptive modes."""
non_preemptive = self.PriorityScheduler(preemptive=False)
preemptive = self.PriorityScheduler(preemptive=True)
self.assertFalse(non_preemptive.is_preemptive)
self.assertTrue(preemptive.is_preemptive)
def test_priority_selects_highest(self):
"""Test priority scheduler selects highest priority (lowest number)."""
scheduler = self.PriorityScheduler()
p1 = self._create_test_process(1, burst_time=5, priority=ProcessPriority.LOW)
p2 = self._create_test_process(2, burst_time=5, priority=ProcessPriority.HIGH)
p3 = self._create_test_process(3, burst_time=5, priority=ProcessPriority.MEDIUM)
scheduler.add_process(p1)
scheduler.add_process(p2)
scheduler.add_process(p3)
selected = scheduler.select_next_process()
self.assertEqual(selected.pid, 2) # HIGH priority
def test_multilevel_queue_structure(self):
"""Test multilevel queue has separate queues."""
from scheduling_algorithms import QueueLevel
scheduler = self.MultilevelQueueScheduler()
# Should have queues for each level
self.assertEqual(len(scheduler.queues), 4) # SYSTEM, INTERACTIVE, BATCH, IDLE
for level in QueueLevel:
self.assertIn(level, scheduler.queues)
def test_mlfq_starts_at_top(self):
"""Test MLFQ adds new processes to top queue."""
scheduler = self.MLFQScheduler(num_queues=4)
p = self._create_test_process(1, burst_time=10)
scheduler.add_process(p)
# New process should be in top queue (index 0)
self.assertEqual(len(scheduler.queues[0]), 1)
def test_mlfq_parameters(self):
"""Test MLFQ configurable parameters."""
scheduler = self.MLFQScheduler(num_queues=3, base_quantum=4, boost_interval=100)
self.assertEqual(scheduler.num_queues, 3)
self.assertEqual(scheduler.base_quantum, 4)
self.assertEqual(scheduler.boost_interval, 100)
# Quantums should double per level: 4, 8, 16
self.assertEqual(scheduler.quantums, [4, 8, 16])
def test_edf_is_preemptive(self):
"""Test EDF is preemptive."""
scheduler = self.EDFScheduler()
self.assertTrue(scheduler.is_preemptive)
def test_edf_selects_earliest_deadline(self):
"""Test EDF selects process with earliest deadline."""
scheduler = self.EDFScheduler()
p1 = self._create_test_process(1, burst_time=5)
p2 = self._create_test_process(2, burst_time=5)
p3 = self._create_test_process(3, burst_time=5)
scheduler.add_process(p1, deadline=30)
scheduler.add_process(p2, deadline=10) # Earliest
scheduler.add_process(p3, deadline=20)
selected = scheduler.select_next_process()
self.assertEqual(selected.pid, 2) # Earliest deadline
def test_scheduler_statistics(self):
"""Test scheduler tracks statistics."""
scheduler = self.FCFSScheduler()
p = self._create_test_process(1, burst_time=5)
scheduler.add_process(p)
stats = scheduler.get_statistics()
self.assertIn('total_processes', stats)
self.assertIn('completed_processes', stats)
self.assertIn('context_switches', stats)
self.assertEqual(stats['total_processes'], 1)
def test_scheduler_reset(self):
"""Test scheduler can be reset."""
scheduler = self.SJFScheduler()
p = self._create_test_process(1, burst_time=5)
scheduler.add_process(p)
scheduler.reset()
self.assertEqual(len(scheduler.ready_queue), 0)
self.assertIsNone(scheduler.running_process)
class TestSchedulerFactory(unittest.TestCase):
"""Test SchedulerFactory."""
def test_create_all_schedulers(self):
"""Test factory can create all scheduler types."""
from scheduling_algorithms import SchedulerFactory, SchedulingAlgorithm
schedulers = [
SchedulingAlgorithm.FCFS,
SchedulingAlgorithm.SJF,
SchedulingAlgorithm.SRTF,
SchedulingAlgorithm.PRIORITY,
SchedulingAlgorithm.PRIORITY_PREEMPTIVE,
SchedulingAlgorithm.MULTILEVEL_QUEUE,
SchedulingAlgorithm.MLFQ,
SchedulingAlgorithm.EDF,
]
for algo in schedulers:
scheduler = SchedulerFactory.create_scheduler(algo)
self.assertIsNotNone(scheduler)
def test_algorithm_info(self):
"""Test algorithm info is comprehensive."""
from scheduling_algorithms import SchedulerFactory
info = SchedulerFactory.get_algorithm_info()
self.assertGreater(len(info), 0)
for name, details in info.items():
self.assertIn('preemptive', details)
self.assertIn('pros', details)
self.assertIn('cons', details)
# =============================================================================
# TEST SIMULATION ENGINE
# =============================================================================
class TestSimulationEngine(unittest.TestCase):
"""Test SimulationEngine class."""
def setUp(self):
"""Set up test fixtures."""
self.config = SimulationConfig(num_processors=4, num_processes=10)
self.engine = SimulationEngine(self.config)
def test_engine_creation(self):
"""Test engine initialization."""
self.assertIsNotNone(self.engine)
self.assertEqual(self.engine.state, SimulationState.IDLE)
def test_engine_initialize(self):
"""Test engine initialization."""
result = self.engine.initialize()
self.assertTrue(result)
self.assertIsNotNone(self.engine.processor_manager)
self.assertIsNotNone(self.engine.load_balancer)
def test_engine_start_stop(self):
"""Test start and stop functionality."""
self.engine.initialize()
# Run a few steps
self.engine.step()
self.engine.step()
self.engine.stop()
self.assertIn(self.engine.state,
[SimulationState.STOPPED, SimulationState.COMPLETED])
def test_engine_step(self):
"""Test single simulation step."""
self.engine.initialize()
initial_time = self.engine.current_time
self.engine.step()
# Time should advance
self.assertGreater(self.engine.current_time, initial_time)
def test_engine_reset(self):
"""Test engine reset via reinitialize."""
self.engine.initialize()
self.engine.step()
self.engine.step()
# Re-initialize resets the engine
self.engine.initialize()
self.assertEqual(self.engine.state, SimulationState.IDLE)
self.assertEqual(self.engine.current_time, 0)
def test_engine_run_to_completion(self):
"""Test running simulation to completion."""
config = SimulationConfig(num_processors=4, num_processes=5)
engine = SimulationEngine(config)
engine.initialize()
result = engine.run()
self.assertIsInstance(result, SimulationResult)
self.assertIn(engine.state,
[SimulationState.COMPLETED, SimulationState.STOPPED])
def test_engine_change_algorithm(self):
"""Test changing load balancing algorithm."""
# Test Least Loaded
self.engine.initialize(algorithm=LoadBalancingAlgorithm.LEAST_LOADED)
self.assertEqual(
self.engine.load_balancer.algorithm_type,
LoadBalancingAlgorithm.LEAST_LOADED
)
# Create new engine for different algorithm test
engine2 = SimulationEngine(self.config)
engine2.initialize(algorithm=LoadBalancingAlgorithm.THRESHOLD_BASED)
self.assertEqual(
engine2.load_balancer.algorithm_type,
LoadBalancingAlgorithm.THRESHOLD_BASED
)
def test_engine_get_current_state(self):
"""Test getting simulation state snapshot."""
self.engine.initialize()
if hasattr(self.engine, 'get_current_state'):
state = self.engine.get_current_state()
self.assertIsNotNone(state)
class TestSimulationResult(unittest.TestCase):
"""Test SimulationResult data class."""
def test_result_creation(self):
"""Test result object creation."""
config = SimulationConfig(num_processors=4, num_processes=5)
engine = SimulationEngine(config)
engine.initialize()
result = engine.run()
self.assertIsInstance(result, SimulationResult)
self.assertIsNotNone(result.config)
def test_result_has_metrics(self):
"""Test result contains metrics."""
config = SimulationConfig(num_processors=4, num_processes=5)
engine = SimulationEngine(config)
engine.initialize()
result = engine.run()
# Should have some form of metrics
if hasattr(result, 'system_metrics'):
self.assertIsNotNone(result.system_metrics)
# =============================================================================
# TEST METRICS MODULE
# =============================================================================
class TestProcessMetrics(unittest.TestCase):
"""Test ProcessMetrics class."""
def test_turnaround_time_calculation(self):
"""Test turnaround time calculation."""
metrics = ProcessMetrics(
pid=1,
arrival_time=0,
burst_time=10,
start_time=2,
completion_time=15,
waiting_time=2,
processor_id=0,
migration_count=0,
priority="MEDIUM"
)
# Turnaround = Completion - Arrival = 15 - 0 = 15
self.assertEqual(metrics.turnaround_time, 15)
def test_response_time_calculation(self):
"""Test response time calculation."""
metrics = ProcessMetrics(
pid=1,
arrival_time=5,
burst_time=10,
start_time=8,
completion_time=18,
waiting_time=3,
processor_id=0,
migration_count=0,
priority="MEDIUM"
)
# Response = Start - Arrival = 8 - 5 = 3
self.assertEqual(metrics.response_time, 3)
def test_normalized_turnaround(self):
"""Test normalized turnaround calculation."""
metrics = ProcessMetrics(
pid=1,
arrival_time=0,
burst_time=10,
start_time=0,
completion_time=20,
waiting_time=0,
processor_id=0,
migration_count=0,
priority="MEDIUM"
)
# Normalized = Turnaround / Burst = 20 / 10 = 2.0
self.assertEqual(metrics.normalized_turnaround, 2.0)
def test_metrics_to_dict(self):
"""Test metrics serialization."""
metrics = ProcessMetrics(
pid=1,
arrival_time=0,
burst_time=10,
start_time=0,
completion_time=10,
waiting_time=0,
processor_id=0,
migration_count=0,
priority="MEDIUM"
)
data = metrics.to_dict()
self.assertEqual(data['pid'], 1)
self.assertEqual(data['burst_time'], 10)
class TestSystemMetrics(unittest.TestCase):
"""Test SystemMetrics calculations."""
def test_system_metrics_structure(self):
"""Test system metrics data structure."""
# SystemMetrics uses default values, create instance
metrics = SystemMetrics()
metrics.total_processes = 10
metrics.completed_processes = 10
metrics.avg_turnaround_time = 25.0
metrics.avg_waiting_time = 15.0
metrics.avg_response_time = 5.0
metrics.avg_utilization = 0.85
metrics.total_throughput = 0.4
metrics.load_variance = 0.02