diff options
author | Benjamin Egelund-Müller <b@egelund-muller.com> | 2021-11-16 09:49:47 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-11-16 17:49:47 +0900 |
commit | e464cb44fa3af5ad3ecd83f9c045b16981d01bb2 (patch) | |
tree | 060cdcdc6d87d0e3763daa52cf40c4d4675a3fb3 | |
parent | cfa05d3fdc6290b4847e4781a06ac0668ea9dc18 (diff) | |
download | msgpack-python-e464cb44fa3af5ad3ecd83f9c045b16981d01bb2.tar.gz |
Nicer error when packing a datetime without tzinfo (#466)
-rw-r--r-- | msgpack/_packer.pyx | 2 | ||||
-rw-r--r-- | msgpack/fallback.py | 4 | ||||
-rw-r--r-- | test/test_timestamp.py | 16 |
3 files changed, 22 insertions, 0 deletions
diff --git a/msgpack/_packer.pyx b/msgpack/_packer.pyx index e6cd2c7..396da0c 100644 --- a/msgpack/_packer.pyx +++ b/msgpack/_packer.pyx @@ -285,6 +285,8 @@ cdef class Packer(object): o = self._default(o) default_used = 1 continue + elif self.datetime and PyDateTime_CheckExact(o): + PyErr_Format(ValueError, b"can not serialize '%.200s' object where tzinfo=None", Py_TYPE(o).tp_name) else: PyErr_Format(TypeError, b"can not serialize '%.200s' object", Py_TYPE(o).tp_name) return ret diff --git a/msgpack/fallback.py b/msgpack/fallback.py index 4540875..b27acb2 100644 --- a/msgpack/fallback.py +++ b/msgpack/fallback.py @@ -874,6 +874,10 @@ class Packer(object): obj = self._default(obj) default_used = 1 continue + + if self._datetime and check(obj, _DateTime): + raise ValueError("Cannot serialize %r where tzinfo=None" % (obj,)) + raise TypeError("Cannot serialize %r" % (obj,)) def pack(self, obj): diff --git a/test/test_timestamp.py b/test/test_timestamp.py index 6a29be7..4e26489 100644 --- a/test/test_timestamp.py +++ b/test/test_timestamp.py @@ -140,3 +140,19 @@ def test_issue451(): unpacked = msgpack.unpackb(packed, timestamp=3) assert dt == unpacked + + +@pytest.mark.skipif(sys.version_info[0] == 2, reason="datetime support is PY3+ only") +def test_pack_datetime_without_tzinfo(): + dt = datetime.datetime(1970, 1, 1, 0, 0, 42, 14) + with pytest.raises(ValueError, match="where tzinfo=None"): + packed = msgpack.packb(dt, datetime=True) + + dt = datetime.datetime(1970, 1, 1, 0, 0, 42, 14) + packed = msgpack.packb(dt, datetime=True, default=lambda x: None) + assert packed == msgpack.packb(None) + + dt = datetime.datetime(1970, 1, 1, 0, 0, 42, 14, tzinfo=_utc) + packed = msgpack.packb(dt, datetime=True) + unpacked = msgpack.unpackb(packed, timestamp=3) + assert unpacked == dt |