import contextlib import io import os from pathlib import Path import runpy import time import tempfile import unittest from unittest.mock import patch m = runpy.run_path(str(Path(__file__).with_name('pages'))) class RememberTests(unittest.TestCase): def test_expired_login_retains_same_account_drafts_and_path(self): with tempfile.TemporaryDirectory() as root, patch.dict(os.environ, {'XDG_CONFIG_HOME': root}), contextlib.redirect_stdout(io.StringIO()): with m['Configuration']().locked() as config: config.data = {'version': 1, 'default_profile': 'default', 'profiles': {'default': {'origin': 'https://wiki.example', 'username': 'anya', 'lang': 'auto'}}} config.save() with m['Profile']('default').locked() as profile: profile.data = {'origin': 'https://wiki.example', 'username': 'anya', 'token': 'expired', 'expires': 1, 'cwd': '/projects/demo', 'task_outbox': {'request': {'title': 'synthetic draft'}}} profile.save() def login(client, username, password, *, remember=False): self.assertTrue(remember) client.token = 'pw_api_'+'x'*43 return time.time()+2592000 with patch.object(m['Client'], 'login', login), patch.object(m['getpass'], 'getpass', return_value='synthetic'): m['main'](['login', '--remember']) with m['Profile']('default').locked() as profile: self.assertEqual(profile.data['cwd'], '/projects/demo') self.assertEqual(profile.data['task_outbox']['request']['title'], 'synthetic draft') self.assertTrue(profile.data['token'].startswith('pw_api_')) def test_password_choice_is_explicit_and_bound_before_totp(self): for remember in (False, True): client = m['Client']('https://wiki.example') challenge = m['Failure']('MFA', 401, {'mfa_required': True, 'challenge_token': 'challenge'}) result = {'access_token': 'pw_api_' + 'x'*43, 'token_type': 'Bearer', 'expires_in': 2592000} with patch.object(client, 'json', side_effect=[challenge, result]) as api: expiry = client.login('anya', 'synthetic-password', lambda _: '123456', remember=remember) self.assertEqual(api.call_args_list[0].kwargs['form'].get('remember'), '1' if remember else None) self.assertNotIn('remember', api.call_args_list[1].kwargs['form']) self.assertAlmostEqual(expiry - time.time(), 2592000, delta=2) def test_oidc_choice_is_bound_at_start(self): for remember in (False, True): client = m['Client']('https://wiki.example') start = {'device_code': 'd'*43, 'verification_uri': '/_/auth/cli/verify?request='+'r'*43, 'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5} result = {'access_token': 'pw_api_'+'x'*43, 'token_type': 'Bearer', 'expires_in': 2592000, 'username': 'anya'} with patch.object(client, 'json', side_effect=[start, result]) as api, contextlib.redirect_stdout(io.StringIO()): client.login_oidc(True, remember=remember, sleep=lambda _: None, clock=lambda: 0) self.assertEqual(api.call_args_list[0].kwargs['form'].get('remember'), '1' if remember else None) self.assertNotIn('remember', api.call_args_list[1].kwargs['form'])