Skip to content

Commit 6c4be38

Browse files
committed
Test save/load of a 'bad' unicode sequence as a byte array.
1 parent 2c276a8 commit 6c4be38

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,3 +692,23 @@ def test_write_stringobjects__fail(self, tmp_path):
692692
)
693693
with pytest.raises(ValueError, match=msg):
694694
iris.save(cube, filepath)
695+
696+
697+
class TestSaveloadBadUnicodeAsBytes:
698+
def test_save_load_bad_unicode(self, tmp_path):
699+
filepath = tmp_path / "bad_unicode_utf8.nc"
700+
test_string = "marré"
701+
bytes_array = test_string.encode("utf8")
702+
s1_array = np.array([bytes_array[i : i + 1] for i in range(len(bytes_array))])
703+
s1_array_bad_utf8 = s1_array[:-1] # invalid without the last byte
704+
cube = Cube(s1_array_bad_utf8, attributes={"_Encoding": "utf8"})
705+
iris.save(cube, filepath)
706+
# First check for error when reading back *normally*
707+
msg = "could not be decoded with the 'utf-8' encoding"
708+
with pytest.raises(ValueError, match=msg):
709+
iris.load(filepath)
710+
# .. but OK in byte-reading mode
711+
with iris.fileformats.netcdf.DECODE_TO_STRINGS_ON_READ.context(False):
712+
readback_cube = iris.load_cube(filepath)
713+
assert readback_cube.dtype == "S1"
714+
assert np.all(readback_cube.data == s1_array_bad_utf8)

0 commit comments

Comments
 (0)