pytest-dev/pytest · error · ValueError

relative tolerance can't be negative: {rel}

Error message

relative tolerance can't be negative: {rel}

What it means

ApproxTimedelta.__init__ rejects a negative relative tolerance for timedelta comparisons. A negative fraction of the expected duration is not a meaningful tolerance.

Source

Thrown at src/_pytest/approx.py:677

                "datetime/timedelta comparisons: "
                "e.g. approx(expected, abs=timedelta(seconds=1)) "
                "or approx(expected, rel=0.01)"
            )
        if abs is not None and not isinstance(abs, timedelta):
            raise TypeError(
                f"absolute tolerance for datetime/timedelta must be a "
                f"timedelta, got {type(abs).__name__}"
            )
        if abs is not None and abs < timedelta(0):
            raise ValueError(f"absolute tolerance can't be negative: {abs}")
        if rel is not None:
            if not isinstance(rel, (int, float)):
                raise TypeError(
                    f"relative tolerance for timedelta must be a "
                    f"number, got {type(rel).__name__}"
                )
            if rel < 0:
                raise ValueError(f"relative tolerance can't be negative: {rel}")
            if math.isnan(rel):
                raise ValueError("relative tolerance can't be NaN.")
            if math.isinf(rel):
                raise ValueError("relative tolerance can't be infinite.")
        # Compute the effective tolerance. abs_tolerance is a timedelta, rel * expected
        # gives a timedelta (timedelta * float works in Python).
        abs_tolerance = abs
        if rel is None:
            rel_tolerance = None
        else:
            # Checked above.
            assert not isinstance(expected, datetime)
            rel_tolerance = rel * builtins.abs(expected)
        if abs_tolerance is not None and rel_tolerance is not None:
            tolerance: timedelta | None = max(abs_tolerance, rel_tolerance)
        else:
            tolerance = abs_tolerance if abs_tolerance is not None else rel_tolerance
        super().__init__(expected, rel=rel, abs=tolerance, nan_ok=False)

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Use a non-negative rel: approx(td, rel=0.01).
  2. Validate the source of the value and strip the sign.
  3. Clamp or assert in the producing fixture.

Example fix

// before
assert got == approx(td, rel=-0.01)
// after
assert got == approx(td, rel=0.01)
Defensive patterns

Strategy: validation

Validate before calling

def approx_td_rel(value, rel):
    if not isinstance(rel, (int, float)) or rel < 0:
        raise ValueError(f'rel must be a non-negative number, got {rel!r}')
    return pytest.approx(value, rel=rel)

Type guard

def is_nonneg_number(v) -> bool:
    return isinstance(v, (int, float)) and v >= 0

Prevention

When it happens

Trigger: Call pytest.approx(some_timedelta, rel=-0.01) (or any negative numeric rel).

Common situations: Sign error when copying a tolerance; tolerance derived from a computation that can go negative; config typo.

Related errors


AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04). Data as JSON: /data/errors/ab29b7d30b2db9ce.json. Report an issue: GitHub.