|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import datetime |
| 16 | +import unittest.mock as mock |
| 17 | + |
| 18 | +import freezegun |
| 19 | +import google.cloud.bigquery |
| 20 | +import pytest |
| 21 | + |
| 22 | +import bigframes.session.time |
| 23 | + |
| 24 | +INITIAL_BQ_TIME = datetime.datetime( |
| 25 | + year=2020, |
| 26 | + month=4, |
| 27 | + day=24, |
| 28 | + hour=8, |
| 29 | + minute=55, |
| 30 | + second=29, |
| 31 | + tzinfo=datetime.timezone.utc, |
| 32 | +) |
| 33 | + |
| 34 | + |
| 35 | +@pytest.fixture() |
| 36 | +def bq_client(): |
| 37 | + bqclient = mock.create_autospec(google.cloud.bigquery.Client, instance=True) |
| 38 | + |
| 39 | + def query_and_wait_mock(query, *args, **kwargs): |
| 40 | + if query.startswith("SELECT CURRENT_TIMESTAMP()"): |
| 41 | + return iter([[INITIAL_BQ_TIME]]) |
| 42 | + else: |
| 43 | + return ValueError(f"mock cannot handle query : {query}") |
| 44 | + |
| 45 | + bqclient.query_and_wait = query_and_wait_mock |
| 46 | + return bqclient |
| 47 | + |
| 48 | + |
| 49 | +def test_bqsyncedclock_get_time(bq_client): |
| 50 | + # this initial local time is actually irrelevant, only the ticks matter |
| 51 | + initial_local_datetime = datetime.datetime( |
| 52 | + year=1, month=7, day=12, hour=15, minute=6, second=3 |
| 53 | + ) |
| 54 | + |
| 55 | + with freezegun.freeze_time(initial_local_datetime) as frozen_datetime: |
| 56 | + clock = bigframes.session.time.BigQuerySyncedClock(bq_client) |
| 57 | + |
| 58 | + t1 = clock.get_time() |
| 59 | + assert t1 == INITIAL_BQ_TIME |
| 60 | + |
| 61 | + frozen_datetime.tick(datetime.timedelta(seconds=3)) |
| 62 | + t2 = clock.get_time() |
| 63 | + assert t2 == INITIAL_BQ_TIME + datetime.timedelta(seconds=3) |
| 64 | + |
| 65 | + frozen_datetime.tick(datetime.timedelta(seconds=23529385)) |
| 66 | + t3 = clock.get_time() |
| 67 | + assert t3 == INITIAL_BQ_TIME + datetime.timedelta( |
| 68 | + seconds=3 |
| 69 | + ) + datetime.timedelta(seconds=23529385) |
0 commit comments