Skip to content

Commit c73d890

Browse files
Fix flaky EngineProcessor time filter tests (#8058)
This fix addresses the flaky tests in engine_processor_test.py as explained in #7851. The tests are fixed by mocking the `datetime.datetime` class with a subclass `_FrozenDateTime` to make `datetime.datetime.now()` return a constant. I reproduced the issue by adding `import time; time.sleep(1)` to both `test_get_schedule_time_filter_behavior` and `test_list_reservations_time_filter_behavior` and confirmed that the fix works for both cases (though I removed the sleeps for this pr). Fixes #7851 --------- Co-authored-by: Pavol Juhas <juhas@google.com>
1 parent f5300e0 commit c73d890

1 file changed

Lines changed: 14 additions & 0 deletions

File tree

cirq-google/cirq_google/engine/engine_processor_test.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from __future__ import annotations
1616

1717
import datetime
18+
import functools
1819
from unittest import mock
1920

2021
import duet
@@ -194,6 +195,17 @@ def _to_timestamp(json_string):
194195
)
195196

196197

198+
class _FrozenDateTime(datetime.datetime):
199+
"""Frozen datetime for testing time related behavior."""
200+
201+
_stock_datetime = datetime.datetime
202+
203+
@classmethod
204+
@functools.cache
205+
def now(cls, tz=None):
206+
return cls._stock_datetime.now(tz)
207+
208+
197209
class FakeEngineContext(EngineContext):
198210
"""Fake engine context for testing."""
199211

@@ -769,6 +781,7 @@ def test_get_schedule_filter_by_time_slot(list_time_slots):
769781
)
770782

771783

784+
@mock.patch('datetime.datetime', _FrozenDateTime)
772785
@mock.patch('cirq_google.engine.engine_client.EngineClient.list_time_slots_async')
773786
def test_get_schedule_time_filter_behavior(list_time_slots):
774787
list_time_slots.return_value = []
@@ -811,6 +824,7 @@ def test_get_schedule_time_filter_behavior(list_time_slots):
811824
list_time_slots.assert_called_with('proj', 'p0', f'start_time < {utc_ts}')
812825

813826

827+
@mock.patch('datetime.datetime', _FrozenDateTime)
814828
@mock.patch('cirq_google.engine.engine_client.EngineClient.list_reservations_async')
815829
def test_list_reservations_time_filter_behavior(list_reservations):
816830
list_reservations.return_value = []

0 commit comments

Comments
 (0)