feat: JSON API checks #76
No files matched your search
@@ -20,24 +20,31 @@
|
||||
// Inputs inside a hidden [data-step] are skipped. Checkboxes become
|
||||
// booleans, or arrays of values with [data-multi]; [data-list] inputs are
|
||||
// split on commas, [data-number] parsed and empty [data-nullable] sent as null.
|
||||
// [data-headers] textareas become objects from "Name: value" lines.
|
||||
// Dotted names such as "config.keyword" build nested objects.
|
||||
const serialize = (form) => {
|
||||
const out = {};
|
||||
// Numeric segments build arrays: "config.assertions.0.path".
|
||||
const set = (name, value) => {
|
||||
const path = name.split(".");
|
||||
let obj = out;
|
||||
for (const key of path.slice(0, -1)) obj = obj[key] ??= {};
|
||||
path.slice(0, -1).forEach((key, i) => {
|
||||
obj = obj[key] ??= /^\d+$/.test(path[i + 1]) ? [] : {};
|
||||
});
|
||||
obj[path.at(-1)] = value;
|
||||
};
|
||||
const get = (name) => name.split(".").reduce((o, k) => o?.[k], out);
|
||||
for (const el of form.elements) {
|
||||
if (!el.name || el.type === "fieldset" || el.closest("[data-step]")?.hidden) continue;
|
||||
// :disabled also covers fields inside a disabled fieldset, such as
|
||||
// the settings of other monitor types.
|
||||
const disabled = el.matches(":disabled");
|
||||
if (el.dataset.multi !== undefined) {
|
||||
if (get(el.name) === undefined) set(el.name, []);
|
||||
if (el.checked && !el.disabled) get(el.name).push(el.value);
|
||||
if (el.checked && !disabled) get(el.name).push(el.value);
|
||||
continue;
|
||||
}
|
||||
if (el.disabled) continue;
|
||||
if (disabled) continue;
|
||||
// "<resource_type>:<id>" limits an assignment to one resource.
|
||||
if (el.dataset.scope !== undefined) {
|
||||
const [type, id] = el.value.split(":");
|
||||
@@ -50,6 +57,10 @@
|
||||
if (el.type === "checkbox") set(el.name, el.checked);
|
||||
else if (el.dataset.number !== undefined) set(el.name, Number(el.value));
|
||||
else if (el.dataset.nullable !== undefined) set(el.name, el.value || null);
|
||||
else if (el.dataset.headers !== undefined)
|
||||
set(el.name, Object.fromEntries(
|
||||
el.value.split("\n").map((l) => l.split(":")).filter((p) => p.length > 1 && p[0].trim())
|
||||
.map(([k, ...v]) => [k.trim(), v.join(":").trim()])));
|
||||
else if (el.dataset.list !== undefined)
|
||||
set(el.name, el.value.split(",").map((v) => v.trim()).filter(Boolean));
|
||||
else set(el.name, el.value);
|
||||
|
||||
+32
-19
@@ -1,16 +1,19 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"html"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestMarkdownEditor runs testdata/editor.html, which drives the editor in
|
||||
// assets/app.js and reports PASS or FAIL lines, in a headless browser.
|
||||
func TestMarkdownEditor(t *testing.T) {
|
||||
// TestScripts runs the pages in testdata, which drive assets/app.js and
|
||||
// report PASS or FAIL lines, in a headless browser.
|
||||
func TestScripts(t *testing.T) {
|
||||
var browser string
|
||||
for _, name := range []string{"chromium", "chromium-browser", "google-chrome"} {
|
||||
if p, err := exec.LookPath(name); err == nil {
|
||||
@@ -21,22 +24,32 @@ func TestMarkdownEditor(t *testing.T) {
|
||||
if browser == "" {
|
||||
t.Skip("no Chromium to run the editor in")
|
||||
}
|
||||
page, err := filepath.Abs("testdata/editor.html")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
pages, err := filepath.Glob("testdata/*.html")
|
||||
if err != nil || len(pages) == 0 {
|
||||
t.Fatalf("no test pages: %v", err)
|
||||
}
|
||||
out, err := exec.Command(browser, "--headless", "--disable-gpu", "--allow-file-access-from-files",
|
||||
"--virtual-time-budget=3000", "--dump-dom", "file://"+page).Output()
|
||||
if err != nil {
|
||||
t.Fatalf("running %s: %v", browser, err)
|
||||
}
|
||||
m := regexp.MustCompile(`(?s)<pre id="out">(.*?)</pre>`).FindSubmatch(out)
|
||||
if m == nil || len(m[1]) == 0 {
|
||||
t.Fatal("the editor test page produced no results")
|
||||
}
|
||||
for _, line := range strings.Split(string(m[1]), "\n") {
|
||||
if !strings.HasPrefix(line, "PASS ") {
|
||||
t.Error(line)
|
||||
}
|
||||
for _, rel := range pages {
|
||||
t.Run(filepath.Base(rel), func(t *testing.T) {
|
||||
page, err := filepath.Abs(rel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, browser, "--headless", "--disable-gpu", "--allow-file-access-from-files",
|
||||
"--virtual-time-budget=3000", "--dump-dom", "file://"+page).Output()
|
||||
if err != nil {
|
||||
t.Fatalf("running %s: %v", browser, err)
|
||||
}
|
||||
m := regexp.MustCompile(`(?s)<pre id="out">(.*?)</pre>`).FindSubmatch(out)
|
||||
if m == nil || len(m[1]) == 0 {
|
||||
t.Fatal("the page produced no results")
|
||||
}
|
||||
for _, line := range strings.Split(string(m[1]), "\n") {
|
||||
if !strings.HasPrefix(line, "PASS ") {
|
||||
t.Error(html.UnescapeString(line))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
<!doctype html><html><body data-msg-network="net">
|
||||
<form data-api="/org/monitors" data-next="#saved" id="f">
|
||||
<select name="type" data-type-select><option value="http">http</option><option value="json" selected>json</option><option value="heartbeat">heartbeat</option></select>
|
||||
<input name="name" value="Queue">
|
||||
<div data-hide-for="heartbeat"><input name="target" value="https://x" required></div>
|
||||
<fieldset data-type="json">
|
||||
<select name="config.method"><option value="POST" selected>POST</option></select>
|
||||
<textarea name="config.headers" data-headers>Authorization: Bearer a:b
|
||||
X-Empty:
|
||||
: nothing</textarea>
|
||||
<input name="config.assertions.0.path" value="status"><input name="config.assertions.0.op" value="==">
|
||||
<input name="config.assertions.1.path" value="queue.depth"><input name="config.assertions.1.op" value="<">
|
||||
</fieldset>
|
||||
<fieldset data-type="http" disabled hidden><select name="config.method"><option value="HEAD" selected>HEAD</option></select></fieldset>
|
||||
<fieldset data-hide-for="heartbeat"><input type="checkbox" name="regions" value="r1" data-multi checked></fieldset>
|
||||
<button type="submit">save</button>
|
||||
</form>
|
||||
<pre id="out"></pre>
|
||||
<script>
|
||||
const sent = [];
|
||||
window.axios = { create: () => ({ interceptors: { request: { use() {} } }, request: async (cfg) => { sent.push(cfg.data); return { data: {} }; }, post: async () => ({ data: {} }) }) };
|
||||
</script>
|
||||
<script src="../assets/app.js"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
const out = [];
|
||||
const check = (name, got, want) => {
|
||||
const g = JSON.stringify(got), w = JSON.stringify(want);
|
||||
out.push((g === w ? "PASS " : "FAIL ") + name + (g === w ? "" : " got=" + g + " want=" + w));
|
||||
};
|
||||
const form = document.getElementById("f");
|
||||
const submit = async () => {
|
||||
form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
return sent.at(-1);
|
||||
};
|
||||
let body = await submit();
|
||||
check("fields of a disabled fieldset are skipped", body.config.method, "POST");
|
||||
check("numbered names build arrays", body.config.assertions, [{ path: "status", op: "==" }, { path: "queue.depth", op: "<" }]);
|
||||
check("header lines become an object", body.config.headers, { Authorization: "Bearer a:b", "X-Empty": "" });
|
||||
check("regions sent", body.regions, ["r1"]);
|
||||
|
||||
const sel = form.querySelector("[data-type-select]");
|
||||
sel.value = "heartbeat";
|
||||
sel.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
check("target hidden for heartbeats", form.querySelector('[data-hide-for]').hidden, true);
|
||||
check("target not required for heartbeats", form.querySelector('[name="target"]').required, false);
|
||||
body = await submit();
|
||||
check("regions of a hidden fieldset are not sent", body.regions, []);
|
||||
sel.value = "json";
|
||||
sel.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
check("target required again", form.querySelector('[name="target"]').required, true);
|
||||
document.getElementById("out").textContent = out.join("\n");
|
||||
})();
|
||||
</script></body></html>
|
||||
Reference in new issue
Block a user