|
| 1 | +import json |
1 | 2 | from dataclasses import dataclass |
| 3 | +from pathlib import Path |
2 | 4 | from typing import Any |
3 | 5 |
|
4 | | -from py_app_dev.core.config import BaseConfigDictMixin, deep_merge, merge_configs |
| 6 | +import pytest |
| 7 | + |
| 8 | +from py_app_dev.core.config import ( |
| 9 | + BaseConfigDictMixin, |
| 10 | + BaseConfigJsonMixin, |
| 11 | + deep_merge, |
| 12 | + merge_configs, |
| 13 | +) |
5 | 14 |
|
6 | 15 |
|
7 | 16 | @dataclass |
@@ -47,3 +56,56 @@ def test_merge_configs_override_none_value(): |
47 | 56 | assert merged.name == "final", "Name should be taken from override" |
48 | 57 | assert merged.nested == {"k": 1}, "Nested should not be overridden by None" |
49 | 58 | assert merged.retries == 0, "Retries should be taken from the default value in override" |
| 59 | + |
| 60 | + |
| 61 | +# ---------- BaseConfigJsonMixin tests ---------- |
| 62 | + |
| 63 | + |
| 64 | +@dataclass |
| 65 | +class SampleJsonConfig(BaseConfigJsonMixin): |
| 66 | + name: str = "" |
| 67 | + count: int = 0 |
| 68 | + label: str | None = None |
| 69 | + metadata: dict[str, Any] | None = None |
| 70 | + |
| 71 | + |
| 72 | +def test_json_mixin_roundtrip_file(tmp_path: Path) -> None: |
| 73 | + original = SampleJsonConfig(name="svc", count=3, metadata={"env": "prod"}) |
| 74 | + file = tmp_path / "config.json" |
| 75 | + |
| 76 | + original.to_json_file(file) |
| 77 | + restored = SampleJsonConfig.from_json_file(file) |
| 78 | + |
| 79 | + assert restored == original |
| 80 | + |
| 81 | + |
| 82 | +def test_json_mixin_from_file_json(tmp_path: Path) -> None: |
| 83 | + file = tmp_path / "config.json" |
| 84 | + file.write_text(json.dumps({"name": "app", "count": 7})) |
| 85 | + |
| 86 | + loaded = SampleJsonConfig.from_file(file) |
| 87 | + |
| 88 | + assert loaded.name == "app" |
| 89 | + assert loaded.count == 7 |
| 90 | + |
| 91 | + |
| 92 | +def test_json_mixin_from_file_unsupported(tmp_path: Path) -> None: |
| 93 | + file = tmp_path / "config.yaml" |
| 94 | + file.write_text("name: oops") |
| 95 | + |
| 96 | + with pytest.raises(ValueError, match=r"\.yaml"): |
| 97 | + SampleJsonConfig.from_file(file) |
| 98 | + |
| 99 | + |
| 100 | +def test_json_mixin_omit_none() -> None: |
| 101 | + cfg = SampleJsonConfig(name="x", label=None, metadata=None) |
| 102 | + parsed = json.loads(cfg.to_json_string()) |
| 103 | + |
| 104 | + assert "label" not in parsed |
| 105 | + assert "metadata" not in parsed |
| 106 | + |
| 107 | + |
| 108 | +def test_json_mixin_to_string() -> None: |
| 109 | + cfg = SampleJsonConfig(name="a", count=1) |
| 110 | + |
| 111 | + assert cfg.to_string() == cfg.to_json_string() |
0 commit comments