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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
|
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
#
# llamachat - a small native chat client for a local llama.cpp router
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
"""Self-checks for the non-GUI logic. Run: ./test_llamachat.py"""
import json
import os
import sys
import tempfile
from pathlib import Path
# Some checks need PySide6, so reuse the launcher's venv discovery rather
# than requiring the venv interpreter to be named on the command line.
sys.path.insert(0, str(Path(__file__).resolve().parent))
import llamachat_venv # noqa: E402
llamachat_venv.reexec(__file__)
from llamachat import backend, config, db
PRESETS_SAMPLE = """\
version = 1
; A preset whose mmproj line is commented out -> not vision capable.
#[Disabled-Model]
#ngl = all
#mmproj = /models/disabled/mmproj.gguf
[vision-model]
ngl = all
ctx-size = 32768
mmproj = /models/vision/mmproj.gguf
[text-model]
ngl = all
ctx-size = 16384
; --- Multimodal ---
; WARNING: eats VRAM.
#mmproj = /models/text/mmproj.gguf
[no-ctx-model]
ngl = all
"""
def test_presets():
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "presets.ini"
path.write_text(PRESETS_SAMPLE)
presets = config.parse_presets(path)
# A '#'-commented section must not appear at all.
assert "Disabled-Model" not in presets, presets.keys()
assert set(presets) == {"vision-model", "text-model", "no-ctx-model"}
# mmproj present -> vision; commented out -> not vision.
assert presets["vision-model"].vision is True
assert presets["text-model"].vision is False
assert presets["no-ctx-model"].vision is False
assert presets["vision-model"].ctx_size == 32768
assert presets["text-model"].ctx_size == 16384
assert presets["no-ctx-model"].ctx_size == 4096 # default
# 32768 tokens * 3.5 chars * 0.5 -> 57344 chars
assert presets["vision-model"].char_budget(0.5, 3.5) == 57344
# A missing file yields no presets rather than raising.
assert config.parse_presets(Path("/nonexistent/presets.ini")) == {}
print("ok presets parsing")
def test_real_presets():
"""The user's actual file, if present, must classify as expected."""
path = Path("/etc/llama-server/presets.ini")
if not path.exists():
print("skip real presets (file absent)")
return
presets = config.parse_presets(path)
assert "gemma-4-12B-it" in presets
assert presets["gemma-4-12B-it"].vision is True
# Qwen3.5-9B has its mmproj line commented out with '#'.
if "Qwen3.5-9B" in presets:
assert presets["Qwen3.5-9B"].vision is False
print("ok real presets classification")
def test_fts_query_escaping():
# Bare punctuation and FTS keywords must not become query syntax.
assert db._fts_query("hello world") == '"hello" "world"'
assert db._fts_query("foo AND bar") == '"foo" "AND" "bar"'
assert db._fts_query('say "hi"') == '"say" """hi"""'
assert db._fts_query("-flag") == '"-flag"'
assert db._fts_query(" ") == ""
print("ok fts query escaping")
def test_history_roundtrip():
with tempfile.TemporaryDirectory() as tmp:
history = db.History(Path(tmp) / "test.db")
chat = history.create_session("chat", "vision-model", "About otters")
history.add_message(chat, "user", "Tell me about otters please")
history.add_message(chat, "assistant", "Otters are semiaquatic mammals")
shot = history.create_session("oneshot", "text-model", "Capital city")
history.add_message(shot, "user", "What is the capital of Italy")
rows = history.messages(chat)
assert len(rows) == 2
assert rows[0]["role"] == "user"
# Newest session first.
recent = history.recent_sessions()
assert len(recent) == 2
assert recent[0]["id"] == shot
# FTS finds content across sessions, and punctuation cannot break it.
assert len(history.search("otters")) == 2
assert len(history.search("capital")) == 1
assert history.search("zebra") == []
assert history.search('otters "AND') == [] # must not raise
# Attachments survive with enough detail to reconstruct context.
message_id = history.add_message(chat, "user", "look at this")
history.add_attachment(
message_id, "/home/u/pic.png", "image",
mime="image/png", size=1234, sha256="abc", thumb=b"\xff\xd8jpeg",
)
saved = history.attachments(message_id)
assert len(saved) == 1
assert saved[0]["path"] == "/home/u/pic.png"
assert saved[0]["kind"] == "image"
assert saved[0]["thumb"] == b"\xff\xd8jpeg"
# Editing a streamed message keeps the FTS index in step.
streamed = history.add_message(chat, "assistant", "")
history.update_message(streamed, "the platypus is unusual")
assert len(history.search("platypus")) == 1
# Deleting a session takes its messages out of search too.
history.delete_session(chat)
assert history.search("otters") == []
assert len(history.recent_sessions()) == 1
history.close()
print("ok history roundtrip")
def test_attachment_truncation():
with tempfile.TemporaryDirectory() as tmp:
big = Path(tmp) / "big.py"
big.write_text("x" * 5000)
att = backend.load_attachment(big, char_budget=1000)
assert att.kind == "text"
assert att.truncated is True
assert len(att.text) == 1000
assert att.size == 5000
assert len(att.sha256) == 64
small = Path(tmp) / "small.txt"
small.write_text("hello")
att = backend.load_attachment(small, char_budget=1000)
assert att.truncated is False
assert att.text == "hello"
odd = Path(tmp) / "thing.bin"
odd.write_bytes(b"\x00\x01")
try:
backend.load_attachment(odd, char_budget=1000)
except backend.BackendError:
pass
else:
raise AssertionError("unsupported type should raise")
print("ok attachment truncation")
def test_classify():
assert backend.classify(Path("a.py")) == "text"
assert backend.classify(Path("a.SlackBuild")) == "text"
assert backend.classify(Path("a.png")) == "image"
assert backend.classify(Path("a.jpg")) == "image"
assert backend.classify(Path("a.so")) == "unknown"
print("ok file classification")
def test_sse_parsing():
line = 'data: {"choices":[{"delta":{"content":"hi"}}]}'
assert backend._parse_sse_line(line) == ("content", "hi")
# Reasoning arrives in its own field, which is what lets the UI keep
# thinking and reply apart without parsing <think> tags.
think = 'data: {"choices":[{"delta":{"reasoning_content":"hmm"}}]}'
assert backend._parse_sse_line(think) == ("reasoning", "hmm")
assert backend._parse_sse_line("data: [DONE]") == backend.DONE
assert backend._parse_sse_line(": keepalive") is None
assert backend._parse_sse_line("") is None
assert backend._parse_sse_line("data: {bad json") is None
# An opening delta of {'role': 'assistant', 'content': None} carries
# nothing to render and must not be mistaken for end-of-stream.
opening = backend._parse_sse_line(
'data: {"choices":[{"delta":{"role":"assistant","content":null}}]}'
)
assert opening is None
assert opening != backend.DONE
print("ok sse parsing")
def test_reasoning_storage():
with tempfile.TemporaryDirectory() as tmp:
history = db.History(Path(tmp) / "r.db")
sid = history.create_session("chat", "m", "t")
# A streamed reply is inserted empty, then filled in once done.
mid = history.add_message(sid, "assistant", "")
history.update_message(mid, "51", "the model's private thinking")
row = history.messages(sid)[0]
assert row["content"] == "51"
assert row["reasoning"] == "the model's private thinking"
# Reasoning must stay out of the search index, or thinking text
# would drown out real hits.
assert history.search("51") != []
assert history.search("private") == []
# Omitting the argument leaves stored reasoning untouched.
history.update_message(mid, "52")
assert history.messages(sid)[0]["reasoning"] == (
"the model's private thinking"
)
history.close()
print("ok reasoning storage")
def test_migration_adds_reasoning():
"""A database created before the reasoning column must still open."""
import sqlite3
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "old.db"
conn = sqlite3.connect(path)
conn.executescript(
"CREATE TABLE sessions (id INTEGER PRIMARY KEY, mode TEXT,"
" title TEXT, model TEXT, created_at INTEGER, updated_at INTEGER);"
"CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id INTEGER,"
" role TEXT NOT NULL, content TEXT NOT NULL,"
" created_at INTEGER NOT NULL);"
"INSERT INTO sessions VALUES (1,'chat','old','m',0,0);"
"INSERT INTO messages VALUES (1,1,'user','older message',0);"
)
conn.commit()
conn.close()
history = db.History(path)
rows = history.messages(1)
assert rows[0]["content"] == "older message"
assert rows[0]["reasoning"] == "" # backfilled by the migration
mid = history.add_message(1, "assistant", "new")
history.update_message(mid, "new", "fresh thinking")
assert history.messages(1)[1]["reasoning"] == "fresh thinking"
history.close()
print("ok reasoning column migration")
def test_user_content():
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "code.py"
src.write_text("print(1)")
text_att = backend.load_attachment(src, 1000)
# Text only -> a plain string, file inlined before the prompt.
content = backend.build_user_content("explain", [text_att])
assert isinstance(content, str)
assert "print(1)" in content
assert content.endswith("explain")
# No attachments -> just the prompt.
assert backend.build_user_content("hi", []) == "hi"
# An image -> the multi-part array the vision API expects.
img = backend.Attachment(
path=Path("/x/a.png"), kind="image", mime="image/png",
size=1, sha256="", data_url="data:image/png;base64,AAA",
)
content = backend.build_user_content("what is this", [img])
assert isinstance(content, list)
assert content[0]["type"] == "text"
assert content[1]["type"] == "image_url"
assert content[1]["image_url"]["url"].startswith("data:image/png")
print("ok user content assembly")
def test_markdown_rendering():
"""Replies render as markdown; markup inside them stays literal."""
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
from llamachat.ui import _markdown_to_fragment
app = QApplication.instance() or QApplication([])
assert app is not None
fragment = _markdown_to_fragment(
"**bold** and *italic* and `code`\n\n"
"- a\n- b\n\n"
"| x | y |\n|---|---|\n| 1 | 2 |\n\n"
"```py\ndef f():\n pass\n```\n"
)
assert "font-weight:700" in fragment
assert "font-style:italic" in fragment
assert "<ul" in fragment
assert "<table" in fragment
assert "<pre" in fragment
# Every <pre> is tinted, since Qt emits one per line of a code block.
assert fragment.count("<pre") == fragment.count("background:rgba")
# The document wrapper must not leak into the fragment.
assert "<html" not in fragment and "<body" not in fragment
# Markup in a reply is shown, never interpreted.
hostile = _markdown_to_fragment(
'Text <b>tag</b> <img src=x onerror=alert(1)> <a href="http://bad">l</a>'
)
assert "<b>" in hostile, hostile
assert "font-weight:700" not in hostile
# The URL may appear, but only as escaped text, never as a live anchor.
assert "<a href" not in hostile
assert "<a href="http://bad">" in hostile, hostile
# A markdown link is a real anchor, so check a reply cannot forge one
# aimed at the reasoning toggle.
from llamachat.ui import REASONING_SCHEME
forged = _markdown_to_fragment(f"[click]({REASONING_SCHEME}0)")
assert f'href="{REASONING_SCHEME}' not in forged, forged
assert 'href="blocked:' in forged, forged
# Ordinary markdown links still work.
link = _markdown_to_fragment("[site](http://example.com)")
assert "http://example.com" in link
# Empty input renders nothing rather than an empty document wrapper.
assert _markdown_to_fragment("") == ""
# Partial markdown arrives constantly while streaming and must not raise.
for partial in ("```", "```py", "```py\ndef f(", "| a |", "**unclosed", "#"):
_markdown_to_fragment(partial)
print("ok markdown rendering")
def test_system_qt_theme_guard():
"""The plugin path is only borrowed when the Qt versions agree."""
import os
from llamachat.__main__ import _system_qt_version, _use_system_qt_theme
# An explicit user setting is never overridden.
saved = os.environ.get("QT_PLUGIN_PATH")
try:
os.environ["QT_PLUGIN_PATH"] = "/user/choice"
_use_system_qt_theme()
assert os.environ["QT_PLUGIN_PATH"] == "/user/choice"
finally:
if saved is None:
os.environ.pop("QT_PLUGIN_PATH", None)
else:
os.environ["QT_PLUGIN_PATH"] = saved
system = _system_qt_version()
if not system:
print("skip qt theme guard (no system Qt6 found)")
return
assert system.count(".") == 2, system
from PySide6.QtCore import qVersion
saved = os.environ.pop("QT_PLUGIN_PATH", None)
try:
_use_system_qt_theme()
chosen = os.environ.get("QT_PLUGIN_PATH")
if system == qVersion():
assert chosen, "matching Qt versions should adopt system plugins"
assert Path(chosen, "platformthemes").is_dir()
else:
assert chosen is None, (
f"must not load {system} plugins into Qt {qVersion()}"
)
finally:
if saved is None:
os.environ.pop("QT_PLUGIN_PATH", None)
else:
os.environ["QT_PLUGIN_PATH"] = saved
print("ok system qt theme guard")
def test_prompt_store():
"""Prompts are files; a preset replaces the global one."""
from llamachat import prompts
with tempfile.TemporaryDirectory() as tmp:
store = prompts.PromptStore(Path(tmp) / "prompts")
assert store.names() == []
store.ensure_default()
assert store.names() == ["default"]
assert store.path_for("default").exists()
# ensure_default must not clobber an edited global prompt.
store.save("default", "edited global")
store.ensure_default()
assert store.load("default").text == "edited global"
store.save("coding", "you write code")
store.save("terse", "be brief")
# Global first, then presets alphabetically.
assert store.names() == ["default", "coding", "terse"]
# A preset replaces the global prompt rather than adding to it.
assert store.resolve("coding") == "you write code"
assert store.resolve("") == "edited global"
assert store.resolve("default") == "edited global"
# Sentinels.
assert store.resolve(prompts.NONE) == ""
assert store.resolve(prompts.CUSTOM, "one off") == "one off"
# A preset deleted behind our back falls back rather than sending
# nothing, which would silently change the model's behaviour.
assert store.resolve("missing") == "edited global"
assert store.delete("coding") is True
assert store.names() == ["default", "terse"]
# The global prompt is the fallback for everything, so it stays.
assert store.delete("default") is False
assert "default" in store.names()
# Names become filenames, so path separators must not escape.
assert prompts.safe_name("../../etc/passwd") == "etc-passwd"
assert prompts.safe_name("/etc/passwd") == "etc-passwd"
assert prompts.safe_name("my prompt!") == "my-prompt"
for hostile in ("../escape", "a/b", "/tmp/x"):
saved = store.save(hostile, "x")
assert saved.path.parent == store.dir, saved.path
assert saved.path.resolve().parent == store.dir.resolve()
# A name that reduces to nothing is rejected rather than writing
# a dotfile called ".md".
for empty in ("..", "", "....", "///"):
assert prompts.safe_name(empty) == ""
assert store.load(empty) is None
assert store.delete(empty) is False
try:
store.path_for(empty)
except ValueError:
pass
else:
raise AssertionError(f"{empty!r} should be rejected")
print("ok prompt store")
def test_token_estimate():
"""The meter's pre-send estimate tracks message size."""
small = [{"role": "user", "content": "hi"}]
large = [{"role": "user", "content": "word " * 1000}]
assert backend.estimate_tokens([], 3.5) == 0
assert backend.estimate_tokens(small, 3.5) < 20
assert backend.estimate_tokens(large, 3.5) > 1000
# More history means a bigger prompt.
grown = large + [{"role": "assistant", "content": "reply " * 500}]
assert backend.estimate_tokens(grown, 3.5) > backend.estimate_tokens(
large, 3.5
)
# An image costs far more than its text part suggests.
with_image = [
{
"role": "user",
"content": [
{"type": "text", "text": "what is this"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAA"}},
],
}
]
assert backend.estimate_tokens(with_image, 3.5) > 500
# A silly ratio must not divide by zero.
assert backend.estimate_tokens(small, 0) > 0
print("ok token estimate")
def test_usage_parsing():
"""The final stream chunk carries the exact prompt token count."""
line = (
'data: {"choices":[],"usage":{"prompt_tokens":1234,'
'"completion_tokens":56,"total_tokens":1290}}'
)
kind, payload = backend._parse_sse_line(line)
assert kind == "usage"
stats = json.loads(payload)
assert stats["prompt_tokens"] == 1234
assert stats["total_tokens"] == 1290
# A usage-less chunk with empty choices is not mistaken for one.
assert backend._parse_sse_line('data: {"choices":[]}') is None
print("ok usage parsing")
def test_session_prompt_storage():
"""A conversation remembers the prompt it was built with."""
from llamachat import prompts
with tempfile.TemporaryDirectory() as tmp:
history = db.History(Path(tmp) / "p.db")
sid = history.create_session(
"chat", "m", "t", prompt_name="coding", prompt_custom=""
)
row = history.get_session(sid)
assert row["prompt_name"] == "coding"
assert row["prompt_custom"] == ""
history.set_prompt(sid, prompts.CUSTOM, "just this once")
row = history.get_session(sid)
assert row["prompt_name"] == prompts.CUSTOM
assert row["prompt_custom"] == "just this once"
# Defaults keep older call sites working.
plain = history.create_session("oneshot", "m", "t")
assert history.get_session(plain)["prompt_name"] == ""
history.close()
print("ok session prompt storage")
def test_prompt_column_migration():
"""A database predating the prompt columns must still open."""
import sqlite3
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "old.db"
conn = sqlite3.connect(path)
conn.executescript(
"CREATE TABLE sessions (id INTEGER PRIMARY KEY, mode TEXT,"
" title TEXT, model TEXT, created_at INTEGER, updated_at INTEGER);"
"CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id INTEGER,"
" role TEXT NOT NULL, content TEXT NOT NULL,"
" created_at INTEGER NOT NULL);"
"INSERT INTO sessions VALUES (1,'chat','old','m',0,0);"
)
conn.commit()
conn.close()
history = db.History(path)
row = history.get_session(1)
assert row["title"] == "old"
assert row["prompt_name"] == ""
assert row["prompt_custom"] == ""
history.set_prompt(1, "coding")
assert history.get_session(1)["prompt_name"] == "coding"
history.close()
print("ok prompt column migration")
def test_sidebar_toggle():
"""The history panel hides, restores its width, and persists."""
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
from llamachat import backend as _backend
from llamachat import config as _config
from llamachat.ui import ChatWindow
app = QApplication.instance() or QApplication([])
assert app is not None
with tempfile.TemporaryDirectory() as tmp:
cfg = _config.load(Path(tmp) / "config.toml")
cfg.prompts_dir = Path(tmp) / "prompts"
cfg.db_path = Path(tmp) / "t.db"
# state_path already points inside tmp, since it is derived from the
# config path, so these checks cannot touch the real saved layout.
assert cfg.state_path.parent == Path(tmp), cfg.state_path
history = db.History(cfg.db_path)
client = _backend.Client(cfg.base_url)
presets = _config.parse_presets(cfg.presets_path)
window = ChatWindow(cfg, history, client, presets)
window.resize(1000, 700)
# The shortcut must be registered on the window itself.
shortcuts = [
a.shortcut().toString()
for a in window.actions()
if not a.shortcut().isEmpty()
]
assert "Ctrl+\\" in shortcuts, shortcuts
window.show()
assert window.sidebar_visible()
assert window.sidebar_button.isChecked()
window.toggle_sidebar()
assert not window.sidebar_visible()
assert not window.sidebar_button.isChecked()
window.toggle_sidebar()
assert window.sidebar_visible()
# The width survives a hide/show rather than snapping to a default.
window.splitter.setSizes([333, 667])
app.processEvents()
window.toggle_sidebar()
window.toggle_sidebar()
assert window.sidebar_width == 333, window.sidebar_width
# Driving the button directly must take the same path.
window.sidebar_button.setChecked(False)
app.processEvents()
assert not window.sidebar_visible()
window.sidebar_button.setChecked(True)
app.processEvents()
assert window.sidebar_visible()
assert window.sidebar_width == 333, window.sidebar_width
# Hidden state and width must come back on the next start.
window.sidebar_button.setChecked(False)
window._save_layout()
restored = ChatWindow(cfg, history, client, presets)
assert not restored.sidebar_button.isChecked()
assert restored.sidebar_width == 333, restored.sidebar_width
restored.close()
window.close()
history.close()
print("ok sidebar toggle")
def test_version_matches_changelog():
"""The package version must be the newest release in the changelog."""
import re
import llamachat
assert re.fullmatch(r"\d+\.\d+\.\d+", llamachat.__version__), (
f"not semver: {llamachat.__version__}"
)
changelog = Path(__file__).resolve().parent / "CHANGELOG.md"
if not changelog.exists():
print("skip changelog check (file absent)")
return
released = re.findall(
r"^## \[(\d+\.\d+\.\d+)\]", changelog.read_text(), re.MULTILINE
)
assert released, "changelog has no released versions"
assert released[0] == llamachat.__version__, (
f"__version__ is {llamachat.__version__} but the newest changelog "
f"entry is {released[0]}"
)
print("ok version matches changelog")
def test_venv_discovery():
"""The launcher must find a venv even when it shares the system binary."""
saved = os.environ.pop("LLAMACHAT_PYTHON", None)
try:
found = llamachat_venv.find_interpreter()
current = Path(sys.executable)
other = [
c for c in llamachat_venv.CANDIDATES if c.is_file() and c != current
]
if other:
# A venv built with --system-site-packages has a bin/python3 that
# symlinks to the system interpreter. Comparing resolved paths
# would discard it as "the interpreter we are already running".
assert found is not None, (
f"a candidate exists ({other[0]}) but none was selected"
)
assert found.is_file()
else:
# Already running as the only candidate; nothing to hand over to.
assert found is None
# An explicit override wins over the search order.
os.environ["LLAMACHAT_PYTHON"] = sys.executable
chosen = llamachat_venv.find_interpreter()
# Only rejected because it is the interpreter already running.
assert chosen is None or chosen == Path(sys.executable)
os.environ["LLAMACHAT_PYTHON"] = "/nonexistent/python3"
assert llamachat_venv.find_interpreter() is None
finally:
if saved is None:
os.environ.pop("LLAMACHAT_PYTHON", None)
else:
os.environ["LLAMACHAT_PYTHON"] = saved
# reexec must be a no-op once PySide6 is importable, or it would loop.
if llamachat_venv.have_pyside():
llamachat_venv.reexec(__file__) # returns rather than exec'ing
print("ok venv discovery")
def test_config_defaults():
cfg = config.load(Path("/nonexistent/config.toml"))
assert cfg.base_url == "http://localhost:8181"
assert cfg.presets_path == Path("/etc/llama-server/presets.ini")
assert cfg.socket_path.name == "llamachat.sock"
assert cfg.db_path.name == "history.db"
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "config.toml"
path.write_text(
'base_url = "http://localhost:9999/"\ndefault_model = "m"\n'
)
cfg = config.load(path)
assert cfg.base_url == "http://localhost:9999" # trailing / stripped
assert cfg.default_model == "m"
assert cfg.request_timeout == 300 # default kept
print("ok config defaults")
if __name__ == "__main__":
test_presets()
test_real_presets()
test_fts_query_escaping()
test_history_roundtrip()
test_attachment_truncation()
test_classify()
test_sse_parsing()
test_reasoning_storage()
test_migration_adds_reasoning()
test_user_content()
test_prompt_store()
test_token_estimate()
test_usage_parsing()
test_session_prompt_storage()
test_prompt_column_migration()
test_markdown_rendering()
test_sidebar_toggle()
test_system_qt_theme_guard()
test_version_matches_changelog()
test_venv_discovery()
test_config_defaults()
print("\nall checks passed")
|