diff options
Diffstat (limited to 'packages/meshbay-hub/tests')
| -rw-r--r-- | packages/meshbay-hub/tests/harness/cast_session_probe.py | 521 | ||||
| -rw-r--r-- | packages/meshbay-hub/tests/harness/copy_link_probe.py | 264 | ||||
| -rw-r--r-- | packages/meshbay-hub/tests/harness/group_link_probe.py | 176 | ||||
| -rw-r--r-- | packages/meshbay-hub/tests/test_android_cast.py | 8 | ||||
| -rw-r--r-- | packages/meshbay-hub/tests/test_cast_files.py | 372 | ||||
| -rw-r--r-- | packages/meshbay-hub/tests/test_copy_link.py | 98 | ||||
| -rw-r--r-- | packages/meshbay-hub/tests/test_group_link.py | 170 | ||||
| -rw-r--r-- | packages/meshbay-hub/tests/test_group_link_flow.py | 67 | ||||
| -rw-r--r-- | packages/meshbay-hub/tests/test_http_api_doc.py | 30 | ||||
| -rw-r--r-- | packages/meshbay-hub/tests/test_spa_ordering.py | 4 |
10 files changed, 1705 insertions, 5 deletions
diff --git a/packages/meshbay-hub/tests/harness/cast_session_probe.py b/packages/meshbay-hub/tests/harness/cast_session_probe.py new file mode 100644 index 0000000..573dd95 --- /dev/null +++ b/packages/meshbay-hub/tests/harness/cast_session_probe.py @@ -0,0 +1,521 @@ +#!/usr/bin/env python3 +""" +A television chosen once, then photos and a film sent to it. + +Casting a photo or opening a film on a television chosen elsewhere is a claim +about four pieces at once: the cast button (cast-session.js), the lightbox +that follows it, the player that opens as a remote, and the native bridge the +page talks to. This renders the shipped `GroupPage` against a stub node and a +stub bridge that records what the page asks of it, and walks it as a reader +would: open an album, choose the television, page on, start a slideshow, +then open a film from Videos and stop casting from its remote. + +A second case renders the same page with no bridge at all — a browser — where +no cast button may appear. + + cast_session_probe.py Chrome, then Firefox +""" + +import http.server +import json +import shutil +import socketserver +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static" +PORT = 8763 +RECORDS = [] +FINISHED = threading.Event() +socketserver.TCPServer.allow_reuse_address = True + +FRAME = r"""<!doctype html><html><head><meta charset=utf-8> +<link rel="stylesheet" href="/style.css"></head><body> +<nav class="nav"><div class="nav-left"><a class="nav-brand" href="#/">MeshBay</a></div></nav> +<div class="layout"><main class="main"><div id="root"></div></main></div> +<script> +// A module that fails to load never reaches its own catch: say so. +const report = (error) => parent.postMessage({ error }, '*'); +// Scripts only: the music case's stub track is three bytes no <audio> +// element can decode, which is expected and is not the page failing. +addEventListener('error', (e) => { + if (!(e instanceof ErrorEvent) && !(e.target && e.target.tagName === 'SCRIPT')) return; + report(`${e.message || 'load error'} ${e.filename || (e.target && e.target.src) || ''}` + + `:${e.lineno || ''}`); +}, true); +addEventListener('unhandledrejection', + (e) => report(String((e.reason && e.reason.stack) || e.reason))); +const WITH_BRIDGE = !location.search.includes('nobridge'); +const ENTRIES = []; +for (let i = 1; i <= 3; i++) { + ENTRIES.push({ id: 'p' + i, name: 'photo' + i + '.png', path: 'photos/Trip', + type: 'image', size: 1000, added_at: 1750000000 + i }); +} +ENTRIES.push({ id: 'film', name: 'A.Film.mkv', display_title: 'A Film', + path: 'videos/films', type: 'video', duration: 6000, size: 1024, added_at: 1750000100 }); + +const ACK = { + is_node_admin: false, enabled_apps: ['video', 'photo'], + tmdb_enabled: true, tmdb_language: 'en-US', + video_directories: ['videos'], music_directories: [], photo_directories: ['photos'], +}; + +// A camera-sized picture, made here: 4000×3000, which the television must +// receive as 1440×1080. +let PHOTO = null; +async function photoBytes() { + if (PHOTO) return PHOTO; + const c = document.createElement('canvas'); + c.width = 4000; c.height = 3000; + const g = c.getContext('2d'); + g.fillStyle = '#3a7'; g.fillRect(0, 0, 4000, 3000); + const blob = await new Promise((r) => c.toBlob(r, 'image/png')); + PHOTO = new Uint8Array(await blob.arrayBuffer()); + return PHOTO; +} + +window.MeshBayCrypto = { + importGEK: async () => 'gek', + b64encode: (x) => String(x), + decryptChunkBin: async (_g, _f, _i, _n, ct) => ct, +}; + +window.MeshBayTransport = function () { + const self = { + connected: false, memberRole: 'member', supportsAppOps: true, + sessionKeys: null, gekRaw: 'k', + newNodeBundle: null, newNodeBundleRecovery: null, + async connect() { self.connected = true; return ACK; }, + async fetchIndex() { + return { entries: ENTRIES, dirs: ['photos', 'videos'], + roots: [{ name: 'photos', available: true, writable: false, removable: false }, + { name: 'videos', available: true, writable: false, removable: false }] }; + }, + async fetchMediaMeta() { return { confidence: 0 }; }, + // One chunk per photo: every photo is the same picture. + async fetchChunk() { return { nonce: 'n', ct: await photoBytes() }; }, + addReconnectListener() { return () => {}; }, + close() {}, + }; + return new Proxy(self, { + get(target, prop) { + if (prop in target) return target[prop]; + if (typeof prop === 'string' && prop.startsWith('on')) return undefined; + if (typeof prop === 'symbol') return undefined; + return () => new Promise(() => {}); + }, + set(target, prop, value) { target[prop] = value; return true; }, + }); +}; + +// The native side, as the Electron preload and the Android shim present it, +// recording every cast call. +window.CALLS = []; +// What the stub receiver reports: the music case moves it along. +window.TV = { state: 'IDLE', position: 0, idle: null }; +if (WITH_BRIDGE) { + let connected = false, v = 0; + const rec = (name, arg) => { CALLS.push({ name, arg }); }; + window.meshbay = { + hubBase: () => '', + setLocale: async () => true, + capabilities: { lanCast: true, nodeAdmin: false, localFolders: false, nativeSave: false }, + cast: { + start: async (o) => { + rec('start', o && { codec: o.codec }); + return { url: 'http://tv/stream.mp4?t=x' }; + }, + push: async () => true, + stop: async () => { rec('stop'); return true; }, + subtitle: async () => null, + finish: async () => true, + file: async (f) => { + let info = { type: f.type, size: f.bytes.length, title: f.title || null, + artist: f.artist || null, album: f.album || null, cover: !!f.cover }; + if (f.type.startsWith('image/')) { + const bmp = await createImageBitmap(new Blob([f.bytes], { type: f.type })); + info = { ...info, width: bmp.width, height: bmp.height, + jpeg: f.bytes[0] === 0xff && f.bytes[1] === 0xd8 }; + } + rec('file', info); + return { url: 'http://tv/file?t=x&v=' + (++v) }; + }, + status: async () => ({ active: true, url: null, chromecast: { + connected, playerState: TV.state, position: TV.position, idleReason: TV.idle } }), + scan: async () => { rec('scan'); return true; }, + devices: async () => ({ devices: [{ id: 'tv1', name: 'Salon' }], scanning: false }), + chromecastConnect: async (o) => { + rec('connect', o); connected = true; + return { deviceName: 'Salon' }; + }, + chromecastReload: async (o) => { rec('reload', o); return { playerState: 'IDLE' }; }, + chromecastDisconnect: async () => { rec('disconnect'); connected = false; return true; }, + chromecastPause: async () => { rec('pause'); TV.state = 'PAUSED'; return {}; }, + chromecastPlay: async () => { rec('play'); TV.state = 'PLAYING'; return {}; }, + chromecastSeek: async (t) => { rec('seek', t); TV.position = t; return {}; }, + }, + }; +} +</script> +<script type="module"> +import { html, render } from '/vendor/htm-preact.js'; +import { initLocale } from '/i18n.js'; +import { GroupPage } from '/group-page.js'; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const $ = (sel) => document.querySelector(sel); +const $$ = (sel) => [...document.querySelectorAll(sel)]; +async function until(pred, what, tries = 200) { + for (let i = 0; i < tries; i++) { if (pred()) return; await sleep(50); } + throw new Error('timed out waiting for ' + what); +} +const calls = (name) => CALLS.filter((c) => c.name === name); +const files = () => calls('file').map((c) => c.arg); +// Files is always first; then the enabled apps in their registry order. +const videosTab = () => $$('.group-tab')[1]; +const count = () => (($('.photo-lightbox-count') || {}).textContent || '').trim(); + +// The music bar, with a television already chosen: two tracks of one album. +async function music() { + const { MusicPlayerBar } = await import('/music-player.js'); + const { castSession } = await import('/cast-session.js'); + const out = {}; + castSession.choose({ id: 'tv1', name: 'Salon' }); + // Which hashes were fetched, so a cover can be traced to where it came from. + window.FETCHED = []; + const transport = { connected: true, async waitForReconnect() {}, + async fetchChunk(id) { + FETCHED.push(id); + return { nonce: 'n', ct: new Uint8Array([1, 2, 3]) }; + }, + // The node's MusicBrainz answer: a cover for the other album only. + async fetchMusicMeta(id) { + CALLS.push({ name: 'musicMeta', arg: id }); + return id === 't3' ? { confidence: 1, cover_thumb_hash: 'mb-cover' } + : { confidence: 0 }; + } }; + const getConnection = async () => ({ transport, gek: 'gek' }); + // One has no cover of its own but Two, of the same album, has; Three is of + // another album whose only cover is the one the node found. + const track = (n, title, album, hash) => ({ id: 't' + n, name: title + '.mp3', size: 3, + groupId: 'g1', display_title: title, artist: 'Some Band', album, duration: 200, + thumb_hash: hash }); + const queue = { tracks: [track(1, 'One', 'An Album', null), track(2, 'Two', 'An Album', 'cover2'), + track(3, 'Three', 'Another Album', null)], startIndex: 0, nonce: 1 }; + render(html`<${MusicPlayerBar} getConnection=${getConnection} queue=${queue} + userPrefs=${{}} onClose=${() => {}} />`, document.getElementById('root')); + + await until(() => calls('connect').length === 1, 'the first track on the television'); + out.first = { file: files()[0], connect: calls('connect')[0].arg, + coverFetched: FETCHED.includes('cover2') }; + TV.state = 'PLAYING'; TV.position = 12; + await until(() => ($$('.music-player-time')[0] || {}).textContent === '0:12', + "the television's clock in the bar"); + out.barButton = !!$('.music-player-bar .cast-btn.casting'); + out.volumeDisabled = $('.music-player-volume input').disabled; + + $('.music-player-play').click(); + await until(() => calls('pause').length === 1, 'pause on the television'); + const slider = $('.music-player-seek input'); + slider.value = '30'; + slider.dispatchEvent(new Event('input', { bubbles: true })); + await until(() => calls('seek').length === 1, 'a seek on the television'); + out.seek = calls('seek')[0].arg; + + // The television finishes the track: the next one goes, once. + TV.state = 'IDLE'; TV.idle = 'FINISHED'; + await until(() => calls('reload').length === 1, 'the next track on the television'); + out.second = { file: files()[1], reload: calls('reload')[0].arg, + title: $('.music-player-title').textContent.trim() }; + TV.state = 'PLAYING'; TV.idle = null; TV.position = 1; + await sleep(2500); + out.filesAfterSettling = files().length; + + // Three: the cover comes from the node's answer for its album. + TV.state = 'IDLE'; TV.idle = 'FINISHED'; + await until(() => calls('reload').length === 2, 'the third track on the television'); + out.third = { file: files()[2], mbCover: FETCHED.includes('mb-cover'), + metaAsked: calls('musicMeta').map((c) => c.arg) }; + TV.state = 'PLAYING'; TV.idle = null; + + // Stopping the cast lets the television go. + await castSession.end(); + await sleep(200); + out.afterStop = { disconnects: calls('disconnect').length, + barCasting: !!$('.music-player-bar .cast-btn.casting') }; + parent.postMessage(out, '*'); +} + +(async () => { + const out = { bridge: !!window.meshbay }; + if (location.search.includes('music')) { + try { await initLocale(); await music(); } + catch (err) { + parent.postMessage({ calls: CALLS, error: String((err && err.stack) || err) }, '*'); + } + return; + } + try { + await initLocale(); + render(html`<${GroupPage} groupId="g1" token="t" username="me" userId="u1" + group=${{ id: 'g1', name: 'a group', owner_username: 'me', is_admin: false }} + userPrefs=${{ default_tab: 'photo', media_page_size: '50' }} />`, + document.getElementById('root')); + + await until(() => $('.photo-album-card'), 'the album card'); + out.landingButton = !!$('.photo-toolbar .cast-btn'); + $('.photo-album-card').click(); + await until(() => $('.photo-album-bar'), 'the album'); + out.albumButton = !!$('.photo-album-bar .cast-btn'); + + if (!window.meshbay) { + videosTab().click(); + await until(() => $('.video-toolbar'), 'the videos toolbar'); + out.videosButton = !!$('.video-toolbar .cast-btn'); + parent.postMessage(out, '*'); + return; + } + + // Choose the television from the album: the first photo opens and goes. + $('.photo-album-bar .cast-btn').click(); + await until(() => $$('.cast-menu .ctx-menu-item').some((b) => b.textContent.includes('Salon')), + 'the receiver in the menu'); + $$('.cast-menu .ctx-menu-item').find((b) => b.textContent.includes('Salon')).click(); + await until(() => $('.photo-lightbox'), 'the lightbox to open on choosing'); + await until(() => calls('connect').length === 1, 'the first photo to reach the television'); + out.first = { count: count(), image: files()[0], connect: calls('connect')[0].arg, + lightboxCasting: !!$('.photo-lightbox .cast-btn.casting') }; + + // Next photo: the receiver is connected, so it is reloaded. + $('.photo-nav-next').click(); + await until(() => calls('reload').length === 1, 'the second photo'); + out.second = { count: count(), reload: calls('reload')[0].arg, images: files().length }; + + // Slideshow: on by itself to the last photo, then off. + const play = $$('.photo-lightbox .video-top-bar .video-close') + .find((b) => b.getAttribute('aria-pressed') !== null); + play.click(); + await until(() => count() === '3 / 3', 'the slideshow to reach the last photo', 160); + await until(() => play.getAttribute('aria-pressed') === 'false', 'the slideshow to end', 160); + out.slideshow = { count: count(), images: files().length, + reloads: calls('reload').length }; + + // Close the lightbox; Videos shows the same television; a film opens as its remote. + $$('.photo-lightbox .video-top-bar .video-close').pop().click(); + await until(() => !$('.photo-lightbox'), 'the lightbox to close'); + videosTab().click(); + await until(() => $('.video-toolbar'), 'the videos toolbar'); + out.videosCasting = !!$('.video-toolbar .cast-btn.casting'); + await until(() => $('.video-card'), 'the film card'); + $('.video-card').click(); + await until(() => $('.video-detail .admin-btn'), 'the film modal'); + $('.video-detail .admin-btn').click(); + await until(() => $('.video-remote'), 'the player as a remote'); + out.remote = { device: $('.video-remote-device').textContent.trim(), + pickerOpen: !!$('.video-player-overlay .cast-picker') }; + + // Stop from the remote: forgotten for the session. + $$('.video-remote button').pop().click(); + await until(() => !$('.video-remote'), 'the remote to go'); + $$('.video-player-overlay .video-top-bar .video-close').pop().click(); + await until(() => !$('.video-player-overlay'), 'the player to close'); + await sleep(100); + out.afterStop = { videosCasting: !!$('.video-toolbar .cast-btn.casting'), + disconnects: calls('disconnect').length }; + parent.postMessage(out, '*'); + } catch (err) { + parent.postMessage({ ...out, calls: CALLS, error: String((err && err.stack) || err) }, '*'); + } +})(); +</script></body></html>""" + +# Firefox headless runs a page only while taking its screenshot, which is taken +# once the page has loaded: an image that does not answer until the case has +# reported keeps it loading (the same hold as invitation_probe.py). +HOLD_TAG = '<img src="/hold" style="position:fixed;left:-4px;top:-4px;width:1px">' + +PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head> +<body style="margin:0"> +<iframe src="/case{query}" style="width:1100px;height:800px;border:0"></iframe> +<script> +addEventListener('message', (e) => fetch('/log', { method: 'POST', body: JSON.stringify(e.data) })); +</script>{hold}</body></html>""" + + +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + if self.path == "/log": + RECORDS.append(json.loads(self.rfile.read(length).decode())) + FINISHED.set() + else: + self.rfile.read(length) + self.send_response(204) + self.end_headers() + + def _send(self, body: bytes, ctype: str) -> None: + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + path, _, query = self.path.partition("?") + if path == "/hold": + FINISHED.wait(90) + self._send(b"", "image/gif") + elif path == "/": + q = f"?{query.replace('engine=firefox', '').strip('&')}" if query else "" + hold = HOLD_TAG if "engine=firefox" in query else "" + page = PAGE.replace("{query}", q if q != "?" else "").replace("{hold}", hold) + self._send(page.encode(), "text/html; charset=utf-8") + elif path == "/case": + self._send(FRAME.encode(), "text/html; charset=utf-8") + elif path == "/v1/groups/g1/nodes": + self._send(b'{"nodes": [{"node_id": "n1"}]}', "application/json") + else: + asset = (STATIC / path.lstrip("/")).resolve() + if not str(asset).startswith(str(STATIC)) or not asset.is_file(): + self.send_response(404) + self.end_headers() + return + self._send(asset.read_bytes(), + "text/css" if asset.suffix == ".css" + else "text/javascript" if asset.suffix == ".js" + else "application/octet-stream") + + +def browse(engine: str, query: str) -> dict | None: + RECORDS.clear() + FINISHED.clear() + sep = "&" if query else "?" + url = f"http://127.0.0.1:{PORT}/{query}{sep + 'engine=firefox' if engine == 'firefox' else ''}" + # Firefox is a snap here, and needs its profile under $HOME (invitation_probe.py). + snap = Path.home() / "snap" / "firefox" / "common" + parent = (str(snap if snap.is_dir() else Path.home()) if engine == "firefox" else None) + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True, prefix="meshbay-probe-", + dir=parent) as profile: + if engine == "chrome": + cmd = ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox", + f"--user-data-dir={profile}", "--window-size=1100,900", url] + else: + cmd = ["firefox", "--headless", "--profile", profile, "--window-size=1100,900", + "--screenshot", str(Path(profile) / "shot.png"), url] + proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + deadline = time.time() + 90 + while not RECORDS and time.time() < deadline: + time.sleep(0.2) + proc.terminate() + try: + proc.wait(timeout=20) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + return RECORDS[0] if RECORDS else None + + +def check(engine: str, cast: dict, plain: dict) -> list[str]: + bad = [] + if "error" in cast: + return [f"{engine}: {cast['error']}"] + if not cast["landingButton"]: + bad.append("no cast button on the Photos landing") + if not cast["albumButton"]: + bad.append("no cast button in the album bar") + first = cast["first"] + if first["count"] != "1 / 3": + bad.append(f"choosing a television did not open the first photo: {first['count']}") + img = first["image"] + if not (img["type"] == "image/jpeg" and img["jpeg"] and img["width"] == 1440 + and img["height"] == 1080): + bad.append(f"the photo did not leave as a 1440x1080 JPEG: {img}") + if first["connect"] != {"deviceId": "tv1", "mediaUrl": "http://tv/file?t=x&v=1", + "startAt": 0}: + bad.append(f"connect: {first['connect']}") + if not first["lightboxCasting"]: + bad.append("the lightbox's cast button does not say it is casting") + if cast["second"]["count"] != "2 / 3" or cast["second"]["reload"] != { + "mediaUrl": "http://tv/file?t=x&v=2", "startAt": 0}: + bad.append(f"next photo: {cast['second']}") + if cast["slideshow"]["count"] != "3 / 3" or cast["slideshow"]["images"] != 3: + bad.append(f"slideshow: {cast['slideshow']}") + if not cast["videosCasting"]: + bad.append("Videos does not show the television chosen in Photos") + if cast["remote"]["device"] != "Salon" or cast["remote"]["pickerOpen"]: + bad.append(f"the film did not open as the television's remote: {cast['remote']}") + if cast["afterStop"]["videosCasting"] or cast["afterStop"]["disconnects"] < 1: + bad.append(f"stopping from the remote: {cast['afterStop']}") + if "error" in plain: + bad.append(f"no bridge: {plain['error']}") + elif plain["landingButton"] or plain["albumButton"] or plain["videosButton"]: + bad.append(f"a cast button without a bridge: {plain}") + return [f"{engine}: {b}" for b in bad] + + +def check_music(engine: str, m: dict) -> list[str]: + if "error" in m: + return [f"{engine}: music: {m['error']}"] + bad = [] + f = m["first"]["file"] + if not (f["type"] == "audio/mpeg" and f["title"] == "One" and f["artist"] == "Some Band" + and f["album"] == "An Album" and f["cover"] and m["first"]["coverFetched"]): + bad.append(f"the first track left without its album's cover: {m['first']}") + third = m["third"] + if not (third["file"]["title"] == "Three" and third["file"]["cover"] and third["mbCover"]): + bad.append(f"the node's cover did not reach the television: {third}") + if "t1" in third["metaAsked"] or "t2" in third["metaAsked"]: + bad.append(f"the node was asked for a cover a track already had: {third['metaAsked']}") + if m["first"]["connect"] != {"deviceId": "tv1", "mediaUrl": "http://tv/file?t=x&v=1", + "startAt": 0}: + bad.append(f"connect: {m['first']['connect']}") + if not m["barButton"]: + bad.append("the music bar's cast button does not say it is casting") + if not m["volumeDisabled"]: + bad.append("the volume slider still acts while casting") + if m["seek"] != 30: + bad.append(f"seek: {m['seek']}") + s = m["second"] + if s["file"]["title"] != "Two" or s["title"] != "Two" or s["reload"] != { + "mediaUrl": "http://tv/file?t=x&v=2", "startAt": 0}: + bad.append(f"the end of a track did not move the queue on: {s}") + if m["filesAfterSettling"] != 2: + bad.append(f"a finished track moved the queue on more than once: {m['filesAfterSettling']}") + if m["afterStop"]["disconnects"] < 1 or m["afterStop"]["barCasting"]: + bad.append(f"stopping: {m['afterStop']}") + return [f"{engine}: music: {b}" for b in bad] + + +def main() -> int: + failures = [] + with socketserver.ThreadingTCPServer(("127.0.0.1", PORT), H) as srv: + threading.Thread(target=srv.serve_forever, daemon=True).start() + for engine in ("chrome", "firefox"): + if shutil.which("google-chrome" if engine == "chrome" else engine) is None: + print(f"{engine}: not installed, skipped") + continue + cast = browse(engine, "") + plain = browse(engine, "?nobridge") + music = browse(engine, "?music") + if cast is None or plain is None or music is None: + failures.append(f"{engine}: the page never reported") + continue + print(f"{engine}:", json.dumps({"photos-videos": cast, "music": music}, indent=1)) + failures += check(engine, cast, plain) + failures += check_music(engine, music) + for f in failures: + print("FAIL", f, file=sys.stderr) + if not failures: + print("OK") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packages/meshbay-hub/tests/harness/copy_link_probe.py b/packages/meshbay-hub/tests/harness/copy_link_probe.py new file mode 100644 index 0000000..50d269d --- /dev/null +++ b/packages/meshbay-hub/tests/harness/copy_link_probe.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +""" +"Copy link" in Files, Music and Photos, in a real browser. + +Mounts the shipped `FilesPanel`, `MusicApp` and `PhotosApp` on a made-up +index — no node, no transport — with the `linkFor` a group page gives them, +built by the real `copy-link.js` for a group `demo@someowner`. Opens each +menu the way a reader would (right-click; the dots on a phone; the Files +toolbar with one row ticked), picks "Copy link", and reads back what reached +the clipboard and what the page said. + + copy_link_probe.py + +Prints JSON: one entry per case. +""" + +import http.server +import json +import socketserver +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static" +PORT = 8775 +RECORDS = [] +socketserver.TCPServer.allow_reuse_address = True + +FRAME = r"""<!doctype html><html><head><meta charset=utf-8> +<link rel="stylesheet" href="/style.css"></head><body> +<div id="files"></div><div id="music"></div><div id="photos"></div> +<script type="module"> +import { html, render } from '/vendor/htm-preact.js'; +import { initLocale, setLocale } from '/i18n.js'; +import { FilesPanel } from '/files-app.js'; +import { MusicApp } from '/music-app.js'; +import { PhotosApp } from '/photos-app.js'; +import { groupItemLink, entryPath } from '/copy-link.js'; + +const LOGS = []; +addEventListener('error', (e) => LOGS.push('error: ' + (e.message || e))); +addEventListener('unhandledrejection', + (e) => LOGS.push('rejection: ' + (e.reason && e.reason.message || e.reason))); +const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +// What the clipboard was handed, and nothing else: a headless page has no +// clipboard permission to test against. +const COPIES = []; +Object.defineProperty(navigator, 'clipboard', { configurable: true, + value: { writeText: async (text) => { COPIES.push(text); } } }); + +const GROUP = { name: 'demo', owner_username: 'someowner' }; +const linkFor = (target) => (target + ? groupItemLink(GROUP, typeof target === 'string' ? target : entryPath(target)) : null); +const noop = () => {}; +const ref = { current: null }; + +const labels = () => [...document.querySelectorAll('.ctx-menu .ctx-menu-label')] + .map((el) => el.textContent); +const pick = async (label) => { + const item = [...document.querySelectorAll('.ctx-menu .ctx-menu-item')] + .find((b) => b.querySelector('.ctx-menu-label').textContent === label); + if (!item) return false; + item.click(); + await wait(50); + return true; +}; +const note = () => (document.querySelector('.copy-link-note') || {}).textContent || ''; +const closeMenus = async () => { + document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); + await frame(); +}; +const rightClick = async (el) => { + await closeMenus(); + const r = el.getBoundingClientRect(); + el.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, + clientX: r.left + 10, clientY: r.top + 5 })); + await frame(); +}; +const rowNamed = (name) => [...document.querySelectorAll('tr.file-row')] + .find((tr) => tr.querySelector('.file-name') + && tr.querySelector('.file-name').textContent.trim().startsWith(name)); + +(async () => { + const cases = []; + try { + setLocale('en'); + await initLocale(); + try { localStorage.setItem('meshbay_music_view_mode', 'flat'); } catch {} + + // -- Files -- + const FILES = [ + { id: 'f1', name: 'IMG 0001.JPG', path: 'Root/trip_2015', size: 10, type: 'image', + added_at: 1 }, + { id: 'f2', name: 'notes.txt', path: 'Root/trip_2015', size: 5, type: 'document', + added_at: 2 }, + ]; + render(html`<${FilesPanel} groupId="g" transportRef=${ref} gekRef=${ref} + status="connected" entries=${FILES} nodeDirs=${['Root', 'Root/trip_2015']} + nodeRoots=${[{ name: 'Root', writable: false }]} + setEntries=${noop} setNodeDirs=${noop} setNodeRoots=${noop} applyIndex=${noop} + isNodeAdmin=${false} operatorPaired=${false} userId="me" setError=${noop} + onPreview=${noop} linkFor=${linkFor} />`, document.getElementById('files')); + await frame(); + + await rightClick(rowNamed('Root')); + const folderLabels = labels(); + await pick('Copy link'); + cases.push({ case: 'files folder', labels: folderLabels, copied: COPIES.at(-1), note: note() }); + + rowNamed('Root').click(); await frame(); + rowNamed('trip_2015').click(); await frame(); + await rightClick(rowNamed('IMG 0001.JPG')); + const fileLabels = labels(); + await pick('Copy link'); + cases.push({ case: 'files file', labels: fileLabels, copied: COPIES.at(-1), note: note() }); + + await closeMenus(); + const linkBtn = () => document.querySelector('.tb-actions button[aria-label="Copy link"]'); + rowNamed('notes.txt').querySelector('input[type=checkbox]').click(); await frame(); + const oneTicked = linkBtn() ? !linkBtn().disabled : null; + if (linkBtn() && !linkBtn().disabled) { linkBtn().click(); await wait(50); } + const copiedFromToolbar = COPIES.at(-1); + for (const n of ['IMG 0001.JPG', 'notes.txt']) { + rowNamed(n).querySelector('input[type=checkbox]').click(); await frame(); + } + const twoTicked = linkBtn() ? !linkBtn().disabled : null; + cases.push({ case: 'files toolbar', one_enabled: oneTicked, two_enabled: twoTicked, + copied: copiedFromToolbar }); + render(null, document.getElementById('files')); + + // -- Music: a loose track, its row's dots (what a phone has) -- + const TRACKS = [ + { id: 'a1', name: 'track 01.flac', path: 'Music/Some Album', size: 3, type: 'audio' }, + { id: 'a2', name: 'track 02.flac', path: 'Music/Some Album', size: 3, type: 'audio' }, + ]; + render(html`<${MusicApp} groupId="g" transportRef=${ref} gekRef=${ref} + status="connected" entries=${TRACKS} musicDirectories=${['Music']} + musicbrainzConfig=${{ enabled: false }} onPlayQueue=${noop} userId="" + linkFor=${linkFor} />`, document.getElementById('music')); + await frame(); + await closeMenus(); + const dots = document.querySelector('.music-flat-track .ctx-dots'); + if (dots) { dots.click(); await frame(); } + const trackLabels = labels(); + await pick('Copy link'); + cases.push({ case: 'music track', dots: Boolean(dots), labels: trackLabels, + copied: COPIES.at(-1) }); + render(null, document.getElementById('music')); + + // -- Photos: right-click a tile; the lightbox's button -- + const PHOTOS = [ + { id: 'p1', name: 'beach.jpg', path: 'Pics/Summer', size: 4, type: 'image', added_at: 1 }, + ]; + render(html`<${PhotosApp} groupId="g" transportRef=${ref} gekRef=${ref} + status="connected" entries=${PHOTOS} photoDirectories=${['Pics']} + setError=${noop} linkFor=${linkFor} />`, document.getElementById('photos')); + await frame(); + const album = document.querySelector('.photo-album-card'); + if (album) { album.click(); await frame(); } + const tile = document.querySelector('.photo-tile'); + let tileLabels = []; + if (tile) { + await rightClick(tile); + tileLabels = labels(); + await pick('Copy link'); + } + const fromTile = COPIES.at(-1); + if (tile) { tile.click(); await frame(); } + const lb = document.querySelector('.photo-lightbox button[aria-label="Copy link"]'); + COPIES.length = 0; + if (lb) { lb.click(); await wait(50); } + cases.push({ case: 'photos', tile: Boolean(tile), labels: tileLabels, copied: fromTile, + lightbox_button: Boolean(lb), lightbox_copied: COPIES.at(-1) || null }); + + parent.postMessage({ cases, logs: LOGS, origin: location.origin }, '*'); + } catch (err) { + parent.postMessage({ error: String(err && (err.stack || err)), logs: LOGS }, '*'); + } +})(); +</script></body></html>""" + +PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head> +<body style="margin:0"><div id="frames"></div><script> +addEventListener('message', (e) => { + fetch('/log', { method: 'POST', body: JSON.stringify(e.data) }); +}); +const f = document.createElement('iframe'); +f.src = '/case'; +f.style.cssText = 'width:1100px;height:800px;border:0;display:block'; +document.getElementById('frames').appendChild(f); +</script></body></html>""" + + +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + if self.path == "/log": + RECORDS.append(json.loads(self.rfile.read(length).decode())) + else: + self.rfile.read(length) + self.send_response(204) + self.end_headers() + + def _send(self, body: bytes, ctype: str) -> None: + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + path = self.path.split("?")[0] + if path == "/": + self._send(PAGE.encode(), "text/html; charset=utf-8") + elif path == "/case": + self._send(FRAME.encode(), "text/html; charset=utf-8") + else: + asset = (STATIC / path.lstrip("/")).resolve() + if not str(asset).startswith(str(STATIC)) or not asset.is_file(): + self.send_response(404) + self.end_headers() + return + self._send(asset.read_bytes(), + "text/css" if asset.suffix == ".css" + else "text/javascript" if asset.suffix == ".js" + else "application/octet-stream") + + +def main() -> int: + with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv: + threading.Thread(target=srv.serve_forever, daemon=True).start() + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile: + proc = subprocess.Popen( + ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox", + f"--user-data-dir={profile}", "--window-size=1100,900", + f"http://127.0.0.1:{PORT}/"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(300): + if RECORDS: + break + time.sleep(0.1) + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + if not RECORDS: + print(json.dumps({"error": "no measurement"}), file=sys.stderr) + return 1 + print(json.dumps(RECORDS[0], indent=1)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/meshbay-hub/tests/harness/group_link_probe.py b/packages/meshbay-hub/tests/harness/group_link_probe.py new file mode 100644 index 0000000..2d7c0d7 --- /dev/null +++ b/packages/meshbay-hub/tests/harness/group_link_probe.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +""" +A group link, `#/name@owner[/path]`, opened in the real application. + +`test_group_link.py` runs `group-link.js` on its own; this is where it meets +the router, the account's group list and the sign-in state. Loads the shipped +`app.js` in a real browser with `fetch` stubbed (no node answers, so a group +page goes as far as "offline"), once per case: + + handle — `#/demo@someowner`: the group page, the address left as it is + uuid — `#/group/<id>`: the same page, the address showing the handle + file — `#/demo@someowner/<path>`: the page, the path kept in the address + until the index can say what it is (no node here: never) + unknown — `#/demo@stranger1`: not among the account's groups + signed_out — `#/demo@someowner/<path>` with no session: the sign-in form, and + the address untouched under it + + group_link_probe.py + +Prints JSON: one object per case. +""" + +import http.server +import json +import socketserver +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static" +PORT = 8774 +RECORDS = [] +socketserver.TCPServer.allow_reuse_address = True + +GROUP = "0f8fad5b-d9cb-469f-a165-70867728950e" +FILE = "backup/city_2015/backup/IMG_0001.JPG" +LINKS = { + "handle": "#/demo@someowner", + "uuid": f"#/group/{GROUP}", + "file": f"#/demo@someowner/{FILE}", + "unknown": "#/demo@stranger1", + "signed_out": f"#/demo@someowner/{FILE}", +} +CASES = list(LINKS) + +PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head><body> +<div id="app"></div> +<script type="module"> +const CASE = new URLSearchParams(location.search).get('case'); +const LINKS = __LINKS__; +const realFetch = window.fetch.bind(window); +const post = (o) => realFetch('/log', { method: 'POST', body: JSON.stringify(o) }); +const calls = []; +const json = (body, status = 200) => ({ + ok: status < 400, status, statusText: '', headers: new Headers(), + json: async () => body, text: async () => JSON.stringify(body), +}); +window.fetch = async (url, init = {}) => { + const u = String(url); + calls.push(u); + if (u.includes('/v1/users/me/preferences')) return json({}); + if (u.includes('/v1/users/me')) return json({ user_id: 'u-1', role: 'user' }); + if (u.includes('/v1/groups/mine')) return json({ groups: [ + { id: '__GROUP__', name: 'demo', owner_username: 'someowner', visibility: 'private', + created_at: '2026-01-01T00:00:00+00:00', description: '' }, + { id: 'other-group', name: 'demo', owner_username: 'otherowner', visibility: 'private', + created_at: '2026-01-01T00:00:00+00:00', description: '' }, + ] }); + if (u.includes('/nodes')) return json({ nodes: [] }); + return json({}); +}; +if (CASE === 'signed_out') { + localStorage.removeItem('mb_auth'); +} else { + localStorage.setItem('mb_auth', JSON.stringify({ + username: 'member-account', userId: 'u-1', token: 'tok', refreshToken: 'ref', + role: 'user' })); +} +sessionStorage.clear(); +history.replaceState(null, '', '/?case=' + CASE + LINKS[CASE]); + +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +(async () => { + const out = { case: CASE }; + try { + await import('/app.js'); + await wait(2000); + out.hash = decodeURI(location.hash); + out.history_length = history.length; + out.group_page = Boolean(document.querySelector('.group-header')); + out.group_title = (document.querySelector('.group-header h2') || {}).innerText || ''; + out.active_sidebar = [...document.querySelectorAll('.sidebar-group.active')] + .map((a) => a.getAttribute('href')); + out.message = (document.querySelector('main .page-message') || {}).innerText || ''; + out.spinner = Boolean(document.querySelector('main .page-message .spinner')); + out.login_form = Boolean(document.querySelector('input[type=password]')); + out.hub_calls = calls.map((c) => c.replace(/^https?:\/\/[^/]+/, '')); + } catch (e) { + out.error = String(e && e.stack || e); + } + post(out); +})(); +</script></body></html> +""".replace("__GROUP__", GROUP).replace("__LINKS__", json.dumps(LINKS)) + + +class H(http.server.SimpleHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) + if self.path == "/log": + RECORDS.append(json.loads(body.decode())) + self.send_response(204) + self.end_headers() + + def _send(self, body: bytes, ctype: str) -> None: + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + path = self.path.split("?")[0] + if path == "/": + self._send(PAGE.encode(), "text/html; charset=utf-8") + return + asset = (STATIC / path.lstrip("/")).resolve() + if not str(asset).startswith(str(STATIC)) or not asset.is_file(): + self.send_response(404) + self.end_headers() + return + ctype = "text/javascript" if asset.suffix in (".js", ".mjs") else ( + "application/wasm" if asset.suffix == ".wasm" else "application/octet-stream") + self._send(asset.read_bytes(), ctype) + + +def _run(case: str) -> dict | None: + before = len(RECORDS) + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile: + proc = subprocess.Popen( + ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox", + f"--user-data-dir={profile}", f"http://127.0.0.1:{PORT}/?case={case}"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(300): + if len(RECORDS) > before: + break + time.sleep(0.1) + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + return RECORDS[before] if len(RECORDS) > before else None + + +def main() -> int: + with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv: + threading.Thread(target=srv.serve_forever, daemon=True).start() + results = [_run(case) for case in CASES] + if not all(results): + print(json.dumps({"error": "no measurement", "got": results}), file=sys.stderr) + return 1 + print(json.dumps(results, indent=1)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/meshbay-hub/tests/test_android_cast.py b/packages/meshbay-hub/tests/test_android_cast.py index bc5264e..ebcdec4 100644 --- a/packages/meshbay-hub/tests/test_android_cast.py +++ b/packages/meshbay-hub/tests/test_android_cast.py @@ -103,12 +103,14 @@ def test_the_receiver_is_pointed_at_the_relay_and_nothing_else(): def test_relay_calls_keep_their_order(): """The page does not await each push; on a pool they could overtake.""" channels = _read(CAST / "CastChannels.kt") - assert '"cast:start", "cast:push", "cast:subtitle", "cast:finish", "cast:stop"' in channels + assert '"cast:start", "cast:push", "cast:subtitle",' in channels + assert ('"cast:file:begin", "cast:file:write", "cast:file:end", "cast:finish", "cast:stop"' + in channels) bridge = _read(SRC / "bridge" / "Bridge.kt") assert "Executors.newSingleThreadExecutor()" in bridge assert "(if (ordered) serial else work).execute" in bridge - assert "fun ordered(frame: BinaryFrame) = frame.channel == BinaryFrame.CAST_PUSH" in _read( - SRC / "bridge" / "Channels.kt") + assert ("fun ordered(frame: BinaryFrame) = frame.channel == BinaryFrame.CAST_PUSH" + " || frame.channel == BinaryFrame.CAST_FILE") in _read(SRC / "bridge" / "Channels.kt") def test_screen_off_survival_is_switched_on_only_while_casting_or_playing(): diff --git a/packages/meshbay-hub/tests/test_cast_files.py b/packages/meshbay-hub/tests/test_cast_files.py new file mode 100644 index 0000000..8f51d80 --- /dev/null +++ b/packages/meshbay-hub/tests/test_cast_files.py @@ -0,0 +1,372 @@ +""" +Whole files on a cast receiver — photos and music tracks — and the television +a session casts to. + +A file takes a different road to the television than a film: no stream, one +file at a time, handed to the relay in pieces (begin, writes, end), served at +`/file` with its cover at `/cover`, and loaded by the default media receiver +as a picture or as a music track. The page scales and re-encodes a photo +first (cast-session.js); a track goes as it is stored. + +The first half runs the desktop relay itself, as test_cast_subtitles.py does: +it is plain Node with no dependencies. The file is behind the same token as +the stream, its address changes with every file — a receiver handed the same +URL twice shows what it already has — ranges are honoured, because that is how +a receiver seeks in a track, and only a picture or a sound is served as one. + +The second half holds the wiring: what the receiver loads is the shell's to +say, never the page's; Android accepts no URL but the relay's own; a +television chosen anywhere is the one a film opens on, with the player as its +remote from the start; and the music bar drives the television once one is +chosen. +""" + +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest + +PACKAGES = Path(__file__).resolve().parents[2] +STATIC = PACKAGES / "meshbay-hub" / "src" / "meshbay_hub" / "static" +DESKTOP = PACKAGES / "meshbay-client" / "src" +RELAY = DESKTOP / "cast-relay.js" +CHROMECAST = DESKTOP / "cast-chromecast.js" +ANDROID_MAIN = PACKAGES / "meshbay-android" / "app" / "src" / "main" +ANDROID_SRC = ANDROID_MAIN / "kotlin" +CLIENT = ANDROID_SRC / "org" / "meshbay" / "client" +CAST = CLIENT / "cast" +SHIM = ANDROID_MAIN / "assets" / "bridge" / "meshbay-bridge.js" + + +def _read(path: Path) -> str: + return path.read_text(encoding="utf-8") + + +RELAY_SCRIPT = r""" +const http = require('node:http'); +const CastRelay = require(process.argv[2]); +const get = (url, headers = {}) => new Promise((resolve, reject) => { + http.get(url, { headers }, (res) => { + const parts = []; + res.on('data', (c) => parts.push(c)); + res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, + body: Buffer.concat(parts).toString('hex') })); + }).on('error', reject); +}); +const refused = async (f) => { try { await f(); return false; } catch { return true; } }; +const send = async (relay, bytes, opts) => { + await relay.beginFile({ size: bytes.length, ...opts }); + for (let at = 0; at < bytes.length; at += 3) relay.writeFile(bytes.subarray(at, at + 3)); + return relay.endFile(); +}; +(async () => { + const relay = new CastRelay(); + const out = {}; + out.activeBefore = relay.active; + out.htmlRefused = await refused(() => relay.beginFile({ type: 'text/html', size: 3 })); + out.activeAfterRefusal = relay.active; + + const jpeg = Buffer.from([0xff, 0xd8, 1, 2, 0xff, 0xd9]); + const first = await send(relay, jpeg, { type: 'image/jpeg' }); + out.activeAfterPhoto = relay.active; + out.firstUrl = first.url; + out.photo = await get(first.url); + out.badToken = (await get(first.url.replace(/t=[0-9a-f]+/, 't=x'))).status; + out.photoMeta = relay.fileMeta; + + // A track, its cover and what to show with it; read back whole and by range. + const track = Buffer.from([...Array(20).keys()]); + const second = await send(relay, track, { + type: 'audio/flac', title: 'A Song', artist: 'Some Band', album: 'An Album', + cover: { bytes: Buffer.from([0xff, 0xd8, 7, 0xff, 0xd9]), type: 'image/jpeg' } }); + out.secondUrl = second.url; + out.trackType = relay.fileType; + out.trackMeta = relay.fileMeta; + out.whole = await get(second.url); + out.range = await get(second.url, { Range: 'bytes=5-9' }); + out.tail = await get(second.url, { Range: 'bytes=15-' }); + out.beyond = (await get(second.url, { Range: 'bytes=50-60' })).status; + out.cover = await get(relay.fileMeta.cover); + + // Fewer bytes than announced is not a file; more is refused as they come. + await relay.beginFile({ type: 'audio/mpeg', size: 10 }); + relay.writeFile(Buffer.from([1, 2, 3])); + out.shortRefused = await refused(() => relay.endFile()); + await relay.beginFile({ type: 'audio/mpeg', size: 2 }); + out.longRefused = await refused(() => relay.writeFile(Buffer.from([1, 2, 3]))); + out.stillServed = (await get(second.url)).status; + + await relay.start({}); + out.fileAfterFilm = relay.fileUrl; + await send(relay, jpeg, { type: 'image/jpeg' }); + await relay.stop(); + out.fileAfterStop = relay.fileUrl; + console.log(JSON.stringify(out)); +})().catch((e) => { console.error(e); process.exit(1); }); +""" + + +@pytest.fixture(scope="module") +def relay_run(tmp_path_factory): + if shutil.which("node") is None or not RELAY.exists(): + pytest.skip("node or the desktop client sources are not available") + script = tmp_path_factory.mktemp("cf") / "relay.cjs" + script.write_text(RELAY_SCRIPT, encoding="utf-8") + proc = subprocess.run(["node", str(script), str(RELAY)], + capture_output=True, text=True, encoding="utf-8", timeout=30) + assert proc.returncode == 0, proc.stderr + return json.loads(proc.stdout) + + +def test_a_file_starts_the_relay_and_is_served_behind_its_token(relay_run): + assert relay_run["activeBefore"] is False + assert relay_run["activeAfterPhoto"] is True + photo = relay_run["photo"] + assert photo["status"] == 200 + assert photo["headers"]["content-type"] == "image/jpeg" + assert photo["headers"]["cache-control"] == "no-store" + assert photo["body"] == "ffd80102ffd9" + assert relay_run["badToken"] == 403 + assert relay_run["photoMeta"]["cover"] is None + + +def test_every_file_has_its_own_address(relay_run): + assert re.search(r"/file\?t=[0-9a-f]{32}&v=\d+$", relay_run["firstUrl"]) + assert relay_run["secondUrl"] != relay_run["firstUrl"] + + +def test_a_track_is_served_with_its_cover_and_what_it_is(relay_run): + assert relay_run["trackType"] == "audio/flac" + meta = relay_run["trackMeta"] + assert (meta["title"], meta["artist"], meta["album"]) == ("A Song", "Some Band", "An Album") + assert re.search(r"/cover\?t=[0-9a-f]{32}&v=\d+$", meta["cover"]) + assert relay_run["cover"]["status"] == 200 + assert relay_run["cover"]["body"] == "ffd807ffd9" + assert relay_run["whole"]["body"] == bytes(range(20)).hex() + assert relay_run["whole"]["headers"]["accept-ranges"] == "bytes" + + +def test_a_receiver_seeks_in_a_track_by_range(relay_run): + r = relay_run["range"] + assert r["status"] == 206 + assert r["headers"]["content-range"] == "bytes 5-9/20" + assert r["body"] == bytes(range(5, 10)).hex() + tail = relay_run["tail"] + assert tail["status"] == 206 and tail["body"] == bytes(range(15, 20)).hex() + assert relay_run["beyond"] == 416 + + +def test_only_a_whole_picture_or_sound_is_served(relay_run): + assert relay_run["htmlRefused"] is True + assert relay_run["activeAfterRefusal"] is False, "a refused file starts nothing" + assert relay_run["shortRefused"] is True + assert relay_run["longRefused"] is True + assert relay_run["stillServed"] == 200, "a failed send leaves the shown file alone" + + +def test_a_film_or_a_stop_takes_the_file_down(relay_run): + assert relay_run["fileAfterFilm"] is None + assert relay_run["fileAfterStop"] is None + + +def test_the_receiver_loads_a_photo_as_a_picture_and_a_track_as_music(): + if shutil.which("node") is None or not CHROMECAST.exists(): + pytest.skip("node or the desktop client sources are not available") + script = ( + "const Module = require('node:module');" + "const real = Module._load;" + "Module._load = function (r, ...a) {" + " if (r === 'bonjour-service') return { Bonjour: class {} };" + " if (r === 'castv2-client') return { Client: class {}, DefaultMediaReceiver: {} };" + " return real.call(this, r, ...a); };" + f"const {{ mediaFor, loadOptionsFor }} = require({json.dumps(str(CHROMECAST))});" + "const meta = { title: 'A Song', artist: 'Some Band', album: 'An Album'," + " cover: 'http://x/cover?t=a&v=2' };" + "console.log(JSON.stringify({" + " photo: mediaFor('http://x/file?t=a&v=1', null," + " { contentType: 'image/jpeg', meta: { cover: null } })," + " track: mediaFor('http://x/file?t=a&v=2', null, { contentType: 'audio/flac', meta })," + " from: loadOptionsFor(null, 42.5)," + " film: mediaFor('http://x/stream.mp4?t=a', null, null)," + " filmOptions: loadOptionsFor(null, 0)," + " legacy: mediaFor('http://x/stream.mp4?t=a', null) }));") + proc = subprocess.run(["node", "-e", script], capture_output=True, text=True, + encoding="utf-8", timeout=30) + assert proc.returncode == 0, proc.stderr + out = json.loads(proc.stdout) + assert out["photo"]["contentType"] == "image/jpeg" + assert out["photo"]["streamType"] == "NONE" + assert "tracks" not in out["photo"] + track = out["track"] + assert track["contentType"] == "audio/flac" and track["streamType"] == "BUFFERED" + assert track["metadata"] == {"metadataType": 3, "title": "A Song", "artist": "Some Band", + "albumName": "An Album", + "images": [{"url": "http://x/cover?t=a&v=2"}]} + assert out["from"]["currentTime"] == 42.5 + assert "currentTime" not in out["filmOptions"] + assert out["film"] == out["legacy"], "a film is loaded exactly as before" + assert out["film"]["streamType"] == "LIVE" and out["film"]["contentType"] == "video/mp4" + + +def test_the_shell_not_the_page_says_what_the_receiver_loads(): + """The page names a URL; what it is, is the relay's to say. A page that + could name the content type could have a television load the stream as + anything at all.""" + main = _read(DESKTOP / "main.js") + load_of = main.split("const loadOf = ", 1)[1].split("\n\n", 1)[0] + assert "mediaUrl === castRelay.fileUrl" in load_of + assert "contentType: castRelay.fileType, meta: castRelay.fileMeta" in load_of + assert "subtitle: null" in load_of, "a file carries no subtitle" + assert main.count("loadOf(mediaUrl, subtitle)") == 2, "connect and reload both" + # A start position means something for a file only; a film starts where + # its relay does. + assert main.count("l.file ? startAt : 0") == 2 + + +def test_android_accepts_the_relays_file_and_nothing_else(): + if not CAST.exists(): + pytest.skip("android sources not present") + channels = _read(CAST / "CastChannels.kt") + check = channels.split("private fun relayUrl(", 1)[1].split("\n }", 1)[0] + assert "asked != ours && asked != relay.fileUrl" in check + assert 'put("contentType", relay.fileType).put("meta", relay.fileMeta()' in channels + assert "url == relay.fileUrl -> null" in channels, "a file carries no subtitle" + assert 'if (url == relay.fileUrl) maxOf(0.0, o.optDouble("startAt", 0.0)) else 0.0' in channels + # A file is not a cast that has to survive the screen going off. + begin = channels.split('"cast:file:begin" ->', 1)[1].split('"cast:file:end"', 1)[0] + assert "onCasting" not in begin + relay = _read(CAST / "CastRelay.kt") + assert '"/file" -> serveFile(out, socket, range)' in relay + assert '"/cover" -> serveCover(out, socket)' in relay + serve = relay.split("private fun serve(", 1)[1] + assert serve.index('query["t"] != token') < serve.index('"/file"'), "behind the token" + # On disk, never held: a long lossless track is a few hundred megabytes. + assert 'File(spoolDir, "file-${fileSeq.incrementAndGet()}.bin")' in relay + assert "java.io.FileOutputStream(slot.path)" in relay + control = _read(CAST / "CastControl.kt") + assert "MediaInfo.STREAM_TYPE_NONE" in control + assert "MediaMetadata.MEDIA_TYPE_PHOTO" in control + assert "MediaMetadata.MEDIA_TYPE_MUSIC_TRACK" in control + assert "MediaInfo.STREAM_TYPE_BUFFERED" in control + assert "setCurrentTime((startAt * 1000).toLong())" in control + assert "MediaSeekOptions.Builder().setPosition(" in control + # Loaded is shown: a photo never reaches PLAYING, and waiting for it + # would hold every photo for the full fifteen seconds. + load = control.split("private fun load(", 1)[1] + assert load.index("if (photo) return") < load.index("PLAY_WAIT_MS") + + +def test_a_file_crosses_the_android_bridge_in_binary_pieces(): + """One message the size of a lossless track would be the WebView's to + refuse; a file goes in pieces of a megabyte, as binary frames where the + WebView has them.""" + if not SHIM.exists(): + pytest.skip("android sources not present") + shim = _read(SHIM) + assert "const CAST_FILE = 3;" in shim + assert "const FILE_PIECE = 1024 * 1024;" in shim + assert ("BINARY ? sendBinary(CAST_FILE, 0, piece) : call('cast:file:write', base64Of(piece))" + in shim) + assert "const val CAST_FILE = 3" in _read(CLIENT / "save" / "SaveNames.kt") + channels = _read(CLIENT / "bridge" / "Channels.kt") + assert "BinaryFrame.CAST_FILE -> " in channels and ".writeFile(frame.bytes" in channels + + +def test_a_television_chosen_anywhere_takes_the_next_film(): + """The player opens as the remote of a television chosen before it, the + cast pending until the first segment exactly as a restart is; choosing one + in the player keeps it for the session, and stopping there forgets it.""" + player = _read(STATIC / "video-player.js") + assert ("const [autoCast] = useState(() => " + "(castSession.supported ? castSession.device : null));") in player + assert "useState(Boolean(autoCast))" in player + assert "castActiveRef = useRef(Boolean(autoCast))" in player + assert "castRestartPendingRef = useRef(Boolean(autoCast))" in player + assert "castDeviceRef = useRef(autoCast)" in player + assert "useState(autoCast ? autoCast.name : null)" in player + stop = player.split("const stopCast = async () => {", 1)[1].split("};", 1)[0] + assert "castSession.forget()" in stop + assert "castSession.choose(d);" in player + assert "castSession.claim('video')" in player + + +def test_the_cast_button_is_where_the_media_are(): + """Videos' toolbar, the Photos landing, a photo album's bar and Music's + toolbar are drawn by the group page and the search page alike, so one + button in each covers both. On the Photos landing the button keeps a + toolbar Search would otherwise hide. The music bar has its own, opening + upward from the bottom of the window.""" + videos = _read(STATIC / "video-app.js") + assert "<${CastButton} />" in videos.split('<div class="video-toolbar">', 1)[1] + photos = _read(STATIC / "photos-app.js") + landing = photos.split("function PhotosApp(", 1)[1] + assert "(!hideFilter || castSession.supported) && html`" in landing + assert "<${CastButton} />" in landing.split('<div class="photo-toolbar">', 1)[1] + album = photos.split("function AlbumView(", 1)[1] + assert "<${CastButton}" in album + lightbox = photos.split("function Lightbox(", 1)[1].split("function AlbumView(", 1)[0] + assert '<${CastButton} variant="overlay"' in lightbox + assert "if (castDevice && blobUrl && blob) showPhoto(blob);" in lightbox + music = _read(STATIC / "music-app.js") + assert "<${CastButton} />" in music.split('<div class="video-toolbar">', 1)[1] + bar = _read(STATIC / "music-player.js") + assert '<${CastButton} cls="music-player-btn" up />' in bar + # The group page draws them through the app registry, the search page + # imports them: the same components either way. + registry = _read(STATIC / "apps.js") + search = _read(STATIC / "search-page.js") + for page in (registry, search): + for app in ("VideoApp", "PhotosApp", "MusicApp"): + assert app in page + + +def test_the_music_bar_drives_the_television(): + """With a television chosen, the decrypted track goes to the relay instead + of the element, and the bar's controls and clock are the receiver's. The + receiver keeps saying FINISHED until it is given something else, so the + end of a track moves the queue on once; and a television a film or a + photo has taken is not the bar's to read.""" + bar = _read(STATIC / "music-player.js") + assert "const remote = Boolean(castDevice) && castSession.canSendFiles;" in bar + send = bar.split("const sendToTv = useCallback(", 1)[1].split("}, [fetchCover]);", 1)[0] + assert "owner: 'music', startAt," in send + assert "type: cached.mime, cover," in send + assert "sendingRef.current = true;" in send + load = bar.split("if (remoteRef.current) {\n // To the television", 1)[1] + assert "audio.pause();" in load.split("await audio.play();", 1)[0] + tick = bar.split("const tick = async () => {", 1)[1].split("const id = setInterval", 1)[0] + assert "castSession.owner !== 'music'" in tick + assert "sendingRef.current" in tick + assert "finishedRef.current !== remoteTrackRef.current" in tick + assert "String(c.idleReason || '').toLowerCase() === 'finished'" in tick + # The cover is found as the album card finds it, not only on the track. + cover = bar.split("const fetchCover = useCallback(", 1)[1] + cover = cover.split("}, [getConnection, tracks]);", 1)[0] + assert "entry.thumb_hash || (sibling && sibling.thumb_hash)" in cover + assert "transport.fetchMusicMeta(entry.id)" in cover + assert "meta.cover_thumb_hash" in cover + assert "castBridge.chromecastSeek(to)" in bar + assert "castBridge.chromecastPause() : castBridge.chromecastPlay()" in bar + # Stopping the cast carries the track on here; a film taking the + # television pauses the bar. + assert "if (castSession.device && castSession.owner !== 'music') setPlaying(false);" in bar + + +def test_a_photo_leaves_scaled_and_upright(): + session = _read(STATIC / "cast-session.js") + assert "imageOrientation: 'from-image'" in session + assert "const TV_WIDTH = 1920;" in session and "const TV_HEIGHT = 1080;" in session + assert "Math.min(1, TV_WIDTH / bitmap.width, TV_HEIGHT / bitmap.height)" in session + assert "await loadFile({ owner: 'photo', bytes, type: 'image/jpeg' });" in session + # Only the newest photo asked for is sent. + assert session.count("gen !== photoGen") >= 2 + + +def test_every_locale_names_the_slideshow(): + for f in sorted((STATIC / "locales").glob("*.js")): + text = f.read_text(encoding="utf-8") + for key in ("photo.slideshow", "photo.slideshow_stop"): + assert f"'{key}':" in text, f"{f.name} lacks {key}" diff --git a/packages/meshbay-hub/tests/test_copy_link.py b/packages/meshbay-hub/tests/test_copy_link.py new file mode 100644 index 0000000..7115d04 --- /dev/null +++ b/packages/meshbay-hub/tests/test_copy_link.py @@ -0,0 +1,98 @@ +""" +"Copy link": the `#/name@owner/path` address of a file or folder, from the +views that show one (harness/copy_link_probe.py). + +Files offers it for one row — right-click, or the toolbar with one row ticked, +which is how a phone reaches it; Music on one track's menu, whose dots are a +phone's way in; Photos on a right-clicked tile and in the lightbox. The video +player and the file preview carry a button. Search passes the same `linkFor`, +naming each result's own group and its path there rather than the merged tree's. +""" + +import json +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +HARNESS = Path(__file__).parent / "harness" / "copy_link_probe.py" +STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static" +ORIGIN = "http://127.0.0.1:8775" + + +@pytest.fixture(scope="module") +def cases(): + if shutil.which("google-chrome") is None: + pytest.skip("Chrome is not available") + proc = subprocess.run([sys.executable, str(HARNESS)], + capture_output=True, text=True, timeout=180) + assert proc.returncode == 0, f"probe failed: {proc.stdout}{proc.stderr}" + out = json.loads(proc.stdout) + assert "error" not in out, out["error"] + assert out["logs"] == [] + return {c["case"]: c for c in out["cases"]} + + +def test_files_a_folder(cases): + c = cases["files folder"] + assert "Copy link" in c["labels"] + assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Root" + assert c["note"] == "Link copied" + + +def test_files_a_file(cases): + c = cases["files file"] + assert c["labels"].index("Copy link") > c["labels"].index("Download") + assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Root/trip_2015/IMG%200001.JPG" + + +def test_files_toolbar_one_ticked_row_only(cases): + c = cases["files toolbar"] + assert c["one_enabled"] is True and c["two_enabled"] is False + assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Root/trip_2015/notes.txt" + + +def test_music_a_track_from_its_dots(cases): + c = cases["music track"] + assert c["dots"] and c["labels"][-1] == "Copy link" + assert c["copied"] == f"{ORIGIN}/#/demo@someowner/Music/Some%20Album/track%2001.flac" + + +def test_photos_tile_and_lightbox(cases): + c = cases["photos"] + link = f"{ORIGIN}/#/demo@someowner/Pics/Summer/beach.jpg" + assert c["labels"] == ["Copy link"] and c["copied"] == link + assert c["lightbox_button"] and c["lightbox_copied"] == link + + +@pytest.mark.parametrize("module", ["video-player.js", "files-app.js"]) +def test_the_modals_carry_a_link_button(module): + source = (STATIC / module).read_text(encoding="utf-8") + assert re.search(r"function (VideoPlayer|FilePreview)\(\{[^}]*onCopyLink", source) + assert "${onCopyLink && html`" in source + + +@pytest.mark.parametrize("page, n", [("group-page.js", 2), ("search-page.js", 2)]) +def test_both_pages_hand_the_modals_a_link(page, n): + source = (STATIC / page).read_text(encoding="utf-8") + assert source.count("onCopyLink=${linkFor(") == n + + +def test_search_names_each_results_own_group_and_path(): + source = (STATIC / "search-page.js").read_text(encoding="utf-8") + # Every view prefixes `path`; the link is built from the original. + assert source.count("_origPath: e.path,") == 4 + assert "entryPath(target, target._origPath)" in source + for view in ("FilesPanel", "MusicApp", "PhotosApp"): + at = source.index(f"<${{{view}}}") + assert "linkFor=${linkFor}" in source[at:source.index("/>", at)], view + + +def test_the_link_is_the_hubs_not_the_pages(): + """In the desktop application the page is app://meshbay.""" + source = (STATIC / "copy-link.js").read_text(encoding="utf-8") + assert "platform.hubOrigin() + '/#' + groupLinkRoute(" in source + assert "location.origin" not in source diff --git a/packages/meshbay-hub/tests/test_group_link.py b/packages/meshbay-hub/tests/test_group_link.py new file mode 100644 index 0000000..e71df20 --- /dev/null +++ b/packages/meshbay-hub/tests/test_group_link.py @@ -0,0 +1,170 @@ +""" +A group named in the address: `#/name@owner[/path]`. + +The handle under every group's name is also a link to it, and a path after it +names a folder to open or a file to download. `group-link.js` parses it, +builds it, finds the group among the account's own and the entry in the +group's index; the module is executed whole, as `test_search_source_merge.py` +does with `source-merge.js`, so these rules are the ones the page runs. + +Also held here, at source level: the sign-in form no longer sends everyone +home, which is what made any link opened signed out land on the home page. +""" + +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest + +STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static" +SRC = STATIC / "group-link.js" + +IMPORT = re.compile(r"^\s*import\b", re.M) +EXPORT = re.compile(r"^export \{[^}]*\};?\s*$", re.M) + +needs_node = pytest.mark.skipif( + shutil.which("node") is None or not SRC.exists(), + reason="node or the SPA sources are not available") + + +@pytest.fixture(scope="module") +def module_source(): + text = SRC.read_text(encoding="utf-8") + assert not IMPORT.search(text), ( + "group-link.js has gained an import; this test runs it standalone") + stripped, n = EXPORT.subn("", text) + assert n == 1 + return stripped + + +def _run(tmp_path, module_source, expr): + script = tmp_path / "case.js" + script.write_text(f"{module_source}\nconsole.log(JSON.stringify({expr}));\n", + encoding="utf-8") + out = subprocess.run(["node", str(script)], capture_output=True, text=True, + encoding="utf-8", timeout=30) + assert out.returncode == 0, out.stderr + return json.loads(out.stdout) + + +GROUPS = [ + {"id": "g1", "name": "demo", "owner_username": "someowner"}, + {"id": "g2", "name": "demo", "owner_username": "otherowner"}, + {"id": "g3", "name": "trips@home", "owner_username": "someowner"}, + {"id": "g4", "name": "a/b c", "owner_username": "someowner"}, +] + +ENTRIES = [ + {"path": "backup/city_2015/backup", "name": "IMG_0001.JPG"}, + {"path": "backup/city_2015", "name": "notes.txt"}, + {"path": "music", "name": "track 01.flac"}, +] + + +@needs_node +@pytest.mark.parametrize("route, expected", [ + ("/demo@someowner", {"name": "demo", "owner": "someowner", "path": ""}), + ("/demo@someowner/backup/city_2015/backup/IMG_0001.JPG", + {"name": "demo", "owner": "someowner", + "path": "backup/city_2015/backup/IMG_0001.JPG"}), + # The owner is after the last `@`: a group name may hold one, a username not. + ("/trips@home@someowner", {"name": "trips@home", "owner": "someowner", "path": ""}), + # Each segment decoded on its own: an escaped `/` stays inside its segment. + ("/a%2Fb%20c@someowner/music/track%2001.flac", + {"name": "a/b c", "owner": "someowner", "path": "music/track 01.flac"}), + ("/demo@someowner/music/", {"name": "demo", "owner": "someowner", "path": "music"}), + # Every other route, and anything that is not a well-formed handle. + ("/group/0f8fad5b-d9cb-469f-a165-70867728950e", None), + ("/login", None), ("/", None), ("", None), + ("/@someowner", None), ("/demo@", None), + ("/demo@someowner/%E0%A4%A", None), + ("/demo@someowner/music/../../etc", None), +]) +def test_parse(tmp_path, module_source, route, expected): + assert _run(tmp_path, module_source, f"parseGroupLink({json.dumps(route)})") == expected + + +@needs_node +@pytest.mark.parametrize("group, path", [ + (GROUPS[0], ""), + (GROUPS[0], "backup/city_2015/backup/IMG_0001.JPG"), + (GROUPS[2], ""), + (GROUPS[3], "music/track 01.flac"), + ({"name": "Été à la mer", "owner_username": "someowner"}, "photos/plage #1.jpg"), +]) +def test_built_routes_parse_back(tmp_path, module_source, group, path): + out = _run(tmp_path, module_source, + f"(() => {{ const r = groupLinkRoute({json.dumps(group)}, {json.dumps(path)});" + f" return [r, parseGroupLink(r)]; }})()") + route, parsed = out + assert parsed == {"name": group["name"], "owner": group["owner_username"], "path": path} + # Nothing that ends or splits a fragment is left bare. + assert not re.search(r"[#?\s%](?![0-9A-F]{2})", route) + + +@needs_node +def test_a_plain_handle_stays_readable(tmp_path, module_source): + route = _run(tmp_path, module_source, + f"groupLinkRoute({json.dumps(GROUPS[0])}, 'backup/city_2015/IMG_1.JPG')") + assert route == "/demo@someowner/backup/city_2015/IMG_1.JPG" + + +@needs_node +@pytest.mark.parametrize("link, expected", [ + ({"name": "demo", "owner": "someowner"}, "g1"), + ({"name": "demo", "owner": "otherowner"}, "g2"), + # The hub keeps names unique on lower(name). + ({"name": "DEMO", "owner": "someowner"}, "g1"), + ({"name": "demo", "owner": "SomeOwner"}, "g1"), + # Not among the account's groups: nothing, and nothing asked of the hub. + ({"name": "demo", "owner": "stranger1"}, None), + ({"name": "secret", "owner": "someowner"}, None), +]) +def test_find_among_own_groups(tmp_path, module_source, link, expected): + out = _run(tmp_path, module_source, + f"(findLinkedGroup({json.dumps(GROUPS)}, {json.dumps(link)}) || {{}}).id || null") + assert out == expected + + +@needs_node +@pytest.mark.parametrize("path, expected", [ + ("backup/city_2015/backup/IMG_0001.JPG", + {"kind": "file", "entry": ENTRIES[0]}), + ("backup/city_2015/notes.txt", {"kind": "file", "entry": ENTRIES[1]}), + ("backup/city_2015", {"kind": "dir", "dir": "backup/city_2015"}), + ("backup", {"kind": "dir", "dir": "backup"}), + # An empty folder exists only in the node's own listing. + ("backup/empty", {"kind": "dir", "dir": "backup/empty"}), + # A prefix of a folder name is not that folder. + ("backup/city", None), + ("backup/city_2015/backup/img_0001.jpg", None), + ("", None), +]) +def test_resolve_in_index(tmp_path, module_source, path, expected): + out = _run(tmp_path, module_source, + f"resolveLinkedPath({json.dumps(ENTRIES)}, ['backup/empty'], {json.dumps(path)})") + assert out == expected + + +def test_signing_in_keeps_the_page_the_address_names(): + """A group or file link opened signed out shows the sign-in form in its + place; signing in must leave the address alone, not send everyone home.""" + source = (STATIC / "auth-page.js").read_text(encoding="utf-8") + body = source[source.index("export function LoginPage"):] + body = body[:body.index("\n}\n")] + assert "navigate('/')" not in body and 'navigate("/")' not in body + assert "if (loadPending()) navigate('/invite');" in body + + +def test_the_router_resolves_a_handle_and_shows_it(): + source = (STATIC / "app.js").read_text(encoding="utf-8") + body = source[source.index("\nfunction App() {"):] + assert "parseGroupLink(route)" in body + assert "findLinkedGroup(groups, groupLink)" in body + # Rewritten with `replace`: showing the handle is not a history entry. + assert "window.location.replace('#' + shownGroupRoute)" in body + # The sidebar highlights the group whichever form opened it. + assert re.search(r"<\$\{Sidebar\}[\s\S]*?route=\$\{groupRoute\}", body) diff --git a/packages/meshbay-hub/tests/test_group_link_flow.py b/packages/meshbay-hub/tests/test_group_link_flow.py new file mode 100644 index 0000000..eb6a353 --- /dev/null +++ b/packages/meshbay-hub/tests/test_group_link_flow.py @@ -0,0 +1,67 @@ +""" +A group link, opened in the real application (harness/group_link_probe.py). + +`test_group_link.py` holds the parsing and the lookups; this is where they meet +the router. A handle opens the group's page, and an id opens it with the handle +in the address; a path waits in the address for the index to say what it is; a +handle the account does not know is said to be unknown without the hub ever +being asked about it; and signed out, the sign-in form stands in for the page +with the address left alone, which is what lets signing in land there. +""" + +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +HARNESS = Path(__file__).parent / "harness" / "group_link_probe.py" +GROUP_HREF = "#/group/0f8fad5b-d9cb-469f-a165-70867728950e" +FILE_LINK = "#/demo@someowner/backup/city_2015/backup/IMG_0001.JPG" + + +@pytest.fixture(scope="module") +def cases(): + if shutil.which("google-chrome") is None: + pytest.skip("Chrome is not available") + proc = subprocess.run([sys.executable, str(HARNESS)], + capture_output=True, text=True, timeout=240) + assert proc.returncode == 0, f"probe failed: {proc.stdout}{proc.stderr}" + out = {c["case"]: c for c in json.loads(proc.stdout)} + for c in out.values(): + assert "error" not in c, c["error"] + return out + + +@pytest.mark.parametrize("case", ["handle", "uuid", "file"]) +def test_a_handle_or_an_id_opens_the_group(cases, case): + c = cases[case] + assert c["group_page"] and c["group_title"] == "demo@someowner" + # Of two groups called "demo", the one whose owner the handle names. + assert c["active_sidebar"] == [GROUP_HREF] + + +@pytest.mark.parametrize("case", ["handle", "uuid"]) +def test_the_address_shows_the_handle_without_a_history_entry(cases, case): + assert cases[case]["hash"] == "#/demo@someowner" + assert cases[case]["history_length"] == 1 + + +def test_a_path_stays_in_the_address_until_it_has_been_acted_on(cases): + assert cases["file"]["hash"] == FILE_LINK + + +def test_an_unknown_handle_is_said_so_without_asking_the_hub(cases): + c = cases["unknown"] + assert not c["group_page"] and c["message"] and not c["spinner"] + assert c["hash"] == "#/demo@stranger1" + for case in cases.values(): + assert not any("stranger1" in u or "@" in u for u in case["hub_calls"]) + + +def test_signed_out_the_form_stands_in_for_the_page(cases): + c = cases["signed_out"] + assert c["login_form"] and not c["group_page"] + assert c["hash"] == FILE_LINK diff --git a/packages/meshbay-hub/tests/test_http_api_doc.py b/packages/meshbay-hub/tests/test_http_api_doc.py new file mode 100644 index 0000000..5568e63 --- /dev/null +++ b/packages/meshbay-hub/tests/test_http_api_doc.py @@ -0,0 +1,30 @@ +""" +docs/MESHBAY_HTTP_API.md is generated from the routes of the hub and of the +node's control API. A route added, removed or redescribed without running +`python docs/generate_http_api.py` fails here. +""" + +import importlib.util +from pathlib import Path + +GENERATOR = Path(__file__).resolve().parents[3] / "docs" / "generate_http_api.py" + + +def _generator(): + spec = importlib.util.spec_from_file_location("generate_http_api", GENERATOR) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_the_api_listing_matches_the_routes(): + gen = _generator() + assert gen.OUT.read_text(encoding="utf-8") == gen.render(), ( + "docs/MESHBAY_HTTP_API.md is out of date: run python docs/generate_http_api.py") + + +def test_every_route_says_what_it_does(): + gen = _generator() + bare = [f"{gen.method(r)} {r.path}" for r in gen.hub_routes() + gen.node_routes() + if not gen.summary(r)] + assert not bare, f"give these routes a docstring, it is their line in the listing: {bare}" diff --git a/packages/meshbay-hub/tests/test_spa_ordering.py b/packages/meshbay-hub/tests/test_spa_ordering.py index 6f28aaa..44f98db 100644 --- a/packages/meshbay-hub/tests/test_spa_ordering.py +++ b/packages/meshbay-hub/tests/test_spa_ordering.py @@ -162,7 +162,7 @@ def _component(name: str) -> str: def test_the_group_settings_panel_renders_what_it_owns(): panel = _component("GroupSettingsPanel") - assert "members.map(" in panel, "the member list is not rendered" + assert "joined.map(" in panel, "the member list is not rendered" assert "onSubmit=${doInvite}" in panel, "the invite form is not rendered" assert "onSubmit=${doPair}" in panel, "the pairing form is not rendered" assert "device.mine_title" in panel, "the devices section is not rendered" @@ -175,7 +175,7 @@ def test_the_roster_comes_last(): order is for — asked for in those terms. """ panel = _component("GroupSettingsPanel") - listing = panel.index("members.map(") + listing = panel.index("joined.map(") for name, marker in (("the invite form", "onSubmit=${doInvite}"), ("the pairing form", "onSubmit=${doPair}"), ("the devices section", "device.mine_title"), |