Newer
Older
RobotCar / tests / test_json_utils.py
"""json_utils モジュールのテスト"""

from pathlib import Path

from common.json_utils import read_json, write_json


class TestWriteReadRoundtrip:
    """write_json / read_json の往復テスト"""

    def test_dict_roundtrip(self, tmp_path: Path) -> None:
        """dict を書き込んで読み込むと一致する"""
        path = tmp_path / "test.json"
        data = {"key": "value", "number": 42}
        write_json(path, data)
        assert read_json(path) == data

    def test_list_roundtrip(self, tmp_path: Path) -> None:
        """list を書き込んで読み込むと一致する"""
        path = tmp_path / "test.json"
        data = [{"a": 1}, {"b": 2}]
        write_json(path, data)
        assert read_json(path) == data

    def test_creates_parent_dir(
        self, tmp_path: Path,
    ) -> None:
        """親ディレクトリが存在しなくても自動作成される"""
        path = tmp_path / "sub" / "dir" / "test.json"
        data = {"created": True}
        write_json(path, data)
        assert path.exists()
        assert read_json(path) == data

    def test_japanese_text(self, tmp_path: Path) -> None:
        """日本語テキストが正しく保存・復元される"""
        path = tmp_path / "test.json"
        data = {"title": "テスト", "memo": "日本語メモ"}
        write_json(path, data)
        assert read_json(path) == data

    def test_overwrite(self, tmp_path: Path) -> None:
        """既存ファイルを上書きできる"""
        path = tmp_path / "test.json"
        write_json(path, {"v": 1})
        write_json(path, {"v": 2})
        assert read_json(path) == {"v": 2}