PROJECT SOURCE

check_browser.cjs

系统学习/项目/05-资产API/check_browser.cjs

配套学习源码,可下载后在本机运行。

下载原文件 ↓ 下载完整学习资料 ZIP

"use strict";
// 可选开发验证依赖:npm install --no-save playwright;npx playwright install chromium
var playwright = require("playwright");
var assert = require("node:assert/strict");
var childProcess = require("node:child_process");
var path = require("node:path");
var fs = require("node:fs");
var os = require("node:os");
var directory = fs.mkdtempSync(path.join(os.tmpdir(), "ops-course07-"));
var python = process.env.COURSE_PYTHON || "python";
var secureTest = process.env.COURSE_AUTH_TEST === "1";
var testPassword = require("node:crypto").randomBytes(24).toString("hex");
var serverFile = "server.py";
if (secureTest) {
    serverFile = "secure_server.py";
    var setup = childProcess.spawnSync(python, ["-c", "import json,sys; from auth import Auth; from storage import Store; data=json.load(sys.stdin); Auth(Store(data['db'])).set_user('browser_admin',data['password'],'admin')"], {cwd: __dirname, input: JSON.stringify({db: path.join(directory, "test.sqlite3"), password: testPassword}), encoding: "utf8"});
    assert.equal(setup.status, 0, setup.stderr);
}
var server = childProcess.spawn(python, [path.join(__dirname, serverFile), "--db", path.join(directory, "test.sqlite3"), "--port", "0"]);
var browser;
var context;
var page;
var base;
var errors = [];
var output = "";
var started = false;
var startTimer = setTimeout(function () { fail(new Error("服务启动超过 10 秒")); }, 10000);

function fail(error) {
    console.error(error);
    process.exitCode = 1;
    cleanup();
}

function cleanup() {
    clearTimeout(startTimer);
    if (browser) { browser.close(); }
    server.kill();
    // 保留临时数据库便于定位失败,不纳入仓库。
}

function messageContains(text) {
    return page.waitForFunction(function (expected) {
        var message = document.getElementById("message");
        return message !== null && message.textContent.indexOf(expected) !== -1;
    }, text);
}

function createAsset(name) {
    return page.locator("#name").fill(name).then(function () {
        return page.locator("#host").fill("127.0.0.1");
    }).then(function () { return page.locator("#save").click(); }).then(function () { return messageContains("已保存"); });
}

function runSteps(steps, index) {
    if (index === steps.length) { return Promise.resolve(); }
    return Promise.resolve().then(steps[index]).then(function () { return runSteps(steps, index + 1); });
}

function run(port) {
    base = "http://127.0.0.1:" + port;
    // 浏览器只测试自己启动的服务与临时数据。
    return playwright.chromium.launch({headless: true}).then(function (instance) {
        browser = instance;
        return browser.newContext({viewport: {width: 1280, height: 900}});
    }).then(function (value) {
        context = value;
        return context.newPage();
    }).then(function (value) {
        page = value;
        page.on("pageerror", function (error) { errors.push(error.message); });
        return runSteps([
            function () {
                var lesson = fs.readFileSync(path.join(__dirname, "../../第七单元-前端与Node交互.md"), "utf8");
                var html = lesson.match(/```html\r?\n([\s\S]*?)```/)[1];
                var examples = Array.from(lesson.matchAll(/```javascript\r?\n([\s\S]*?)```/g));
                var expected = ["web01:80\n801\n81\nfalse", "第一步:当前代码继续运行\n第二步:回调运行", "1"];
                for (var i = 0; i < 3; i = i + 1) {
                    var result = childProcess.spawnSync(process.execPath, ["-e", examples[i][1]], {encoding: "utf8", timeout: 5000});
                    assert.equal(result.status, 0, result.stderr);
                    assert.equal(result.stdout.trim().replace(/\r/g, ""), expected[i]);
                }
                return page.setContent(html);
            },
            function () { return page.locator("#host").fill("lesson01"); },
            function () { return page.getByRole("button", {name: "预览"}).click(); },
            function () { return page.locator("#result").textContent().then(function (text) { assert.equal(text, "准备登记:lesson01"); }); },
            function () {
                return context.request.get(base + "/storage.py").then(function (response) { var expected = 404; if (secureTest) { expected = 401; } assert.equal(response.status(), expected); });
            },
            function () {
                return context.request.get(base + "/assets.sqlite3").then(function (response) { var expected = 404; if (secureTest) { expected = 401; } assert.equal(response.status(), expected); });
            },
            function () { return page.goto(base); },
            function () {
                if (!secureTest) { return; }
                return page.locator("#username").fill("browser_admin").then(function () {
                    return page.locator("#password").fill(testPassword);
                }).then(function () { return page.locator("#login-button").click(); });
            },
            function () { return messageContains("列表已加载"); },
            function () { return page.locator("#empty").isVisible().then(function (visible) { assert.equal(visible, true); }); },
            function () { return createAsset("web01"); },
            function () { return page.reload(); },
            function () { return messageContains("列表已加载"); },
            function () { return page.locator("#rows").textContent().then(function (text) { assert.ok(text.indexOf("web01") !== -1); }); },
            function () { return page.locator("#name").fill("web01"); },
            function () { return page.locator("#host").fill("127.0.0.1"); },
            function () { return page.locator("#save").click(); },
            function () { return messageContains("409"); },
            function () { return page.locator("#name").inputValue().then(function (text) { assert.equal(text, "web01"); }); },
            function () { return page.locator("#cancel").click(); },
            function () { return page.getByRole("button", {name: "编辑", exact: true}).click(); },
            function () { return page.locator("#name").fill("<img src=x onerror=alert(1)>"); },
            function () { return page.locator("#port").fill("8080"); },
            function () { return page.locator("#save").click(); },
            function () { return messageContains("已保存"); },
            function () { return page.locator("#rows img").count().then(function (count) { assert.equal(count, 0); }); },
            function () { return page.getByRole("button", {name: "删除", exact: true}).click(); },
            function () { return page.locator("#cancel-delete").click(); },
            function () { return page.locator("#rows tr").count().then(function (count) { assert.equal(count, 1); }); },
            function () { return page.getByRole("button", {name: "删除", exact: true}).click(); },
            function () { return page.locator("#confirm-delete").click(); },
            function () { return messageContains("已删除"); },
            function () { return createAsset("page01"); },
            function () { return createAsset("page02"); },
            function () { return createAsset("page03"); },
            function () { return createAsset("page04"); },
            function () { return createAsset("page05"); },
            function () { return createAsset("page06"); },
            function () { return page.locator("#next").click(); },
            function () { return messageContains("已切换"); },
            function () { return page.locator("#rows").textContent().then(function (text) { assert.ok(text.indexOf("page06") !== -1); assert.equal(text.indexOf("page01"), -1); }); },
            function () { return page.getByRole("button", {name: "删除", exact: true}).click(); },
            function () { return page.locator("#confirm-delete").click(); },
            function () { return messageContains("已删除"); },
            function () { return page.locator("#page").textContent().then(function (text) { assert.equal(text, "第 1 页"); }); },
            function () { return context.setOffline(true); },
            function () { return page.locator("#refresh").click(); },
            function () { return messageContains("无法连接"); },
            function () { return context.setOffline(false); },
            function () { return page.locator("#refresh").click(); },
            function () { return messageContains("列表已刷新"); },
            function () { return page.locator("#submit-task").click(); },
            function () {
                return page.waitForFunction(function () {
                    var text = document.getElementById("job-detail").textContent;
                    return text.indexOf("succeeded") !== -1 && text.indexOf("total_bytes") !== -1;
                });
            },
            function () { return page.locator("#rows tr").first().getByRole("button", {name: "编辑", exact: true}).click(); },
            function () { return page.locator("#port").fill(String(port)); },
            function () { return page.locator("#save").click(); },
            function () { return messageContains("已保存"); },
            function () { return page.locator("#task-kind").selectOption("tcp_connect"); },
            function () {
                return page.locator("#rows tr").first().locator("td").first().textContent().then(function (text) {
                    return page.locator("#task-asset").fill(text.match(/#(\d+)/)[1]);
                });
            },
            function () { return page.locator("#submit-task").click(); },
            function () {
                return page.waitForFunction(function () {
                    var text = document.getElementById("job-detail").textContent;
                    return text.indexOf("succeeded") !== -1 && text.indexOf('"connected": true') !== -1;
                });
            },
            function () { return page.locator("#task-asset").fill("999999"); },
            function () { return page.locator("#submit-task").click(); },
            function () { return page.waitForFunction(function () { return document.getElementById("task-message").textContent.indexOf("404") !== -1; }); },
            function () { return page.screenshot({path: path.join(directory, "desktop.png"), fullPage: true}); },
            function () { return page.setViewportSize({width: 390, height: 844}); },
            function () { return page.screenshot({path: path.join(directory, "mobile.png"), fullPage: true}); },
            function () { return page.evaluate(function () { return document.documentElement.scrollWidth <= window.innerWidth; }).then(function (fits) { assert.equal(fits, true); }); },
            function () {
                var result = childProcess.spawnSync(process.execPath, [path.join(__dirname, "node_client.cjs"), String(port)], {encoding: "utf8", timeout: 10000});
                if (secureTest) {
                    assert.equal(result.status, 1);
                    assert.ok(result.stderr.indexOf("HTTP 401") !== -1);
                } else {
                    assert.equal(result.status, 0, result.stderr);
                    assert.ok(result.stdout.indexOf("资产总数:5") !== -1);
                }
                var invalid = childProcess.spawnSync(process.execPath, [path.join(__dirname, "node_client.cjs"), "0"], {encoding: "utf8", timeout: 5000});
                assert.equal(invalid.status, 2);
                assert.deepEqual(errors, []);
                console.log("PASS: lesson HTML/JS, static paths, browser CRUD, pagination, offline recovery, real disk/TCP jobs and error, mobile width, Node access (secure=" + secureTest + ")");
                console.log("Screenshots: " + directory);
            },
            function () {
                if (!secureTest) { return; }
                return page.locator("#refresh-audit").click().then(function () {
                    return page.waitForFunction(function () {
                        var text = document.getElementById("audit-result").textContent;
                        return text.indexOf("browser_admin") !== -1 && text.indexOf("login_success") !== -1;
                    });
                });
            },
            function () {
                if (!secureTest) { return; }
                return page.locator("#logout").click().then(function () { return page.locator("#login-button").waitFor(); });
            }
        ], 0);
    });
}

server.on("error", fail);
server.stderr.on("data", function (chunk) { process.stderr.write(chunk); });
server.stdout.on("data", function (chunk) {
    output = output + chunk.toString();
    if (!started && output.indexOf("\n") !== -1) {
        started = true;
        clearTimeout(startTimer);
        run(Number(output.trim())).then(cleanup).catch(fail);
    }
});

输入关键词,查找课程与配套源码。