Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit e464cb4

Browse filesBrowse files
Nicer error when packing a datetime without tzinfo (#466)
1 parent cfa05d3 commit e464cb4
Copy full SHA for e464cb4

File tree

Expand file treeCollapse file tree

3 files changed

+22
-0
lines changed
Filter options
Expand file treeCollapse file tree

3 files changed

+22
-0
lines changed

‎msgpack/_packer.pyx

Copy file name to clipboardExpand all lines: msgpack/_packer.pyx
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,8 @@ cdef class Packer(object):
285285
o = self._default(o)
286286
default_used = 1
287287
continue
288+
elif self.datetime and PyDateTime_CheckExact(o):
289+
PyErr_Format(ValueError, b"can not serialize '%.200s' object where tzinfo=None", Py_TYPE(o).tp_name)
288290
else:
289291
PyErr_Format(TypeError, b"can not serialize '%.200s' object", Py_TYPE(o).tp_name)
290292
return ret

‎msgpack/fallback.py

Copy file name to clipboardExpand all lines: msgpack/fallback.py
+4Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -874,6 +874,10 @@ def _pack(
874874
obj = self._default(obj)
875875
default_used = 1
876876
continue
877+
878+
if self._datetime and check(obj, _DateTime):
879+
raise ValueError("Cannot serialize %r where tzinfo=None" % (obj,))
880+
877881
raise TypeError("Cannot serialize %r" % (obj,))
878882

879883
def pack(self, obj):

‎test/test_timestamp.py

Copy file name to clipboardExpand all lines: test/test_timestamp.py
+16Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,3 +140,19 @@ def test_issue451():
140140

141141
unpacked = msgpack.unpackb(packed, timestamp=3)
142142
assert dt == unpacked
143+
144+
145+
@pytest.mark.skipif(sys.version_info[0] == 2, reason="datetime support is PY3+ only")
146+
def test_pack_datetime_without_tzinfo():
147+
dt = datetime.datetime(1970, 1, 1, 0, 0, 42, 14)
148+
with pytest.raises(ValueError, match="where tzinfo=None"):
149+
packed = msgpack.packb(dt, datetime=True)
150+
151+
dt = datetime.datetime(1970, 1, 1, 0, 0, 42, 14)
152+
packed = msgpack.packb(dt, datetime=True, default=lambda x: None)
153+
assert packed == msgpack.packb(None)
154+
155+
dt = datetime.datetime(1970, 1, 1, 0, 0, 42, 14, tzinfo=_utc)
156+
packed = msgpack.packb(dt, datetime=True)
157+
unpacked = msgpack.unpackb(packed, timestamp=3)
158+
assert unpacked == dt

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.