🎄 Sync 2026-11-14 17:29:54

This commit is contained in:
github-actions[bot] committed 2026-11-14 17:29:54 +08:00
1 parent 00efd4e7cf
commit 4e24fe7535
123 files changed
+26051

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
# Tests
| Suite | Command | Needs |
|---|---|---|
| Unit: formatting, i18n, devices, ARP, IPv6, brands (`carbon.test.js`) | `npm test` | Node 18+ |
| Unit: LuCI glue — poll pause, language list/switch, menu cache | `npm test` | Node 18+ |
| Unit: release-notes Markdown | `npm test` | Node 18+ |
| Unit: settings backend — logo upload validation (types, size, unsafe SVG) (`settings-backend.test.js`; `CARBON_TEST_SH=/bin/dash` for a strict shell) | `npm test` | Node 18+, `sh` |
| Unit: release body — one bilingual file per release, each language read through once, legacy notes (`release-notes.test.js`) | `npm test` | Node 18+, `sh` |
| Browser: preview pages, accessibility, minified build parity | `npm run test:browser` | `npm ci`, `npx playwright install chromium` |
| Installer control flow (stub apk/opkg/uci) | `npm test` | Node 18+, `sh`, `tar` |
| Installer with real apk (25.12) and opkg (24.10) | `python3 tests/installer-integration.py` | Docker, network |
| Theme templates rendered by OpenWrt's ucode | see below | Docker |
| Updater (APK and IPK) | see [online-update.md](../docs/online-update.md#maintainers) | Docker |
The browser suite also checks every bundled catalogue in the sidebar, the custom-logo hero, the settings page layout (`tests/fixtures/settings.html`), the language listbox, and the plugin adapters (DiskMan partition bar) against copied plugin markup. It serves the repository and a minified copy locally, runs `tests/navigation.html` at 390 × 844, loads the preview in Chinese/English × light/dark × desktop/phone (screenshots go to `.cache/screenshots/`), checks the dashboard data, the language switch, keyboard/touch behaviour of the rail and drawer, and compares computed styles of the minified release build with the sources.
Device regressions cover DHCP-disabled side routers with static or DHCP-client LAN, failed DHCP RPC calls, retained leases, gateway labels, and separate static WAN neighbours. These use the production dashboard with simulated provider responses. `CARBON_TEST_BROWSER` can point to an installed Chromium executable instead of Playwright's bundled browser. On a real router, also verify ARP reads after logging out and back in following an upgrade; an older session may lack the dashboard permissions. An IPv6-only device without a lease or local Wi-Fi association is not discoverable: this provider reads IPv4 ARP, while IPv6 addresses come from leases and host hints.
Render the templates with the real ucode runtime:
```bash
docker run --rm --mount "type=bind,source=$PWD,target=/source,readonly" openwrt/rootfs:x86_64-24.10.8 sh /source/tests/template-render.sh
```
# Navigation and menu cache regressions
Run `node --test tests/menu-cache.test.js` from the repository root. This executes the production LuCI menu module with both menu-cache layers and checks version invalidation, retained session data, unchanged-version reuse and retry after failure. CI runs this suite before packaging.
Serve the repository locally (for example, `python -m http.server 8080 --bind 127.0.0.1`) and open `/tests/navigation.html` at a **390 × 844** viewport. All ten checks must show `PASS`. The page loads the production theme script and stylesheet and tests route tabs, nested tabs, asynchronously inserted form tabs, hidden panes, resizing, manual scrolling and focus/vertical-scroll preservation. A desktop viewport fails the viewport check because desktop tabs wrap instead of overflowing.
Also verify in a disposable LuCI environment: open a multi-page app with an active tab beyond the initial visible area, then navigate between nested pages. When testing a real upgrade, keep the existing login session, install the native package and reload. LuCI uses the package database modification time to invalidate JavaScript module URLs; merely copying files into an already loaded development instance does not reproduce this part of installation.
For signed APK and native IPK updater integration tests, see [online-update.md](../docs/online-update.md#maintainers).
## Release notes
Run `node --test tests/markdown.test.js` to check the built-in Markdown renderer (`htdocs/luci-static/resources/carbon/markdown.js`): release-note structures, unsafe HTML/URLs, pathological input and unchanged-content polling. In LuCI, check for updates and confirm the notes render as headings, lists, links, tables and code, in both appearance modes and at 390px width. Long code/table content must scroll inside the notes; status polling must retain the reading position and text selection.
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
# Integration test with a real SDK-produced APK. Needs apk-tools 3 + openssl.
# Usage: sh tests/apk-signing.sh path/to/unsigned.apk
set -eu
[ "$#" -eq 1 ] && [ -s "$1" ] || { echo 'Pass an unsigned SDK APK' >&2; exit 1; }
repo=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM
umask 077
mkdir "$work/keys" "$work/empty" "$work/wrong"
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$work/private.pem"
openssl pkey -in "$work/private.pem" -pubout -out "$work/keys/public.pem"
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$work/other.pem"
openssl pkey -in "$work/other.pem" -pubout -out "$work/wrong/public.pem"
cp "$1" "$work/package.apk"
reject() {
if "$@"; then echo 'FAIL: expected rejection' >&2; exit 1; fi
}
verify() {
apk --keys-dir "$1" --repositories-file /dev/null --no-network verify "$2"
}
reject verify "$work/keys" "$work/package.apk"
before=$(sha256sum "$work/package.apk")
reject sh "$repo/scripts/sign-apk.sh" "$work/private.pem" "$work/wrong/public.pem" "$work/package.apk"
[ "$before" = "$(sha256sum "$work/package.apk")" ]
reject sh "$repo/scripts/sign-apk.sh" "$work/missing.pem" "$work/keys/public.pem" "$work/package.apk"
sh "$repo/scripts/sign-apk.sh" "$work/private.pem" "$work/keys/public.pem" "$work/package.apk"
verify "$work/keys" "$work/package.apk"
reject verify "$work/empty" "$work/package.apk"
reject verify "$work/wrong" "$work/package.apk"
# Truncating the compressed payload must also be rejected with the correct key.
size=$(wc -c < "$work/package.apk")
dd if="$work/package.apk" of="$work/damaged.apk" bs=1 count="$((size / 2))" 2>/dev/null
reject verify "$work/keys" "$work/damaged.apk"
echo 'PASS: unsigned, missing/mismatched key, untrusted key and damaged payload rejected; signed package verified'
@@ -0,0 +1,545 @@
'use strict';
/*
* Browser tests against the static preview (no router needed):
* npm install && npx playwright install chromium && npm run test:browser
*
* - tests/navigation.html regression page at phone width
* - preview pages in zh/en × light/dark × desktop/phone: no script errors,
* screenshots written to .cache/screenshots for review
* - dashboard data (devices, Wi‑Fi, IPv6, sensors, traffic picker)
* - keyboard / touch / drawer accessibility
* - the minified release build computes the same styles as the sources
*/
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { execFileSync } = require('node:child_process');
const { chromium } = require('playwright');
const ROOT = path.resolve(__dirname, '..', '..');
const SHOTS = path.join(ROOT, '.cache', 'screenshots');
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.json': 'application/json' };
let server, base, browser, minRoot;
function serve(roots) {
return http.createServer((req, res) => {
const url = new URL(req.url, 'http://x');
const [, mount, ...rest] = url.pathname.split('/');
const root = roots[mount];
const file = root && path.resolve(root, decodeURIComponent(rest.join('/')));
if (!file || !file.startsWith(root) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {
res.writeHead(404); res.end(); return;
}
res.writeHead(200, { 'content-type': (TYPES[path.extname(file)] || 'application/octet-stream') + '; charset=utf-8' });
fs.createReadStream(file).pipe(res);
});
}
test.before(async () => {
minRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'carbon-min-'));
for (const dir of ['htdocs', 'preview'])
fs.cpSync(path.join(ROOT, dir), path.join(minRoot, dir), { recursive: true });
execFileSync(process.execPath, [path.join(ROOT, 'scripts', 'minify.mjs'), minRoot], { stdio: 'pipe' });
server = serve({ src: ROOT, min: minRoot });
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = 'http://127.0.0.1:' + server.address().port;
browser = await chromium.launch({ executablePath: process.env.CARBON_TEST_BROWSER || undefined });
fs.mkdirSync(SHOTS, { recursive: true });
});
test.after(async () => {
if (browser) await browser.close();
if (server) server.close();
if (minRoot) fs.rmSync(minRoot, { recursive: true, force: true });
});
async function open(url, { width = 1280, height = 900, appearance = 'light', storage = {}, touch = false } = {}) {
const context = await browser.newContext({ viewport: { width, height }, hasTouch: touch, colorScheme: appearance === 'dark' ? 'dark' : 'light' });
await context.addInitScript((items) => {
for (const [k, v] of Object.entries(items)) localStorage.setItem(k, v);
}, Object.assign({ 'carbon.appearance': appearance }, storage));
const page = await context.newPage();
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto(base + url);
return { page, context, errors };
}
/* every async source has rendered: leases, Wi‑Fi stations, sensors, languages */
const dashboardReady = (page) => page.waitForFunction(() =>
document.querySelectorAll('.cb-card.span-8 .cb-list li').length >= 8 && document.querySelector('.cb-tag-wifi') &&
document.querySelectorAll('.cb-kv li').length >= 3 && document.querySelector('.cb-lang .cb-lb'));
test('side-router discovery works without DHCP and distinguishes neighbours, gateways and lease records', async () => {
const mock = fs.readFileSync(path.join(ROOT, 'preview', 'mock.js'), 'utf8');
for (const scenario of [
{ proto: 'static', leases: 'empty', lang: 'en' },
{ proto: 'dhcp', leases: 'empty', lang: 'en' },
{ proto: 'dhcp', leases: 'unavailable', lang: 'en' },
{ proto: 'static', leases: 'retained', lang: 'en' },
{ proto: 'dhcp', leases: 'empty', lang: 'zh-Hans' }
]) {
const context = await browser.newContext();
const page = await context.newPage();
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
try {
await page.route('**/preview/mock.js', (route) => route.fulfill({
contentType: 'text/javascript',
body: mock + '\n(' + ((s) => {
Object.assign(window.CarbonPreview.provider, {
interfaces: async () => [
{ interface: 'lan', up: true, proto: s.proto, device: 'br-lan', route: [{ target: '0.0.0.0', mask: 0, nexthop: '192.168.1.1' }] },
{ interface: 'wan', up: true, proto: 'static', device: 'eth1', route: [{ target: '0.0.0.0', mask: 0, nexthop: '10.0.0.1' }] }
],
leases: async () => {
if (s.leases === 'unavailable') throw new Error('DHCP RPC unavailable');
return { dhcp_leases: s.leases === 'retained' ? [
{ hostname: 'lease-only', ipaddr: '192.168.1.30', macaddr: '00:11:32:aa:bb:30', expires: 3600 }
] : [], dhcp6_leases: [] };
},
wireless: async () => ({}),
hostHints: async () => ({}),
neighbors: async () => [
'IP address HW type Flags HW address Mask Device',
'192.168.1.1 0x1 0x2 00:11:32:aa:bb:01 * br-lan',
'192.168.1.20 0x1 0x2 00:11:32:aa:bb:20 * br-lan',
'10.0.0.1 0x1 0x2 00:11:32:aa:bb:91 * eth1',
'10.0.0.20 0x1 0x2 00:11:32:aa:bb:92 * eth1'
].join('\n')
});
}).toString() + ')(' + JSON.stringify(scenario) + ');'
}));
await page.goto(base + '/src/preview/index.html?lang=' + scenario.lang);
const count = scenario.leases === 'retained' ? '3' : '2';
await page.waitForFunction((n) => document.querySelector('.cb-count')?.textContent === n, count);
const zh = scenario.lang === 'zh-Hans';
const clients = await page.textContent('.cb-clients');
assert.match(clients, zh ? /已发现设备/ : /Discovered devices/);
assert.match(clients, zh ? /网关/ : /Gateway/);
assert.match(clients, zh ? /邻居记录/ : /Neighbor entry/);
assert.doesNotMatch(clients, /Fixed IP|固定 IP|10\.0\.0\./);
if (scenario.leases === 'retained') assert.match(clients, /DHCP lease · 1h 0m left/);
assert.equal(await page.textContent('.cb-tile-val'), count);
assert.equal(await page.textContent('.cb-tile-sub'), zh ? '本机已知设备' : 'Known to this router');
assert.equal(await page.getAttribute('.cb-tile-head span[title]', 'title'), zh ? '可能包含离线设备。' : 'May include offline devices.');
assert.deepEqual(errors, []);
} finally { await context.close(); }
}
});
test('navigation regression page passes at phone width', async () => {
const { page, context } = await open('/src/tests/navigation.html', { width: 390, height: 844 });
await page.waitForFunction(() => /^(PASS|FAIL)/.test(document.title));
const results = await page.textContent('#results');
assert.match(await page.title(), /^PASS/, results);
await context.close();
});
for (const lang of ['zh-Hans', 'en']) {
for (const appearance of ['light', 'dark']) {
for (const [device, width, height] of [['desktop', 1440, 1000], ['phone', 390, 844]]) {
test(`preview ${lang} ${appearance} ${device} renders without errors`, async () => {
const { page, context, errors } = await open(`/src/preview/index.html?lang=${lang}`, { width, height, appearance });
await dashboardReady(page);
assert.equal(await page.getAttribute('html', 'data-darkmode'), appearance === 'dark' ? 'true' : 'false');
if (device === 'phone') {
const widths = await page.$$eval('.cb-clients .cb-list-main', (els) => els.map((e) => e.getBoundingClientRect().width));
assert.ok(widths.every((w) => w >= 90), 'lease labels and badges leave room for device names: ' + widths);
}
await page.screenshot({ path: path.join(SHOTS, `overview-${lang}-${appearance}-${device}.png`), fullPage: true });
assert.deepEqual(errors, []);
await context.close();
});
}
}
}
test('dashboard shows merged devices, Wi-Fi details, IPv6, sensors and a traffic picker', async () => {
const { page, context } = await open('/src/preview/index.html?lang=en');
await dashboardReady(page);
const info = await page.evaluate(() => ({
count: document.querySelector('.cb-count').textContent,
wifiTags: document.querySelectorAll('.cb-tag-wifi').length,
nas: [...document.querySelectorAll('.cb-list-title')].some((e) => e.textContent === 'DiskStation'),
gateway: document.body.textContent.includes('100.64.0.1') && [...document.querySelectorAll('.cb-list .cb-mono')].some((e) => e.textContent === '100.64.0.1'),
ipv6: !document.querySelector('.cb-ip6').closest('.cb-meta').classList.contains('hidden') && document.querySelector('.cb-ip6').textContent,
sensors: [...document.querySelectorAll('.cb-kv li')].map((li) => li.firstChild.textContent).filter((t) => t.startsWith('Temperature')),
tile: document.querySelector('.cb-tile .cb-tile-sub').textContent
}));
assert.equal(info.count, '17');
assert.ok(info.wifiTags >= 3, 'Wi-Fi tags among the first eight devices');
assert.ok(info.nas, 'static-IP device from ARP named by host hints');
assert.equal(info.gateway, false, 'upstream gateway is not a LAN device');
assert.equal(info.ipv6, '240e:3a1:4c2:8f0::1');
assert.deepEqual(info.sensors, ['Temperature · cpu', 'Temperature · mt7986 phy1']);
assert.match(info.tile, /^\d+ on Wi-Fi$/);
/* the traffic picker is a Carbon listbox (same control as the language switch), grouped like <optgroup> */
const picker = '.cb-card.cb-traffic .cb-lb.cb-traffic-select';
const listed = async () => {
await page.click(picker);
await page.waitForSelector('.cb-lb-list.show');
return page.evaluate(() => {
const ul = document.querySelector('.cb-lb-list');
return {
options: [...ul.querySelectorAll('[role="option"]')].map((li) => li.textContent),
groups: [...ul.querySelectorAll('.cb-lb-group')].map((li) => li.textContent)
};
});
};
let list = await listed();
assert.equal(list.options.length, 10);
assert.match(list.options[0], /^Auto/);
assert.deepEqual(list.groups, ['Interfaces', 'Network devices']);
assert.ok(list.options.includes('LAN (br-lan)') || list.options.some((o) => o.endsWith('(br-lan)')));
await page.click('.cb-lb-list li[role="option"]:has-text("(br-lan)")');
assert.equal(await page.evaluate(() => localStorage.getItem('carbon.traffic')), 'br-lan');
assert.match(await page.textContent(picker), /\(br-lan\)$/);
/* a physical port (e.g. an xPON uplink) is selectable and survives the next refresh */
list = await listed();
await page.click('.cb-lb-list li[role="option"] >> text="wan"');
assert.equal(await page.evaluate(() => localStorage.getItem('carbon.traffic')), 'wan');
assert.equal(await page.textContent(picker), 'wan');
/* keyboard: Escape closes and returns focus to the trigger */
await page.focus(picker);
await page.keyboard.press('ArrowDown');
await page.waitForSelector('.cb-lb-list.show');
await page.keyboard.press('Escape');
assert.equal(await page.$('.cb-lb-list'), null);
assert.equal(await page.evaluate(() => document.activeElement.classList.contains('cb-traffic-select')), true);
/* a scroll that leaves the trigger in place (scroll anchoring while cards refresh) keeps the list open;
scrolling the page closes it */
await page.click(picker);
await page.waitForSelector('.cb-lb-list.show');
await page.evaluate(() => document.dispatchEvent(new Event('scroll')));
assert.notEqual(await page.$('.cb-lb-list'), null, 'a scroll that does not move the trigger keeps the list open');
await page.evaluate(() => window.scrollBy(0, 120));
await page.waitForFunction(() => !document.querySelector('.cb-lb-list'));
await context.close();
});
/* every bundled catalogue loads, translates the shell and fits the sidebar */
const CATALOGUES = fs.readdirSync(path.join(ROOT, 'htdocs/luci-static/carbon/i18n')).map((f) => f.replace(/\.js$/, ''));
test('bundled catalogues translate the shell and fit the sidebar', async () => {
assert.ok(CATALOGUES.length >= 12, CATALOGUES.join(','));
for (const code of CATALOGUES) {
const lang = { 'zh-cn': 'zh-Hans', 'zh-tw': 'zh-Hant', 'pt-br': 'pt-BR' }[code] || code;
const { page, context, errors } = await open(`/src/preview/index.html?lang=${lang}`, { width: 1280 });
await dashboardReady(page);
const r = await page.evaluate(() => ({
loaded: Object.keys(window.Carbon.I18N || {}).length,
common: document.querySelector('.cb-nav-sect').textContent,
expected: window.Carbon.I18N.Common,
/* segmented labels must not overflow their buttons */
clipped: [...document.querySelectorAll('.cb-mode .cb-seg-btn, .cb-lang .cb-seg-btn')].filter((b) => b.scrollWidth > b.clientWidth + 1).map((b) => b.textContent),
navClipped: [...document.querySelectorAll('.cb-nav-label')].filter((l) => l.scrollWidth > l.clientWidth + 1 && getComputedStyle(l).textOverflow !== 'ellipsis').map((l) => l.textContent)
}));
assert.ok(r.loaded > 150, `${code}: catalogue loaded`);
assert.equal(r.common, r.expected, `${code}: sidebar section translated`);
assert.deepEqual(r.clipped, [], `${code}: segmented labels fit`);
assert.deepEqual(r.navClipped, [], `${code}: menu labels fit or ellipsize`);
assert.deepEqual(errors, [], code);
if (code === 'de' || code === 'ja')
await page.screenshot({ path: path.join(SHOTS, `overview-${code}-light-desktop.png`), fullPage: true });
await context.close();
}
});
test('a custom logo replaces the sidebar logo and the dashboard hero icon', async () => {
/* the theme header marks an uploaded logo with data-custom */
const ctx2 = await browser.newContext({ viewport: { width: 1280, height: 900 } });
await ctx2.route('**/preview/index.html*', async (route) => {
const res = await route.fetch();
const body = (await res.text()).replace('<img class="cb-brand-logo" src="../htdocs/luci-static/carbon/logo.svg" alt="">',
'<img class="cb-brand-logo" src="../htdocs/luci-static/carbon/logo.svg?v=1" alt="" data-custom>');
await route.fulfill({ response: res, body });
});
const p2 = await ctx2.newPage();
await p2.goto(base + '/src/preview/index.html?lang=en');
await dashboardReady(p2);
const hero = await p2.evaluate(() => {
const img = document.querySelector('.cb-hero-icon.custom img');
const brand = document.querySelector('.cb-brand-logo');
return { src: img && img.getAttribute('src'), fit: getComputedStyle(brand).objectFit, shadow: getComputedStyle(brand).boxShadow };
});
assert.equal(hero.src, '../htdocs/luci-static/carbon/logo.svg?v=1');
assert.equal(hero.fit, 'contain');
assert.equal(hero.shadow, 'none');
await ctx2.close();
});
/* plugin adapters (styles/18-plugins.css) against markup copied from luci-app-diskman */
const DISKMAN_FIXTURE = `<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="/src/htdocs/luci-static/carbon/carbon.css">
</head><body data-page="admin-system-diskman-disks"><div id="maincontent">
<table class="table cbi-section-table"><tbody><tr><td>/dev/sda</td><td>2.38 GB</td></tr>
<tr width="100%" style="white-space:nowrap;"><td style="margin:0px; padding:0px; border:0px; white-space:nowrap;" colspan="15">
<div title="sda1 fat16 128.00 MB" style="color:#525F7F; display:inline-block; text-align:center; background-color:#fbbd00; width:8%">sda1 fat16 128.00 MB </div><div title="sda2 squashfs 256.00 MB" style="color:#525F7F; display:inline-block; text-align:center; background-color:#e97c30; width:8.4%">sda2 squashfs 256.00 MB </div><div title="sda3 ext4 2.00 GB" style="color:#525F7F; display:inline-block; text-align:center; background-color:#a0e0a0; width:83.6%">sda3 ext4 2.00 GB </div>
</td></tr></tbody></table></div></body></html>`;
test('DiskMan partition bar stays inside its card on desktop and phone', async () => {
for (const width of [1280, 390]) {
const context = await browser.newContext({ viewport: { width, height: 800 } });
const page = await context.newPage();
await page.goto(base + '/src/preview/form.html');
await page.setContent(DISKMAN_FIXTURE, { waitUntil: 'load' });
const r = await page.evaluate(() => {
const td = document.querySelector('td[colspan]');
const segs = [...td.children].map((d) => d.getBoundingClientRect());
return {
pageScroll: document.documentElement.scrollWidth - document.documentElement.clientWidth,
inside: segs.every((b) => b.right <= td.getBoundingClientRect().right + 1),
clipped: [...td.children].every((d) => getComputedStyle(d).textOverflow === 'ellipsis')
};
});
assert.equal(r.pageScroll, 0, `${width}px: no sideways scroll`);
assert.ok(r.inside, `${width}px: segments fit the row`);
assert.ok(r.clipped, `${width}px: long labels ellipsize`);
await context.close();
}
});
test('settings page: buttons, links, fields and status text share one centre line', async () => {
for (const width of [1200, 390]) {
const { page, context, errors } = await open('/src/tests/fixtures/settings.html', { width });
await page.waitForSelector('body[data-ready]');
/* a status message next to the mirror field, as after saving */
await page.evaluate(() => { document.querySelector('.cb-update-field .cb-update-note').textContent = '已保存。'; });
const rows = await page.evaluate(() => [...document.querySelectorAll('.cb-update-actions, .cb-logo-actions, .cb-update-field')].map((row) => {
const kids = [...row.children].filter((c) => c.offsetParent && c.getBoundingClientRect().width);
/* compare items on the same line only (rows may wrap on phones) */
const lines = {};
kids.forEach((c) => {
const r = c.getBoundingClientRect(), mid = r.top + r.height / 2;
const key = Object.keys(lines).find((k) => Math.abs(k - mid) < 12) || mid;
(lines[key] = lines[key] || []).push(mid);
});
return { row: row.className, spread: Math.max(...Object.values(lines).map((m) => Math.max(...m) - Math.min(...m))) };
}));
assert.equal(rows.length, 3, JSON.stringify(rows));
const stray = await page.evaluate(() => [...document.querySelectorAll('#view *')].flatMap((el) => [...el.childNodes])
.filter((n) => n.nodeType === 3 && /^(null|undefined)$/.test(n.textContent.trim())).length);
assert.equal(stray, 0, 'no "null" / "undefined" text from absent children');
/* release notes from the built-in renderer: structure, safe links, local scrolling */
const notes = await page.evaluate(() => {
const box = document.querySelector('.cb-release-notes');
return {
tags: ['h2', 'h3', 'ul', 'li', 'strong', 'table', 'pre', 'code'].filter((t) => box.querySelector(t)),
links: [...box.querySelectorAll('a')].every((a) => a.target === '_blank' && a.rel === 'noopener noreferrer'),
fits: box.scrollWidth <= box.clientWidth + 1 || getComputedStyle(box).overflowX !== 'visible'
};
});
assert.deepEqual(notes.tags, ['h2', 'h3', 'ul', 'li', 'strong', 'table', 'pre', 'code']);
assert.ok(notes.links && notes.fits);
if (width === 1200) await page.screenshot({ path: path.join(SHOTS, 'settings-release-notes.png'), fullPage: true });
rows.forEach((r) => assert.ok(r.spread <= 0.5, `${width}px ${r.row}: ${r.spread}px off centre`));
assert.deepEqual(errors, []);
await context.close();
}
});
test('settings page: the mirror explanation lives in a ? toggletip', async () => {
for (const width of [1200, 390]) {
const { page, context, errors } = await open('/src/tests/fixtures/settings.html', { width, height: 900 });
await page.waitForSelector('body[data-ready]');
const section = page.locator('section.cbi-section', { has: page.locator('#carbon-mirror') });
assert.equal(await section.locator('.cbi-section-descr').count(), 0, 'no long paragraph on the page');
const btn = section.locator('h3 .cb-hint-btn'), bubble = section.locator('.cb-hint-bubble');
const shown = () => bubble.evaluate((b) => getComputedStyle(b).visibility === 'visible');
assert.equal(await btn.getAttribute('aria-describedby'), await bubble.getAttribute('id'));
assert.match(await bubble.textContent(), /HTTPS/);
assert.equal(await shown(), false, 'hidden by default');
await btn.hover();
await page.waitForTimeout(200);
assert.equal(await shown(), true, 'hover shows it');
await page.mouse.move(5, 5);
await page.waitForTimeout(200);
assert.equal(await shown(), false, 'leaving hides it');
await btn.click();
await page.mouse.move(5, 5);
await page.waitForTimeout(200);
assert.equal(await shown(), true, 'a click pins it');
assert.equal(await btn.getAttribute('aria-expanded'), 'true');
const box = await bubble.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= width, `${width}px: bubble inside the window`);
await page.mouse.click(5, 5);
await page.waitForTimeout(200);
assert.equal(await shown(), false, 'a click elsewhere closes it');
await btn.click();
await page.keyboard.press('Escape');
await page.waitForTimeout(200);
assert.equal(await btn.getAttribute('aria-expanded'), 'false', 'Esc closes it');
await page.keyboard.press('Tab');
await page.keyboard.press('Shift+Tab');
await page.waitForTimeout(200);
assert.equal(await shown(), true, 'keyboard focus shows it');
if (width === 1200) {
await page.mouse.move(5, 5);
await btn.hover();
await page.waitForTimeout(200);
await section.screenshot({ path: path.join(SHOTS, 'settings-mirror-hint.png') });
}
assert.deepEqual(errors, []);
await context.close();
}
});
test('language switch is a Carbon listbox with every bundled language', async () => {
const { page, context } = await open('/src/preview/index.html?lang=en');
await page.waitForSelector('.cb-lang .cb-lb');
assert.equal(await page.$('.cb-lang select'), null, 'no native select');
assert.equal(await page.textContent('.cb-lang .cb-lb'), 'English');
await page.click('.cb-lang .cb-lb');
const list = await page.evaluate(() => {
const ul = document.querySelector('.cb-lb-list');
const r = ul.getBoundingClientRect(), t = document.querySelector('.cb-lang .cb-lb').getBoundingClientRect();
return {
labels: [...ul.children].map((li) => li.textContent),
selected: [...ul.querySelectorAll('[aria-selected="true"]')].map((li) => li.textContent),
expanded: document.querySelector('.cb-lang .cb-lb').getAttribute('aria-expanded'),
focus: document.activeElement === ul,
opensUp: r.bottom <= t.top, inView: r.top >= 0 && r.bottom <= innerHeight,
bg: getComputedStyle(ul).backgroundColor
};
});
assert.deepEqual(list.labels, ['Auto', 'English', 'Deutsch', 'Español', 'Français', 'Italiano', '日本語', '한국어',
'Português do Brasil', 'Русский', 'Türkçe', 'Tiếng Việt', '简体中文', '繁體中文']);
assert.deepEqual(list.selected, ['English']);
assert.equal(list.expanded, 'true');
assert.ok(list.focus, 'the list takes focus');
assert.ok(list.opensUp && list.inView, 'opens above the footer trigger, inside the window');
await Promise.all([page.waitForURL(/lang=zh-Hant/), page.click('.cb-lb-list li:has-text("繁體中文")')]);
await page.waitForSelector('.cb-dash');
assert.equal(await page.textContent('.cb-card.cb-traffic h3'), await page.evaluate(() => window.Carbon.I18N['Live Traffic']));
assert.equal(await page.textContent('.cb-lang .cb-lb'), '繁體中文');
await context.close();
});
test('language listbox: keyboard, type-ahead and dismissal', async () => {
const { page, context } = await open('/src/preview/index.html?lang=en');
await page.waitForSelector('.cb-lang .cb-lb');
await page.focus('.cb-lang .cb-lb');
await page.keyboard.press('ArrowDown');
const activeText = () => page.evaluate(() => document.querySelector('.cb-lb-list li.active').textContent);
assert.equal(await activeText(), 'English', 'opens on the current language');
assert.equal(await page.evaluate(() => document.querySelector('.cb-lb-list').getAttribute('aria-activedescendant') === document.querySelector('.cb-lb-list li.active').id), true);
await page.keyboard.press('End');
assert.equal(await activeText(), '繁體中文');
await page.waitForTimeout(150);
assert.notEqual(await page.$('.cb-lb-list'), null, 'scrolling inside the list keeps it open');
await page.keyboard.press('Home');
assert.equal(await activeText(), 'Auto');
await page.keyboard.type('fr');
assert.equal(await activeText(), 'Français', 'type-ahead');
await page.keyboard.press('Escape');
assert.equal(await page.$('.cb-lb-list'), null, 'Escape closes');
assert.equal(await page.evaluate(() => document.activeElement.classList.contains('cb-lb')), true, 'focus returns to the trigger');
assert.equal(new URL(page.url()).searchParams.get('lang'), 'en', 'nothing chosen yet');
await page.click('.cb-lang .cb-lb');
await page.mouse.click(700, 400);
assert.equal(await page.$('.cb-lb-list'), null, 'an outside click closes');
await page.focus('.cb-lang .cb-lb');
await page.keyboard.press('Enter');
await page.keyboard.press('ArrowDown');
await Promise.all([page.waitForURL(/lang=de/), page.keyboard.press('Enter')]);
await context.close();
});
test('language listbox opens beside the collapsed rail and returns focus to it', async () => {
const { page, context } = await open('/src/preview/index.html?lang=en', { storage: { 'carbon.collapsed': '1' } });
await page.waitForSelector('.cb-lang-mini');
await page.click('.cb-lang-mini');
const r = await page.evaluate(() => {
const ul = document.querySelector('.cb-lb-list').getBoundingClientRect();
return { left: ul.left, rail: document.getElementById('cb-sidebar').getBoundingClientRect().right, bottom: ul.bottom, h: innerHeight };
});
assert.ok(r.left >= r.rail, 'beside the rail');
assert.ok(r.bottom <= r.h, 'inside the window');
await page.keyboard.press('Escape');
assert.equal(await page.evaluate(() => document.activeElement.classList.contains('cb-lang-mini')), true);
await page.click('.cb-lang-mini');
await page.click('.cb-lang-mini');
assert.equal(await page.$('.cb-lb-list'), null, 'the rail button toggles');
await context.close();
});
test('segmented controls follow the radio pattern', async () => {
const { page, context } = await open('/src/preview/index.html?lang=en');
await page.waitForSelector('#cb-appearance .cb-seg-btn');
await page.focus('#cb-appearance .cb-seg-btn[aria-checked="true"]');
await page.keyboard.press('ArrowRight'); // auto | light | dark: light → dark
assert.equal(await page.getAttribute('html', 'data-appearance'), 'dark');
assert.deepEqual(await page.$$eval('#cb-appearance .cb-seg-btn', (b) => b.map((x) => x.tabIndex)), [-1, -1, 0]);
assert.equal(await page.evaluate(() => document.activeElement.getAttribute('aria-checked')), 'true');
await context.close();
});
test('collapsed rail: keyboard opens and leaves the sub-menu, touch taps toggle it', async () => {
const storage = { 'carbon.collapsed': '1', 'carbon.mode': 'pro' };
let { page, context } = await open('/src/preview/index.html?lang=en', { storage });
await page.waitForSelector('.cb-nav-head');
await page.focus('.cb-nav-head');
await page.keyboard.press('Enter');
assert.equal(await page.evaluate(() => document.activeElement.closest('.cb-fly') !== null), true, 'focus moved into the flyout');
await page.keyboard.press('Escape');
assert.equal(await page.evaluate(() => document.activeElement.classList.contains('cb-nav-head')), true);
assert.equal(await page.$eval('.cb-fly', (f) => f.classList.contains('show')), false);
await context.close();
({ page, context } = await open('/src/preview/index.html?lang=en', { storage, touch: true }));
await page.waitForSelector('.cb-nav-head');
const before = page.url();
await page.tap('.cb-nav-head');
assert.equal(await page.$eval('.cb-fly', (f) => f.classList.contains('show')), true, 'tap shows the sub-menu');
assert.equal(page.url(), before, 'tap does not navigate');
await page.tap('.cb-hero');
assert.equal(await page.$eval('.cb-fly', (f) => f.classList.contains('show')), false, 'tapping elsewhere closes it');
await context.close();
});
test('phone drawer traps the page behind it and restores focus', async () => {
const { page, context } = await open('/src/preview/index.html?lang=en', { width: 390, height: 844 });
await page.waitForSelector('.cb-nav a');
assert.equal(await page.$eval('#cb-sidebar', (e) => e.hasAttribute('inert')), true);
await page.click('#cb-burger');
assert.equal(await page.getAttribute('#cb-burger', 'aria-expanded'), 'true');
assert.equal(await page.$eval('.cb-main', (e) => e.hasAttribute('inert')), true);
assert.equal(await page.evaluate(() => document.activeElement.closest('#cb-sidebar') !== null), true);
await page.keyboard.press('Escape');
assert.equal(await page.evaluate(() => document.activeElement.id), 'cb-burger');
assert.equal(await page.$eval('.cb-main', (e) => e.hasAttribute('inert')), false);
await context.close();
});
async function styleSnapshot(url, width) {
const { page, context, errors } = await open(url, { width, height: 900 });
if (url.includes('index.html')) await dashboardReady(page);
else await page.waitForSelector('.cb-login-card');
await page.waitForTimeout(300);
const props = ['display', 'position', 'color', 'background-color', 'background-image', 'font-size', 'font-weight', 'line-height',
'padding-top', 'padding-left', 'margin-top', 'margin-left', 'border-top-width', 'border-top-color', 'border-top-left-radius',
'gap', 'opacity', 'visibility', 'box-shadow', 'backdrop-filter', 'grid-template-columns', 'flex-direction', 'transform', 'text-decoration-line'];
const snapshot = await page.evaluate((list) => [...document.querySelectorAll('body *:not(svg *)')]
.filter((el) => !el.closest('.cb-chart, .cb-spark, .cb-ring'))
.map((el) => { const cs = getComputedStyle(el); return el.tagName + '.' + el.className + ' ' + list.map((p) => cs.getPropertyValue(p)).join('|'); }), props);
await context.close();
return { snapshot, errors };
}
for (const [name, url, width] of [['overview', 'preview/index.html?lang=en', 1440], ['overview phone', 'preview/index.html?lang=en', 390], ['login', 'preview/login.html?lang=en', 1280]]) {
test(`minified build computes the same styles: ${name}`, async () => {
const src = await styleSnapshot('/src/' + url, width);
const min = await styleSnapshot('/min/' + url, width);
assert.deepEqual(min.errors, []);
assert.equal(min.snapshot.length, src.snapshot.length);
const diff = src.snapshot.map((line, i) => line === min.snapshot[i] ? null : line + '\n ≠ ' + min.snapshot[i]).filter(Boolean);
assert.deepEqual(diff.slice(0, 5), []);
});
}
+285
View File
@@ -0,0 +1,285 @@
'use strict';
// Unit tests for the DOM-independent parts of carbon.js: formatting, i18n,
// version detection, device merging, ARP parsing and IPv6 uplink detection.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync('htdocs/luci-static/carbon/carbon.js', 'utf8');
const brands = fs.readFileSync('htdocs/luci-static/carbon/brands.js', 'utf8');
function load({ lang = 'en', src = '/luci-static/carbon/carbon.js?v=1.2.3-r4', catalogue = null, luciTr = null } = {}) {
const classes = new Set();
const element = () => ({
setAttribute() {}, getAttribute: () => null, classList: { toggle() {}, contains: () => false, add() {}, remove() {} },
addEventListener() {}, appendChild() {}, style: { setProperty() {} }
});
const window = {
localStorage: { getItem: () => null, setItem() {} },
matchMedia: () => ({ matches: false, addEventListener() {} }),
addEventListener() {},
atob: (b64) => Buffer.from(b64, 'base64').toString('latin1'),
Carbon: catalogue ? { I18N: catalogue } : undefined
};
if (luciTr) window._ = luciTr;
const document = {
currentScript: { src },
documentElement: {
getAttribute: (name) => name === 'lang' ? lang : null,
setAttribute() {},
classList: { toggle: (c, on) => (on ? classes.add(c) : classes.delete(c)), contains: (c) => classes.has(c) }
},
querySelector: () => null,
getElementById: () => null,
createElement: element,
addEventListener() {}
};
const context = { window, document, navigator: { language: lang }, Intl, Map, WeakSet, setTimeout, clearTimeout, console };
vm.runInNewContext(source, context);
return window.Carbon;
}
test('version comes from the ?v= parameter the theme header adds', () => {
assert.equal(load().version, '1.2.3-r4');
assert.equal(load({ src: '/luci-static/carbon/carbon.js' }).version, 'dev');
assert.equal(load({ src: '/x/carbon.js?v=<script>' }).version, 'dev');
});
test('bundled catalogue first, then LuCI catalogues, then English; placeholders fill in order', () => {
const C = load({ lang: 'zh-cn', catalogue: { 'Show all %d devices': '显示全部 %d 台设备' }, luciTr: (s) => s === 'Memory' ? '内存(LuCI)' : s });
assert.equal(C.t('Show all %d devices', 12), '显示全部 12 台设备');
assert.equal(C.t('Memory'), '内存(LuCI)');
assert.equal(C.t('Unknown string %s', 'x'), 'Unknown string x');
assert.equal(C.locale, 'zh-CN');
assert.equal(load({ lang: 'zh_Hant' }).locale, 'zh-TW');
assert.equal(load({ lang: 'en', luciTr: () => 'wrong' }).t('Memory'), 'Memory');
});
test('placeholders are filled once, literally', () => {
const C = load();
assert.equal(C.t('%s and %s', '$& %s', 'b'), '$& %s and b');
assert.equal(C.t('only %d', 1, 2), 'only 1');
assert.equal(C.t('%s %s', 'a'), 'a %s');
});
test('durations use translatable patterns', () => {
const en = load();
assert.equal(en.fmt.duration(3 * 86400 + 5 * 3600), '3d 5h');
assert.equal(en.fmt.duration(2 * 3600 + 7 * 60), '2h 7m');
assert.equal(en.fmt.duration(30), '<1 min');
const zh = load({ lang: 'zh-cn', catalogue: { '%dd %dh': '%d 天 %d 小时' } });
assert.equal(zh.fmt.duration(86400 + 3600), '1 天 1 小时');
});
test('byte formatting', () => {
const C = load();
assert.deepEqual(Array.from(C.fmt.bytes(1536, true)), ['1.5', 'KB/s']);
assert.equal(C.fmt.bytesStr(0), '0 B');
assert.equal(C.fmt.pair(149 * 1048576, 428 * 1048576), '149 / 428 MB');
assert.deepEqual(Array.from(C.fmt.bytes(null)), ['—', '']);
});
test('language matching maps LuCI codes to the installed catalogue', () => {
const C = load();
const options = [{ code: 'en' }, { code: 'zh_cn' }, { code: 'zh_tw' }, { code: 'pt_br' }];
assert.equal(C.matchLanguage(options, 'zh-Hans').code, 'zh_cn');
assert.equal(C.matchLanguage(options, 'zh_Hant').code, 'zh_tw');
assert.equal(C.matchLanguage(options, 'pt-BR').code, 'pt_br');
assert.equal(C.matchLanguage(options, 'de').code, 'en');
});
test('ARP parsing keeps complete LAN entries only', () => {
const C = load();
const arp = [
'IP address HW type Flags HW address Mask Device',
'192.168.1.5 0x1 0x2 00:11:32:aa:bb:cc * br-lan',
'192.168.1.9 0x1 0x0 00:00:00:00:00:00 * br-lan',
'192.168.1.7 0x1 0x6 AA:BB:CC:00:11:22 * br-lan',
'100.64.0.1 0x1 0x2 00:00:5e:00:01:01 * pppoe-wan'
].join('\n');
assert.deepEqual(Array.from(C.parseArp(arp, ['br-lan']), (n) => n.ip), ['192.168.1.5', '192.168.1.7']);
assert.equal(C.parseArp(arp, null).length, 3);
assert.equal(C.parseArp(arp, ['br-lan'])[1].mac, 'aa:bb:cc:00:11:22');
});
test('LAN devices exclude non-static uplinks but keep a dumb AP\'s static LAN', () => {
const C = load();
const ifs = [
{ interface: 'lan', up: true, proto: 'static', device: 'br-lan', l3_device: 'br-lan', route: [{ target: '0.0.0.0', mask: 0 }] },
{ interface: 'wan', up: true, proto: 'pppoe', device: 'eth1', l3_device: 'pppoe-wan', route: [{ target: '0.0.0.0', mask: 0 }] },
{ interface: 'guest', up: false, proto: 'static', device: 'br-guest' },
{ interface: 'loopback', up: true, proto: 'static', device: 'lo' }
];
assert.deepEqual(Array.from(C.lanDevices(ifs)), ['br-lan']);
assert.equal(C.lanDevices(null), null);
});
test('DHCP-disabled side routers discover ARP clients even when LAN obtains its address by DHCP', () => {
const C = load();
const arp = 'IP address HW type Flags HW address Mask Device\n192.168.1.20 0x1 0x2 00:11:32:aa:bb:cc * br-lan';
for (const proto of ['static', 'dhcp']) {
const ifs = [
{ interface: 'lan', up: true, proto, device: 'br-lan', route: [{ target: '0.0.0.0', mask: 0, nexthop: '192.168.1.1' }] },
{ interface: 'guest', up: true, proto: 'static', device: 'br-guest' }
];
for (const leases of [[], null]) {
const list = C.mergeDevices({ leases, arp: C.parseArp(arp, C.lanDevices(ifs), ifs) });
assert.equal(list.length, 1, proto + ': empty or unavailable local DHCP must not hide ARP clients');
assert.equal(list[0].ipaddr, '192.168.1.20');
assert.equal(list[0].lease, false);
}
}
});
test('separate static and dynamic uplinks, including aliases, are not client networks', () => {
const C = load();
for (const proto of ['static', 'dhcp', 'pppoe']) {
const ifs = [
{ interface: 'lan', up: true, proto: 'static', device: 'br-lan' },
{ interface: 'internet', up: true, proto, device: 'eth1', l3_device: 'eth1', route: [{ target: '0.0.0.0', mask: 0 }] },
{ interface: 'internet6', up: true, proto: 'dhcpv6', device: 'eth1', l3_device: 'eth1', route: [] },
{ interface: 'guest', up: true, proto: 'static', device: 'br-guest' }
];
assert.deepEqual(Array.from(C.lanDevices(ifs)), ['br-lan', 'br-guest'], proto);
}
assert.deepEqual(Array.from(C.lanDevices([
{ interface: 'lan', up: false, device: 'br-lan' },
{ interface: 'wan', up: true, proto: 'dhcp', device: 'eth1', route: [{ target: '0.0.0.0', mask: 0 }] }
])), [], 'a disconnected LAN must not cause WAN neighbours to appear');
});
test('a single custom client link with IPv6 aliases remains discoverable', () => {
const C = load();
assert.deepEqual(Array.from(C.lanDevices([
{ interface: 'home', up: true, proto: 'dhcp', device: 'br-home', l3_device: 'br-home', route: [{ target: '0.0.0.0', mask: 0 }] },
{ interface: 'home6', up: true, proto: 'dhcpv6', device: 'br-home', l3_device: 'br-home', route: [{ target: '::', mask: 0 }] },
{ interface: 'loopback', up: true, proto: 'static', device: 'lo' }
])), ['br-home']);
});
test('custom side-router links are not discarded merely because a guest network exists', () => {
const C = load();
for (const proto of ['static', 'dhcp']) {
assert.deepEqual(Array.from(C.lanDevices([
{ interface: 'home', up: true, proto, device: 'br-home', route: [{ target: '0.0.0.0', mask: 0 }] },
{ interface: 'guest', up: true, proto: 'static', device: 'br-guest' }
])), ['br-home', 'br-guest']);
}
});
test('gateways are identified on their own interface and retained as discovered devices', () => {
const C = load();
const ifs = [{ interface: 'lan', up: true, proto: 'static', device: 'br-lan', route: [
{ target: '0.0.0.0', mask: 0, nexthop: '192.168.1.1' },
{ target: '10.0.0.0', mask: 8, nexthop: '192.168.1.2' }
] }];
const arp = C.parseArp([
'IP address HW type Flags HW address Mask Device',
'192.168.1.1 0x1 0x2 00:11:32:aa:bb:01 * br-lan',
'192.168.1.1 0x1 0x2 00:11:32:aa:bb:02 * br-guest',
'192.168.1.2 0x1 0x2 00:11:32:aa:bb:03 * br-lan'
].join('\n'), null, ifs);
const list = C.mergeDevices({ arp, leases: [{ macaddr: '00:11:32:aa:bb:01', ipaddr: '192.168.1.1' }] });
assert.equal(list.length, 3);
assert.deepEqual(Array.from(list, (d) => d.gateway), [true, false, false]);
});
test('traffic picker lists interfaces plus physical ports such as an xPON uplink', () => {
const C = load();
/* xPON router: internet and IPTV are PPPoE sessions on VLANs of pon0 */
const ifs = [
{ interface: 'lan', up: true, device: 'br-lan', l3_device: 'br-lan' },
{ interface: 'wan', up: true, device: 'pon0.41', l3_device: 'pppoe-wan' },
{ interface: 'wan6', up: true, device: 'pppoe-wan', l3_device: 'pppoe-wan' },
{ interface: 'IPTV', up: true, device: 'pon0mac0.42', l3_device: 'pppoe-IPTV' },
{ interface: 'guest', up: false, device: 'br-guest' },
{ interface: 'loopback', up: true, device: 'lo', l3_device: 'lo' }
];
const dev = (up, extra) => Object.assign({ flags: { up: up } }, extra);
const netdevs = {
lo: dev(true, { flags: { up: true, loopback: true } }), 'br-lan': dev(true), 'pppoe-wan': dev(true), 'pppoe-IPTV': dev(true),
pon0: dev(true), 'pon0.41': dev(true), pon0mac0: dev(true), 'pon0mac0.42': dev(true), omci0: dev(true),
lan1: dev(true), lan10: dev(true), lan2: dev(false), eth0: { up: true }, sit0: dev(false), ifb0: dev(true), gre0: dev(true)
};
const plain = (x) => JSON.parse(JSON.stringify(x));
const src = plain(C.trafficSources(ifs, netdevs));
assert.deepEqual(src.ifaces.map((g) => [g.dev, g.alt, g.names.join('/')]),
[['br-lan', 'br-lan', 'LAN'], ['pppoe-wan', 'pon0.41', 'WAN/WAN6'], ['pppoe-IPTV', 'pon0mac0.42', 'IPTV']]);
assert.deepEqual(src.devices.map((d) => d.dev), ['eth0', 'lan1', 'lan10', 'omci0', 'pon0', 'pon0.41', 'pon0mac0', 'pon0mac0.42']);
/* no device list (old provider, failed call): interfaces only */
assert.deepEqual(plain(C.trafficSources(ifs, null).devices), []);
assert.deepEqual(plain(C.trafficSources(null, netdevs).ifaces), []);
});
test('devices merge leases, Wi-Fi stations, ARP and host hints by MAC', () => {
const C = load();
const list = C.mergeDevices({
leases: [
{ hostname: 'phone', ipaddr: '192.168.1.23', macaddr: 'A6:83:E7:2C:91:0F', expires: 3600 },
{ hostname: 'laptop', ipaddr: '192.168.1.3', macaddr: 'f0:ee:7a:91:aa:12', expires: false }
],
leases6: [{ hostname: 'laptop', ip6addrs: ['fd00::3/128'] }],
stations: [{ ifname: 'phy1-ap0', mac: 'a6:83:e7:2c:91:0f', signal: -48 }, { ifname: 'phy0-ap0', mac: '11:22:33:44:55:66', signal: 0 }],
arp: [{ ip: '192.168.1.5', mac: '00:11:32:aa:bb:cc' }, { ip: '192.168.1.3', mac: 'f0:ee:7a:91:aa:12' }],
hints: { '00:11:32:AA:BB:CC': { name: 'nas', ipaddrs: ['192.168.1.5'] } },
bands: { 'phy1-ap0': '5 GHz', 'phy0-ap0': '2.4 GHz' }
});
const by = Object.fromEntries(list.map((d) => [d.macaddr, d]));
assert.equal(list.length, 4);
assert.deepEqual(Array.from(list, (d) => d.ipaddr), ['192.168.1.3', '192.168.1.5', '192.168.1.23', '']);
assert.deepEqual({ ...by['a6:83:e7:2c:91:0f'].wifi }, { band: '5 GHz', signal: -48 });
assert.equal(by['f0:ee:7a:91:aa:12'].ip6addr, 'fd00::3');
assert.equal(by['f0:ee:7a:91:aa:12'].active, true);
assert.equal(by['00:11:32:aa:bb:cc'].hostname, 'nas');
assert.equal(by['00:11:32:aa:bb:cc'].lease, false);
assert.equal(by['11:22:33:44:55:66'].wifi.signal, null);
assert.deepEqual(Array.from(C.mergeDevices({ leases: [{ macaddr: 'bad' }] })), []);
});
test('IPv6-only leases are known devices without claiming an ARP or Wi-Fi observation', () => {
const C = load();
const list = C.mergeDevices({ leases6: [
{ hostname: 'ipv6-client', macaddr: '00:11:32:aa:bb:cc', ip6addrs: ['fd00::20/128'], expires: 3600 }
] });
assert.equal(list.length, 1);
assert.equal(list[0].ip6addr, 'fd00::20');
assert.equal(list[0].lease, true);
assert.equal(list[0].expires, 3600);
assert.equal(list[0].active, false);
});
test('IPv6 uplink address ignores link-local and needs a default route', () => {
const C = load();
assert.equal(C.wanIPv6([{ interface: 'lan', up: true, 'ipv6-address': [{ address: 'fd00::1', mask: 60 }], route: [] }]), null);
const v6 = C.wanIPv6([{ interface: 'wan6', up: true, route: [{ target: '::', mask: 0 }],
'ipv6-address': [{ address: 'fe80::1', mask: 64 }, { address: '240e:3a1::1', mask: 64 }] }]);
assert.deepEqual({ ...v6 }, { address: '240e:3a1::1', mask: 64, iface: 'wan6' });
const pd = C.wanIPv6([{ interface: 'wan6', up: true, route: [{ target: '::', mask: 0 }], 'ipv6-prefix': [{ address: '2001:db8:1::', mask: 56 }] }]);
assert.equal(pd.address, '2001:db8:1::');
});
test('brand identification by hostname, OUI and randomised MAC', () => {
const C = load();
vm.runInNewContext(brands, { window: { Carbon: C } });
assert.ok(C.BRAND_DATA);
assert.equal(C.identify('iPhone-15', '').brand.n, 'Apple');
assert.equal(C.identify('', 'f0:ee:7a:66:0b:3e').brand.n, 'Apple');
assert.equal(C.identify('', 'de:ad:be:ef:12:34').priv, true);
assert.equal(C.identify('', 'de:ad:be:ef:12:34').brand, null);
});
test('Docker uses the whale icon and its pages get their own icons', () => {
const C = load();
assert.equal(C.pageIcon('dockerman'), 'docker');
assert.equal(C.pageIcon('docker'), 'docker');
assert.deepEqual(['config', 'overview', 'containers', 'images', 'networks', 'volumes', 'events'].map((n) => C.pageIcon(n, 'docker')),
['sliders', 'gauge', 'box', 'layers', 'nodes', 'disk', 'pulse']);
/* the same names elsewhere keep the general rules */
assert.equal(C.pageIcon('overview', 'status'), 'gauge');
assert.equal(C.pageIcon('images', 'services'), 'dot');
assert.equal(C.pageIcon('podman-containers'), 'box');
assert.match(C.icon('docker'), /<rect /);
assert.notEqual(C.icon('nodes'), C.icon('nonexistent'));
});
+54
View File
@@ -0,0 +1,54 @@
<!doctype html>
<!-- Renders view/system/carbon-update.js with minimal LuCI stand-ins (E, rpc, poll …)
for the browser tests; served from /src/ by tests/browser/preview.test.js. -->
<html lang="zh-Hans">
<head>
<meta charset="utf-8">
<script src="../../htdocs/luci-static/carbon/i18n/zh-cn.js"></script>
<link rel="stylesheet" href="../../htdocs/luci-static/carbon/carbon.css">
<script src="../../htdocs/luci-static/carbon/carbon.js"></script>
</head>
<body>
<div class="cb-app"><main class="cb-main" style="margin-left:0"><div id="maincontent" class="cb-content"><div id="view"></div></div></main></div>
<script>
/* E() with LuCI's dom.append rules (luci.js): array items that are not
elements become text, so a null item shows up as "null" like on a router */
function E(tag, attrs, children) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs || {})) {
if (v == null || v === false) continue;
if (typeof v === 'function') el.addEventListener(k, v);
else el.setAttribute(k, v === true ? '' : v);
}
if (Array.isArray(children))
children.forEach((c) => el.appendChild(c instanceof Node ? c : document.createTextNode(`${c}`)));
else if (children instanceof Node) el.appendChild(children);
else if (children != null) el.innerHTML = `${children}`;
return el;
}
const L = { hasViewPermission: () => true, env: { cgi_base: '/cgi-bin' } };
const data = {
current: '1.1.3-r1', latest: '1.1.4-r1', can_upgrade: true, manager: 'opkg', notes: '', mirror: '',
logo: '../../htdocs/luci-static/carbon/logo.svg'
};
const stubs = {
view: { extend: (o) => o }, rpc: { declare: () => async () => data, getSessionID: () => 'test' },
poll: { add() {} }, ui: { menu: { flushCache() {} } }, request: {}
};
/* the real Markdown module, fed real bilingual release notes */
const text = (url) => fetch(url).then((r) => r.text());
Promise.all([
text('../../htdocs/luci-static/resources/view/system/carbon-update.js'),
text('../../htdocs/luci-static/resources/carbon/markdown.js'),
text('../../docs/releases/v1.1.4.md')
]).then(([src, md, notes]) => {
const markdown = new Function('baseclass', md)({ extend: (o) => o });
data.notes = notes + '\n| Firmware | File |\n|---|---|\n| OpenWrt 24.10 | `luci-theme-carbon_*_all.ipk` |\n\n```sh\nopkg install /tmp/luci-theme-carbon.ipk\n```\n';
const v = new Function('view', 'rpc', 'poll', 'ui', 'request', 'markdown', 'E', 'L', '_', src)(
stubs.view, stubs.rpc, stubs.poll, stubs.ui, stubs.request, markdown, E, L, (s) => s);
document.getElementById('view').appendChild(v.render(data));
document.body.dataset.ready = '1';
});
</script>
</body>
</html>
@@ -0,0 +1,153 @@
"""carbon-install.sh against the real apk (OpenWrt 25.12) and opkg (24.10) managers.
Usage: python3 tests/installer-integration.py (requires Docker and network access)
Fixture packages are disposable: the APK is signed with a throwaway test key, the
IPK only carries marker files. Dependencies come from the official feeds.
"""
import io
from pathlib import Path
import shutil
import subprocess
import tarfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
FIXTURES = ROOT / '.cache' / 'update-tests'
OUT = ROOT / '.cache' / 'installer-tests'
ALPINE = 'alpine:3.23@sha256:469c9ea410b9215eaee7976ba6c0639039b444be8e5d638f7abbada189971eb2'
APK_IMAGE = 'openwrt/rootfs:x86_64-25.12.6@sha256:14401c04218c2e0da0448f099710ada2460636a92395f353351cc616cf3f67af'
OPKG_IMAGE = 'openwrt/rootfs:x86_64-24.10.8@sha256:9972a4b4747cd136abd597475d7b88c51a49fd849d0d53f069a2f4bf446061b9'
DEPS = "CARBON_DEPS='curl ca-bundle flock'" # luci-base is not needed by the fixtures
PREPARE = ('mkdir -p /usr/share/ucode/luci/template /var/lock && touch /usr/share/ucode/luci/template/header.ut /etc/config/luci && '
'uci set luci.main=core && uci set luci.themes=internal && uci commit luci')
def docker(*args, check=True):
r = subprocess.run(['docker', *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=300)
out = r.stdout.decode()
if check and r.returncode:
raise AssertionError(f'docker {" ".join(args[:3])}… exited {r.returncode}:\n{out}')
return r.returncode, out
def archive(files):
# Like ipkg-build: parent directory entries first, then the files.
out = io.BytesIO()
with tarfile.open(fileobj=out, mode='w:gz') as tar:
dirs = sorted({'/'.join(name.split('/')[:i]) for name in files for i in range(1, name.count('/') + 1)})
for d in dirs:
entry = tarfile.TarInfo('./' + d)
entry.type, entry.mode = tarfile.DIRTYPE, 0o755
tar.addfile(entry)
for name, content in files.items():
content = content.encode() if isinstance(content, str) else content
entry = tarfile.TarInfo('./' + name)
entry.size, entry.mode = len(content), 0o644
tar.addfile(entry, io.BytesIO(content))
return out.getvalue()
def fixture_ipk(path):
control = archive({'control': 'Package: luci-theme-carbon\nVersion: 1.1.0-r1\nDepends: curl, ca-bundle, flock\n'
'Architecture: all\nDescription: installer test fixture\n'})
data = archive({'www/luci-static/carbon/marker': 'ipk\n', 'usr/share/carbon/version': '1.1.0-r1\n'})
path.write_bytes(archive({'debian-binary': '2.0\n', 'control.tar.gz': control, 'data.tar.gz': data}))
def build(name, *args):
subprocess.run(['sh', str(ROOT / 'scripts' / 'build-installer.sh'), str(OUT / name), *map(str, args)],
check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return f'/source/.cache/installer-tests/{name}/carbon-install.sh'
class Router:
def __init__(self, image):
self.id = docker('run', '-d', '--mount', f'type=bind,source={ROOT},target=/source,readonly', image, 'sleep', '900')[1].strip()
self.sh(PREPARE)
def sh(self, command, check=True):
return docker('exec', self.id, 'sh', '-c', command, check=check)
def close(self):
docker('rm', '-f', self.id, check=False)
class InstallerTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
FIXTURES.mkdir(parents=True, exist_ok=True)
docker('run', '--rm', '--mount', f'type=bind,source={ROOT},target=/source,readonly',
'--mount', f'type=bind,source={FIXTURES},target=/fixtures', ALPINE,
'sh', '-c', 'apk add --no-cache openssl >/dev/null && sh /source/tests/make-update-fixtures.sh')
shutil.rmtree(OUT, ignore_errors=True)
OUT.mkdir(parents=True)
fixture_ipk(OUT / 'fixture.ipk')
key = FIXTURES / 'keys' / 'carbon-apk.pem'
cls.good = build('good', '--ipk', OUT / 'fixture.ipk', '--apk', FIXTURES / 'luci-theme-carbon-1.1.0-r1.apk', '--key', key)
(OUT / 'bad').mkdir()
shutil.copy(FIXTURES / 'wrong.apk', OUT / 'bad' / 'luci-theme-carbon-1.1.0-r1.apk')
cls.wrong = build('wrong', '--ipk', OUT / 'fixture.ipk', '--apk', OUT / 'bad' / 'luci-theme-carbon-1.1.0-r1.apk', '--key', key)
cls.key = key.read_text()
def router(self, image):
r = Router(image)
self.addCleanup(r.close)
return r
def test_apk_native_install_trust_key_and_uninstall(self):
r = self.router(APK_IMAGE)
code, out = r.sh(f'{DEPS} sh {self.good}', check=False)
self.assertEqual(code, 0, out)
self.assertIn('installed with apk', out)
self.assertIn('luci-theme-carbon-1.1.0-r1', r.sh('apk list --installed luci-theme-carbon')[1])
self.assertEqual(r.sh('test -e /etc/apk/keys/carbon-apk.pem', check=False)[0], 1, 'system trust unchanged')
self.assertEqual(r.sh('uci get luci.main.mediaurlbase')[1].strip(), '/luci-static/carbon')
# signature checks stay enabled for everything else
self.assertEqual(r.sh('apk verify /source/.cache/update-tests/luci-theme-carbon-1.1.0-r1.apk', check=False)[0] != 0, True)
code, out = r.sh(f'{DEPS} sh {self.good} --trust-key', check=False)
self.assertEqual(code, 0, out)
self.assertEqual(r.sh('cat /etc/apk/keys/carbon-apk.pem')[1], self.key)
code, out = r.sh(f'sh {self.good} uninstall', check=False)
self.assertEqual(code, 0, out)
self.assertEqual(r.sh('apk list --installed luci-theme-carbon')[1].strip(), '')
def test_apk_wrong_signature_installs_nothing(self):
r = self.router(APK_IMAGE)
code, out = r.sh(f'{DEPS} sh {self.wrong}', check=False)
self.assertNotEqual(code, 0, out)
self.assertIn('signature verification failed', out)
self.assertEqual(r.sh('apk list --installed luci-theme-carbon')[1].strip(), '')
self.assertEqual(r.sh('test -e /www/luci-static/carbon', check=False)[0], 1)
def test_apk_script_only_install_is_migrated(self):
r = self.router(APK_IMAGE)
self.assertEqual(r.sh(f'sh {self.good} --files', check=False)[0], 0)
self.assertEqual(r.sh('cat /www/luci-static/carbon/marker')[1], 'ipk\n')
self.assertEqual(r.sh('apk list --installed luci-theme-carbon')[1].strip(), '')
code, out = r.sh(f'{DEPS} sh {self.good}', check=False)
self.assertEqual(code, 0, out)
self.assertIn('luci-theme-carbon-1.1.0-r1', r.sh('apk list --installed luci-theme-carbon')[1])
def test_opkg_native_install_and_uninstall(self):
r = self.router(OPKG_IMAGE)
self.assertEqual(r.sh(f'sh {self.good} --files', check=False)[0], 0)
code, out = r.sh(f'{DEPS} sh {self.good}', check=False)
self.assertEqual(code, 0, out)
self.assertIn('installed with opkg', out)
status = r.sh('opkg status luci-theme-carbon')[1]
self.assertIn('Version: 1.1.0-r1', status)
self.assertRegex(status, r'Status: .* installed')
owned = r.sh('opkg files luci-theme-carbon')[1]
self.assertIn('/www/luci-static/carbon/marker', owned)
self.assertEqual(r.sh('cat /www/luci-static/carbon/marker', check=False)[1], 'ipk\n', owned)
code, out = r.sh(f'sh {self.good} uninstall', check=False)
self.assertEqual(code, 0, out)
self.assertNotIn('Version:', r.sh('opkg status luci-theme-carbon', check=False)[1])
self.assertEqual(r.sh('test -e /www/luci-static/carbon/marker', check=False)[0], 1)
if __name__ == '__main__':
unittest.main(verbosity=2)
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
echo "apk $*" >> "$STATE/log"
args=''; skip=0
for a in "$@"; do
if [ "$skip" = 1 ]; then skip=0; continue; fi
case "$a" in --keys-dir|--repositories-file) skip=1 ;; -*) ;; *) args="$args $a" ;; esac
done
set -- $args
cmd=$1; shift
case "$cmd" in
verify) exit "${APK_VERIFY_RC:-0}" ;;
list) [ -f "$STATE/pkgs/$1" ] && echo "$1-$(cat "$STATE/pkgs/$1") noarch {$1} (MIT) [installed]"; exit 0 ;;
version) if [ "$1" = "$2" ]; then echo '='; elif [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | head -n 1)" = "$1" ]; then echo '<'; else echo '>'; fi ;;
update) exit 0 ;;
add)
for a in "$@"; do
case "$a" in
*.apk) [ "${APK_ADD_RC:-0}" = 0 ] || exit 1; cat "$(dirname "$a")/apk.version" > "$STATE/pkgs/luci-theme-carbon" ;;
*) [ -z "$DEPS_FAIL" ] || exit 1; echo 1.0-r1 > "$STATE/pkgs/$a" ;;
esac
done ;;
del) rm -f "$STATE/pkgs/$1" ;;
esac
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
echo "opkg $*" >> "$STATE/log"
cmd=$1; shift
case "$cmd" in
status) [ -f "$STATE/pkgs/$1" ] && printf 'Package: %s\nVersion: %s\nStatus: install user installed\n' "$1" "$(cat "$STATE/pkgs/$1")"; exit 0 ;;
compare-versions)
if [ "$1" = "$3" ]; then r='='; elif [ "$(printf '%s\n%s\n' "$1" "$3" | sort -V | head -n 1)" = "$1" ]; then r='<'; else r='>'; fi
case "$2" in '<<') [ "$r" = '<' ] ;; '=') [ "$r" = '=' ] ;; *) exit 2 ;; esac ;;
update) exit 0 ;;
install)
for a in "$@"; do
case "$a" in
--*) ;;
*.ipk) cat "$(dirname "$a")/opkg.version" > "$STATE/pkgs/luci-theme-carbon" ;;
*) [ -z "$DEPS_FAIL" ] || exit 1; echo 1.0-1 > "$STATE/pkgs/$a" ;;
esac
done ;;
remove) rm -f "$STATE/pkgs/$1" ;;
esac
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
echo "uci $*" >> "$STATE/log"
[ "$1" = -q ] && shift
case "$1" in
get) [ "$2" = luci.main.mediaurlbase ] && cat "$STATE/theme" 2>/dev/null ;;
set) case "$2" in luci.main.mediaurlbase=*) echo "${2#*=}" > "$STATE/theme" ;; esac ;;
esac
exit 0
+179
View File
@@ -0,0 +1,179 @@
'use strict';
// carbon-install.sh control flow against a fake root with stub apk/opkg/uci.
// Real package managers are exercised in tests/installer-integration.py (Docker).
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync, spawnSync } = require('node:child_process');
const REPO = path.resolve(__dirname, '..');
const VERSION = fs.readFileSync(path.join(REPO, 'root/usr/share/carbon/version'), 'utf8').trim();
let tmp, installer, plainInstaller;
const STUBS = path.join(__dirname, 'installer-stubs'); // stub apk / opkg / uci
test.before(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'carbon-installer-'));
const fakeApk = path.join(tmp, 'luci-theme-carbon-9.9.9-r1.apk');
fs.writeFileSync(fakeApk, 'signed apk stand-in');
execFileSync('sh', [path.join(REPO, 'scripts/build-installer.sh'), path.join(tmp, 'full'), '--apk', fakeApk], { stdio: 'pipe' });
execFileSync('sh', [path.join(REPO, 'scripts/build-installer.sh'), path.join(tmp, 'plain')], { stdio: 'pipe' });
installer = path.join(tmp, 'full', 'carbon-install.sh');
plainInstaller = path.join(tmp, 'plain', 'carbon-install.sh');
for (const [name, tools] of Object.entries({ apk: ['apk', 'uci'], opkg: ['opkg', 'uci'], none: ['uci'] })) {
const dir = path.join(tmp, 'bin-' + name);
fs.mkdirSync(dir);
for (const tool of tools) fs.copyFileSync(path.join(STUBS, tool), path.join(dir, tool));
for (const tool of tools) fs.chmodSync(path.join(dir, tool), 0o755);
}
});
test.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
let n = 0;
function router(manager, { installed = {} } = {}) {
const dir = path.join(tmp, 'router' + (++n));
const root = path.join(dir, 'root'), state = path.join(dir, 'state');
fs.mkdirSync(path.join(root, 'usr/share/ucode/luci/template'), { recursive: true });
fs.writeFileSync(path.join(root, 'usr/share/ucode/luci/template/header.ut'), '');
if (manager === 'apk') { fs.mkdirSync(path.join(root, 'etc/apk'), { recursive: true }); fs.writeFileSync(path.join(root, 'etc/apk/world'), ''); }
fs.mkdirSync(path.join(state, 'pkgs'), { recursive: true });
fs.writeFileSync(path.join(state, 'log'), '');
for (const [name, version] of Object.entries(installed)) fs.writeFileSync(path.join(state, 'pkgs', name), version);
const run = (args = [], env = {}, file = installer) => {
const r = spawnSync('sh', [file, ...args], {
encoding: 'utf8',
env: { PATH: path.join(tmp, 'bin-' + manager) + ':/usr/bin:/bin', CARBON_ROOT: root, STATE: state, ...env }
});
return { code: r.status, out: r.stdout + r.stderr };
};
return {
root, run,
log: () => fs.readFileSync(path.join(state, 'log'), 'utf8'),
version: (name = 'luci-theme-carbon') => { try { return fs.readFileSync(path.join(state, 'pkgs', name), 'utf8').trim(); } catch (e) { return null; } },
theme: () => { try { return fs.readFileSync(path.join(state, 'theme'), 'utf8').trim(); } catch (e) { return null; } },
exists: (p) => fs.existsSync(path.join(root, p))
};
}
test('apk: installs the embedded signed package through apk with a private key directory', () => {
const r = router('apk');
const { code, out } = r.run();
assert.equal(code, 0, out);
assert.equal(r.version(), '9.9.9-r1');
assert.match(r.log(), /apk --keys-dir \S+ --repositories-file \/dev\/null --no-network verify \S+luci-theme-carbon\.apk/);
assert.match(r.log(), /apk add luci-base curl ca-bundle flock/, 'missing dependencies come from the feeds');
assert.match(r.log(), /apk --keys-dir \S+ --repositories-file \/dev\/null --no-network add \S+luci-theme-carbon\.apk/);
assert.equal(r.exists('etc/apk/keys/carbon-apk.pem'), false, 'system trust unchanged');
assert.equal(r.exists('www/luci-static/carbon'), false, 'no loose files copied');
assert.equal(r.theme(), '/luci-static/carbon');
assert.match(out, /installed with apk/);
});
test('apk: --trust-key also adds the embedded key to /etc/apk/keys', () => {
const r = router('apk');
assert.equal(r.run(['--trust-key']).code, 0);
assert.equal(fs.readFileSync(path.join(r.root, 'etc/apk/keys/carbon-apk.pem'), 'utf8'),
fs.readFileSync(path.join(REPO, 'keys/carbon-apk.pem'), 'utf8'));
});
test('apk: a bad signature aborts without installing or copying anything', () => {
const r = router('apk');
const { code, out } = r.run([], { APK_VERIFY_RC: '1' });
assert.notEqual(code, 0);
assert.match(out, /signature verification failed/);
assert.equal(r.version(), null);
assert.equal(r.exists('www/luci-static/carbon'), false);
assert.equal(r.theme(), null);
});
test('offline without dependencies: falls back to copying files, with a warning', () => {
const r = router('apk');
const { code, out } = r.run([], { DEPS_FAIL: '1' });
assert.equal(code, 0, out);
assert.equal(r.version(), null);
assert.ok(r.exists('www/luci-static/carbon/carbon.css'));
assert.ok(r.exists('usr/libexec/rpcd/luci.carbon_update'));
assert.match(out, /online updates stay\s+WARNING: disabled|online updates stay/);
});
test('script-only install migrates to a registered package', () => {
const r = router('opkg');
assert.equal(r.run(['--files']).code, 0);
assert.ok(r.exists('www/luci-static/carbon/carbon.css'));
assert.equal(r.version(), null);
const { code, out } = r.run();
assert.equal(code, 0, out);
assert.equal(r.version(), VERSION);
// unowned files were removed so the package owns them (the stub installs no files)
assert.equal(r.exists('www/luci-static/carbon'), false);
});
test('opkg: installs the embedded ipk; same version reinstalls; newer installed is kept', () => {
let r = router('opkg', { installed: { 'luci-base': '1', curl: '1', 'ca-bundle': '1', flock: '1' } });
assert.equal(r.run().code, 0);
assert.equal(r.version(), VERSION);
assert.doesNotMatch(r.log(), /opkg update/, 'no feed access when dependencies are present');
assert.equal(r.run().code, 0);
assert.match(r.log(), /opkg install --force-reinstall \S+\.ipk/);
r = router('opkg', { installed: { 'luci-theme-carbon': '9.0.0-r1' } });
const { code, out } = r.run();
assert.equal(code, 0);
assert.match(out, /newer than this installer/);
assert.equal(r.version(), '9.0.0-r1');
});
test('a failed upgrade of a registered package stops instead of copying files', () => {
const r = router('apk', { installed: { 'luci-theme-carbon': '1.0.0-r1', 'luci-base': '1', curl: '1', 'ca-bundle': '1', flock: '1' } });
const { code, out } = r.run([], { APK_ADD_RC: '1' });
assert.notEqual(code, 0);
assert.match(out, /remains installed/);
assert.equal(r.version(), '1.0.0-r1');
assert.equal(r.exists('www/luci-static/carbon'), false);
});
test('apk system with an installer that has no .apk falls back to files', () => {
const r = router('apk');
const { code, out } = r.run([], {}, plainInstaller);
assert.equal(code, 0, out);
assert.match(out, /no \.apk package/);
assert.ok(r.exists('www/luci-static/carbon/carbon.css'));
});
test('no package manager: copies files', () => {
const r = router('none');
assert.equal(r.run().code, 0);
assert.ok(r.exists('www/luci-static/carbon/carbon.css'));
});
test('--files refuses to overwrite a registered package', () => {
const r = router('opkg', { installed: { 'luci-theme-carbon': '1.0.0-r1' } });
const { code, out } = r.run(['--files']);
assert.notEqual(code, 0);
assert.match(out, /upgrade it without --files/);
});
test('uninstall removes the package, leftover files and settings, and restores a theme', () => {
const r = router('apk');
assert.equal(r.run().code, 0);
fs.mkdirSync(path.join(r.root, 'www/luci-static/bootstrap'), { recursive: true });
fs.mkdirSync(path.join(r.root, 'etc/config'), { recursive: true });
fs.writeFileSync(path.join(r.root, 'etc/config/carbon'), '');
const { code, out } = r.run(['uninstall']);
assert.equal(code, 0, out);
assert.match(r.log(), /apk del luci-theme-carbon/);
assert.equal(r.version(), null);
assert.equal(r.exists('etc/config/carbon'), false);
assert.equal(r.theme(), '/luci-static/bootstrap');
});
test('unknown arguments print usage', () => {
const r = router('none');
const { code, out } = r.run(['--bogus']);
assert.equal(code, 1);
assert.match(out, /Usage:/);
});
@@ -0,0 +1,20 @@
#!/bin/sh
# Run in Alpine with apk-tools 3 and OpenSSL; all keys are disposable test keys.
set -eu
cd /fixtures
mkdir -p keys wrong data/usr/share
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out private.pem
openssl pkey -in private.pem -pubout -out keys/carbon-apk.pem
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out wrong/private.pem
printf '#!/bin/sh\necho installed >> /tmp/carbon-install-count\n' > post-install
for version in 1.0.0-r1 1.1.0-r1 1.2.0-r1; do
printf '%s\n' "$version" > data/usr/share/carbon-test-marker
apk mkpkg --info "name:luci-theme-carbon" --info "version:$version" --info 'arch:noarch' \
--files data --script post-install:post-install --script post-upgrade:post-install \
--output "luci-theme-carbon-$version.apk"
done
cp luci-theme-carbon-1.1.0-r1.apk unsigned.apk
cp unsigned.apk wrong.apk
apk adbsign --allow-untrusted --sign-key wrong/private.pem wrong.apk
sh /source/scripts/sign-apk.sh private.pem keys/carbon-apk.pem luci-theme-carbon-*.apk
rm private.pem wrong/private.pem
+105
View File
@@ -0,0 +1,105 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const baseclass = { extend: value => value };
const markdown = new Function('baseclass', fs.readFileSync('htdocs/luci-static/resources/carbon/markdown.js', 'utf8'))(baseclass);
test('formats real release notes including headings, lists, tables and fenced commands', () => {
const notes = fs.readFileSync('docs/releases/v1.1.2.md', 'utf8') + '\n\n| Firmware | File |\n|---|---|\n| APK | `carbon.apk` |\n\n```sh\nopkg install carbon.ipk\n```';
const html = markdown.render(notes);
for (const pattern of [/<h3>v1\.1\.2<\/h3>/, /<ul>/, /<li>/, /<strong>升级:<\/strong>/, /<table>/, /<code>carbon\.apk<\/code>/, /<pre><code class="language-sh">opkg install carbon\.ipk/])
assert.match(html, pattern);
});
test('supports nested lists, quotations, emphasis, references and automatic links', () => {
const html = markdown.render('1. **First**\n - *Nested* and ~~old~~\n\n> Quote\n\n[Manual][docs]\n\n[docs]: https://example.com/guide\n\nhttps://example.com/update');
for (const pattern of [/<ol>/, /<ul>/, /<em>Nested<\/em>/, /<s>old<\/s>/, /<blockquote>/, /href="https:\/\/example.com\/guide"/, /href="https:\/\/example.com\/update"/])
assert.match(html, pattern);
});
test('raw HTML, SVG, event handlers and code examples remain inert text', () => {
const html = markdown.render('<script>alert(1)</script>\n\n<img src=x onerror=alert(1)>\n\n<svg onload=alert(1)></svg>\n\n<iframe srcdoc="<script>alert(1)</script>"></iframe>\n\n```html\n<img src=x onerror=alert(1)>\n```');
assert.doesNotMatch(html, /<(?:script|img|svg|iframe)\b/i);
assert.match(html, /&lt;script&gt;/);
assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/);
});
test('rejects script, data, file and encoded unsafe URLs in links and images', () => {
for (const url of ['javascript:alert(1)', 'JaVaScRiPt:alert(1)', 'javascript&#58;alert(1)', 'java&#10;script:alert(1)', 'data:text/html;base64,PHNjcmlwdD4=', 'vbscript:msgbox(1)', 'file:///etc/passwd', 'data:image/svg+xml;base64,PHN2Zz4=']) {
const html = markdown.render(`[unsafe](${url})\n\n![unsafe](${url})`);
assert.doesNotMatch(html, /<(?:a|img)\b/i, url);
}
});
test('opens safe links separately and resolves relative paths away from the router', () => {
const html = markdown.render('[Docs](docs/apk-install.md) [Web](https://example.com/?a=1&b=2) [Mail](mailto:test@example.com)');
assert.match(html, /href="https:\/\/github.com\/mrjoechen\/luci-theme-carbon\/blob\/main\/docs\/apk-install.md"/);
assert.equal((html.match(/target="_blank" rel="noopener noreferrer"/g) || []).length, 3);
assert.match(html, /a=1&amp;b=2/);
});
test('safe images are lazy loaded without a router referrer', () => {
const html = markdown.render('![Preview](https://example.com/preview.png "Carbon")');
assert.match(html, /<img src="https:\/\/example.com\/preview.png"/);
assert.match(html, /alt="Preview"/);
assert.match(html, /loading="lazy"/);
assert.match(html, /referrerpolicy="no-referrer"/);
});
test('empty or malformed Markdown has a stable text rendering', () => {
assert.equal(markdown.render(null), '');
assert.equal(markdown.render(''), '');
assert.match(markdown.render('**unfinished [link](\n\nA & B < C'), /A &amp; B &lt; C/);
});
test('setext headings, rules, table alignment and ordered list start', () => {
const html = markdown.render('Title\n=====\n\nSub\n---\n\n***\n\n| L | C | R |\n|:--|:-:|--:|\n| a \\| b | c | d |\n\n3. three\n4. four');
for (const pattern of [/<h1>Title<\/h1>/, /<h2>Sub<\/h2>/, /<hr>/, /<th style="text-align:left">L<\/th>/, /<th style="text-align:center">C<\/th>/,
/<td style="text-align:right">d<\/td>/, /<td style="text-align:left">a \| b<\/td>/, /<ol start="3">/])
assert.match(html, pattern);
});
test('tight lists stay inline, loose lists get paragraphs', () => {
assert.match(markdown.render('- a\n- b'), /<li>a<\/li>\n<li>b<\/li>/);
assert.match(markdown.render('- a\n\n- b'), /<li><p>a<\/p><\/li>\n<li><p>b<\/p><\/li>/);
assert.match(markdown.render('- a\ncontinued\n- b'), /<li>a\ncontinued<\/li>/);
});
test('escapes, code spans and URL punctuation', () => {
assert.equal(markdown.render('\\*not em\\* `**not strong**` **strong** _em_ snake_case_name'),
'<p>*not em* <code>**not strong**</code> <strong>strong</strong> <em>em</em> snake_case_name</p>\n');
assert.match(markdown.render('See https://example.com/a.'), /href="https:\/\/example.com\/a"[^>]*>https:\/\/example.com\/a<\/a>\.<\/p>/);
assert.match(markdown.render('line one \nline two'), /line one<br>\nline two/);
});
test('deep nesting and pathological input stay bounded', () => {
const t = Date.now();
assert.match(markdown.render('>'.repeat(500) + ' deep'), /deep/);
for (const s of ['['.repeat(12000), '**'.repeat(6000), '_a '.repeat(4000), '[a]('.repeat(3000), '`'.repeat(12000)]) markdown.render(s);
assert.ok(Date.now() - t < 2000, 'renders in under 2 s');
});
test('status polling keeps the notes DOM, selection and scroll when content is unchanged', async () => {
let writes = 0;
function E(tag, attrs = {}, children) {
let html = '', text = '';
return { tag, attrs, children, hidden: false,
set innerHTML(value) { html = value; if (attrs.class === 'cb-release-notes') writes++; },
get innerHTML() { return html; },
set textContent(value) { text = value; }, get textContent() { return text; }
};
}
let current = { current: '1.1.2-r1', notes: '# First', manager: 'apk' };
const subject = new Function('view', 'rpc', 'poll', 'ui', 'markdown', 'document', 'E', 'L', 'window', '_', fs.readFileSync('htdocs/luci-static/resources/view/system/carbon-update.js', 'utf8'))(
baseclass, { declare: () => async () => current }, { add() {} }, {}, markdown,
{ documentElement: { lang: 'zh' }, querySelectorAll: () => [] }, E, { hasViewPermission: () => true }, {}, s => s);
subject.render(current);
assert.equal(writes, 1);
await subject.pollStatus();
assert.equal(writes, 1);
current = { ...current, notes: '# Second' };
await subject.pollStatus();
assert.equal(writes, 2);
});
@@ -0,0 +1,71 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync('htdocs/luci-static/resources/menu-carbon.js', 'utf8');
function fixture({ stamp, memory = false, fail = false } = {}) {
const oldMenu = { title: 'Carbon Update' };
const newMenu = { title: 'Carbon Theme Settings' };
const data = { menu: oldMenu, 'carbon-menu-version': stamp, tab: { selected: 3 }, auth: 'unchanged' };
let requests = 0, rendered;
const session = {
getLocalData: key => data[key],
setLocalData: (key, value) => { data[key] = value; }
};
// Same two cache layers as LuCI ui.menu: an instance value and session data.
const menu = {
menu: memory ? oldMenu : null,
flushCache() { session.setLocalData('menu', null); },
load() {
if (this.menu == null) this.menu = session.getLocalData('menu');
if (!this.menu) {
requests++;
if (fail) return Promise.reject(new Error('offline'));
this.menu = newMenu;
session.setLocalData('menu', newMenu);
}
return Promise.resolve(this.menu);
}
};
const subject = vm.runInNewContext('(function() {\n' + source + '\n})()', {
baseclass: { extend: value => value }, ui: { menu }, session,
rpc: { declare: () => () => {} }, fs: {},
window: { Carbon: { version: '1.1.2' } },
document: { documentElement: { getAttribute: () => 'zh' } }
});
subject.render = tree => { rendered = tree; };
return { subject, data, oldMenu, newMenu, get rendered() { return rendered; }, get requests() { return requests; } };
}
test('old session menu refreshes without clearing login or selected tabs', async () => {
const f = fixture();
await f.subject.__init__();
assert.equal(f.rendered, f.newMenu);
assert.equal(f.data.auth, 'unchanged');
assert.deepEqual(f.data.tab, { selected: 3 });
assert.equal(f.requests, 1);
});
test('theme upgrade also invalidates a menu already loaded in memory', async () => {
const f = fixture({ stamp: '1.1.1', memory: true });
await f.subject.__init__();
assert.equal(f.rendered, f.newMenu);
assert.equal(f.data['carbon-menu-version'], '1.1.2');
});
test('normal navigation in the same version keeps the menu cache', async () => {
const f = fixture({ stamp: '1.1.2', memory: true });
await f.subject.__init__();
assert.equal(f.rendered, f.oldMenu);
assert.equal(f.requests, 0);
});
test('failed menu refresh does not mark the new version as loaded', async () => {
const f = fixture({ stamp: '1.1.1', fail: true });
await assert.rejects(() => f.subject.__init__(), /offline/);
assert.equal(f.data['carbon-menu-version'], '1.1.1');
});
@@ -0,0 +1,99 @@
'use strict';
// LuCI glue: poll gating under the dashboard and the language list/switch.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync('htdocs/luci-static/resources/menu-carbon.js', 'utf8');
function load({ uci = {}, lang = 'en' } = {}) {
const calls = [], indicators = [];
const poll = {
running: true,
active() { return this.running; },
start() { calls.push('start'); this.running = true; },
stop() { calls.push('stop'); this.running = false; }
};
const writes = [];
const declare = ({ object, method }) => (...args) => {
if (object === 'uci' && method === 'get') return Promise.resolve((uci[args[0]] || {})[args[1]] || {});
if (object === 'uci' && method === 'set') { writes.push(['set', ...args]); return Promise.resolve(0); }
if (object === 'uci' && method === 'commit') { writes.push(['commit', ...args]); return Promise.resolve(0); }
return Promise.resolve({});
};
const listeners = {};
const context = {
baseclass: { extend: (v) => v }, session: {}, fs: {}, poll,
ui: { menu: {}, hideIndicator: (id) => indicators.push(id) },
rpc: { declare },
L: { resolveDefault: (p, d) => Promise.resolve(p).catch(() => d) },
window: { Carbon: { version: 'test' }, setTimeout: (fn) => fn() },
E: () => ({}),
document: {
getElementById: (id) => id === 'maincontent' ? { insertBefore() {} } : null,
documentElement: { getAttribute: () => lang },
addEventListener: (name, fn) => { listeners[name] = fn; }
}
};
const subject = vm.runInNewContext('(function() {\n' + source + '\n})()', context);
return { subject, poll, calls, indicators, writes, listeners, context };
}
test('collapsed details pause LuCI polling and hide the paused badge; expanding resumes', () => {
const f = load();
f.subject.gatePoll(false);
assert.deepEqual(f.calls, ['stop']);
assert.deepEqual(f.indicators, ['poll-status']);
f.subject.gatePoll(false);
assert.deepEqual(f.calls, ['stop'], 'no repeated stop');
f.subject.gatePoll(true);
assert.deepEqual(f.calls, ['stop', 'start']);
});
test('a poll started later by the status view is stopped again while collapsed', () => {
const f = load();
let toggle;
f.context.window.Carbon = {
Dashboard: { mount() {} },
mode: { get: () => 'simple' },
detailsToggle: (host, open, onToggle) => { toggle = onToggle; onToggle(false); }
};
f.subject.mountDashboard('admin', {});
assert.deepEqual(f.calls, ['stop']);
f.poll.running = true; // status/index.js calls poll.add() after our mount
f.listeners['poll-start']();
assert.deepEqual(f.calls, ['stop', 'stop']);
toggle(true);
f.listeners['poll-start']();
assert.deepEqual(f.calls, ['stop', 'stop', 'start'], 'expanded details keep LuCI polling');
});
test('language list offers English plus installed catalogues with native names', async () => {
const f = load({ uci: { luci: {
languages: { '.name': 'languages', '.type': 'internal', zh_cn: '简体中文 (Chinese Simplified)', zh_tw: '繁體中文 (Chinese Traditional)', de: 'Deutsch (German)', 'bad key': 'x' },
main: { lang: 'auto' }
} } });
const info = await f.subject.language.load();
assert.deepEqual(JSON.parse(JSON.stringify(info.options.map((o) => [o.code, o.label, o.short]))), [
['en', 'English', 'EN'], ['de', 'Deutsch', 'DE'], ['zh_cn', '简体中文', '简'], ['zh_tw', '繁體中文', '繁']
]);
assert.equal(info.selected, 'auto');
});
test('a single Chinese catalogue is labelled 中; unknown saved languages fall back to auto', async () => {
const f = load({ uci: { luci: { languages: { zh_cn: '中文 (Chinese)' }, main: { lang: 'fr' } } } });
const info = await f.subject.language.load();
assert.equal(info.options[1].short, '中');
assert.equal(info.selected, 'auto');
});
test('switching language writes luci.main.lang only for installed languages', async () => {
const f = load({ uci: { luci: { languages: { zh_cn: '简体中文 (Chinese Simplified)' }, main: { lang: 'en' } } } });
await f.subject.language.set('zh_cn');
assert.deepEqual(JSON.parse(JSON.stringify(f.writes)), [['set', 'luci', 'main', { lang: 'zh_cn' }], ['commit', 'luci']]);
await assert.rejects(() => f.subject.language.set('ru'), /not installed/);
await f.subject.language.set('auto');
assert.equal(f.writes.length, 4);
});
+81
View File
@@ -0,0 +1,81 @@
<!doctype html>
<html lang="zh-Hans">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Carbon navigation regressions</title>
<link rel="stylesheet" href="../htdocs/luci-static/carbon/carbon.css">
<script>
const carbonReady = new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = '../htdocs/luci-static/carbon/carbon.js?test=' + Date.now();
script.onload = resolve; script.onerror = reject; document.head.append(script);
});
</script>
<style>body {padding:16px} #maincontent {max-width:358px} #results {white-space:pre-wrap} .test-spacer {height:900px}</style>
<h1>Carbon navigation regressions</h1>
<pre id="results" role="status">Running…</pre>
<div id="maincontent"><div id="tabmenu"></div><div id="view"></div></div>
<script>
(async function () {
await carbonReady;
const results = [];
const report = (name, pass) => results.push((pass ? 'PASS ' : 'FAIL ') + name);
report('mobile viewport (390px recommended)', window.innerWidth <= 600);
const frame = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
const makeRow = (kind, active = 9) => {
const row = document.createElement('ul'); row.className = kind;
for (let i = 0; i < 10; i++) {
const li = document.createElement('li');
li.className = kind === 'tabs' ? (i === active ? 'active' : '') : (i === active ? 'cbi-tab' : 'cbi-tab-disabled');
li.innerHTML = '<a href="#">功能页面 ' + String(i + 1).padStart(2, '0') + '</a>';
row.append(li);
}
return row;
};
const visible = row => {
const r = row.getBoundingClientRect(), a = row.querySelector('.active, .cbi-tab').getBoundingClientRect();
return a.left >= r.left - 1 && a.right <= r.right + 1;
};
const menu = document.getElementById('tabmenu'), view = document.getElementById('view');
const parent = makeRow('tabs'), child = makeRow('tabs', 8);
menu.append(parent, child);
Carbon.initShell();
await frame();
report('initial active route tab', visible(parent));
report('nested active route tab', visible(child));
const dynamic = makeRow('cbi-tabmenu');
view.append(dynamic);
await frame();
report('asynchronously inserted form tabs', visible(dynamic));
dynamic.children[9].className = 'cbi-tab-disabled';
dynamic.children[1].className = 'cbi-tab';
await frame();
report('programmatic active tab change', visible(dynamic));
const hidden = document.createElement('div'); hidden.hidden = true;
const nested = makeRow('cbi-tabmenu'); hidden.append(nested); view.append(hidden);
await frame(); hidden.hidden = false; await frame();
report('tabs revealed inside a hidden pane', visible(nested));
parent.scrollLeft = 0;
view.append(document.createElement('p'));
await frame();
report('unrelated refresh preserves manual horizontal scrolling', parent.scrollLeft === 0);
dynamic.children[1].className = 'cbi-tab-disabled';
dynamic.children[8].className = 'cbi-tab';
await frame();
view.style.maxWidth = '240px';
await frame();
report('active tab stays visible after narrowing the container', visible(dynamic));
view.style.maxWidth = '';
const spacer = document.createElement('div'); spacer.className = 'test-spacer'; view.append(spacer);
const input = document.createElement('input'); input.setAttribute('aria-label', 'Focus stays here');
view.prepend(input); input.focus({ preventScroll: true });
const before = window.scrollY;
dynamic.children[8].className = 'cbi-tab-disabled'; dynamic.children[1].className = 'cbi-tab';
await frame();
report('revealing a tab does not scroll the document vertically', window.scrollY === before);
report('revealing a tab preserves input focus', document.activeElement === input);
document.getElementById('results').textContent = results.join('\n');
document.title = results.some(line => line.startsWith('FAIL')) ? 'FAIL — Carbon navigation' : 'PASS — Carbon navigation';
})();
</script>
</html>
+90
View File
@@ -0,0 +1,90 @@
"""Upgrade a legacy IPK using the real OpenWrt 24.10 opkg manager."""
import hashlib
import io
import json
from pathlib import Path
import subprocess
import tarfile
import time
import unittest
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / '.cache' / 'opkg-update'
IMAGE = 'openwrt/rootfs:x86_64-24.10.8@sha256:9972a4b4747cd136abd597475d7b88c51a49fd849d0d53f069a2f4bf446061b9'
def docker(*args, input=None):
r = subprocess.run(['docker', *args], input=input.encode() if input is not None else None,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180, check=True)
return r.stdout.decode()
def archive(files):
out = io.BytesIO()
with tarfile.open(fileobj=out, mode='w:gz') as tar:
for name, content in files.items():
content = content.encode() if isinstance(content, str) else content
entry = tarfile.TarInfo('./' + name)
entry.size = len(content)
entry.mode = 0o755 if name == 'postrm' else 0o644
tar.addfile(entry, io.BytesIO(content))
return out.getvalue()
class OpkgUpgrade(unittest.TestCase):
def test_legacy_hook_does_not_reset_preferences(self):
OUT.mkdir(parents=True, exist_ok=True)
control = archive({'control': 'Package: luci-theme-carbon\nVersion: 1.0.0-r1\nArchitecture: all\nDescription: Upgrade regression fixture\n',
'postrm': '#!/bin/sh\nuci set luci.main.mediaurlbase=/luci-static/bootstrap\nuci commit luci\n'})
(OUT / 'legacy.ipk').write_bytes(archive({'control.tar.gz': control, 'data.tar.gz': archive({'usr/share/carbon-test-marker': 'old'}), 'debian-binary': '2.0\n'}))
docker('run', '--rm', '--mount', f'type=bind,source={ROOT},target=/source,readonly',
'--mount', f'type=bind,source={OUT},target=/out',
'alpine:3.23@sha256:469c9ea410b9215eaee7976ba6c0639039b444be8e5d638f7abbada189971eb2',
'sh', '-c', 'apk add --no-cache tar && sh /source/scripts/build-ipk.sh /out')
c = docker('run', '-d', '--mount', f'type=bind,source={ROOT},target=/source,readonly', IMAGE, 'sleep', '600').strip()
def shell(command): return docker('exec', c, 'sh', '-c', command)
def put(path, text): docker('exec', '-i', c, 'sh', '-c', 'cat > "$1"', 'sh', path, input=text)
def rpc(method, payload=None):
return json.loads(docker('exec', '-i', c, '/usr/libexec/rpcd/luci.carbon_update', 'call', method, input=json.dumps(payload or {})))
def wait():
for _ in range(100):
result = rpc('status')
if not result.get('busy'): return result
time.sleep(.1)
self.fail('Worker did not finish')
try:
shell('mkdir -p /var/lock; opkg update >/tmp/feeds.log 2>&1; opkg install curl ca-bundle flock >/tmp/tools.log 2>&1')
shell('opkg install /source/.cache/opkg-update/legacy.ipk; cp -r /source/root/usr/. /usr/; chmod 755 /usr/libexec/rpcd/luci.carbon_update')
fullversion = (ROOT / 'root/usr/share/carbon/version').read_text().strip()
name = f'luci-theme-carbon_{fullversion}_all.ipk'
content = (OUT / name).read_bytes()
put('/tmp/release.json', json.dumps(dict(tag_name='v' + fullversion.split('-r')[0], draft=False, prerelease=False, body='IPK test',
assets=[dict(name=name, size=len(content), digest='sha256:' + hashlib.sha256(content).hexdigest())])))
shell('mv /usr/bin/curl /usr/bin/test-real-curl')
put('/usr/bin/curl', '''#!/bin/sh
while [ "$#" -gt 0 ]; do
case "$1" in -o) out=$2; shift ;; https://*) url=$1 ;; esac
shift
done
case "$url" in
*/releases/latest) cp /tmp/release.json "$out" ;;
*.ipk) cp /source/.cache/opkg-update/''' + name + ''' "$out" ;;
*) exit 22 ;;
esac
''')
shell('chmod 755 /usr/bin/curl; uci set luci.main.lang=zh_cn; uci set luci.main.mediaurlbase=/luci-static/carbon; uci commit luci')
before = shell('uci show luci.main')
self.assertTrue(rpc('check')['started'])
self.assertTrue(wait()['can_upgrade'])
self.assertTrue(rpc('upgrade', dict(version=fullversion))['started'])
result = wait()
self.assertEqual((result['state'], result['current']), ('success', fullversion), result)
self.assertEqual(shell('uci show luci.main'), before)
self.assertNotIn('syntax error', result['log'])
self.assertFalse(result['can_upgrade'])
finally:
docker('rm', '-f', c)
if __name__ == '__main__':
unittest.main(verbosity=2)
@@ -0,0 +1,52 @@
'use strict';
/* Release body assembly (scripts/release-notes.sh): bilingual files, each language read through once. */
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const ROOT = path.join(__dirname, '..');
const RELEASES = path.join(ROOT, 'docs/releases');
function notes(tag, files, repo) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'carbon-notes-'));
fs.copyFileSync(path.join(RELEASES, 'install.md'), path.join(dir, 'install.md'));
for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(dir, name), text);
const args = [path.join(ROOT, 'scripts/release-notes.sh'), tag].concat(repo ? [repo] : []);
return spawnSync('sh', args, { encoding: 'utf8', env: Object.assign({}, process.env, { RELEASE_NOTES_DIR: dir }) });
}
const headings = (md) => md.split('\n').filter((l) => /^(##+ |---$)/.test(l));
test('a bilingual release reads English start to finish, then Simplified Chinese', () => {
const r = notes('v9.9.9', { 'v9.9.9.md': fs.readFileSync(path.join(RELEASES, 'v1.1.4.md'), 'utf8') }, 'someone/fork');
assert.equal(r.status, 0, r.stderr);
assert.deepEqual(headings(r.stdout), [
'## English', "### What's new", '### Upgrade notes', '### Install', '---',
'## 简体中文', '### 更新内容', '### 升级须知', '### 安装'
]);
const [en, zh] = r.stdout.split('\n---\n');
assert.doesNotMatch(en, /[一-鿿]/, 'no Chinese in the English section');
assert.match(zh, /[一-鿿]/);
assert.match(r.stdout, /github\.com\/someone\/fork\/releases\/latest\/download\/carbon-install\.sh/);
assert.doesNotMatch(r.stdout, /@REPOSITORY@/);
});
test('a release file must have both language sections', () => {
const r = notes('v9.9.9', { 'v9.9.9.md': '## English\n\n### What\'s new\n\n- Only English\n' });
assert.notEqual(r.status, 0);
assert.match(r.stderr, /missing section ## 简体中文/);
});
test('older single-language notes are kept above both sections', () => {
const r = notes('v1.0.9', { 'v1.0.9.md': '### v1.0.9\n\n- 旧格式\n' });
assert.equal(r.status, 0, r.stderr);
assert.match(r.stdout, /^### v1\.0\.9\n\n- 旧格式\n\n---\n\n## English\n\n### Install/);
assert.match(r.stdout, /\n---\n\n## 简体中文\n\n### 安装/);
});
test('tag and repository are validated', () => {
assert.notEqual(notes('latest', {}).status, 0);
assert.notEqual(notes('v1.2.3', {}, 'bad repo').status, 0);
});
@@ -0,0 +1,25 @@
// Render a Carbon theme template the way LuCI's runtime does (template mode)
// with stubbed LuCI globals. Usage: ucode render-template.uc <file.ut> <lang> [login]
const path = ARGV[0], lang = ARGV[1] ?? 'en', login = ARGV[2] == 'login';
const scope = {
ubus: { call: (obj, method) => ({ hostname: 'OpenWrt<b>', model: 'Test Router', rootfs_type: 'squashfs' }) },
http: { prepare_content: (type) => null },
dispatcher: {
lang: lang,
build_url: (...parts) => '/cgi-bin/luci/' + join('/', parts),
lookup: (path) => true
},
ctx: { request_path: [ 'admin', 'status', 'overview' ], path: [ 'admin', 'status', 'overview' ] },
node: { title: 'Overview' }, dispatched: null, duser: login ? 'root' : null,
blank_page: false, css: null,
media: '/luci-static/carbon', resource: '/luci-static/resources',
version: { distname: 'OpenWrt', distversion: '24.10', disturl: 'https://openwrt.org', luciname: 'LuCI', luciversion: 'test' },
_: (s) => s,
striptags: (s) => replace(s, /<[^>]*>/g, ''),
entityencode: (s) => replace(s, /[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c])
};
const fn = loadfile(path, {
raw_mode: false,
module_search_path: [ '/source/tests/ucode-stubs/*.uc', '/usr/lib/ucode/*.so', '/usr/share/ucode/*.uc' ]
});
call(fn, null, scope);
@@ -0,0 +1,120 @@
'use strict';
/*
* Theme settings backend (root/usr/libexec/rpcd/luci.carbon_update): custom
* logo. The real shell functions run with a minimal jshn stand-in and
* temporary paths.
*/
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const SCRIPT = fs.readFileSync(path.join(__dirname, '..', 'root/usr/libexec/rpcd/luci.carbon_update'), 'utf8');
const JSHN = path.join(__dirname, 'shell-stubs', 'jshn.sh');
function backend() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'carbon-logo-'));
const body = SCRIPT
.replace('. /usr/share/libubox/jshn.sh', `. "${JSHN}"`)
.replace(/\ncase "\$1" in\n\tlist\)[\s\S]*$/, '\n');
assert.notEqual(body, SCRIPT, 'dispatch block stripped');
const lib = path.join(dir, 'backend.sh');
fs.writeFileSync(lib, body + `\nlogo_dir="${dir}/www/custom"\nlogo_upload="${dir}/upload"\n`);
const call = (action) => JSON.parse(execFileSync(process.env.CARBON_TEST_SH || 'sh', ['-c', `. "${lib}"; input='{"action":"${action}"}'; logo`], { encoding: 'utf8' }));
const upload = (data) => fs.writeFileSync(path.join(dir, 'upload'), data);
const files = () => fs.existsSync(path.join(dir, 'www/custom')) ? fs.readdirSync(path.join(dir, 'www/custom')).sort() : [];
return { dir, call, upload, files, uploaded: () => fs.existsSync(path.join(dir, 'upload')) };
}
const PNG = Buffer.concat([Buffer.from('89504e470d0a1a0a0000000d49484452', 'hex'), Buffer.alloc(64)]);
const JPEG = Buffer.concat([Buffer.from('ffd8ffe000104a464946', 'hex'), Buffer.alloc(64)]);
const WEBP = Buffer.concat([Buffer.from('RIFF'), Buffer.from('24000000', 'hex'), Buffer.from('WEBPVP8 '), Buffer.alloc(32)]);
const SVG = '<?xml version="1.0"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
'<SVG xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#4F5BEA"/>' +
'<text font-family="Montserrat" x="8" y="40">Carbon one</text></SVG>';
test('a PNG upload becomes the logo; a later JPEG replaces it', () => {
const b = backend();
b.upload(PNG);
const r = b.call('set');
assert.match(r.logo, /^\/luci-static\/carbon\/custom\/logo\.png(\?v=\d+)?$/);
assert.deepEqual(b.files(), ['logo.png']);
assert.equal(b.uploaded(), false, 'upload is consumed');
b.upload(JPEG);
assert.match(b.call('set').logo, /logo\.jpg/);
assert.deepEqual(b.files(), ['logo.jpg']);
assert.equal(fs.statSync(path.join(b.dir, 'www/custom/logo.jpg')).mode & 0o777, 0o644);
b.upload(WEBP);
assert.match(b.call('set').logo, /logo\.webp/);
});
test('the image type comes from the content, never the file name', () => {
const b = backend();
b.upload('GIF89a' + '\0'.repeat(40));
assert.match(b.call('set').logo, /logo\.gif/);
b.upload('<html><body>not an image</body></html>');
assert.deepEqual(b.call('set'), { error: 'logo_type' });
assert.deepEqual(b.files(), ['logo.gif'], 'a rejected upload keeps the current logo');
assert.equal(b.uploaded(), false);
});
test('size limits: empty and over 256 KB are rejected', () => {
const b = backend();
b.upload('');
assert.deepEqual(b.call('set'), { error: 'logo_size' });
b.upload(Buffer.concat([PNG, Buffer.alloc(262144)]));
assert.deepEqual(b.call('set'), { error: 'logo_size' });
assert.deepEqual(b.call('set'), { error: 'logo_missing' }, 'nothing left to apply');
});
test('plain SVG logos are accepted, including DOCTYPE and raster data: images', () => {
const b = backend();
b.upload(SVG);
assert.match(b.call('set').logo, /logo\.svg/);
b.upload('<svg xmlns="http://www.w3.org/2000/svg"><image href="data:image/png;base64,iVBORw0KGgo="/></svg>');
assert.match(b.call('set').logo, /logo\.svg/);
});
test('SVG that could run script on the LuCI origin is rejected', () => {
const unsafe = [
'<svg><script>alert(1)</script></svg>',
'<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/>',
'<svg>\n<rect\n\tONCLICK = "x()"/></svg>',
'<svg><foreignObject><iframe src="x"/></foreignObject></svg>',
'<svg><a href="javascript:alert(1)"><rect/></a></svg>',
'<svg><a xlink:href="https://example.com"><rect/></a></svg>',
'<svg><set attributeName="href" to="x"/></svg>',
'<svg><animate attributeName="href" values="x"/></svg>',
'<svg><image href="&#106;avascript:x"/></svg>',
'<!DOCTYPE svg [<!ENTITY x "y">]><svg>&x;</svg>',
'<svg><use href="data:image/svg+xml;base64,PHN2Zz4="/></svg>',
'<svg><embed src="x"/></svg>'
];
const b = backend();
unsafe.forEach((svg) => {
b.upload(svg);
assert.deepEqual(b.call('set'), { error: 'logo_unsafe' }, svg);
});
assert.deepEqual(b.files(), []);
});
test('reset restores the default logo and removes the directory', () => {
const b = backend();
b.upload(PNG);
b.call('set');
assert.deepEqual(b.call('reset'), { logo: '' });
assert.equal(fs.existsSync(path.join(b.dir, 'www/custom')), false);
assert.deepEqual(b.call('reset'), { logo: '' }, 'idempotent');
assert.deepEqual(b.call('bogus'), { error: 'invalid' });
});
test('a symlinked upload is refused', () => {
const b = backend();
fs.writeFileSync(path.join(b.dir, 'secret'), PNG);
fs.symlinkSync(path.join(b.dir, 'secret'), path.join(b.dir, 'upload'));
assert.deepEqual(b.call('set'), { error: 'logo_missing' });
assert.deepEqual(b.files(), []);
});
@@ -0,0 +1,9 @@
# Minimal stand-in for /usr/share/libubox/jshn.sh: flat objects with string,
# integer and boolean values (enough for the logo methods).
json_init() { _J=''; }
json_add_string() { _J="$_J\"$1\":\"$2\","; }
json_add_int() { _J="$_J\"$1\":$2,"; }
json_add_boolean() { _J="$_J\"$1\":$2,"; }
json_dump() { printf '{%s}\n' "${_J%,}"; }
json_load() { _IN=$1; }
json_get_var() { eval "$1=\$(printf '%s' \"\$_IN\" | sed -n 's/.*\"$2\" *: *\"\\([^\"]*\\)\".*/\\1/p')"; }
@@ -0,0 +1,38 @@
#!/bin/sh
# Render the theme templates with OpenWrt's ucode (run inside an OpenWrt rootfs
# container with the repository mounted at /source).
set -eu
T=/source/ucode/template/themes/carbon
render() { ucode /source/tests/render-template.uc "$@"; }
fail() { echo "FAIL: $*" >&2; exit 1; }
mkdir -p /www /usr/share/carbon
cp -R /source/htdocs/. /www/
cp /source/root/usr/share/carbon/version /usr/share/carbon/version
v=$(cat /usr/share/carbon/version)
out=$(render "$T/header.ut" zh-cn)
printf '%s' "$out" | grep -q "carbon.css?v=$v\"" || fail "css version"
printf '%s' "$out" | grep -q "carbon.js?v=$v\"" || fail "js version"
printf '%s' "$out" | grep -q "/luci-static/carbon/i18n/zh-cn.js?v=$v\"" || fail "zh-cn catalogue"
printf '%s' "$out" | grep -q 'id="topmenu"' || fail "app shell"
printf '%s' "$out" | grep -q '<b>' && fail "hostname not stripped"
render "$T/header.ut" zh_Hant | grep -q '/i18n/zh-tw.js' || fail "zh_Hant alias"
render "$T/header.ut" zh-hans | grep -q '/i18n/zh-cn.js' || fail "zh-hans alias"
render "$T/header.ut" en | grep -q '/i18n/' && fail "english loads no catalogue"
render "$T/header.ut" '../x' | grep -q '/i18n/' && fail "unsafe language code"
render "$T/header.ut" en login | grep -q 'cb-login-card' || fail "login layout"
render "$T/header.ut" en login | grep -q 'Test Router' && fail "login page shows the device model"
render "$T/header.ut" en | grep -q '<small>Test Router</small>' || fail "sidebar shows the device model"
render "$T/footer.ut" en | grep -q "L.require('menu-carbon')" || fail "footer"
render "$T/header.ut" en | grep -q 'src="/luci-static/carbon/logo.svg" alt="">' || fail "default logo"
mkdir -p /www/luci-static/carbon/custom
printf '\211PNG\r\n\032\n' > /www/luci-static/carbon/custom/logo.png
out=$(render "$T/header.ut" en)
printf '%s' "$out" | grep -q 'class="cb-brand-logo" src="/luci-static/carbon/custom/logo.png?v=[0-9]*" alt="" data-custom>' || fail "custom sidebar logo"
printf '%s' "$out" | grep -q 'rel="icon" href="/luci-static/carbon/custom/logo.png?v=' || fail "custom favicon"
render "$T/header.ut" en login | grep -q 'class="cb-login-logo" src="/luci-static/carbon/custom/logo.png?v=' || fail "custom login logo"
rm -r /www/luci-static/carbon/custom
rm /usr/share/carbon/version
render "$T/header.ut" en | grep -q 'carbon.js?v=dev"' || fail "missing version file falls back to dev"
echo "templates render OK ($v)"
@@ -0,0 +1,3 @@
// Stand-in for LuCI's native luci.core module (template rendering tests only).
export function getuid() { return 0; };
export function getspnam(name) { return { pwdp: 'x' }; };
@@ -0,0 +1,220 @@
"""Exercise the production RPC script with real OpenWrt apk-tools and signed APKs.
Usage: python tests/update-integration.py
Requires Docker. Only HTTPS downloads are replaced by deterministic fixture transport.
The native package manager, version comparison, signatures, RPC script and locks are real.
"""
import hashlib
import json
from pathlib import Path
import subprocess
import time
import unittest
ROOT = Path(__file__).resolve().parents[1]
FIXTURES = ROOT / '.cache' / 'update-tests'
ALPINE = 'alpine:3.23@sha256:469c9ea410b9215eaee7976ba6c0639039b444be8e5d638f7abbada189971eb2'
OPENWRT = 'openwrt/rootfs:x86_64-25.12.6@sha256:14401c04218c2e0da0448f099710ada2460636a92395f353351cc616cf3f67af'
RPC = '/usr/libexec/rpcd/luci.carbon_update'
def docker(*args, input=None, check=True):
result = subprocess.run(['docker', *args], input=input.encode('utf-8') if input is not None else None,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=check, timeout=150)
return subprocess.CompletedProcess(result.args, result.returncode, result.stdout.decode('utf-8'), result.stderr.decode('utf-8'))
class UpdateTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
FIXTURES.mkdir(parents=True, exist_ok=True)
docker('run', '--rm', '--mount', f'type=bind,source={ROOT},target=/source,readonly',
'--mount', f'type=bind,source={FIXTURES},target=/fixtures', ALPINE,
'sh', '-c', 'apk add --no-cache openssl && sh /source/tests/make-update-fixtures.sh')
cls.container = docker('run', '-d', '--mount', f'type=bind,source={ROOT},target=/source,readonly',
OPENWRT, 'sleep', '3600').stdout.strip()
try:
cls.shell('apk add curl ca-bundle flock')
cls.shell('mkdir -p /usr/share/carbon/keys /usr/libexec/rpcd /tmp/transport; '
'cp /source/root/usr/libexec/rpcd/luci.carbon_update ' + RPC + '; chmod 755 ' + RPC)
cls.put('/tmp/transport/curl', '''#!/bin/sh
out=''; url=''
while [ "$#" -gt 0 ]; do
case "$1" in -o) out=$2; shift ;; https://*) url=$1 ;; esac
shift
done
[ ! -f /tmp/network-fail ] || { echo 'fixture network failure' >&2; exit 7; }
[ ! -f /tmp/slow-download ] || sleep 2
case "$url" in
https://mirror.test/https://github.com/mrjoechen/luci-theme-carbon/releases/download/v*/luci-theme-carbon-*.apk)
echo "$url" >> /tmp/mirror-hits
[ ! -f /tmp/mirror-fail ] || exit 7
if [ -f /tmp/mirror-corrupt ]; then printf corrupt > "$out"; else cp /tmp/candidate.apk "$out"; fi ;;
https://api.github.com/repos/mrjoechen/luci-theme-carbon/releases/latest) cp /tmp/metadata.json "$out" ;;
https://github.com/mrjoechen/luci-theme-carbon/releases/download/v*/luci-theme-carbon-*.apk) cp /tmp/candidate.apk "$out" ;;
*) echo 'Unexpected download URL' >&2; exit 22 ;;
esac
''')
cls.shell('chmod 755 /tmp/transport/curl')
except Exception:
docker('rm', '-f', cls.container)
raise
@classmethod
def tearDownClass(cls):
docker('rm', '-f', cls.container)
@classmethod
def shell(cls, command):
return docker('exec', cls.container, 'sh', '-c', command).stdout
@classmethod
def put(cls, path, content):
docker('exec', '-i', cls.container, 'sh', '-c', 'cat > "$1"', 'sh', path, input=content)
def rpc(self, method, payload=None):
result = docker('exec', '-i', '-e', 'PATH=/tmp/transport:/usr/sbin:/usr/bin:/sbin:/bin',
self.container, RPC, 'call', method, input=json.dumps(payload or {}))
return json.loads(result.stdout)
def wait(self):
end = time.monotonic() + 15
while time.monotonic() < end:
state = self.rpc('status')
if not state.get('busy'):
return state
time.sleep(.1)
self.fail('Worker did not finish')
def setUp(self):
self.shell('apk --repositories-file /dev/null del luci-theme-carbon >/dev/null 2>&1 || true; '
'rm -rf /tmp/carbon-update; rm -f /tmp/network-fail /tmp/slow-download /tmp/carbon-install-count; '
'rm -f /tmp/mirror-hits /tmp/mirror-fail /tmp/mirror-corrupt /etc/config/carbon; '
'cp /source/.cache/update-tests/keys/carbon-apk.pem /usr/share/carbon/keys/; '
'apk --keys-dir /usr/share/carbon/keys --repositories-file /dev/null --no-network add '
'/source/.cache/update-tests/luci-theme-carbon-1.0.0-r1.apk >/dev/null')
self.candidate()
self.put('/etc/config/carbon-test', 'config preferences\n option language zh_cn\n option style dark\n')
def candidate(self, filename='luci-theme-carbon-1.1.0-r1.apk', **changes):
content = (FIXTURES / filename).read_bytes()
self.shell(f'cp /source/.cache/update-tests/{filename} /tmp/candidate.apk')
self.metadata = dict(tag_name='v1.1.0', draft=False, prerelease=False, body='<script>not HTML</script>', assets=[
dict(name='luci-theme-carbon-1.1.0-r1.apk', size=len(content), digest='sha256:' + hashlib.sha256(content).hexdigest())])
self.metadata.update(changes)
self.put('/tmp/metadata.json', json.dumps(self.metadata))
def checked(self):
self.assertTrue(self.rpc('check').get('started'))
result = self.wait()
self.assertEqual(result['state'], 'idle', result)
return result
def assert_rejected(self, error):
self.checked()
self.assertTrue(self.rpc('upgrade', dict(version='1.1.0-r1')).get('started'))
result = self.wait()
self.assertEqual(result['error'], error, result)
self.assertEqual(result['current'], '1.0.0-r1')
self.assertEqual(self.shell('wc -l < /tmp/carbon-install-count').strip(), '1')
def test_signed_upgrade_and_settings_preserved(self):
result = self.checked()
self.assertTrue(result['can_upgrade'])
self.shell('uci set luci.main.lang=zh_cn; uci set luci.main.mediaurlbase=/luci-static/carbon; uci commit luci')
before = self.shell('cat /etc/config/carbon-test; uci show luci.main')
self.assertTrue(self.rpc('upgrade', dict(version='1.1.0-r1'))['started'])
result = self.wait()
self.assertEqual((result['state'], result['current']), ('success', '1.1.0-r1'), result)
self.assertEqual(self.shell('cat /etc/config/carbon-test; uci show luci.main'), before)
self.assertFalse(result['can_upgrade'])
self.assertEqual(self.rpc('upgrade', dict(version='1.1.0-r1'))['error'], 'stale')
def test_unsigned_apk_rejected_even_with_matching_sha(self):
self.candidate('unsigned.apk')
self.assert_rejected('signature')
def test_wrong_signer_rejected_even_with_matching_sha(self):
self.candidate('wrong.apk')
self.assert_rejected('signature')
def test_signed_package_with_wrong_actual_version_rejected(self):
self.candidate('luci-theme-carbon-1.2.0-r1.apk')
self.assert_rejected('metadata')
def test_checksum_failure_never_installs(self):
self.checked()
self.shell("printf 'corrupt' >> /tmp/candidate.apk")
self.assertTrue(self.rpc('upgrade', dict(version='1.1.0-r1'))['started'])
self.assertEqual(self.wait()['error'], 'checksum')
def test_network_failure_is_reported_and_retry_recovers(self):
self.shell('touch /tmp/network-fail')
self.rpc('check')
self.assertEqual(self.wait()['error'], 'network')
self.shell('rm /tmp/network-fail')
self.assertTrue(self.checked()['can_upgrade'])
def test_invalid_or_prerelease_metadata_rejected(self):
for changes in [dict(prerelease=True), dict(tag_name='v1.1.0;reboot'), dict(assets=[])]:
self.candidate(**changes)
self.rpc('check')
self.assertEqual(self.wait()['error'], 'metadata')
def test_duplicate_request_and_resume_status(self):
self.checked()
self.shell('touch /tmp/slow-download')
self.assertTrue(self.rpc('upgrade', dict(version='1.1.0-r1'))['started'])
self.assertEqual(self.rpc('upgrade', dict(version='1.1.0-r1'))['error'], 'busy')
self.assertTrue(self.rpc('status')['busy'])
self.assertEqual(self.wait()['state'], 'success')
def test_stale_and_unchecked_requests_rejected(self):
self.assertEqual(self.rpc('upgrade', dict(version='1.1.0-r1'))['error'], 'stale')
self.checked()
self.assertEqual(self.rpc('upgrade', dict(version='1.2.0-r1'))['error'], 'stale')
self.assertEqual(self.rpc('upgrade', dict(version=';reboot'))['error'], 'invalid')
cached = json.loads(self.shell('cat /tmp/carbon-update/release.json'))
cached['checked'] -= 1801
self.put('/tmp/carbon-update/release.json', json.dumps(cached))
self.assertFalse(self.rpc('status')['can_upgrade'])
self.assertEqual(self.rpc('upgrade', dict(version='1.1.0-r1'))['error'], 'stale')
def test_mirror_setting_is_validated(self):
for bad in ['http://mirror.test/', 'https://mirror.test/;reboot', 'https://user@mirror.test/', 'ftp://x/', 'https://-bad/']:
self.assertEqual(self.rpc('configure', dict(mirror=bad)).get('error'), 'invalid_mirror', bad)
self.assertEqual(self.rpc('configure', dict(mirror=' https://mirror.test ')), dict(mirror='https://mirror.test/'))
self.assertEqual(self.rpc('status')['mirror'], 'https://mirror.test/')
self.assertEqual(self.rpc('configure', dict(mirror='')), dict(mirror=''))
self.assertEqual(self.rpc('status')['mirror'], '')
def test_mirror_download_is_used_and_verified(self):
self.rpc('configure', dict(mirror='https://mirror.test/'))
self.checked()
self.assertTrue(self.rpc('upgrade', dict(version='1.1.0-r1'))['started'])
result = self.wait()
self.assertEqual((result['state'], result['current']), ('success', '1.1.0-r1'), result)
self.assertEqual(self.shell('wc -l < /tmp/mirror-hits').strip(), '1')
def test_bad_or_unreachable_mirror_falls_back_to_github(self):
self.rpc('configure', dict(mirror='https://mirror.test/'))
for flag in ['mirror-corrupt', 'mirror-fail']:
self.setUp()
self.rpc('configure', dict(mirror='https://mirror.test/'))
self.shell('touch /tmp/' + flag)
self.checked()
self.assertTrue(self.rpc('upgrade', dict(version='1.1.0-r1'))['started'])
result = self.wait()
self.assertEqual((result['state'], result['current']), ('success', '1.1.0-r1'), (flag, result))
self.assertIn('Downloading from github', result['log'])
def test_downgrade_rejected(self):
self.candidate('luci-theme-carbon-1.0.0-r1.apk', tag_name='v0.9.0')
self.metadata['assets'][0]['name'] = 'luci-theme-carbon-0.9.0-r1.apk'
self.put('/tmp/metadata.json', json.dumps(self.metadata))
self.assertFalse(self.checked()['can_upgrade'])
self.assertEqual(self.rpc('upgrade', dict(version='0.9.0-r1'))['error'], 'stale')
if __name__ == '__main__':
unittest.main(verbosity=2)