Skip to content

fix: handle infinite relative tolerance for timedelta values#14754

Open
winklemad wants to merge 3 commits into
pytest-dev:mainfrom
winklemad:fix-timedelta-infinite-relative-tolerance
Open

fix: handle infinite relative tolerance for timedelta values#14754
winklemad wants to merge 3 commits into
pytest-dev:mainfrom
winklemad:fix-timedelta-infinite-relative-tolerance

Conversation

@winklemad

@winklemad winklemad commented Jul 22, 2026

Copy link
Copy Markdown

Summary

pytest.approx() multiplies a timedelta by the relative tolerance while constructing the comparison. When rel=float("inf"), Python raises OverflowError because timedelta has no infinite representation.

Reject infinite relative tolerances alongside the existing negative and NaN validation, producing a clear ValueError before multiplication. Numeric approximate-comparison behavior remains unchanged.

Validation

  • tox -e py312 -- testing/python/approx.py::TestApproxDatetime::test_timedelta_rel_must_not_be_infinite
  • tox -e py312 -- testing/python/approx.py
  • tox -e py312
  • tox -e linting
  • git diff --check

@psf-chronographer psf-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Jul 22, 2026

@Pierre-Sassoulas Pierre-Sassoulas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for working on this ! I'm curious about what others expect from pytest in this case. Silentely succeed, or raise ? And from their linter ? Probably raise a warning as it's a constant condition or an underhanded way to check typing.

Comment thread src/_pytest/approx.py Outdated
rel_tolerance = None
elif math.isinf(rel):
if expected == timedelta(0):
raise ValueError("relative tolerance can't be NaN.")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't be infinite ? Should it be be line 679 with the other sanity guards checks ? This value can be infinite but it doesn't make a lot of sense to test this. (Like an assert True) Maybe warning for this is a linter job and not pytest though.

@@ -0,0 +1 @@
``pytest.approx()`` now rejects infinite relative tolerances for ``datetime.timedelta`` values with a clear ``ValueError`` instead of raising ``OverflowError``.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be an improvement rather than a bugfix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants