Skip to content

Commit 6089230

Browse files
ngnpopefelixxm
authored andcommitted
Refs #34986 -- Fixed mocking in utils_tests.test_http.HttpDateProcessingTests.test_parsing_rfc850.
Mocking in the `datetime` module can be tricky. In CPython the datetime C module is used, but PyPy uses a pure Python implementation. This caused issues with the prior approach to mocking `datetime.datetime`. See https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking
1 parent 0fcd72b commit 6089230

File tree

2 files changed

+4
-6
lines changed

2 files changed

+4
-6
lines changed

django/utils/http.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import base64
2-
import datetime
32
import re
43
import unicodedata
54
from binascii import Error as BinasciiError
5+
from datetime import datetime, timezone
66
from email.utils import formatdate
77
from urllib.parse import quote, unquote
88
from urllib.parse import urlencode as original_urlencode
@@ -113,10 +113,9 @@ def parse_http_date(date):
113113
else:
114114
raise ValueError("%r is not in a valid HTTP date format" % date)
115115
try:
116-
tz = datetime.timezone.utc
117116
year = int(m["year"])
118117
if year < 100:
119-
current_year = datetime.datetime.now(tz=tz).year
118+
current_year = datetime.now(tz=timezone.utc).year
120119
current_century = current_year - (current_year % 100)
121120
if year - (current_year % 100) > 50:
122121
# year that appears to be more than 50 years in the future are
@@ -129,7 +128,7 @@ def parse_http_date(date):
129128
hour = int(m["hour"])
130129
min = int(m["min"])
131130
sec = int(m["sec"])
132-
result = datetime.datetime(year, month, day, hour, min, sec, tzinfo=tz)
131+
result = datetime(year, month, day, hour, min, sec, tzinfo=timezone.utc)
133132
return int(result.timestamp())
134133
except Exception as exc:
135134
raise ValueError("%r is not a valid date" % date) from exc

tests/utils_tests/test_http.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -334,10 +334,9 @@ def test_parsing_rfc1123(self):
334334
)
335335

336336
@unittest.skipIf(platform.architecture()[0] == "32bit", "The Year 2038 problem.")
337-
@mock.patch("django.utils.http.datetime.datetime")
337+
@mock.patch("django.utils.http.datetime")
338338
def test_parsing_rfc850(self, mocked_datetime):
339339
mocked_datetime.side_effect = datetime
340-
mocked_datetime.now = mock.Mock()
341340
now_1 = datetime(2019, 11, 6, 8, 49, 37, tzinfo=timezone.utc)
342341
now_2 = datetime(2020, 11, 6, 8, 49, 37, tzinfo=timezone.utc)
343342
now_3 = datetime(2048, 11, 6, 8, 49, 37, tzinfo=timezone.utc)

0 commit comments

Comments
 (0)