MCPcopy
hub / github.com/pydata/xarray / test_to_and_from_dict

Method test_to_and_from_dict

xarray/tests/test_dataarray.py:3907–3991  ·  view source on GitHub ↗
(
        self, encoding: bool, data: bool | Literal["list", "array"], use_dask: bool
    )

Source from the content-addressed store, hash-verified

3905 @pytest.mark.parametrize("data", ["list", "array", True])
3906 @pytest.mark.parametrize("encoding", [True, False])
3907 def test_to_and_from_dict(
3908 self, encoding: bool, data: bool | Literal["list", "array"], use_dask: bool
3909 ) -> None:
3910 if use_dask and not has_dask:
3911 pytest.skip("requires dask")
3912 encoding_data = {"bar": "spam"}
3913 array = DataArray(
3914 np.random.randn(2, 3), {"x": ["a", "b"]}, ["x", "y"], name="foo"
3915 )
3916 array.encoding = encoding_data
3917
3918 return_data = array.to_numpy()
3919 coords_data = np.array(["a", "b"])
3920 if data == "list" or data is True:
3921 return_data = return_data.tolist()
3922 coords_data = coords_data.tolist()
3923
3924 expected: dict[str, Any] = {
3925 "name": "foo",
3926 "dims": ("x", "y"),
3927 "data": return_data,
3928 "attrs": {},
3929 "coords": {"x": {"dims": ("x",), "data": coords_data, "attrs": {}}},
3930 }
3931 if encoding:
3932 expected["encoding"] = encoding_data
3933
3934 if has_dask:
3935 da = array.chunk()
3936 else:
3937 da = array
3938
3939 if data == "array" or data is False:
3940 with raise_if_dask_computes():
3941 actual = da.to_dict(encoding=encoding, data=data)
3942 else:
3943 actual = da.to_dict(encoding=encoding, data=data)
3944
3945 # check that they are identical
3946 np.testing.assert_equal(expected, actual)
3947
3948 # check roundtrip
3949 assert_identical(da, DataArray.from_dict(actual))
3950
3951 # a more bare bones representation still roundtrips
3952 d = {
3953 "name": "foo",
3954 "dims": ("x", "y"),
3955 "data": da.values.tolist(),
3956 "coords": {"x": {"dims": "x", "data": ["a", "b"]}},
3957 }
3958 assert_identical(da, DataArray.from_dict(d))
3959
3960 # and the most bare bones representation still roundtrips
3961 d = {"name": "foo", "dims": ("x", "y"), "data": da.values}
3962 assert_identical(da.drop_vars("x"), DataArray.from_dict(d))
3963
3964 # missing a dims in the coords

Callers

nothing calls this directly

Calls 10

to_numpyMethod · 0.95
chunkMethod · 0.95
DataArrayClass · 0.90
raise_if_dask_computesFunction · 0.90
assert_identicalFunction · 0.90
to_dictMethod · 0.45
from_dictMethod · 0.45
drop_varsMethod · 0.45
copyMethod · 0.45
updateMethod · 0.45

Tested by

no test coverage detected