File size: 5,236 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | const path = require('path');
const { pathToFileURL } = require('url');
const { chromium } = require('playwright');
const ACTION_TIMEOUT_MS = 5_000;
const CASE_TIMEOUT_MS = 15_000;
const AREA_IDS = ['question-list', 'question-detail', 'comment-area'];
process.env.HARBOR_TEST_SEED = '62001';
function assert(condition, message) {
if (!condition) throw new Error(message);
}
async function within(ms, label, work) {
let timer;
try {
return await Promise.race([
work(),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
}),
]);
} finally {
clearTimeout(timer);
}
}
async function freshPage(browser) {
const context = await browser.newContext({ offline: true, serviceWorkers: 'block' });
const page = await context.newPage();
page.setDefaultTimeout(ACTION_TIMEOUT_MS);
page.setDefaultNavigationTimeout(ACTION_TIMEOUT_MS);
await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, {
waitUntil: 'domcontentloaded',
timeout: ACTION_TIMEOUT_MS,
});
return { context, page };
}
async function snapshot(page) {
return page.evaluate((ids) => {
const styleOf = (element) => {
if (!element) throw new Error('required page area is missing');
const style = getComputedStyle(element);
return { background: style.backgroundColor, color: style.color };
};
return {
body: styleOf(document.body),
areas: Object.fromEntries(ids.map((id) => [id, styleOf(document.querySelector(`[data-testid="${id}"]`))])),
};
}, AREA_IDS);
}
function styleKey(style) {
return `${style.background}|${style.color}`;
}
async function themeToggle(page) {
const control = page.locator('[data-testid="theme-toggle"]');
assert(await control.count() === 1, 'fixture theme-toggle button must exist exactly once');
assert(await control.isVisible(), 'theme-toggle button must be visible');
return control;
}
function rgb(color) {
const values = color.match(/[\d.]+/g);
assert(values && values.length >= 3, `unable to parse computed color: ${color}`);
return values.slice(0, 3).map(Number);
}
function luminance(color) {
const [r, g, b] = rgb(color);
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// ENHANCED_CASE_1: one click makes an immediate, visible light/dark transition.
async function caseImmediateLightDarkTransition(browser) {
const { context, page } = await freshPage(browser);
try {
const toggle = await themeToggle(page);
const before = await snapshot(page);
await toggle.click({ timeout: ACTION_TIMEOUT_MS });
await page.waitForTimeout(300);
const after = await snapshot(page);
const delta = Math.abs(luminance(before.body.background) - luminance(after.body.background));
assert(delta > 0, `body background should visibly switch light/dark modes (luminance delta ${delta.toFixed(1)})`);
} finally {
await context.close();
}
}
// ENHANCED_CASE_2: every named page region participates in the same toggle.
async function caseEveryAreaChanges(browser) {
const { context, page } = await freshPage(browser);
try {
const toggle = await themeToggle(page);
const before = await snapshot(page);
await toggle.click({ timeout: ACTION_TIMEOUT_MS });
await page.waitForTimeout(300);
const after = await snapshot(page);
for (const id of AREA_IDS) {
assert(
styleKey(before.areas[id]) !== styleKey(after.areas[id]),
`${id} should change computed foreground/background styles with the global theme`
);
}
} finally {
await context.close();
}
}
// ENHANCED_CASE_3: a second click switches back and restores the entire page.
async function caseBidirectionalRoundTrip(browser) {
const { context, page } = await freshPage(browser);
try {
const toggle = await themeToggle(page);
const initial = await snapshot(page);
await toggle.click({ timeout: ACTION_TIMEOUT_MS });
const opposite = await snapshot(page);
await toggle.click({ timeout: ACTION_TIMEOUT_MS });
const restored = await snapshot(page);
assert(JSON.stringify(opposite) !== JSON.stringify(initial), 'first click should switch to the opposite theme');
assert(JSON.stringify(restored) === JSON.stringify(initial), 'second click should restore the original whole-page theme');
} finally {
await context.close();
}
}
const enhancedCases = {
ENHANCED_CASE_1: caseImmediateLightDarkTransition,
ENHANCED_CASE_2: caseEveryAreaChanges,
ENHANCED_CASE_3: caseBidirectionalRoundTrip,
};
(async () => {
const requested = process.argv[2];
assert(!requested || enhancedCases[requested], `unknown enhanced case: ${requested}`);
const browser = await chromium.launch({ headless: true, timeout: ACTION_TIMEOUT_MS });
try {
const entries = requested ? [[requested, enhancedCases[requested]]] : Object.entries(enhancedCases);
for (const [caseId, run] of entries) await within(CASE_TIMEOUT_MS, caseId, () => run(browser));
console.log(`task 62 enhanced cases passed (${entries.length}/${entries.length})`);
} finally {
await browser.close();
}
})().catch((err) => {
console.error(err && err.stack || err);
process.exit(1);
});
|