Skip to content

Commit

Permalink
Merge pull request cherrypy#1992 from chiatchiat/utc-time-in-LazyRfc3…
Browse files Browse the repository at this point in the history
…339UtcTime

This patch fixes `LazyRfc3339UtcTime` to return correct time using
the UTC timezone. Previously, it mistakenly used the local timezone
value for the RFC 3339 representation.
  • Loading branch information
webknjaz committed Apr 1, 2023
2 parents 1f2366f + f119a4a commit 4febc2c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
6 changes: 3 additions & 3 deletions cherrypy/_cplogging.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,6 @@ def emit(self, record):

class LazyRfc3339UtcTime(object):
def __str__(self):
"""Return now() in RFC3339 UTC Format."""
now = datetime.datetime.now()
return now.isoformat('T') + 'Z'
"""Return utcnow() in RFC3339 UTC Format."""
iso_formatted_now = datetime.datetime.utcnow().isoformat('T')
return f'{iso_formatted_now!s}Z'
28 changes: 28 additions & 0 deletions cherrypy/test/test_logging.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Basic tests for the CherryPy core: request handling."""

import datetime
import logging

from cheroot.test import webtest
Expand Down Expand Up @@ -197,6 +198,33 @@ def test_custom_log_format(log_tracker, monkeypatch, server):
)


def test_utc_in_timez(monkeypatch):
"""Test that ``LazyRfc3339UtcTime`` is rendered as ``str`` using UTC timestamp."""
utcoffset8_local_time_in_naive_utc = (
datetime.datetime(
year=2020,
month=1,
day=1,
hour=1,
minute=23,
second=45,
tzinfo=datetime.timezone(datetime.timedelta(hours=8)),
)
.astimezone(datetime.timezone.utc)
.replace(tzinfo=None)
)

class mock_datetime:
@classmethod
def utcnow(cls):
return utcoffset8_local_time_in_naive_utc

monkeypatch.setattr('datetime.datetime', mock_datetime)
rfc3339_utc_time = str(cherrypy._cplogging.LazyRfc3339UtcTime())
expected_time = '2019-12-31T17:23:45Z'
assert rfc3339_utc_time == expected_time


def test_timez_log_format(log_tracker, monkeypatch, server):
"""Test a customized access_log_format string, which is a
feature of _cplogging.LogManager.access()."""
Expand Down

0 comments on commit 4febc2c

Please sign in to comment.