|
| 1 | +# Copyright 2022 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import json |
| 16 | +import typing |
| 17 | + |
| 18 | +import numpy as np |
| 19 | +import pandas as pd |
| 20 | +import pandas._testing as tm |
| 21 | +import pandas.tests.extension.base as base |
| 22 | +import pytest |
| 23 | + |
| 24 | + |
| 25 | +class TestJSONArrayAccumulate(base.BaseAccumulateTests): |
| 26 | + pass |
| 27 | + |
| 28 | + |
| 29 | +class TestJSONArrayCasting(base.BaseCastingTests): |
| 30 | + def test_astype_str(self, data): |
| 31 | + # Use `json.dumps(str)` instead of passing `str(obj)` directly to the super method. |
| 32 | + result = pd.Series(data[:5]).astype(str) |
| 33 | + expected = pd.Series( |
| 34 | + [json.dumps(x, sort_keys=True) for x in data[:5]], dtype=str |
| 35 | + ) |
| 36 | + tm.assert_series_equal(result, expected) |
| 37 | + |
| 38 | + @pytest.mark.parametrize( |
| 39 | + "nullable_string_dtype", |
| 40 | + [ |
| 41 | + "string[python]", |
| 42 | + "string[pyarrow]", |
| 43 | + ], |
| 44 | + ) |
| 45 | + def test_astype_string(self, data, nullable_string_dtype): |
| 46 | + # Use `json.dumps(str)` instead of passing `str(obj)` directly to the super method. |
| 47 | + result = pd.Series(data[:5]).astype(nullable_string_dtype) |
| 48 | + expected = pd.Series( |
| 49 | + [json.dumps(x, sort_keys=True) for x in data[:5]], |
| 50 | + dtype=nullable_string_dtype, |
| 51 | + ) |
| 52 | + tm.assert_series_equal(result, expected) |
| 53 | + |
| 54 | + |
| 55 | +class TestJSONArrayConstructors(base.BaseConstructorsTests): |
| 56 | + def test_from_dtype(self, data): |
| 57 | + # construct from our dtype & string dtype |
| 58 | + dtype = data.dtype |
| 59 | + |
| 60 | + expected = pd.Series(data) |
| 61 | + result = pd.Series(list(data), dtype=dtype) |
| 62 | + tm.assert_series_equal(result, expected) |
| 63 | + |
| 64 | + result = pd.Series(list(data), dtype=str(dtype)) |
| 65 | + tm.assert_series_equal(result, expected) |
| 66 | + |
| 67 | + # Use `{"col1": data}` instead of passing `data` directly to the super method. |
| 68 | + # This prevents the DataFrame constructor from attempting to interpret the |
| 69 | + # dictionary as column headers. |
| 70 | + |
| 71 | + # gh-30280 |
| 72 | + expected = pd.DataFrame({"col1": data}).astype(dtype) |
| 73 | + result = pd.DataFrame({"col1": list(data)}, dtype=dtype) |
| 74 | + tm.assert_frame_equal(result, expected) |
| 75 | + |
| 76 | + result = pd.DataFrame({"col1": list(data)}, dtype=str(dtype)) |
| 77 | + tm.assert_frame_equal(result, expected) |
| 78 | + |
| 79 | + def test_series_constructor_scalar_with_index(self, data, dtype): |
| 80 | + # Use json.dumps(data[0]) instead of passing data[0] directly to the super method. |
| 81 | + # This prevents the Series constructor from attempting to interpret the dictionary |
| 82 | + # as column headers. |
| 83 | + scalar = json.dumps(data[0]) |
| 84 | + result = pd.Series(scalar, index=[1, 2, 3], dtype=dtype) |
| 85 | + expected = pd.Series([scalar] * 3, index=[1, 2, 3], dtype=dtype) |
| 86 | + tm.assert_series_equal(result, expected) |
| 87 | + |
| 88 | + result = pd.Series(scalar, index=["foo"], dtype=dtype) |
| 89 | + expected = pd.Series([scalar], index=["foo"], dtype=dtype) |
| 90 | + tm.assert_series_equal(result, expected) |
| 91 | + |
| 92 | + |
| 93 | +@pytest.mark.skip(reason="BigQuery does not allow group by a JSON-type column.") |
| 94 | +class TestJSONArrayGroupby(base.BaseGroupbyTests): |
| 95 | + pass |
| 96 | + |
| 97 | + |
| 98 | +class TestJSONArrayDtype(base.BaseDtypeTests): |
| 99 | + pass |
| 100 | + |
| 101 | + |
| 102 | +class TestJSONArrayGetitem(base.BaseGetitemTests): |
| 103 | + @pytest.mark.xfail(reason="JSONDtype's type returns its storage type.") |
| 104 | + def test_getitem_scalar(self, data): |
| 105 | + """ |
| 106 | + `_getitem_` can return any JSON-types objects while `data.dtype.type` returns |
| 107 | + a string to indicate its storage type. |
| 108 | + > assert isinstance(result, data.dtype.type) |
| 109 | + E AssertionError |
| 110 | + """ |
| 111 | + super().test_getitem_scalar(data) |
| 112 | + |
| 113 | + |
| 114 | +class TestJSONArrayIndex(base.BaseIndexTests): |
| 115 | + pass |
| 116 | + |
| 117 | + |
| 118 | +class TestJSONArrayInterface(base.BaseInterfaceTests): |
| 119 | + def test_array_interface(self, data): |
| 120 | + result = np.array(data) |
| 121 | + # Use `json.dumps(data[0])` instead of passing `data[0]` directly to the super method. |
| 122 | + assert result[0] == json.dumps(data[0]) |
| 123 | + |
| 124 | + result = np.array(data, dtype=object) |
| 125 | + # Use `json.dumps(x)` instead of passing `x` directly to the super method. |
| 126 | + expected = np.array([json.dumps(x) for x in data], dtype=object) |
| 127 | + # if expected.ndim > 1: |
| 128 | + # # nested data, explicitly construct as 1D |
| 129 | + # expected = construct_1d_object_array_from_listlike(list(data)) |
| 130 | + tm.assert_numpy_array_equal(result, expected) |
| 131 | + |
| 132 | + @pytest.mark.skip(reason="2D support not implemented for JSONArray") |
| 133 | + def test_view(self, data): |
| 134 | + super().test_view(data) |
| 135 | + |
| 136 | + |
| 137 | +class TestJSONArrayParsing(base.BaseParsingTests): |
| 138 | + @pytest.mark.xfail(reason="data type 'json' not understood") |
| 139 | + @pytest.mark.parametrize("engine", ["c", "python"]) |
| 140 | + def test_EA_types(self, engine, data, request): |
| 141 | + super().test_EA_types(engine, data, request) |
| 142 | + |
| 143 | + |
| 144 | +class TestJSONArrayMethods(base.BaseMethodsTests): |
| 145 | + @pytest.mark.xfail(reason="Unhashable") |
| 146 | + def test_value_counts_with_normalize(self, data): |
| 147 | + super().test_value_counts_with_normalize(data) |
| 148 | + |
| 149 | + @pytest.mark.skip("fill-value is interpreted as a dict of values") |
| 150 | + def test_fillna_copy_frame(self, data_missing): |
| 151 | + super().test_fillna_copy_frame(data_missing) |
| 152 | + |
| 153 | + @pytest.mark.xfail(reason="combine for JSONArray not supported") |
| 154 | + def test_combine_le(self, data_repeated): |
| 155 | + super().test_combine_le(data_repeated) |
| 156 | + |
| 157 | + @pytest.mark.skip(reason="'<' not supported between instances of 'dict' and 'dict'") |
| 158 | + def test_searchsorted(self, data_for_sorting, as_series): |
| 159 | + super().test_searchsorted(self, data_for_sorting, as_series) |
| 160 | + |
| 161 | + @pytest.mark.xfail( |
| 162 | + reason="`to_numpy` returns serialized JSON, " |
| 163 | + + "while `__getitem__` returns JSON objects." |
| 164 | + ) |
| 165 | + def test_where_series(self, data, na_value, as_frame): |
| 166 | + # `Series.where` calls `to_numpy` to get results. |
| 167 | + super().test_where_series(data, na_value, as_frame) |
| 168 | + |
| 169 | + @pytest.mark.skip(reason="BigQuery does not allow group by a JSON-type column.") |
| 170 | + def test_factorize(self, data_for_grouping): |
| 171 | + super().test_factorize(data_for_grouping) |
| 172 | + |
| 173 | + @pytest.mark.skip(reason="BigQuery does not allow group by a JSON-type column.") |
| 174 | + def test_factorize_equivalence(self, data_for_grouping): |
| 175 | + super().test_factorize_equivalence(data_for_grouping) |
| 176 | + |
| 177 | + @pytest.mark.skip(reason="BigQuery does not allow sort by a JSON-type column.") |
| 178 | + def test_argsort(self, data_for_sorting): |
| 179 | + super().test_argsort(data_for_sorting) |
| 180 | + |
| 181 | + @pytest.mark.skip(reason="BigQuery does not allow sort by a JSON-type column.") |
| 182 | + def test_argmin_argmax(self, data_for_sorting): |
| 183 | + super().test_argmin_argmax(data_for_sorting) |
| 184 | + |
| 185 | + @pytest.mark.skip(reason="BigQuery does not allow sort by a JSON-type column.") |
| 186 | + def test_sort_values(self, data_for_sorting): |
| 187 | + super().test_sort_values(data_for_sorting) |
| 188 | + |
| 189 | + @pytest.mark.skip(reason="BigQuery does not allow sort by a JSON-type column.") |
| 190 | + def test_sort_values_frame(self, data_for_sorting): |
| 191 | + super().test_sort_values_frame(data_for_sorting) |
| 192 | + |
| 193 | + |
| 194 | +class TestJSONArrayMissing(base.BaseMissingTests): |
| 195 | + @pytest.mark.xfail(reason="Setting a dict as a scalar") |
| 196 | + def test_fillna_series(self): |
| 197 | + """We treat dictionaries as a mapping in fillna, not a scalar.""" |
| 198 | + super().test_fillna_series() |
| 199 | + |
| 200 | + @pytest.mark.xfail(reason="Setting a dict as a scalar") |
| 201 | + def test_fillna_frame(self): |
| 202 | + """We treat dictionaries as a mapping in fillna, not a scalar.""" |
| 203 | + super().test_fillna_frame() |
| 204 | + |
| 205 | + |
| 206 | +@pytest.mark.skip(reason="BigQuery JSON does not allow Arithmetic Ops.") |
| 207 | +class TestJSONArrayArithmeticOps(base.BaseArithmeticOpsTests): |
| 208 | + pass |
| 209 | + |
| 210 | + |
| 211 | +class TestJSONArrayComparisonOps(base.BaseComparisonOpsTests): |
| 212 | + def test_compare_array(self, data, comparison_op, request): |
| 213 | + if comparison_op.__name__ not in ["eq", "ne"]: |
| 214 | + mark = pytest.mark.xfail(reason="Comparison methods not implemented") |
| 215 | + request.applymarker(mark) |
| 216 | + super().test_compare_array(data, comparison_op) |
| 217 | + |
| 218 | + def test_compare_scalar(self, data, comparison_op, request): |
| 219 | + if comparison_op.__name__ not in ["eq", "ne"]: |
| 220 | + mark = pytest.mark.xfail(reason="Comparison methods not implemented") |
| 221 | + request.applymarker(mark) |
| 222 | + super().test_compare_scalar(data, comparison_op) |
| 223 | + |
| 224 | + def _cast_pointwise_result(self, op_name: str, obj, other, pointwise_result): |
| 225 | + dtype = typing.cast(pd.StringDtype, tm.get_dtype(obj)) |
| 226 | + if op_name in ["__add__", "__radd__"]: |
| 227 | + cast_to = dtype |
| 228 | + else: |
| 229 | + cast_to = "boolean[pyarrow]" # type: ignore[assignment] |
| 230 | + return pointwise_result.astype(cast_to) |
| 231 | + |
| 232 | + |
| 233 | +class TestJSONArrayUnaryOps(base.BaseUnaryOpsTests): |
| 234 | + pass |
| 235 | + |
| 236 | + |
| 237 | +class TestJSONArrayPrinting(base.BasePrintingTests): |
| 238 | + pass |
| 239 | + |
| 240 | + |
| 241 | +class TestJSONArrayReduce(base.BaseReduceTests): |
| 242 | + pass |
| 243 | + |
| 244 | + |
| 245 | +class TestJSONArrayReshaping(base.BaseReshapingTests): |
| 246 | + @pytest.mark.skip(reason="2D support not implemented for JSONArray") |
| 247 | + def test_transpose(self, data): |
| 248 | + super().test_transpose(data) |
| 249 | + |
| 250 | + @pytest.mark.xfail( |
| 251 | + reason="`to_numpy` returns serialized JSON, " |
| 252 | + + "while `__getitem__` returns JSON objects." |
| 253 | + ) |
| 254 | + def test_transpose_frame(self, data): |
| 255 | + # `DataFrame.T` calls `to_numpy` to get results. |
| 256 | + super().test_transpose_frame(data) |
| 257 | + |
| 258 | + |
| 259 | +class TestJSONArraySetitem(base.BaseSetitemTests): |
| 260 | + # Patching `[....] * len()` to base.BaseSetitemTests because pandas' internals |
| 261 | + # has trouble setting sequences of values into scalar positions. |
| 262 | + |
| 263 | + @pytest.mark.parametrize( |
| 264 | + "idx", |
| 265 | + [[0, 1, 2], pd.array([0, 1, 2], dtype="Int64"), np.array([0, 1, 2])], |
| 266 | + ids=["list", "integer-array", "numpy-array"], |
| 267 | + ) |
| 268 | + def test_setitem_integer_array(self, data, idx, box_in_series): |
| 269 | + arr = data[:5].copy() |
| 270 | + expected = data.take([0, 0, 0, 3, 4]) |
| 271 | + |
| 272 | + if box_in_series: |
| 273 | + arr = pd.Series(arr) |
| 274 | + expected = pd.Series(expected) |
| 275 | + |
| 276 | + # Use `[arr[0]] * len()` instead of passing `arr[0]` directly to the super method. |
| 277 | + arr[idx] = [arr[0]] * len(arr[idx]) |
| 278 | + tm.assert_equal(arr, expected) |
| 279 | + |
| 280 | + @pytest.mark.parametrize( |
| 281 | + "mask", |
| 282 | + [ |
| 283 | + np.array([True, True, True, False, False]), |
| 284 | + pd.array([True, True, True, False, False], dtype="boolean"), |
| 285 | + pd.array([True, True, True, pd.NA, pd.NA], dtype="boolean"), |
| 286 | + ], |
| 287 | + ids=["numpy-array", "boolean-array", "boolean-array-na"], |
| 288 | + ) |
| 289 | + def test_setitem_mask(self, data, mask, box_in_series): |
| 290 | + arr = data[:5].copy() |
| 291 | + expected = arr.take([0, 0, 0, 3, 4]) |
| 292 | + if box_in_series: |
| 293 | + arr = pd.Series(arr) |
| 294 | + expected = pd.Series(expected) |
| 295 | + # Use `[data[0]] * len()` instead of passing `data[0]` directly to the super method. |
| 296 | + arr[mask] = [data[0]] * len(arr[mask]) |
| 297 | + tm.assert_equal(expected, arr) |
| 298 | + |
| 299 | + def test_setitem_loc_iloc_slice(self, data): |
| 300 | + arr = data[:5].copy() |
| 301 | + s = pd.Series(arr, index=["a", "b", "c", "d", "e"]) |
| 302 | + expected = pd.Series(data.take([0, 0, 0, 3, 4]), index=s.index) |
| 303 | + |
| 304 | + result = s.copy() |
| 305 | + # Use `[data[0]] * len()` instead of passing `data[0]` directly to the super method. |
| 306 | + result.iloc[:3] = [data[0]] * len(result.iloc[:3]) |
| 307 | + tm.assert_equal(result, expected) |
| 308 | + |
| 309 | + result = s.copy() |
| 310 | + result.loc[:"c"] = [data[0]] * len(result.loc[:"c"]) |
| 311 | + tm.assert_equal(result, expected) |
| 312 | + |
| 313 | + def test_setitem_slice(self, data, box_in_series): |
| 314 | + arr = data[:5].copy() |
| 315 | + expected = data.take([0, 0, 0, 3, 4]) |
| 316 | + if box_in_series: |
| 317 | + arr = pd.Series(arr) |
| 318 | + expected = pd.Series(expected) |
| 319 | + |
| 320 | + # Use `[data[0]] * 3` instead of passing `data[0]` directly to the super method. |
| 321 | + arr[:3] = [data[0]] * 3 |
| 322 | + tm.assert_equal(arr, expected) |
| 323 | + |
| 324 | + @pytest.mark.xfail(reason="only integer scalar arrays can be converted") |
| 325 | + def test_setitem_2d_values(self, data): |
| 326 | + super().test_setitem_2d_values(data) |
| 327 | + |
| 328 | + @pytest.mark.xfail( |
| 329 | + reason="`to_numpy` returns serialized JSON, " |
| 330 | + + "while `__getitem__` returns JSON objects." |
| 331 | + ) |
| 332 | + def test_setitem_frame_2d_values(self, data): |
| 333 | + super().test_setitem_frame_2d_values(data) |
| 334 | + |
| 335 | + @pytest.mark.parametrize("setter", ["loc", None]) |
| 336 | + def test_setitem_mask_broadcast(self, data, setter): |
| 337 | + ser = pd.Series(data) |
| 338 | + mask = np.zeros(len(data), dtype=bool) |
| 339 | + mask[:2] = True |
| 340 | + |
| 341 | + if setter: # loc |
| 342 | + target = getattr(ser, setter) |
| 343 | + else: # __setitem__ |
| 344 | + target = ser |
| 345 | + |
| 346 | + # Use `[data[10]] * len()` instead of passing `data[10]` directly to the super method. |
| 347 | + target[mask] = [data[10]] * len(target[mask]) |
| 348 | + assert ser[0] == data[10] |
| 349 | + assert ser[1] == data[10] |
| 350 | + |
| 351 | + @pytest.mark.xfail(reason="eq not implemented for <class 'dict'>") |
| 352 | + def test_setitem_mask_boolean_array_with_na(self, data, box_in_series): |
| 353 | + super().test_setitem_mask_boolean_array_with_na(data, box_in_series) |
| 354 | + |
| 355 | + @pytest.mark.skip(reason="2D support not implemented for JSONArray") |
| 356 | + def test_setitem_preserves_views(self, data): |
| 357 | + super().test_setitem_preserves_views(data) |
| 358 | + |
| 359 | + |
| 360 | +class TestJSONArrayDim2Compat(base.Dim2CompatTests): |
| 361 | + pass |
0 commit comments