fork/mons

git clone https://git.julia.blue/fork/mons

coloursofnoiseAdd tests to cover config and extended help sections384a235

main
4.9 KiB182 linesraw
1import os
2import sys
3import typing as t
4from contextlib import contextmanager
5from dataclasses import dataclass
6from importlib import reload
7
8import click
9import pytest
10
11from mons import config
12from mons.install import Install
13
14
15@pytest.fixture(autouse=True)
16def isolated_filesystem(monkeypatch: pytest.MonkeyPatch, tmp_path):
17    """Isolate all referenced files to temp folder"""
18    user_dirs = ["config", "cache", "data"]
19    ret = dict()
20    for dir in user_dirs:
21        monkeypatch.setattr(
22            f"mons.config.PlatformDirs.user_{dir}_dir", os.path.join(tmp_path, dir)
23        )
24        ret[f"user_{dir}_dir"] = os.path.join(tmp_path, dir)
25    # reload the config module to re-assign global constants
26    reload(sys.modules["mons.config"])
27    return ret
28
29
30@pytest.fixture
31def exception_count():
32    @contextmanager
33    def context(count):
34        with pytest.raises(config.ExceptionCount) as exc_info:
35            yield exc_info
36        assert exc_info.value.count == count
37
38    yield context
39
40
41@dataclass(frozen=True)
42class Subclass:
43    subprop1: int = 321
44    default: t.Optional[int] = None
45
46
47@dataclass
48class ConfigType:
49    prop1: str
50
51    subclass: Subclass = Subclass()
52
53
54def test_dataclass_fromdict():
55    test_config = config.dataclass_fromdict(
56        {
57            "prop1": "test",
58        },
59        ConfigType,
60    )
61    assert test_config == ConfigType("test")
62
63
64def test_dataclass_fromdict_nested():
65    test_config = config.dataclass_fromdict(
66        {
67            "prop1": "test",
68            "subclass": {"subprop1": 123},
69        },
70        ConfigType,
71    )
72    assert test_config == ConfigType("test", Subclass(123, None))
73
74
75@pytest.mark.parametrize(
76    ("input, expect"),
77    [
78        ({"unknown": "test"}, (1, "Unknown key")),
79        ({"prop1": 123}, (1, "Invalid value")),
80        ({"prop1": {"invalid": "object"}}, (1, "Invalid value")),
81        ({"subclass": 123}, (1, "Expected object")),
82        ({"subclass": {"unknown": "key"}}, (1, "Unknown key")),
83        (
84            {"prop1": None, "subclass": {"unknown": "key", "subprop1": "invalid"}},
85            (3, ""),
86        ),
87        ({}, (1, "Missing required key")),
88    ],
89    ids=lambda v: v[1] or f"{v[0]} errors" if isinstance(v, tuple) else None,
90)
91def test_dataclass_fromdict_errors(exception_count, caplog, input, expect):
92    expect_count, expect_msg = expect
93    with exception_count(expect_count):
94        config.dataclass_fromdict(input, ConfigType)
95    assert expect_msg in caplog.text
96
97
98def test_wrap_config_param():
99    @config.wrap_config_param
100    def wrapped(cfg) -> None:
101        assert isinstance(cfg, config.Config)
102
103    wrapped(config.Config())
104    wrapped(config.UserInfo())
105    wrapped(click.Context(click.Command(None)))
106
107
108# mons config-specific tests
109
110
111def test_empty_config():
112    assert config.dataclass_fromdict(
113        {}, config.Config
114    ), "All fields must have default values"
115
116
117def test_save_data():
118    assert not os.path.exists(config.INSTALLS_FILE)
119    assert not os.path.exists(config.CACHE_FILE)
120
121    with config.UserInfo() as user_info:
122        user_info.installs["test_install"] = Install("test_install", "")  # type: ignore
123
124    assert os.path.exists(config.INSTALLS_FILE)
125    with open(config.INSTALLS_FILE) as file:
126        assert "test_install:" in file.read()
127
128    # install cache has not been updated, so should not be saved
129    assert not os.path.exists(config.CACHE_FILE)
130
131
132def test_save_cache():
133    assert not os.path.exists(config.CACHE_FILE)
134
135    with config.UserInfo() as user_info:
136        install = Install("test_install", "")  # type: ignore
137        # hash key specifically is checked to determine if install cache is valid
138        install.get_cache().update(
139            {
140                "hash": "0123456789abcdef",
141                "testkey": "testvalue",
142            }
143        )
144        user_info.installs["test_install"] = install
145
146    assert os.path.exists(config.CACHE_FILE)
147    with open(config.CACHE_FILE) as file:
148        assert "testkey: testvalue" in file.read()
149
150
151def test_truncate_data():
152    os.makedirs(config.CONFIG_DIR, exist_ok=True)
153    assert not os.path.exists(config.INSTALLS_FILE)
154    file_contents = """\
155test_install:
156    path: "fake/path"
157other_install:
158    path: "fake/path"
159"""
160    with open(config.INSTALLS_FILE, "w") as file:
161        file.write(file_contents)
162
163    # Data should not be truncated if not already loaded
164    with config.UserInfo() as user_info:
165        pass
166
167    with open(config.INSTALLS_FILE) as file:
168        assert file.read() == file_contents
169
170    # Updated data should be saved to file
171    with config.UserInfo() as user_info:
172        del user_info.installs["other_install"]
173
174    with open(config.INSTALLS_FILE) as file:
175        assert "other_install" not in file
176
177    # If all data removed, file should be truncated
178    with config.UserInfo() as user_info:
179        user_info.installs.clear()
180
181    with open(config.INSTALLS_FILE) as file:
182        assert not file.read()