forked from Jason-Vaughan/TangleBrain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
615 lines (546 loc) · 28.8 KB
/
Copy pathtest_cli.py
File metadata and controls
615 lines (546 loc) · 28.8 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
"""Tests for the CLI end-to-end wiring (tanglebrain/cli.py).
The adapter is mocked, so these tests verify the roster → select → build → run → print path
without touching the network.
"""
from __future__ import annotations
import io
import os
import tempfile
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from unittest.mock import MagicMock, patch
from tanglebrain.adapters import AdapterError
from tanglebrain.cli import main, run_once, run_once_stream
from tanglebrain.measurement import read_records
from tanglebrain.roster import packaged_roster_path
from tanglebrain.selector import SelectionError
# A self-contained roster (a local entry + a 'claude' sub) for tests that pin --model/--local to a
# known id. Pinned via roster_path so these tests never depend on the ambient
# ~/.config/tanglebrain/roster.yaml: the packaged example ships local-only since the sub entries
# became opt-in/commented (R2a), so an unpinned model="claude" only resolves on a machine that
# happens to have a real roster — which is exactly the non-hermetic gap CI caught.
_PINNED_ROSTER_YAML = """\
- id: local-ollama
tier: local
invoke: {kind: openai-compat, base_url: "http://localhost:11434/v1", model: "llama3.2"}
cost: free
good_at: [grunt]
- id: claude
tier: sub
invoke: {kind: cli, cmd: ["claude"], parse: claude-json}
cost: subscription
good_at: [reasoning]
can_orchestrate: true
"""
def _pinned_roster(test: unittest.TestCase) -> str:
"""Write the pinned local+claude roster to a temp file and return its path (auto-cleaned)."""
handle = tempfile.NamedTemporaryFile("w", suffix=".yaml", delete=False)
handle.write(_PINNED_ROSTER_YAML)
handle.close()
test.addCleanup(os.unlink, handle.name)
return handle.name
class RunOnceTest(unittest.TestCase):
def setUp(self):
# Redirect the usage log into a temp dir so metering side-effects stay hermetic
# (run_once now records each routed task) and never touch the real ~/.cache.
self.tmp = tempfile.mkdtemp()
self._env = patch.dict(os.environ, {"TANGLEBRAIN_STATE_DIR": self.tmp}, clear=False)
self._env.start()
self.addCleanup(self._env.stop)
def _records(self):
return read_records(Path(self.tmp) / "usage.jsonl")
def test_default_routes_through_router(self):
# The default (no flags) routes through the frontier-first Router (not local-first).
fake_router = MagicMock()
fake_router.route.return_value = "routed reply"
with patch("tanglebrain.cli.load_roster"), patch(
"tanglebrain.cli.Router", return_value=fake_router
):
self.assertEqual(run_once("hello"), "routed reply")
fake_router.route.assert_called_once()
def test_local_flag_forces_local_tier(self):
fake_adapter = MagicMock()
fake_adapter.run.return_value = "local reply"
with patch("tanglebrain.cli.build_adapter", return_value=fake_adapter) as build:
# Pin to the packaged example so the asserted local id is machine-independent.
self.assertEqual(
run_once("hello", local=True, roster_path=str(packaged_roster_path())), "local reply"
)
selected = build.call_args.args[0]
self.assertEqual(selected.tier, "local")
self.assertEqual(selected.id, "local-ollama")
def test_max_tokens_threaded_through_local(self):
fake_adapter = MagicMock()
fake_adapter.run.return_value = "x"
with patch("tanglebrain.cli.build_adapter", return_value=fake_adapter):
run_once("hello", local=True, max_tokens=256)
opts = fake_adapter.run.call_args.args[1]
# opts now always carries a minted task_id (for delegate-tree linkage), plus max_tokens here.
self.assertEqual(opts.get("max_tokens"), 256)
self.assertIsInstance(opts.get("task_id"), str)
def test_no_max_tokens_still_passes_task_id_opts_local(self):
fake_adapter = MagicMock()
fake_adapter.run.return_value = "x"
with patch("tanglebrain.cli.build_adapter", return_value=fake_adapter):
run_once("hello", local=True)
opts = fake_adapter.run.call_args.args[1]
# With no max_tokens, opts is no longer None — it still carries the minted task_id.
self.assertNotIn("max_tokens", opts)
self.assertIsInstance(opts.get("task_id"), str)
def test_model_routes_to_named_entry(self):
# --model selects a specific roster entry (here, a sub) instead of local-first.
fake_adapter = MagicMock()
fake_adapter.run.return_value = "claude reply"
with patch("tanglebrain.cli.build_adapter", return_value=fake_adapter) as build:
self.assertEqual(
run_once("hello", model="claude", roster_path=_pinned_roster(self)), "claude reply"
)
selected = build.call_args.args[0]
self.assertEqual(selected.id, "claude")
self.assertEqual(selected.tier, "sub")
def test_unknown_model_raises_selection_error(self):
with self.assertRaises(SelectionError):
run_once("hello", model="no-such-model")
def test_model_to_paid_api_entry_is_inert_with_gate_off(self):
# The boundary the user actually touches: `--model <api-id>` must NOT reach a paid endpoint
# while billing is gated off. This exercises the REAL build_adapter -> load_settings()
# default-load (packaged settings.yaml ships the gate off), no mocks on the gate.
roster_yaml = (
"- id: gpt5\n tier: api\n"
" invoke: {kind: api, base_url: 'http://x/v1', model: gpt-5, key_ref: 'env:NOPE'}\n"
)
handle = tempfile.NamedTemporaryFile("w", suffix=".yaml", delete=False)
handle.write(roster_yaml)
handle.close()
self.addCleanup(os.unlink, handle.name)
with self.assertRaises(AdapterError) as ctx:
run_once("expensive please", roster_path=handle.name, model="gpt5")
self.assertIn("billing is disabled", str(ctx.exception))
# And it must not have metered a task (it never ran).
self.assertEqual(self._records(), [])
def test_router_threads_task_hint(self):
# The default router path passes the task hint through to Router.route.
fake_router = MagicMock()
fake_router.route.return_value = "routed by orchestrator"
with patch("tanglebrain.cli.load_roster"), patch(
"tanglebrain.cli.Router", return_value=fake_router
) as RouterCls:
self.assertEqual(run_once("hello", task="code"), "routed by orchestrator")
RouterCls.assert_called_once()
self.assertEqual(fake_router.route.call_args.kwargs.get("task"), "code")
def test_router_threads_task_id_in_opts(self):
# The minted task_id must reach Router.route's opts — this is the seam that propagates it to
# the orchestrator (and thence to delegated sub-calls). The router path is the feature's point.
fake_router = MagicMock()
fake_router.route.return_value = "routed reply"
with patch("tanglebrain.cli.load_roster"), patch(
"tanglebrain.cli.Router", return_value=fake_router
):
run_once("hello")
opts = fake_router.route.call_args.kwargs.get("opts")
self.assertIsInstance(opts, dict)
self.assertIsInstance(opts.get("task_id"), str)
self.assertTrue(opts["task_id"])
def test_model_takes_precedence_over_router(self):
# model is an explicit override and wins over the default router path.
fake_adapter = MagicMock()
fake_adapter.run.return_value = "from-model"
with patch("tanglebrain.cli.load_roster"), patch(
"tanglebrain.cli.select_by_id"
), patch("tanglebrain.cli.build_adapter", return_value=fake_adapter), patch(
"tanglebrain.cli.Router"
) as RouterCls:
self.assertEqual(run_once("hi", model="claude"), "from-model")
RouterCls.assert_not_called()
def test_local_takes_precedence_over_router(self):
fake_adapter = MagicMock()
fake_adapter.run.return_value = "from-local"
with patch("tanglebrain.cli.load_roster"), patch(
"tanglebrain.cli.select_local"
), patch("tanglebrain.cli.build_adapter", return_value=fake_adapter), patch(
"tanglebrain.cli.Router"
) as RouterCls:
self.assertEqual(run_once("hi", local=True), "from-local")
RouterCls.assert_not_called()
def test_local_path_records_a_task(self):
# Metering seam: the --local path writes one usage record tagged tier=local.
fake_adapter = MagicMock()
fake_adapter.run.return_value = "local reply"
with patch("tanglebrain.cli.build_adapter", return_value=fake_adapter):
run_once("hello there", local=True)
records = self._records()
self.assertEqual(len(records), 1)
self.assertEqual(records[0]["path"], "local")
self.assertEqual(records[0]["tier"], "local")
self.assertGreater(records[0]["spend_avoided_usd"], 0.0)
def test_return_served_local_path(self):
fake_adapter = MagicMock()
fake_adapter.run.return_value = "local reply"
with patch("tanglebrain.cli.build_adapter", return_value=fake_adapter):
result = run_once(
"hi", local=True, return_served=True, roster_path=str(packaged_roster_path())
)
text, served = result
self.assertEqual(text, "local reply")
self.assertEqual(served["path"], "local")
self.assertEqual(served["tier"], "local")
self.assertEqual(served["model"], "local-ollama")
def test_return_served_router_path(self):
served_entry = MagicMock()
served_entry.tier = "sub"
served_entry.id = "codex"
fake_router = MagicMock()
fake_router.route.return_value = "routed"
fake_router.last_served = served_entry
with patch("tanglebrain.cli.load_roster"), patch(
"tanglebrain.cli.Router", return_value=fake_router
):
text, served = run_once("hi", return_served=True)
self.assertEqual(text, "routed")
# task_id is minted per run — assert it's present and well-formed, then the stable rest.
self.assertTrue(served.pop("task_id"))
self.assertEqual(served, {"path": "router", "tier": "sub", "model": "codex"})
def test_default_return_is_plain_str(self):
# Back-compat: without return_served, run_once still returns a bare string.
fake_adapter = MagicMock()
fake_adapter.run.return_value = "x"
with patch("tanglebrain.cli.build_adapter", return_value=fake_adapter):
self.assertEqual(run_once("hi", local=True), "x")
def test_model_path_records_a_task(self):
# The --model override path also meters, tagged path=model with the pinned entry's tier.
fake_adapter = MagicMock()
fake_adapter.run.return_value = "claude reply"
with patch("tanglebrain.cli.build_adapter", return_value=fake_adapter):
run_once("summarize this", model="claude", roster_path=_pinned_roster(self))
records = self._records()
self.assertEqual(len(records), 1)
self.assertEqual(records[0]["path"], "model")
self.assertEqual(records[0]["tier"], "sub")
self.assertEqual(records[0]["model"], "claude")
def test_gate_trivial_routes_to_local(self):
# gate on + classifier says trivial → served by free local (path 'gate-local'), no Router.
fake_adapter = MagicMock(); fake_adapter.run.return_value = "local ans"
with patch("tanglebrain.cli.classify", return_value="trivial") as clf, \
patch("tanglebrain.cli.build_adapter", return_value=fake_adapter), \
patch("tanglebrain.cli.Router") as RouterCls:
text, served = run_once("2+2?", gate=True, return_served=True)
self.assertEqual(text, "local ans")
self.assertEqual(served["path"], "gate-local")
self.assertEqual(served["tier"], "local")
RouterCls.assert_not_called()
clf.assert_called_once()
def test_gate_frontier_falls_through_to_router(self):
served_entry = MagicMock(); served_entry.tier = "sub"; served_entry.id = "claude"
fake_router = MagicMock(); fake_router.route.return_value = "routed"; fake_router.last_served = served_entry
with patch("tanglebrain.cli.classify", return_value="frontier"), \
patch("tanglebrain.cli.Router", return_value=fake_router):
text, served = run_once("design a system", gate=True, return_served=True)
self.assertEqual(text, "routed")
self.assertEqual(served["path"], "router")
def test_gate_false_skips_classifier(self):
fake_router = MagicMock(); fake_router.route.return_value = "routed"; fake_router.last_served = None
with patch("tanglebrain.cli.classify") as clf, patch("tanglebrain.cli.Router", return_value=fake_router):
run_once("hi", gate=False)
clf.assert_not_called()
def test_gate_not_consulted_for_model_or_local(self):
# The gate lives only on the default path — an explicit --model/--local must bypass it
# entirely (classify never called), even with gate forced on.
fake_adapter = MagicMock(); fake_adapter.run.return_value = "x"
roster = _pinned_roster(self)
with patch("tanglebrain.cli.classify") as clf, \
patch("tanglebrain.cli.build_adapter", return_value=fake_adapter):
run_once("hi", model="claude", gate=True, roster_path=roster)
run_once("hi", local=True, gate=True, roster_path=roster)
clf.assert_not_called()
def test_gate_none_uses_setting(self):
from tanglebrain.settings import Settings
fake_adapter = MagicMock(); fake_adapter.run.return_value = "x"
with patch("tanglebrain.cli.load_settings", return_value=Settings(classifier_gate_enabled=True)), \
patch("tanglebrain.cli.classify", return_value="trivial"), \
patch("tanglebrain.cli.build_adapter", return_value=fake_adapter), \
patch("tanglebrain.cli.Router") as RouterCls:
_, served = run_once("2+2?", return_served=True) # gate defaults None → reads the setting
self.assertEqual(served["path"], "gate-local")
RouterCls.assert_not_called()
def test_origin_and_parent_task_recorded(self):
# #74: origin defaults to "cli"; an explicit origin + caller identity land on the record.
fake_adapter = MagicMock()
fake_adapter.run.return_value = "x"
with patch("tanglebrain.cli.build_adapter", return_value=fake_adapter):
run_once("hi", local=True)
run_once("hi", local=True, origin="serve", parent_task_id="tc-42")
default, tagged = self._records()
self.assertEqual(default["origin"], "cli")
self.assertNotIn("parent_task_id", default)
self.assertEqual(tagged["origin"], "serve")
self.assertEqual(tagged["parent_task_id"], "tc-42")
def test_router_path_records_served_entry(self):
# The router surfaces last_served; run_once records that tier/model.
served = MagicMock()
served.tier = "sub"
served.id = "claude"
fake_router = MagicMock()
fake_router.route.return_value = "routed reply"
fake_router.last_served = served
with patch("tanglebrain.cli.load_roster"), patch(
"tanglebrain.cli.Router", return_value=fake_router
):
run_once("hello")
records = self._records()
self.assertEqual(len(records), 1)
self.assertEqual(records[0]["path"], "router")
self.assertEqual(records[0]["tier"], "sub")
self.assertEqual(records[0]["model"], "claude")
class RunOnceStreamTest(unittest.TestCase):
"""run_once_stream — path parity with run_once, delta pass-through, metering (c13-S1).
Fakes use ``spec=[...]`` deliberately: capability detection is ``getattr(adapter,
"run_stream", None)``, and a bare MagicMock would auto-create that attribute and make every
adapter look streaming-capable.
"""
def setUp(self):
self.tmp = tempfile.mkdtemp()
self._env = patch.dict(os.environ, {"TANGLEBRAIN_STATE_DIR": self.tmp}, clear=False)
self._env.start()
self.addCleanup(self._env.stop)
def _records(self):
return read_records(Path(self.tmp) / "usage.jsonl")
def _streaming_adapter(self, *deltas: str) -> MagicMock:
fake = MagicMock(spec=["run", "run_stream"])
fake.run_stream.return_value = iter(deltas)
return fake
def test_model_path_streams_and_records_on_exhaustion(self):
fake = self._streaming_adapter("Hel", "lo")
with patch("tanglebrain.cli.build_adapter", return_value=fake):
deltas, served = run_once_stream(
"hi", model="claude", roster_path=_pinned_roster(self)
)
# served resolves before the first delta; nothing is metered yet.
self.assertEqual(served["path"], "model")
self.assertEqual(served["model"], "claude")
self.assertTrue(served["task_id"])
self.assertEqual(self._records(), [])
self.assertEqual(list(deltas), ["Hel", "lo"])
records = self._records()
self.assertEqual(len(records), 1)
self.assertEqual(records[0]["path"], "model")
self.assertEqual(records[0]["model"], "claude")
def test_non_streaming_adapter_falls_back_to_single_delta(self):
fake = MagicMock(spec=["run"]) # no run_stream — per-backend emulation
fake.run.return_value = "whole answer"
with patch("tanglebrain.cli.build_adapter", return_value=fake):
deltas, served = run_once_stream(
"hi", model="claude", roster_path=_pinned_roster(self)
)
# Blocking path: the spend already happened, so it is metered before consumption.
self.assertEqual(len(self._records()), 1)
self.assertEqual(list(deltas), ["whole answer"])
self.assertEqual(served["path"], "model")
self.assertEqual(len(self._records()), 1)
def test_local_path_streams(self):
fake = self._streaming_adapter("local ", "reply")
with patch("tanglebrain.cli.build_adapter", return_value=fake):
deltas, served = run_once_stream(
"hi", local=True, roster_path=str(packaged_roster_path())
)
self.assertEqual(list(deltas), ["local ", "reply"])
self.assertEqual(served["path"], "local")
self.assertEqual(served["tier"], "local")
self.assertEqual(self._records()[0]["path"], "local")
def test_gate_trivial_streams_from_local(self):
fake = self._streaming_adapter("4")
with patch("tanglebrain.cli.classify", return_value="trivial"), \
patch("tanglebrain.cli.build_adapter", return_value=fake), \
patch("tanglebrain.cli.Router") as RouterCls:
deltas, served = run_once_stream("2+2?", gate=True)
self.assertEqual(list(deltas), ["4"])
self.assertEqual(served["path"], "gate-local")
RouterCls.assert_not_called()
def test_router_path_emulates_single_delta(self):
served_entry = MagicMock(); served_entry.tier = "sub"; served_entry.id = "codex"
fake_router = MagicMock()
fake_router.route.return_value = "routed reply"
fake_router.last_served = served_entry
with patch("tanglebrain.cli.load_roster"), \
patch("tanglebrain.cli.Router", return_value=fake_router):
deltas, served = run_once_stream("hi", gate=False)
# Emulated: route() already ran to completion and was metered at call time.
self.assertEqual(len(self._records()), 1)
self.assertEqual(list(deltas), ["routed reply"])
self.assertEqual(served["path"], "router")
self.assertEqual(served["model"], "codex")
fake_router.route.assert_called_once()
def test_mid_stream_error_records_partial_and_reraises(self):
def exploding():
yield "par"
raise AdapterError("backend died")
fake = MagicMock(spec=["run", "run_stream"])
fake.run_stream.return_value = exploding()
with patch("tanglebrain.cli.build_adapter", return_value=fake):
deltas, _ = run_once_stream("hi", model="claude", roster_path=_pinned_roster(self))
self.assertEqual(next(deltas), "par")
with self.assertRaises(AdapterError):
next(deltas)
records = self._records()
self.assertEqual(len(records), 1)
# The partial text was real backend spend — it is what gets metered.
self.assertGreater(records[0]["out_tokens_est"], 0)
def test_error_before_first_delta_records_nothing(self):
def dead_on_arrival():
raise AdapterError("connect refused")
yield # pragma: no cover — makes this a generator
fake = MagicMock(spec=["run", "run_stream"])
fake.run_stream.return_value = dead_on_arrival()
with patch("tanglebrain.cli.build_adapter", return_value=fake):
deltas, _ = run_once_stream("hi", model="claude", roster_path=_pinned_roster(self))
with self.assertRaises(AdapterError):
next(deltas)
self.assertEqual(self._records(), [])
def test_abandoned_stream_records_partial(self):
fake = self._streaming_adapter("first", "never-pulled")
with patch("tanglebrain.cli.build_adapter", return_value=fake):
deltas, _ = run_once_stream("hi", model="claude", roster_path=_pinned_roster(self))
self.assertEqual(next(deltas), "first")
deltas.close() # caller walks away mid-stream
records = self._records()
self.assertEqual(len(records), 1)
self.assertGreater(records[0]["out_tokens_est"], 0)
def test_opts_thread_task_id_and_max_tokens_to_run_stream(self):
fake = self._streaming_adapter("x")
with patch("tanglebrain.cli.build_adapter", return_value=fake):
deltas, served = run_once_stream(
"hi", model="claude", max_tokens=128, roster_path=_pinned_roster(self)
)
list(deltas)
opts = fake.run_stream.call_args.args[1]
self.assertEqual(opts.get("max_tokens"), 128)
self.assertEqual(opts.get("task_id"), served["task_id"])
def test_unknown_model_raises_selection_error_at_call_time(self):
with self.assertRaises(SelectionError):
run_once_stream("hi", model="no-such-model")
def test_origin_and_parent_task_recorded_on_streamed_and_emulated_paths(self):
# #74: attribution rides every run_once_stream recording site.
streaming = self._streaming_adapter("a")
with patch("tanglebrain.cli.build_adapter", return_value=streaming):
deltas, _ = run_once_stream(
"hi", model="claude", roster_path=_pinned_roster(self),
origin="serve", parent_task_id="tc-42",
)
list(deltas)
blocking = MagicMock(spec=["run"])
blocking.run.return_value = "whole"
with patch("tanglebrain.cli.build_adapter", return_value=blocking):
deltas, _ = run_once_stream(
"hi", model="claude", roster_path=_pinned_roster(self),
origin="serve", parent_task_id="tc-42",
)
list(deltas)
served_entry = MagicMock(); served_entry.tier = "sub"; served_entry.id = "codex"
fake_router = MagicMock()
fake_router.route.return_value = "routed"
fake_router.last_served = served_entry
with patch("tanglebrain.cli.load_roster"), \
patch("tanglebrain.cli.Router", return_value=fake_router):
deltas, _ = run_once_stream(
"hi", gate=False, origin="serve", parent_task_id="tc-42"
)
list(deltas)
records = self._records()
self.assertEqual(len(records), 3) # streamed pin + emulated pin + emulated router
for record in records:
self.assertEqual(record["origin"], "serve")
self.assertEqual(record["parent_task_id"], "tc-42")
def test_gate_not_consulted_for_model_or_local(self):
fake = self._streaming_adapter("x")
roster = _pinned_roster(self)
with patch("tanglebrain.cli.classify") as clf, \
patch("tanglebrain.cli.build_adapter", return_value=fake):
deltas, _ = run_once_stream("hi", model="claude", gate=True, roster_path=roster)
list(deltas)
clf.assert_not_called()
class MainTest(unittest.TestCase):
def test_success_prints_and_returns_zero(self):
with patch("tanglebrain.cli.run_once", return_value="the answer"):
out = io.StringIO()
with redirect_stdout(out):
code = main(["what is 2+2?"])
self.assertEqual(code, 0)
self.assertIn("the answer", out.getvalue())
def test_model_flag_threaded_to_run_once(self):
with patch("tanglebrain.cli.run_once", return_value="ok") as run:
with redirect_stdout(io.StringIO()):
code = main(["--model", "gemini", "hello"])
self.assertEqual(code, 0)
self.assertEqual(run.call_args.kwargs["model"], "gemini")
def test_local_and_task_flags_threaded_to_run_once(self):
with patch("tanglebrain.cli.run_once", return_value="ok") as run:
with redirect_stdout(io.StringIO()):
code = main(["--local", "--task", "code", "hello"])
self.assertEqual(code, 0)
self.assertTrue(run.call_args.kwargs["local"])
self.assertEqual(run.call_args.kwargs["task"], "code")
def test_default_no_flags_routes(self):
# No flags: local defaults False -> run_once takes the router path.
with patch("tanglebrain.cli.run_once", return_value="ok") as run:
with redirect_stdout(io.StringIO()):
code = main(["hello"])
self.assertEqual(code, 0)
self.assertFalse(run.call_args.kwargs["local"])
self.assertIsNone(run.call_args.kwargs["model"])
self.assertIsNone(run.call_args.kwargs["gate"]) # no --gate/--no-gate → defer to the setting
def test_gate_flag_threaded(self):
with patch("tanglebrain.cli.run_once", return_value="ok") as run:
with redirect_stdout(io.StringIO()):
main(["--gate", "hi"])
self.assertIs(run.call_args.kwargs["gate"], True)
def test_no_gate_flag_threaded(self):
with patch("tanglebrain.cli.run_once", return_value="ok") as run:
with redirect_stdout(io.StringIO()):
main(["--no-gate", "hi"])
self.assertIs(run.call_args.kwargs["gate"], False)
def test_router_error_returns_one_and_writes_stderr(self):
from tanglebrain.router import RouterError
with patch("tanglebrain.cli.run_once", side_effect=RouterError("all orchestrators failed")):
err = io.StringIO()
with redirect_stderr(err):
code = main(["hello"])
self.assertEqual(code, 1)
self.assertIn("all orchestrators failed", err.getvalue())
def test_adapter_error_returns_one_and_writes_stderr(self):
with patch("tanglebrain.cli.run_once", side_effect=AdapterError("endpoint down")):
err = io.StringIO()
with redirect_stderr(err):
code = main(["--local", "hello"])
self.assertEqual(code, 1)
self.assertIn("endpoint down", err.getvalue())
def test_stats_prints_rollup_without_prompt(self):
summary = {"tasks": 2, "by_tier": {"local": 2}, "in_tokens_est": 10,
"out_tokens_est": 20, "cloud_equiv_usd": 1.0, "spend_avoided_usd": 1.0}
with patch("tanglebrain.cli.read_records", return_value=[]), patch(
"tanglebrain.cli.rollup", return_value=summary
), patch("tanglebrain.cli.run_once") as run:
out = io.StringIO()
with redirect_stdout(out):
code = main(["--stats"])
self.assertEqual(code, 0)
self.assertIn("Tasks routed:", out.getvalue())
run.assert_not_called() # --stats short-circuits before routing
def test_missing_prompt_without_stats_errors(self):
# argparse parser.error exits with code 2.
with redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as ctx:
main([])
self.assertEqual(ctx.exception.code, 2)
def test_version_flag_prints_version_and_exits_zero(self):
# argparse's version action prints to stdout and exits 0; it short-circuits before routing.
from tanglebrain import __version__
out = io.StringIO()
with patch("tanglebrain.cli.run_once") as run:
with redirect_stdout(out):
with self.assertRaises(SystemExit) as ctx:
main(["--version"])
self.assertEqual(ctx.exception.code, 0)
self.assertIn(__version__, out.getvalue())
run.assert_not_called() # --version never routes
if __name__ == "__main__":
unittest.main()