Files
pages-cli/test_pages.py
T
Anya Tokugawa 9b685b72da feat: opt-in OIDC browser open, atomic page creation, and conflict recovery
- Default pages login --oidc to not auto-open a browser and replace --no-browser with --with-open-browser
- Add atomic new Path/Page creation (PUT /_/api/v1/pages/path:... with If-None-Match: *) in pages edit with confirmation and und warning
- Add interactive 409/412 conflict resolution and pages recover (--list, --edit, --discard)
- Update tests, docs (README.md, DISTRIBUTION.md, docs/client-contract.md, docs/neomutt.md), and macOS CI unittest list
2026-11-30 21:26:57 +09:00

934 lines
58 KiB
Python

import contextlib
import base64
from email.message import Message
import hashlib
import io
import json
import os
from pathlib import Path
import runpy
import stat
import sys
import tempfile
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest.mock import patch
m = runpy.run_path(str(Path(__file__).with_name('pages')))
Client, Failure, Profile = m['Client'], m['Failure'], m['Profile']
@contextlib.contextmanager
def server(callback):
class Handler(BaseHTTPRequestHandler):
def do_GET(self): callback(self)
def do_POST(self): callback(self)
def do_PUT(self): callback(self)
def log_message(self, *args): pass
instance = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
thread = threading.Thread(target=instance.serve_forever, daemon=True)
thread.start()
try: yield 'http://127.0.0.1:%d' % instance.server_port
finally: instance.shutdown(); instance.server_close(); thread.join()
def reply(h, status, body, mime='application/json'):
raw = json.dumps(body).encode() if isinstance(body, dict) else body
h.send_response(status); h.send_header('Content-Type', mime); h.end_headers(); h.wfile.write(raw)
class RemoteTests(unittest.TestCase):
def test_oidc_polling_pkce_and_no_secret_output(self):
now = [0]
waits, calls = [], []
started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43,
'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
client = Client('https://wiki.example')
def sleep(seconds): waits.append(seconds); now[0] += seconds
def request(route, **kwargs):
calls.append((route, kwargs))
if route.endswith('/start'): return started
polls = len(calls)-1
if polls == 1: raise Failure('pending',400,{'error':'authorization_pending'})
if polls == 2: raise Failure('slow',400,{'error':'slow_down'})
return {'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'anya'}
with patch.object(client,'json',side_effect=request), patch.object(m['webbrowser'],'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
expires, name = client.login_oidc(sleep=sleep,clock=lambda:now[0])
self.assertEqual(name,'anya'); self.assertGreater(expires,time.time())
self.assertEqual(waits,[5,5,10]); browser.assert_not_called()
proof = calls[1][1]['form']['code_verifier']
expected=base64.urlsafe_b64encode(hashlib.sha256(proof.encode()).digest()).decode().rstrip('=')
self.assertEqual(calls[0][1]['form']['code_challenge'],expected)
self.assertNotIn(proof,out.getvalue()); self.assertNotIn(started['device_code'],out.getvalue()); self.assertNotIn(client.token,out.getvalue())
self.assertIn('ABCD-1234',out.getvalue())
def test_oidc_unavailable_server_explained_without_retry(self):
for status in (404, 405, 501):
with self.subTest(status=status):
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=Failure('Not found or not readable.', status)) as api, patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
with self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught:
client.login_oidc(open_browser=True)
self.assertEqual(caught.exception.status, status)
api.assert_called_once()
browser.assert_not_called()
self.assertEqual(out.getvalue(), '')
self.assertEqual(client.token, '')
def test_oidc_disabled_and_other_start_errors(self):
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})):
with self.assertRaisesRegex(Failure, 'not enabled for this domain'):
client.login_oidc()
for error in (Failure('Connection/TLS failure.'), Failure('Access denied.', 403), Failure('Unavailable.', 503)):
with patch.object(client, 'json', side_effect=error) as api:
with self.assertRaises(Failure) as caught:
client.login_oidc()
self.assertIs(caught.exception, error)
api.assert_called_once()
def test_oidc_rejects_external_url_and_wrong_account(self):
client=Client('https://wiki.example')
started={'device_code':'D'*43,'verification_uri':'https://evil.example/','user_code':'ABCD-1234','expires_in':300,'interval':5}
with patch.object(client,'json',return_value=started),patch.object(m['webbrowser'],'open') as browser:
with self.assertRaises(Failure): client.login_oidc(open_browser=True)
browser.assert_not_called()
started['verification_uri']='/_/auth/cli/verify?request='+'R'*43
token={'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'other'}
with patch.object(client,'json',side_effect=[started,token,{}]) as api, contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure): client.login_oidc(expected_username='anya',sleep=lambda _:None,clock=lambda:0)
self.assertEqual(api.call_args.args[0],'/_/auth/logout')
self.assertEqual(client.token,'')
def test_oidc_cancellation_denial_and_ambiguous_exchange(self):
started={'device_code':'D'*43,'verification_uri':'/_/auth/cli/verify?request='+'R'*43,'user_code':'ABCD-1234','expires_in':300,'interval':5}
for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]:
client=Client('https://wiki.example')
with patch.object(client,'json',side_effect=[started,error]) as api,contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure): client.login_oidc(sleep=lambda _:None,clock=lambda:0)
self.assertEqual(api.call_count,2)
client=Client('https://wiki.example')
with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()):
def interrupt(_): raise KeyboardInterrupt()
with self.assertRaises(KeyboardInterrupt): client.login_oidc(sleep=interrupt,clock=lambda:0)
self.assertEqual(api.call_count,1)
def test_oidc_main_without_configured_username(self):
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}):
self.configure(None,'--origin','https://wiki.example')
calls=[]
def login(client,*args,**kwargs):
calls.append((args,kwargs))
client.token='pw_api_'+'s'*43; return time.time()+600,'anya'
with patch.object(Client,'login_oidc',login),contextlib.redirect_stdout(io.StringIO()):
m['main'](['login','--oidc'])
m['main'](['status'])
self.configure(None,'--lang','ja')
self.assertIs(calls[-1][0][0],False)
with Profile('default').locked() as profile:
self.assertEqual(profile.data['username'],'anya')
self.assertEqual(profile.data['configured_username'],'')
with self.assertRaises(Failure): self.configure(None,'--username','other')
def test_oidc_browser_opening_is_opt_in(self):
started = {'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_'+'S'*43, 'token_type': 'Bearer', 'expires_in': 3600, 'username': 'anya'}
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=[started, result]), patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()):
client.login_oidc(sleep=lambda _: None, clock=lambda: 0)
browser.assert_not_called()
client = Client('https://wiki.example')
with patch.object(client, 'json', side_effect=[started, result]), patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()):
client.login_oidc(open_browser=True, sleep=lambda _: None, clock=lambda: 0)
browser.assert_called_once_with('https://wiki.example/_/auth/cli/verify?request='+'R'*43, new=2)
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ, {'XDG_CONFIG_HOME': root}):
self.configure(None, '--origin', 'https://wiki.example')
calls = []
def login(client_arg, *args, **kwargs):
calls.append((args, kwargs))
client_arg.token = 'pw_api_'+'s'*43
return time.time()+600, 'anya'
with patch.object(Client, 'login_oidc', login), contextlib.redirect_stdout(io.StringIO()):
m['main'](['login', '--oidc', '--with-open-browser'])
self.assertIs(calls[-1][0][0], True)
with patch.object(Client, 'login_oidc') as login_mock, contextlib.redirect_stderr(io.StringIO()):
for bad_args in (['login', '--with-open-browser'], ['login', '--oidc', '--no-browser']):
with self.assertRaises(SystemExit) as exited:
m['main'](bad_args)
self.assertNotEqual(exited.exception.code, 0)
login_mock.assert_not_called()
def configure(self, root, *args):
with contextlib.redirect_stdout(io.StringIO()) as output:
m['configure'](list(args), root)
return output.getvalue()
def test_configuration_defaults_and_switch(self):
with tempfile.TemporaryDirectory() as root:
self.configure(root,'--origin','https://one.example','--username','anya')
self.configure(root,'set','--profile','work','--origin','https://two.example','--username','worker','--lang','ja')
self.configure(root,'use','work')
settings=json.loads(self.configure(root,'show'))
self.assertEqual(settings['default_profile'],'work')
self.assertEqual(settings['profiles']['default']['lang'],'auto')
self.assertEqual(settings['profiles']['work']['lang'],'ja')
self.configure(root,'--lang','en-US')
settings=json.loads(self.configure(root,'show'))
self.assertEqual(settings['profiles']['work']['lang'],'en-US')
self.configure(root,'--lang','und')
settings=json.loads(self.configure(root,'show'))
self.assertEqual(settings['profiles']['work']['lang'],'und')
with m['Configuration'](root).locked() as cfg:
self.assertEqual(stat.S_IMODE(cfg.path.stat().st_mode),0o600)
with self.assertRaises(Failure): self.configure(root,'use','missing')
with self.assertRaises(Failure): self.configure(root,'--lang','ja_JP')
def test_active_credentials_cannot_be_retargeted_or_shown(self):
with tempfile.TemporaryDirectory() as root:
self.configure(root,'--origin','https://one.example','--username','anya')
with Profile('default',root).locked() as profile:
profile.data={'origin':'https://one.example','username':'anya','token':'private-token'}; profile.save()
for args in [('--origin','https://other.example'),('--username','other')]:
with self.assertRaises(Failure): self.configure(root,*args)
self.assertNotIn('private-token',self.configure(root,'show'))
self.assertNotIn('private-token',self.configure(root,'list'))
self.configure(root,'--lang','ja')
with Profile('default',root).locked():
with self.assertRaises(Failure): self.configure(root,'--lang','en')
with Profile('default',root).locked() as profile:
profile.data.pop('token'); profile.save()
self.configure(root,'--origin','https://other.example')
def test_main_uses_saved_defaults_and_rejects_manual_retarget(self):
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}):
self.configure(root,'set','--profile','work','--origin','https://work.example','--username','worker','--lang','ja')
with Profile('work',root).locked() as profile:
profile.data={'origin':'https://work.example','username':'worker','token':'session-token','expires':time.time()+100,'cwd':'/notes'}; profile.save()
# Patch the globals used by main rather than running a real request.
globals=m['main'].__globals__
with patch.dict(globals,{'execute':lambda client,profile,args: self.assertEqual((client.base,client.lang,args),('https://work.example','ja',['ls']))}):
m['main'](['ls'])
with patch.dict(globals,{'execute':lambda client,profile,args: self.assertEqual(client.lang,'en')}):
m['main'](['--lang','en','ls'])
with m['Configuration'](root).locked() as cfg:
cfg.data['profiles']['work']['origin']='https://evil.example'; cfg.save()
with self.assertRaises(Failure): m['main'](['ls'])
def test_bad_configuration_is_not_printed(self):
with tempfile.TemporaryDirectory() as root:
with m['Configuration'](root).locked() as cfg:
cfg.data={'version':1,'default_profile':'default','profiles':{'default':{'origin':'https://example.test','token':'secret'}}}; cfg.save()
with self.assertRaises(Failure): self.configure(root,'show')
for invalid in [None,42,[],{}]:
with self.assertRaises(Failure): m['profile_name'](invalid)
with self.assertRaises(Failure): m['language'](invalid)
with self.assertRaises(Failure): m['origin'](invalid)
def test_origin_and_paths(self):
for value in ['http://example.com', 'https://user:pass@example.com', 'https://example.com/a', 'https://example.com?token=x']:
with self.assertRaises(Failure): m['origin'](value)
self.assertEqual(m['address']('../日本語 #?%', '/docs/deep'), 'path:/docs/日本語 #?%')
self.assertEqual(m['semantic']('../../..', '/'), '/')
for value in ['https://evil.test', 'asset:x:y', 'rev:bad', '/bad\x1b[31m']:
with self.assertRaises(Failure): m['address'](value)
self.assertNotIn('\x1b', m['safe_text']('\x1b]52;clipboard\x07'))
self.assertNotIn('\u202e', m['safe_text']('abc\u202e'))
def test_redirect_never_receives_bearer(self):
seen = []
with server(lambda h: (seen.append(h.headers.get('Authorization')), reply(h, 200, {}))) as sink:
def redirect(h):
h.send_response(302); h.send_header('Location', sink); h.end_headers()
with server(redirect) as base:
with self.assertRaises(Failure) as error: Client(base, 'secret').json('/test')
self.assertEqual(error.exception.status, 302)
self.assertEqual(seen, [])
def test_protocol_failures_and_limits(self):
for status, body, mime in [(200,b'<html>login</html>','text/html'), (200,b'not-json','application/json'), (403,b'private internal error','text/plain')]:
with server(lambda h: reply(h,status,body,mime)) as base:
with self.assertRaises(Failure) as error: Client(base).json('/test')
self.assertNotIn('private internal', str(error.exception))
with server(lambda h: reply(h,200,b'x'*100)) as base:
with self.assertRaises(Failure): Client(base).request('/large',limit=10)
def test_password_totp_contract(self):
requests = []
def handle(h):
requests.append((h.path, h.rfile.read(int(h.headers['Content-Length'])).decode()))
if h.path.endswith('/login'): reply(h,401,{'mfa_required':True,'challenge_token':'short-lived'})
else: reply(h,200,{'access_token':'a'*32,'token_type':'Bearer','expires_in':3600})
with server(handle) as base:
client = Client(base)
client.login('someone','secret',lambda prompt:'123456')
self.assertEqual(client.token,'a'*32)
self.assertIn('challenge_token=short-lived',requests[1][1])
self.assertNotIn('password',requests[1][1])
def test_private_profile_lock_and_symlinks(self):
with tempfile.TemporaryDirectory() as root:
with Profile('work',root).locked() as profile:
profile.data={'token':'secret'}; profile.save()
self.assertEqual(stat.S_IMODE(profile.path.stat().st_mode),0o600)
self.assertEqual(stat.S_IMODE(profile.root.stat().st_mode),0o700)
with self.assertRaises(Failure):
with Profile('work',root).locked(): pass
with Profile('work',root).locked() as loaded: self.assertEqual(loaded.data['token'],'secret')
profile.path.chmod(0o644)
with self.assertRaises(Failure):
with Profile('work',root).locked(): pass
profile.path.unlink(); profile.path.symlink_to(Path(root)/'missing')
with self.assertRaises(Failure):
with Profile('work',root).locked(): pass
def test_cas_and_authoring_contract(self):
state={'object_uuid':'object','head_revision_uuid':'base','principal_uuid':'person','lang':'ja',
'content_type':'text/html','filename':'a.html','body':'old'}
client=Client('https://example.test')
calls=[]
def api(route, **kwargs):
calls.append((route,kwargs['data']))
return {'html':'<p>new</p>'} if route.endswith('/markdown') else {'revision_uuid':'new'}
with patch.object(client,'json',side_effect=api): client.save(state,'new',True)
self.assertTrue(calls[0][1]['authoring']); self.assertFalse(calls[0][1]['projection'])
self.assertEqual(calls[1][1]['base_revision_uuid'],'base')
self.assertEqual(calls[1][1]['editor_principal_uuid'],'person')
self.assertEqual(calls[1][1]['lang'],'ja')
with patch.object(client,'json',side_effect=Failure('conflict',409)):
with self.assertRaises(Failure): client.save(state,'new')
def test_download_private_and_no_clobber(self):
headers=Message(); headers['X-PagesWiki-Revision-UUID']='rev'
with tempfile.TemporaryDirectory() as root:
profile=Profile('test',root)
client=Client('https://example.test')
file=str(Path(root)/'download')
with patch.object(client,'raw',return_value=(b'data',headers)), contextlib.redirect_stdout(io.StringIO()):
m['execute'](client,profile,['get','/path',file])
self.assertEqual(stat.S_IMODE(Path(file).stat().st_mode),0o600)
with self.assertRaises(FileExistsError): m['execute'](client,profile,['get','/path',file])
def test_auto_snapshot_pins_visible_language_and_head(self):
client=Client('https://example.test','token')
state={'lang':'ja','head_revision_uuid':'current-ja','content_type':'text/plain','filename':'x.txt','body':'new','markdown':'new','editable':True,'principal_uuid':'owner'}
headers={'X-PagesWiki-Object-UUID':'object','X-PagesWiki-Revision-UUID':'visible-ja'}
with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[{'lang':'ja'},state]) as api:
result=client.snapshot('path:/x')
self.assertEqual(result['lang'],'ja')
self.assertEqual(result['head_revision_uuid'],'current-ja')
self.assertIn('revision=visible-ja',api.call_args_list[0].args[0])
self.assertIn('lang=ja',api.call_args_list[1].args[0])
self.assertNotIn('revision=',api.call_args_list[1].args[0])
def test_fork_uses_empty_base_and_preserves_source(self):
client=Client('https://example.test','token','en')
target={'lang':'en','head_revision_uuid':'','content_type':'text/html','filename':'','body':'','markdown':'','editable':True,'principal_uuid':'owner'}
source=dict(target,lang='ja',body='<h1>Source</h1>',markdown='# Source',revision_uuid='ja-base')
headers={'X-PagesWiki-Object-UUID':'object','X-PagesWiki-Revision-UUID':'ja-base'}
with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[target,source]):
result=client.snapshot('path:/x')
self.assertEqual(result['lang'],'en'); self.assertEqual(result['head_revision_uuid'],'')
self.assertEqual(result['source_language'],'ja'); self.assertEqual(result['body'],source['body'])
with patch.object(client,'json',return_value={'revision_uuid':'en-new'}) as api:
client.save(result,result['body'])
self.assertEqual(api.call_args.kwargs['data']['base_revision_uuid'],'')
self.assertEqual(api.call_args.kwargs['data']['lang'],'en')
for changes in ({'editable':False},{'principal_uuid':'someone-else'}):
with patch.object(client,'raw',return_value=(b'',headers)),patch.object(client,'json',side_effect=[dict(target,head_revision_uuid=''),dict(source,**changes)]):
with self.assertRaises(Failure): client.snapshot('path:/x')
def test_editor_unchanged_fork_does_not_save(self):
client=Client('https://example.test','token','ja')
state={'object_uuid':'object','head_revision_uuid':'','principal_uuid':'owner','lang':'ja',
'content_type':'text/plain','filename':'x.txt','body':'source','markdown':'source','new_language':True,'source_language':'und'}
with patch.object(client,'snapshot',return_value=state),patch.object(client,'save') as save,patch('subprocess.run') as command,contextlib.redirect_stdout(io.StringIO()):
command.return_value.returncode=0
m['editor'](client,'path:/x','auto')
save.assert_not_called()
self.assertFalse(Path(command.call_args.args[0][-1]).exists())
def test_edit_language_override_does_not_change_profile(self):
client=Client('https://example.test','token','und')
with tempfile.TemporaryDirectory() as root:
profile=Profile('test',root)
profile.data={'cwd':'/notes'}
def editor_override(editing,addr,mode):
self.assertEqual((editing.base,editing.token,editing.lang),(client.base,client.token,'auto'))
self.assertEqual((addr,mode),('path:/notes/page','auto'))
with patch.dict(m['execute'].__globals__,{'editor':editor_override}):
m['execute'](client,profile,['edit','page','--lang','auto'])
self.assertEqual(client.lang,'und')
self.assertEqual(profile.data,{'cwd':'/notes'})
with patch.object(client,'snapshot',return_value={'head_revision_uuid':''}),patch.object(client,'save') as save:
with self.assertRaisesRegex(Failure,'use edit --lang'):
m['execute'](client,profile,['put','unused','page','--base',''])
save.assert_not_called()
def test_editor_conflict_retains_private_recovery(self):
state={'object_uuid':'object','head_revision_uuid':'base','principal_uuid':'person','lang':'und',
'content_type':'text/plain','filename':'x.txt','body':'old','markdown':'old'}
client=Client('https://example.test','secret-token')
with tempfile.TemporaryDirectory() as root:
directory=Path(root)/'working'; directory.mkdir(mode=0o700)
def edit(args, **kwargs):
Path(args[-1]).write_text('my edit')
class Result: returncode=0
return Result()
with patch('tempfile.mkdtemp',return_value=str(directory)), patch('subprocess.run',side_effect=edit), patch.object(client,'snapshot',return_value=state) as snapshot, patch.object(client,'save',side_effect=Failure('conflict',409)), patch.object(m['sys'],'stdin',io.StringIO('')), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(Failure): m['editor'](client,'path:/x','auto')
snapshot.assert_called_with('uuid:object',lang='und')
self.assertEqual((directory/'document.txt').read_text(),'my edit')
recovery=(directory/'recovery.json').read_text()
self.assertNotIn('secret-token',recovery)
self.assertIn('base',recovery)
self.assertEqual(stat.S_IMODE((directory/'recovery.json').stat().st_mode),0o600)
def test_create_page_put_contract_and_errors(self):
recorded = []
mode = {'status': 201, 'headers': None}
def handle(h):
length = int(h.headers.get('Content-Length', 0))
body = h.rfile.read(length)
recorded.append((h.command, h.path, h.headers, body))
if h.path == '/_/api/v1/render/markdown':
req = json.loads(body)
self.assertTrue(req['authoring'])
self.assertFalse(req['projection'])
reply(h, 200, {'html': '<p>' + req['markdown'].strip() + '</p>'})
return
if mode['status'] != 201:
reply(h, mode['status'], {'error': 'rejected'})
return
digest = hashlib.sha256(body).hexdigest()
headers = {
'Content-Type': 'application/json; charset=utf-8',
'Location': '/o/uuid:00000000-0000-4000-8000-000000000001',
'ETag': '"' + digest + '"',
'Content-Language': h.headers.get('Content-Language', 'und'),
'X-PagesWiki-Object-UUID': '00000000-0000-4000-8000-000000000001',
'X-PagesWiki-Revision-UUID': '00000000-0000-4000-8000-000000000002',
'X-PagesWiki-Document-SHA256': digest,
}
if mode['headers'] is not None:
headers = mode['headers'](digest)
h.send_response(201)
for k, v in headers.items():
h.send_header(k, v)
h.end_headers()
with server(handle) as base:
client = Client(base, 'secret-token', 'auto')
created = client.create_page('path:/docs/新規 ガイド', '# Title\n', markdown=True)
self.assertEqual(created['path'], '/docs/新規 ガイド')
self.assertEqual(created['lang'], 'und')
self.assertEqual(created['object_uuid'], '00000000-0000-4000-8000-000000000001')
self.assertEqual(created['revision_uuid'], '00000000-0000-4000-8000-000000000002')
self.assertEqual(recorded[0][0], 'POST')
self.assertEqual(recorded[0][1], '/_/api/v1/render/markdown')
method, path, hdrs, raw = recorded[1]
self.assertEqual(method, 'PUT')
self.assertEqual(path, '/_/api/v1/pages/path:/docs/%E6%96%B0%E8%A6%8F%20%E3%82%AC%E3%82%A4%E3%83%89')
self.assertEqual(hdrs.get('Authorization'), 'Bearer secret-token')
self.assertEqual(hdrs.get('If-None-Match'), '*')
self.assertEqual(hdrs.get('Content-Language'), 'und')
self.assertEqual(hdrs.get('Content-Type'), 'text/html; charset=utf-8')
self.assertEqual(hdrs.get('X-PagesWiki-Commit-Message'), 'Remote%20CLI%20create')
self.assertEqual(raw, b'<p># Title</p>')
recorded.clear()
raw_created = client.create_page('path:/notes/memo.txt', 'hello', markdown=False, lang='ja', filename='メモ.txt')
self.assertEqual(raw_created['lang'], 'ja')
self.assertEqual(len(recorded), 1)
self.assertEqual(recorded[0][0], 'PUT')
self.assertEqual(recorded[0][2].get('Content-Type'), 'text/plain; charset=utf-8')
self.assertEqual(recorded[0][2].get('Content-Language'), 'ja')
self.assertEqual(recorded[0][2].get('X-PagesWiki-Filename'), '%E3%83%A1%E3%83%A2.txt')
self.assertEqual(recorded[0][3], b'hello')
before = len(recorded)
for bad in ('path:/', 'uuid:00000000-0000-0000-0000-000000000000', 'rev:00000000-0000-0000-0000-000000000000'):
with self.assertRaises(Failure):
client.create_page(bad, 'x')
with self.assertRaises(Failure):
client.create_page('path:/too-big', 'a' * ((1 << 20) + 1))
self.assertEqual(len(recorded), before)
mode['headers'] = lambda d: {'X-PagesWiki-Object-UUID': '00000000-0000-4000-8000-000000000001'}
with self.assertRaisesRegex(Failure, 'missing document identity'):
client.create_page('path:/bad-headers', 'x')
mode['headers'] = None
for status, pattern in ((200, 'Unexpected HTTP status'), (412, 'already exists'), (428, 'If-None-Match'), (404, 'unavailable'), (405, 'unavailable'), (501, 'unavailable'), (403, 'Access denied')):
recorded.clear()
mode['status'] = status
with self.assertRaisesRegex(Failure, pattern) as caught:
client.create_page('path:/err', 'x')
self.assertEqual(caught.exception.status, status)
self.assertEqual(len(recorded), 1)
def test_editor_creates_new_page_with_confirmation_and_und_warning(self):
client = Client('https://example.test', 'token', 'auto')
with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: False}), \
patch.object(client, 'create_page') as create_mock, \
patch('subprocess.run') as run_mock, \
contextlib.redirect_stdout(io.StringIO()) as out:
m['editor'](client, 'path:/docs/new', 'auto')
self.assertIn('Aborted.', out.getvalue())
run_mock.assert_not_called()
create_mock.assert_not_called()
def edit_ok(args, **kwargs):
Path(args[-1]).write_text('# Hello\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-1', 'revision_uuid': 'rev-1'}) as create_mock, \
patch('subprocess.run', side_effect=edit_ok) as run_mock, \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
m['editor'](client, 'path:/docs/new', 'auto')
self.assertIn("WARNING: Creating a new page with language 'und'", err.getvalue())
self.assertIn('Created page: /docs/new', out.getvalue())
self.assertTrue(run_mock.call_args.args[0][-1].endswith('document.md'))
self.assertFalse(Path(run_mock.call_args.args[0][-1]).exists())
create_mock.assert_called_once_with('path:/docs/new', '# Hello\n', True, lang='und')
client_ja = Client('https://example.test', 'token', 'ja')
with patch.object(client_ja, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client_ja, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-1', 'revision_uuid': 'rev-1'}) as create_mock, \
patch('subprocess.run', side_effect=edit_ok), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
m['editor'](client_ja, 'path:/docs/new', 'raw')
self.assertEqual(err.getvalue(), '')
create_mock.assert_called_once_with('path:/docs/new', '# Hello\n', False, lang='ja')
confirm_calls = []
def record_confirm(addr, status):
confirm_calls.append((addr, status))
return True
with patch.object(client_ja, 'snapshot', side_effect=Failure('Access denied', 403)), \
patch.dict(m['editor'].__globals__, {'confirm_create': record_confirm}), \
patch.object(client_ja, 'create_page', return_value={'path': '/docs/create-only', 'object_uuid': 'obj-2', 'revision_uuid': 'rev-2'}), \
patch('subprocess.run', side_effect=edit_ok), \
contextlib.redirect_stdout(io.StringIO()):
m['editor'](client_ja, 'path:/docs/create-only', 'auto')
self.assertEqual(confirm_calls, [('path:/docs/create-only', 403)])
for non_creatable in ('uuid:00000000-0000-0000-0000-000000000000', 'rev:00000000-0000-0000-0000-000000000000', 'path:/'):
with patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda *_: self.fail('should not prompt')}):
with self.assertRaises(Failure):
m['editor'](client, non_creatable, 'auto')
non_tty = io.StringIO('y\n')
with patch.object(m['sys'], 'stdin', non_tty), \
patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)):
with self.assertRaises(Failure) as caught:
m['editor'](client, 'path:/docs/new', 'auto')
self.assertEqual(caught.exception.status, 404)
def test_editor_new_page_empty_aborts_and_failure_retains_private_recovery(self):
client = Client('https://example.test', 'secret-token', 'auto')
with tempfile.TemporaryDirectory() as root:
directory = Path(root) / 'empty'; directory.mkdir(mode=0o700)
with patch('tempfile.mkdtemp', return_value=str(directory)), \
patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client, 'create_page') as create_mock, \
patch('subprocess.run', return_value=type('R', (), {'returncode': 0})()), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()):
m['editor'](client, 'path:/docs/empty', 'auto')
create_mock.assert_not_called()
self.assertIn('was not created', out.getvalue())
self.assertFalse(directory.exists())
working = Path(root) / 'race'; working.mkdir(mode=0o700)
def edit_write(args, **kwargs):
Path(args[-1]).write_text('draft body', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(working)), \
patch.object(client, 'snapshot', side_effect=Failure('Not found', 404)), \
patch.dict(m['editor'].__globals__, {'confirm_create': lambda addr, st: True}), \
patch.object(client, 'create_page', side_effect=Failure('Conflict', 412)), \
patch('subprocess.run', side_effect=edit_write), \
patch.object(m['sys'], 'stdin', io.StringIO('')), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
with self.assertRaises(Failure) as caught:
m['editor'](client, 'path:/docs/race', 'auto')
self.assertEqual(caught.exception.status, 412)
self.assertNotIn('secret-token', err.getvalue())
self.assertEqual((working / 'document.md').read_text(encoding='utf-8'), 'draft body')
self.assertEqual(stat.S_IMODE((working / 'document.md').stat().st_mode), 0o600)
recovery_text = (working / 'recovery.json').read_text(encoding='utf-8')
self.assertNotIn('secret-token', recovery_text)
recovery = json.loads(recovery_text)
self.assertEqual(recovery['mode'], 'create')
self.assertEqual(recovery['address'], 'path:/docs/race')
self.assertEqual(recovery['lang'], 'und')
self.assertEqual(recovery['format'], 'markdown')
self.assertEqual(stat.S_IMODE((working / 'recovery.json').stat().st_mode), 0o600)
def test_editor_409_interactive_edit_and_force_save(self):
state = {'object_uuid': 'object', 'head_revision_uuid': 'base-rev', 'principal_uuid': 'person', 'lang': 'und',
'content_type': 'text/plain', 'filename': 'x.txt', 'body': 'base\n', 'markdown': 'base\n'}
latest = {'object_uuid': 'object', 'head_revision_uuid': 'latest-rev', 'principal_uuid': 'person', 'lang': 'und',
'content_type': 'text/plain', 'filename': 'x.txt', 'body': 'remote line\n', 'markdown': 'remote line\n'}
client = Client('https://example.test', 'token')
with tempfile.TemporaryDirectory() as root:
working = Path(root) / 'merge'; working.mkdir(mode=0o700)
seen_buffers = []
call_count = [0]
def run_ed(args, **kwargs):
call_count[0] += 1
p = Path(args[-1])
if call_count[0] == 1:
p.write_text('local line\n', encoding='utf-8')
else:
seen_buffers.append(p.read_text(encoding='utf-8'))
p.write_text('merged line\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(working)), \
patch('subprocess.run', side_effect=run_ed), \
patch.object(client, 'snapshot', side_effect=[state, latest]), \
patch.object(client, 'save', side_effect=[Failure('conflict', 409), {'revision_uuid': 'merged-rev'}]) as save_mock, \
patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \
contextlib.redirect_stdout(io.StringIO()) as out:
m['editor'](client, 'path:/x', 'auto')
self.assertIn('<<<<<<< local\nlocal line\n=======\nremote line\n>>>>>>> remote (rev: latest-rev)\n', seen_buffers[0])
self.assertEqual(save_mock.call_args_list[1].args, (latest, 'merged line\n', False))
self.assertIn('Saved revision: merged-rev', out.getvalue())
self.assertFalse(working.exists())
markers = Path(root) / 'markers'; markers.mkdir(mode=0o700)
call_count[0] = 0
def leave_markers(args, **kwargs):
call_count[0] += 1
if call_count[0] == 1:
Path(args[-1]).write_text('local line\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(markers)), \
patch('subprocess.run', side_effect=leave_markers), \
patch.object(client, 'snapshot', side_effect=[state, latest]), \
patch.object(client, 'save', side_effect=Failure('conflict', 409)) as save_mock, \
patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \
contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()) as err:
with self.assertRaises(Failure) as caught:
m['editor'](client, 'path:/x', 'auto')
self.assertEqual(caught.exception.status, 409)
self.assertEqual(save_mock.call_count, 1)
self.assertIn('Conflict markers remain', err.getvalue())
self.assertTrue((markers / 'recovery.json').exists())
force_dir = Path(root) / 'force'; force_dir.mkdir(mode=0o700)
def edit_local(args, **kwargs):
Path(args[-1]).write_text('forced body\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(force_dir)), \
patch('subprocess.run', side_effect=edit_local) as run_mock, \
patch.object(client, 'snapshot', side_effect=[state, latest]), \
patch.object(client, 'save', side_effect=[Failure('conflict', 409), {'revision_uuid': 'forced-rev'}]) as save_mock, \
patch.dict(m['editor'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'f'}), \
contextlib.redirect_stdout(io.StringIO()) as out:
m['editor'](client, 'path:/x', 'auto')
self.assertEqual(run_mock.call_count, 1)
self.assertEqual(save_mock.call_args_list[1].args, (latest, 'forced body\n', False))
self.assertIn('Saved revision: forced-rev', out.getvalue())
self.assertFalse(force_dir.exists())
def test_editor_412_interactive_pick_path_and_merge(self):
client = Client('https://example.test', 'token', 'auto')
with tempfile.TemporaryDirectory() as root:
pick_dir = Path(root) / 'pick'; pick_dir.mkdir(mode=0o700)
def edit_new(args, **kwargs):
Path(args[-1]).write_text('# New Draft\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(pick_dir)), \
patch('subprocess.run', side_effect=edit_new), \
patch.object(client, 'snapshot', side_effect=[Failure('Not found', 404), Failure('Forbidden', 403)]), \
patch.object(client, 'create_page', side_effect=[Failure('Exists', 412), {'path': '/docs/alt', 'object_uuid': 'obj-2', 'revision_uuid': 'rev-2'}]) as create_mock, \
patch.dict(m['editor'].__globals__, {
'confirm_create': lambda addr, st: True,
'choose_conflict_action': lambda kind, has_remote=True: 'p',
'prompt_new_path': lambda cwd='/': 'path:/docs/alt',
}), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()):
m['editor'](client, 'path:/docs/orig', 'auto')
self.assertEqual(create_mock.call_args_list[1].args[0], 'path:/docs/alt')
self.assertIn('Created page: /docs/alt', out.getvalue())
self.assertFalse(pick_dir.exists())
merge_dir = Path(root) / 'merge-create'; merge_dir.mkdir(mode=0o700)
existing = {'object_uuid': 'obj-existing', 'head_revision_uuid': 'rev-existing', 'principal_uuid': 'person',
'lang': 'ja', 'content_type': 'text/html', 'filename': '', 'body': '<p>Existing</p>', 'markdown': 'Existing\n'}
call_count = [0]
seen_buffers = []
def edit_merge(args, **kwargs):
call_count[0] += 1
p = Path(args[-1])
if call_count[0] == 1:
p.write_text('My new page\n', encoding='utf-8')
else:
seen_buffers.append(p.read_text(encoding='utf-8'))
p.write_text('Combined page\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch('tempfile.mkdtemp', return_value=str(merge_dir)), \
patch('subprocess.run', side_effect=edit_merge), \
patch.object(client, 'snapshot', side_effect=[Failure('Not found', 404), existing]), \
patch.object(client, 'create_page', side_effect=Failure('Exists', 412)), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-combined'}) as save_mock, \
patch.dict(m['editor'].__globals__, {
'confirm_create': lambda addr, st: True,
'choose_conflict_action': lambda kind, has_remote=True: 'e',
}), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()):
m['editor'](client, 'path:/docs/race', 'auto')
self.assertIn('<<<<<<< local\nMy new page\n=======\nExisting\n>>>>>>> remote (rev: rev-existing)\n', seen_buffers[0])
save_mock.assert_called_once_with(existing, 'Combined page\n', True)
self.assertIn('Saved revision: rev-combined', out.getvalue())
self.assertFalse(merge_dir.exists())
def test_recover_list_resume_conflict_discard_and_security(self):
client = Client('https://example.test', 'token', 'auto')
profile = type('P', (), {'data': {'cwd': '/notes'}})()
def make_draft(base_dir, name, meta, doc_text, *, dir_mode=0o700, file_mode=0o600):
d = Path(base_dir) / name
d.mkdir(mode=0o700)
doc_name = 'document.md' if meta['format'] == 'markdown' else 'document.txt'
doc = d / doc_name
doc.touch(mode=0o600); doc.write_text(doc_text, encoding='utf-8'); doc.chmod(file_mode)
meta_file = d / 'recovery.json'
meta_file.touch(mode=0o600); meta_file.write_text(json.dumps(meta), encoding='utf-8'); meta_file.chmod(file_mode)
d.chmod(dir_mode)
return d, doc, meta_file
with tempfile.TemporaryDirectory() as root:
good_dir, good_doc, _ = make_draft(root, 'pageswiki-edit-good', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'ja', 'format': 'raw',
}, 'recovered text\n')
make_draft(root, 'pageswiki-edit-badperm', {
'origin': 'https://example.test', 'address': 'uuid:obj-2',
'base_revision_uuid': 'rev-2', 'lang': 'ja', 'format': 'raw',
}, 'ignored\n', dir_mode=0o755)
bad_link = Path(root) / 'pageswiki-edit-symlink'
bad_link.symlink_to(good_dir)
out = io.StringIO()
with contextlib.redirect_stdout(out):
m['recover'](client, profile, list_only=True, temp_root=root)
lines = out.getvalue().strip().splitlines()
self.assertEqual(len(lines), 1)
self.assertIn(str(good_dir), lines[0])
self.assertNotIn('badperm', out.getvalue())
self.assertNotIn('symlink', out.getvalue())
bad_link.unlink()
# Resume update when head still matches.
state = {'object_uuid': 'obj-1', 'head_revision_uuid': 'rev-1', 'principal_uuid': 'person',
'lang': 'ja', 'content_type': 'text/plain', 'filename': 'a.txt', 'body': 'old', 'markdown': 'old'}
with patch.object(client, 'snapshot', return_value=state), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-2'}) as save_mock, \
contextlib.redirect_stdout(io.StringIO()) as out:
m['recover'](client, profile, str(good_doc))
save_mock.assert_called_once_with(state, 'recovered text\n', False)
self.assertIn('Saved revision: rev-2', out.getvalue())
self.assertFalse(good_dir.exists())
# Resume update when remote head changed: non-interactive keeps draft; interactive 'e' merges.
moved_dir, moved_doc, _ = make_draft(root, 'pageswiki-edit-moved', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'ja', 'format': 'raw',
}, 'draft edit\n')
newer = {'object_uuid': 'obj-1', 'head_revision_uuid': 'rev-9', 'principal_uuid': 'person',
'lang': 'ja', 'content_type': 'text/plain', 'filename': 'a.txt', 'body': 'newer remote\n', 'markdown': 'newer remote\n'}
with patch.object(client, 'snapshot', return_value=newer), \
patch.object(client, 'save') as save_mock, \
patch.object(m['sys'], 'stdin', io.StringIO('')), \
contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(Failure) as caught:
m['recover'](client, profile, str(moved_dir))
self.assertEqual(caught.exception.status, 409)
save_mock.assert_not_called()
self.assertTrue(moved_doc.exists())
def resolve_in_ed(args, **kwargs):
p = Path(args[-1])
self.assertIn('<<<<<<< local\ndraft edit\n=======\nnewer remote\n>>>>>>> remote (rev: rev-9)\n', p.read_text(encoding='utf-8'))
p.write_text('resolved draft\n', encoding='utf-8')
return type('R', (), {'returncode': 0})()
with patch.object(client, 'snapshot', return_value=newer), \
patch.object(client, 'save', return_value={'revision_uuid': 'rev-10'}) as save_mock, \
patch('subprocess.run', side_effect=resolve_in_ed), \
patch.dict(m['recover'].__globals__, {'choose_conflict_action': lambda kind, has_remote=True: 'e'}), \
contextlib.redirect_stdout(io.StringIO()):
m['recover'](client, profile, str(moved_dir))
save_mock.assert_called_once_with(newer, 'resolved draft\n', False)
self.assertFalse(moved_dir.exists())
# Resume create draft.
create_dir, _, _ = make_draft(root, 'pageswiki-edit-create', {
'origin': 'https://example.test', 'mode': 'create', 'address': 'path:/docs/new',
'lang': 'und', 'format': 'markdown',
}, '# Created from recovery\n')
with patch.object(client, 'create_page', return_value={'path': '/docs/new', 'object_uuid': 'obj-new', 'revision_uuid': 'rev-new'}) as create_mock, \
contextlib.redirect_stdout(io.StringIO()) as out:
m['recover'](client, profile, str(create_dir))
create_mock.assert_called_once_with('path:/docs/new', '# Created from recovery\n', True, lang='und')
self.assertIn('Created page: /docs/new', out.getvalue())
self.assertFalse(create_dir.exists())
# Reject wrong origin with zero network calls.
other_dir, _, _ = make_draft(root, 'pageswiki-edit-other', {
'origin': 'https://other.example', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'other\n')
with patch.object(client, 'snapshot') as snap_mock, patch.object(client, 'save') as save_mock:
with self.assertRaisesRegex(Failure, 'different server origin'):
m['recover'](client, profile, str(other_dir))
snap_mock.assert_not_called(); save_mock.assert_not_called()
# Reject insecure permissions and discard safety check.
_, insecure_doc, _ = make_draft(root, 'pageswiki-edit-insecure', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'x\n', file_mode=0o644)
with self.assertRaisesRegex(Failure, '0600'):
m['recover'](client, profile, str(insecure_doc))
outside_dir, _, _ = make_draft(root, 'custom-dir', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'x\n')
with self.assertRaisesRegex(Failure, 'Refusing to discard'):
m['recover'](client, profile, str(outside_dir), discard=True)
self.assertTrue(outside_dir.exists())
discard_dir, _, _ = make_draft(root, 'pageswiki-edit-discard', {
'origin': 'https://example.test', 'address': 'uuid:obj-1',
'base_revision_uuid': 'rev-1', 'lang': 'und', 'format': 'raw',
}, 'x\n')
with contextlib.redirect_stdout(io.StringIO()) as out:
m['recover'](client, profile, str(discard_dir), discard=True)
self.assertIn('Discarded recovery draft', out.getvalue())
self.assertFalse(discard_dir.exists())
def oidc_integration():
fixture=json.load(sys.stdin)
original=Client.json
grant={}
def capture(client,route,**kwargs):
result=original(client,route,**kwargs)
if route=='/_/auth/cli/start': grant.update(result)
return result
def browser(target,**kwargs):
ident=m['url'].parse_qs(m['url'].urlsplit(target).query)['request'][0]
original(Client(fixture['origin']),'/__test/cli-approve',method='POST',form={'request':ident,'code':grant['user_code']})
return True
with tempfile.TemporaryDirectory() as root,patch.dict(os.environ,{'XDG_CONFIG_HOME':root}),contextlib.redirect_stdout(io.StringIO()) as output:
m['main'](['configure','--origin',fixture['origin']])
with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc','--with-open-browser'])
with Profile('default',root).locked() as session:
token=session.data['token']; assert session.data['username']=='admin'
m['main'](['ls']); m['main'](['status'])
client=Client(fixture['origin'],token)
state=client.snapshot('path:/editor-fixture')
client.save(state,'# OIDC edit\n\n{{children}}\n',True)
assert '{{children}}' in client.snapshot('path:/editor-fixture')['markdown']
m['main'](['logout'])
assert token not in output.getvalue()
try: client.snapshot('path:/editor-fixture')
except Failure as e: assert e.status in (401,403,303)
else: raise AssertionError('revoked CLI session accepted')
print('OIDC CLI configure/login/list/authoring/logout integration passed')
def integration():
fixture=json.load(sys.stdin)
# Exercise the public entry point with persisted defaults, not only Client.
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}), contextlib.redirect_stdout(io.StringIO()) as output:
m['main'](['configure','--origin',fixture['origin'],'--username','admin'])
with patch('getpass.getpass',return_value='a long test password'): m['main'](['login'])
with Profile('default',root).locked() as session: session_token=session.data['token']
m['main'](['ls'])
m['main'](['status'])
def local_editor(args, **kwargs):
file=Path(args[-1]); file.write_text(file.read_text()+'\nConfigured CLI edit\n')
class Result: returncode=0
return Result()
with patch('subprocess.run',side_effect=local_editor): m['main'](['edit','/editor-fixture'])
check=Client(fixture['origin'],session_token)
assert 'Configured CLI edit' in check.snapshot('path:/editor-fixture')['body']
m['main'](['logout'])
assert session_token not in output.getvalue()
with Profile('default',root).locked() as session: assert 'token' not in session.data
client=Client(fixture['origin'], lang='und')
client.login('admin','a long test password')
addr='path:/editor-fixture'
state=client.snapshot(addr)
assert state['lang']=='und' and state['principal_uuid']
missing=Client(fixture['origin'], client.token, 'ja')
fork=missing.snapshot(addr)
assert fork['lang']=='ja' and fork['head_revision_uuid']=='' and fork['new_language']
assert fork['body']==state['body'] and fork['source_language']=='und'
missing.save(fork,'# Japanese draft\n\n{{children}}\n',True)
assert missing.snapshot(addr)['lang']=='ja'
assert client.snapshot(addr)['head_revision_uuid']==state['head_revision_uuid']
try: missing.save(fork,'competing first revision')
except Failure as e: assert e.status==409
else: raise AssertionError('concurrent language creation overwrote the head')
auto=Client(fixture['origin'],client.token)
auto_state=auto.snapshot('path:/ja-only')
assert auto_state['lang']=='ja' and auto_state['head_revision_uuid']
def edit_japanese(args, **kwargs):
path=Path(args[-1]); path.write_text(path.read_text()+'\nJapanese edit\n')
class Result: returncode=0
return Result()
with patch('subprocess.run',side_effect=edit_japanese),contextlib.redirect_stdout(io.StringIO()):
m['editor'](auto,'path:/ja-only','auto')
assert 'Japanese edit' in auto.snapshot('path:/ja-only')['body']
pending=Client(fixture['origin'],client.token,'und').snapshot('path:/ja-only')
assert pending['head_revision_uuid']==''
assert client.listing('/')['entries']
assert client.save(state,'# Remote\n\n{{children}}\n',True)['revision_uuid'] != state['head_revision_uuid']
latest=client.snapshot(addr)
assert '{{children}}' in latest['markdown'] and '<h1' in latest['body']
try: client.save(state,'stale edit')
except Failure as e: assert e.status==409
else: raise AssertionError('stale save accepted')
raw,headers=client.raw(addr)
assert hashlib.sha256(raw).hexdigest()==headers['X-PagesWiki-Document-SHA256']
assert client.raw('rev:'+latest['revision_uuid'])[0]==raw
try: client.snapshot('rev:'+latest['revision_uuid'])
except Failure: pass
else: raise AssertionError('immutable edit accepted')
with tempfile.TemporaryDirectory() as root:
profile=Profile('integration',root)
profile.data={'cwd':'/'}
file=Path(root)/'edit.txt'; file.write_text('local replacement')
with contextlib.redirect_stdout(io.StringIO()):
m['execute'](client,profile,['put',str(file),addr,'--base',latest['head_revision_uuid']])
assert client.snapshot(addr)['body']=='local replacement'
client.json('/_/auth/logout',method='POST')
try: client.snapshot(addr)
except Failure as e: assert e.status in (401,403,303)
else: raise AssertionError('revoked session accepted')
print('Remote login/list/read/authoring/CAS/put/logout integration passed')
if __name__=='__main__':
if sys.argv[1:] == ['--integration']: integration()
elif sys.argv[1:] == ['--oidc-integration']: oidc_integration()
else: unittest.main()