Testing your code#

Hypothesis testing#

Note

Testing with hypothesis is a fairly advanced topic. Before reading this section it is recommended that you take a look at our guide to xarray’s Data Structures, are familiar with conventional unit testing in pytest, and have seen the hypothesis library documentation.

The hypothesis library is a powerful tool for property-based testing. Instead of writing tests for one example at a time, it allows you to write tests parameterized by a source of many dynamically generated examples. For example you might have written a test which you wish to be parameterized by the set of all possible integers via hypothesis.strategies.integers().

Property-based testing is extremely powerful, because (unlike more conventional example-based testing) it can find bugs that you did not even think to look for!

Strategies#

Each source of examples is called a “strategy”, and xarray provides a range of custom strategies which produce xarray data structures containing arbitrary data. You can use these to efficiently test downstream code, quickly ensuring that your code can handle xarray objects of all possible structures and contents.

These strategies are accessible in the xarray.testing.strategies module, which provides

testing.strategies.supported_dtypes()

Generates only those numpy dtypes which xarray can handle.

testing.strategies.names()

Generates arbitrary string names for dimensions / variables.

testing.strategies.dimension_names(*[, ...])

Generates an arbitrary list of valid dimension names.

testing.strategies.dimension_sizes(*[, ...])

Generates an arbitrary mapping from dimension names to lengths.

testing.strategies.attrs()

Generates arbitrary valid attributes dictionaries for xarray objects.

testing.strategies.variables(*[, ...])

Generates arbitrary xarray.Variable objects.

testing.strategies.unique_subset_of(objs, *)

Return a strategy which generates a unique subset of the given objects.

These build upon the numpy and array API strategies offered in hypothesis.extra.numpy and hypothesis.extra.array_api:

In [1]: import hypothesis.extra.numpy as npst

Generating Examples#

To see an example of what each of these strategies might produce, you can call one followed by the .example() method, which is a general hypothesis method valid for all strategies.

In [2]: import xarray.testing.strategies as xrst

In [3]: xrst.variables().example()
Out[3]: 
<xarray.Variable (0: 3)> Size: 24B
array([0, 0, 0], dtype=uint64)

In [4]: xrst.variables().example()
Out[4]: 
<xarray.Variable (àŽŵŹĻ: 3, ť: 1)> Size: 12B
array([[4294967294],
       [     49851],
       [1137498527]], dtype=uint32)
Attributes:
    XĐĴ6ě:    True
    ý:        True
    ŮÐĐ:      [200]

In [5]: xrst.variables().example()
Out[5]: 
<xarray.Variable (ĖÏžŸ: 5, ĨźŘq: 3)> Size: 240B
array([[ 9.007e+015+5.000e-001j,  9.007e+015       +infj, -2.225e-308-5.000e-001j],
       [-1.798e+308-1.192e-007j,  9.007e+015+5.000e-001j,  1.157e-094+1.175e-038j],
       [ 9.007e+015+0.000e+000j,  9.007e+015+5.000e-001j, -6.142e+016+2.225e-309j],
       [ 9.007e+015+5.000e-001j,  9.007e+015+5.000e-001j,  3.235e+016       +infj],
       [ 9.007e+015+5.000e-001j,        -inf       +infj,  9.007e+015+0.000e+000j]])
Attributes:
    :         ['0717-01'     'NaT']
    Uė:       [[-inf]]
    ġáūćŽ:    [226 238]

You can see that calling .example() multiple times will generate different examples, giving you an idea of the wide range of data that the xarray strategies can generate.

In your tests however you should not use .example() - instead you should parameterize your tests with the hypothesis.given() decorator:

In [6]: from hypothesis import given
In [7]: @given(xrst.variables())
   ...: def test_function_that_acts_on_variables(var):
   ...:     assert func(var) == ...
   ...: 

Chaining Strategies#

Xarray’s strategies can accept other strategies as arguments, allowing you to customise the contents of the generated examples.

# generate a Variable containing an array with a complex number dtype, but all other details still arbitrary
In [8]: from hypothesis.extra.numpy import complex_number_dtypes

In [9]: xrst.variables(dtype=complex_number_dtypes()).example()
Out[9]: 
<xarray.Variable (ůk: 3, Î: 6, Ñ: 6)> Size: 2kB
array([[[-8.482e+287-3.333e-001j,         inf+9.120e-222j,         inf+9.120e-222j,
                 inf+9.120e-222j, -1.175e-038+6.860e+016j,         inf+9.120e-222j],
        [        nan+5.960e-008j,         inf+9.120e-222j,         inf+9.120e-222j,
         -3.333e-001       +infj,  6.496e+016       +nanj,         inf+9.120e-222j],
        [        inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j,
          3.829e+016       +nanj,         inf+9.120e-222j,         inf+9.120e-222j],
        [        nan-9.007e+015j,         inf+9.120e-222j,         inf+9.120e-222j,
         -1.798e+308+6.582e+016j,         inf+9.120e-222j,         inf+9.120e-222j],
        [        inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j,
                 inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j],
        [-2.329e+016-3.333e-001j,  2.225e-309       +infj,         inf+9.120e-222j,
                 inf+9.120e-222j,         nan+1.739e+016j,         inf+9.120e-222j]],

       [[        inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j,
          4.941e-324       -infj,  1.798e+308-1.000e+000j,         inf+9.120e-222j],
        [        inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j,
         -2.665e+016       -infj,         inf+9.120e-222j,         inf+9.120e-222j],
        [-1.500e+000-6.104e-005j,         inf+9.120e-222j,         inf+9.120e-222j,
         -3.333e-001-1.960e+016j,  1.113e-308-1.401e-045j, -3.333e-001       +nanj],
        [        inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j,
                 inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j],
        [        inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j,
                 inf+9.120e-222j,         inf+9.120e-222j,  1.500e+000       -infj],
        [ 6.386e+016-5.188e+016j,         inf+9.120e-222j,         inf+9.120e-222j,
                 inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j]],

       [[        inf+9.120e-222j,  1.798e+308-1.000e+000j,         inf+9.120e-222j,
          3.737e+016-1.433e+132j,         inf+9.120e-222j,         inf+9.120e-222j],
        [        inf+9.120e-222j,         inf+9.120e-222j,  4.941e-324-1.900e+000j,
                 inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j],
        [        inf+9.120e-222j, -1.192e-007-6.026e+016j,         inf+9.120e-222j,
          1.900e+000-2.000e+000j,         inf+9.120e-222j,         inf+9.120e-222j],
        [        inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j,
                 inf+9.120e-222j, -1.175e-038-3.333e-001j,         inf+9.120e-222j],
        [        inf+9.120e-222j,         inf+9.120e-222j,        -inf       +nanj,
                 inf+9.120e-222j, -1.113e-308       +infj,         inf+9.120e-222j],
        [-1.175e-038-0.000e+000j,         inf+9.120e-222j,         inf+9.120e-222j,
                 inf+9.120e-222j,         inf+9.120e-222j,         inf+9.120e-222j]]], dtype='>c16')

This also works with custom strategies, or strategies defined in other packages. For example you could imagine creating a chunks strategy to specify particular chunking patterns for a dask-backed array.

Fixing Arguments#

If you want to fix one aspect of the data structure, whilst allowing variation in the generated examples over all other aspects, then use hypothesis.strategies.just().

In [10]: import hypothesis.strategies as st

# Generates only variable objects with dimensions ["x", "y"]
In [11]: xrst.variables(dims=st.just(["x", "y"])).example()
Out[11]: 
<xarray.Variable (x: 5, y: 1)> Size: 10B
array([[ 6967],
       [10258],
       [13104],
       [22888],
       [ 1364]], dtype=uint16)

(This is technically another example of chaining strategies - hypothesis.strategies.just() is simply a special strategy that just contains a single example.)

To fix the length of dimensions you can instead pass dims as a mapping of dimension names to lengths (i.e. following xarray objects’ .sizes() property), e.g.

# Generates only variables with dimensions ["x", "y"], of lengths 2 & 3 respectively
In [12]: xrst.variables(dims=st.just({"x": 2, "y": 3})).example()
Out[12]: 
<xarray.Variable (x: 2, y: 3)> Size: 48B
array([[-inf, -inf, -inf],
       [-inf, -inf, -inf]])
Attributes: (12/31)
    ŕĻ³Żż:    False
    sœŽõg:    None
    ĆőZD4:    ŁŕîoĜ
    ēĈĹŻĭ:    True
    á:        True
    E:        False
    ...       ...
    ĎÓł:      ['1969-04-11T06'           'NaT']
    ½1Ŷă:     None
    śſĂFÈ:    [[-1.+1.052e+201j]\n [-1.+1.052e+201j]]
    ŞÕIJžč:    None
    ż:        ['1969-12-31T18:44:33'                 'NaT']
    ŗ:        None

You can also use this to specify that you want examples which are missing some part of the data structure, for instance

# Generates a Variable with no attributes
In [13]: xrst.variables(attrs=st.just({})).example()
Out[13]: 
<xarray.Variable (Čs: 5)> Size: 40B
array([ 1.175e-38+1.000e+00j,  0.000e+00+0.000e+00j,        inf+1.175e-38j,  1.175e-38+1.000e+00j,
       -1.500e+00+5.000e-01j], dtype=complex64)

Through a combination of chaining strategies and fixing arguments, you can specify quite complicated requirements on the objects your chained strategy will generate.

In [14]: fixed_x_variable_y_maybe_z = st.fixed_dictionaries(
   ....:     {"x": st.just(2), "y": st.integers(3, 4)}, optional={"z": st.just(2)}
   ....: )
   ....: 

In [15]: fixed_x_variable_y_maybe_z.example()
Out[15]: {'x': 2, 'y': 4, 'z': 2}

In [16]: special_variables = xrst.variables(dims=fixed_x_variable_y_maybe_z)

In [17]: special_variables.example()
Out[17]: 
<xarray.Variable (x: 2, y: 4, z: 2)> Size: 256B
array([[[ 1.500e+000+2.225e-308j, -1.798e+308       +nanj],
        [-1.798e+308       +nanj, -1.798e+308       +nanj],
        [-1.113e-308       +nanj, -2.225e-311       +infj],
        [        nan+2.488e-004j, -1.798e+308       +nanj]],

       [[-3.333e-001-1.113e-308j, -1.798e+308       +nanj],
        [ 0.000e+000       -infj, -0.000e+000-1.292e+016j],
        [ 1.000e-005-2.220e-016j, -1.798e+308       +nanj],
        [ 5.059e+016-3.333e-001j,  8.829e-204+6.104e-005j]]])
Attributes:
    ĚGúıO:    [[ True]]
    ĿŦčqú:    True
    Ğ:        None
    OŞżĕs:    [[  'NaT' '51261']]

In [18]: special_variables.example()
Out[18]: 
<xarray.Variable (x: 2, y: 4)> Size: 64B
array([[                 79,                  79,                  79,                  79],
       [                 79,                  79,                  79, 4378219662979108869]])
Attributes:
    ìž:       False
    h:        [[-1.9  inf]]

Here we have used one of hypothesis’ built-in strategies hypothesis.strategies.fixed_dictionaries() to create a strategy which generates mappings of dimension names to lengths (i.e. the size of the xarray object we want). This particular strategy will always generate an x dimension of length 2, and a y dimension of length either 3 or 4, and will sometimes also generate a z dimension of length 2. By feeding this strategy for dictionaries into the dims argument of xarray’s variables() strategy, we can generate arbitrary Variable objects whose dimensions will always match these specifications.

Generating Duck-type Arrays#

Xarray objects don’t have to wrap numpy arrays, in fact they can wrap any array type which presents the same API as a numpy array (so-called “duck array wrapping”, see wrapping numpy-like arrays).

Imagine we want to write a strategy which generates arbitrary Variable objects, each of which wraps a sparse.COO array instead of a numpy.ndarray. How could we do that? There are two ways:

1. Create a xarray object with numpy data and use the hypothesis’ .map() method to convert the underlying array to a different type:

In [19]: import sparse
In [20]: def convert_to_sparse(var):
   ....:     return var.copy(data=sparse.COO.from_numpy(var.to_numpy()))
   ....: 
In [21]: sparse_variables = xrst.variables(dims=xrst.dimension_names(min_dims=1)).map(
   ....:     convert_to_sparse
   ....: )
   ....: 

In [22]: sparse_variables.example()
Out[22]: 
<xarray.Variable (V: 3, Ò: 5, ÖŝLí: 6)> Size: 2kB
<COO: shape=(3, 5, 6), dtype=float32, nnz=89, fill_value=0.0>
Attributes:
    ĕªſï:     {'ČDš': '', 'Ř': '', 'žÊ6ĖĒ': False}

In [23]: sparse_variables.example()
Out[23]: 
<xarray.Variable (d: 5, ŽŌţvż: 5)> Size: 450B
<COO: shape=(5, 5), dtype=int16, nnz=25, fill_value=0>
  1. Pass a function which returns a strategy which generates the duck-typed arrays directly to the array_strategy_fn argument of the xarray strategies:

In [24]: def sparse_random_arrays(shape: tuple[int]) -> sparse._coo.core.COO:
   ....:     """Strategy which generates random sparse.COO arrays"""
   ....:     if shape is None:
   ....:         shape = npst.array_shapes()
   ....:     else:
   ....:         shape = st.just(shape)
   ....:     density = st.integers(min_value=0, max_value=1)
   ....:     return st.builds(sparse.random, shape=shape, density=density)
   ....: 

In [25]: def sparse_random_arrays_fn(
   ....:     *, shape: tuple[int, ...], dtype: np.dtype
   ....: ) -> st.SearchStrategy[sparse._coo.core.COO]:
   ....:     return sparse_random_arrays(shape=shape)
   ....: 
In [26]: sparse_random_variables = xrst.variables(
   ....:     array_strategy_fn=sparse_random_arrays_fn, dtype=st.just(np.dtype("float64"))
   ....: )
   ....: 

In [27]: sparse_random_variables.example()
Out[27]: 
<xarray.Variable (ēĽM: 6, Ë: 6, gsŝŦŻ: 2)> Size: 0B
<COO: shape=(6, 6, 2), dtype=float64, nnz=0, fill_value=0.0>

Either approach is fine, but one may be more convenient than the other depending on the type of the duck array which you want to wrap.

Compatibility with the Python Array API Standard#

Xarray aims to be compatible with any duck-array type that conforms to the Python Array API Standard (see our docs on Array API Standard support).

Warning

The strategies defined in testing.strategies are not guaranteed to use array API standard-compliant dtypes by default. For example arrays with the dtype np.dtype('float16') may be generated by testing.strategies.variables() (assuming the dtype kwarg was not explicitly passed), despite np.dtype('float16') not being in the array API standard.

If the array type you want to generate has an array API-compliant top-level namespace (e.g. that which is conventionally imported as xp or similar), you can use this neat trick:

In [28]: from numpy import array_api as xp  # available in numpy 1.26.0

In [29]: from hypothesis.extra.array_api import make_strategies_namespace

In [30]: xps = make_strategies_namespace(xp)

In [31]: xp_variables = xrst.variables(
   ....:     array_strategy_fn=xps.arrays,
   ....:     dtype=xps.scalar_dtypes(),
   ....: )
   ....: 

In [32]: xp_variables.example()
Out[32]: 
<xarray.Variable (ŻĎ: 1, â: 3, ž: 6)> Size: 144B
Array([[[1.5+1.5j, 1.5+1.5j, 1.5+1.5j, 1.5+1.5j, 1.5+1.5j, 1.5+1.5j],
        [1.5+1.5j, 1.5+1.5j, 1.5+1.5j, 1.5+1.5j, 1.5+1.5j, 1.5+1.5j],
        [1.5+1.5j, 1.5+1.5j, 1.5+1.5j, 1.5+1.5j, 1.5+1.5j, 1.5+1.5j]]], dtype=complex64)
Attributes:
    ž:        {'žaŦľő': array([-2663429887303220853], dtype='>i8'), 'ž': None}

Another array API-compliant duck array library would replace the import, e.g. import cupy as cp instead.

Testing over Subsets of Dimensions#

A common task when testing xarray user code is checking that your function works for all valid input dimensions. We can chain strategies to achieve this, for which the helper strategy unique_subset_of() is useful.

It works for lists of dimension names

In [33]: dims = ["x", "y", "z"]

In [34]: xrst.unique_subset_of(dims).example()
Out[34]: ['z', 'y', 'x']

In [35]: xrst.unique_subset_of(dims).example()
Out[35]: ['y', 'z', 'x']

as well as for mappings of dimension names to sizes

In [36]: dim_sizes = {"x": 2, "y": 3, "z": 4}

In [37]: xrst.unique_subset_of(dim_sizes).example()
Out[37]: {'x': 2, 'z': 4, 'y': 3}

In [38]: xrst.unique_subset_of(dim_sizes).example()
Out[38]: {'y': 3, 'z': 4}

This is useful because operations like reductions can be performed over any subset of the xarray object’s dimensions. For example we can write a pytest test that tests that a reduction gives the expected result when applying that reduction along any possible valid subset of the Variable’s dimensions.

import numpy.testing as npt


@given(st.data(), xrst.variables(dims=xrst.dimension_names(min_dims=1)))
def test_mean(data, var):
    """Test that the mean of an xarray Variable is always equal to the mean of the underlying array."""

    # specify arbitrary reduction along at least one dimension
    reduction_dims = data.draw(xrst.unique_subset_of(var.dims, min_size=1))

    # create expected result (using nanmean because arrays with Nans will be generated)
    reduction_axes = tuple(var.get_axis_num(dim) for dim in reduction_dims)
    expected = np.nanmean(var.data, axis=reduction_axes)

    # assert property is always satisfied
    result = var.mean(dim=reduction_dims).data
    npt.assert_equal(expected, result)