Skip to content

Commit 042028e

Browse files
committed
Get temporary iris load/save exercises working (todo: proper tests).
1 parent 10831d7 commit 042028e

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

lib/iris/fileformats/netcdf/saver.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1713,6 +1713,12 @@ def add_names_attrs():
17131713
if element.units.calendar:
17141714
_setncattr(cf_var, "calendar", str(element.units.calendar))
17151715

1716+
# Most attributes are dealt with later.
1717+
# But _Encoding need to be defined before we can write to a character variable
1718+
if element.dtype.kind in "SU" and "_Encoding" in element.attributes:
1719+
encoding = element.attributes.pop("_Encoding")
1720+
_setncattr(cf_var, "_Encoding", encoding)
1721+
17161722
if not isinstance(element, Cube):
17171723
# Add any other custom coordinate attributes.
17181724
# N.B. not Cube, which has specific handling in _create_cf_data_variable

lib/iris/tests/integration/netcdf/test_chararrays.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ def test_load_encodings(encoding, save_dir):
218218
# small change
219219
print(f"\n=========\nTesting encoding: {encoding}")
220220
filepath = save_dir / f"tmp_load_{str(encoding)}.nc"
221+
# Actual content is always either utf-8 or utf-32
221222
do_as = encoding
222223
if encoding != "utf-32":
223224
do_as = "utf-8"
@@ -228,7 +229,14 @@ def test_load_encodings(encoding, save_dir):
228229
TEST_COORD_VALS, N_STRLEN, encoding=do_as
229230
)
230231
make_testfile(filepath, TEST_CHARARRAY, TEST_COORDARRAY, encoding_str=encoding)
231-
show_result(filepath)
232+
if encoding == "ascii":
233+
# If explicitly labelled as ascii, 'utf-8' data will fail to load back ...
234+
msg = r"Character data .* could not be decoded with the 'ascii' encoding\."
235+
with pytest.raises(ValueError, match=msg):
236+
show_result(filepath)
237+
else:
238+
# ... otherwise, utf-8 data loads even without a label, as 'utf-8' default used
239+
show_result(filepath)
232240

233241

234242
@pytest.mark.parametrize("encoding", test_encodings)
@@ -243,10 +251,14 @@ def test_save_encodings(encoding, save_dir):
243251
)
244252
print(cube)
245253
filepath = save_dir / f"tmp_save_{str(encoding)}.nc"
246-
if encoding == "ascii":
254+
if encoding in ("ascii", None):
255+
msg = (
256+
"String data written to netcdf character variable 'v' "
257+
"could not be represented in encoding 'ascii'"
258+
)
247259
with pytest.raises(
248-
UnicodeEncodeError,
249-
match="'ascii' codec can't encode character.*not in range",
260+
ValueError,
261+
match=msg,
250262
):
251263
iris.save(cube, filepath)
252264
else:

0 commit comments

Comments
 (0)