|
13 | 13 | # limitations under the License.
|
14 | 14 |
|
15 | 15 |
|
16 |
| -import datetime as dt |
17 |
| -from typing import Optional |
| 16 | +import json |
18 | 17 |
|
19 |
| -import pandas |
20 |
| -import pandas.api.extensions |
| 18 | +import pandas as pd |
21 | 19 | import pandas.testing
|
22 |
| -import pyarrow |
23 | 20 | import pytest
|
24 | 21 |
|
25 |
| -import packaging.version |
26 |
| - |
27 | 22 | import db_dtypes
|
28 | 23 |
|
29 |
| -is_supported_version = packaging.version.Version(pandas.__version__) >= packaging.version.Version("1.5.0") |
| 24 | +# Check for minimum Pandas version. |
| 25 | +pytest.importorskip("pandas", minversion="1.5.0") |
| 26 | + |
| 27 | + |
| 28 | +# # Python data types mirroring all standard JSON types |
| 29 | +# https://json-schema.org/understanding-json-schema/reference/type |
| 30 | +JSON_DATA = { |
| 31 | + "boolean": True, |
| 32 | + "int": 100, |
| 33 | + "float": 0.98, |
| 34 | + "string": "hello world", |
| 35 | + "array": [0.1, 0.2], |
| 36 | + "dict": { |
| 37 | + "null_field": None, |
| 38 | + "order": { |
| 39 | + "items": ["book", "pen", "computer"], |
| 40 | + "total": 15.99, |
| 41 | + "address": {"street": "123 Main St", "city": "Anytown"}, |
| 42 | + }, |
| 43 | + }, |
| 44 | + "null": None, |
| 45 | +} |
| 46 | + |
| 47 | + |
| 48 | +def test_get_items(): |
| 49 | + data = db_dtypes.JSONArray._from_sequence(JSON_DATA.values()) |
| 50 | + for id, key in enumerate(JSON_DATA.keys()): |
| 51 | + if key == "null": |
| 52 | + assert pd.isna(data[id]) |
| 53 | + else: |
| 54 | + assert data[id] == JSON_DATA[key] |
| 55 | + |
| 56 | + |
| 57 | +def test_get_items_unbox_object(): |
| 58 | + data = db_dtypes.JSONArray._from_sequence([JSON_DATA["dict"]]) |
| 59 | + assert len(data[0]) == 2 |
| 60 | + |
| 61 | + assert data[0]["null_field"] is None |
| 62 | + assert data[0]["order"]["address"]["city"] == "Anytown" |
| 63 | + assert len(data[0]["order"]["items"]) == 3 |
| 64 | + assert data[0]["order"]["items"][0] == "book" |
| 65 | + |
| 66 | + with pytest.raises(KeyError): |
| 67 | + data[0]["unknown"] |
| 68 | + |
| 69 | + |
| 70 | +def test_to_numpy(): |
| 71 | + s = pd.Series(db_dtypes.JSONArray._from_sequence(JSON_DATA.values())) |
| 72 | + data = s.to_numpy() |
| 73 | + for id, key in enumerate(JSON_DATA.keys()): |
| 74 | + if key == "null": |
| 75 | + assert pd.isna(data[id]) |
| 76 | + else: |
| 77 | + assert data[id] == json.dumps(JSON_DATA[key], sort_keys=True) |
| 78 | + |
30 | 79 |
|
31 |
| -@pytest.mark.skipif(not is_supported_version, reason="requires Pandas 1.5.0 and above") |
32 |
| -def test_constructor_from_sequence(): |
33 |
| - json_obj = [0, "str", {"a": 0, "b": 1}] |
34 |
| - data = db_dtypes.JSONArray._from_sequence(json_obj) |
| 80 | +def test_deterministic_json_serialization(): |
| 81 | + x = {"a": 0, "b": 1} |
| 82 | + y = {"b": 1, "a": 0} |
| 83 | + data = db_dtypes.JSONArray._from_sequence([x]) |
| 84 | + assert y in data |
0 commit comments