Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix utcnow() deprecation warning #69

Merged
merged 5 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/other_plugins.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ used in a particular test: ``@pytest.mark.now('2016-12-01T12:00:00')`` or
``@pytest.mark.now(enabled=True)``.

If time is not specified in ``@pytest.mark.now``, then
``datetime.datetime.utcnow()`` value at the start of test is used as time value
current time at UTC timezone is used at the start of test as time value
until it is modified by calling ``mocked_time.set(...)`` or
``mocked_time.sleep(...)``

Expand Down
2 changes: 1 addition & 1 deletion tests/plugins/test_mocked_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def test_disabled_mocked_time_raises_on_usage_attempt(mocked_time):
assert not mocked_time.is_enabled

with pytest.raises(mocked_time_module.DisabledUsageError):
mocked_time.set(datetime.datetime.utcnow())
mocked_time.set(datetime.datetime.now(datetime.timezone.utc))

with pytest.raises(mocked_time_module.DisabledUsageError):
mocked_time.sleep(2)
4 changes: 2 additions & 2 deletions testsuite/mockserver/server.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import contextlib
import datetime
import itertools
import logging
import pathlib
Expand All @@ -19,6 +18,7 @@
from testsuite.utils import http
from testsuite.utils import net as net_utils
from testsuite.utils import url_util
from testsuite import utils

from . import classes
from . import exceptions
Expand Down Expand Up @@ -281,7 +281,7 @@ def _log_request(self, started, request, response=None, exc=None):
return
fields = {
'_type': 'mockserver_request',
'timestamp': datetime.datetime.utcnow(),
'timestamp': utils.utcnow(),
'method': request.method,
'url': request.rel_url,
}
Expand Down
8 changes: 4 additions & 4 deletions testsuite/plugins/mocked_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ def now(self) -> datetime.datetime:
""":returns: current value of mock time"""
if self._is_enabled:
return self._now
return datetime.datetime.utcnow()
return utils.utcnow()

def set(self, time: datetime.datetime):
"""Set mock time value"""
if not self._is_enabled:
raise DisabledUsageError(MOCK_TIME_DISABLED_MESSAGE)
self._now = time
self._now = utils.to_utc(time)

@property
def is_enabled(self) -> bool:
Expand Down Expand Up @@ -87,10 +87,10 @@ def mocked_time(_mocked_time_enabled, now) -> MockedTime:
def now(request) -> datetime.datetime:
marker = request.node.get_closest_marker('now')
if not marker or not marker.args:
return datetime.datetime.utcnow()
return utils.utcnow()
stamp = marker.args[0]
if isinstance(stamp, int):
return datetime.datetime.utcfromtimestamp(stamp)
return utils.utcfromtimestamp(stamp)
return utils.to_utc(dateutil.parser.parse(stamp))


Expand Down
19 changes: 14 additions & 5 deletions testsuite/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
# flake8: noqa
import pytz
import datetime

from .cached_property import cached_property


def to_utc(stamp):
def to_utc(stamp: datetime.datetime) -> datetime.datetime:
if stamp.tzinfo is not None:
stamp = stamp.astimezone(pytz.utc).replace(tzinfo=None)
stamp = stamp.astimezone(datetime.timezone.utc).replace(tzinfo=None)
return stamp


def timestring(stamp):
def timestring(stamp: datetime.datetime) -> str:
stamp = to_utc(stamp)
return stamp.strftime('%Y-%m-%dT%H:%M:%S.%f+0000')


def utcnow() -> datetime.datetime:
return datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)


def utcfromtimestamp(stamp: int) -> datetime.datetime:
return datetime.datetime.fromtimestamp(
stamp, tz=datetime.timezone.utc
).replace(tzinfo=None)
1 change: 1 addition & 0 deletions testsuite/utils/compat.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import contextlib


# Required for python3.6 compatibility
if not hasattr(contextlib, 'asynccontextmanager'):
import contextlib2 # pylint: disable=import-error
Expand Down
5 changes: 3 additions & 2 deletions testsuite/utils/json_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from bson import json_util

from testsuite.utils import object_hook as object_hook_util
from testsuite import utils


def loads(string, *args, **kwargs):
Expand All @@ -22,7 +23,7 @@ def substitute(json_obj, *, object_hook=None):
"""Create transformed json by making substitutions:

{"$mockserver": "/path", "$schema": true} -> "http://localhost:9999/path"
{"$dateDiff": 10} -> datetime.utcnow() + timedelta(seconds=10)
{"$dateDiff": 10} -> datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None) + timedelta(seconds=10)
"""
hook = object_hook_util.build_object_hook(object_hook=object_hook)
return object_hook_util.substitute(json_obj, hook)
Expand Down Expand Up @@ -58,6 +59,6 @@ def default(obj):
def relative_dates_default(obj):
"""Add ``$dateDiff`` hook to ``bson.json_util.default``."""
if isinstance(obj, datetime.datetime):
diff = obj.replace(tzinfo=None) - datetime.datetime.utcnow()
diff = obj.replace(tzinfo=None) - utils.utcnow()
return {'$dateDiff': diff.total_seconds()}
return default(obj)
Loading