77 lines
2.4 KiB
Python
77 lines
2.4 KiB
Python
"""Tests for JSON converter."""
|
|
|
|
import json
|
|
import pytest
|
|
import tempfile
|
|
import os
|
|
|
|
from config_convert.converters import JSONConverter
|
|
|
|
|
|
class TestJSONConverter:
|
|
@pytest.fixture
|
|
def converter(self):
|
|
return JSONConverter()
|
|
|
|
def test_loads_valid_json(self, converter):
|
|
data = '{"name": "test", "value": 123}'
|
|
result = converter.loads(data)
|
|
assert result == {"name": "test", "value": 123}
|
|
|
|
def test_loads_nested_json(self, converter):
|
|
data = '{"database": {"host": "localhost", "port": 5432}}'
|
|
result = converter.loads(data)
|
|
assert result == {"database": {"host": "localhost", "port": 5432}}
|
|
|
|
def test_loads_array_json(self, converter):
|
|
data = '{"tags": ["a", "b", "c"]}'
|
|
result = converter.loads(data)
|
|
assert result == {"tags": ["a", "b", "c"]}
|
|
|
|
def test_dumps_basic_dict(self, converter):
|
|
data = {"name": "test", "value": 123}
|
|
result = converter.dumps(data)
|
|
parsed = json.loads(result)
|
|
assert parsed == data
|
|
|
|
def test_dumps_with_custom_indent(self, converter):
|
|
data = {"name": "test"}
|
|
result = converter.dumps(data, indent=4)
|
|
assert "\n" in result
|
|
|
|
def test_dumps_nested_dict(self, converter):
|
|
data = {"database": {"host": "localhost", "port": 5432}}
|
|
result = converter.dumps(data)
|
|
parsed = json.loads(result)
|
|
assert parsed == data
|
|
|
|
def test_roundtrip(self, converter):
|
|
original = {"name": "test", "version": "1.0.0", "enabled": True, "count": 42}
|
|
dumped = converter.dumps(original)
|
|
loaded = converter.loads(dumped)
|
|
assert loaded == original
|
|
|
|
def test_load_file(self, converter, temp_file, sample_json):
|
|
gen = temp_file(json.dumps(sample_json), suffix=".json")
|
|
path = next(gen)
|
|
try:
|
|
result = converter.load(path)
|
|
assert result == sample_json
|
|
finally:
|
|
import os
|
|
os.unlink(path)
|
|
|
|
def test_dump_file(self, converter, temp_dir, sample_json):
|
|
path = tempfile.mktemp(suffix=".json")
|
|
try:
|
|
converter.dump(sample_json, path)
|
|
result = json.loads(open(path).read())
|
|
assert result == sample_json
|
|
finally:
|
|
if os.path.exists(path):
|
|
os.unlink(path)
|
|
|
|
def test_invalid_json_raises(self, converter):
|
|
with pytest.raises(json.JSONDecodeError):
|
|
converter.loads("{invalid json}")
|