Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions doc/en/getting-started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
--------------------------------------------------------------

Expand Down
27 changes: 27 additions & 0 deletions doc/en/how-to/assert.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
------------------------------------------

Expand Down