From 443d0604616ba546012cf5a2e9f01be03367a8be Mon Sep 17 00:00:00 2001 From: Loic Huder Date: Mon, 26 Aug 2024 12:01:37 +0200 Subject: [PATCH] Raise 422 errors when requesting scalar datasets with tiff or csv format --- h5grove/encoders.py | 21 +++++++++++++-------- test/base_test.py | 18 +++++++++++++++++- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/h5grove/encoders.py b/h5grove/encoders.py index a2ad5ea..12a1b44 100644 --- a/h5grove/encoders.py +++ b/h5grove/encoders.py @@ -126,21 +126,26 @@ def encode(content: Any, encoding: Optional[str] = "json") -> Response: f"Unsupported encoding {encoding} for non-numeric content" ) - if encoding == "csv": + if encoding == "npy": return Response( - csv_encode(content_array), + npy_encode(content_array), headers={ - "Content-Type": "text/csv", - "Content-Disposition": 'attachment; filename="data.csv"', + "Content-Type": "application/octet-stream", + "Content-Disposition": 'attachment; filename="data.npy"', }, ) - if encoding == "npy": + if content_array.ndim == 0: + raise QueryArgumentError( + f"Unsupported encoding {encoding} for empty and scalar datasets" + ) + + if encoding == "csv": return Response( - npy_encode(content_array), + csv_encode(content_array), headers={ - "Content-Type": "application/octet-stream", - "Content-Disposition": 'attachment; filename="data.npy"', + "Content-Type": "text/csv", + "Content-Disposition": 'attachment; filename="data.csv"', }, ) diff --git a/test/base_test.py b/test/base_test.py index b3bc66d..154d161 100644 --- a/test/base_test.py +++ b/test/base_test.py @@ -77,7 +77,6 @@ def test_data_on_array_with_format(self, server, format_arg): assert np.array_equal(retrieved_data, data) - # TODO: What should we do for csv, tiff @pytest.mark.parametrize("format_arg", ("json", "bin", "npy")) def test_data_on_scalar_with_format(self, server, format_arg): """Test /data/ endpoint on scalar dataset""" @@ -596,3 +595,20 @@ def test_422_on_invalid_query_arg(self, server): f"/meta/?file={filename}&path={path}&resolve_links={invalid_link_resolution}", 422, ) + + @pytest.mark.parametrize("format_arg", ("csv", "tiff")) + def test_422_on_format_incompatible_with_empty_or_scalar_datasets( + self, server, format_arg + ): + filename = "test.h5" + + with h5py.File(server.served_directory / filename, mode="w") as h5file: + h5file["scalar"] = 55 + h5file["empty"] = h5py.Empty(dtype="<4f") + + server.assert_error_code( + f"/data/?file={filename}&path=/scalar&format={format_arg}", 422 + ) + server.assert_error_code( + f"/data/?file={filename}&path=/empty&format={format_arg}", 422 + )