|
1
|
|
|
# SPDX-FileCopyrightText: Copyright 2020-2023, Contributors to typed-dfs |
|
2
|
|
|
# SPDX-PackageHomePage: https://github.com/dmyersturnbull/typed-dfs |
|
3
|
|
|
# SPDX-License-Identifier: Apache-2.0 |
|
4
|
|
|
import inspect |
|
5
|
|
|
|
|
6
|
|
|
import numpy as np |
|
7
|
|
|
import pytest |
|
8
|
|
|
from pocketutils.tools.json_tools import JsonTools, NanInfHandling |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
class TestJsonTools: |
|
12
|
|
|
def test_preserve_inf(self): |
|
13
|
|
|
matrix = np.zeros((2, 2)) |
|
14
|
|
|
# assert (JsonTools.prepare(matrix) == matrix.astype(str)).all() |
|
15
|
|
|
matrix = np.asarray([[2, float("inf")], [float("inf"), 2]]) |
|
16
|
|
|
# assert (JsonTools.preserve_inf(matrix) == matrix.astype(str)).all() |
|
17
|
|
|
# TODO: nested tests |
|
18
|
|
|
|
|
19
|
|
|
def test_new_default(self): |
|
20
|
|
|
class X: |
|
21
|
|
|
def __str__(self): |
|
22
|
|
|
return "from-str" |
|
23
|
|
|
|
|
24
|
|
|
def __repr__(self): |
|
25
|
|
|
return "from-repr" |
|
26
|
|
|
|
|
27
|
|
|
default = JsonTools.new_default() |
|
28
|
|
|
x = default(None) |
|
29
|
|
|
assert x is None |
|
30
|
|
|
assert default(X()) == "from-str" |
|
31
|
|
|
default = JsonTools.new_default(last=repr) |
|
32
|
|
|
assert default(X()) == "from-repr" |
|
33
|
|
|
|
|
34
|
|
|
def fixer(obj): |
|
35
|
|
|
if isinstance(obj, X): |
|
36
|
|
|
return "gotcha!" |
|
37
|
|
|
|
|
38
|
|
|
default = JsonTools.new_default(fixer) |
|
39
|
|
|
assert default(X()) == "gotcha!" |
|
40
|
|
|
|
|
41
|
|
|
def test_to_json(self): |
|
42
|
|
|
assert JsonTools.encoder().as_str("hi") == '"hi"\n' |
|
43
|
|
|
assert JsonTools.encoder().as_str(["hi", "bye"]) == '[\n "hi",\n "bye"\n]\n' |
|
44
|
|
|
data = { |
|
45
|
|
|
"list": [ |
|
46
|
|
|
{ |
|
47
|
|
|
"numbers": { |
|
48
|
|
|
1: np.asarray([float("inf"), 0]), |
|
49
|
|
|
2: np.asarray([1, 1]), |
|
50
|
|
|
3: np.half(float("inf")), |
|
51
|
|
|
4: np.half(float("-inf")), |
|
52
|
|
|
5: float("inf"), |
|
53
|
|
|
6: float("-inf"), |
|
54
|
|
|
7: 1, |
|
55
|
|
|
}, |
|
56
|
|
|
}, |
|
57
|
|
|
], |
|
58
|
|
|
} |
|
59
|
|
|
encoder = JsonTools.encoder( |
|
60
|
|
|
inf_handling=NanInfHandling.convert_to_str, |
|
61
|
|
|
nan_handling=NanInfHandling.convert_to_str, |
|
62
|
|
|
) |
|
63
|
|
|
x = encoder.as_str(data) |
|
64
|
|
|
assert ( |
|
65
|
|
|
x |
|
66
|
|
|
== inspect.cleandoc( |
|
67
|
|
|
""" |
|
68
|
|
|
{ |
|
69
|
|
|
"list": [ |
|
70
|
|
|
{ |
|
71
|
|
|
"numbers": { |
|
72
|
|
|
"1": [ |
|
73
|
|
|
"inf", |
|
74
|
|
|
"0.0" |
|
75
|
|
|
], |
|
76
|
|
|
"2": [ |
|
77
|
|
|
1, |
|
78
|
|
|
1 |
|
79
|
|
|
], |
|
80
|
|
|
"3": "inf", |
|
81
|
|
|
"4": "-inf", |
|
82
|
|
|
"5": "inf", |
|
83
|
|
|
"6": "-inf", |
|
84
|
|
|
"7": 1 |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
] |
|
88
|
|
|
} |
|
89
|
|
|
""", |
|
90
|
|
|
) |
|
91
|
|
|
+ "\n" |
|
92
|
|
|
) |
|
93
|
|
|
|
|
94
|
|
|
|
|
95
|
|
|
if __name__ == "__main__": |
|
96
|
|
|
pytest.main() |
|
97
|
|
|
|