2023-08-06 12:33:41 +03:00
|
|
|
try:
|
|
|
|
from ujson import JSONDecodeError, dumps
|
|
|
|
except ImportError:
|
|
|
|
from json import dumps, JSONDecodeError
|
|
|
|
|
2023-08-06 02:25:32 +03:00
|
|
|
from pathlib import Path
|
|
|
|
from typing import Any, Union
|
|
|
|
|
|
|
|
import pytest
|
2024-12-18 15:16:37 +02:00
|
|
|
from libbot.utils import json_read, json_write
|
2023-08-06 02:25:32 +03:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"path, expected",
|
|
|
|
[
|
|
|
|
(
|
2023-08-06 03:08:02 +03:00
|
|
|
"tests/data/test.json",
|
2023-08-06 02:25:32 +03:00
|
|
|
{
|
|
|
|
"foo": "bar",
|
|
|
|
"abcdefg": ["higklmnop", {"lol": {"kek": [1.0000035, 0.2542, 1337]}}],
|
|
|
|
},
|
|
|
|
),
|
2023-08-06 03:08:02 +03:00
|
|
|
("tests/data/empty.json", {}),
|
2023-08-06 02:25:32 +03:00
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_json_read_valid(path: Union[str, Path], expected: Any):
|
|
|
|
assert await json_read(path) == expected
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"path, expected",
|
|
|
|
[
|
2023-08-06 12:33:41 +03:00
|
|
|
("tests/data/invalid.json", JSONDecodeError),
|
|
|
|
("tests/data/nonexistent.json", FileNotFoundError),
|
2023-08-06 02:25:32 +03:00
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_json_read_invalid(path: Union[str, Path], expected: Any):
|
2023-08-06 12:33:41 +03:00
|
|
|
with pytest.raises(expected):
|
|
|
|
await json_read(path)
|
2023-08-06 02:25:32 +03:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"data, path",
|
|
|
|
[
|
|
|
|
(
|
|
|
|
{
|
|
|
|
"foo": "bar",
|
|
|
|
"abcdefg": ["higklmnop", {"lol": {"kek": [1.0000035, 0.2542, 1337]}}],
|
|
|
|
},
|
2023-08-06 03:08:02 +03:00
|
|
|
"tests/data/test.json",
|
2023-08-06 02:25:32 +03:00
|
|
|
),
|
2023-08-06 03:08:02 +03:00
|
|
|
({}, "tests/data/empty.json"),
|
2023-08-06 02:25:32 +03:00
|
|
|
],
|
|
|
|
)
|
|
|
|
async def test_json_write(data: Any, path: Union[str, Path]):
|
|
|
|
await json_write(data, path)
|
|
|
|
|
|
|
|
assert Path(path).is_file()
|
|
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
|
|
assert f.read() == dumps(data, ensure_ascii=False, indent=4)
|