Skip to content

Commit 3f1cec5

Browse files
committed
Introduce Rfc3339.now_utc() and deprecate utcnow usage #760
1 parent 2a935cc commit 3f1cec5

File tree

8 files changed

+40
-32
lines changed

8 files changed

+40
-32
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1111

1212
### Changed
1313

14+
- Eliminate deprecated `utcnow` usage patterns. Introduce `Rfc3339.now_utc()` method (as replacement for deprecated `utcnow()` method) to simplify finding deprecated `utcnow` usage in user code. ([#760](https://github.com/Open-EO/openeo-python-client/issues/760))
15+
1416
### Removed
1517

1618
### Fixed

docs/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858

5959
# General information about the project.
6060
project = 'openEO Python Client'
61-
copyright = '2017 - {d}, Jeroen Dries'.format(d=datetime.datetime.utcnow().strftime("%Y"))
61+
copyright = '2017 - {d}, Jeroen Dries'.format(d=datetime.date.today().strftime("%Y"))
6262
author = 'Jeroen Dries'
6363

6464
# The version info for the project you're documenting, acts as replacement for

openeo/extra/job_management/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,7 @@ def _launch_job(self, start_job, df, i, backend_name, stats: Optional[dict] = No
595595
df.loc[i, "status"] = "start_failed"
596596
stats["start_job error"] += 1
597597
else:
598-
df.loc[i, "start_time"] = rfc3339.utcnow()
598+
df.loc[i, "start_time"] = rfc3339.now_utc()
599599
if job:
600600
df.loc[i, "id"] = job.job_id
601601
with ignore_connection_errors(context="get status"):
@@ -675,7 +675,7 @@ def _cancel_prolonged_job(self, job: BatchJob, row):
675675
job_running_start_time = rfc3339.parse_datetime(row.get("running_start_time"), with_timezone=True)
676676

677677
# Parse the current time into a datetime object with timezone info
678-
current_time = rfc3339.parse_datetime(rfc3339.utcnow(), with_timezone=True)
678+
current_time = rfc3339.parse_datetime(rfc3339.now_utc(), with_timezone=True)
679679

680680
# Calculate the elapsed time between job start and now
681681
elapsed = current_time - job_running_start_time
@@ -751,15 +751,15 @@ def _track_statuses(self, job_db: JobDatabaseInterface, stats: Optional[dict] =
751751

752752
if previous_status in {"created", "queued"} and new_status == "running":
753753
stats["job started running"] += 1
754-
active.loc[i, "running_start_time"] = rfc3339.utcnow()
754+
active.loc[i, "running_start_time"] = rfc3339.now_utc()
755755

756756
if self._cancel_running_job_after and new_status == "running":
757757
if (not active.loc[i, "running_start_time"] or pd.isna(active.loc[i, "running_start_time"])):
758758
_log.warning(
759759
f"Unknown 'running_start_time' for running job {job_id}. Using current time as an approximation."
760760
)
761761
stats["job started running"] += 1
762-
active.loc[i, "running_start_time"] = rfc3339.utcnow()
762+
active.loc[i, "running_start_time"] = rfc3339.now_utc()
763763

764764
self._cancel_prolonged_job(the_job, active.loc[i])
765765

openeo/rest/auth/config.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,6 @@ def assert_private_file(path: Path):
5959
raise PermissionError(message)
6060

6161

62-
def utcnow_rfc3339() -> str:
63-
"""Current datetime formatted as RFC-3339 string."""
64-
return rfc3339.datetime(datetime.utcnow())
65-
66-
6762
def _normalize_url(url: str) -> str:
6863
"""Normalize a url (trim trailing slash), to simplify equality checking."""
6964
return url.rstrip("/") or "/"
@@ -146,7 +141,7 @@ def _write(self, data: dict):
146141
if "metadata" not in data:
147142
data["metadata"] = {
148143
"type": "AuthConfig",
149-
"created": utcnow_rfc3339(),
144+
"created": rfc3339.now_utc(),
150145
"created_by": "openeo-python-client {v}".format(v=__version__),
151146
"version": 1,
152147
}
@@ -169,7 +164,7 @@ def set_basic_auth(self, backend: str, username: str, password: Union[str, None]
169164
"basic",
170165
)
171166
# TODO: support multiple basic auth credentials? (pick latest by default for example)
172-
deep_set(data, *keys, "date", value=utcnow_rfc3339())
167+
deep_set(data, *keys, "date", value=rfc3339.now_utc())
173168
deep_set(data, *keys, "username", value=username)
174169
if password:
175170
deep_set(data, *keys, "password", value=password)
@@ -203,7 +198,7 @@ def set_oidc_client_config(
203198
data = self.load()
204199
keys = ("backends", _normalize_url(backend), "oidc", "providers", provider_id)
205200
# TODO: support multiple clients? (pick latest by default for example)
206-
deep_set(data, *keys, "date", value=utcnow_rfc3339())
201+
deep_set(data, *keys, "date", value=rfc3339.now_utc())
207202
deep_set(data, *keys, "client_id", value=client_id)
208203
deep_set(data, *keys, "client_secret", value=client_secret)
209204
if issuer:
@@ -233,7 +228,7 @@ def set_refresh_token(self, issuer: str, client_id: str, refresh_token: str):
233228
_normalize_url(issuer),
234229
client_id,
235230
value={
236-
"date": utcnow_rfc3339(),
231+
"date": rfc3339.now_utc(),
237232
"refresh_token": refresh_token,
238233
},
239234
)

openeo/util.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
import shapely.geometry.base
2424
from deprecated import deprecated
2525

26+
from openeo.internal.warnings import legacy_alias
27+
2628
try:
2729
# pyproj is an optional dependency
2830
import pyproj
@@ -194,12 +196,15 @@ def today(self) -> str:
194196
"""Today (date) in RFC3339 format"""
195197
return self.date(dt.date.today())
196198

197-
def utcnow(self) -> str:
198-
"""Current UTC datetime in RFC3339 format."""
199+
def now_utc(self) -> str:
200+
"""Current datetime (in UTC timezone) in RFC3339 format."""
199201
# Current time in UTC timezone (instead of naive `datetime.datetime.utcnow()`, per `datetime` documentation)
200202
now = dt.datetime.now(tz=dt.timezone.utc)
201203
return self.datetime(now)
202204

205+
# Legacy alias
206+
utcnow = legacy_alias(now_utc, name="utcnow", since="0.41.0")
207+
203208

204209
# Default RFC3339 date-time formatter
205210
rfc3339 = Rfc3339()

tests/extra/job_management/test_job_management.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -573,9 +573,9 @@ def test_automatic_cancel_of_too_long_running_jobs(
573573
job_manager_root_dir,
574574
):
575575
def get_status(job_id, current_status):
576-
if rfc3339.utcnow() < start_time:
576+
if rfc3339.now_utc() < start_time:
577577
return "queued"
578-
elif rfc3339.utcnow() < end_time:
578+
elif rfc3339.now_utc() < end_time:
579579
return "running"
580580
return end_status
581581

@@ -685,9 +685,9 @@ def test_ensure_running_start_time_is_datetime(
685685
job_manager_root_dir,
686686
):
687687
def get_status(job_id, current_status):
688-
if rfc3339.utcnow() < start_time:
688+
if rfc3339.now_utc() < start_time:
689689
return "queued"
690-
elif rfc3339.utcnow() < end_time:
690+
elif rfc3339.now_utc() < end_time:
691691
return "running"
692692
return end_status
693693

tests/rest/auth/test_config.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -113,10 +113,10 @@ def test_start_empty(self, tmp_path):
113113
assert config.get_basic_auth("foo") == (None, None)
114114
assert config.get_oidc_client_configs("oeo.test", "default") == (None, None)
115115

116-
def test_basic_auth(self, tmp_path):
116+
def test_basic_auth(self, tmp_path, time_machine):
117+
time_machine.move_to("2020-06-08T11:18:27Z")
117118
config = AuthConfig(path=tmp_path)
118-
with mock.patch.object(openeo.rest.auth.config, "utcnow_rfc3339", return_value="2020-06-08T11:18:27Z"):
119-
config.set_basic_auth("oeo.test", "John", "j0hn123")
119+
config.set_basic_auth("oeo.test", "John", "j0hn123")
120120
assert config.path.exists()
121121
assert [p.name for p in tmp_path.iterdir()] == [AuthConfig.DEFAULT_FILENAME]
122122
with config.path.open("r") as f:
@@ -137,10 +137,10 @@ def test_basic_auth_url_normalization(self, tmp_path, to_set, to_get):
137137
assert config.get_basic_auth(to_set) == ("John", "j0hn123")
138138
assert config.get_basic_auth(to_get) == ("John", "j0hn123")
139139

140-
def test_oidc(self, tmp_path):
140+
def test_oidc(self, tmp_path, time_machine):
141+
time_machine.move_to("2020-06-08T11:18:27Z")
141142
config = AuthConfig(path=tmp_path)
142-
with mock.patch.object(openeo.rest.auth.config, "utcnow_rfc3339", return_value="2020-06-08T11:18:27Z"):
143-
config.set_oidc_client_config("oeo.test", "default", client_id="client123", client_secret="$6cr67")
143+
config.set_oidc_client_config("oeo.test", "default", client_id="client123", client_secret="$6cr67")
144144
assert config.path.exists()
145145
assert [p.name for p in tmp_path.iterdir()] == [AuthConfig.DEFAULT_FILENAME]
146146
with config.path.open("r") as f:
@@ -157,10 +157,10 @@ def test_oidc(self, tmp_path):
157157
("https://oeo.test", "https://oeo.test/"),
158158
("https://oeo.test/", "https://oeo.test"),
159159
])
160-
def test_oidc_backend_normalization(self, tmp_path, to_set, to_get):
160+
def test_oidc_backend_normalization(self, tmp_path, to_set, to_get, time_machine):
161+
time_machine.move_to("2020-06-08T11:18:27Z")
161162
config = AuthConfig(path=tmp_path)
162-
with mock.patch.object(openeo.rest.auth.config, "utcnow_rfc3339", return_value="2020-06-08T11:18:27Z"):
163-
config.set_oidc_client_config(to_set, "default", client_id="client123", client_secret="$6cr67")
163+
config.set_oidc_client_config(to_set, "default", client_id="client123", client_secret="$6cr67")
164164
for backend in [to_set, to_get]:
165165
assert config.get_oidc_client_configs(backend, "default") == ("client123", "$6cr67")
166166
assert config.get_oidc_provider_configs(backend) == {

tests/test_util.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import pytest
1313
import shapely.geometry
1414

15+
from openeo.internal.warnings import UserDeprecationWarning
1516
from openeo.util import (
1617
BBoxDict,
1718
ContextTimer,
@@ -284,11 +285,16 @@ def test_today(self, time_machine):
284285
time_machine.move_to("2023-02-10T12:34:56Z")
285286
assert rfc3339.today() == "2023-02-10"
286287

287-
def test_utcnow(self, time_machine):
288+
def test_now_utc(self, time_machine):
288289
time_machine.move_to("2023-02-10T12:34:56Z")
289-
assert rfc3339.utcnow() == "2023-02-10T12:34:56Z"
290+
assert rfc3339.now_utc() == "2023-02-10T12:34:56Z"
290291
time_machine.move_to("2023-02-10T12:34:56+03")
291-
assert rfc3339.utcnow() == "2023-02-10T09:34:56Z"
292+
assert rfc3339.now_utc() == "2023-02-10T09:34:56Z"
293+
294+
def test_legacy_utcnow(self, time_machine):
295+
time_machine.move_to("2023-02-10T12:34:56Z")
296+
with pytest.warns(UserDeprecationWarning, match=r"Call to deprecated method utcnow.*Use `\.now_utc` instead"):
297+
assert rfc3339.utcnow() == "2023-02-10T12:34:56Z"
292298

293299

294300
def test_dict_no_none_kwargs():

0 commit comments

Comments
 (0)