import json from pathlib import Path import tempfile import unittest from install_ai_auth import install,parse_auth def sample(account='owner',refresh='fake-refresh'): return json.dumps({'auth_mode':'chatgpt','tokens':{'account_id':account, 'access_token':'fake-access','id_token':'fake-id','refresh_token':refresh}}).encode() class ImportTests(unittest.TestCase): def test_install_private_file_without_printing_credentials(self): with tempfile.TemporaryDirectory() as temporary: root=Path(temporary)/'login';message=install(sample(),root) self.assertNotIn('fake',message) self.assertEqual((root/'auth.json').stat().st_mode & 0o777,0o600) self.assertEqual(root.stat().st_mode & 0o777,0o700) self.assertEqual(parse_auth((root/'auth.json').read_bytes()),parse_auth(sample())) def test_refresh_preserved_and_different_account_not_overwritten(self): with tempfile.TemporaryDirectory() as temporary: root=Path(temporary)/'login';install(sample(refresh='newer-refresh'),root) before=(root/'auth.json').read_bytes();install(sample(),root) self.assertEqual((root/'auth.json').read_bytes(),before) with self.assertRaises(ValueError):install(sample('different'),root) self.assertEqual((root/'auth.json').read_bytes(),before) def test_invalid_inputs_do_not_create_auth_directory(self): for payload in (b'',b'not json',b'[]',b'{}',b'x'*(1024*1024+1)): with tempfile.TemporaryDirectory() as temporary: root=Path(temporary)/'login' with self.assertRaises(ValueError):install(payload,root) self.assertFalse(root.exists()) def test_symlink_is_rejected(self): with tempfile.TemporaryDirectory() as temporary: root=Path(temporary);(root/'link').symlink_to(root/'elsewhere') with self.assertRaises(ValueError):install(sample(),root/'link') if __name__=='__main__':unittest.main()