Skip to content

Commit 861ec38

Browse files
authored
test: fix flaky stats logging interval timing test (#1463)
Replace real time.sleep() calls with mocked time.time() to eliminate timing dependencies that caused intermittent CI failures. The test would occasionally fail when execution overhead pushed total elapsed time over the 1.0 second threshold, triggering unexpected stats logging. Mocking time.time() ensures deterministic behavior across all environments and reduces test execution time from ~1.16s to ~0.02s.
1 parent bab0026 commit 861ec38

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

tests/test_cache_lfu.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -553,21 +553,24 @@ def test_stats_logging_interval_timing(self):
553553

554554
with patch.object(
555555
logging.getLogger("nemoguardrails.llm.cache.lfu"), "info"
556-
) as mock_log:
557-
# Multiple operations within interval
556+
) as mock_log, patch("time.time") as mock_time:
557+
current_time = [0.0]
558+
559+
def time_side_effect():
560+
return current_time[0]
561+
562+
mock_time.side_effect = time_side_effect
563+
558564
for i in range(10):
559565
cache.put(f"key{i}", f"value{i}")
560566
cache.get(f"key{i}")
561-
time.sleep(0.05) # Total time < 1.0
567+
current_time[0] += 0.05
562568

563-
# Should not have logged yet
564569
self.assertEqual(mock_log.call_count, 0)
565570

566-
# Wait for interval to pass
567-
time.sleep(0.6)
568-
cache.get("key1") # Trigger check
571+
current_time[0] += 0.6
572+
cache.get("key1")
569573

570-
# Now should have logged once
571574
self.assertEqual(mock_log.call_count, 1)
572575

573576
def test_stats_logging_with_updates(self):

0 commit comments

Comments
 (0)