Skip to content

Commit 9ec6fb9

Browse files
committed
cleaning up new test
1 parent e2e34d5 commit 9ec6fb9

File tree

2 files changed

+30
-17
lines changed

2 files changed

+30
-17
lines changed

xarray/tests/conftest.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,26 @@ def d(request, backend, type) -> DataArray | Dataset:
139139
raise ValueError
140140

141141

142+
@pytest.fixture
143+
def byte_attrs_dataset():
144+
"""For testing issue #9407"""
145+
null_byte = b"\x00"
146+
other_bytes = bytes(range(1, 256))
147+
ds = Dataset({"x": 1}, coords={"x_coord": [1]})
148+
ds["x"].attrs["null_byte"] = null_byte
149+
ds["x"].attrs["other_bytes"] = other_bytes
150+
151+
expected = ds.copy()
152+
expected["x"].attrs["null_byte"] = ""
153+
expected["x"].attrs["other_bytes"] = other_bytes.decode(errors="replace")
154+
155+
return {
156+
"input": ds,
157+
"expected": expected,
158+
"h5netcdf_error": r"Invalid value provided for attribute .*: .*\. Null characters .*",
159+
}
160+
161+
142162
@pytest.fixture(scope="module")
143163
def create_test_datatree():
144164
"""

xarray/tests/test_backends.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1404,23 +1404,12 @@ def test_refresh_from_disk(self) -> None:
14041404
a.close()
14051405
b.close()
14061406

1407-
def test_byte_attrs(self) -> None:
1408-
with create_tmp_file() as tmp_file:
1409-
try:
1410-
null_byte = b"\x00"
1411-
other_bytes = bytes(range(1, 256))
1412-
ds = Dataset({"x": 1}, coords={"x_coord": [1]})
1413-
ds["x"].attrs["null_byte"] = null_byte
1414-
ds["x"].attrs["other_bytes"] = other_bytes
1415-
self.save(ds, tmp_file)
1416-
except ValueError:
1417-
assert self.engine == "h5netcdf"
1418-
else:
1419-
with self.open(tmp_file) as ds_out:
1420-
assert ds_out["x"].attrs["null_byte"] == ""
1421-
assert ds_out["x"].attrs["other_bytes"] == other_bytes.decode(
1422-
errors="replace"
1423-
)
1407+
def test_byte_attrs(self, byte_attrs_dataset: dict[str, Any]) -> None:
1408+
# test for issue #9407
1409+
input = byte_attrs_dataset["input"]
1410+
expected = byte_attrs_dataset["expected"]
1411+
with self.roundtrip(input) as actual:
1412+
assert_identical(actual, expected)
14241413

14251414

14261415
_counter = itertools.count()
@@ -3879,6 +3868,10 @@ def test_decode_utf8_warning(self) -> None:
38793868
assert ds.title == title
38803869
assert "attribute 'title' of h5netcdf object '/'" in str(w[0].message)
38813870

3871+
def test_byte_attrs(self, byte_attrs_dataset: dict[str, Any]) -> None:
3872+
with pytest.raises(ValueError, match=byte_attrs_dataset["h5netcdf_error"]):
3873+
super().test_byte_attrs(byte_attrs_dataset)
3874+
38823875

38833876
@requires_h5netcdf
38843877
@requires_netCDF4

0 commit comments

Comments
 (0)