Files
pages-cli/tools/smoke_binary.py
T
Anya Tokugawa e27c023d66
Test and release pages-cli / linux (push) Successful in 19s
Test and release pages-cli / macos (push) Skipped
fix: explicitly recreate deleted task captures
2026-11-08 19:26:51 +09:00

74 lines
4.9 KiB
Python

"""Exercise the actual packaged executable against a synthetic loopback API."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
binary=str(Path(sys.argv[1]).resolve())
token='synthetic_session_'+('x'*40)
seen=[]
captures=[]
class Handler(BaseHTTPRequestHandler):
def log_message(self,*args):pass
def do_POST(self):
body=self.rfile.read(int(self.headers.get('Content-Length',0)))
if self.path=='/_/auth/login': self.reply({'access_token':token,'token_type':'Bearer','expires_in':3600})
elif self.path=='/_/auth/logout':self.reply({})
elif self.path=='/_/api/v1/extension/organizer.tasks/capture':
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
item=json.loads(body)
captures.append(item.copy())
if item.get('wiki_prefix')=='/rejected':self.reply({'error':'invalid'},422);return
if item.get('wiki_prefix')=='/deleted' and not item.get('replaces_deleted'):self.reply({'error':'deleted'},410);return
if item.get('replaces_deleted') and item['request_id']!=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+item['replaces_deleted'])):self.send_error(422);return
if item.get('wiki_body') != 'Message-ID: <smoke@example.invalid>\n\nPRIVATE BODY':self.send_error(422);return
item.pop('wiki_body');self.reply({'item':item,'page_path':'/private/mail/synthetic'})
else:self.send_error(404)
def do_GET(self):
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
seen.append(self.path)
if self.path.startswith('/_/api/v1/extension/organizer.contacts/items?'):
self.reply({'items':[{'name':'Synthetic Person','emails':['person@example.invalid'],'organization':'Test'}]})
else:self.reply({'items':[{'uuid':'synthetic-task','title':'Packaged CLI task','status':'todo'}]})
def reply(self,value,status=200):
self.send_response(status);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps(value).encode())
server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
try:
with tempfile.TemporaryDirectory() as root:
env={**os.environ,'XDG_CONFIG_HOME':root}
def run(*args,stdin='',success=True):
p=subprocess.run([binary,*args],input=stdin,text=True,capture_output=True,env=env,timeout=15)
if token in p.stdout+p.stderr:raise AssertionError('Credential leaked')
if (p.returncode==0)!=success:raise AssertionError('Packaged command failed: '+str(args)+' '+p.stderr)
return p.stdout
run('configure','--origin',f'http://127.0.0.1:{server.server_port}','--username','synthetic')
run('login',stdin='synthetic-password\n')
if 'Packaged CLI task' not in run('task','list'):raise AssertionError('Task missing')
mail='Subject: Mail task\r\nMessage-ID: <smoke@example.invalid>\r\nContent-Type: text/plain\r\n\r\nPRIVATE BODY'
run('task','from-mail','--wiki-prefix','/rejected',stdin=mail,success=False)
captured=run('task','from-mail','--wiki-prefix','/private/mail',stdin=mail)
if len(captures)!=2 or captures[0]['request_id']!=captures[1]['request_id'] or captures[1]['wiki_prefix']!='/private/mail':raise AssertionError('Retained draft was not overwritten under the same request ID')
if 'Mail task' not in captured or 'PRIVATE BODY' in captured:raise AssertionError('Mail privacy')
run('task','from-mail','--wiki-prefix','/deleted',stdin=mail,success=False)
deleted_id=captures[-1]['request_id']
restored=json.loads(run('task','retry',deleted_id,'--recreate-deleted'))['item']
if restored['request_id']!=str(uuid.uuid5(uuid.NAMESPACE_URL,'pages:task-recreate:'+deleted_id)) or restored['replaces_deleted']!=deleted_id:raise AssertionError('Recreation identity')
contact=run('contacts','query','--neomutt','--','--name')
if 'person@example.invalid\tSynthetic Person\tTest' not in contact:raise AssertionError('NeoMutt query')
run('shell',stdin='pwd\nexit\n')
profile=Path(root)/'pages-cli/sessions/default.json'
if json.loads(profile.read_text()).get('task_outbox'):raise AssertionError('Successful replacement remains pending')
if profile.stat().st_mode&0o077:raise AssertionError('Credential permissions')
profile.chmod(0o644);run('task','list',success=False);profile.chmod(0o600)
run('logout')
if not seen:raise AssertionError('No HTTP request')
print('Packaged CLI: configure/login/task-list/mail-capture/draft-overwrite/deleted-recreation/neomutt-query/shell/permissions/logout passed')
finally:server.shutdown();server.server_close();thread.join()