883 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
92 lines
7.0 KiB
Python
92 lines
7.0 KiB
Python
"""Authenticated realm chooser/real input-pipe contracts; no game or auth."""
|
|
import importlib.util,io,json,subprocess,sys,tempfile,unittest
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from unittest.mock import Mock,patch
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
spec=importlib.util.spec_from_file_location('realm_frontend',ROOT/'launcher/launcher.py');launcher=importlib.util.module_from_spec(spec);spec.loader.exec_module(launcher)
|
|
|
|
def event(rows=None):
|
|
return dict(schema=1,phase='realms',message='Choose a real authenticated realm',realms=rows if rows is not None else [dict(index=7,name="C'Thun",offline=False),dict(index=3,name="N'Zoth",offline=True),dict(index=42,name="Y'Shaarj",offline=False)])
|
|
|
|
class RealmSelection(unittest.TestCase):
|
|
def choose(self,stdout='42\n',code=0,rows=None):
|
|
with patch.object(launcher.shutil,'which',return_value='/usr/bin/kdialog'),patch.object(launcher.subprocess,'run',return_value=SimpleNamespace(stdout=stdout,returncode=code))as run:
|
|
value=launcher.choose_authenticated_realm(event(rows));return value,run
|
|
def test_menu_uses_exact_online_indices_and_literal_names(self):
|
|
value,run=self.choose();self.assertEqual(value,42);command=run.call_args.args[0]
|
|
self.assertEqual(command[-4:],['7',"[7] C'Thun",'42',"[42] Y'Shaarj"])
|
|
self.assertNotIn("N'Zoth",' '.join(command));self.assertNotIn('shell',run.call_args.kwargs)
|
|
self.assertEqual(run.call_args.kwargs['timeout'],80);self.assertEqual(run.call_args.kwargs['stdin'],subprocess.DEVNULL)
|
|
def test_invalid_or_offline_output_is_never_forwarded(self):
|
|
for value in('3\n','042\n','42\njunk','999\n','42 \n','', '42\n'*20):
|
|
with self.subTest(value=value),self.assertRaises(ValueError):self.choose(value)
|
|
def test_cancel_and_timeout_choose_nothing(self):
|
|
self.assertIsNone(self.choose('',1)[0])
|
|
with patch.object(launcher.shutil,'which',return_value='/usr/bin/kdialog'),patch.object(launcher.subprocess,'run',side_effect=subprocess.TimeoutExpired('fixture',80)):
|
|
self.assertIsNone(launcher.choose_authenticated_realm(event()))
|
|
def test_no_online_realms_never_opens_menu(self):
|
|
with patch.object(launcher.subprocess,'run')as run,self.assertRaisesRegex(ValueError,'no online realms'):
|
|
launcher.choose_authenticated_realm(event([dict(index=4,name="C'Thun",offline=True)]))
|
|
run.assert_not_called()
|
|
def test_malformed_or_control_text_rejected(self):
|
|
for name in('', ' Cthun','Cthun\nOther','Cthun\x00','Cthun\u202eOther','<b>Cthun</b>'):
|
|
with self.subTest(name=name):self.assertIsNone(launcher.public_event(json.dumps(event([dict(index=4,name=name,offline=False)]))))
|
|
rows=event()['realms'];rows.append(dict(rows[0]));self.assertIsNone(launcher.public_event(json.dumps(event(rows))))
|
|
def test_other_phase_or_unknown_fields_cannot_open_chooser(self):
|
|
invalid=event();invalid['phase']='login'
|
|
with self.assertRaises(ValueError):launcher.choose_authenticated_realm(invalid)
|
|
invalid=event();invalid['account']='not permitted'
|
|
with self.assertRaises(ValueError):launcher.choose_authenticated_realm(invalid)
|
|
|
|
class ActualPipeHandshake(unittest.TestCase):
|
|
def run_child(self,choice=42,rows=None,choose_error=None,duplicate=False):
|
|
self.tmp=tempfile.TemporaryDirectory(dir=ROOT/'runtime',prefix='realm-pipe-');self.addCleanup(self.tmp.cleanup)
|
|
folder=Path(self.tmp.name);receipt=folder/'reply.json';panel=Mock()
|
|
script='''import json,sys
|
|
from pathlib import Path
|
|
value=json.loads(sys.argv[2]);print(json.dumps(value),flush=True)
|
|
if sys.argv[3]=='duplicate':print(json.dumps(value),flush=True)
|
|
line=sys.stdin.readline(257);tail=sys.stdin.read(1)
|
|
Path(sys.argv[1]).write_text(json.dumps(dict(line=line,tail=tail)))
|
|
if line:print(json.dumps(dict(schema=1,phase='characters',message='Native character selection ready')),flush=True)
|
|
'''
|
|
choose=patch.object(launcher,'choose_authenticated_realm',side_effect=choose_error)if choose_error else patch.object(launcher,'choose_authenticated_realm',return_value=choice)
|
|
command=[sys.executable,'-u','-c',script,str(receipt),json.dumps(event(rows)),'duplicate'if duplicate else'single']
|
|
with choose as selected:
|
|
try:result=launcher.supervise(command,folder,panel_factory=lambda:panel)
|
|
except ValueError:
|
|
self.last_receipt=json.loads(receipt.read_text());self.last_selected=selected;self.last_panel=panel;raise
|
|
self.last_receipt=json.loads(receipt.read_text());self.last_selected=selected;self.last_panel=panel;return result
|
|
def test_real_pipe_sends_only_one_exact_index_then_eof(self):
|
|
result=self.run_child();self.assertEqual(result,(0,'Native character selection ready'))
|
|
self.assertEqual(self.last_receipt,dict(line='{"realm_index":42}\n',tail=''));self.last_selected.assert_called_once()
|
|
self.last_panel.close.assert_called_once()
|
|
def test_cancel_closes_pipe_without_realm_or_auth_retry(self):
|
|
code,message=self.run_child(None);self.assertEqual(code,2);self.assertIn('cancelled or expired',message);self.assertIn('no password resent',message)
|
|
self.assertEqual(self.last_receipt,dict(line='',tail=''));self.last_selected.assert_called_once()
|
|
def test_malformed_authenticated_list_closes_real_pipe(self):
|
|
with self.assertRaisesRegex(ValueError,'realm list is invalid'):self.run_child(rows=[dict(index=1,name='bad\nname',offline=False)])
|
|
self.last_selected.assert_not_called();self.assertEqual(self.last_receipt,dict(line='',tail=''))
|
|
def test_duplicate_prompt_never_sends_second_reply(self):
|
|
with self.assertRaisesRegex(ValueError,'no longer pending'):self.run_child(duplicate=True)
|
|
self.assertEqual(self.last_receipt,dict(line='{"realm_index":42}\n',tail=''));self.last_selected.assert_called_once()
|
|
def test_offline_or_noninteger_choice_is_never_sent_to_backend(self):
|
|
for choice in(3,True,'42',99):
|
|
with self.subTest(choice=choice),self.assertRaisesRegex(ValueError,'unavailable or invalid'):self.run_child(choice)
|
|
self.assertEqual(self.last_receipt,dict(line='',tail=''))
|
|
def test_invalid_or_offline_dialog_result_closes_real_pipe(self):
|
|
with self.assertRaisesRegex(ValueError,'invalid'):self.run_child(choose_error=ValueError('invalid choice'))
|
|
self.assertEqual(self.last_receipt,dict(line='',tail=''));self.last_selected.assert_called_once()
|
|
def test_backend_eof_does_not_restart_or_authenticate(self):
|
|
panel=Mock();code,message=launcher.supervise([sys.executable,'-u','-c','pass'],ROOT,panel_factory=lambda:panel)
|
|
self.assertEqual(code,2);self.assertIn('before readiness',message);panel.close.assert_called_once()
|
|
def test_broken_input_is_explicit_and_no_retry(self):
|
|
panel=Mock();child=Mock();child.stdout=io.StringIO(json.dumps(event())+'\n');child.poll.return_value=None;child.stdin.write.side_effect=BrokenPipeError
|
|
context=Mock();context.__enter__=Mock(return_value=child);context.__exit__=Mock(return_value=False)
|
|
with patch.object(launcher.subprocess,'Popen',return_value=context)as spawn,patch.object(launcher,'choose_authenticated_realm',return_value=7),self.assertRaisesRegex(ValueError,'could not reach'):
|
|
launcher.supervise(['fixture'],ROOT,panel_factory=lambda:panel)
|
|
self.assertEqual(spawn.call_count,1);panel.close.assert_called_once()
|
|
|
|
if __name__=='__main__':unittest.main()
|