From 278d3e937e92392425621639309435463918cc5f Mon Sep 17 00:00:00 2001 From: omicron Date: Mon, 19 Oct 2026 01:23:21 +0200 Subject: [PATCH] Add to_dict and to_file API to SiteConfig --- omicron/ssg/config.py | 13 +++++++++ tests/unit/test_config.py | 57 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/omicron/ssg/config.py b/omicron/ssg/config.py index 7b104e0..4f7387f 100644 --- a/omicron/ssg/config.py +++ b/omicron/ssg/config.py @@ -99,3 +99,16 @@ class SiteConfig: items_per_page=items_per_page, template=template, ) + + def to_dict(self) -> dict[str, str | int]: + return { + "name": self.name, + "template": self.template, + "items_per_page": self.items_per_page, + "base_url": f"{self.origin}{self.base_dir}", + } + + def to_file(self, path: Path) -> None: + log.debug("Writing config file %s", path) + with open(path, "w") as f: + yaml.safe_dump(self.to_dict(), f, default_flow_style=False) diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index c1ae224..4a48603 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -58,6 +58,48 @@ def test_from_dict_full(): assert config.base_dir == Path("/blog") +def test_to_dict(): + config = SiteConfig( + name="My Site", + origin="http://example.com", + base_dir=Path("/blog"), + items_per_page=42, + template="plain", + ) + + assert config.to_dict() == { + "name": "My Site", + "template": "plain", + "items_per_page": 42, + "base_url": "http://example.com/blog", + } + + +def test_to_dict_default_base_url(): + config = SiteConfig( + name="My Site", + origin="", + base_dir=Path("/"), + items_per_page=DEFAULT_ITEMS_PER_PAGE, + template="plain", + ) + + assert config.to_dict()["base_url"] == "/" + + +def test_to_dict_round_trip(): + original = SiteConfig.from_dict( + { + "name": "My Site", + "template": "plain", + "base_url": "http://example.com/blog", + "items_per_page": 42, + } + ) + + assert SiteConfig.from_dict(original.to_dict()) == original + + MISSING = object() @@ -128,6 +170,21 @@ def test_from_file_full(tmp_path): assert config.base_dir == Path("/blog") +def test_to_file(tmp_path): + path = tmp_path / "config.yml" + config = SiteConfig( + name="My Site", + origin="http://example.com", + base_dir=Path("/blog"), + items_per_page=42, + template="plain", + ) + + config.to_file(path) + + assert SiteConfig.from_file(path) == config + + def test_from_file_missing(tmp_path): path = tmp_path / "config.yml"