Files
pages/pages-cli/test_neomutt_viewer.py

110 lines
5.6 KiB
Python

"""Synthetic NeoMutt pipe -> real CLI -> full HTTP router -> browser viewer.
Run by TestNeoMuttMailViewerFlow; never reads a real mail or CLI profile.
"""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
from email.header import Header
from html.parser import HTMLParser
from urllib.parse import quote, unquote, urlencode, urlsplit
from urllib.request import Request, urlopen
class Links(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if 'browser-row' in attrs.get('class', '').split():
self.links.append(attrs.get('data-path', ''))
if tag == 'a':
self.links.append(attrs.get('href', ''))
def main():
fixture = json.load(sys.stdin)
root = Path(fixture['root'])
env = {**os.environ, 'HOME': str(root), 'XDG_CONFIG_HOME': str(root / 'config')}
executable = str(Path(__file__).with_name('pages').resolve())
binary = os.environ.get('PAGES_CLI_TEST_BINARY')
command = [str(Path(binary).resolve())] if binary else [sys.executable, executable]
def cli(*args, data=b''):
run = subprocess.run([*command, *args], input=data,
capture_output=True, env=env, timeout=15)
assert run.returncode == 0, (args, run.stderr.decode())
return run.stdout
def get(path):
request = Request(fixture['origin'] + quote(path, safe='/:?=&%'),
headers={'Cookie': 'pageswiki_session=' + fixture['browser'],
'Accept-Language': 'ja,en;q=0.8'})
with urlopen(request, timeout=10) as response:
body = response.read().decode()
assert response.status == 200, (path, response.status)
assert response.headers.get_content_type() == 'text/html', (path, body[:100])
assert unquote(urlsplit(response.url).path) == unquote(urlsplit(path).path).rstrip('/'), response.url
return body
cli('configure', '--origin', fixture['origin'], '--username', 'admin')
cli('login', data=b'a long test password\n')
paths = []
for parent in ['/tasks', '/mail', '/private/mail', '/受信 メール', '/u/admin/mail', '/docs/mail', '/api/mail']:
cli('task', 'preferences', '--wiki-prefix', parent)
for charset in ['utf-8', 'iso-2022-jp']:
for kind in ['ml', 'message-id', 'hash']:
number = len(paths) + 1
title = '日本語の依頼'
subject = (f'[example.list {number:05d}] ' if kind == 'ml' else '') + title
# pipe_decode=no / pipe_split=yes: exactly one un-decoded RFC mail
# is delivered to the CLI's stdin, as in the published NeoMutt macro.
raw = ('From: Test <test@example.invalid>\r\n'
'Date: Sat, 31 Jan 2026 23:30:00 -0800\r\n'
'Subject: ' + Header(subject, charset).encode() + '\r\n'
+ (f'Message-ID: <synthetic-{number}@example.invalid>\r\n' if kind != 'hash' else '')
+ 'MIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n'
'Content-Transfer-Encoding: 8bit\r\n\r\n'
f'Synthetic mail body {number}. {{' + '{children}}\r\n').encode()
result = json.loads(cli('task', 'from-mail', data=raw))
path = result['page_path']
suffix = ('example.list/' + str(number) if kind == 'ml' else '2026/01/' +
(result['item']['uuid'] if kind == 'message-id' else hashlib.sha256(raw).hexdigest()))
assert path == parent + '/' + suffix, path
assert result['item']['title'] == title
# Confirm browser listing actually links to the same semantic URL.
listing = get('/v/browser' + path.rsplit('/', 1)[0])
links = Links(); links.feed(listing)
linked = next((href for href in links.links if unquote(urlsplit(href).path) == path), None)
assert linked is not None, ('missing listing link', path, links.links, listing[:600])
page = get(path)
assert f'Synthetic mail body {number}.' in page, path
assert title in page, path
assert '{"detail":"Not Found"}' not in page
assert f'Synthetic mail body {number}.' in get(linked)
assert f'Synthetic mail body {number}.' in get(path + '/')
assert f'Synthetic mail body {number}.' in get(path + '?lang=ja')
paths.append(path)
if fixture['chromium']:
# Real browser session, normal navigation and scripts, without injecting
# page HTML or bypassing the production handler.
for i, path in enumerate([paths[0], paths[14], paths[-1]]):
target = fixture['origin'] + '/fixture-browser-login?' + urlencode({'return': path})
run = subprocess.run(['chromium', '--headless', '--no-sandbox', '--disable-gpu',
'--disable-background-networking', '--no-proxy-server',
'--user-data-dir=' + str(root / ('chromium-' + str(i))),
'--dump-dom', '--virtual-time-budget=2000', target],
capture_output=True, timeout=20)
assert run.returncode == 0, run.stderr.decode()[-1000:]
assert 'Synthetic mail body' in run.stdout.decode(), (path, run.stdout.decode()[:500])
print('MAIL_VIEWER_OK cases=' + str(len(paths)) + ' chromium=' + str(fixture['chromium']))
if __name__ == '__main__':
main()