You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
232 lines
7.6 KiB
JavaScript
232 lines
7.6 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { createServer } from 'node:http';
|
|
import { existsSync } from 'node:fs';
|
|
import { readFile } from 'node:fs/promises';
|
|
import { createRequire } from 'node:module';
|
|
import { join, normalize } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const require = createRequire(import.meta.url);
|
|
let chromium;
|
|
try {
|
|
({ chromium } = require('playwright'));
|
|
} catch {
|
|
console.log('Cloud invoice payment runtime browser checks skipped: Playwright is unavailable.');
|
|
process.exit(0);
|
|
}
|
|
const browserExecutable = [
|
|
process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE,
|
|
chromium.executablePath(),
|
|
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
'/usr/bin/google-chrome',
|
|
'/usr/bin/chromium',
|
|
].find(path => path && existsSync(path));
|
|
if (!browserExecutable) {
|
|
console.log('Cloud invoice payment runtime browser checks skipped: Chromium is unavailable.');
|
|
process.exit(0);
|
|
}
|
|
const publicRoot = fileURLToPath(new URL('../public/', import.meta.url))
|
|
.replace(/\/+$/, '');
|
|
const runtimePath = join(publicRoot, 'cloud/invoice-detail-runtime.js');
|
|
const runtimeSource = await readFile(runtimePath, 'utf8');
|
|
const ids = [...runtimeSource.matchAll(/byId\('([^']+)'\)/g)]
|
|
.map(match => match[1])
|
|
.filter((id, index, all) => all.indexOf(id) === index);
|
|
|
|
const html = `<!doctype html><html><body data-invoice-id="21">${ids.map(id => {
|
|
if (['invoice-payment-submit', 'invoice-detail-refresh'].includes(id)) {
|
|
return `<button id="${id}" type="button"></button>`;
|
|
}
|
|
return `<div id="${id}"></div>`;
|
|
}).join('')}</body></html>`;
|
|
|
|
const server = createServer(async (request, response) => {
|
|
const url = new URL(request.url || '/', 'http://127.0.0.1');
|
|
if (url.pathname === '/') {
|
|
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
response.end(html);
|
|
return;
|
|
}
|
|
if (!url.pathname.startsWith('/cloud/')) {
|
|
response.writeHead(404).end();
|
|
return;
|
|
}
|
|
const path = normalize(join(publicRoot, url.pathname));
|
|
if (!path.startsWith(`${publicRoot}/`)) {
|
|
response.writeHead(403).end();
|
|
return;
|
|
}
|
|
try {
|
|
response.writeHead(200, {
|
|
'Content-Type': 'application/javascript; charset=utf-8',
|
|
'Cache-Control': 'no-store',
|
|
});
|
|
response.end(await readFile(path));
|
|
} catch {
|
|
response.writeHead(404).end();
|
|
}
|
|
});
|
|
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
const address = server.address();
|
|
if (!address || typeof address === 'string') throw new Error('Test server failed.');
|
|
|
|
const browser = await chromium.launch({
|
|
headless: true,
|
|
executablePath: browserExecutable,
|
|
});
|
|
try {
|
|
const page = await browser.newPage();
|
|
await page.goto(`http://127.0.0.1:${address.port}/`);
|
|
await page.evaluate(() => {
|
|
const jsonResponse = (status, payload) => new Response(
|
|
JSON.stringify(payload),
|
|
{ status, headers: { 'Content-Type': 'application/json' } },
|
|
);
|
|
window.__resolveOldStatus = null;
|
|
window.fetch = async input => {
|
|
const path = new URL(String(input), location.href).pathname;
|
|
if (path === '/api/v1/invoices/21/status') {
|
|
return new Promise(resolve => {
|
|
window.__resolveOldStatus = payload => resolve(jsonResponse(200, payload));
|
|
});
|
|
}
|
|
if (path === '/api/v1/invoices/21/payments') {
|
|
return jsonResponse(202, {
|
|
task_id: '99',
|
|
status_url: '/api/v1/tasks/99',
|
|
});
|
|
}
|
|
if (path === '/api/v1/tasks/99') {
|
|
return jsonResponse(200, {
|
|
id: '99',
|
|
completed: true,
|
|
status: 'succeeded',
|
|
result: { payment: window.__newPayment },
|
|
});
|
|
}
|
|
throw new Error(`Unexpected fetch: ${path}`);
|
|
};
|
|
});
|
|
|
|
const now = Math.floor(Date.now() / 1000);
|
|
const invoice = {
|
|
id: '21',
|
|
purpose: 'renewal',
|
|
title: '实例续费',
|
|
status: 'open',
|
|
display_status: 'open',
|
|
payable: true,
|
|
amount: '10.00',
|
|
currency: 'USD',
|
|
created_at: now - 60,
|
|
due_at: now + 86400,
|
|
renews_expires_at: now + 86400,
|
|
validity_days: 30,
|
|
traffic_quota_bytes: 0,
|
|
items: [],
|
|
};
|
|
const oldPayment = {
|
|
invoice_id: '21',
|
|
method: 'stripe_card',
|
|
status: 'pending',
|
|
payment_kind: 'payurl',
|
|
payment_value: 'https://checkout.stripe.test/old',
|
|
label: 'Stripe Card',
|
|
expires_at: now + 900,
|
|
};
|
|
const newPayment = {
|
|
invoice_id: '21',
|
|
method: 'usdt',
|
|
status: 'pending',
|
|
payment_kind: 'usdt',
|
|
actual_amount: '1.500001',
|
|
receive_address: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
|
|
label: 'USDT',
|
|
expires_at: now + 900,
|
|
};
|
|
const base = {
|
|
csrf_token: 'a'.repeat(64),
|
|
user_id: '1',
|
|
username: 'runtime-test',
|
|
balance: '0.00',
|
|
balance_payment_allowed: false,
|
|
payment_methods: [
|
|
{ id: 'stripe_card', name: 'Stripe Card' },
|
|
{ id: 'usdt', name: 'USDT' },
|
|
],
|
|
};
|
|
await page.evaluate(async ({ base, invoice, oldPayment, newPayment }) => {
|
|
window.__newPayment = newPayment;
|
|
window.__invoiceRuntime = await import(
|
|
`/cloud/invoice-detail-runtime.js?behavior=${Date.now()}`
|
|
);
|
|
window.__invoicePayload = {
|
|
...base,
|
|
invoice,
|
|
active_payment: {
|
|
status: 'pending',
|
|
task_id: null,
|
|
payment: oldPayment,
|
|
can_submit: true,
|
|
},
|
|
};
|
|
window.__invoiceRuntime.hydrateInvoiceDetail(window.__invoicePayload, '21');
|
|
}, { base, invoice, oldPayment, newPayment });
|
|
|
|
assert.equal(await page.locator('.invoice-payment-method-card').count(), 2);
|
|
assert.equal(await page.locator('#invoice-payment-submit').isEnabled(), true);
|
|
assert.equal(await page.locator('a[href="https://checkout.stripe.test/old"]').count(), 1);
|
|
|
|
await page.waitForFunction(() => typeof window.__resolveOldStatus === 'function',
|
|
null, { timeout: 5000 });
|
|
await page.locator('.invoice-payment-method-card[data-method-id="usdt"]').click();
|
|
await page.locator('#invoice-payment-submit').click();
|
|
await page.waitForFunction(() => document.querySelector(
|
|
'.cloud-payment-instructions strong'
|
|
)?.textContent?.includes('USDT'), null, { timeout: 5000 });
|
|
|
|
await page.evaluate(oldStatus => {
|
|
window.__resolveOldStatus(oldStatus);
|
|
}, {
|
|
invoice,
|
|
active_payment: {
|
|
status: 'pending',
|
|
task_id: null,
|
|
payment: oldPayment,
|
|
can_submit: true,
|
|
},
|
|
});
|
|
await page.waitForTimeout(50);
|
|
assert.match(
|
|
await page.locator('.cloud-payment-instructions strong').textContent(),
|
|
/USDT/,
|
|
'A late status response replaced the newer provider order.',
|
|
);
|
|
assert.equal(await page.locator('a[href="https://checkout.stripe.test/old"]').count(), 0);
|
|
|
|
await page.evaluate(({ base, invoice }) => {
|
|
sessionStorage.setItem('virt-cloud:invoice-payment:1:21:stripe_card',
|
|
'stripe-runtime-stale-key-0001');
|
|
sessionStorage.setItem('virt-cloud:invoice-payment:1:21:usdt',
|
|
'usdt-runtime-stale-key-0002');
|
|
window.__invoiceRuntime.stopInvoicePoll();
|
|
window.__invoiceRuntime.hydrateInvoiceDetail({
|
|
...base,
|
|
invoice,
|
|
active_payment: null,
|
|
}, '21');
|
|
}, { base, invoice });
|
|
|
|
assert.equal(await page.locator('.cloud-payment-instructions').count(), 0);
|
|
assert.equal(await page.locator('.invoice-payment-method-card').count(), 2);
|
|
assert.equal(await page.locator('#invoice-payment-submit').isEnabled(), true);
|
|
assert.equal(await page.evaluate(() => [...Array(sessionStorage.length).keys()]
|
|
.map(index => sessionStorage.key(index))
|
|
.filter(key => key?.startsWith('virt-cloud:invoice-payment:1:21:')).length), 0);
|
|
} finally {
|
|
await browser.close();
|
|
await new Promise(resolve => server.close(resolve));
|
|
}
|
|
|
|
console.log('Cloud invoice payment runtime browser behavior checks passed.');
|