summaryrefslogtreecommitdiff
path: root/tests/test_config.py
blob: 5d339f89bef8a2d82de0548ed2a1648b61e27dc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
from __future__ import annotations

from pathlib import Path

import pytest

from mcp_sd15.config import ConfigError, load_config


def make_models(root: Path) -> None:
    for folder, names in {
        "checkpoints": ["base.safetensors"],
        "vae": ["vae.safetensors"],
        "lora": ["a.safetensors", "b.safetensors"],
        "controlnet": ["depth.safetensors", "pose.safetensors", "inpaint.safetensors"],
    }.items():
        destination = root / folder
        destination.mkdir(parents=True)
        for name in names:
            (destination / name).touch()


def valid_toml(root: Path) -> str:
    return f'''[model]
root = "{root.as_posix()}"
checkpoint = "base.safetensors"
vae = "vae.safetensors"
[[model.lora]]
file = "a.safetensors"
weight = 0.8
[[model.lora]]
file = "b.safetensors"
weight = -0.2
[generation]
steps = 20
cfg_scale = 6.5
scheduler = "euler_a"
default_size = "portrait_512"
[controlnet.depth]
enabled = true
model = "depth.safetensors"
preprocessor = "midas"
[controlnet.openpose]
enabled = true
model = "pose.safetensors"
[controlnet.inpaint]
enabled = true
model = "inpaint.safetensors"
[output]
enabled = true
directory = "generated"
'''


def test_loads_and_resolves_all_model_paths(tmp_path: Path) -> None:
    root = tmp_path / "models"
    make_models(root)
    path = tmp_path / "config.toml"
    path.write_text(valid_toml(root), encoding="utf-8")

    config = load_config(path)

    assert config.model.checkpoint_path() == root / "checkpoints" / "base.safetensors"
    assert config.model.vae_path() == root / "vae" / "vae.safetensors"
    assert config.model.lora_paths() == (
        root / "lora" / "a.safetensors",
        root / "lora" / "b.safetensors",
    )
    assert config.generation.default_size == "portrait_512"
    assert config.output.directory == tmp_path / "generated"
    assert config.controlnet_path("openpose_full") == root / "controlnet" / "pose.safetensors"


@pytest.mark.parametrize(
    "line, message",
    [
        ('checkpoint = "../base.safetensors"', "file name"),
        ("steps = 0", "steps"),
        ('scheduler = "dpmpp_2m"', "scheduler"),
        ('scheduler = "euler"', "scheduler"),
        ('scheduler = "unknown"', "scheduler"),
        ('default_size = "1024"', "default_size"),
        ('preprocessor = "zoe"', "preprocessor"),
    ],
)
def test_rejects_invalid_values(tmp_path: Path, line: str, message: str) -> None:
    root = tmp_path / "models"
    make_models(root)
    text = valid_toml(root)
    if line.startswith("checkpoint"):
        text = text.replace('checkpoint = "base.safetensors"', line)
    elif line.startswith("steps"):
        text = text.replace("steps = 20", line)
    elif line.startswith("scheduler"):
        text = text.replace('scheduler = "euler_a"', line)
    elif line.startswith("default_size"):
        text = text.replace('default_size = "portrait_512"', line)
    else:
        text = text.replace('preprocessor = "midas"', line)
    path = tmp_path / "bad.toml"
    path.write_text(text, encoding="utf-8")

    with pytest.raises(ConfigError, match=message):
        load_config(path)


def test_missing_model_fails_startup_validation(tmp_path: Path) -> None:
    root = tmp_path / "models"
    make_models(root)
    (root / "controlnet" / "depth.safetensors").unlink()
    path = tmp_path / "config.toml"
    path.write_text(valid_toml(root), encoding="utf-8")

    with pytest.raises(ConfigError, match=r"depth\.safetensors"):
        load_config(path)


def test_can_skip_path_checks_for_schema_only_use(tmp_path: Path) -> None:
    path = tmp_path / "config.toml"
    path.write_text(
        '[model]\nroot = "missing"\ncheckpoint = "base.safetensors"\n', encoding="utf-8"
    )
    config = load_config(path, validate_paths=False)
    assert config.model.root == (tmp_path / "missing").resolve()
    assert config.generation.scheduler == "dpmpp_2m_karras"


def test_server_defaults_to_stdio_when_omitted(tmp_path: Path) -> None:
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n',
        encoding="utf-8",
    )
    config = load_config(path, validate_paths=False)
    assert config.server.transport == "stdio"
    assert config.server.host == "127.0.0.1"
    assert config.server.port == 8000


def test_server_reads_streamable_http(tmp_path: Path) -> None:
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        '[server]\ntransport = "streamable-http"\nhost = "0.0.0.0"\nport = 9000\n',
        encoding="utf-8",
    )
    config = load_config(path, validate_paths=False)
    assert config.server.transport == "streamable-http"
    assert config.server.host == "0.0.0.0"
    assert config.server.port == 9000


@pytest.mark.parametrize(
    "transport",
    ["sse", "http", "ws", "unknown"],
)
def test_rejects_invalid_transport(tmp_path: Path, transport: str) -> None:
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        f'[server]\ntransport = "{transport}"\n',
        encoding="utf-8",
    )
    with pytest.raises(ConfigError, match="transport"):
        load_config(path, validate_paths=False)


@pytest.mark.parametrize(
    "port, message",
    [
        (0, "port"),
        (65536, "port"),
        (-1, "port"),
        ("8000", "port"),
    ],
)
def test_rejects_invalid_port(tmp_path: Path, port: str | int, message: str) -> None:
    path = tmp_path / "config.toml"
    port_literal = f'"{port}"' if isinstance(port, str) else str(port)
    path.write_text(
        f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        f'[server]\ntransport = "streamable-http"\nport = {port_literal}\n',
        encoding="utf-8",
    )
    with pytest.raises(ConfigError, match=message):
        load_config(path, validate_paths=False)


def test_rejects_empty_host(tmp_path: Path) -> None:
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        '[server]\ntransport = "streamable-http"\nhost = ""\n',
        encoding="utf-8",
    )
    with pytest.raises(ConfigError, match="host"):
        load_config(path, validate_paths=False)


def test_prompt_defaults_to_empty_when_omitted(tmp_path: Path) -> None:
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n',
        encoding="utf-8",
    )
    config = load_config(path, validate_paths=False)
    assert config.prompt.positive == ""
    assert config.prompt.negative == ""


def test_prompt_reads_files_from_root_prompts(tmp_path: Path) -> None:
    root = tmp_path / "models"
    (root / "checkpoints").mkdir(parents=True)
    (root / "checkpoints" / "base.safetensors").touch()
    (root / "prompts").mkdir()
    (root / "prompts" / "positive.txt").write_text("masterpiece, best quality", encoding="utf-8")
    (root / "prompts" / "negative.txt").write_text("low quality, blurry", encoding="utf-8")
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{root.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        '[prompt]\npositive_file = "positive.txt"\nnegative_file = "negative.txt"\n',
        encoding="utf-8",
    )
    config = load_config(path)
    assert config.prompt.positive == "masterpiece, best quality"
    assert config.prompt.negative == "low quality, blurry"


def test_prompt_rejects_path_traversal(tmp_path: Path) -> None:
    root = tmp_path / "models"
    (root / "checkpoints").mkdir(parents=True)
    (root / "checkpoints" / "base.safetensors").touch()
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{root.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        '[prompt]\npositive_file = "../escape.txt"\n',
        encoding="utf-8",
    )
    with pytest.raises(ConfigError, match="file name"):
        load_config(path, validate_paths=False)


def test_prompt_rejects_missing_file(tmp_path: Path) -> None:
    root = tmp_path / "models"
    (root / "checkpoints").mkdir(parents=True)
    (root / "checkpoints" / "base.safetensors").touch()
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{root.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        '[prompt]\npositive_file = "absent.txt"\n',
        encoding="utf-8",
    )
    with pytest.raises(ConfigError, match="prompt file"):
        load_config(path, validate_paths=False)


def test_prompt_accepts_only_positive(tmp_path: Path) -> None:
    root = tmp_path / "models"
    (root / "checkpoints").mkdir(parents=True)
    (root / "checkpoints" / "base.safetensors").touch()
    (root / "prompts").mkdir()
    (root / "prompts" / "positive.txt").write_text("masterpiece", encoding="utf-8")
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{root.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        '[prompt]\npositive_file = "positive.txt"\n',
        encoding="utf-8",
    )
    config = load_config(path)
    assert config.prompt.positive == "masterpiece"
    assert config.prompt.negative == ""


def test_generation_defaults_clip_skip_and_pad_last_block(tmp_path: Path) -> None:
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n',
        encoding="utf-8",
    )
    config = load_config(path, validate_paths=False)
    assert config.generation.clip_skip == 0
    assert config.generation.pad_last_block is False


def test_generation_reads_clip_skip_and_pad_last_block(tmp_path: Path) -> None:
    path = tmp_path / "config.toml"
    path.write_text(
        f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        "[generation]\nclip_skip = 2\npad_last_block = true\n",
        encoding="utf-8",
    )
    config = load_config(path, validate_paths=False)
    assert config.generation.clip_skip == 2
    assert config.generation.pad_last_block is True


@pytest.mark.parametrize(
    "clip_skip, message",
    [
        (-1, "clip_skip"),
        (13, "clip_skip"),
        (2.5, "clip_skip"),
        (True, "clip_skip"),
    ],
)
def test_rejects_invalid_clip_skip(
    tmp_path: Path, clip_skip: float | int | bool, message: str
) -> None:
    path = tmp_path / "config.toml"
    literal = "true" if isinstance(clip_skip, bool) else str(clip_skip)
    path.write_text(
        f'[model]\nroot = "{tmp_path.as_posix()}"\ncheckpoint = "base.safetensors"\n'
        f"[generation]\nclip_skip = {literal}\n",
        encoding="utf-8",
    )
    with pytest.raises(ConfigError, match=message):
        load_config(path, validate_paths=False)