initial 0.1.0 commit
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
# Test harness
|
||||
|
||||
Drives the real extension in real Firefox through Selenium and asserts on the
|
||||
browser's own tab state.
|
||||
|
||||
```
|
||||
build-test-extension.sh copies the extension to /tmp/tabpark-test-build and
|
||||
adds the test hook (fixture host permission, content
|
||||
script, background hook)
|
||||
test-hook-content.js forwards page messages to the background
|
||||
test-hook-background.js exposes tuUnloadOtherTabs / tuUnloadActiveTab / tuSweep
|
||||
plus pin, activate, close, settings and state
|
||||
driver.py the main test
|
||||
protect.py the per-tab exception test
|
||||
```
|
||||
|
||||
Requirements: `firefox-esr`, `python3-selenium`, geckodriver, Xvfb. On this
|
||||
host geckodriver lives at `/tmp/rig/bin/geckodriver`; override with
|
||||
`GECKODRIVER=...`.
|
||||
|
||||
```
|
||||
Xvfb :99 -screen 0 1280x1024x24 -nolisten tcp &
|
||||
DISPLAY=:99 python3 test/harness/driver.py
|
||||
DISPLAY=:99 python3 test/harness/no-tabs.py
|
||||
DISPLAY=:99 python3 test/harness/protect.py
|
||||
```
|
||||
|
||||
`driver.py` adds the `tabs` permission to the test variant only, so the hook
|
||||
can identify tabs by URL. The extension code never reads tab URLs.
|
||||
`no-tabs.py` builds without it and identifies tabs by id, matching the shipped
|
||||
permission set exactly.
|
||||
|
||||
The driver serves `/p1` ... `/p6` from `127.0.0.1:8765` and counts hits, so a
|
||||
reload after unloading is observable independently of the extension.
|
||||
|
||||
Covered:
|
||||
|
||||
- unload others: keeps the active tab, discards every other non-pinned
|
||||
tab, leaves the pinned tab loaded, tab count unchanged
|
||||
- unload current: focus moves to the next loaded tab before the old tab is
|
||||
discarded; keeps the tab count
|
||||
- unload current on a blank tab: refused, nothing changes, pressing again is
|
||||
still a no-op
|
||||
- unload current when nothing else is loaded: opens a new tab and discards
|
||||
the old one
|
||||
- unload current on a pinned tab: honoured when asked directly
|
||||
- idle sweep: enabling auto-unload creates the alarm, the alarm (not a direct
|
||||
call) discards tabs idle past the threshold, the active tab survives
|
||||
- a discarded tab reloads when selected (server hit count increases)
|
||||
- popup and options pages render, read the saved settings, and the popup
|
||||
button drives the background
|
||||
- per-tab exception: a protected tab survives unload-others and the idle
|
||||
sweep, and is discarded once unprotected
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
# Builds the test variant of Tab Park into /tmp/tabpark-test-build:
|
||||
# identical extension code, plus
|
||||
# - the "tabs" permission, for the test hook only: it reports tab URLs so
|
||||
# the driver can identify tabs. The extension code never reads tab URLs.
|
||||
# - host permission for the fixture server
|
||||
# - content/test-hook-content.js, which forwards page messages
|
||||
# - background/test-hook-background.js, which exposes the real helpers
|
||||
set -euo pipefail
|
||||
|
||||
SRC=/workspace/tabpark
|
||||
OUT=/tmp/tabpark-test-build
|
||||
rm -rf "$OUT"
|
||||
mkdir -p "$OUT/content" "$OUT/background"
|
||||
|
||||
cp "$SRC"/manifest.json "$SRC"/common.js "$SRC"/background.js \
|
||||
"$SRC"/popup.html "$SRC"/popup.js "$SRC"/popup.css \
|
||||
"$SRC"/options.html "$SRC"/options.js "$SRC"/options.css "$OUT"/
|
||||
cp -r "$SRC"/icons "$OUT"/
|
||||
cp "$SRC"/test/harness/test-hook-content.js "$OUT/content/test-hook-content.js"
|
||||
cp "$SRC"/test/harness/test-hook-background.js "$OUT/background/test-hook-background.js"
|
||||
|
||||
python3 - "$OUT/manifest.json" <<'PY'
|
||||
import json, os, sys
|
||||
p = sys.argv[1]
|
||||
m = json.load(open(p))
|
||||
if os.environ.get('TU_NO_TABS') != '1' and 'tabs' not in m['permissions']:
|
||||
m['permissions'].append('tabs')
|
||||
m['host_permissions'] = ['http://127.0.0.1/*']
|
||||
m['content_scripts'] = [{
|
||||
'matches': ['http://127.0.0.1/*'],
|
||||
'js': ['content/test-hook-content.js'],
|
||||
'run_at': 'document_start'
|
||||
}]
|
||||
m['background']['scripts'].append('background/test-hook-background.js')
|
||||
json.dump(m, open(p, 'w'), indent=2)
|
||||
PY
|
||||
|
||||
echo "built $OUT"
|
||||
@@ -0,0 +1,421 @@
|
||||
#!/usr/bin/env python3
|
||||
"""End-to-end test for Tab Park in real Firefox.
|
||||
|
||||
Builds the test variant, serves fixture pages on 127.0.0.1, installs the
|
||||
extension temporarily, and drives it through a test hook. Every assertion is
|
||||
made against the browser's own tab state (tabs.query), not against the
|
||||
extension's bookkeeping.
|
||||
|
||||
Run with: DISPLAY=:99 python3 test/harness/driver.py
|
||||
"""
|
||||
|
||||
import collections
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.firefox.options import Options
|
||||
from selenium.webdriver.firefox.service import Service
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
BUILD = Path('/tmp/tabpark-test-build')
|
||||
GECKODRIVER = os.environ.get('GECKODRIVER', '/tmp/rig/bin/geckodriver')
|
||||
FIREFOX = os.environ.get('FIREFOX', '/usr/bin/firefox-esr')
|
||||
PORT = int(os.environ.get('TU_PORT', '8765'))
|
||||
BASE = f'http://127.0.0.1:{PORT}'
|
||||
|
||||
HITS = collections.Counter()
|
||||
CHECKS = []
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
path = self.path.split('?')[0]
|
||||
if not path.startswith('/p'):
|
||||
self.send_error(404)
|
||||
return
|
||||
HITS[path] += 1
|
||||
body = (f'<!DOCTYPE html><html><head><meta charset="utf-8">'
|
||||
f'<title>{path}</title></head><body><h1>{path}</h1></body></html>').encode()
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'text/html; charset=utf-8')
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def check(name, condition, detail=''):
|
||||
CHECKS.append((name, bool(condition)))
|
||||
line = ('PASS ' if condition else 'FAIL ') + name
|
||||
if detail and not condition:
|
||||
line += f' [{detail}]'
|
||||
print(line, flush=True)
|
||||
|
||||
|
||||
def launch():
|
||||
opts = Options()
|
||||
opts.binary_location = FIREFOX
|
||||
for key, value in {
|
||||
'browser.shell.checkDefaultBrowser': False,
|
||||
'browser.startup.homepage_override.mstone': 'ignore',
|
||||
'browser.aboutwelcome.enabled': False,
|
||||
'datareporting.policy.dataSubmissionEnabled': False,
|
||||
'toolkit.telemetry.reportingpolicy.firstRun': False,
|
||||
'extensions.autoDisableScopes': 0,
|
||||
'extensions.enabledScopes': 15,
|
||||
}.items():
|
||||
opts.set_preference(key, value)
|
||||
service = Service(executable_path=GECKODRIVER, service_args=['--allow-system-access'])
|
||||
return webdriver.Firefox(options=opts, service=service)
|
||||
|
||||
|
||||
def wait_uuid(driver, addon_id, timeout=20):
|
||||
prefs = Path(driver.capabilities['moz:profile']) / 'prefs.js'
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if prefs.exists():
|
||||
match = re.search(
|
||||
r'user_pref\("extensions\.webextensions\.uuids",\s*"(.*)"\);',
|
||||
prefs.read_text(errors='replace'))
|
||||
if match:
|
||||
uuids = json.loads(match.group(1).replace('\\"', '"'))
|
||||
if addon_id in uuids:
|
||||
return uuids[addon_id]
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError('extension uuid not found in prefs.js')
|
||||
|
||||
|
||||
def hook(driver, cmd, **kwargs):
|
||||
payload = {'cmd': cmd, **kwargs}
|
||||
last = None
|
||||
for _ in range(5):
|
||||
result = driver.execute_async_script("""
|
||||
const payload = arguments[0];
|
||||
const done = arguments[arguments.length - 1];
|
||||
const id = 'r' + Math.random();
|
||||
const timer = setTimeout(() => {
|
||||
window.removeEventListener('message', onMessage);
|
||||
done({timeout: true});
|
||||
}, 5000);
|
||||
function onMessage(event) {
|
||||
if (!event.data || event.data.tuResult !== id) return;
|
||||
clearTimeout(timer);
|
||||
window.removeEventListener('message', onMessage);
|
||||
done(event.data);
|
||||
}
|
||||
window.addEventListener('message', onMessage);
|
||||
window.postMessage(Object.assign({tuTest: true, id}, payload), '*');
|
||||
""", payload)
|
||||
if not result.get('timeout'):
|
||||
if 'error' in result:
|
||||
last = result['error']
|
||||
if 'Could not establish connection' not in last:
|
||||
raise RuntimeError(f'{cmd}: {last}')
|
||||
else:
|
||||
return result.get('value')
|
||||
time.sleep(0.4)
|
||||
raise RuntimeError(f'hook {cmd} failed: {last or "timeout"}')
|
||||
|
||||
|
||||
def state(driver):
|
||||
return hook(driver, 'state')
|
||||
|
||||
|
||||
def by_url(tabs, suffix):
|
||||
return next(tab for tab in tabs if (tab.get('url') or '').endswith(suffix))
|
||||
|
||||
|
||||
def wait_tab(driver, suffix, timeout=10):
|
||||
"""Poll until a tab with this URL suffix is visible.
|
||||
|
||||
A tab that is reloading after a discard briefly has no url, so a single
|
||||
state() read can miss it.
|
||||
"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
tabs = state(driver)
|
||||
match = next((tab for tab in tabs if (tab.get('url') or '').endswith(suffix)), None)
|
||||
if match:
|
||||
return match
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError(f'tab {suffix} not found')
|
||||
|
||||
|
||||
def use(driver, handles, path):
|
||||
driver.switch_to.window(handles[path])
|
||||
|
||||
|
||||
def fire(driver, cmd, **kwargs):
|
||||
"""Post a hook command without waiting for the reply.
|
||||
|
||||
Needed when the command discards the tab it is sent from: the async
|
||||
script would die with "Document was unloaded" before answering.
|
||||
"""
|
||||
driver.execute_script("""
|
||||
window.postMessage(Object.assign({tuTest: true, id: 'fire'}, arguments[0]), '*');
|
||||
""", {'cmd': cmd, **kwargs})
|
||||
|
||||
|
||||
def build():
|
||||
subprocess.run([str(HERE / 'build-test-extension.sh')], check=True)
|
||||
|
||||
|
||||
def main():
|
||||
build()
|
||||
server = ThreadingHTTPServer(('127.0.0.1', PORT), Handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
|
||||
driver = launch()
|
||||
handles = {}
|
||||
try:
|
||||
addon_id = driver.install_addon(str(BUILD), temporary=True)
|
||||
uuid = wait_uuid(driver, addon_id)
|
||||
print(f'installed {addon_id} as {uuid}', flush=True)
|
||||
|
||||
driver.get(BASE + '/p1')
|
||||
handles['/p1'] = driver.current_window_handle
|
||||
for i in range(2, 6):
|
||||
driver.switch_to.new_window('tab')
|
||||
driver.get(BASE + f'/p{i}')
|
||||
handles[f'/p{i}'] = driver.current_window_handle
|
||||
time.sleep(1.0)
|
||||
|
||||
tabs = state(driver)
|
||||
check('five fixture tabs are open', len(tabs) == 5, f'{len(tabs)} tabs')
|
||||
check('all five start loaded', all(not tab['discarded'] for tab in tabs))
|
||||
|
||||
shortcuts = {cmd['name']: cmd['shortcut'] for cmd in hook(driver, 'commands')}
|
||||
check('unload-current shortcut registered',
|
||||
shortcuts.get('unload-current') == 'Ctrl+Alt+P', str(shortcuts))
|
||||
check('unload-others shortcut registered',
|
||||
shortcuts.get('unload-others') == 'Ctrl+Alt+A', str(shortcuts))
|
||||
|
||||
manifest = json.loads((Path('/workspace/tabpark') / 'manifest.json').read_text())
|
||||
check('shipped manifest does not request the tabs permission',
|
||||
'tabs' not in manifest['permissions'], str(manifest['permissions']))
|
||||
check('shipped manifest does not request the menus permission',
|
||||
'menus' not in manifest['permissions'], str(manifest['permissions']))
|
||||
|
||||
synthetic = [
|
||||
{'id': 1, 'discarded': False, 'pinned': False, 'active': False,
|
||||
'status': 'complete', 'audible': True},
|
||||
{'id': 2, 'discarded': False, 'pinned': False, 'active': False,
|
||||
'status': 'complete', 'audible': False},
|
||||
]
|
||||
check('audible tabs are skipped when the setting is on',
|
||||
hook(driver, 'candidates', tabs=synthetic, skipAudible=True) == [2])
|
||||
check('audible tabs are included when the setting is off',
|
||||
hook(driver, 'candidates', tabs=synthetic, skipAudible=False) == [1, 2])
|
||||
|
||||
hook(driver, 'pin', tabId=by_url(tabs, '/p1')['id'])
|
||||
tabs = state(driver)
|
||||
check('p1 is pinned', by_url(tabs, '/p1')['pinned'])
|
||||
|
||||
# ---- unload others: keep the active tab, unload the rest
|
||||
hook(driver, 'activate', tabId=by_url(tabs, '/p2')['id'])
|
||||
time.sleep(0.4)
|
||||
# Call from the pinned tab: switching the WebDriver context activates
|
||||
# that tab, so p2 is re-activated afterwards.
|
||||
use(driver, handles, '/p1')
|
||||
hook(driver, 'activate', tabId=by_url(tabs, '/p2')['id'])
|
||||
time.sleep(0.3)
|
||||
count = hook(driver, 'unload-others', tabId=by_url(tabs, '/p2')['id'])
|
||||
time.sleep(0.6)
|
||||
tabs = state(driver)
|
||||
active = next(tab for tab in tabs if tab['active'])
|
||||
check('unload-others reports three tabs', count == 3, f'count={count}')
|
||||
check('unload-others keeps the tab count', len(tabs) == 5, f'{len(tabs)} tabs')
|
||||
check('unload-others leaves the pinned tab loaded', not by_url(tabs, '/p1')['discarded'])
|
||||
check('unload-others leaves the active tab loaded', not by_url(tabs, '/p2')['discarded'])
|
||||
check('unload-others discards p3, p4, p5',
|
||||
all(by_url(tabs, f'/p{i}')['discarded'] for i in (3, 4, 5)))
|
||||
check('unload-others keeps the active tab active',
|
||||
active['url'].endswith('/p2'), active['url'])
|
||||
|
||||
# ---- unload current: focus moves to the next loaded tab
|
||||
use(driver, handles, '/p1')
|
||||
tabs = state(driver)
|
||||
hook(driver, 'activate', tabId=by_url(tabs, '/p4')['id'])
|
||||
time.sleep(0.8)
|
||||
hook(driver, 'activate', tabId=by_url(tabs, '/p3')['id'])
|
||||
time.sleep(0.8)
|
||||
tabs = state(driver)
|
||||
check('p3 and p4 are loaded for the next test',
|
||||
not by_url(tabs, '/p3')['discarded'] and not by_url(tabs, '/p4')['discarded'])
|
||||
hook(driver, 'unload-current')
|
||||
time.sleep(0.6)
|
||||
tabs = state(driver)
|
||||
check('unload-current discards the tab it left', by_url(tabs, '/p3')['discarded'])
|
||||
active = next(tab for tab in tabs if tab['active'])
|
||||
check('unload-current lands on the next loaded tab',
|
||||
active['url'].endswith('/p4'), active['url'])
|
||||
check('unload-current keeps the tab count', len(tabs) == 5, f'{len(tabs)} tabs')
|
||||
|
||||
# ---- unload current when nothing else is loaded: open a new tab
|
||||
tabs = state(driver)
|
||||
hook(driver, 'unpin', tabId=by_url(tabs, '/p1')['id'])
|
||||
tabs = state(driver)
|
||||
hook(driver, 'activate', tabId=by_url(tabs, '/p4')['id'])
|
||||
time.sleep(0.6)
|
||||
use(driver, handles, '/p4')
|
||||
hook(driver, 'discard-all')
|
||||
time.sleep(0.5)
|
||||
tabs = state(driver)
|
||||
loaded = [tab for tab in tabs if not tab['discarded']]
|
||||
check('only p4 is loaded before the last-tab test', len(loaded) == 1,
|
||||
str([tab['url'] for tab in loaded]))
|
||||
before = len(tabs)
|
||||
before_handles = set(driver.window_handles)
|
||||
fire(driver, 'unload-current')
|
||||
time.sleep(1.5)
|
||||
new_handles = [h for h in driver.window_handles if h not in before_handles]
|
||||
check('unload-current opens a tab when all others are unloaded',
|
||||
len(new_handles) == 1, f'{before} -> {len(driver.window_handles)} handles')
|
||||
if new_handles:
|
||||
driver.switch_to.window(new_handles[0])
|
||||
driver.get(BASE + '/p6')
|
||||
handles['/p6'] = driver.current_window_handle
|
||||
tabs = state(driver)
|
||||
check('the old tab is discarded', by_url(tabs, '/p4')['discarded'])
|
||||
check('the new tab is active and loaded',
|
||||
len(tabs) == before + 1 and not next(t for t in tabs if t['active'])['discarded'],
|
||||
f'{before} -> {len(tabs)} tabs')
|
||||
|
||||
# ---- idle sweep, driven by the alarm rather than a direct call
|
||||
for path in ('/p3', '/p4', '/p5'):
|
||||
tabs = state(driver)
|
||||
hook(driver, 'activate', tabId=by_url(tabs, path)['id'])
|
||||
time.sleep(0.8)
|
||||
hook(driver, 'settings', values={'autoUnload': True, 'idleSeconds': 10, 'skipAudible': True})
|
||||
tabs = state(driver)
|
||||
hook(driver, 'activate', tabId=by_url(tabs, '/p3')['id'])
|
||||
time.sleep(0.5)
|
||||
use(driver, handles, '/p3')
|
||||
alarms = hook(driver, 'alarms')
|
||||
check('enabling auto-unload creates the sweep alarm',
|
||||
any(alarm['name'] == 'tu-idle-sweep' for alarm in alarms), str(alarms))
|
||||
|
||||
start = time.time()
|
||||
discarded_at = None
|
||||
while time.time() - start < 75:
|
||||
tabs = state(driver)
|
||||
if by_url(tabs, '/p4')['discarded'] and by_url(tabs, '/p5')['discarded']:
|
||||
discarded_at = time.time() - start
|
||||
break
|
||||
time.sleep(2)
|
||||
check('the idle sweep discards idle tabs', discarded_at is not None,
|
||||
f'still loaded after {time.time() - start:.0f}s')
|
||||
if discarded_at is not None:
|
||||
print(f' sweep latency: {discarded_at:.0f}s after enabling', flush=True)
|
||||
tabs = state(driver)
|
||||
check('the idle sweep leaves the active tab loaded', not by_url(tabs, '/p3')['discarded'])
|
||||
|
||||
# ---- a discarded tab really reloads when selected
|
||||
tabs = state(driver)
|
||||
check('p4 is discarded before the reload check', by_url(tabs, '/p4')['discarded'])
|
||||
before_hits = HITS['/p4']
|
||||
hook(driver, 'activate', tabId=by_url(tabs, '/p4')['id'])
|
||||
reloaded = False
|
||||
try:
|
||||
WebDriverWait(driver, 20).until(lambda d: HITS['/p4'] > before_hits)
|
||||
reloaded = True
|
||||
except Exception:
|
||||
pass
|
||||
check('selecting a discarded tab reloads the page', reloaded,
|
||||
f'{before_hits} -> {HITS["/p4"]}')
|
||||
p4 = wait_tab(driver, '/p4')
|
||||
check('the reloaded tab is no longer discarded', not p4['discarded'])
|
||||
|
||||
# ---- an explicit unload of a pinned tab is honoured
|
||||
tabs = state(driver)
|
||||
hook(driver, 'pin', tabId=by_url(tabs, '/p1')['id'])
|
||||
hook(driver, 'activate', tabId=by_url(tabs, '/p1')['id'])
|
||||
time.sleep(0.8)
|
||||
hook(driver, 'unload-current')
|
||||
time.sleep(0.6)
|
||||
tabs = state(driver)
|
||||
check('unload-current unloads a pinned tab when asked directly',
|
||||
by_url(tabs, '/p1')['discarded'])
|
||||
|
||||
# ---- extension pages render
|
||||
driver.switch_to.new_window('tab')
|
||||
driver.get(f'moz-extension://{uuid}/popup.html')
|
||||
WebDriverWait(driver, 10).until(
|
||||
lambda d: d.find_element(By.ID, 'counts').text != 'Reading tabs...')
|
||||
counts = driver.find_element(By.ID, 'counts').text
|
||||
check('popup renders the tab counts', 'loaded' in counts, counts)
|
||||
idle_value = driver.find_element(By.ID, 'idle').get_attribute('value')
|
||||
check('popup shows the saved threshold', idle_value == '10', idle_value)
|
||||
|
||||
# Pin this tab so the bulk unload does not discard the page under test
|
||||
# before it can show the result.
|
||||
driver.execute_async_script("""
|
||||
const done = arguments[0];
|
||||
browser.tabs.query({active: true, currentWindow: true})
|
||||
.then(([tab]) => browser.tabs.update(tab.id, {pinned: true}))
|
||||
.then(() => done(true), error => done(String(error)));
|
||||
""")
|
||||
driver.find_element(By.ID, 'unload-others').click()
|
||||
WebDriverWait(driver, 15).until(
|
||||
lambda d: d.find_element(By.ID, 'status').text != 'Unloading...')
|
||||
status = driver.find_element(By.ID, 'status').text
|
||||
check('popup button unloads through the background',
|
||||
status.startswith('Unloaded') or status == 'Nothing to unload', status)
|
||||
|
||||
driver.get(f'moz-extension://{uuid}/options.html')
|
||||
WebDriverWait(driver, 10).until(
|
||||
lambda d: d.find_element(By.ID, 'shortcut-current').text)
|
||||
current = driver.find_element(By.ID, 'shortcut-current').text
|
||||
check('options page shows the current shortcut',
|
||||
'Ctrl' in current and 'Alt' in current and 'P' in current, current)
|
||||
|
||||
# ---- a single-tab window is left alone
|
||||
main_handle = driver.current_window_handle
|
||||
driver.switch_to.new_window('window')
|
||||
driver.get(f'moz-extension://{uuid}/popup.html')
|
||||
WebDriverWait(driver, 10).until(
|
||||
lambda d: d.find_element(By.ID, 'counts').text != 'Reading tabs...')
|
||||
win_id = driver.execute_async_script(
|
||||
"const done = arguments[0]; browser.windows.getCurrent().then(w => done(w.id));")
|
||||
before = driver.execute_async_script(
|
||||
"const done = arguments[0]; browser.tabs.query({}).then(t => done(t.length));")
|
||||
result = driver.execute_async_script("""
|
||||
const winId = arguments[0];
|
||||
const done = arguments[arguments.length - 1];
|
||||
browser.runtime.sendMessage({type: 'tu:unload-current', windowId: winId})
|
||||
.then(done, error => done('ERR ' + error));
|
||||
""", win_id)
|
||||
time.sleep(0.5)
|
||||
after = driver.execute_async_script(
|
||||
"const done = arguments[0]; browser.tabs.query({}).then(t => done(t.length));")
|
||||
check('unload-current leaves a single-tab window alone',
|
||||
result is False and after == before, f'{result} {before}->{after}')
|
||||
driver.close()
|
||||
driver.switch_to.window(main_handle)
|
||||
finally:
|
||||
driver.quit()
|
||||
server.shutdown()
|
||||
|
||||
failed = [name for name, ok in CHECKS if not ok]
|
||||
print(f'\n{len(CHECKS) - len(failed)}/{len(CHECKS)} checks passed', flush=True)
|
||||
if failed:
|
||||
print('failed: ' + ', '.join(failed), flush=True)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercises the default build, which has no "tabs" permission.
|
||||
|
||||
The main driver adds "tabs" so it can identify tabs by URL. This one builds
|
||||
without it and identifies tabs by id, which is the shipped configuration.
|
||||
|
||||
Run with: DISPLAY=:99 python3 test/harness/no-tabs.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from http.server import ThreadingHTTPServer
|
||||
|
||||
from driver import (BASE, BUILD, CHECKS, PORT, Handler, build, check, hook,
|
||||
launch, state, wait_uuid)
|
||||
|
||||
|
||||
def active_id(driver):
|
||||
return next(tab['id'] for tab in state(driver) if tab['active'])
|
||||
|
||||
|
||||
def by_id(tabs, tab_id):
|
||||
return next(tab for tab in tabs if tab['id'] == tab_id)
|
||||
|
||||
|
||||
def main():
|
||||
os.environ['TU_NO_TABS'] = '1'
|
||||
build()
|
||||
|
||||
server = ThreadingHTTPServer(('127.0.0.1', PORT), Handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
|
||||
driver = launch()
|
||||
handles = {}
|
||||
ids = {}
|
||||
try:
|
||||
addon_id = driver.install_addon(str(BUILD), temporary=True)
|
||||
wait_uuid(driver, addon_id)
|
||||
print(f'installed {addon_id} without the tabs permission', flush=True)
|
||||
|
||||
driver.get(BASE + '/p1')
|
||||
handles['/p1'] = driver.current_window_handle
|
||||
ids['/p1'] = active_id(driver)
|
||||
for i in (2, 3):
|
||||
driver.switch_to.new_window('tab')
|
||||
driver.get(BASE + f'/p{i}')
|
||||
handles[f'/p{i}'] = driver.current_window_handle
|
||||
ids[f'/p{i}'] = active_id(driver)
|
||||
time.sleep(0.5)
|
||||
|
||||
tabs = state(driver)
|
||||
check('three tabs open without the tabs permission', len(tabs) == 3, str(len(tabs)))
|
||||
|
||||
hook(driver, 'pin', tabId=ids['/p1'])
|
||||
hook(driver, 'activate', tabId=ids['/p2'])
|
||||
time.sleep(0.3)
|
||||
# switch_to activates p1, so re-activate p2 before the bulk unload
|
||||
driver.switch_to.window(handles['/p1'])
|
||||
hook(driver, 'activate', tabId=ids['/p2'])
|
||||
time.sleep(0.3)
|
||||
|
||||
count = hook(driver, 'unload-others', tabId=ids['/p2'])
|
||||
time.sleep(0.5)
|
||||
tabs = state(driver)
|
||||
check('unload-others reports one tab', count == 1, f'count={count}')
|
||||
check('unload-others keeps the tab count', len(tabs) == 3, f'{len(tabs)} tabs')
|
||||
check('the pinned tab survives', not by_id(tabs, ids['/p1'])['discarded'])
|
||||
check('the kept tab survives', not by_id(tabs, ids['/p2'])['discarded'])
|
||||
check('p3 is discarded', by_id(tabs, ids['/p3'])['discarded'])
|
||||
|
||||
hook(driver, 'activate', tabId=ids['/p3'])
|
||||
time.sleep(0.8)
|
||||
hook(driver, 'unload-current')
|
||||
time.sleep(0.5)
|
||||
tabs = state(driver)
|
||||
check('unload-current discards the tab it left', by_id(tabs, ids['/p3'])['discarded'])
|
||||
active = next(tab for tab in tabs if tab['active'])
|
||||
check('unload-current lands on a loaded tab', not active['discarded'])
|
||||
|
||||
hook(driver, 'protect', tabId=ids['/p2'], value=True)
|
||||
hook(driver, 'unload-others', tabId=ids['/p1'])
|
||||
time.sleep(0.4)
|
||||
tabs = state(driver)
|
||||
check('unload-others skips the protected tab', not by_id(tabs, ids['/p2'])['discarded'])
|
||||
|
||||
hook(driver, 'protect', tabId=ids['/p2'], value=False)
|
||||
hook(driver, 'unload-others', tabId=ids['/p1'])
|
||||
time.sleep(0.4)
|
||||
tabs = state(driver)
|
||||
check('unload-others discards it once unprotected', by_id(tabs, ids['/p2'])['discarded'])
|
||||
|
||||
parked = hook(driver, 'park')
|
||||
check('the parking tab is created', bool(parked and parked.get('id')))
|
||||
hook(driver, 'activate', tabId=parked['id'])
|
||||
time.sleep(0.3)
|
||||
result = hook(driver, 'unload-current')
|
||||
check('unload-current refuses the parking tab', result is False, str(result))
|
||||
finally:
|
||||
driver.quit()
|
||||
server.shutdown()
|
||||
|
||||
failed = [name for name, ok in CHECKS if not ok]
|
||||
print(f'\n{len(CHECKS) - len(failed)}/{len(CHECKS)} checks passed', flush=True)
|
||||
if failed:
|
||||
print('failed: ' + ', '.join(failed), flush=True)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests the per-tab "Never park this tab" exception.
|
||||
|
||||
Run with: DISPLAY=:99 python3 test/harness/protect.py
|
||||
"""
|
||||
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from http.server import ThreadingHTTPServer
|
||||
|
||||
from driver import (BASE, BUILD, CHECKS, PORT, Handler, build, check, hook,
|
||||
launch, state, wait_uuid)
|
||||
|
||||
|
||||
def active_id(driver):
|
||||
return next(tab['id'] for tab in state(driver) if tab['active'])
|
||||
|
||||
|
||||
def by_id(tabs, tab_id):
|
||||
return next(tab for tab in tabs if tab['id'] == tab_id)
|
||||
|
||||
|
||||
def main():
|
||||
build()
|
||||
server = ThreadingHTTPServer(('127.0.0.1', PORT), Handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
|
||||
driver = launch()
|
||||
handles = {}
|
||||
ids = {}
|
||||
try:
|
||||
addon_id = driver.install_addon(str(BUILD), temporary=True)
|
||||
wait_uuid(driver, addon_id)
|
||||
|
||||
driver.get(BASE + '/p1')
|
||||
handles['/p1'] = driver.current_window_handle
|
||||
ids['/p1'] = active_id(driver)
|
||||
for i in (2, 3):
|
||||
driver.switch_to.new_window('tab')
|
||||
driver.get(BASE + f'/p{i}')
|
||||
handles[f'/p{i}'] = driver.current_window_handle
|
||||
ids[f'/p{i}'] = active_id(driver)
|
||||
time.sleep(0.5)
|
||||
|
||||
hook(driver, 'protect', tabId=ids['/p2'], value=True)
|
||||
check('p2 is marked protected', ids['/p2'] in hook(driver, 'protected'))
|
||||
|
||||
# Call from p2: it is the active tab and protected, so it survives and
|
||||
# the other two become candidates.
|
||||
driver.switch_to.window(handles['/p2'])
|
||||
hook(driver, 'unload-others', tabId=ids['/p2'])
|
||||
time.sleep(0.5)
|
||||
tabs = state(driver)
|
||||
check('unload-others skips the protected tab', not by_id(tabs, ids['/p2'])['discarded'])
|
||||
check('unload-others still discards the rest',
|
||||
by_id(tabs, ids['/p1'])['discarded'] and by_id(tabs, ids['/p3'])['discarded'])
|
||||
|
||||
hook(driver, 'settings', values={'autoUnload': True, 'idleSeconds': 10, 'skipAudible': True})
|
||||
driver.switch_to.window(handles['/p1'])
|
||||
time.sleep(11)
|
||||
hook(driver, 'sweep')
|
||||
time.sleep(0.5)
|
||||
tabs = state(driver)
|
||||
check('the idle sweep skips the protected tab', not by_id(tabs, ids['/p2'])['discarded'])
|
||||
|
||||
hook(driver, 'protect', tabId=ids['/p2'], value=False)
|
||||
check('p2 is no longer protected', ids['/p2'] not in hook(driver, 'protected'))
|
||||
hook(driver, 'sweep')
|
||||
time.sleep(0.5)
|
||||
tabs = state(driver)
|
||||
check('the sweep discards it once unprotected', by_id(tabs, ids['/p2'])['discarded'])
|
||||
finally:
|
||||
driver.quit()
|
||||
server.shutdown()
|
||||
|
||||
failed = [name for name, ok in CHECKS if not ok]
|
||||
print(f'\n{len(CHECKS) - len(failed)}/{len(CHECKS)} checks passed', flush=True)
|
||||
if failed:
|
||||
print('failed: ' + ', '.join(failed), flush=True)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,65 @@
|
||||
// Test-only background hook. Appended after common.js and background.js, so
|
||||
// the real helpers (tuUnloadOtherTabs, tuUnloadActiveTab, tuSweep, ...) are in
|
||||
// scope. It exists so the Selenium driver can trigger the extension from a
|
||||
// normal page and read back the browser's own tab state.
|
||||
|
||||
async function tuTestState() {
|
||||
const tabs = await browser.tabs.query({});
|
||||
return tabs.map(tab => ({
|
||||
id: tab.id,
|
||||
index: tab.index,
|
||||
windowId: tab.windowId,
|
||||
url: tab.url,
|
||||
title: tab.title,
|
||||
active: tab.active,
|
||||
pinned: tab.pinned,
|
||||
discarded: tab.discarded,
|
||||
audible: tab.audible,
|
||||
lastAccessed: tab.lastAccessed
|
||||
}));
|
||||
}
|
||||
|
||||
browser.runtime.onMessage.addListener((message, sender) => {
|
||||
if (!message || message.type !== 'tu-test') return;
|
||||
const windowId = sender.tab ? sender.tab.windowId : undefined;
|
||||
switch (message.cmd) {
|
||||
case 'state':
|
||||
return tuTestState();
|
||||
case 'unload-others':
|
||||
return tuUnloadOtherTabs(windowId, message.tabId);
|
||||
case 'park':
|
||||
return tuCreateParkingTab(windowId);
|
||||
case 'unload-current':
|
||||
return browser.tabs.query({ active: true, windowId })
|
||||
.then(([tab]) => tab ? tuUnloadActiveTab(tab) : false);
|
||||
case 'pin':
|
||||
return browser.tabs.update(message.tabId, { pinned: true });
|
||||
case 'unpin':
|
||||
return browser.tabs.update(message.tabId, { pinned: false });
|
||||
case 'activate':
|
||||
return browser.tabs.update(message.tabId, { active: true });
|
||||
case 'close':
|
||||
return browser.tabs.remove(message.tabId);
|
||||
case 'discard-all':
|
||||
return browser.tabs.query({ windowId })
|
||||
.then(tabs => tuDiscard(tuCandidates(tabs)));
|
||||
case 'settings':
|
||||
return browser.storage.local.set(message.values);
|
||||
case 'sweep':
|
||||
return tuSweep();
|
||||
case 'alarms':
|
||||
return browser.alarms.getAll();
|
||||
case 'parking':
|
||||
return tuParkingTabId();
|
||||
case 'protect':
|
||||
return tuSetProtected(message.tabId, message.value);
|
||||
case 'protected':
|
||||
return tuProtectedIds().then(ids => [...ids]);
|
||||
case 'candidates':
|
||||
return Promise.resolve(
|
||||
tuCandidates(message.tabs, { skipAudible: message.skipAudible }).map(tab => tab.id)
|
||||
);
|
||||
case 'commands':
|
||||
return browser.commands.getAll();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
// Test-only content script: forwards page messages to the background hook.
|
||||
// Injected by build-test-extension.sh into the fixture pages only.
|
||||
window.addEventListener('message', event => {
|
||||
if (event.source !== window || !event.data || event.data.tuTest !== true) return;
|
||||
const { id, cmd, tabId, values, value, tabs, skipAudible } = event.data;
|
||||
browser.runtime.sendMessage({ type: 'tu-test', cmd, tabId, values, value, tabs, skipAudible }).then(
|
||||
value => window.postMessage({ tuResult: id, value }, '*'),
|
||||
error => window.postMessage({ tuResult: id, error: String(error) }, '*')
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user