Restore env and CLI model configuration
This commit is contained in:
1 parent
7c80500280
commit
fd8e0ddea5
5 files changed
+77
-384
No files matched your search
+21
-90
@@ -4,19 +4,14 @@ import unittest
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
import stat
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from rich.console import Console
|
||||
from rich.markdown import Markdown
|
||||
from textual.widgets import Button
|
||||
|
||||
import httpx
|
||||
|
||||
from ai_chat import AIChatApp, AIConfig, MessageBubble, ChatMessage, ControlsHelp, ScreenshotOptions, ModelSettings, main
|
||||
from settings import load_settings, save_settings, store_model, model_from_settings
|
||||
from ai_chat import AIChatApp, AIConfig, MessageBubble, ChatMessage, ControlsHelp, ScreenshotOptions, main
|
||||
|
||||
|
||||
class ChatTests(unittest.IsolatedAsyncioTestCase):
|
||||
@@ -200,32 +195,6 @@ class ChatTests(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertEqual([m.content for m in app.messages], ['Start here', 'complete reply', 'second reply'])
|
||||
self.assertNotIn('partial secret', json.dumps(requests[2]))
|
||||
|
||||
async def test_invalid_settings_picker_reports_error_and_chat_remains_usable(self):
|
||||
app = await self.make_app(lambda request: httpx.Response(200, text='data: {"choices":[{"delta":{"content":"working"}}]}\n\ndata: [DONE]\n\n'))
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
app.settings_path = Path(directory) / 'sloppy.json'
|
||||
app.settings_path.write_text('{"models": {"x": null}}', encoding='utf-8')
|
||||
async with app.run_test() as pilot:
|
||||
with patch.object(app, 'notify') as notify:
|
||||
app.action_model_settings()
|
||||
self.assertIn('models.x', notify.call_args.args[0])
|
||||
await self.wait_finished(app, pilot)
|
||||
self.assertEqual(app.messages[-1].content, 'working')
|
||||
|
||||
async def test_back_exits_model_picker_without_saving(self):
|
||||
app = await self.make_app(lambda request: httpx.Response(500))
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'sloppy.json'
|
||||
app.settings_path = path
|
||||
app.choose_models = True
|
||||
async with app.run_test() as pilot:
|
||||
self.assertIsInstance(app.screen, ModelSettings)
|
||||
app.screen.query_one('#back-models', Button).press()
|
||||
await pilot.pause()
|
||||
self.assertNotIsInstance(app.screen, ModelSettings)
|
||||
self.assertFalse(path.exists())
|
||||
self.assertIn('Ctrl+M', str(app.status_bar.render()))
|
||||
|
||||
async def test_empty_stream_uses_fallback(self):
|
||||
calls = []
|
||||
def handler(request):
|
||||
@@ -401,70 +370,32 @@ class ChatTests(unittest.IsolatedAsyncioTestCase):
|
||||
|
||||
|
||||
class CommandLineTests(unittest.TestCase):
|
||||
def test_settings_validation_identifies_invalid_fields(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'sloppy.json'
|
||||
for data, field in [
|
||||
({'models': {}, 'selected': None}, 'selected'),
|
||||
({'models': {'x': None}}, 'models.x'),
|
||||
({'models': {'x': {'api_key': None}}}, 'models.x.api_key'),
|
||||
({'models': {}, 'selected': {'ai1': None}}, 'selected.ai1'),
|
||||
]:
|
||||
path.write_text(json.dumps(data), encoding='utf-8')
|
||||
with self.subTest(field=field), self.assertRaisesRegex(ValueError, field.replace('.', r'\.')):
|
||||
load_settings(path)
|
||||
path.write_text(json.dumps({'models': {'x': {'model': 'm'}}}), encoding='utf-8')
|
||||
self.assertEqual(load_settings(path)['selected'], {'ai1': '', 'ai2': ''})
|
||||
|
||||
@unittest.skipIf(os.name == 'nt', 'Unix file modes only')
|
||||
def test_settings_temp_is_private_and_failure_cleans_up(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'sloppy.json'
|
||||
for existing in (False, True):
|
||||
if existing:
|
||||
path.write_text('old', encoding='utf-8')
|
||||
path.chmod(0o644)
|
||||
original_replace = os.replace
|
||||
def inspect_replace(source, destination):
|
||||
self.assertEqual(stat.S_IMODE(source.stat().st_mode), 0o600)
|
||||
self.assertIn('secret', source.read_text(encoding='utf-8'))
|
||||
original_replace(source, destination)
|
||||
with patch('settings.os.replace', side_effect=inspect_replace):
|
||||
save_settings({'api_key': 'secret'}, path)
|
||||
self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
|
||||
with patch('settings.os.replace', side_effect=OSError('replace failed')):
|
||||
with self.assertRaisesRegex(OSError, 'replace failed'):
|
||||
save_settings({'api_key': 'secret'}, path)
|
||||
self.assertFalse(path.with_name('sloppy.json.tmp').exists())
|
||||
|
||||
def test_env_only_starts_without_picker_or_json_import(self):
|
||||
def test_env_connections_start_directly(self):
|
||||
variables = {
|
||||
'AI1_BASE_URL': 'http://one.test/v1', 'AI1_API_KEY': 'one-key',
|
||||
'AI2_BASE_URL': 'http://two.test/v1', 'AI2_API_KEY': 'two-key',
|
||||
'INITIAL_PROMPT': 'Discuss this', 'MAX_TURNS': '2',
|
||||
}
|
||||
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, variables), \
|
||||
patch('sys.argv', ['ai_chat.py']), patch('ai_chat.AIChatApp.run', autospec=True) as run:
|
||||
original = os.getcwd()
|
||||
try:
|
||||
os.chdir(directory)
|
||||
main()
|
||||
self.assertFalse(Path('sloppy.json').exists())
|
||||
finally:
|
||||
os.chdir(original)
|
||||
self.assertFalse(run.call_args.args[0].choose_models)
|
||||
with patch.dict(os.environ, variables), patch('sys.argv', ['ai_chat.py']), \
|
||||
patch('ai_chat.AIChatApp.run', autospec=True) as run:
|
||||
main()
|
||||
app = run.call_args.args[0]
|
||||
self.assertEqual(app.ai1.base_url, variables['AI1_BASE_URL'])
|
||||
self.assertEqual(app.ai2.api_key, variables['AI2_API_KEY'])
|
||||
|
||||
def test_model_settings_round_trip(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'sloppy.json'
|
||||
settings = load_settings(path)
|
||||
store_model(settings, 'local', AIConfig('Local', 'http://localhost:11434/v1',
|
||||
'env:LOCAL_KEY', 'llama3'))
|
||||
settings['selected'] = {'ai1': 'local', 'ai2': 'local'}
|
||||
save_settings(settings, path)
|
||||
loaded = load_settings(path)
|
||||
self.assertEqual(loaded['selected']['ai2'], 'local')
|
||||
self.assertEqual(model_from_settings(loaded, 'local')['api_key'], 'env:LOCAL_KEY')
|
||||
def test_cli_model_overrides_environment(self):
|
||||
variables = {
|
||||
'AI1_BASE_URL': 'http://one.test/v1', 'AI1_API_KEY': 'one-key',
|
||||
'AI2_BASE_URL': 'http://two.test/v1', 'AI2_API_KEY': 'two-key',
|
||||
'INITIAL_PROMPT': 'Discuss this',
|
||||
}
|
||||
with patch.dict(os.environ, variables), \
|
||||
patch('sys.argv', ['ai_chat.py', '--ai1-model', 'different', '--ai2-url', 'http://other.test/v1']), \
|
||||
patch('ai_chat.AIChatApp.run', autospec=True) as run:
|
||||
main()
|
||||
app = run.call_args.args[0]
|
||||
self.assertEqual(app.ai1.model, 'different')
|
||||
self.assertEqual(app.ai2.base_url, 'http://other.test/v1')
|
||||
|
||||
def test_invalid_environment_turns_reports_usage_error(self):
|
||||
with patch.dict(os.environ, {"MAX_TURNS": "invalid"}), patch('sys.argv', ['ai_chat.py']):
|
||||
|
||||
Reference in new issue
Block a user