Skip to content
This repository was archived by the owner on Mar 31, 2026. It is now read-only.

Commit 2d08ad3

Browse files
committed
chore: replace utcnow() with now(timezone.utc) and fix test collection
- Replaces deprecated datetime.utcnow() with timezone-aware datetime.now(timezone.utc). - Renames MockCredentials and MockClass to avoid pytest/unittest collection warnings.
1 parent 13fca93 commit 2d08ad3

File tree

12 files changed

+68
-57
lines changed

12 files changed

+68
-57
lines changed

google/cloud/spanner_v1/pool.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@
3535

3636
from google.cloud.spanner_v1.metrics.metrics_capture import MetricsCapture
3737

38-
_NOW = datetime.datetime.utcnow # unit tests may replace
38+
def _NOW():
39+
return datetime.datetime.now(datetime.timezone.utc) # unit tests may replace
3940

4041

4142
class AbstractSessionPool(object):

google/cloud/spanner_v1/session.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
from functools import total_ordering
1818
import time
19-
from datetime import datetime
19+
from datetime import datetime, timezone
2020
from typing import MutableMapping, Optional
2121

2222
from google.api_core.exceptions import Aborted
@@ -80,7 +80,7 @@ def __init__(self, database, labels=None, database_role=None, is_multiplexed=Fal
8080
self._labels: MutableMapping[str, str] = labels
8181
self._database_role: Optional[str] = database_role
8282
self._is_multiplexed: bool = is_multiplexed
83-
self._last_use_time: datetime = datetime.utcnow()
83+
self._last_use_time: datetime = datetime.now(timezone.utc)
8484

8585
def __lt__(self, other):
8686
return self._session_id < other._session_id

tests/system/test_dbapi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1482,7 +1482,7 @@ def test_read_only_dml(self):
14821482
def test_staleness(self):
14831483
"""Check the DB API `staleness` option."""
14841484

1485-
before_insert = datetime.datetime.utcnow().replace(tzinfo=UTC)
1485+
before_insert = datetime.datetime.now(UTC)
14861486
time.sleep(0.25)
14871487

14881488
self._cursor.execute(

tests/system/test_session_api.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1749,7 +1749,7 @@ def test_snapshot_read_w_various_staleness(sessions_database):
17491749
committed = _set_up_table(sessions_database, row_count)
17501750
all_data_rows = list(_row_data(row_count))
17511751

1752-
before_reads = datetime.datetime.utcnow().replace(tzinfo=UTC)
1752+
before_reads = datetime.datetime.now(UTC)
17531753

17541754
# Test w/ read timestamp
17551755
with sessions_database.snapshot(read_timestamp=committed) as read_tx:
@@ -1761,7 +1761,7 @@ def test_snapshot_read_w_various_staleness(sessions_database):
17611761
rows = list(min_read_ts.read(sd.TABLE, sd.COLUMNS, sd.ALL))
17621762
sd._check_row_data(rows, all_data_rows)
17631763

1764-
staleness = datetime.datetime.utcnow().replace(tzinfo=UTC) - before_reads
1764+
staleness = datetime.datetime.now(UTC) - before_reads
17651765

17661766
# Test w/ max staleness
17671767
with sessions_database.snapshot(max_staleness=staleness) as max_staleness:

tests/unit/test__helpers.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -868,7 +868,7 @@ def test(self):
868868

869869

870870
class Test_retry(unittest.TestCase):
871-
class test_class:
871+
class MockClass:
872872
def test_fxn(self):
873873
return True
874874

@@ -877,7 +877,7 @@ def test_retry_on_error(self):
877877
from google.cloud.spanner_v1._helpers import _retry
878878
import functools
879879

880-
test_api = mock.create_autospec(self.test_class)
880+
test_api = mock.create_autospec(self.MockClass)
881881
test_api.test_fxn.side_effect = [
882882
InternalServerError("testing"),
883883
NotFound("testing"),
@@ -893,7 +893,7 @@ def test_retry_allowed_exceptions(self):
893893
from google.cloud.spanner_v1._helpers import _retry
894894
import functools
895895

896-
test_api = mock.create_autospec(self.test_class)
896+
test_api = mock.create_autospec(self.MockClass)
897897
test_api.test_fxn.side_effect = [
898898
NotFound("testing"),
899899
InternalServerError("testing"),
@@ -914,7 +914,7 @@ def test_retry_count(self):
914914
from google.cloud.spanner_v1._helpers import _retry
915915
import functools
916916

917-
test_api = mock.create_autospec(self.test_class)
917+
test_api = mock.create_autospec(self.MockClass)
918918
test_api.test_fxn.side_effect = [
919919
InternalServerError("testing"),
920920
InternalServerError("testing"),
@@ -930,7 +930,7 @@ def test_check_rst_stream_error(self):
930930
from google.cloud.spanner_v1._helpers import _retry, _check_rst_stream_error
931931
import functools
932932

933-
test_api = mock.create_autospec(self.test_class)
933+
test_api = mock.create_autospec(self.MockClass)
934934
test_api.test_fxn.side_effect = [
935935
InternalServerError("Received unexpected EOS on DATA frame from server"),
936936
InternalServerError("RST_STREAM"),
@@ -951,7 +951,7 @@ def test_retry_on_aborted_exception_with_success_after_first_aborted_retry(self)
951951
from google.cloud.spanner_v1._helpers import _retry_on_aborted_exception
952952
import functools
953953

954-
test_api = mock.create_autospec(self.test_class)
954+
test_api = mock.create_autospec(self.MockClass)
955955
test_api.test_fxn.side_effect = [
956956
Aborted("aborted exception", errors=("Aborted error")),
957957
"true",
@@ -970,7 +970,7 @@ def test_retry_on_aborted_exception_with_success_after_three_retries(self):
970970
from google.cloud.spanner_v1._helpers import _retry_on_aborted_exception
971971
import functools
972972

973-
test_api = mock.create_autospec(self.test_class)
973+
test_api = mock.create_autospec(self.MockClass)
974974
# Case where aborted exception is thrown after other generic exceptions
975975
aborted = Aborted("aborted exception", errors=["Aborted error"])
976976
test_api.test_fxn.side_effect = [
@@ -994,7 +994,7 @@ def test_retry_on_aborted_exception_raises_aborted_if_deadline_expires(self):
994994
from google.cloud.spanner_v1._helpers import _retry_on_aborted_exception
995995
import functools
996996

997-
test_api = mock.create_autospec(self.test_class)
997+
test_api = mock.create_autospec(self.MockClass)
998998
test_api.test_fxn.side_effect = [
999999
Aborted("aborted exception", errors=("Aborted error")),
10001000
"true",

tests/unit/test_backup.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def _make_timestamp():
3636
import datetime
3737
from google.cloud._helpers import UTC
3838

39-
return datetime.datetime.utcnow().replace(tzinfo=UTC)
39+
return datetime.datetime.now(UTC)
4040

4141

4242
class TestBackup(_BaseTest):
@@ -357,8 +357,7 @@ def test_create_success(self):
357357
api.create_backup.return_value = op_future
358358

359359
instance = _Instance(self.INSTANCE_NAME, client=client)
360-
version_timestamp = datetime.utcnow() - timedelta(minutes=5)
361-
version_timestamp = version_timestamp.replace(tzinfo=timezone.utc)
360+
version_timestamp = datetime.now(timezone.utc) - timedelta(minutes=5)
362361
expire_timestamp = self._make_timestamp()
363362
encryption_config = {"encryption_type": 3, "kms_key_name": "key_name"}
364363
backup = self._make_one(

tests/unit/test_batch.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ def test_commit_grpc_error(self, mock_region):
238238
return_value="global",
239239
)
240240
def test_commit_ok(self, mock_region):
241-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
241+
now = datetime.datetime.now(UTC)
242242
now_pb = _datetime_to_pb_timestamp(now)
243243
response = CommitResponse(commit_timestamp=now_pb)
244244
database = _Database()
@@ -321,7 +321,7 @@ def _test_commit_with_options(
321321
isolation_level=TransactionOptions.IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED,
322322
read_lock_mode=TransactionOptions.ReadWrite.ReadLockMode.READ_LOCK_MODE_UNSPECIFIED,
323323
):
324-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
324+
now = datetime.datetime.now(UTC)
325325
now_pb = _datetime_to_pb_timestamp(now)
326326
response = CommitResponse(commit_timestamp=now_pb)
327327
database = _Database()
@@ -513,7 +513,7 @@ def test_commit_w_isolation_level_and_read_lock_mode(self, mock_region):
513513
return_value="global",
514514
)
515515
def test_context_mgr_already_committed(self, mock_region):
516-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
516+
now = datetime.datetime.now(UTC)
517517
database = _Database()
518518
api = database.spanner_api = _FauxSpannerAPI()
519519
session = _Session(database)
@@ -531,7 +531,7 @@ def test_context_mgr_already_committed(self, mock_region):
531531
return_value="global",
532532
)
533533
def test_context_mgr_success(self, mock_region):
534-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
534+
now = datetime.datetime.now(UTC)
535535
now_pb = _datetime_to_pb_timestamp(now)
536536
response = CommitResponse(commit_timestamp=now_pb)
537537
database = _Database()
@@ -582,7 +582,7 @@ def test_context_mgr_success(self, mock_region):
582582
return_value="global",
583583
)
584584
def test_context_mgr_failure(self, mock_region):
585-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
585+
now = datetime.datetime.now(UTC)
586586
now_pb = _datetime_to_pb_timestamp(now)
587587
response = CommitResponse(commit_timestamp=now_pb)
588588
database = _Database()
@@ -671,7 +671,7 @@ def _test_batch_write_with_request_options(
671671
exclude_txn_from_change_streams=False,
672672
enable_end_to_end_tracing=False,
673673
):
674-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
674+
now = datetime.datetime.now(UTC)
675675
now_pb = _datetime_to_pb_timestamp(now)
676676
status_pb = Status(code=200)
677677
response = BatchWriteResponse(

tests/unit/test_database.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def _make_timestamp():
9191
import datetime
9292
from google.cloud._helpers import UTC
9393

94-
return datetime.datetime.utcnow().replace(tzinfo=UTC)
94+
return datetime.datetime.now(UTC)
9595

9696
@staticmethod
9797
def _make_duration(seconds=1, microseconds=0):
@@ -1580,7 +1580,7 @@ def test_snapshot_w_read_timestamp_and_multi_use(self):
15801580
from google.cloud.spanner_v1.database import SnapshotCheckout
15811581
from google.cloud.spanner_v1.snapshot import Snapshot
15821582

1583-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
1583+
now = datetime.datetime.now(UTC)
15841584
client = _Client()
15851585
instance = _Instance(self.INSTANCE_NAME, client=client)
15861586
pool = _Pool()
@@ -2155,7 +2155,7 @@ def test_context_mgr_success(self):
21552155
from google.cloud._helpers import _datetime_to_pb_timestamp
21562156
from google.cloud.spanner_v1.batch import Batch
21572157

2158-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
2158+
now = datetime.datetime.now(UTC)
21592159
now_pb = _datetime_to_pb_timestamp(now)
21602160
response = CommitResponse(commit_timestamp=now_pb)
21612161
database = _Database(self.DATABASE_NAME)
@@ -2206,7 +2206,7 @@ def test_context_mgr_w_commit_stats_success(self):
22062206
from google.cloud._helpers import _datetime_to_pb_timestamp
22072207
from google.cloud.spanner_v1.batch import Batch
22082208

2209-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
2209+
now = datetime.datetime.now(UTC)
22102210
now_pb = _datetime_to_pb_timestamp(now)
22112211
commit_stats = CommitResponse.CommitStats(mutation_count=4)
22122212
response = CommitResponse(commit_timestamp=now_pb, commit_stats=commit_stats)
@@ -2358,7 +2358,7 @@ def test_ctor_w_read_timestamp_and_multi_use(self):
23582358
from google.cloud._helpers import UTC
23592359
from google.cloud.spanner_v1.snapshot import Snapshot
23602360

2361-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
2361+
now = datetime.datetime.now(UTC)
23622362
database = _Database(self.DATABASE_NAME)
23632363
session = _Session(database)
23642364
pool = database._pool = _Pool()
@@ -3358,7 +3358,7 @@ def test_context_mgr_success(self):
33583358
from google.cloud.spanner_v1.batch import MutationGroups
33593359
from google.rpc.status_pb2 import Status
33603360

3361-
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
3361+
now = datetime.datetime.now(UTC)
33623362
now_pb = _datetime_to_pb_timestamp(now)
33633363
status_pb = Status(code=200)
33643364
response = BatchWriteResponse(

tests/unit/test_instance.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -680,7 +680,7 @@ def test_backup_factory_explicit(self):
680680
instance = self._make_one(self.INSTANCE_ID, client, self.CONFIG_NAME)
681681
BACKUP_ID = "backup-id"
682682
DATABASE_NAME = "database-name"
683-
timestamp = datetime.datetime.utcnow().replace(tzinfo=UTC)
683+
timestamp = datetime.datetime.now(UTC)
684684
encryption_config = CreateBackupEncryptionConfig(
685685
encryption_type=CreateBackupEncryptionConfig.EncryptionType.CUSTOMER_MANAGED_ENCRYPTION,
686686
kms_key_name="kms_key_name",

tests/unit/test_metrics.py

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2025 Google LLC
1+
# Copyright 2025 Google LLC
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
@@ -31,7 +31,7 @@
3131
# pytest.importorskip("opentelemetry.semconv.attributes.otel_attributes")
3232

3333

34-
class TestCredentials(Credentials):
34+
class MockCredentials(Credentials):
3535
@property
3636
def expired(self):
3737
return False
@@ -60,12 +60,23 @@ def patched_client(monkeypatch):
6060
if SpannerMetricsTracerFactory._metrics_tracer_factory is not None:
6161
SpannerMetricsTracerFactory._metrics_tracer_factory = None
6262

63-
client = Client(
64-
project="test",
65-
credentials=TestCredentials(),
66-
# client_options={"api_endpoint": "none"}
67-
)
68-
yield client
63+
# Reset the global flag to ensure metrics initialization runs
64+
from google.cloud.spanner_v1 import client as client_module
65+
66+
client_module._metrics_monitor_initialized = False
67+
68+
with patch(
69+
"google.cloud.spanner_v1.metrics.metrics_exporter.MetricServiceClient"
70+
), patch(
71+
"google.cloud.spanner_v1.metrics.metrics_exporter.CloudMonitoringMetricsExporter"
72+
), patch(
73+
"opentelemetry.sdk.metrics.export.PeriodicExportingMetricReader"
74+
):
75+
client = Client(
76+
project="test",
77+
credentials=MockCredentials(),
78+
)
79+
yield client
6980

7081
# Resetting
7182
metrics.set_meter_provider(metrics.NoOpMeterProvider())

0 commit comments

Comments
 (0)