-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_test.py
More file actions
2157 lines (1875 loc) · 78 KB
/
get_test.py
File metadata and controls
2157 lines (1875 loc) · 78 KB
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
get_test.py -- Comprehensive end-to-end test suite for the `get` CLI.
Sections (188 test cases total):
A info_help -- version / help / get get / intro / license
B boolean_options -- 8 booleans x {true,false,default}
C integer_options -- 7 integers x {pos,zero,disabled,default}
D string_options -- url / model / system-prompt set/clear/reset
E command_pattern -- default / disabled / custom / dangerous / reset
F key_and_config -- key set/clear isolation, config --reset, fields
G invalid_inputs -- malformed CLI arguments, missing values, types
H cache_log_mgmt -- clean/display/unset for cache and log stores
I instance_queries -- real LLM queries with ground-truth validation
J agent_queries -- real tool-invoking agent queries
K cache_behaviour -- threshold / force / hit-timing / unset / expiry
L param_interactions -- model/timeout/max-rounds/system-prompt/pattern
M missing_config -- key/url/model absence
Z teardown -- full configuration restore and diff
Usage:
python get_test.py --key <API_KEY> [--url URL] [--model MODEL]
[--skip-llm] [--only A,B,...] [--stop-on-fail]
[--verbose]
Assumes `get` is installed and on $PATH.
"""
from __future__ import annotations
import argparse
import getpass
import os
import platform
import re
import shlex
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import (Any, Callable, Dict, Iterable, List, Optional, Tuple)
# =============================================================================
# CONSTANTS & ANSI
# =============================================================================
ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
BOOL_OPTIONS = [
"manual-confirm", "double-check", "instance", "log",
"hide-process", "cache", "vivid", "external-display",
]
INT_OPTIONS_DEFAULTS = {
"timeout": "300",
"max-token": "20480",
"max-rounds": "3",
"cache-expiry": "30",
"cache-max-entries": "1000",
"cache-trigger-threshold": "1",
"log-max-entries": "1000",
}
STRING_OPTIONS = ["url", "model", "system-prompt"]
class C:
R = "\033[0m"
BLD = "\033[1m"
DIM = "\033[2m"
RED = "\033[31m"
GRN = "\033[32m"
YEL = "\033[33m"
BLU = "\033[34m"
MAG = "\033[35m"
CYA = "\033[36m"
if not sys.stdout.isatty():
for _k in list(vars(C)):
if not _k.startswith("_"):
setattr(C, _k, "")
def strip_ansi(s: str) -> str:
"""Remove ANSI colour/cursor escapes."""
return ANSI_RE.sub("", s or "")
# =============================================================================
# LOGGER / OUTPUT
# =============================================================================
VERBOSE = False
def _c(colour: str, msg: str) -> str:
return f"{colour}{msg}{C.R}"
def log_hdr(title: str) -> None:
bar = "=" * 72
print(f"\n{C.BLD}{C.CYA}{bar}")
print(f" {title}")
print(f"{bar}{C.R}")
def log_sub(title: str) -> None:
print(f"\n{C.BLD}{C.BLU}-- {title}{C.R}")
def log_pass(name: str, detail: str = "") -> None:
tag = _c(C.GRN, "PASS")
extra = f" {C.DIM}{detail}{C.R}" if detail else ""
print(f" [{tag}] {name}{extra}")
def log_fail(name: str, reason: str = "") -> None:
tag = _c(C.RED, "FAIL")
extra = f" {C.DIM}-- {reason}{C.R}" if reason else ""
print(f" [{tag}] {name}{extra}")
def log_skip(name: str, reason: str = "") -> None:
tag = _c(C.YEL, "SKIP")
extra = f" {C.DIM}-- {reason}{C.R}" if reason else ""
print(f" [{tag}] {name}{extra}")
def log_info(msg: str) -> None:
print(f" {_c(C.DIM, msg)}")
def log_debug(msg: str) -> None:
if VERBOSE:
print(f" {_c(C.DIM, msg)}")
# =============================================================================
# ENVIRONMENT GROUND TRUTH
# =============================================================================
#
# The test suite prefers to verify the LLM's answers against values the test
# process can compute locally (hostname, cwd, user, etc.). This makes the
# suite mostly deterministic: if the LLM / tool actually worked, the
# local ground truth will appear somewhere in the output.
@dataclass(frozen=True)
class EnvFacts:
hostname: str
short_host: str
username: str
cwd: str
cwd_basename: str
home: str
platform_name: str # 'linux' | 'darwin' | 'windows'
py_major_minor: str # e.g. '3.12'
py_major: str # e.g. '3'
uname_release: str
year: str
ipv4_candidates: Tuple[str, ...]
@classmethod
def detect(cls) -> "EnvFacts":
hn = socket.gethostname()
sh = hn.split(".")[0]
try:
user = getpass.getuser()
except Exception:
user = os.environ.get("USER") or os.environ.get("USERNAME") or ""
cwd = os.getcwd()
home = os.path.expanduser("~")
plt = platform.system().lower()
vi = sys.version_info
ips: List[str] = []
try:
for fam, *_rest, sa in socket.getaddrinfo(
socket.gethostname(), None):
if fam == socket.AF_INET and sa[0] not in ips:
ips.append(sa[0])
except socket.gaierror:
pass
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0.2)
s.connect(("10.255.255.255", 1))
probe = s.getsockname()[0]
s.close()
if probe not in ips:
ips.append(probe)
except OSError:
pass
return cls(
hostname=hn,
short_host=sh,
username=user,
cwd=cwd,
cwd_basename=os.path.basename(cwd) or cwd,
home=home,
platform_name=plt,
py_major_minor=f"{vi.major}.{vi.minor}",
py_major=str(vi.major),
uname_release=platform.release(),
year=str(datetime.now().year),
ipv4_candidates=tuple(ips),
)
FACTS = EnvFacts.detect()
# =============================================================================
# PROCESS RUNNER
# =============================================================================
@dataclass
class RunResult:
argv: List[str]
returncode: int
stdout: str
stderr: str
elapsed: float
@property
def out_plain(self) -> str:
return strip_ansi(self.stdout)
@property
def err_plain(self) -> str:
return strip_ansi(self.stderr)
@property
def all_plain(self) -> str:
return self.out_plain + "\n" + self.err_plain
@property
def ok(self) -> bool:
return self.returncode == 0
def run_get(*args: str, timeout: int = 60,
stdin: Optional[str] = None,
env_extra: Optional[Dict[str, str]] = None) -> RunResult:
"""Run `get` with the given arguments."""
argv = ["get", *args]
log_debug("$ " + " ".join(shlex.quote(a) for a in argv))
env = os.environ.copy()
if env_extra:
env.update(env_extra)
t0 = time.time()
try:
proc = subprocess.run(
argv,
capture_output=True,
text=True,
timeout=timeout,
input=stdin,
encoding="utf-8",
errors="replace",
env=env,
)
dt = time.time() - t0
return RunResult(argv, proc.returncode, proc.stdout or "",
proc.stderr or "", dt)
except subprocess.TimeoutExpired as te:
dt = time.time() - t0
return RunResult(argv, 124,
(te.stdout or b"").decode(errors="replace")
if isinstance(te.stdout, bytes) else (te.stdout or ""),
(te.stderr or b"").decode(errors="replace")
if isinstance(te.stderr, bytes) else (te.stderr or ""),
dt)
except FileNotFoundError:
print(_c(C.RED, "fatal: 'get' binary not found on PATH"),
file=sys.stderr)
sys.exit(2)
# =============================================================================
# PARSERS (config / cache / log)
# =============================================================================
KV_LINE_RE = re.compile(r"^\s*([\w\-]+)\s*=\s*(.*?)\s*$")
def parse_keyvalues(text: str) -> Dict[str, str]:
"""Parse `key = value` lines from stripped stdout."""
result: Dict[str, str] = {}
for raw in strip_ansi(text).splitlines():
m = KV_LINE_RE.match(raw)
if m:
k, v = m.group(1), m.group(2)
result[k.strip()] = v.rstrip()
return result
def get_config() -> Dict[str, str]:
r = run_get("config", timeout=20)
if not r.ok:
raise RuntimeError(f"`get config` failed: {r.err_plain!r}")
return parse_keyvalues(r.stdout)
def get_config_field(name: str) -> str:
r = run_get("config", f"--{name}", timeout=20)
if not r.ok:
return "<ERROR>"
d = parse_keyvalues(r.stdout)
return d.get(name, "")
def get_cache_info() -> Dict[str, str]:
r = run_get("cache", timeout=20)
if not r.ok:
return {}
return parse_keyvalues(r.stdout)
def get_log_info() -> Dict[str, str]:
r = run_get("log", timeout=20)
if not r.ok:
return {}
return parse_keyvalues(r.stdout)
def cache_entries_count() -> int:
info = get_cache_info()
try:
return int(info.get("entries", "-1"))
except ValueError:
return -1
def log_entries_count() -> int:
info = get_log_info()
try:
return int(info.get("entries", "-1"))
except ValueError:
return -1
# =============================================================================
# CONFIG MANAGER (backup / restore)
# =============================================================================
@dataclass
class ConfigManager:
"""Wrapper around `get set` / `get config` for test orchestration."""
backup: Dict[str, str] = field(default_factory=dict)
def snapshot(self) -> None:
self.backup = dict(get_config())
log_info(f"backed up {len(self.backup)} configuration options")
def set(self, opt: str, *values: str) -> bool:
r = run_get("set", opt, *values, timeout=20)
return r.ok
def clear(self, opt: str) -> bool:
r = run_get("set", opt, timeout=20)
return r.ok
def value(self, opt: str) -> str:
return get_config_field(opt)
def restore(self) -> List[str]:
"""Best-effort restore; returns list of fields that could not be
fully restored."""
diffs: List[str] = []
current = dict(get_config())
for k, v in self.backup.items():
if k == "key":
continue # not restorable (encrypted write-only store)
if k == "command-pattern":
if "built-in" in v:
self.clear("command-pattern")
elif "disabled" in v.lower() or v == "":
self.set("command-pattern", "")
else:
self.set("command-pattern", v)
continue
if k == "system-prompt":
if v == "":
self.clear("system-prompt")
else:
self.set("system-prompt", v)
continue
if current.get(k) != v:
self.set(k, v)
for k, v in self.backup.items():
if k == "key":
continue
now = get_config_field(k)
if now != v and k not in ("command-pattern", "system-prompt"):
diffs.append(f"{k}: was={v!r} now={now!r}")
return diffs
# =============================================================================
# STATS / REGISTRY
# =============================================================================
@dataclass
class Stats:
passed: int = 0
failed: int = 0
skipped: int = 0
section: str = ""
failures: List[Tuple[str, str, str]] = field(default_factory=list)
def pass_(self, name: str, detail: str = "") -> None:
self.passed += 1
log_pass(name, detail)
def fail(self, name: str, reason: str = "") -> None:
self.failed += 1
self.failures.append((self.section, name, reason))
log_fail(name, reason)
if STOP_ON_FAIL:
raise SystemExit(self._summary_then_exit_code())
def skip(self, name: str, reason: str = "") -> None:
self.skipped += 1
log_skip(name, reason)
def _summary_then_exit_code(self) -> int:
summarize(self)
return 1 if self.failed else 0
STOP_ON_FAIL = False
# =============================================================================
# ASSERTION HELPERS
# =============================================================================
def a_eq(stats: Stats, name: str, got: Any, expected: Any,
detail: str = "") -> bool:
if got == expected:
stats.pass_(name, detail or f"= {expected!r}")
return True
stats.fail(name, f"got={got!r} expected={expected!r}")
return False
def a_ne(stats: Stats, name: str, got: Any, not_expected: Any) -> bool:
if got != not_expected:
stats.pass_(name, f"!= {not_expected!r}")
return True
stats.fail(name, f"got={got!r} should differ from {not_expected!r}")
return False
def a_contains(stats: Stats, name: str, haystack: str,
needle: str, *, case_insensitive: bool = False) -> bool:
h = haystack.lower() if case_insensitive else haystack
n = needle.lower() if case_insensitive else needle
if n in h:
stats.pass_(name, f"contains {needle!r}")
return True
short = haystack.strip().replace("\n", "\\n")[:140]
stats.fail(name, f"missing {needle!r}; saw {short!r}")
return False
def a_contains_any(stats: Stats, name: str, haystack: str,
needles: Iterable[str],
*, case_insensitive: bool = False) -> bool:
h = haystack.lower() if case_insensitive else haystack
for n in needles:
if (n.lower() if case_insensitive else n) in h:
stats.pass_(name, f"contains {n!r}")
return True
short = haystack.strip().replace("\n", "\\n")[:140]
stats.fail(name,
f"none of {list(needles)!r} in output; saw {short!r}")
return False
def a_not_contains(stats: Stats, name: str, haystack: str,
needle: str, *, case_insensitive: bool = False) -> bool:
h = haystack.lower() if case_insensitive else haystack
n = needle.lower() if case_insensitive else needle
if n not in h:
stats.pass_(name, f"absent {needle!r}")
return True
stats.fail(name, f"unexpectedly found {needle!r}")
return False
def a_regex(stats: Stats, name: str, haystack: str,
pattern: str, *, flags: int = 0) -> bool:
if re.search(pattern, haystack, flags):
stats.pass_(name, f"~/{pattern}/")
return True
short = haystack.strip().replace("\n", "\\n")[:140]
stats.fail(name, f"no match for /{pattern}/; saw {short!r}")
return False
def a_exit_ok(stats: Stats, name: str, r: RunResult) -> bool:
if r.ok:
stats.pass_(name, f"exit=0 ({r.elapsed:.1f}s)")
return True
snippet = r.err_plain.strip().replace("\n", "\\n")[:140]
stats.fail(name, f"exit={r.returncode} err={snippet!r}")
return False
def a_exit_nonzero(stats: Stats, name: str, r: RunResult) -> bool:
if not r.ok:
stats.pass_(name, f"exit={r.returncode}")
return True
stats.fail(name, "unexpected exit 0")
return False
def a_cfg_eq(stats: Stats, name: str, opt: str, expected: str) -> bool:
got = get_config_field(opt)
if got == expected:
stats.pass_(name, f"{opt} = {expected!r}")
return True
stats.fail(name, f"{opt}: got={got!r} expected={expected!r}")
return False
def a_cfg_contains(stats: Stats, name: str, opt: str,
needle: str) -> bool:
got = get_config_field(opt)
if needle in got:
stats.pass_(name, f"{opt} ~ {needle!r}")
return True
stats.fail(name, f"{opt}: {needle!r} not in {got!r}")
return False
# =============================================================================
# GLOBAL TEST ARGUMENTS
# =============================================================================
ARGS: Any = None # populated in main()
def _apply_test_preset(cm: ConfigManager, args) -> None:
"""Baseline configuration for tests that need to run LLM queries."""
cm.set("key", args.key)
if args.url:
cm.set("url", args.url)
if args.model:
cm.set("model", args.model)
cm.set("double-check", "false")
cm.set("manual-confirm", "false")
cm.set("hide-process", "true")
cm.set("vivid", "false")
cm.set("log", "true")
cm.set("cache", "true")
# =============================================================================
# =============================================================================
# S E C T I O N A : INFO & HELP
# =============================================================================
# =============================================================================
def section_info_help(stats: Stats) -> None:
stats.section = "A"
log_hdr("SECTION A -- info & help surfaces")
# A-1 version
log_sub("A.1 version")
r = run_get("version")
a_exit_ok(stats, "A01 get version exits 0", r)
if r.ok:
ver = r.out_plain.strip()
a_regex(stats, "A02 version matches X.Y(.Z)", ver,
r"\d+\.\d+")
a_not_contains(stats, "A03 version has no stack trace",
ver, "traceback", case_insensitive=True)
# A-2 help variants
log_sub("A.2 help / --help / -h")
for i, cmd in enumerate(["help", "--help", "-h"], start=4):
r = run_get(cmd)
a_exit_ok(stats, f"A{i:02d} `get {cmd}` exits 0", r)
if r.ok:
text = r.out_plain.lower()
a_contains(stats, f"A{i + 3:02d} `get {cmd}` mentions usage",
text, "usage")
# A-10 usage mentions at least several subcommands
r = run_get("help")
text = r.out_plain.lower()
for idx, kw in enumerate(["set", "config", "cache", "log"], start=10):
a_contains(stats, f"A{idx:02d} help mentions `{kw}`", text, kw)
# A-14 get get all fields
log_sub("A.3 `get get` self metadata")
r = run_get("get")
a_exit_ok(stats, "A14 `get get` exits 0", r)
if r.ok:
low = r.out_plain.lower()
for idx, kw in enumerate(["name", "version", "author",
"license", "github"], start=15):
a_contains(stats, f"A{idx:02d} `get get` has {kw}", low, kw)
# A-20..A-23 individual meta flags
for idx, (flag, check) in enumerate([
("--intro", lambda s: len(s.strip()) > 5),
("--version", lambda s: re.search(r"\d+\.\d+", s)),
("--license", lambda s: "agpl" in s.lower()
or "gpl" in s.lower()
or "mit" in s.lower()),
("--github", lambda s: "github.com" in s.lower()),
], start=20):
r = run_get("get", flag)
if r.ok and check(r.out_plain):
stats.pass_(f"A{idx:02d} `get get {flag}` content ok")
else:
stats.fail(f"A{idx:02d} `get get {flag}`",
f"exit={r.returncode} out={r.out_plain[:80]!r}")
# A-24 unknown meta flag
r = run_get("get", "--totally-unknown-flag")
a_exit_nonzero(stats, "A24 unknown meta flag fails", r)
# =============================================================================
# S E C T I O N B : BOOLEAN OPTIONS
# =============================================================================
def section_boolean_options(stats: Stats) -> None:
stats.section = "B"
log_hdr("SECTION B -- boolean options roundtrip")
cm = ConfigManager() # local manager; we only call set/clear
idx = 1
for opt in BOOL_OPTIONS:
log_sub(f"B.{opt}")
prev = get_config_field(opt)
for value in ("true", "false"):
ok_ = cm.set(opt, value)
if not ok_:
stats.fail(f"B{idx:02d} set {opt}={value} exit 0",
"non-zero exit")
idx += 1
continue
stats.pass_(f"B{idx:02d} set {opt}={value} exit 0")
idx += 1
a_cfg_eq(stats, f"B{idx:02d} readback {opt}",
opt, value)
idx += 1
# restore to previous value (should not be 'default' notion)
if prev in ("true", "false"):
cm.set(opt, prev)
# =============================================================================
# S E C T I O N C : INTEGER OPTIONS
# =============================================================================
def section_integer_options(stats: Stats) -> None:
stats.section = "C"
log_hdr("SECTION C -- integer options (int / disabled / default)")
cm = ConfigManager()
idx = 1
for opt, default_val in INT_OPTIONS_DEFAULTS.items():
log_sub(f"C.{opt}")
prev = get_config_field(opt)
# positive int
cm.set(opt, "42")
a_cfg_eq(stats, f"C{idx:02d} set {opt}=42", opt, "42")
idx += 1
# disabled ("false")
cm.set(opt, "false")
a_cfg_eq(stats, f"C{idx:02d} disable {opt}",
opt, "false")
idx += 1
# reset to default (omit value)
cm.clear(opt)
a_cfg_eq(stats, f"C{idx:02d} reset {opt} default",
opt, default_val)
idx += 1
# restore user value
if prev and prev != default_val:
cm.set(opt, prev)
# =============================================================================
# S E C T I O N D : STRINGS
# =============================================================================
def section_string_options(stats: Stats) -> None:
stats.section = "D"
log_hdr("SECTION D -- string options (url / model / system-prompt)")
cm = ConfigManager()
prev_url = get_config_field("url")
prev_model = get_config_field("model")
prev_sp = get_config_field("system-prompt")
# D.url
log_sub("D.url")
cm.set("url", "https://example.test/v1")
a_cfg_eq(stats, "D01 url roundtrip",
"url", "https://example.test/v1")
cm.set("url", "http://localhost:8080/api/v1")
a_cfg_eq(stats, "D02 url alt roundtrip",
"url", "http://localhost:8080/api/v1")
cm.set("url", prev_url)
a_cfg_eq(stats, "D03 url restore", "url", prev_url)
# D.model
log_sub("D.model")
cm.set("model", "test-model-xyz-1")
a_cfg_eq(stats, "D04 model roundtrip", "model", "test-model-xyz-1")
cm.set("model", "another/model-v2")
a_cfg_eq(stats, "D05 model roundtrip with slash",
"model", "another/model-v2")
cm.set("model", prev_model)
a_cfg_eq(stats, "D06 model restore", "model", prev_model)
# D.system-prompt
log_sub("D.system-prompt")
sp1 = "You are a terse assistant. Reply concisely."
cm.set("system-prompt", sp1)
a_cfg_eq(stats, "D07 system-prompt roundtrip",
"system-prompt", sp1)
sp2 = "Multiple words including punctuation: apostrophes' and \"quotes\"."
cm.set("system-prompt", sp2)
a_cfg_eq(stats, "D08 system-prompt punctuation",
"system-prompt", sp2)
cm.clear("system-prompt")
a_cfg_eq(stats, "D09 system-prompt clear",
"system-prompt", "")
if prev_sp:
cm.set("system-prompt", prev_sp)
# =============================================================================
# S E C T I O N E : COMMAND-PATTERN
# =============================================================================
def section_command_pattern(stats: Stats) -> None:
stats.section = "E"
log_hdr("SECTION E -- command-pattern semantics")
cm = ConfigManager()
prev = get_config_field("command-pattern")
# E-1 built-in default when value omitted
cm.clear("command-pattern")
v = get_config_field("command-pattern")
ok_builtin = "built-in" in v.lower() and ("\\b" in v or r"\b" in v)
if ok_builtin:
stats.pass_("E01 command-pattern default = built-in regex")
else:
stats.fail("E01 command-pattern default", f"got={v!r}")
# E-2 disabled when empty string
cm.set("command-pattern", "")
v = get_config_field("command-pattern")
if "disabled" in v.lower():
stats.pass_("E02 command-pattern \"\" => disabled")
else:
stats.fail("E02 command-pattern disabled", f"got={v!r}")
# E-3 custom pattern roundtrip
cm.set("command-pattern", r"\bmydanger\b")
v = get_config_field("command-pattern")
if r"\bmydanger\b" in v:
stats.pass_("E03 command-pattern custom roundtrip")
else:
stats.fail("E03 command-pattern custom", f"got={v!r}")
# E-4 very permissive / weak pattern still accepted
r = run_get("set", "command-pattern", "^ls$")
a_exit_ok(stats, "E04 weak pattern accepted", r)
# E-5 regex with pipe alternation
alt = r"\b(rm|dd|mkfs)\b"
cm.set("command-pattern", alt)
a_cfg_contains(stats, "E05 alternation pattern", "command-pattern", alt)
# E-6 invalid regex still probably rejected OR still stored — we only
# require the CLI does not crash
r = run_get("set", "command-pattern", "[unbalanced")
if r.returncode in (0, 1, 2):
stats.pass_("E06 malformed pattern handled without crash",
f"exit={r.returncode}")
else:
stats.fail("E06 malformed pattern crash", f"exit={r.returncode}")
# restore
if "built-in" in prev.lower():
cm.clear("command-pattern")
elif "disabled" in prev.lower():
cm.set("command-pattern", "")
else:
# best-effort: strip tags if the "value" shown includes decoration
m = re.search(r"(\\b.*\\b)", prev)
if m:
cm.set("command-pattern", m.group(1))
else:
cm.clear("command-pattern")
# =============================================================================
# S E C T I O N F : KEY & CONFIG
# =============================================================================
def section_key_and_config(stats: Stats) -> None:
stats.section = "F"
log_hdr("SECTION F -- key storage and config view")
cm = ConfigManager()
# F.1 key set does not leak
log_sub("F.1 key isolation")
cm.set("key", ARGS.key)
shown = get_config_field("key")
if "set" in shown.lower() and ARGS.key not in shown:
stats.pass_("F01 `config --key` says 'set' without leaking value")
else:
stats.fail("F01 key leak guard", f"shown={shown!r}")
# F.2 clear key
cm.clear("key")
shown = get_config_field("key")
if "not set" in shown.lower() or "unset" in shown.lower():
stats.pass_("F02 cleared key shows 'not set'")
else:
stats.fail("F02 cleared key state", f"shown={shown!r}")
# F.3 re-apply
cm.set("key", ARGS.key)
shown = get_config_field("key")
if "set" in shown.lower():
stats.pass_("F03 re-applied key -> shown 'set'")
else:
stats.fail("F03 re-apply key", f"shown={shown!r}")
# F.4 config shows many fields
log_sub("F.2 config view")
cfg = get_config()
a_eq(stats, "F04 config has >= 16 fields",
len(cfg) >= 16, True, detail=f"count={len(cfg)}")
# F.5-F.10 each known key present
for idx, opt in enumerate(
["url", "model", "timeout", "max-token",
"cache-expiry", "log"], start=5):
if opt in cfg:
stats.pass_(f"F{idx:02d} config has `{opt}`")
else:
stats.fail(f"F{idx:02d} config missing `{opt}`", repr(cfg))
# F.11 reset
log_sub("F.3 config --reset")
cm.set("timeout", "777")
cm.set("max-token", "11111")
r = run_get("config", "--reset")
a_exit_ok(stats, "F11 `config --reset` exit 0", r)
a_cfg_eq(stats, "F12 timeout back to default",
"timeout", INT_OPTIONS_DEFAULTS["timeout"])
a_cfg_eq(stats, "F13 max-token back to default",
"max-token", INT_OPTIONS_DEFAULTS["max-token"])
# F.14 unknown --xxx
r = run_get("config", "--totally-unknown-opt")
a_exit_nonzero(stats, "F14 unknown config flag fails", r)
# reapply test credentials since reset wiped them
_apply_test_preset(cm, ARGS)
# =============================================================================
# S E C T I O N G : INVALID INPUTS
# =============================================================================
def section_invalid_inputs(stats: Stats) -> None:
stats.section = "G"
log_hdr("SECTION G -- invalid CLI input")
# G-01 bool with non-boolean value
cases = [
("G01 bool non-bool value",
["set", "double-check", "maybe"]),
("G02 bool empty-string odd value",
["set", "instance", "?"]),
("G03 int non-numeric",
["set", "timeout", "abc"]),
("G04 int negative",
["set", "timeout", "-5"]),
("G05 int float",
["set", "timeout", "3.14"]),
("G06 int with unit",
["set", "cache-expiry", "30d"]),
("G07 int overflow-ish",
["set", "max-token", "999999999999999999999"]),
("G08 unknown option name",
["set", "nosuch-opt", "x"]),
("G09 set missing option name",
["set"]),
("G10 unknown top-level subcommand",
["no-such-command"]),
("G11 query + --model with no value",
["what is two plus two", "--model"]),
("G12 query + --timeout with no value",
["what is two plus two", "--timeout"]),
("G13 query + --timeout not a number",
["what is two plus two", "--timeout", "notanumber"]),
("G14 cache --unset missing arg",
["cache", "--unset"]),
("G15 set url missing value would be clear — allowed; "
"but set with unknown flag should fail",
["set", "--no-such-flag"]),
("G16 config --key value (flag does not take value)",
["config", "--key", "should-not-accept"]),
("G17 get get unknown flag",
["get", "--no-such-meta"]),
("G18 integer option 'true' not allowed",
["set", "timeout", "true"]),
]
for name, argv in cases:
r = run_get(*argv, timeout=15)
a_exit_nonzero(stats, name, r)
# G-19 empty query string treated as missing (permissive: may succeed
# printing help or fail; we accept either but require no crash)
r = run_get("", timeout=15)
if r.returncode in (0, 1, 2):
stats.pass_(f"G19 empty query handled (exit {r.returncode})")
else:
stats.fail("G19 empty query crash", f"exit={r.returncode}")
# =============================================================================
# S E C T I O N H : CACHE / LOG MGMT
# =============================================================================
def section_cache_log_mgmt(stats: Stats) -> None:
stats.section = "H"
log_hdr("SECTION H -- cache/log management commands")
# H.1 cache display
log_sub("H.1 cache display")
r = run_get("cache")
a_exit_ok(stats, "H01 `cache` exits 0", r)
info = parse_keyvalues(r.stdout)
for idx, k in enumerate(
["cache", "entries", "max-entries", "file"], start=2):
if k in info:
stats.pass_(f"H{idx:02d} cache display has `{k}`")
else:
stats.fail(f"H{idx:02d} cache display missing `{k}`",
f"fields={list(info)}")
# H.6 cache --clean
r = run_get("cache", "--clean")
a_exit_ok(stats, "H06 `cache --clean` exits 0", r)
n = cache_entries_count()
a_eq(stats, "H07 entries after --clean", n, 0)
# H.8 cache --unset non-existent query
r = run_get("cache", "--unset", "this-query-does-not-exist-xxx")
a_exit_ok(stats, "H08 `cache --unset` on unknown query exits 0", r)
n2 = cache_entries_count()
a_eq(stats, "H09 entries unchanged after no-op unset", n2, 0)
# H.10 log display
log_sub("H.2 log display")
r = run_get("log")
a_exit_ok(stats, "H10 `log` exits 0", r)
info = parse_keyvalues(r.stdout)
for idx, k in enumerate(
["log", "entries", "file", "file-size"], start=11):
if k in info:
stats.pass_(f"H{idx:02d} log display has `{k}`")
else:
stats.fail(f"H{idx:02d} log display missing `{k}`",
f"fields={list(info)}")
# H.15 log --clean
r = run_get("log", "--clean")
a_exit_ok(stats, "H15 `log --clean` exits 0", r)
a_eq(stats, "H16 log entries after clean",
log_entries_count(), 0)
# H.17 log display file path points to a real file
info = get_log_info()
fpath = info.get("file", "")
if fpath and Path(fpath).exists():