Skip to content

Commit

Permalink
Fix jsonToArray error on empty data read (#237)
Browse files Browse the repository at this point in the history
* Fix jsonToArray error on empty data read

This lets clients read from an empty attribute without causing
an internal server error.

* Add test for empty jsonToArray
  • Loading branch information
mattjala authored Aug 8, 2023
1 parent ae1e926 commit 822fe76
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 17 deletions.
37 changes: 20 additions & 17 deletions hsds/util/arrayUtil.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,24 +174,27 @@ def fillVlenArray(rank, data, arr, index):
data_json,
] # listify

if isVlen(data_dtype):
arr = np.zeros((npoints,), dtype=data_dtype)
fillVlenArray(np_shape_rank, data_json, arr, 0)
if not (None in data_json):
if isVlen(data_dtype):
arr = np.zeros((npoints,), dtype=data_dtype)
fillVlenArray(np_shape_rank, data_json, arr, 0)
else:
try:
arr = np.array(data_json, dtype=data_dtype)
except UnicodeEncodeError as ude:
msg = "Unable to encode data"
raise ValueError(msg) from ude
# raise an exception of the array shape doesn't match the selection shape
# allow if the array is a scalar and the selection shape is one element,
# numpy is ok with this
if arr.size != npoints:
msg = "Input data doesn't match selection number of elements"
msg += f" Expected {npoints}, but received: {arr.size}"
raise ValueError(msg)
if arr.shape != data_shape:
arr = arr.reshape(data_shape) # reshape to match selection
else:
try:
arr = np.array(data_json, dtype=data_dtype)
except UnicodeEncodeError as ude:
msg = "Unable to encode data"
raise ValueError(msg) from ude
# raise an exception of the array shape doesn't match the selection shape
# allow if the array is a scalar and the selection shape is one element,
# numpy is ok with this
if arr.size != npoints:
msg = "Input data doesn't match selection number of elements"
msg += f" Expected {npoints}, but received: {arr.size}"
raise ValueError(msg)
if arr.shape != data_shape:
arr = arr.reshape(data_shape) # reshape to match selection
arr = np.array([]).astype(data_dtype)

return arr

Expand Down
14 changes: 14 additions & 0 deletions tests/unit/array_util_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,20 @@ def testIndexIterator(self):
cnt += 1
self.assertEqual(cnt, 20)

def testJsonToArrayOnNoneArray(self):
data_dtype = np.dtype("i4")
data_shape = [0, ]
data_json = [None]
arr = None

try:
arr = jsonToArray(data_shape, data_dtype, data_json)
except Exception as e:
print(f"Exception while testing jsonToArray on array with None elements: {e}")

self.assertTrue(len(arr) == 0)
self.assertTrue(arr.dtype == data_dtype)


if __name__ == "__main__":
# setup test files
Expand Down

0 comments on commit 822fe76

Please sign in to comment.