File size: 15,748 Bytes
eadbc29
 
 
 
 
 
 
 
 
6a28f91
 
 
 
eadbc29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
6a28f91
eadbc29
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
6a28f91
eadbc29
 
 
6a28f91
eadbc29
 
 
 
 
6a28f91
 
 
eadbc29
 
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
6a28f91
eadbc29
 
 
6a28f91
eadbc29
 
 
 
 
6a28f91
 
 
eadbc29
 
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
 
6a28f91
 
eadbc29
 
 
 
 
 
6a28f91
eadbc29
 
 
6a28f91
 
eadbc29
 
 
 
6a28f91
 
 
eadbc29
 
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
6a28f91
 
 
eadbc29
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
6a28f91
eadbc29
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
6a28f91
 
eadbc29
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
 
6a28f91
eadbc29
 
6a28f91
 
 
eadbc29
 
 
6a28f91
 
 
eadbc29
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a28f91
 
 
eadbc29
 
 
 
 
 
 
 
 
6a28f91
eadbc29
 
 
 
 
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
"""Unit tests for SchedulingAlgorithm.

Tests algorithm coordination, override handling, constraint enforcement, and policy integration.
"""

from datetime import date

import pytest

from src.control.overrides import Override, OverrideType
from src.core.algorithm import SchedulingAlgorithm
from src.simulation.allocator import CourtroomAllocator
from src.simulation.policies.readiness import ReadinessPolicy


@pytest.mark.unit
class TestAlgorithmBasics:
    """Test basic algorithm setup and execution."""

    def test_create_algorithm(self):
        """Test creating scheduling algorithm."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(num_courtrooms=5, per_courtroom_capacity=50)

        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        assert algorithm.policy is not None
        assert algorithm.allocator is not None

    def test_schedule_simple_day(self, small_case_set, courtrooms):
        """Test scheduling a simple day with 10 cases."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        result = algorithm.schedule_day(
            cases=small_case_set, courtrooms=courtrooms, current_date=date(2024, 2, 1)
        )

        assert result is not None
        assert hasattr(result, "scheduled_cases")
        assert len(result.scheduled_cases) > 0


@pytest.mark.unit
class TestOverrideHandling:
    """Test override processing and validation."""

    def test_valid_priority_override(self, small_case_set, courtrooms):
        """Test applying valid priority override."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        # Create priority override for first case
        override = Override(
            override_id="PRI-001",
            override_type=OverrideType.PRIORITY,
            case_id=small_case_set[0].case_id,
            judge_id="J001",
            timestamp=date(2024, 1, 31),
            new_priority=0.95,
        )

        result = algorithm.schedule_day(
            cases=small_case_set,
            courtrooms=courtrooms,
            current_date=date(2024, 2, 1),
            overrides=[override],
        )

        # Verify override was applied
        assert hasattr(result, "applied_overrides")
        assert len(result.applied_overrides) >= 0

    def test_invalid_override_rejection(self, small_case_set, courtrooms):
        """Test that invalid overrides are rejected."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        # Create override for non-existent case
        override = Override(
            override_id="INVALID-001",
            override_type=OverrideType.PRIORITY,
            case_id="NONEXISTENT-CASE",
            judge_id="J001",
            timestamp=date(2024, 1, 31),
            new_priority=0.95,
        )

        result = algorithm.schedule_day(
            cases=small_case_set,
            courtrooms=courtrooms,
            current_date=date(2024, 2, 1),
            overrides=[override],
        )

        # Verify rejection tracking
        assert hasattr(result, "override_rejections")
        # Invalid override should be rejected

    def test_mixed_valid_invalid_overrides(self, small_case_set, courtrooms):
        """Test handling mix of valid and invalid overrides."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        overrides = [
            Override(
                override_id="VALID-001",
                override_type=OverrideType.PRIORITY,
                case_id=small_case_set[0].case_id,
                judge_id="J001",
                timestamp=date(2024, 1, 31),
                new_priority=0.95,
            ),
            Override(
                override_id="INVALID-001",
                override_type=OverrideType.EXCLUDE,
                case_id="NONEXISTENT",
                judge_id="J001",
                timestamp=date(2024, 1, 31),
            ),
            Override(
                override_id="VALID-002",
                override_type=OverrideType.DATE,
                case_id=small_case_set[1].case_id,
                judge_id="J002",
                timestamp=date(2024, 1, 31),
                preferred_date=date(2024, 2, 5),
            ),
        ]

        result = algorithm.schedule_day(
            cases=small_case_set,
            courtrooms=courtrooms,
            current_date=date(2024, 2, 1),
            overrides=overrides,
        )

        # Valid overrides should be applied, invalid rejected
        assert hasattr(result, "applied_overrides")
        assert hasattr(result, "override_rejections")

    def test_override_list_not_mutated(self, small_case_set, courtrooms):
        """Test that original override list is not mutated."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        overrides = [
            Override(
                override_id="TEST-001",
                override_type=OverrideType.PRIORITY,
                case_id=small_case_set[0].case_id,
                judge_id="J001",
                timestamp=date(2024, 1, 31),
                new_priority=0.95,
            )
        ]

        original_count = len(overrides)

        algorithm.schedule_day(
            cases=small_case_set,
            courtrooms=courtrooms,
            current_date=date(2024, 2, 1),
            overrides=overrides,
        )

        # Original list should remain unchanged
        assert len(overrides) == original_count


@pytest.mark.unit
class TestConstraintEnforcement:
    """Test constraint enforcement (min gap, capacity, etc.)."""

    def test_min_gap_enforcement(self, sample_cases, courtrooms):
        """Test that minimum gap between hearings is enforced."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        # Record recent hearing for a case
        sample_cases[0].record_hearing(
            date(2024, 1, 28), was_heard=True, outcome="HEARD"
        )
        sample_cases[0].update_age(date(2024, 2, 1))

        algorithm.schedule_day(
            cases=sample_cases, courtrooms=courtrooms, current_date=date(2024, 2, 1)
        )

        # Case with recent hearing (4 days ago) should not be scheduled if min_gap=7
        # (Implementation dependent on min_gap setting)

    def test_capacity_limits(self, sample_cases, single_courtroom):
        """Test that courtroom capacity is not exceeded."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(num_courtrooms=1, per_courtroom_capacity=50)
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        result = algorithm.schedule_day(
            cases=sample_cases,
            courtrooms=[single_courtroom],
            current_date=date(2024, 2, 1),
        )

        # Should not schedule more than capacity
        assert len(result.scheduled_cases) <= 50

    def test_working_days_only(self, small_case_set, courtrooms):
        """Test scheduling only happens on working days."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        # Try scheduling on a weekend (if enforced)
        saturday = date(2024, 6, 15)  # Assume Saturday

        algorithm.schedule_day(
            cases=small_case_set, courtrooms=courtrooms, current_date=saturday
        )

        # Implementation may allow or prevent weekend scheduling


@pytest.mark.unit
class TestRipenessFiltering:
    """Test that unripe cases are filtered out."""

    def test_ripe_cases_scheduled(self, ripe_case, courtrooms):
        """Test that RIPE cases are scheduled."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        result = algorithm.schedule_day(
            cases=[ripe_case], courtrooms=courtrooms, current_date=date(2024, 3, 1)
        )

        # RIPE case should be scheduled
        assert len(result.scheduled_cases) > 0

    def test_unripe_cases_filtered(self, unripe_case, courtrooms):
        """Test that UNRIPE cases are not scheduled."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        algorithm.schedule_day(
            cases=[unripe_case], courtrooms=courtrooms, current_date=date(2024, 2, 1)
        )

        # UNRIPE case should not be scheduled
        # (or be in filtered list)


@pytest.mark.unit
class TestLoadBalancing:
    """Test load balancing across courtrooms."""

    def test_balanced_allocation(self, sample_cases, courtrooms):
        """Test that cases are distributed evenly across courtrooms."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        result = algorithm.schedule_day(
            cases=sample_cases, courtrooms=courtrooms, current_date=date(2024, 2, 1)
        )

        # Check Gini coefficient for balance
        if hasattr(result, "gini_coefficient"):
            # Low Gini = good balance
            assert result.gini_coefficient < 0.3

    def test_single_courtroom_allocation(self, small_case_set, single_courtroom):
        """Test allocation with single courtroom."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(num_courtrooms=1, per_courtroom_capacity=50)
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        result = algorithm.schedule_day(
            cases=small_case_set,
            courtrooms=[single_courtroom],
            current_date=date(2024, 2, 1),
        )

        # All scheduled cases should go to single courtroom
        assert len(result.scheduled_cases) <= 50


@pytest.mark.edge_case
class TestAlgorithmEdgeCases:
    """Test algorithm edge cases."""

    def test_empty_case_list(self, courtrooms):
        """Test scheduling with no cases."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        result = algorithm.schedule_day(
            cases=[], courtrooms=courtrooms, current_date=date(2024, 2, 1)
        )

        # Should handle gracefully
        assert len(result.scheduled_cases) == 0

    def test_all_cases_unripe(self, courtrooms):
        """Test when all cases are unripe."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        # Create unripe cases
        from src.core.case import Case

        unripe_cases = [
            Case(
                case_id=f"UNRIPE-{i}",
                case_type="RSA",
                filed_date=date(2024, 1, 1),
                current_stage="PRE-ADMISSION",
                hearing_count=0,
            )
            for i in range(10)
        ]

        for case in unripe_cases:
            case.service_status = "PENDING"

        result = algorithm.schedule_day(
            cases=unripe_cases, courtrooms=courtrooms, current_date=date(2024, 2, 1)
        )

        # Should schedule few or no cases
        assert len(result.scheduled_cases) < len(unripe_cases)

    def test_more_cases_than_capacity(self, courtrooms):
        """Test with more eligible cases than total capacity."""
        from src.data.case_generator import CaseGenerator

        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        # Generate 500 cases (capacity is 5*50=250)
        generator = CaseGenerator(
            start=date(2024, 1, 1), end=date(2024, 1, 31), seed=42
        )
        many_cases = generator.generate(500)

        result = algorithm.schedule_day(
            cases=many_cases, courtrooms=courtrooms, current_date=date(2024, 2, 1)
        )

        # Should not exceed total capacity
        total_capacity = sum(c.daily_capacity for c in courtrooms)
        assert len(result.scheduled_cases) <= total_capacity

    def test_single_case_scheduling(self, single_case, single_courtroom):
        """Test scheduling exactly one case."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(num_courtrooms=1, per_courtroom_capacity=50)
        algorithm = SchedulingAlgorithm(policy=policy, allocator=allocator)

        result = algorithm.schedule_day(
            cases=[single_case],
            courtrooms=[single_courtroom],
            current_date=date(2024, 2, 1),
        )

        # Should schedule the single case (if eligible)
        assert len(result.scheduled_cases) <= 1


@pytest.mark.failure
class TestAlgorithmFailureScenarios:
    """Test algorithm failure scenarios."""

    def test_null_policy(self, small_case_set, courtrooms):
        """Test algorithm with None policy."""
        with pytest.raises((ValueError, TypeError, AttributeError)):
            SchedulingAlgorithm(policy=None, allocator=CourtroomAllocator(5, 50))

    def test_null_allocator(self, small_case_set, courtrooms):
        """Test algorithm with None allocator."""
        with pytest.raises((ValueError, TypeError, AttributeError)):
            SchedulingAlgorithm(policy=ReadinessPolicy(), allocator=None)

    def test_invalid_override_type(self, small_case_set, courtrooms):
        """Test with invalid override type."""
        policy = ReadinessPolicy()
        allocator = CourtroomAllocator(
            num_courtrooms=len(courtrooms), per_courtroom_capacity=50
        )
        SchedulingAlgorithm(policy=policy, allocator=allocator)

        # Create override with invalid type
        try:
            Override(
                override_id="BAD-001",
                override_type="INVALID_TYPE",  # Not a valid OverrideType
                case_id=small_case_set[0].case_id,
                judge_id="J001",
                timestamp=date(2024, 1, 31),
            )
            # May fail at creation or during processing
        except (ValueError, TypeError):
            # Expected for strict validation
            pass