Files
slic/tests/test_utils_jsonext.py
T
tligui_y e16bc21a81
Run CI Tests / test (push) Successful in 29s
Add tests/test_utils_jsonext.py
2025-07-25 16:10:28 +02:00

72 lines
2.2 KiB
Python

import pytest
import sys
import os
from pathlib import Path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from slic.utils.jsonext import *
@pytest.mark.parametrize(
"input_obj, expected",
[
# Numpy array case
(np.array([1, 2, 3]), [1, 2, 3]),
# Numpy scalar case
(np.int32(42), 42),
# Complex number case
(complex(1, -1), {"real": 1.0, "imag": -1.0}),
# Path object case
(Path("/tmp/file.txt"), "/tmp/file.txt"),
# Set case
({3, 1, 2}, [1, 2, 3]),
# Dict case
({"a": np.array([10, 20])}, {"a": [10, 20]}),
# Dict case
({"c": complex(2, 3)}, {"c": {"real": 2.0, "imag": 3.0}}),
# Mixte
(
{
"nested": {
"arr": np.array([[10, 20], [30, 40]]),
"complex_num": complex(-1, 5),
"files": [Path("/file1"), Path("/file2")],
"set_values": {100, 200},
"inner": {"num": np.int16(7)},
}
},
{
"nested": {
"arr": [[10, 20], [30, 40]],
"complex_num": {"real": -1.0, "imag": 5.0},
"files": ["/file1", "/file2"],
"set_values": [100, 200], # sets become sorted lists
"inner": {"num": 7},
}
}
),
]
)
def test_json_validate_save_load(tmp_path, input_obj, expected):
# Validate the object by serializing and deserializing it with ExtendedJSONEncoder
validated = json_validate(input_obj)
# Assert that the validated object matches the expected JSON-compatible structure
assert validated == expected
# Save the original input object to a JSON file + test json_save()
filepath = tmp_path / "test.json"
json_save(input_obj, filepath)
# Confirm the file was created
assert filepath.exists()
# Load the JSON file back into a Python object + test json_load()
loaded = json_load(filepath)
# Assert the loaded object matches the expected JSON-compatible structure
assert loaded == expected