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

Method test_to_and_from_dict

xarray/tests/test_dataset.py:5566–5659  ·  view source on GitHub ↗
(
        self, encoding: bool, data: bool | Literal["list", "array"]
    )

Source from the content-addressed store, hash-verified

5564 @pytest.mark.parametrize("encoding", [True, False])
5565 @pytest.mark.parametrize("data", [True, "list", "array"])
5566 def test_to_and_from_dict(
5567 self, encoding: bool, data: bool | Literal["list", "array"]
5568 ) -> None:
5569 # <xarray.Dataset>
5570 # Dimensions: (t: 10)
5571 # Coordinates:
5572 # * t (t) <U1 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j'
5573 # Data variables:
5574 # a (t) float64 0.6916 -1.056 -1.163 0.9792 -0.7865 ...
5575 # b (t) float64 1.32 0.1954 1.91 1.39 0.519 -0.2772 ...
5576 x = np.random.randn(10)
5577 y = np.random.randn(10)
5578 t = list("abcdefghij")
5579 ds = Dataset({"a": ("t", x), "b": ("t", y), "t": ("t", t)})
5580 expected: dict[str, dict[str, Any]] = {
5581 "coords": {"t": {"dims": ("t",), "data": t, "attrs": {}}},
5582 "attrs": {},
5583 "dims": {"t": 10},
5584 "data_vars": {
5585 "a": {"dims": ("t",), "data": x.tolist(), "attrs": {}},
5586 "b": {"dims": ("t",), "data": y.tolist(), "attrs": {}},
5587 },
5588 }
5589 if encoding:
5590 ds.t.encoding.update({"foo": "bar"})
5591 expected["encoding"] = {}
5592 expected["coords"]["t"]["encoding"] = ds.t.encoding
5593 for vvs in ["a", "b"]:
5594 expected["data_vars"][vvs]["encoding"] = {}
5595
5596 actual = ds.to_dict(data=data, encoding=encoding)
5597
5598 # check that they are identical
5599 np.testing.assert_equal(expected, actual)
5600
5601 # check roundtrip
5602 ds_rt = Dataset.from_dict(actual)
5603 assert_identical(ds, ds_rt)
5604 if encoding:
5605 assert set(ds_rt.variables) == set(ds.variables)
5606 for vv in ds.variables:
5607 np.testing.assert_equal(ds_rt[vv].encoding, ds[vv].encoding)
5608
5609 # check the data=False option
5610 expected_no_data = expected.copy()
5611 del expected_no_data["coords"]["t"]["data"]
5612 del expected_no_data["data_vars"]["a"]["data"]
5613 del expected_no_data["data_vars"]["b"]["data"]
5614 endiantype = "<U1" if sys.byteorder == "little" else ">U1"
5615 expected_no_data["coords"]["t"].update({"dtype": endiantype, "shape": (10,)})
5616 expected_no_data["data_vars"]["a"].update({"dtype": "float64", "shape": (10,)})
5617 expected_no_data["data_vars"]["b"].update({"dtype": "float64", "shape": (10,)})
5618 actual_no_data = ds.to_dict(data=False, encoding=encoding)
5619 assert expected_no_data == actual_no_data
5620
5621 # verify coords are included roundtrip
5622 expected_ds = ds.set_coords("b")
5623 actual2 = Dataset.from_dict(expected_ds.to_dict(data=data, encoding=encoding))

Callers

nothing calls this directly

Calls 7

to_dictMethod · 0.95
set_coordsMethod · 0.95
DatasetClass · 0.90
assert_identicalFunction · 0.90
updateMethod · 0.45
from_dictMethod · 0.45
copyMethod · 0.45

Tested by

no test coverage detected