8000 Let the developer page call every method of Database by dominion525 · Pull Request #107 · dominion525/jetdb · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8000
120 changes: 113 additions & 7 deletions crates/jetdb-wasm/examples/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
scripts/build-wasm-package.sh
node scripts/serve-wasm-example.mjs
then open http://localhost:8080/examples/ and choose a .mdb or .accdb file.
The file is read in the browser and is not sent anywhere.
The file is read in the browser and is not sent anywhere. Once it is open,
Call runs any method of Database on it, with an argument and options as
JSON, and shows what the method returns.
-->
<html lang="en">
<head>
Expand All @@ -33,6 +35,12 @@
dd {
margin-left: 1rem;
}
#output {
background: #f4f4f4;
padding: 0.5rem;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
Expand All @@ -59,11 +67,86 @@ <h1>jetdb-wasm check</h1>
<dd><ul id="tables"></ul></dd>
</dl>

<!-- Calls a method of the open database and shows what it returns. -->
<section id="call" hidden>
<h2>Call</h2>
<label
>Method
<select id="method"></select
></label>
<label>Argument <input id="argument" /></label>
<label>Options (JSON) <input id="options" /></label>
<button id="run">Run</button>
<pre id="output"></pre>
</section>

<script type="module">
import init, { Database } from "../pkg/web/jetdb_wasm.js";

const $ = (id) => document.getElementById(id);

// Each method of Database but open, with what it takes: the name of
// its argument, if any, and whether it takes options.
const METHODS = [
["version"],
["tables", null, true],
["columns", "table"],
["indexes", "table"],
["rows", "table", true],
["csv", "table", true],
["ddl", "dialect", true],
["relationships", null, true],
["properties", "name", true],
["queries", null, true],
["querySql", "name"],
["modules"],
["moduleSource", "name"],
["forms"],
["formControls", "name", true],
["formStream", "name", true],
["formProperties", "name", true],
["macros", null, true],
["macro", "name"],
["embeddedMacros", "form", true],
["dataMacros", "table"],
["dataMacrosText", "table"],
];

// The database open on the page, kept for the calls until the next one
// is opened.
let db;

$("method").replaceChildren(
...METHODS.map(([name]) => new Option(name, name)),
);
const showParameters = () => {
const [, argument, options] = METHODS[$("method").selectedIndex];
$("argument").disabled = !argument;
$("argument").placeholder = argument ?? "";
$("options").disabled = !options;
$("options").placeholder = options ? '{"system": true}' : "";
};
$("method").addEventListener("change", showParameters);
showParameters();

// A value as JSON, with the bytes of a Uint8Array shown by their number
// and the first 16 in hex, and a BigInt with n after it.
const json = (value) =>
JSON.stringify(
value,
(_, v) => {
if (typeof v === "bigint") return `${v}n`;
if (v instanceof Uint8Array) {
const head = [...v.slice(0, 16)]
.map((b) => b.toString(16).padStart(2, "0"))
.join(" ");
return `Uint8Array(${v.length}) ${head}`;
}
return v;
},
2,
);

try {
await init();
$("open").disabled = false;
Expand All @@ -74,29 +157,52 @@ <h1>jetdb-wasm check</h1>
$("open").addEventListener("click", async () => {
$("error").textContent = "";
$("result").hidden = true;
$("call").hidden = true;
$("output").textContent = "";
const file = $("file").files[0];
if (!file) {
$("error").textContent = "Choose a database file first.";
return;
}
// Free the copy of the database opened before in the Wasm memory.
db?.free();
db = undefined;
try {
const bytes = new Uint8Array(await file.arrayBuffer());
const password = $("password").value || undefined;
const db = Database.open(bytes, password);
// Free the copy of the file in the Wasm memory even when reading fails.
const opened = Database.open(bytes, password);
try {
$("version").textContent = db.version();
$("version").textContent = opened.version();
$("tables").replaceChildren(
...db.tables({ system: $("system").checked }).map((name) => {
...opened.tables({ system: $("system").checked }).map((name) => {
const li = document.createElement("li");
li.textContent = name;
return li;
}),
);
} finally {
db.free();
} catch (e) {
opened.free();
throw e;
}
db = opened;
$("result").hidden = false;
$("call").hidden = false;
} catch (e) {
$("error").textContent = e.message;
}
});

$("run").addEventListener("click", () => {
$("error").textContent = "";
$("output").textContent = "";
const [name, argument, options] = METHODS[$("method").selectedIndex];
try {
const args = argument ? [$("argument").value] : [];
const text = $("options").value.trim();
if (options && text) args.push(JSON.parse(text));
const value = db[name](...args);
$("output").textContent =
typeof value === "string" ? value : json(value);
} catch (e) {
$("error").textContent = e.message;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/jetdb-wasm/src/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1334,7 +1334,6 @@ fn cell_value(cell: Cell) -> JsValue {
}
}

/// Sets a property on an object made here, which cannot fail.
/// An object `{ name, type }`, as `queries`, `modules` and `forms` give one
/// for each query, module, and form or report.
fn name_and_type(name: &str, type_name: &str) -> Object {
Expand All @@ -1344,6 +1343,7 @@ fn name_and_type(name: &str, type_name: &str) -> Object {
object
}

/// Sets a property on an object made here, which cannot fail.
fn set(object: &Object, key: &str, value: JsValue) {
Reflect::set(object, &JsValue::from_str(key), &value).expect("set a property");
}
Expand Down
115 changes: 115 additions & 0 deletions crates/jetdb-wasm/tests/browser/examples.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,118 @@ test("asks for a file when none is chosen", async ({ page }) => {
"Choose a database file first.",
);
});

// Runs `method` of the database open on the page with `argument` and
// `options` (JSON), where the method takes them, and returns what the page
// shows.
async function call(page, method, argument = "", options = "") {
await page.locator("#method").selectOption(method);
for (const [id, value] of [
["#argument", argument],
["#options", options],
]) {
const input = page.locator(id);
if (await input.isEnabled()) await input.fill(value);
}
await page.locator("#run").click();
await expect(page.locator("#error")).toHaveText("");
return page.locator("#output").textContent();
}

const callJson = async (...args) => JSON.parse(await call(...args));

test("lists every method of Database to call", async ({ page }) => {
const methods = await page.evaluate(async () => {
const { Database } = await import("../pkg/web/jetdb_wasm.js");
// Leaving out free, and the methods wasm-bindgen makes for itself.
return Object.getOwnPropertyNames(Database.prototype).filter(
(name) => !["constructor", "free"].includes(name) && !name.startsWith("__"),
);
});
const listed = await page.locator("#method option").allTextContents();
expect(listed.toSorted()).toEqual(methods.toSorted());
});

test("calls the methods of tables", async ({ page }) => {
await open(page, "V2003/testV2003.mdb");
expect(await call(page, "version")).toBe("JET4");
expect(await callJson(page, "tables", "", '{"system": true}')).toContain(
"MSysObjects",
);
const columns = await callJson(page, "columns", "Table1");
expect(columns.map((c) => c.name)).toContain("A");
expect(Array.isArray(await callJson(page, "indexes", "Table1"))).toBe(true);
const rows = await callJson(page, "rows", "Table1", '{"limit": 1}');
expect(rows.columns).toEqual(columns.map((c) => c.name));
expect(rows.rows).toHaveLength(1);
expect((await call(page, "csv", "Table1")).split("\n").length).toBeGreaterThan(
1,
);
});

test("calls the methods of relationships, DDL and properties", async ({
page,
}) => {
await open(page, "V2003/indexTestV2003.mdb");
expect((await callJson(page, "relationships")).length).toBeGreaterThan(0);
expect(await call(page, "ddl", "postgres", '{"table": "Table2"}')).toMatch(
/^CREATE TABLE "Table2" \(/,
);
await open(page, "V2010/calcFieldTestV2010.accdb");
const props = await callJson(page, "properties", "Table1");
expect(props.columns.length).toBeGreaterThan(0);
});

test("calls the methods of queries and modules", async ({ page }) => {
await open(page, "V2003/queryTestV2003.mdb");
expect((await callJson(page, "queries")).map((q) => q.name)).toContain(
"DeleteQuery",
);
expect(await call(page, "querySql", "DeleteQuery")).toMatch(/^DELETE/);
await open(page, "vbaV2007.accdb");
expect((await callJson(page, "modules")).map((m) => m.name)).toContain(
"Module1",
);
expect(await call(page, "moduleSource", "Module1")).toContain(
'Attribute VB_Name = "Module1"',
);
});

test("calls the methods of forms", async ({ page }) => {
await open(page, "formPropTest.accdb");
const form = "jp_フォーム_2";
expect((await callJson(page, "forms")).map((f) => f.name)).toContain(form);
const controls = await callJson(page, "formControls", form);
expect(Object.keys(controls[0])).toEqual(["name", "type", "typeCode", "index"]);
// The bytes of a stream are shown by their number and the first in hex.
expect(await call(page, "formStream", form, '{"stream": "blob"}')).toMatch(
/^"Uint8Array\(\d+\) 15 00 14 00 00 00 00 00 /,
);
const design = await callJson(page, "formProperties", form);
expect(design.controls).toHaveLength(controls.length);
});

test("calls the methods of macros", async ({ page }) => {
await open(page, "V2010/macroTestV2010.accdb");
expect(await callJson(page, "macros")).toContain("mcrSimple");
expect((await callJson(page, "macro", "mcrSimple")).source.name).toBe(
"mcrSimple",
);
expect((await callJson(page, "embeddedMacros", "tblItems")).length).toBeGreaterThan(0);
expect((await callJson(page, "dataMacros", "tblItems")).length).toBeGreaterThan(0);
expect((await call(page, "dataMacrosText", "tblItems")).length).toBeGreaterThan(0);
});

test("shows the error of a call", async ({ page }) => {
await open(page, "V2003/testV2003.mdb");
await page.locator("#method").selectOption("columns");
await page.locator("#argument").fill("NoSuchTable");
await page.locator("#run").click();
await expect(page.locator("#error")).toHaveText(/NoSuchTable/);
await expect(page.locator("#output")).toHaveText("");

await page.locator("#method").selectOption("tables");
await page.locator("#options").fill("{system");
await page.locator("#run").click();
await expect(page.locator("#error")).not.toHaveText("");
});
2 changes: 1 addition & 1 deletion docs/ci.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ cargo metadata --format-version 1 --filter-platform wasm32-unknown-unknown | jq

ブラウザ用テストには Node.js も必要。パッケージのビルドとテストには jq と npm も必要。wasmtime は https://wasmtime.dev/ を参照(macOS では `brew install wasmtime`)。

CI の Wasm パッケージのジョブでは、`scripts/test-wasm-browser.sh` も実行する。開発者向けページ `crates/jetdb-wasm/examples/index.html` を Playwright で Chromium、Firefox、WebKit 上で操作する。`scripts/quality-check.sh` では実行しない。手元で実行するときは、パッケージをビルドし、`crates/jetdb-wasm/tests/browser/package-lock.json` で固定した版の Playwright 用のブラウザを先に入れる:
CI の Wasm パッケージのジョブでは、`scripts/test-wasm-browser.sh` も実行する。開発者向けページ `crates/jetdb-wasm/examples/index.html` を Playwright で Chromium、Firefox、WebKit 上で操作する。ページはファイルを開き、`Database` のどのメソッドも呼べる。テストは、ページが全メソッドを載せていることを確かめ、それぞれをテストデータで呼ぶ。`scripts/quality-check.sh` では実行しない。手元で実行するときは、パッケージをビルドし、`crates/jetdb-wasm/tests/browser/package-lock.json` で固定した版の Playwright 用のブラウザを先に入れる:

```bash
npm ci --prefix crates/jetdb-wasm/tests/browser
Expand Down
2 changes: 1 addition & 1 deletion docs/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ cargo metadata --format-version 1 --filter-platform wasm32-unknown-unknown | jq

The browser tests also need Node.js, and the package build and test need jq and npm. For wasmtime, see https://wasmtime.dev/ (on macOS, `brew install wasmtime`).

The Wasm package job in CI also runs `scripts/test-wasm-browser.sh`, which drives the developer page `crates/jetdb-wasm/examples/index.html` with Playwright in Chromium, Firefox and WebKit. `scripts/quality-check.sh` does not run it. To run it locally, build the package and install the browsers for the Playwright version pinned by `crates/jetdb-wasm/tests/browser/package-lock.json` first:
The Wasm package job in CI also runs `scripts/test-wasm-browser.sh`, which drives the developer page `crates/jetdb-wasm/examples/index.html` with Playwright in Chromium, Firefox and WebKit. The page opens a file and calls any method of `Database` on it; the tests check that it lists every method and call each with the test data. `scripts/quality-check.sh` does not run it. To run it locally, build the package and install the browsers for the Playwright version pinned by `crates/jetdb-wasm/tests/browser/package-lock.json` first:

```bash
npm ci --prefix crates/jetdb-wasm/tests/browser
Expand Down
Loading
0