Skip to content

Commit

Permalink
Convert ValueError for invalid epoch-based datetime values
Browse files Browse the repository at this point in the history
  • Loading branch information
agronholm committed Jan 16, 2024
1 parent 4ef178b commit 7c6e647
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion cbor2/_decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ def decode_epoch_datetime(self) -> datetime:

try:
tmp = datetime.fromtimestamp(value, timezone.utc)
except (OverflowError, OSError) as exc:
except (OverflowError, OSError, ValueError) as exc:
raise CBORDecodeValueError("error decoding datetime from epoch") from exc

return self.set_shareable(tmp)
Expand Down
4 changes: 2 additions & 2 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ This library adheres to `Semantic Versioning <http://semver.org/>`_.
``CBORDecodeValueError``
- Fixed ``TypeError`` from a failed decoding of ``MIMEMessage`` not being wrapped as
``CBORDecodeValueError``
- Fixed ``OverflowError`` or ``OSError`` from a failed decoding of epoch-based ``datetime`` not
being wrapped as ``CBORDecodeValueError``
- Fixed ``OverflowError``, ``OSError`` or ``ValueError`` from a failed decoding of epoch-based
``datetime`` not being wrapped as ``CBORDecodeValueError``

**5.5.1** (2023-11-02)

Expand Down
1 change: 1 addition & 0 deletions source/decoder.c
Original file line number Diff line number Diff line change
Expand Up @@ -1406,6 +1406,7 @@ CBORDecoder_decode_epoch_datetime(CBORDecoderObject *self)
if (!ret && (
PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_OverflowError)
|| PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_OSError)
|| PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_ValueError)
))
raise_from(_CBOR2_CBORDecodeValueError, "error decoding datetime from epoch");
}
Expand Down
7 changes: 7 additions & 0 deletions tests/test_decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,13 @@ def test_datetime_value_too_large(impl):
assert isinstance(excinfo.value.__cause__, OSError)


def test_datetime_date_out_of_range(impl):
with pytest.raises(impl.CBORDecodeError) as excinfo:
impl.loads(unhexlify("a6c11b00002401001b000000000000ff00"))

assert isinstance(excinfo.value.__cause__, ValueError)


def test_datetime_timezone(impl):
decoded = impl.loads(b"\xc0\x78\x192018-08-02T07:00:59+00:30")
assert decoded == datetime(2018, 8, 2, 7, 0, 59, tzinfo=timezone(timedelta(minutes=30)))
Expand Down

0 comments on commit 7c6e647

Please sign in to comment.