diff --git a/doc/en/getting-started.rst b/doc/en/getting-started.rst index d349e28ac07..24501f53a69 100644 --- a/doc/en/getting-started.rst +++ b/doc/en/getting-started.rst @@ -199,6 +199,26 @@ This is outlined below: Note that attributes added at class level are *class attributes*, so they will be shared between tests. +Compare floating-point values with pytest.approx +-------------------------------------------------------------- + +``pytest`` also provides a number of utilities to make writing tests easier. +For example, you can use :func:`pytest.approx` to compare floating-point +values that may have small rounding errors: + +.. code-block:: python + + # content of test_approx.py + import pytest + + + def test_sum(): + assert (0.1 + 0.2) == pytest.approx(0.3) + +This avoids the need for manual tolerance checks or using +``math.isclose`` and works with scalars, lists, and NumPy arrays. + + Request a unique temporary directory for functional tests -------------------------------------------------------------- diff --git a/doc/en/how-to/assert.rst b/doc/en/how-to/assert.rst index 8e368c35f7a..4dfceda0fad 100644 --- a/doc/en/how-to/assert.rst +++ b/doc/en/how-to/assert.rst @@ -66,6 +66,33 @@ See :ref:`assert-details` for more information on assertion introspection. .. _`assertraises`: +Assertions about approximate equality +------------------------------------- + +When comparing floating point values (or arrays of floats), small rounding +errors are common. Instead of using ``assert abs(a - b) < tol`` or +``numpy.isclose``, you can use :func:`pytest.approx`: + +.. code-block:: python + + import pytest + import numpy as np + + + def test_floats(): + assert (0.1 + 0.2) == pytest.approx(0.3) + + + def test_arrays(): + a = np.array([1.0, 2.0, 3.0]) + b = np.array([0.9999, 2.0001, 3.0]) + assert a == pytest.approx(b) + +``pytest.approx`` works with scalars, lists, dictionaries, and NumPy arrays. +It also supports comparisons involving NaNs. + +See :func:`pytest.approx` for details. + Assertions about expected exceptions ------------------------------------------