mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-03 01:23:31 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # deploy/logging/sanitize.vrl
This commit is contained in:
commit
7c9e803fbd
65 files changed
+6008
-575
No files matched your search
@@ -0,0 +1,143 @@
|
||||
const { strict: assert } = require("node:assert");
|
||||
const { setTimeout } = require("node:timers");
|
||||
const express = require("express");
|
||||
require("ts-node/register/transpile-only");
|
||||
const config = require("../src/config").default;
|
||||
const AnonymousError = require("../src/core/AnonymousError").default;
|
||||
const File = require("../src/core/AnonymizedFile").default;
|
||||
const GitHubStream = require("../src/core/source/GitHubStream").default;
|
||||
const { AnonymizeTransformer } = require("../src/core/anonymize-utils");
|
||||
const { errorLogLevel, handleError } = require("../src/server/routes/route-utils");
|
||||
const streamer = require("../src/streamer/route").default;
|
||||
const got = require("got");
|
||||
|
||||
const error = (code, httpStatus, extra = {}) => Object.assign(new AnonymousError(code, { httpStatus }), extra);
|
||||
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/** Collect the structured records written to stdout while `run` executes. */
|
||||
async function captureLogs(run) {
|
||||
const records = [];
|
||||
const write = process.stdout.write;
|
||||
process.stdout.write = function (chunk, ...rest) {
|
||||
for (const line of String(chunk).split("\n")) {
|
||||
try { const record = JSON.parse(line); if (record && record.severity) { records.push(record); continue; } } catch { /* not a record */ }
|
||||
if (line) write.call(process.stdout, line + "\n");
|
||||
}
|
||||
const callback = rest.find((arg) => typeof arg === "function");
|
||||
if (callback) callback();
|
||||
return true;
|
||||
};
|
||||
try { await run(); } finally { process.stdout.write = write; }
|
||||
return records;
|
||||
}
|
||||
|
||||
describe("error log levels", () => {
|
||||
it("logs expected client outcomes at info and faults at warn or error", () => {
|
||||
for (const [code, status] of [["repo_not_found", 404], ["repository_expired", 410], ["file_not_found", 404],
|
||||
["github_app_access_required", 403], ["repository_archived", 410], ["folder_not_supported", 404], ["is_removed", 410]]) {
|
||||
assert.equal(errorLogLevel(error(code, status)), "info", code);
|
||||
}
|
||||
assert.equal(errorLogLevel(error("token_expired", 401)), "warn");
|
||||
assert.equal(errorLogLevel(error("rate_limited", 429)), "warn");
|
||||
assert.equal(errorLogLevel(error("github_rate_limit_exceeded", 429)), "warn");
|
||||
assert.equal(errorLogLevel(error("invalid_file_path", 400)), "warn");
|
||||
assert.equal(errorLogLevel(error("upstream_error", 502)), "error");
|
||||
assert.equal(errorLogLevel(error("streamer_unreachable", 502)), "error");
|
||||
assert.equal(errorLogLevel(new Error("boom")), "error");
|
||||
// A known code with a server status is still a fault.
|
||||
assert.equal(errorLogLevel(error("file_not_found", 500)), "error");
|
||||
});
|
||||
|
||||
it("leaves a relayed failure to the service that logged it", () => {
|
||||
assert.equal(errorLogLevel(error("upstream_error", 502, { upstreamStatus: 502, upstreamLogged: true })), "info");
|
||||
assert.equal(errorLogLevel(error("streamer_upstream_error", 502, { upstreamStatus: 502 })), "error");
|
||||
});
|
||||
|
||||
it("drops expected outcomes to debug when another service logs the end state", () => {
|
||||
assert.equal(errorLogLevel(error("repo_not_found", 404), { internal: true }), "debug");
|
||||
assert.equal(errorLogLevel(error("token_expired", 401), { internal: true }), "warn");
|
||||
assert.equal(errorLogLevel(error("upstream_error", 502), { internal: true }), "error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("streamer file failures", function () {
|
||||
this.timeout(10000);
|
||||
let old, original, streamerServer, apiServer, base;
|
||||
beforeEach(async () => {
|
||||
old = { ...config };
|
||||
original = GitHubStream.prototype.getFileContentCache;
|
||||
const streamerApp = express(); streamerApp.use(express.json()); streamerApp.use("/api", streamer);
|
||||
streamerServer = await new Promise((resolve) => { const s = streamerApp.listen(0, "127.0.0.1", () => resolve(s)); });
|
||||
Object.assign(config, { STREAMER_ENTRYPOINT: `http://127.0.0.1:${streamerServer.address().port}/`, SHARED_CACHE_ENABLED: false });
|
||||
const api = express();
|
||||
api.get("/file", async (req, res) => {
|
||||
const file = new File({ repository: {
|
||||
repoId: "anon", owner: { id: "507f1f77bcf86cd799439011" }, options: { terms: [] },
|
||||
model: { _id: "507f1f77bcf86cd799439012", source: { repositoryName: "owner/gone" } },
|
||||
getToken: async () => "token",
|
||||
generateAnonymizeTransformer: (filePath) => new AnonymizeTransformer({ terms: [], filePath }),
|
||||
}, anonymizedPath: "README.md" });
|
||||
file._file = { name: "README.md", path: "", sha: "sha", size: 10 };
|
||||
try { await file.send(res); } catch (failure) { handleError(failure, res, req); }
|
||||
});
|
||||
apiServer = await new Promise((resolve) => { const s = api.listen(0, "127.0.0.1", () => resolve(s)); });
|
||||
base = `http://127.0.0.1:${apiServer.address().port}`;
|
||||
});
|
||||
afterEach(async () => {
|
||||
GitHubStream.prototype.getFileContentCache = original;
|
||||
await new Promise((resolve) => apiServer.close(resolve));
|
||||
await new Promise((resolve) => streamerServer.close(resolve));
|
||||
Object.assign(config, old);
|
||||
});
|
||||
|
||||
const request = async (failure) => {
|
||||
GitHubStream.prototype.getFileContentCache = async () => { throw failure; };
|
||||
let response;
|
||||
const records = await captureLogs(async () => {
|
||||
response = await got(`${base}/file`, { throwHttpErrors: false, retry: 0 });
|
||||
await wait(50);
|
||||
});
|
||||
return { response, records: records.filter((record) => record.severity !== "debug") };
|
||||
};
|
||||
|
||||
it("logs a missing source repository once, at info", async () => {
|
||||
const { response, records } = await request(new AnonymousError("repo_not_found", { httpStatus: 404 }));
|
||||
assert.equal(response.statusCode, 404);
|
||||
assert.equal(records.length, 1, JSON.stringify(records));
|
||||
assert.equal(records[0].severity, "info");
|
||||
assert.equal(records[0].errorCode, "repo_not_found");
|
||||
assert.equal(records[0].upstreamStatus, 404);
|
||||
});
|
||||
|
||||
it("keeps a single fault record from the streamer", async () => {
|
||||
const { response, records } = await request(new AnonymousError("upstream_error", { httpStatus: 502 }));
|
||||
assert.equal(response.statusCode, 502);
|
||||
const faults = records.filter((record) => record.severity === "warn" || record.severity === "error");
|
||||
assert.equal(faults.length, 1, JSON.stringify(records));
|
||||
assert.equal(faults[0].errorCode, "upstream_error");
|
||||
// The streamer's own record, not the API relay (which carries upstreamStatus).
|
||||
assert.equal(faults[0].upstreamStatus, undefined);
|
||||
assert.equal(records.filter((record) => record.upstreamStatus === 502).length, 1);
|
||||
});
|
||||
|
||||
it("reports an uncoded 4xx from in front of the streamer as a fault", async () => {
|
||||
// e.g. a body-size limit or an ingress 404: nothing logged it upstream.
|
||||
const proxy = await new Promise((resolve) => {
|
||||
const s = require("node:http").createServer((req, res) => {
|
||||
req.resume();
|
||||
res.writeHead(413, { "content-type": "text/html" }).end("<h1>Payload Too Large</h1>");
|
||||
}).listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
config.STREAMER_ENTRYPOINT = `http://127.0.0.1:${proxy.address().port}/`;
|
||||
try {
|
||||
const { response, records } = await request(new Error("unused"));
|
||||
assert.equal(response.statusCode, 502);
|
||||
assert.equal(records.length, 1, JSON.stringify(records));
|
||||
assert.equal(records[0].severity, "error");
|
||||
assert.equal(records[0].errorCode, "streamer_unexpected_response");
|
||||
assert.equal(records[0].upstreamStatus, 413);
|
||||
} finally {
|
||||
await new Promise((resolve) => proxy.close(resolve));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -29,6 +29,13 @@ function harness(date) {
|
||||
context.createListeners = () => (target, name, callback) => target.addEventListener(name, callback);
|
||||
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../public/script/billing.js"), "utf8").replaceAll("export function", "function"), context);
|
||||
context.createPageState = parent => Object.create(parent);
|
||||
context.nextTick = fn => Promise.resolve().then(fn);
|
||||
context.window.document = context.document;
|
||||
// Modules the controllers import: outline helpers, the diff parser and the reviewer pages.
|
||||
for (const name of ["outline.js", "formatters.js", "table-analysis.js", "review-pages.js"]) {
|
||||
const moduleSource = fs.readFileSync(path.join(__dirname, "../public/script", name), "utf8");
|
||||
vm.runInNewContext(moduleSource.replace(/^import .*;$/gm, "").replace(/export function/g, "function").replace(/export const/g, "var"), context);
|
||||
}
|
||||
const viewerSource = fs.readFileSync(path.join(__dirname, "../public/script/file-viewer.js"), "utf8");
|
||||
vm.runInNewContext(viewerSource.replace(/^import .*;$/gm, "").replace(/export const/g, "var"), context);
|
||||
const names = [...source.matchAll(/export const (\w+)/g)].map(match => match[1]);
|
||||
@@ -358,11 +365,11 @@ describe("frontend production regressions", function () {
|
||||
request.resolve({ data: { contents: ["title", "MASK", "MASK comment"] } }); await h.flush();
|
||||
expect(h.scope.anonymizePrContent("Alice")).to.equal("MASK");
|
||||
});
|
||||
it("selects the diff tab after asynchronous PR loading", async function () {
|
||||
it("selects the files tab after asynchronous PR loading when there is no conversation", async function () {
|
||||
const h = harness(); h.defs.pullRequestController(h.scope, h.http, {}, { pullRequestId: "pr" }, {});
|
||||
h.requests[0].resolve({ data: {} }); await h.flush();
|
||||
h.requests[1].resolve({ data: { diff: "patch" } }); await h.flush();
|
||||
expect(h.scope.tabState.active).to.equal("diff");
|
||||
expect(h.scope.tabState.active).to.equal("files");
|
||||
const template = fs.readFileSync(path.join(__dirname, "../public/partials/pullRequest.htm"), "utf8");
|
||||
expect(template).not.to.include('ng-init="tabState');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
const { expect } = require("chai");
|
||||
require("ts-node/register/transpile-only");
|
||||
const { default: Gist } = require("../src/core/Gist");
|
||||
|
||||
function makeGist(options) {
|
||||
return new Gist({
|
||||
gistId: "g-test",
|
||||
owner: "000000000000000000000001",
|
||||
source: { gistId: "abc" },
|
||||
options: { terms: ["Alice"], content: true, title: true, image: true, ...options },
|
||||
gist: {
|
||||
description: "By Alice",
|
||||
files: [
|
||||
{ filename: "notes-Alice.md", content: "Written by Alice", language: "Markdown", size: 16 },
|
||||
{ filename: "plot-Alice.png", content: "iVBORw0KGgoAlice==", encoding: "base64", size: 12, type: "image/png" },
|
||||
{ filename: "paper.pdf", content: "JVBERi0xLjQK", encoding: "base64", size: 9, type: "application/pdf" },
|
||||
{ filename: "huge.bin", content: "", encoding: "base64", size: 99999999, tooLarge: true },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("Gist.content() binary files", function () {
|
||||
it("anonymizes text files and names, passes image bytes through, and never serves other binaries", function () {
|
||||
const [md, png, pdf, huge] = makeGist().content().files;
|
||||
expect(md).to.include({ filename: "notes-XXXX-1.md", content: "Written by XXXX-1" });
|
||||
expect(md).to.not.have.property("encoding");
|
||||
expect(png).to.include({ filename: "plot-XXXX-1.png", encoding: "base64", content: "iVBORw0KGgoAlice==" });
|
||||
// A PDF stored by an older version keeps its author metadata: never served.
|
||||
expect(pdf).to.include({ encoding: "base64" });
|
||||
expect(pdf.content).to.be.undefined;
|
||||
expect(huge).to.include({ tooLarge: true, encoding: "base64" });
|
||||
expect(huge.content).to.be.undefined;
|
||||
});
|
||||
|
||||
it("withholds images unless images are displayed, as for repositories", function () {
|
||||
for (const image of [false, undefined]) {
|
||||
const [, png] = makeGist({ image }).content().files;
|
||||
expect(png.content).to.be.undefined;
|
||||
expect(png.hidden).to.equal(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Gist download of binary files", function () {
|
||||
const GitHubUtils = require("../src/core/GitHubUtils");
|
||||
let originalOctokit, originalFetch, fetched;
|
||||
beforeEach(() => { originalOctokit = GitHubUtils.octokit; originalFetch = global.fetch; fetched = []; });
|
||||
afterEach(() => { GitHubUtils.octokit = originalOctokit; global.fetch = originalFetch; });
|
||||
|
||||
async function download(files, respond) {
|
||||
GitHubUtils.octokit = () => ({
|
||||
rest: { gists: { get: async () => ({ data: { files, owner: { login: "alice" } } }) } },
|
||||
paginate: async () => [],
|
||||
});
|
||||
global.fetch = async (url) => { fetched.push(url); return respond(url); };
|
||||
const gist = makeGist();
|
||||
gist._model.set = () => {}; gist._model.markModified = () => {};
|
||||
await gist["downloadContent"]("token");
|
||||
return Object.fromEntries(gist._gistPayload.files.map((f) => [f.filename, f]));
|
||||
}
|
||||
const raw = (name) => `https://gist.githubusercontent.com/alice/abc/raw/1/${name}`;
|
||||
const ok = (bytes) => ({ ok: true, status: 200, arrayBuffer: async () => bytes });
|
||||
|
||||
it("stores images only, within the per-gist budget, and skips unreadable ones", async function () {
|
||||
const MB = 1024 * 1024;
|
||||
const files = {
|
||||
"paper.pdf": { filename: "paper.pdf", size: 10, raw_url: raw("paper.pdf") },
|
||||
"a.png": { filename: "a.png", size: 3 * MB, raw_url: raw("a.png") },
|
||||
"b.png": { filename: "b.png", size: 3 * MB, raw_url: raw("b.png") },
|
||||
"c.png": { filename: "c.png", size: 3 * MB, raw_url: raw("c.png") },
|
||||
"big.png": { filename: "big.png", size: 5 * MB, raw_url: raw("big.png") },
|
||||
"gone.png": { filename: "gone.png", size: 10, raw_url: raw("gone.png") },
|
||||
"elsewhere.png": { filename: "elsewhere.png", size: 10, raw_url: "http://169.254.169.254/x.png" },
|
||||
};
|
||||
const stored = await download(files, (url) => url.endsWith("gone.png") ? { ok: false, status: 404 } : ok(new Uint8Array(8)));
|
||||
expect(fetched.some((u) => u.endsWith("paper.pdf"))).to.equal(false);
|
||||
expect(fetched.some((u) => u.includes("169.254"))).to.equal(false);
|
||||
expect(stored["paper.pdf"]).to.include({ encoding: "base64", content: "" });
|
||||
expect(stored["big.png"].tooLarge).to.equal(true);
|
||||
// 8 MB budget: two 3 MB images fit, the third does not.
|
||||
expect(["a.png", "b.png", "c.png"].filter((n) => stored[n].tooLarge)).to.have.length(1);
|
||||
expect(stored["gone.png"]).to.include({ content: "" });
|
||||
});
|
||||
});
|
||||
@@ -797,6 +797,16 @@ describeMongo("GitHub App credential and repository integration", function () {
|
||||
expect((await Installations.findOne({ installationId: 4 })).blocked).to.equal(false);
|
||||
});
|
||||
|
||||
it("blocks a deleted installation even when the picker list update fails", async () => {
|
||||
const UserRepositories = require("../src/core/model/user-repositories").UserRepositoryModel;
|
||||
const original = UserRepositories.deleteMany;
|
||||
UserRepositories.deleteMany = async () => { throw new Error("picker write failed"); };
|
||||
try {
|
||||
expect((await webhook("installation", { action: "deleted", installation: { id: 4, app_id: 123 } })).status).to.equal(503);
|
||||
} finally { UserRepositories.deleteMany = original; }
|
||||
expect((await Installations.findOne({ installationId: 4 })).blocked).to.equal(true);
|
||||
});
|
||||
|
||||
it("does not let an in-flight installation check undo a deletion", async () => {
|
||||
await Installations.create({ appId: "123", installationId: 4, revision: "old", blocked: true, reconciliationPending: true });
|
||||
mock(async () => {
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
const { expect } = require("chai");
|
||||
require("ts-node/register/transpile-only");
|
||||
const github = require("../src/core/GitHubUtils");
|
||||
const { repositoryPickerPage } = require("../src/core/github-repository-picker");
|
||||
|
||||
describe("repository picker bounded pages", () => {
|
||||
let original;
|
||||
beforeEach(() => { original = github.octokit; });
|
||||
afterEach(() => { github.octokit = original; });
|
||||
it("fetches only one small upstream page for browsing", async () => {
|
||||
let calls = 0;
|
||||
github.octokit = token => ({ request: async (route, params) => {
|
||||
calls++;
|
||||
expect(token).to.equal("private-token");
|
||||
expect(params).to.include({ page: 2, per_page: 20, sort: "full_name" });
|
||||
return { data: [{ id: 21, full_name: "org/repo" }], headers: {} };
|
||||
} });
|
||||
expect(await repositoryPickerPage("private-token", 20)).to.deep.equal({
|
||||
items: [{ id: 21, fullName: "org/repo" }], nextCursor: null,
|
||||
});
|
||||
expect(calls).to.equal(1);
|
||||
});
|
||||
it("searches case-insensitively and resumes without skipping matches", async () => {
|
||||
github.octokit = () => ({ request: async () => ({
|
||||
data: Array.from({ length: 100 }, (_, id) => ({ id, full_name: `Org/${id % 2 ? "other" : "Match"}-${id}` })),
|
||||
headers: { link: '<https://api.github.com/user/repos?page=2>; rel="next"' },
|
||||
}) });
|
||||
const first = await repositoryPickerPage("token", 0, "org/match");
|
||||
expect(first.items).to.have.length(20);
|
||||
expect(first.nextCursor).to.equal(39);
|
||||
const second = await repositoryPickerPage("token", first.nextCursor, "org/match");
|
||||
expect(second.items[0].id).to.equal(40);
|
||||
expect(second.items).to.have.length(20);
|
||||
});
|
||||
it("returns a continuation for an empty search batch, not a false end", async () => {
|
||||
github.octokit = () => ({ request: async () => ({
|
||||
data: Array.from({ length: 100 }, (_, id) => ({ id, full_name: `org/repo-${id}` })),
|
||||
headers: { link: '<https://api.github.com/user/repos?page=2>; rel="next"' },
|
||||
}) });
|
||||
expect(await repositoryPickerPage("token", 0, "missing")).to.deep.equal({ items: [], nextCursor: 100 });
|
||||
});
|
||||
it("propagates upstream failures so the UI can retry", async () => {
|
||||
github.octokit = () => ({ request: async () => { throw new Error("rate limit"); } });
|
||||
try { await repositoryPickerPage("token"); throw new Error("unexpected success"); }
|
||||
catch (error) { expect(error.message).to.equal("rate limit"); }
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ const github = require("../src/core/source/GitHubRepository");
|
||||
const Resources = require("../src/core/model/anonymizedRepositories/anonymizedRepositories.model").default;
|
||||
const Sources = require("../src/core/model/repositories/repositories.model").default;
|
||||
const Users = require("../src/core/model/users/users.model").default;
|
||||
const { UserRepositorySyncModel } = require("../src/core/model/user-repositories");
|
||||
const repositoryRouter = require("../src/server/routes/repository-private").default;
|
||||
const appRouter = require("../src/server/routes/github-app").githubAppRouter;
|
||||
const handler = (router, path) => router.stack.find(layer => layer.route?.path === path).route.stack.at(-1).handle;
|
||||
@@ -52,6 +53,8 @@ describe("owner actions rearm access alerts", () => {
|
||||
for (const action of ["install", "request", "unverified"]) it(`handles ${action} installation completion without premature resets`, async () => {
|
||||
stub(app, "userInstallations", async () => [{ id: 42 }]);
|
||||
stub(Users, "updateOne", async () => ({}));
|
||||
let staleList;
|
||||
stub(UserRepositorySyncModel, "updateMany", async filter => { staleList = filter; return {}; });
|
||||
const req = { session: {
|
||||
githubInstallFlow: { ownerId: owner, state: "state", expires: Date.now() + 60000, returnTo: "/connections" },
|
||||
save: callback => callback(),
|
||||
@@ -60,6 +63,10 @@ describe("owner actions rearm access alerts", () => {
|
||||
try { await handler(appRouter, "/app/setup")(req, { redirect() {} }); } catch (error) { failure = error; }
|
||||
expect(resets).to.deep.equal(action === "install" ? [[owner]] : []);
|
||||
if (action === "unverified") expect(failure?.message).to.equal("github_app_access_required");
|
||||
else expect(failure).to.equal(undefined);
|
||||
else {
|
||||
expect(failure).to.equal(undefined);
|
||||
// Completing setup marks the stored repository picker list for a sync.
|
||||
expect(staleList).to.deep.equal({ ownerId: { $in: [owner] }, connection: "github-app" });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
const { expect } = require("chai");
|
||||
require("ts-node/register/transpile-only");
|
||||
const { default: PullRequest, reviewThreads, commitMessage } = require("../src/core/PullRequest");
|
||||
|
||||
const at = (day) => new Date(`2026-03-${String(day).padStart(2, "0")}T10:00:00Z`);
|
||||
|
||||
function makePullRequest(options) {
|
||||
return new PullRequest({
|
||||
pullRequestId: "pr-test",
|
||||
owner: "000000000000000000000001",
|
||||
anonymizeDate: at(20),
|
||||
source: { pullRequestId: 12, repositoryFullName: "alice/secret-project" },
|
||||
options: { terms: ["Alice", "secret-project"], image: true, link: true, ...options },
|
||||
pullRequest: {
|
||||
title: "Fix by Alice",
|
||||
body: "Body",
|
||||
diff: "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-Alice\n+Bob\n",
|
||||
state: "open",
|
||||
author: "Alice",
|
||||
baseRef: "main",
|
||||
headRef: "Alice/fix-secret-project",
|
||||
creationDate: at(1),
|
||||
updatedDate: at(2),
|
||||
comments: [],
|
||||
commits: [
|
||||
{ message: "First commit by Alice\n\nDetails for secret-project", author: "Alice", date: at(3) },
|
||||
{ message: "Second", author: "bob", date: at(4) },
|
||||
],
|
||||
reviewComments: [
|
||||
{ commentId: 11, path: "src/Alice.py", line: 4, body: "Why Alice?", author: "bob", creationDate: at(5), updatedDate: at(5) },
|
||||
{ commentId: 13, inReplyTo: 11, path: "src/Alice.py", line: 4, body: "Because", author: "Alice", creationDate: at(7), updatedDate: at(7) },
|
||||
{ commentId: 12, path: "README.md", line: 1, body: "Typo", author: "carol", creationDate: at(6), updatedDate: at(6) },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const all = { title: true, body: true, comments: true, diff: true, username: true, date: true, origin: false };
|
||||
|
||||
describe("PullRequest.content() commits, branches and review threads", function () {
|
||||
it("anonymizes the author, and shows branch names only with the origin", function () {
|
||||
const out = makePullRequest(all).content();
|
||||
expect(out.author).to.equal("XXXX-1");
|
||||
expect(out).to.not.have.property("baseRef");
|
||||
expect(out).to.not.have.property("headRef");
|
||||
const withOrigin = makePullRequest({ ...all, origin: true }).content();
|
||||
expect(withOrigin.baseRef).to.equal("main");
|
||||
expect(withOrigin.headRef).to.equal("XXXX-1/fix-XXXX-2");
|
||||
});
|
||||
|
||||
it("strips people from commit messages even without matching terms", function () {
|
||||
const message = "Merge pull request #3 from asmith/fix-x\n\nFix x <asmith@uni.edu>\n\nSigned-off-by: Ann Smith <ann@uni.edu>\nCo-authored-by: Bo <bo@x.org>\n";
|
||||
expect(commitMessage(message, { origin: false })).to.equal("Merge pull request #3\n\nFix x");
|
||||
expect(commitMessage(message, { origin: true })).to.equal("Merge pull request #3 from fix-x\n\nFix x");
|
||||
expect(commitMessage("Merge branch 'main' of github.com:asmith/repo into dev", { origin: true })).to.equal("Merge branch 'main' into dev");
|
||||
expect(commitMessage("Merge branch 'asmith/x'", { origin: false })).to.equal("Merge branch");
|
||||
expect(commitMessage("Plain message", { origin: false })).to.equal("Plain message");
|
||||
const pr = makePullRequest(all);
|
||||
pr.model.pullRequest.commits = [{ message: "Merge pull request #3 from asmith/fix\n\nSigned-off-by: Ann Smith <ann@uni.edu>", author: "asmith", date: at(3) }];
|
||||
expect(pr.content().commits[0].message).to.equal("Merge pull request #3");
|
||||
});
|
||||
|
||||
it("hides the author without the username option", function () {
|
||||
const out = makePullRequest({ ...all, username: false }).content();
|
||||
expect(out.author).to.be.undefined;
|
||||
expect(out.commits[0]).to.not.have.property("author");
|
||||
expect(out.reviewComments[0].comments[0]).to.not.have.property("author");
|
||||
});
|
||||
|
||||
it("lists commits with anonymized messages and no SHA", function () {
|
||||
const out = makePullRequest(all).content();
|
||||
expect(out.commits).to.have.length(2);
|
||||
expect(out.commits[0].message).to.equal("First commit by XXXX-1\n\nDetails for XXXX-2");
|
||||
expect(out.commits[0].author).to.equal("XXXX-1");
|
||||
expect(out.commits[0].date).to.deep.equal(at(3));
|
||||
expect(Object.keys(out.commits[0])).to.have.members(["message", "author", "date"]);
|
||||
});
|
||||
|
||||
it("drops commits when the diff is hidden, and dates when dates are hidden", function () {
|
||||
expect(makePullRequest({ ...all, diff: false }).content().commits).to.be.undefined;
|
||||
expect(makePullRequest({ ...all, date: false }).content().commits[0]).to.not.have.property("date");
|
||||
});
|
||||
|
||||
it("groups review comments into threads without GitHub ids", function () {
|
||||
const out = makePullRequest(all).content();
|
||||
expect(out.reviewComments).to.have.length(2);
|
||||
const [first, second] = out.reviewComments;
|
||||
expect(first.path).to.equal("src/XXXX-1.py");
|
||||
expect(first.line).to.equal(4);
|
||||
expect(first.comments.map((c) => c.body)).to.deep.equal(["Why XXXX-1?", "Because"]);
|
||||
expect(first.comments[1].author).to.equal("XXXX-1");
|
||||
expect(second.path).to.equal("README.md");
|
||||
expect(JSON.stringify(out.reviewComments)).to.not.match(/commentId|inReplyTo|"1[123]"/);
|
||||
});
|
||||
|
||||
it("omits review threads without the comments option", function () {
|
||||
expect(makePullRequest({ ...all, comments: false }).content().reviewComments).to.be.undefined;
|
||||
});
|
||||
|
||||
it("keeps pull requests stored before commits and review comments readable", function () {
|
||||
const pr = makePullRequest(all);
|
||||
delete pr.model.pullRequest.commits;
|
||||
delete pr.model.pullRequest.reviewComments;
|
||||
const out = pr.content();
|
||||
expect(out.commits).to.be.undefined;
|
||||
expect(out.reviewComments).to.be.undefined;
|
||||
expect(out.diff).to.include("XXXX-1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reviewThreads()", function () {
|
||||
it("attaches replies to their thread even when they arrive out of order", function () {
|
||||
const threads = reviewThreads([
|
||||
{ commentId: 3, inReplyTo: 1, path: "a", line: 2, body: "reply 2", author: "x", creationDate: at(9), updatedDate: at(9) },
|
||||
{ commentId: 1, path: "a", line: 2, body: "root", author: "x", creationDate: at(1), updatedDate: at(1) },
|
||||
{ commentId: 2, inReplyTo: 1, path: "a", line: 2, body: "reply 1", author: "y", creationDate: at(2), updatedDate: at(2) },
|
||||
{ commentId: 4, inReplyTo: 99, path: "b", line: 5, body: "orphan", author: "z", creationDate: at(3), updatedDate: at(3) },
|
||||
]);
|
||||
expect(threads.map((t) => t.comments.map((c) => c.body))).to.deep.equal([["root", "reply 1", "reply 2"], ["orphan"]]);
|
||||
expect(threads[1]).to.include({ path: "b", line: 5 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
const { expect } = require("chai");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const load = (name) => import(pathToFileURL(path.join(__dirname, "../public/script", name)).href);
|
||||
|
||||
describe("Reviewer page outlines and diffs", function () {
|
||||
let outline, formatters, pages, dom, vue;
|
||||
// The pages register their scroll listeners in the controller's effect scope.
|
||||
const inScope = (fn) => { const scope = vue.effectScope(); scope.run(fn); return scope; };
|
||||
before(async () => {
|
||||
dom = new JSDOM("<!doctype html><body></body>", { pretendToBeVisual: true });
|
||||
global.window = dom.window;
|
||||
outline = await load("outline.js");
|
||||
formatters = await load("formatters.js");
|
||||
pages = await load("review-pages.js");
|
||||
vue = await import("vue");
|
||||
});
|
||||
after(() => { delete global.window; dom.window.close(); });
|
||||
|
||||
it("splits redaction masks into slot parts", () => {
|
||||
expect(outline.redactParts("Results from XXXX-2 cluster")).to.deep.equal([{ t: "Results from " }, { n: "2" }, { t: " cluster" }]);
|
||||
expect(outline.redactParts("")).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("outlines h1-h3 with redaction slots read back from the chips", () => {
|
||||
const html = '<h1 id="t">Guide</h1><h2 id="a">Setup</h2><h3 id="b">Data</h3><h4 id="c">Skip</h4>'
|
||||
+ '<h2 id="r">Results from <mark class="redact-chip" data-term="XXXX-2"><i>2</i></mark> cluster</h2>';
|
||||
const list = outline.headingOutline(html);
|
||||
expect(list.map((h) => [h.id, h.level, h.depth])).to.deep.equal([["t", 1, 0], ["a", 2, 1], ["b", 3, 2], ["r", 2, 1]]);
|
||||
expect(list[3].parts).to.deep.equal([{ t: "Results from " }, { n: "2" }, { t: " cluster" }]);
|
||||
});
|
||||
|
||||
it("starts depth at the shallowest heading", () => {
|
||||
const list = outline.headingOutline('<h2 id="a">A</h2><h3 id="b">B</h3>');
|
||||
expect(list.map((h) => h.depth)).to.deep.equal([0, 1]);
|
||||
});
|
||||
|
||||
it("highlights the last section above the reading line", () => {
|
||||
const doc = dom.window.document;
|
||||
doc.body.innerHTML = '<h2 id="one">1</h2><h2 id="two">2</h2><h2 id="three">3</h2>';
|
||||
const tops = { one: -400, two: 120, three: 700 };
|
||||
for (const id of Object.keys(tops)) doc.getElementById(id).getBoundingClientRect = () => ({ top: tops[id] });
|
||||
const view = { innerHeight: 900, scrollY: 400 };
|
||||
expect(outline.activeSection(["one", "two", "three"], { doc, view })).to.equal("two");
|
||||
tops.two = 400;
|
||||
expect(outline.activeSection(["one", "two", "three"], { doc, view })).to.equal("one");
|
||||
tops.one = 50;
|
||||
tops.two = 300; tops.three = 600;
|
||||
expect(outline.activeSection(["one", "two", "three"], { doc, view: { innerHeight: 900, scrollY: 0 } })).to.equal("one");
|
||||
});
|
||||
|
||||
it("parses a diff into files with status and counts, without a phantom last line", () => {
|
||||
const files = formatters.parseDiff([
|
||||
"diff --git a/a.py b/a.py", "--- a/a.py", "+++ b/a.py", "@@ -1,2 +1,2 @@", " keep", "-old", "+new",
|
||||
"diff --git a/gone.sh b/gone.sh", "deleted file mode 100644", "--- a/gone.sh", "+++ /dev/null", "@@ -1,2 +0,0 @@", "-x", "-y",
|
||||
"diff --git a/new.md b/new.md", "new file mode 100644", "--- /dev/null", "+++ b/new.md", "@@ -0,0 +1 @@", "+hi",
|
||||
"\\ No newline at end of file", "",
|
||||
].join("\n"));
|
||||
expect(files.map((f) => [f.path, f.status, f.additions, f.deletions, f.lines.length])).to.deep.equal([
|
||||
["a.py", "modified", 1, 1, 4], ["gone.sh", "deleted", 0, 2, 3], ["new.md", "added", 1, 0, 2],
|
||||
]);
|
||||
expect(files[0].lines[3]).to.include({ kind: "add", newNo: 2 });
|
||||
});
|
||||
|
||||
it("keeps removed '-- ' and added '++ ' lines inside a hunk as content", () => {
|
||||
const files = formatters.parseDiff([
|
||||
"diff --git a/q.sql b/q.sql", "--- a/q.sql", "+++ b/q.sql", "@@ -1,3 +1,3 @@", " select 1;", "--- old comment", "+++ new counter", " end;",
|
||||
"diff --git a/b.txt b/b.txt", "--- a/b.txt", "+++ b/b.txt", "@@ -1 +1 @@", "-x", "+y",
|
||||
].join("\n"));
|
||||
expect(files.map((f) => [f.path, f.additions, f.deletions])).to.deep.equal([["q.sql", 1, 1], ["b.txt", 1, 1]]);
|
||||
expect(files[0].lines.map((l) => l.text)).to.deep.equal(["@@ -1,3 +1,3 @@", "select 1;", "-- old comment", "++ new counter", "end;"]);
|
||||
});
|
||||
|
||||
it("places a LEFT thread on the removed line and a RIGHT one on the new line with the same number", () => {
|
||||
const state = { details: {
|
||||
diff: "--- a/a.py\n+++ b/a.py\n@@ -1,2 +1,2 @@\n-gone\n+added\n keep\n",
|
||||
reviewComments: [{ path: "a.py", line: 1, side: "LEFT", comments: [{ body: "old" }] }, { path: "a.py", line: 1, side: "RIGHT", comments: [{ body: "new" }] }],
|
||||
}, fmt: { date: (d) => d } };
|
||||
const scope = inScope(() => pages.setupPullRequestPage(state));
|
||||
const [file] = state.prFiles();
|
||||
expect(file.lines.filter((l) => l.threads).map((l) => [l.kind, l.threads[0].comments[0].body])).to.deep.equal([["remove", "old"], ["add", "new"]]);
|
||||
scope.stop();
|
||||
});
|
||||
|
||||
it("renders the legacy diff HTML from the same parser", () => {
|
||||
const html = formatters.diff("--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a<b\n+b\n");
|
||||
expect(html).to.include('diff-file-status-modified').and.include("a<b");
|
||||
expect((html.match(/<tr/g) || []).length).to.equal(3);
|
||||
});
|
||||
|
||||
it("places review threads on their diff line and keeps the rest at the end of the file", () => {
|
||||
const state = { details: {
|
||||
diff: "--- a/src/a.py\n+++ b/src/a.py\n@@ -1,2 +1,3 @@\n one\n+two\n three\n",
|
||||
reviewComments: [{ path: "src/a.py", line: 2, comments: [{ body: "here" }] }, { path: "src/a.py", line: 40, comments: [{ body: "elsewhere" }] }, { path: "other", line: 1, comments: [] }],
|
||||
comments: [{ body: "c", creationDate: "2026-03-02" }],
|
||||
commits: [{ message: "First\n\nBody", date: "2026-03-01" }, { message: "Second", date: "2026-03-01" }],
|
||||
}, fmt: { date: (d) => d.slice(0, 10) } };
|
||||
const scope = inScope(() => pages.setupPullRequestPage(state));
|
||||
const [file] = state.prFiles();
|
||||
expect(file).to.include({ path: "src/a.py", dir: "src/", name: "a.py", threads: 2, id: "diff-1" });
|
||||
expect(file.lines.find((l) => l.threads)).to.include({ newNo: 2, text: "two" });
|
||||
expect(file.looseThreads.map((t) => t.line)).to.deep.equal([40]);
|
||||
expect(state.prStats()).to.deep.equal({ files: 1, additions: 1, deletions: 0 });
|
||||
expect(state.diffBar(file)).to.deep.equal(["add", "add", "add", "add", "add"]);
|
||||
expect(state.commitGroups()).to.deep.equal([{ day: "2026-03-01", commits: [
|
||||
{ message: "First\n\nBody", date: "2026-03-01", index: 1, headline: "First", detail: "Body" },
|
||||
{ message: "Second", date: "2026-03-01", index: 2, headline: "Second", detail: "" },
|
||||
] }]);
|
||||
expect(state.prTimeline().map((i) => i.kind)).to.deep.equal(["comment", "review", "review", "review"]);
|
||||
state.toggleAllFiles();
|
||||
expect(state.allCollapsed()).to.equal(true);
|
||||
scope.stop();
|
||||
});
|
||||
|
||||
it("opens a pull request on its conversation, or on the files without one", () => {
|
||||
expect(pages.defaultPullRequestTab({ body: "x", diff: "d" })).to.equal("conversation");
|
||||
expect(pages.defaultPullRequestTab({ diff: "d", comments: [] })).to.equal("files");
|
||||
expect(pages.defaultPullRequestTab({ commits: [{}] })).to.equal("commits");
|
||||
});
|
||||
|
||||
it("lists gist files with language, lines and nested Markdown headings", () => {
|
||||
const state = { tabState: { active: "files" }, details: { files: [
|
||||
{ filename: "NOTES-XXXX-1.md", language: "Markdown", content: "# A\n\n## B\n" },
|
||||
{ filename: "run.sh", language: "Shell", content: "a\nb\nc\n" },
|
||||
] } };
|
||||
const scope = inScope(() => pages.setupGistPage(state));
|
||||
state.setFileOutline(0, [{ id: "file-1-a", level: 1, depth: 0, parts: [{ t: "A" }] }]);
|
||||
const toc = state.gistToc();
|
||||
expect(toc.map((f) => [f.id, f.language, f.lines, f.headings.length])).to.deep.equal([["file-1", "Markdown", 3, 1], ["file-2", "Shell", 3, 0]]);
|
||||
expect(toc[0].parts).to.deep.equal([{ t: "NOTES-" }, { n: "1" }, { t: ".md" }]);
|
||||
expect(state.showGistToc()).to.equal(true);
|
||||
state.activeAnchor = "file-1-a";
|
||||
expect(state.activeFileIndex()).to.equal(0);
|
||||
state.details.files.pop();
|
||||
expect(state.showGistToc()).to.equal(false);
|
||||
scope.stop();
|
||||
});
|
||||
|
||||
it("chooses the explorer viewer for each gist file and a source language", () => {
|
||||
const kind = (file) => pages.gistFileKind(file);
|
||||
expect(kind({ filename: "a.md", content: "# x" })).to.equal("markdown");
|
||||
expect(kind({ filename: "notes", language: "Markdown", content: "x" })).to.equal("markdown");
|
||||
expect(kind({ filename: "a.ipynb", content: "{}" })).to.equal("notebook");
|
||||
expect(kind({ filename: "a.tsv", content: "a\tb" })).to.equal("csv");
|
||||
expect(kind({ filename: "a.csv", content: "x".repeat(1024 * 1024 + 1) })).to.equal("code");
|
||||
expect(kind({ filename: "a.svg", content: "<svg/>" })).to.equal("svg");
|
||||
expect(kind({ filename: "a.py", content: "x" })).to.equal("code");
|
||||
expect(kind({ filename: "a.png", encoding: "base64", content: "AA==" })).to.equal("image");
|
||||
expect(kind({ filename: "a.pdf", encoding: "base64", content: "AA==" })).to.equal("pdf");
|
||||
expect(kind({ filename: "a.webm", encoding: "base64", content: "AA==" })).to.equal("video");
|
||||
expect(kind({ filename: "a.mp3", encoding: "base64", content: "AA==" })).to.equal("audio");
|
||||
expect(kind({ filename: "a.bin", encoding: "base64", content: "AA==" })).to.equal("binary");
|
||||
expect(kind({ filename: "a.png", encoding: "base64", hidden: true })).to.equal("hidden");
|
||||
expect(kind({ filename: "a.bin", encoding: "base64", tooLarge: true })).to.equal("too-large");
|
||||
expect(kind({ filename: "a.txt", content: "" })).to.equal("empty");
|
||||
expect(["markdown", "notebook", "csv", "svg", "code", "image"].map(pages.hasRenderedView)).to.deep.equal([true, true, true, true, false, false]);
|
||||
expect(pages.gistSourceLanguage({ filename: "a.ipynb" }, "notebook")).to.equal("json");
|
||||
expect(pages.gistSourceLanguage({ filename: "a.py", language: "Python" }, "code")).to.equal("Python");
|
||||
});
|
||||
|
||||
it("parses quoted CSV cells with the explorer's parser", () => {
|
||||
expect(formatters.parseDelimited('a,"b ""q"", c"\r\n1,2\n', ",")).to.deep.equal([["a", 'b "q", c'], ["1", "2"]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,259 @@
|
||||
const { expect } = require("chai");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const load = (name) => import(pathToFileURL(path.join(__dirname, "../public/script", name)).href);
|
||||
|
||||
describe("Table analysis", function () {
|
||||
let T, chart, formatters;
|
||||
before(async () => {
|
||||
T = await load("table-analysis.js");
|
||||
chart = await load("table-chart.js");
|
||||
formatters = await load("formatters.js");
|
||||
});
|
||||
const table = (text, sep = ",") => T.analyzeTable(formatters.parseDelimited(text, sep));
|
||||
const all = (t) => [...Array(t.size).keys()];
|
||||
const RESULTS = "model,seed,accuracy,plausible\nBaseline,1,71.0,410\nBaseline,2,71.4,414\n+ Aug.,1,73.8,445\n+ Aug.,2,74.2,449\nOurs,1,78.7,501\nOurs,2,79.1,\n";
|
||||
|
||||
describe("numeric parsing", () => {
|
||||
it("reads grouped thousands, percents, exponents, signs and the Unicode minus", () => {
|
||||
expect(["1,234", "12%", "1e-3", "-0.5", "+3", "−2", ".5", " 7 ", "1,234.5"].map(T.parseNumber)).to.deep.equal([1234, 12, 0.001, -0.5, 3, -2, 0.5, 7, 1234.5]);
|
||||
});
|
||||
it("rejects text, misplaced separators and bare signs", () => {
|
||||
expect(["1,2", "12,34", "abc", "-", "", "1.2.3", "0x10", "Infinity", "12 %"].map(T.parseNumber)).to.deep.equal([null, null, null, null, null, null, null, null, null]);
|
||||
});
|
||||
it("counts decimals as written, including exponents", () => {
|
||||
expect(["78.90", "1e-3", "1.38e-3", "12", "2.5e2", "0.3"].map(T.decimalsOf)).to.deep.equal([2, 3, 5, 0, 0, 1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("type detection", () => {
|
||||
it("detects numbers, dates and text, ignoring empty and NA cells", () => {
|
||||
expect(T.detectType(["1", "2.5", "", "NA", "1,000"])).to.equal("number");
|
||||
expect(T.detectType(["2026-03-01", "2026-03-02T10:00Z", "", "Mar 3, 2026"])).to.equal("date");
|
||||
expect(T.detectType(["Baseline", "12"])).to.equal("text");
|
||||
expect(T.detectType(["03/01/2026", "04/01/2026"])).to.equal("text");
|
||||
expect(T.detectType(["", ""])).to.equal("text");
|
||||
});
|
||||
it("keeps a column's precision, unit and scientific notation", () => {
|
||||
const t = table("a,b,c,d\n1,12%,1.38e-3,x\n2.25,8%,2.1e-4,y\n");
|
||||
expect(t.columns.map((c) => [c.type, c.decimals, c.unit])).to.deep.equal([["number", 2, ""], ["number", 0, "%"], ["number", 5, ""], ["text", 0, ""]]);
|
||||
expect(t.columns[2].scientific).to.equal(2);
|
||||
expect(T.summarize(t.columns[2], all(t), "mean").text).to.equal("7.950e-4");
|
||||
expect(T.summarize(t.columns[1], all(t), "mean").text).to.equal("10.0%");
|
||||
});
|
||||
it("parses unambiguous dates only", () => {
|
||||
expect(T.parseDate("2026-03-01")).to.equal(Date.UTC(2026, 2, 1));
|
||||
expect(T.parseDate("2026/3/1 10:30")).to.equal(Date.UTC(2026, 2, 1, 10, 30));
|
||||
expect(T.parseDate("1 March 2026")).to.equal(Date.UTC(2026, 2, 1));
|
||||
expect(T.parseDate("2026-13-01")).to.equal(null);
|
||||
expect(T.parseDate("03/01/2026")).to.equal(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("aggregates", () => {
|
||||
const keys = [3, null, 1, 4, 1, 5];
|
||||
const rows = [0, 1, 2, 3, 4, 5];
|
||||
it("skips empty cells", () => {
|
||||
expect(T.aggregate(keys, rows, "count")).to.equal(5);
|
||||
expect(T.aggregate(keys, rows, "sum")).to.equal(14);
|
||||
expect(T.aggregate(keys, rows, "mean")).to.equal(2.8);
|
||||
expect(T.aggregate(keys, rows, "min")).to.equal(1);
|
||||
expect(T.aggregate(keys, rows, "max")).to.equal(5);
|
||||
});
|
||||
it("computes the median for odd and even counts", () => {
|
||||
expect(T.aggregate(keys, rows, "median")).to.equal(3);
|
||||
expect(T.aggregate([4, 1, 3, 2], [0, 1, 2, 3], "median")).to.equal(2.5);
|
||||
});
|
||||
it("uses the sample standard deviation and needs two values", () => {
|
||||
expect(T.aggregate([2, 4, 4, 4, 5, 5, 7, 9], [0, 1, 2, 3, 4, 5, 6, 7], "std")).to.be.closeTo(2.138, 1e-3);
|
||||
expect(T.aggregate([5, null], [0, 1], "std")).to.equal(null);
|
||||
expect(T.aggregate([null], [0], "mean")).to.equal(null);
|
||||
expect(T.aggregate([null], [0], "count")).to.equal(0);
|
||||
});
|
||||
it("formats a summary with the column's precision, over the given rows only", () => {
|
||||
const t = table(RESULTS);
|
||||
expect(T.summarize(t.columns[2], all(t), "mean").text).to.equal("74.7");
|
||||
expect(T.summarize(t.columns[2], [0, 1], "mean").text).to.equal("71.2");
|
||||
expect(T.summarize(t.columns[3], all(t), "mean").text).to.equal("443.8");
|
||||
expect(T.summarize(t.columns[3], all(t), "count").text).to.equal("5");
|
||||
expect(T.summarize(t.columns[3], all(t), "sum").text).to.equal("2,219");
|
||||
// Text columns count distinct values; identifier columns stay empty.
|
||||
expect(T.summarize(t.columns[0], all(t)).text).to.equal("3 distinct");
|
||||
expect(T.summarize(t.columns[1], all(t), "mean").kind).to.equal("none");
|
||||
expect(T.summarize(t.columns[1], all(t), "mean", () => true).text).to.equal("1.5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("identifier columns", () => {
|
||||
const ids = (text) => table(text).columns.map((c) => c.identifier);
|
||||
it("recognizes seed, id, run, fold, index and year by name", () => {
|
||||
expect(ids("seed,run_id,fold,index,year,Trial,accuracy\n1,10,0,5,2024,3,71.2\n2,11,1,6,2025,4,71.4\n")).to.deep.equal([true, true, true, true, true, true, false]);
|
||||
expect(ids("modelId,seeds,n_runs\n4,1,7\n9,2,8\n")).to.deep.equal([true, true, true]);
|
||||
});
|
||||
it("recognizes small consecutive whole numbers that repeat across rows", () => {
|
||||
expect(ids("k,v\n1,5\n2,9\n3,4\n1,7\n2,2\n3,1\n")).to.deep.equal([true, false]);
|
||||
expect(ids("k\n0\n1\n0\n1\n")).to.deep.equal([true]);
|
||||
});
|
||||
it("leaves measures alone: decimals, percents, gaps, big ranges, negatives, unique values", () => {
|
||||
expect(ids("a,b,c,d,e\n1.0,1%,1,410,-1\n2.0,2%,3,414,0\n1.0,1%,1,445,-1\n2.0,2%,3,449,0\n")).to.deep.equal([false, false, false, false, false]);
|
||||
expect(ids("epochs,plausible\n10,410\n20,414\n")).to.deep.equal([false, false]);
|
||||
expect(ids("seed,name\nx,y\n")).to.deep.equal([false, false]);
|
||||
expect(ids("seed\n1.5\n2.5\n")).to.deep.equal([false]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sorting", () => {
|
||||
it("sorts numbers numerically and keeps empty cells last in both directions", () => {
|
||||
const t = table("k,v\na,10\nb,\nc,9\nd,-1\ne,1e1\n");
|
||||
expect(T.sortIndices(t, all(t), 1, "asc")).to.deep.equal([3, 2, 0, 4, 1]);
|
||||
expect(T.sortIndices(t, all(t), 1, "desc")).to.deep.equal([0, 4, 2, 3, 1]);
|
||||
});
|
||||
it("is stable: ties keep their current order", () => {
|
||||
const t = table(RESULTS);
|
||||
expect(T.sortIndices(t, all(t), 0, "asc")).to.deep.equal([2, 3, 0, 1, 4, 5]);
|
||||
const bySeed = T.sortIndices(t, all(t), 1, "desc");
|
||||
expect(bySeed).to.deep.equal([1, 3, 5, 0, 2, 4]);
|
||||
expect(T.sortIndices(t, bySeed, 0, "asc")).to.deep.equal([3, 2, 1, 0, 5, 4]);
|
||||
});
|
||||
it("sorts text naturally and dates chronologically", () => {
|
||||
const t = table("name,date\nrun 10,Mar 3 2026\nrun 2,2026-03-01\nRun 1,2026-02-28\n");
|
||||
expect(T.sortIndices(t, all(t), 0, "asc")).to.deep.equal([2, 1, 0]);
|
||||
expect(t.columns[1].type).to.equal("date");
|
||||
expect(T.sortIndices(t, all(t), 1, "desc")).to.deep.equal([0, 1, 2]);
|
||||
const d = table("date\n2026-03-10\n2026-02-28\n2026-03-01\n");
|
||||
expect(T.sortIndices(d, all(d), 0, "asc")).to.deep.equal([1, 2, 0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filtering", () => {
|
||||
it("combines the search box, numeric ranges and value sets", () => {
|
||||
const t = table(RESULTS);
|
||||
expect(T.filterIndices(t, { query: "aug" })).to.deep.equal([2, 3]);
|
||||
expect(T.filterIndices(t, { ranges: { 2: [74, null] } })).to.deep.equal([3, 4, 5]);
|
||||
expect(T.filterIndices(t, { ranges: { 3: [null, 450] } })).to.deep.equal([0, 1, 2, 3]);
|
||||
expect(T.filterIndices(t, { values: { 0: ["Ours", "Baseline"] }, ranges: { 1: [2, 2] } })).to.deep.equal([1, 5]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("grouping", () => {
|
||||
it("reproduces the mean per model over seeds", () => {
|
||||
const t = table(RESULTS);
|
||||
const g = T.groupTable(t, all(t), 0, "mean");
|
||||
expect(g.header).to.deep.equal(["model", "Rows", "accuracy", "plausible"]);
|
||||
expect(g.body).to.deep.equal([["Baseline", "2", "71.2", "412.0"], ["+ Aug.", "2", "74.0", "447.0"], ["Ours", "2", "78.9", "501.0"]]);
|
||||
// "Treat as number" brings the seed back.
|
||||
expect(T.groupTable(t, all(t), 0, "mean", () => true).header).to.deep.equal(["model", "Rows", "seed", "accuracy", "plausible"]);
|
||||
expect(g.columns[2].agg).to.equal("mean");
|
||||
expect(g.columns[2].keys[0]).to.be.closeTo(71.2, 1e-9);
|
||||
});
|
||||
it("groups only the filtered rows and can be sorted, counted and exported", () => {
|
||||
const t = table(RESULTS);
|
||||
const g = T.groupTable(t, T.filterIndices(t, { ranges: { 1: [1, 1] } }), 0, "max");
|
||||
expect(g.body.map((r) => r[0])).to.deep.equal(["Baseline", "+ Aug.", "Ours"]);
|
||||
const order = T.sortIndices(g, [0, 1, 2], 2, "desc");
|
||||
expect(order.map((i) => g.body[i][0])).to.deep.equal(["Ours", "+ Aug.", "Baseline"]);
|
||||
expect(T.toMarkdown(g.header, order.map((i) => g.body[i]), g.columns.map((c) => c.type === "number")).split("\n")[1]).to.equal("| --- | ---: | ---: | ---: |");
|
||||
});
|
||||
it("labels empty groups", () => {
|
||||
const t = table("k,v\na,1\n,2\na,3\n");
|
||||
expect(T.groupTable(t, all(t), 0, "sum").body).to.deep.equal([["a", "2", "4"], ["(empty)", "1", "2"]]);
|
||||
});
|
||||
it("keeps 'none', 'NA' and '-' as categories in text columns", () => {
|
||||
const t = table("augmentation,acc\nnone,1\nflip,2\nnone,3\nNA,4\n-,5\n,6\n");
|
||||
expect(t.columns[0].type).to.equal("text");
|
||||
expect(t.columns[0].empty).to.equal(1);
|
||||
expect(T.groupTable(t, all(t), 0, "sum").body.map((r) => r[0])).to.deep.equal(["none", "flip", "NA", "-", "(empty)"]);
|
||||
// In a number column they still mean "no value".
|
||||
expect(table("v\n1\nNA\n-\n3\n").columns[0]).to.include({ type: "number", empty: 2 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("export", () => {
|
||||
it("quotes CSV cells only when needed and escapes Markdown pipes", () => {
|
||||
expect(T.toDelimited(["a", "b"], [["x,y", 'say "hi"'], ["plain", ""]])).to.equal('a,b\n"x,y","say ""hi"""\nplain,\n');
|
||||
expect(T.toMarkdown(["a|b"], [["c|d"]])).to.equal("| a\\|b |\n| --- |\n| c\\|d |\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shareable state", () => {
|
||||
it("round-trips through the fragment and stays empty by default", () => {
|
||||
expect(T.writeHashState("table", T.DEFAULT_STATE)).to.equal("");
|
||||
const state = { ...T.DEFAULT_STATE, view: "chart", group: "model", agg: "median", sort: { column: "accuracy", dir: "desc" }, values: { model: ["Ours", "+ Aug."] }, ranges: { accuracy: [70, null] }, sums: { accuracy: "std" }, chart: "bar", y: ["accuracy", "plausible"] };
|
||||
const hash = T.writeHashState("table-2", state);
|
||||
expect(hash).to.match(/^#table-2:view=chart&sort=accuracy:desc&group=model&agg=median/);
|
||||
const back = T.readHashState(hash, "table-2");
|
||||
expect(back).to.deep.include({ view: "chart", group: "model", agg: "median", chart: "bar" });
|
||||
expect(back.sort).to.deep.equal({ column: "accuracy", dir: "desc" });
|
||||
expect(back.values).to.deep.equal({ model: ["Ours", "+ Aug."] });
|
||||
expect(back.ranges).to.deep.equal({ accuracy: [70, null] });
|
||||
expect(back.y).to.deep.equal(["accuracy", "plausible"]);
|
||||
expect(T.readHashState(hash, "table")).to.equal(null);
|
||||
expect(T.readHashState("#L12", "table")).to.equal(null);
|
||||
expect(T.isTableHash("#L12")).to.equal(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("column stats and charts", () => {
|
||||
it("summarizes a column with a histogram", () => {
|
||||
const t = table(RESULTS);
|
||||
const s = T.columnStats(t.columns[3], all(t), 4);
|
||||
expect(s).to.include({ type: "number", count: 5, empty: 1, distinct: 5, min: 410, max: 501 });
|
||||
expect(s.histogram.map((b) => b.count)).to.deep.equal([2, 2, 0, 1]);
|
||||
expect(T.columnStats(t.columns[0], all(t)).top[0]).to.deep.equal(["+ Aug.", 2]);
|
||||
});
|
||||
it("defaults to a bar of the first measure by the first text column, skipping seeds", () => {
|
||||
const t = table(RESULTS);
|
||||
expect(chart.defaultChart(t, false)).to.deep.equal({ type: "bar", x: "model", y: ["accuracy"] });
|
||||
const g = T.groupTable(t, all(t), 0, "mean");
|
||||
expect(chart.defaultChart(g, true)).to.deep.equal({ type: "bar", x: "model", y: ["accuracy"] });
|
||||
});
|
||||
it("averages repeated categories in a bar chart and says so", () => {
|
||||
const t = table(RESULTS);
|
||||
const c = chart.buildChart(t, all(t), { type: "bar", x: "model", y: ["accuracy"], agg: "mean" }, { width: 600 });
|
||||
expect(c.categories.map((x) => x.label)).to.deep.equal(["Baseline", "+ Aug.", "Ours"]);
|
||||
expect(c.categories[2].tip.rows[0].value).to.equal("78.9");
|
||||
expect(c.notes[0]).to.equal("Average per model over 6 rows.");
|
||||
expect(c.marks.every((m) => m.h <= 24)).to.equal(true);
|
||||
});
|
||||
it("draws lines on a date axis in order and scatter points with their rows", () => {
|
||||
const t = table("date\tv\n2026-03-03\t3\n2026-03-01\t1\n2026-03-02\t2\n", "\t");
|
||||
const line = chart.buildChart(t, all(t), { type: "line", x: "date", y: ["v"] }, { width: 600 });
|
||||
expect(line.points.map((p) => p.title)).to.deep.equal(["date 2026-03-01", "date 2026-03-02", "date 2026-03-03"]);
|
||||
expect(line.series[0].path.startsWith("M")).to.equal(true);
|
||||
const scatter = chart.buildChart(t, all(t), { type: "scatter", x: "v", y: ["v"] }, { width: 600 });
|
||||
expect(scatter.series[0].dots).to.have.length(3);
|
||||
// An ID-like text x column is refused instead of measuring every label.
|
||||
const ids = table("id,v\n" + Array.from({ length: 200000 }, (_, i) => `row-${i},${i % 7}`).join("\n"));
|
||||
const many = chart.buildChart(ids, all(ids), { type: "scatter", x: "id", y: ["v"] }, { width: 600 });
|
||||
expect(many.empty).to.match(/200,000 different values/);
|
||||
});
|
||||
it("explains an empty chart", () => {
|
||||
const t = table(RESULTS);
|
||||
expect(chart.buildChart(t, [], { type: "bar", x: "model", y: ["accuracy"] }, { width: 600 }).empty).to.match(/No rows/);
|
||||
expect(chart.buildChart(t, all(t), { type: "bar", x: "model", y: [] }, { width: 600 }).empty).to.match(/numeric/);
|
||||
});
|
||||
it("picks round ticks", () => {
|
||||
expect(chart.niceTicks(0, 79.1, 5).ticks).to.deep.equal([0, 20, 40, 60, 80]);
|
||||
expect(chart.tickLabel(25000, 5000)).to.equal("25K");
|
||||
expect(chart.tickLabel(0.775, 0.025)).to.equal("0.775");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Markdown and notebook tables", () => {
|
||||
let dom;
|
||||
before(() => { dom = new JSDOM("<!doctype html><body></body>"); global.window = dom.window; });
|
||||
after(() => { delete global.window; dom.window.close(); });
|
||||
it("reads redaction chips and slots back as XXXX-n and the pandas header rows", async () => {
|
||||
const enhance = await load("table-enhance.js");
|
||||
const doc = dom.window.document;
|
||||
doc.body.innerHTML = '<table class="dataframe"><thead><tr><th></th><th>acc</th></tr><tr><th>model</th><th></th></tr></thead><tbody>'
|
||||
+ '<tr><th>Ours</th><td>78.9</td></tr><tr><th><mark class="redact-chip" data-term="XXXX-2"><i>2</i></mark></th><td>71.2</td></tr></tbody></table>';
|
||||
const data = enhance.tableData(doc.querySelector("table"));
|
||||
expect(data.rows).to.deep.equal([["model", "acc"], ["Ours", "78.9"], ["XXXX-2", "71.2"]]);
|
||||
doc.body.innerHTML = '<table><tr><td colspan="2">x</td></tr><tr><td>1</td><td>2</td></tr></table>';
|
||||
expect(enhance.tableData(doc.querySelector("table"))).to.equal(null);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,356 @@
|
||||
const { expect } = require("chai");
|
||||
const { createHmac, generateKeyPairSync } = require("crypto");
|
||||
const process = require("process");
|
||||
const { URL, URLSearchParams } = require("node:url");
|
||||
const express = require("express");
|
||||
const mongoose = require("mongoose");
|
||||
require("ts-node/register/transpile-only");
|
||||
const config = require("../src/config").default;
|
||||
const github = require("../src/core/GitHubUtils");
|
||||
const app = require("../src/core/github-app");
|
||||
const { setCredential } = require("../src/core/credentials");
|
||||
const list = require("../src/core/user-repository-list");
|
||||
const { UserRepositoryModel: Rows, UserRepositorySyncModel: Syncs } = require("../src/core/model/user-repositories");
|
||||
const Users = require("../src/core/model/users/users.model").default;
|
||||
const Credentials = require("../src/core/model/credentials/credentials.model").default;
|
||||
const Installations = require("../src/core/model/github-installation").default;
|
||||
const { githubAppWebhook, revokeGrant } = require("../src/server/routes/github-app");
|
||||
|
||||
const keys = JSON.stringify({ test: Buffer.alloc(32, 9).toString("base64") });
|
||||
const pem = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs8", format: "pem" });
|
||||
const repo = (id, name, extra = {}) => ({ id, full_name: name, private: id % 2 === 0, default_branch: "main",
|
||||
updated_at: "2026-01-01T00:00:00Z", pushed_at: "2026-01-02T00:00:00Z", ...extra });
|
||||
|
||||
const describeMongo = process.env.TEST_MONGODB_URI ? describe : describe.skip;
|
||||
describeMongo("stored repository picker list", function () {
|
||||
this.timeout(20000);
|
||||
let owner, other, previousConfig, previousOctokit, previousFetch, server, base, upstream, calls;
|
||||
before(async () => {
|
||||
previousConfig = { ...config };
|
||||
Object.assign(config, { GITHUB_APP_ENABLED: true, GITHUB_APP_ID: "123", GITHUB_APP_CLIENT_ID: "Iv.test",
|
||||
GITHUB_APP_PRIVATE_KEY: pem, CREDENTIAL_KEYS: keys, CREDENTIAL_ACTIVE_KEY_ID: "test",
|
||||
GITHUB_APP_WEBHOOK_SECRET: "webhook-secret" });
|
||||
await mongoose.connect(process.env.TEST_MONGODB_URI, { dbName: "repo_list_test_" + Date.now() });
|
||||
await Promise.all([Rows, Syncs, Credentials, Installations].map(m => m.createIndexes()));
|
||||
const api = express();
|
||||
api.use("/github/app/webhook", githubAppWebhook);
|
||||
api.use((req, _res, next) => {
|
||||
req.user = { user: owner };
|
||||
req.isAuthenticated = () => true;
|
||||
req.logout = done => done();
|
||||
next();
|
||||
});
|
||||
api.use("/api/user", require("../src/server/routes/user").default);
|
||||
server = await new Promise(resolve => { const s = api.listen(0, "127.0.0.1", () => resolve(s)); });
|
||||
base = `http://127.0.0.1:${server.address().port}`;
|
||||
previousOctokit = github.octokit;
|
||||
previousFetch = globalThis.fetch;
|
||||
});
|
||||
after(async () => {
|
||||
github.octokit = previousOctokit;
|
||||
globalThis.fetch = previousFetch;
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
await mongoose.connection.dropDatabase();
|
||||
await mongoose.disconnect();
|
||||
Object.assign(config, previousConfig);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await list.settleRepositorySyncs();
|
||||
await Promise.all([Rows, Syncs, Users, Credentials, Installations].map(m => m.deleteMany({})));
|
||||
owner = await Users.create({ username: "owner", externalIDs: { github: "10" } });
|
||||
other = await Users.create({ username: "other", externalIDs: { github: "11" } });
|
||||
calls = [];
|
||||
// OAuth: GitHub /user/repos pages of 100, sorted by name.
|
||||
upstream = Array.from({ length: 250 }, (_, i) => repo(1000 + i, `org/repo-${String(i).padStart(3, "0")}`));
|
||||
github.octokit = () => ({ request: async (route, params) => {
|
||||
calls.push(params.page);
|
||||
const data = upstream.slice((params.page - 1) * 100, params.page * 100);
|
||||
const more = params.page * 100 < upstream.length;
|
||||
return { data, headers: more ? { link: '<https://api.github.com/user/repos?page=2>; rel="next"' } : {} };
|
||||
} });
|
||||
globalThis.fetch = previousFetch;
|
||||
});
|
||||
afterEach(async () => { await list.settleRepositorySyncs(); });
|
||||
|
||||
const picker = async (params = {}) => {
|
||||
const response = await previousFetch(`${base}/api/user/repository_picker?${new URLSearchParams(params)}`);
|
||||
return { status: response.status, body: await response.json() };
|
||||
};
|
||||
function webhook(event, payload, secret = "webhook-secret") {
|
||||
const body = JSON.stringify(payload);
|
||||
return previousFetch(base + "/github/app/webhook", { method: "POST", body, headers: {
|
||||
"Content-Type": "application/json", "X-GitHub-Event": event,
|
||||
"X-Hub-Signature-256": "sha256=" + createHmac("sha256", secret).update(body).digest("hex") } });
|
||||
}
|
||||
// GitHub App upstream: installations and their repositories, plus the installation check.
|
||||
function mockApp(installations) {
|
||||
globalThis.fetch = async (url, options) => {
|
||||
if (String(url).startsWith(base)) return previousFetch(url, options);
|
||||
const path = new URL(String(url)).pathname;
|
||||
calls.push(path);
|
||||
let body;
|
||||
const listed = /^\/user\/installations\/(\d+)\/repositories$/.exec(path);
|
||||
if (path === "/user/installations") body = { installations: Object.keys(installations).map(id => ({ id: Number(id), app_id: 123, suspended_at: null, account: { id: 10, login: "owner", type: "User" }, permissions: {} })) };
|
||||
else if (listed) body = { repositories: installations[listed[1]] || [] };
|
||||
else if (/^\/app\/installations\/\d+$/.test(path)) body = { id: Number(path.split("/").pop()), app_id: 123, suspended_at: null, account: { id: 10, login: "owner", type: "User" } };
|
||||
else return new globalThis.Response("{}", { status: 404 });
|
||||
return new globalThis.Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
|
||||
};
|
||||
}
|
||||
const grantApp = ownerId => app.saveAppGrant(ownerId, { access_token: "ghu_" + ownerId, refresh_token: "ghr", expires_in: 3600, refresh_token_expires_in: 100000 });
|
||||
const names = async ownerId => (await Rows.find({ ownerId: String(ownerId) }).sort({ nameKey: 1 }).lean()).map(r => r.fullName);
|
||||
|
||||
it("fetches an empty list once, then pages and searches from MongoDB", async () => {
|
||||
await setCredential(owner.id, "oauth-token");
|
||||
const first = await picker();
|
||||
expect(first.status).to.equal(200);
|
||||
expect(first.body.items).to.have.length(20);
|
||||
expect(first.body.items[0]).to.deep.equal({ id: 1000, fullName: "org/repo-000", private: true });
|
||||
expect(first.body.nextCursor).to.equal(20);
|
||||
expect(first.body.webhooks).to.equal(false);
|
||||
await list.settleRepositorySyncs();
|
||||
expect(calls).to.deep.equal([1, 2, 3]);
|
||||
expect(await Rows.countDocuments({ ownerId: owner.id, connection: "oauth" })).to.equal(250);
|
||||
const stored = await Rows.findOne({ repositoryId: 1001 }).lean();
|
||||
expect(stored).to.include({ fullName: "org/repo-001", private: false, defaultBranch: "main", connection: "oauth" });
|
||||
expect(stored.pushedAt.toISOString()).to.equal("2026-01-02T00:00:00.000Z");
|
||||
|
||||
calls = [];
|
||||
const page = await picker({ cursor: 240 });
|
||||
expect(page.body.items.map(r => r.fullName)).to.deep.equal(Array.from({ length: 10 }, (_, i) => `org/repo-${240 + i}`));
|
||||
expect(page.body.nextCursor).to.equal(null);
|
||||
expect(page.body.syncedAt).to.be.a("string");
|
||||
const search = await picker({ q: "REPO-12" });
|
||||
expect(search.body.items.map(r => r.fullName)).to.deep.equal([...Array.from({ length: 10 }, (_, i) => `org/repo-12${i}`)]);
|
||||
// Regex characters are literal.
|
||||
expect((await picker({ q: "repo.01" })).body.items).to.deep.equal([]);
|
||||
expect(calls).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("returns the first page of a large account before pagination finishes", async () => {
|
||||
await setCredential(owner.id, "oauth-token");
|
||||
let release;
|
||||
const gate = new Promise(resolve => { release = resolve; });
|
||||
const original = github.octokit;
|
||||
github.octokit = token => ({ request: async (route, params) => {
|
||||
if (params.page > 1) await gate;
|
||||
return original(token).request(route, params);
|
||||
} });
|
||||
const first = await picker();
|
||||
expect(first.body.items).to.have.length(20);
|
||||
expect(first.body.nextCursor).to.equal(20);
|
||||
expect(first.body.syncing).to.equal(true);
|
||||
expect(first.body.syncedAt).to.equal(null);
|
||||
// A second request while the sync runs does not start another one.
|
||||
expect((await picker()).body.syncing).to.equal(true);
|
||||
release();
|
||||
await list.settleRepositorySyncs();
|
||||
expect(calls).to.deep.equal([1, 2, 3]);
|
||||
const done = await picker();
|
||||
expect(done.body.syncing).to.equal(false);
|
||||
expect(await Rows.countDocuments()).to.equal(250);
|
||||
});
|
||||
|
||||
it("runs one sync per list even when requests arrive together", async () => {
|
||||
await setCredential(owner.id, "oauth-token");
|
||||
const results = await Promise.all([picker(), picker(), picker()]);
|
||||
await list.settleRepositorySyncs();
|
||||
expect(calls.filter(page => page === 1)).to.have.length(1);
|
||||
expect(results.every(r => r.status === 200)).to.equal(true);
|
||||
// A lock held by another process blocks this one until it expires.
|
||||
await Syncs.updateOne({ ownerId: owner.id }, { $set: { lockId: "elsewhere", lockUntil: new Date(Date.now() + 60000) } });
|
||||
expect(await list.startRepositorySync(owner.id, "oauth")).to.equal(null);
|
||||
await Syncs.updateOne({ ownerId: owner.id }, { $set: { lockUntil: new Date(Date.now() - 1) } });
|
||||
expect(await list.startRepositorySync(owner.id, "oauth")).to.have.property("first");
|
||||
});
|
||||
|
||||
it("refreshes only when forced, and drops repositories that disappeared", async () => {
|
||||
await setCredential(owner.id, "oauth-token");
|
||||
await picker();
|
||||
await list.settleRepositorySyncs();
|
||||
upstream = [repo(1, "new/one"), ...upstream.slice(1)];
|
||||
calls = [];
|
||||
await picker();
|
||||
expect(calls).to.deep.equal([]);
|
||||
// A forced refresh right after a sync is ignored.
|
||||
await picker({ force: "1" });
|
||||
expect(calls).to.deep.equal([]);
|
||||
await Syncs.updateOne({ ownerId: owner.id }, { $set: { syncedAt: new Date(Date.now() - 60000) } });
|
||||
const forced = await picker({ force: "1" });
|
||||
expect(forced.status).to.equal(200);
|
||||
await list.settleRepositorySyncs();
|
||||
expect(calls).to.deep.equal([1, 2, 3]);
|
||||
const stored = await names(owner.id);
|
||||
expect(stored).to.include("new/one");
|
||||
expect(stored).not.to.include("org/repo-000");
|
||||
expect(stored).to.have.length(250);
|
||||
});
|
||||
|
||||
it("resyncs a list older than 12 hours in the background", async () => {
|
||||
await setCredential(owner.id, "oauth-token");
|
||||
await picker();
|
||||
await list.settleRepositorySyncs();
|
||||
calls = [];
|
||||
await Syncs.updateOne({ ownerId: owner.id }, { $set: { syncedAt: new Date(Date.now() - 11 * 3600_000) } });
|
||||
await picker();
|
||||
await list.settleRepositorySyncs();
|
||||
expect(calls).to.deep.equal([]);
|
||||
await Syncs.updateOne({ ownerId: owner.id }, { $set: { syncedAt: new Date(Date.now() - 13 * 3600_000) } });
|
||||
expect((await picker()).status).to.equal(200);
|
||||
await list.settleRepositorySyncs();
|
||||
expect(calls).to.deep.equal([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("pauses after a rate limit instead of retrying on every load", async () => {
|
||||
await setCredential(owner.id, "oauth-token");
|
||||
github.octokit = () => ({ request: async () => {
|
||||
calls.push("limited");
|
||||
const error = new Error("API rate limit exceeded");
|
||||
error.status = 403;
|
||||
error.response = { headers: { "x-ratelimit-remaining": "0", "retry-after": "120" } };
|
||||
throw error;
|
||||
} });
|
||||
expect((await picker()).status).to.equal(429);
|
||||
await list.settleRepositorySyncs();
|
||||
const state = await Syncs.findOne({ ownerId: owner.id }).lean();
|
||||
expect(state.error).to.equal("github_rate_limit_exceeded");
|
||||
expect(state.retryAfter.getTime()).to.be.greaterThan(Date.now() + 100000);
|
||||
expect((await picker({ force: "1" })).status).to.equal(429);
|
||||
expect(calls).to.deep.equal(["limited"]);
|
||||
});
|
||||
|
||||
it("lists App installations and keeps OAuth and App lists apart", async () => {
|
||||
await setCredential(owner.id, "oauth-token");
|
||||
await grantApp(owner.id);
|
||||
mockApp({ 4: [repo(7, "owner/app-repo")], 5: [repo(8, "acme/lab")] });
|
||||
// The first installation's page answers at once; the next one follows.
|
||||
expect((await picker({ connection: "github-app" })).body.items.map(r => r.fullName)).to.deep.equal(["owner/app-repo"]);
|
||||
await list.settleRepositorySyncs();
|
||||
const result = await picker({ connection: "github-app" });
|
||||
expect(result.body.items.map(r => r.fullName)).to.deep.equal(["acme/lab", "owner/app-repo"]);
|
||||
expect(result.body.webhooks).to.equal(true);
|
||||
expect((await Rows.findOne({ repositoryId: 8 }).lean()).installationId).to.equal(5);
|
||||
expect(await Rows.countDocuments({ connection: "oauth" })).to.equal(0);
|
||||
expect((await picker()).body.items[0].fullName).to.equal("org/repo-000");
|
||||
await list.settleRepositorySyncs();
|
||||
await revokeGrant(owner.id, "github-app-user");
|
||||
expect(await Rows.countDocuments({ connection: "github-app" })).to.equal(0);
|
||||
expect(await Rows.countDocuments({ connection: "oauth" })).to.equal(250);
|
||||
expect((await picker({ connection: "github-app" })).status).to.equal(401);
|
||||
});
|
||||
|
||||
describe("GitHub App webhooks", () => {
|
||||
beforeEach(async () => {
|
||||
await grantApp(owner.id);
|
||||
await grantApp(other.id);
|
||||
mockApp({ 4: [repo(7, "owner/seven"), repo(9, "owner/nine")], 6: [repo(70, "acme/shared")] });
|
||||
await picker({ connection: "github-app" });
|
||||
await list.settleRepositorySyncs();
|
||||
await Rows.insertMany([
|
||||
{ ownerId: other.id, connection: "github-app", repositoryId: 7, fullName: "owner/seven", nameKey: "owner/seven", installationId: 4, syncedAt: new Date() },
|
||||
]);
|
||||
await Syncs.create({ ownerId: other.id, connection: "github-app", syncedAt: new Date() });
|
||||
calls = [];
|
||||
});
|
||||
|
||||
it("rejects unsigned or forged deliveries without changing lists", async () => {
|
||||
const payload = { action: "deleted", installation: { id: 4, app_id: 123 } };
|
||||
expect((await webhook("installation", payload, "wrong-secret")).status).to.equal(401);
|
||||
expect(await Rows.countDocuments({ installationId: 4 })).to.equal(3);
|
||||
});
|
||||
|
||||
it("adds and removes selected repositories idempotently", async () => {
|
||||
const added = { action: "added", installation: { id: 4, app_id: 123, account: { id: 10, type: "User" } },
|
||||
sender: { id: 10 }, repository_selection: "selected", repositories_added: [{ id: 12, full_name: "owner/twelve", private: true }] };
|
||||
expect((await webhook("installation_repositories", added)).status).to.equal(204);
|
||||
expect((await webhook("installation_repositories", added)).status).to.equal(204);
|
||||
expect(await Rows.countDocuments({ repositoryId: 12, ownerId: owner.id })).to.equal(1);
|
||||
// Another installation user is not told about a private repository; they resync instead.
|
||||
expect(await Rows.countDocuments({ repositoryId: 12, ownerId: other.id })).to.equal(0);
|
||||
expect((await Syncs.findOne({ ownerId: other.id }).lean()).needsSyncAt).to.be.instanceOf(Date);
|
||||
expect((await Syncs.findOne({ ownerId: owner.id }).lean()).needsSyncAt).to.equal(undefined);
|
||||
const search = await picker({ connection: "github-app", q: "twelve" });
|
||||
expect(search.body.items).to.deep.equal([{ id: 12, fullName: "owner/twelve", private: true }]);
|
||||
|
||||
const removed = { action: "removed", installation: { id: 4, app_id: 123 }, sender: { id: 10 },
|
||||
repositories_removed: [{ id: 7, full_name: "owner/seven" }, { id: 12, full_name: "owner/twelve" }] };
|
||||
expect((await webhook("installation_repositories", removed)).status).to.equal(204);
|
||||
expect((await webhook("installation_repositories", removed)).status).to.equal(204);
|
||||
expect(await names(owner.id)).to.deep.equal(["acme/shared", "owner/nine"]);
|
||||
expect(await names(other.id)).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("removes an uninstalled installation's repositories and hides suspended ones", async () => {
|
||||
const suspend = { action: "suspend", installation: { id: 6, app_id: 123 } };
|
||||
expect((await webhook("installation", suspend)).status).to.equal(204);
|
||||
expect((await picker({ connection: "github-app" })).body.items.map(r => r.fullName)).to.deep.equal(["owner/nine", "owner/seven"]);
|
||||
expect((await webhook("installation", { action: "unsuspend", installation: { id: 6, app_id: 123 } })).status).to.equal(204);
|
||||
expect((await Syncs.findOne({ ownerId: owner.id }).lean()).needsSyncAt).to.be.instanceOf(Date);
|
||||
await list.settleRepositorySyncs();
|
||||
expect((await picker({ connection: "github-app" })).body.items.map(r => r.fullName)).to.include("acme/shared");
|
||||
await list.settleRepositorySyncs();
|
||||
|
||||
const deleted = { action: "deleted", installation: { id: 4, app_id: 123 } };
|
||||
expect((await webhook("installation", deleted)).status).to.equal(204);
|
||||
expect((await webhook("installation", deleted)).status).to.equal(204);
|
||||
expect(await names(owner.id)).to.deep.equal(["acme/shared"]);
|
||||
expect(await names(other.id)).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("stores a new installation's repositories for the user who installed it", async () => {
|
||||
const created = { action: "created", installation: { id: 8, app_id: 123, account: { id: 99, type: "Organization" } },
|
||||
sender: { id: 11 }, repositories: [{ id: 80, full_name: "neworg/tool", private: false }] };
|
||||
expect((await webhook("installation", created)).status).to.equal(204);
|
||||
expect(await names(other.id)).to.deep.equal(["neworg/tool", "owner/seven"]);
|
||||
expect((await Rows.findOne({ repositoryId: 80 }).lean()).installationId).to.equal(8);
|
||||
expect(await Rows.countDocuments({ repositoryId: 80, ownerId: owner.id })).to.equal(0);
|
||||
expect((await Syncs.findOne({ ownerId: other.id }).lean()).needsSyncAt).to.be.instanceOf(Date);
|
||||
});
|
||||
|
||||
it("follows repository renames, visibility changes and deletions", async () => {
|
||||
const renamed = { action: "renamed", installation: { id: 4 }, sender: { id: 10 },
|
||||
repository: repo(7, "owner/seven-renamed", { private: false, updated_at: "2026-02-01T00:00:00Z" }) };
|
||||
expect((await webhook("repository", renamed)).status).to.equal(204);
|
||||
expect(await names(owner.id)).to.include("owner/seven-renamed");
|
||||
expect(await names(other.id)).to.deep.equal(["owner/seven-renamed"]);
|
||||
// A delayed older delivery does not undo the rename.
|
||||
const stale = { ...renamed, repository: repo(7, "owner/seven-old", { updated_at: "2026-01-15T00:00:00Z" }) };
|
||||
expect((await webhook("repository", stale)).status).to.equal(204);
|
||||
expect(await names(other.id)).to.deep.equal(["owner/seven-renamed"]);
|
||||
|
||||
const privatized = { action: "privatized", installation: { id: 4 }, sender: { id: 10 },
|
||||
repository: repo(7, "owner/seven-renamed", { private: true, updated_at: "2026-02-02T00:00:00Z" }) };
|
||||
expect((await webhook("repository", privatized)).status).to.equal(204);
|
||||
expect((await Rows.findOne({ ownerId: other.id, repositoryId: 7 }).lean()).private).to.equal(true);
|
||||
expect((await Syncs.findOne({ ownerId: other.id }).lean()).needsSyncAt).to.be.instanceOf(Date);
|
||||
|
||||
const created = { action: "created", installation: { id: 4 }, sender: { id: 10 }, repository: repo(15, "owner/fresh") };
|
||||
expect((await webhook("repository", created)).status).to.equal(204);
|
||||
expect(await names(owner.id)).to.include("owner/fresh");
|
||||
expect(await Rows.countDocuments({ repositoryId: 15, ownerId: other.id })).to.equal(0);
|
||||
|
||||
const deleted = { action: "deleted", installation: { id: 4 }, sender: { id: 10 }, repository: repo(7, "owner/seven-renamed") };
|
||||
expect((await webhook("repository", deleted)).status).to.equal(204);
|
||||
expect((await webhook("repository", deleted)).status).to.equal(204);
|
||||
expect(await Rows.countDocuments({ repositoryId: 7 })).to.equal(0);
|
||||
expect(calls.filter(c => c.startsWith("/user/"))).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("lets a sync keep rows a webhook wrote while it ran", async () => {
|
||||
let release;
|
||||
const gate = new Promise(resolve => { release = resolve; });
|
||||
const fetchApp = globalThis.fetch;
|
||||
globalThis.fetch = async (url, options) => {
|
||||
if (String(url).includes("/user/installations/6/repositories")) await gate;
|
||||
return fetchApp(url, options);
|
||||
};
|
||||
await Syncs.updateOne({ ownerId: owner.id }, { $set: { syncedAt: new Date(Date.now() - 60000) } });
|
||||
await picker({ connection: "github-app", force: "1" });
|
||||
await webhook("installation_repositories", { action: "added", installation: { id: 4, app_id: 123, account: { id: 10, type: "User" } },
|
||||
sender: { id: 10 }, repositories_added: [{ id: 13, full_name: "owner/during", private: false }] });
|
||||
release();
|
||||
await list.settleRepositorySyncs();
|
||||
expect(await names(owner.id)).to.include("owner/during");
|
||||
});
|
||||
});
|
||||
});
|
||||
+477
-6
@@ -449,13 +449,16 @@ describe("Vue 3 UI", function () {
|
||||
},
|
||||
});
|
||||
const picker = () => ui.window.document.querySelector(".repo-picker");
|
||||
const button = text => [...picker().querySelectorAll("button")].find(b => b.textContent.trim() === text);
|
||||
const button = label => picker().querySelector(`button[aria-label="${label}"]`);
|
||||
expect(picker().textContent).to.include("repo-0");
|
||||
expect(button("Previous").disabled).to.equal(true);
|
||||
button("Next").click();
|
||||
// Page 1 has no Previous button; the pager is the footer's compact icon pair.
|
||||
expect(button("Previous page")).to.equal(null);
|
||||
expect(picker().querySelector(".repo-picker-foot .repo-picker-pagination")).to.not.equal(null);
|
||||
button("Next page").click();
|
||||
await delay(30);
|
||||
expect(picker().textContent).to.include("repo-20");
|
||||
button("Previous").click();
|
||||
expect(button("Previous page").disabled).to.equal(false);
|
||||
button("Previous page").click();
|
||||
await delay(30);
|
||||
expect(picker().textContent).to.include("repo-0");
|
||||
await ui.input(".repo-picker-filter", "needle");
|
||||
@@ -1099,9 +1102,12 @@ describe("Vue 3 UI", function () {
|
||||
state.sourceUrl = "https://github.com/owner/repo";
|
||||
await state.urlSelected(); await delay(60);
|
||||
expect(doc.querySelector('.repository-task')).to.equal(null);
|
||||
for (const selector of ['#sourceUrl', '#terms', '#image', '#conference', '#expirationDate']) {
|
||||
for (const selector of ['#sourceUrl', '#terms', '#image', '#conference']) {
|
||||
expect(doc.querySelector(selector).closest('details')).to.equal(null);
|
||||
}
|
||||
// Under the free plan's limit the expiry reads as text; the exact date is one click away.
|
||||
expect(doc.querySelector('.expiry-meta').textContent).to.include("Maximum on your plan");
|
||||
expect(doc.querySelector('#expirationDate').closest('.hosting-date').style.display).to.equal("none");
|
||||
state.terms = "Private Author";
|
||||
await delay(450);
|
||||
expect(doc.querySelector('.reviewer-preview .file-content, .anonymize-preview-body').textContent).to.include("MASKED");
|
||||
@@ -1109,7 +1115,7 @@ describe("Vue 3 UI", function () {
|
||||
state.options.expirationMode = "never"; await delay(20);
|
||||
expect(doc.querySelector('.hosting-options').textContent).to.include("20 repositories");
|
||||
expect(doc.querySelector('.anonymize-submit-bar').textContent).to.include("Continue to checkout");
|
||||
// The caption also has a "Files" toggle (.rp-open) for the preview's tree; target Expand preview.
|
||||
// Expand preview is the caption's only window control.
|
||||
doc.querySelector('.reviewer-preview .rp-open.is-toggle').click(); await delay(10);
|
||||
expect(doc.querySelector('.anonymize-page').classList.contains('preview-expanded')).to.equal(true);
|
||||
doc.querySelector('.reviewer-preview .rp-open.is-toggle').click(); await delay(10);
|
||||
@@ -2977,4 +2983,469 @@ describe("Vue 3 UI", function () {
|
||||
}
|
||||
expect(ui.app.router.currentRoute.value.path).to.equal("/");
|
||||
});
|
||||
|
||||
it("renders the pull request header, threaded conversation, commits and collapsible files", async function () {
|
||||
const diff = "diff --git a/src/a.py b/src/a.py\n--- a/src/a.py\n+++ b/src/a.py\n@@ -1,2 +1,3 @@\n one\n+two by XXXX-1\n three\n"
|
||||
+ "diff --git a/old.sh b/old.sh\ndeleted file mode 100644\n--- a/old.sh\n+++ /dev/null\n@@ -1 +0,0 @@\n-gone\n";
|
||||
ui = await browser("/pr/pr-1/", {
|
||||
"/api/pr/pr-1/options": { url: null },
|
||||
"/api/pr/pr-1/content": {
|
||||
state: "open", title: "Fix XXXX-1 harness", author: "XXXX-2", baseRef: "main", headRef: "XXXX-2/fix", diff,
|
||||
comments: [{ author: "XXXX-3", body: "Looks good", creationDate: "2026-03-03" }],
|
||||
reviewComments: [{ path: "src/a.py", line: 2, comments: [{ author: "XXXX-3", body: "Why?", creationDate: "2026-03-02" }, { author: "XXXX-2", body: "Because", creationDate: "2026-03-04" }] }],
|
||||
commits: [{ message: "First", author: "XXXX-2", date: "2026-03-01" }],
|
||||
},
|
||||
});
|
||||
await delay(60);
|
||||
const doc = ui.window.document;
|
||||
expect(doc.querySelector(".pr-title").textContent.replace(/\s+/g, " ").trim()).to.equal("Fix 1 harness");
|
||||
expect(doc.querySelectorAll(".pr-title .redact-slot")).to.have.length(1);
|
||||
// A fully redacted author is one unit: its slot, without a stray "@".
|
||||
const author = doc.querySelector(".pr-summary .pr-author");
|
||||
expect(author.classList.contains("is-redacted")).to.equal(true);
|
||||
expect(author.textContent.trim()).to.equal("2");
|
||||
expect(doc.querySelector(".pr-state").textContent.trim()).to.equal("Open");
|
||||
expect(doc.querySelector(".pr-summary").textContent.replace(/\s+/g, " ")).to.include("wants to merge 1 commit into main from 2/fix");
|
||||
const tabs = [...doc.querySelectorAll(".pr-tabs [role=tab]")].map((t) => t.textContent.replace(/\s+/g, " ").trim());
|
||||
expect(tabs).to.deep.equal(["Conversation2", "Commits1", "Files changed2"]);
|
||||
expect(doc.querySelector(".pr-tabs [aria-selected=true]").id).to.equal("pr-conversation-tab");
|
||||
expect(doc.querySelectorAll(".pr-timeline-item")).to.have.length(3);
|
||||
expect(doc.querySelectorAll(".pr-timeline-item.is-review .pr-thread-comment.is-reply")).to.have.length(1);
|
||||
doc.querySelector("#pr-commits-tab").click(); await delay(20);
|
||||
expect(doc.querySelector(".pr-commit-headline").textContent).to.equal("First");
|
||||
doc.querySelector("#pr-files-tab").click(); await delay(20);
|
||||
const blocks = doc.querySelectorAll(".diff-file-block");
|
||||
expect(blocks).to.have.length(2);
|
||||
expect(doc.querySelectorAll(".pr-file-toc .toc-diff-file")).to.have.length(2);
|
||||
expect(blocks[0].querySelector(".diff-file-stat").textContent).to.include("+1");
|
||||
expect(blocks[0].querySelectorAll(".diff-thread-row")).to.have.length(1);
|
||||
expect(blocks[0].querySelector(".diff-row-add .redact-slot")).to.not.equal(null);
|
||||
// The thread sits in the code column; its comments share one container.
|
||||
const threadRow = blocks[0].querySelector(".diff-thread-row");
|
||||
expect(threadRow.querySelector(".diff-thread-gutter").getAttribute("colspan")).to.equal("3");
|
||||
expect(threadRow.querySelectorAll(".diff-thread-cell > .pr-thread > .pr-thread-comment")).to.have.length(2);
|
||||
expect(threadRow.querySelectorAll(".pr-thread .pr-thread")).to.have.length(0);
|
||||
expect(blocks[1].querySelector(".diff-file-status").textContent).to.equal("deleted");
|
||||
blocks[0].querySelector(".diff-file-toggle").click(); await delay(20);
|
||||
expect(blocks[0].querySelector(".diff-file-body")).to.equal(null);
|
||||
expect(blocks[0].querySelector(".diff-file-toggle").getAttribute("aria-expanded")).to.equal("false");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("outlines a gist's files on the files tab", async function () {
|
||||
ui = await browser("/gist/g-1/", {
|
||||
"/api/gist/g-1/options": { url: null },
|
||||
"/api/gist/g-1/content": { description: "Notes", files: [
|
||||
{ filename: "a-XXXX-1.py", language: "Python", content: "x = 1\ny = 2\n" },
|
||||
{ filename: "b.json", language: "JSON", content: "{}\n" },
|
||||
] },
|
||||
});
|
||||
await delay(60);
|
||||
const doc = ui.window.document;
|
||||
const items = [...doc.querySelectorAll(".page-toc .toc-file")];
|
||||
expect(items.map((a) => a.getAttribute("href"))).to.deep.equal(["#file-1", "#file-2"]);
|
||||
expect(items[0].querySelector(".toc-file-meta").textContent).to.equal("Python · 2 lines");
|
||||
expect(items[0].querySelector(".redact-slot")).to.not.equal(null);
|
||||
expect(items[0].classList.contains("is-active")).to.equal(true);
|
||||
expect(doc.querySelectorAll(".gist-file-card")).to.have.length(2);
|
||||
expect(doc.getElementById("file-2")).to.not.equal(null);
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("outlines Markdown h1-h3 with redaction slots and hides short outlines", async function () {
|
||||
const doc = "# Guide\n\nIntro.\n\n## Setup\n\nText.\n\n### Data\n\nText.\n\n## Results from XXXX-2\n\nText.\n";
|
||||
ui = await browser("/r/test/GUIDE.md", {
|
||||
"/api/repo/test/files/": [{ name: "GUIDE.md", path: "", sha: "1", size: 80 }, { name: "SHORT.md", path: "", sha: "2", size: 20 }],
|
||||
"/api/repo/test/file/GUIDE.md": doc,
|
||||
"/api/repo/test/file/SHORT.md": "# Short\n\n## Only\n",
|
||||
});
|
||||
await delay(150);
|
||||
const document = ui.window.document;
|
||||
const rail = [...document.querySelectorAll(".readme-toc .toc-rail a")];
|
||||
expect(rail.map((a) => a.textContent.trim())).to.deep.equal(["Guide", "Setup", "Data", "Results from 2"]);
|
||||
expect(rail.map((a) => a.className.match(/lvl-\d/)[0])).to.deep.equal(["lvl-2", "lvl-2", "lvl-3", "lvl-2"]);
|
||||
expect(rail[3].querySelector(".redact-slot")).to.not.equal(null);
|
||||
expect(rail[1].getAttribute("href")).to.equal("#" + document.querySelector(".markdown-body h2").id);
|
||||
expect(document.querySelectorAll(".tb-toc-menu, .tb-toc-m")).to.have.length(1);
|
||||
await ui.go("/r/test/SHORT.md");
|
||||
await delay(150);
|
||||
expect(document.querySelector(".readme-toc")).to.equal(null);
|
||||
expect(document.querySelector(".tb-toc-m")).to.equal(null);
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("renders each gist format with the explorer's viewers and toggles a file's source", async function () {
|
||||
const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
|
||||
const files = [
|
||||
{ filename: "README.md", language: "Markdown", content: "# Notes by XXXX-1\n\nText.\n" },
|
||||
{ filename: "data.csv", content: "name,score\nXXXX-2,3\nb,4\n" },
|
||||
{ filename: "run.ipynb", content: JSON.stringify({ nbformat: 4, nbformat_minor: 5, metadata: {}, cells: [{ cell_type: "markdown", metadata: {}, source: ["# Cell"] }] }) },
|
||||
{ filename: "plot.svg", content: "<svg xmlns='http://www.w3.org/2000/svg' width='4' height='4'/>" },
|
||||
{ filename: "train.py", language: "Python", content: "print(1)\n" },
|
||||
{ filename: "fig.png", encoding: "base64", size: 70, content: png },
|
||||
// The API never sends bytes for binaries other than images.
|
||||
{ filename: "talk.mp4", encoding: "base64", size: 4 },
|
||||
{ filename: "beep.wav", encoding: "base64", size: 4 },
|
||||
{ filename: "model.bin", encoding: "base64", size: 4 },
|
||||
{ filename: "big.parquet", encoding: "base64", size: 400000000, tooLarge: true },
|
||||
{ filename: "photo.jpg", encoding: "base64", size: 10, hidden: true },
|
||||
{ filename: "empty.txt", content: "" },
|
||||
];
|
||||
let blobs = 0;
|
||||
ui = await browser("/gist/g-2/", { "/api/gist/g-2/options": { url: null }, "/api/gist/g-2/content": { description: "Formats", files } });
|
||||
ui.window.URL.createObjectURL = () => "blob:http://localhost/" + (++blobs);
|
||||
ui.window.URL.revokeObjectURL = () => {};
|
||||
const copied = [];
|
||||
Object.defineProperty(ui.window.navigator, "clipboard", { value: { writeText: async (text) => copied.push(text) }, configurable: true });
|
||||
await ui.go("/faq"); await ui.go("/gist/g-2/");
|
||||
await delay(150);
|
||||
const doc = ui.window.document;
|
||||
const body = (i) => doc.querySelectorAll(".gist-file-card")[i].querySelector(".gist-file-body");
|
||||
expect(body(0).querySelector("markdown.markdown-body h1")).to.not.equal(null);
|
||||
expect(body(1).querySelectorAll(".csv-table tbody tr")).to.have.length(2);
|
||||
expect(body(1).querySelector(".csv-table tbody .redact-slot")).to.not.equal(null);
|
||||
expect(body(2).querySelector("notebook")).to.not.equal(null);
|
||||
expect(body(3).querySelector("img.image-content").getAttribute("src")).to.match(/^blob:/);
|
||||
expect(body(4).querySelector("pre code")).to.not.equal(null);
|
||||
expect(body(5).querySelector("img.image-content")).to.not.equal(null);
|
||||
for (const i of [6, 7, 8]) {
|
||||
expect(body(i).querySelector(".file-state-title").textContent).to.equal("This file isn't shared");
|
||||
expect(body(i).querySelector("a[download]")).to.equal(null);
|
||||
expect(doc.querySelectorAll(".gist-file-card")[i].querySelector(".gist-file-actions")).to.equal(null);
|
||||
}
|
||||
expect(body(9).querySelector(".file-state-title").textContent).to.equal("This file is too large to preview");
|
||||
expect(body(10).querySelector(".file-state-title").textContent).to.equal("Image not shown");
|
||||
expect(body(11).querySelector(".file-state-title").textContent).to.equal("This file is empty");
|
||||
// Preview/Source only where the two differ; Raw and copy on every readable file.
|
||||
const toggles = [...doc.querySelectorAll(".gist-file-card")].map((card) => !!card.querySelector(".gist-view-toggle"));
|
||||
expect(toggles).to.deep.equal([true, true, true, true, false, false, false, false, false, false, false, false]);
|
||||
const card = doc.querySelectorAll(".gist-file-card")[0];
|
||||
expect(card.querySelector(".gist-file-actions a[target=_blank]").getAttribute("href")).to.match(/^blob:/);
|
||||
card.querySelector(".gist-file-actions button").click(); await delay(20);
|
||||
expect(copied).to.deep.equal([files[0].content]);
|
||||
const [preview, source] = card.querySelectorAll(".gist-view-toggle .seg-chip");
|
||||
source.click(); await delay(60);
|
||||
expect(source.getAttribute("aria-checked")).to.equal("true");
|
||||
expect(body(0).querySelector("markdown")).to.equal(null);
|
||||
expect(body(0).querySelector("pre code").textContent).to.equal(files[0].content);
|
||||
expect(doc.querySelector(".page-toc .toc-heading")).to.equal(null);
|
||||
preview.click(); await delay(60);
|
||||
expect(body(0).querySelector("markdown h1")).to.not.equal(null);
|
||||
// CSV: Table, Chart and Source.
|
||||
const csvChips = () => doc.querySelectorAll(".gist-file-card")[1].querySelectorAll(".gist-view-toggle .seg-chip");
|
||||
expect([...csvChips()].map((c) => c.textContent)).to.deep.equal(["Table", "Chart", "Source"]);
|
||||
csvChips()[1].click(); await delay(40);
|
||||
expect(body(1).querySelector(".dt-chart")).to.not.equal(null);
|
||||
expect(body(1).querySelector(".csv-table")).to.equal(null);
|
||||
csvChips()[2].click(); await delay(40);
|
||||
expect(body(1).querySelector(".csv-table")).to.equal(null);
|
||||
expect(body(1).querySelector("pre code").textContent).to.equal(files[1].content);
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
describe("table analysis", function () {
|
||||
const CSV = "model,seed,accuracy\nBaseline,1,71.0\nBaseline,2,71.4\nOurs,1,78.7\nOurs,2,79.1\nXXXX-2,1,\n";
|
||||
const open = async (hash = "") => {
|
||||
const page = await browser("/r/test/results.csv" + hash, {
|
||||
"/api/repo/test/files/": [{ name: "results.csv", path: "", sha: "1", size: CSV.length }],
|
||||
"/api/repo/test/file/results.csv": CSV,
|
||||
});
|
||||
await delay(120);
|
||||
return page;
|
||||
};
|
||||
const cells = (doc, col) => [...doc.querySelectorAll(".dt-table tbody tr")].map((tr) => tr.cells[col].textContent);
|
||||
const sortButton = (doc, name) => [...doc.querySelectorAll(".dt-sort")].find((b) => b.textContent.trim() === name);
|
||||
|
||||
it("sorts by a header, shows the summary row and keeps redaction slots", async function () {
|
||||
ui = await open();
|
||||
const doc = ui.window.document;
|
||||
expect(cells(doc, 1)).to.deep.equal(["Baseline", "Baseline", "Ours", "Ours", "2"]);
|
||||
expect(doc.querySelector(".dt-table tbody .redact-slot").textContent).to.equal("2");
|
||||
// Σ, distinct count for text, nothing for the seed (an identifier), "Avg ▾ value" per measure.
|
||||
const cellsOf = () => [...doc.querySelectorAll(".dt-summary td")];
|
||||
expect(cellsOf()[0].textContent.trim()).to.match(/^Σ/);
|
||||
expect(cellsOf()[1].textContent.trim()).to.equal("3 distinct");
|
||||
expect(cellsOf()[2].textContent.trim()).to.equal("");
|
||||
expect(doc.querySelectorAll(".dt-summary select")).to.have.length(1);
|
||||
expect(doc.querySelector(".dt-sum-fn-label").textContent).to.equal("Avg");
|
||||
const foot = () => [...doc.querySelectorAll(".dt-sum-value")].map((b) => b.textContent);
|
||||
expect(foot()).to.deep.equal(["75.1"]);
|
||||
sortButton(doc, "accuracy").click(); await delay(30);
|
||||
expect(cells(doc, 3)).to.deep.equal(["71.0", "71.4", "78.7", "79.1", ""]);
|
||||
sortButton(doc, "accuracy").click(); await delay(30);
|
||||
expect(cells(doc, 3)).to.deep.equal(["79.1", "78.7", "71.4", "71.0", ""]);
|
||||
expect(doc.querySelector("th[aria-sort=descending]").textContent).to.contain("accuracy");
|
||||
sortButton(doc, "accuracy").click(); await delay(30);
|
||||
expect(cells(doc, 3)).to.deep.equal(["71.0", "71.4", "78.7", "79.1", ""]);
|
||||
expect(doc.querySelector("th[aria-sort=ascending], th[aria-sort=descending]")).to.equal(null);
|
||||
const select = doc.querySelector(".dt-summary select");
|
||||
select.value = "max"; select.dispatchEvent(new ui.window.Event("change")); await delay(30);
|
||||
expect(foot()).to.deep.equal(["79.1"]);
|
||||
expect(doc.querySelector(".dt-sum-fn-label").textContent).to.equal("Max");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("filters rows, groups them and stores the view in the link", async function () {
|
||||
ui = await open();
|
||||
const doc = ui.window.document;
|
||||
await ui.input(".dt-search-input", "ours");
|
||||
expect(cells(doc, 1)).to.deep.equal(["Ours", "Ours"]);
|
||||
expect(doc.querySelector(".dt-count").textContent).to.equal("2 of 5 rows");
|
||||
expect([...doc.querySelectorAll(".dt-sum-value")].at(-1).textContent).to.equal("78.9");
|
||||
await ui.input(".dt-search-input", "");
|
||||
const group = doc.querySelector(".dt-tools .dt-select select");
|
||||
group.value = "model"; group.dispatchEvent(new ui.window.Event("change")); await delay(30);
|
||||
expect(cells(doc, 0)).to.deep.equal(["Baseline", "Ours", "2"]);
|
||||
expect(doc.querySelector(".dt-table tbody tr:last-child .redact-slot")).to.not.equal(null);
|
||||
expect(cells(doc, 2)).to.deep.equal(["71.2", "78.9", "—"]);
|
||||
expect(doc.querySelector(".dt-count").textContent).to.equal("3 groups · 5 rows");
|
||||
await delay(300);
|
||||
expect(ui.window.location.hash).to.equal("#table:group=model");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("opens a shared link on the grouped chart, with a tooltip on hover", async function () {
|
||||
ui = await open("#table:view=chart&group=model");
|
||||
const doc = ui.window.document;
|
||||
expect(doc.querySelector(".csv-toggle .seg-chip.active").textContent).to.equal("Chart");
|
||||
// jsdom has no layout: give the chart a width.
|
||||
Object.defineProperty(ui.window.HTMLElement.prototype, "clientWidth", { configurable: true, get() { return this.classList.contains("dt-chart") ? 600 : 0; } });
|
||||
doc.querySelector(".csv-toggle .seg-chip").click(); await delay(30);
|
||||
doc.querySelectorAll(".csv-toggle .seg-chip")[1].click(); await delay(60);
|
||||
const svg = doc.querySelector(".dt-svg");
|
||||
expect(svg.getAttribute("aria-label")).to.equal("Bar chart of accuracy by model");
|
||||
expect([...doc.querySelectorAll(".dt-cat")].map((t) => t.textContent)).to.deep.equal(["Baseline", "Ours", "XXXX-2"]);
|
||||
svg.dispatchEvent(new ui.window.KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); await delay(30);
|
||||
expect(doc.querySelector(".dt-tip b").textContent).to.equal("71.2");
|
||||
expect(doc.querySelector(".dt-tip-title").textContent).to.equal("Baseline");
|
||||
delete ui.window.HTMLElement.prototype.clientWidth;
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("copies the current view as Markdown", async function () {
|
||||
ui = await open("#table:group=model&sort=accuracy:desc");
|
||||
const copied = [];
|
||||
Object.defineProperty(ui.window.navigator, "clipboard", { value: { writeText: async (text) => copied.push(text) }, configurable: true });
|
||||
const doc = ui.window.document;
|
||||
doc.querySelector(".dt-copy-btn").click(); await delay(20);
|
||||
[...doc.querySelectorAll(".dt-copy-menu button")].find((b) => /Markdown/.test(b.textContent)).click(); await delay(30);
|
||||
expect(copied[0].split("\n").slice(0, 4)).to.deep.equal(["| model | Rows | accuracy |", "| --- | ---: | ---: |", "| Ours | 2 | 78.9 |", "| Baseline | 2 | 71.2 |"]);
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("sorts a Markdown table, adds a summary row and opens it as a table", async function () {
|
||||
const md = "# Results\n\n| Model | Accuracy |\n| --- | ---: |\n| Baseline | 71.2 |\n| XXXX-3 | 77.5 |\n| Ours | 78.9 |\n";
|
||||
ui = await browser("/r/test/README.md", {
|
||||
"/api/repo/test/files/": [{ name: "README.md", path: "", sha: "1", size: md.length }],
|
||||
"/api/repo/test/file/README.md": md,
|
||||
});
|
||||
await delay(200);
|
||||
const doc = ui.window.document;
|
||||
const table = doc.querySelector(".markdown-body table");
|
||||
expect(table.closest(".md-table")).to.not.equal(null);
|
||||
const firstCol = () => [...table.querySelectorAll("tbody tr")].map((tr) => tr.cells[0].textContent.trim());
|
||||
table.querySelectorAll("th")[1].click(); table.querySelectorAll("th")[1].click(); await delay(20);
|
||||
expect(firstCol()).to.deep.equal(["Ours", "3", "Baseline"]);
|
||||
expect(table.querySelector("tbody .redact-chip, tbody .redact-slot")).to.not.equal(null);
|
||||
doc.querySelector(".md-sigma").click(); await delay(20);
|
||||
expect(table.querySelector("tfoot td").textContent).to.match(/^Σ/);
|
||||
expect(table.querySelector("tfoot .dt-sum-fn-label").textContent).to.equal("Avg");
|
||||
expect(table.querySelector("tfoot .dt-sum-value").textContent).to.equal("75.9");
|
||||
doc.querySelector(".md-open").click(); await delay(60);
|
||||
const dialog = doc.querySelector(".dt-dialog");
|
||||
expect(dialog.querySelector(".dt-dialog-title").textContent).to.equal("Table · Results");
|
||||
expect([...dialog.querySelectorAll(".dt-table tbody tr")].map((tr) => tr.cells[1].textContent)).to.deep.equal(["Baseline", "3", "Ours"]);
|
||||
dialog.querySelector(".dt-dialog-close").click(); await delay(20);
|
||||
expect(doc.querySelector(".dt-dialog")).to.equal(null);
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspace polish (r19)", () => {
|
||||
it("keeps the dashboard tabs and counts rendered while a tab reloads", async () => {
|
||||
const item = (repoId, status) => ({ _type: "repo", repoId, status, source: { fullName: "owner/" + repoId }, options: {} });
|
||||
let release;
|
||||
ui = await browser("/dashboard", {
|
||||
"/api/user": { username: "tester" },
|
||||
"/api/user/dashboard": request => {
|
||||
const removed = request.url.searchParams.get("statuses") === "removed";
|
||||
const body = { items: removed ? [item("gone", "removed")] : [item("alpha", "ready"), item("broken", "error")],
|
||||
total: 3, filtered: removed ? 1 : 2, attention: 1, cursor: null };
|
||||
return removed ? new Promise(resolve => { release = () => resolve(body); }) : body;
|
||||
},
|
||||
});
|
||||
const doc = ui.window.document;
|
||||
await delay(50);
|
||||
const tabs = () => [...doc.querySelectorAll(".dashboard-meta .dashboard-view-tabs button")].map(b => b.textContent.replace(/\s+/g, " ").trim());
|
||||
expect(tabs()).to.deep.equal(["Current", "Needs attention 1", "Removed 1"]);
|
||||
[...doc.querySelectorAll(".dashboard-view-tabs button")].find(b => /Removed/.test(b.textContent)).click();
|
||||
await delay(250);
|
||||
// The answer is pending: same tabs, the table busy, placeholders instead of a false empty state.
|
||||
expect(tabs()).to.deep.equal(["Current", "Needs attention 1", "Removed 1"]);
|
||||
const table = doc.querySelector(".paper-table-dashboard");
|
||||
expect(table.getAttribute("aria-busy")).to.equal("true");
|
||||
expect(table.classList.contains("is-refreshing")).to.equal(true);
|
||||
expect(doc.querySelector(".paper-table-empty")).to.equal(null);
|
||||
expect(doc.querySelectorAll(".paper-table-skeleton").length).to.be.greaterThan(0);
|
||||
release(); await delay(30);
|
||||
expect(table.classList.contains("is-refreshing")).to.equal(false);
|
||||
expect(doc.querySelectorAll(".paper-table-skeleton")).to.have.length(0);
|
||||
expect(doc.querySelector(".paper-table-row:not(.paper-table-skeleton):not(.paper-table-head)").textContent).to.include("gone");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("holds the dashboard tab row with placeholders on the first load", async () => {
|
||||
let release;
|
||||
ui = await browser("/dashboard", {
|
||||
"/api/user": { username: "tester" },
|
||||
"/api/user/dashboard": () => new Promise(resolve => { release = () => resolve({ items: [], total: 0, filtered: 0, attention: 0, cursor: null }); }),
|
||||
});
|
||||
const doc = ui.window.document;
|
||||
expect(doc.querySelector(".dashboard-meta.is-loading .dashboard-tab-skeleton")).to.not.equal(null);
|
||||
expect(doc.querySelector(".paper-table-empty")).to.equal(null);
|
||||
release(); await delay(30);
|
||||
expect(doc.querySelector(".dashboard-meta.is-loading")).to.equal(null);
|
||||
expect(doc.querySelector(".dashboard-meta .dashboard-count")).to.not.equal(null);
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("shows admin placeholder rows instead of an empty state until the list arrives", async () => {
|
||||
let release;
|
||||
ui = await browser("/admin/repositories", {
|
||||
"/api/user": { username: "admin", isAdmin: true },
|
||||
"/api/admin/repos": request => request.url.searchParams.get("limit") === "1"
|
||||
? { total: 1, results: [], statusCounts: [] }
|
||||
: new Promise(resolve => { release = () => resolve({ total: 1, results: [{ repoId: "r1", status: "ready", source: { repositoryName: "owner/r1" }, options: {} }] }); }),
|
||||
});
|
||||
const doc = ui.window.document;
|
||||
await delay(30);
|
||||
expect(doc.querySelectorAll(".paper-table-repos .paper-table-skeleton").length).to.be.greaterThan(0);
|
||||
expect(doc.querySelector(".paper-table-repos .paper-table-empty")).to.equal(null);
|
||||
expect(doc.querySelector(".seg-filter")).to.not.equal(null);
|
||||
release(); await delay(30);
|
||||
expect(doc.querySelectorAll(".paper-table-repos .paper-table-skeleton")).to.have.length(0);
|
||||
expect(doc.querySelector(".paper-table-repos").getAttribute("aria-busy")).to.equal("false");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("gives a picker row a tooltip only when its name is cut short", async () => {
|
||||
ui = await browser("/anonymize", {
|
||||
"/api/user/repository_picker": { items: [{ id: 1, fullName: "org/short" }], nextCursor: null },
|
||||
});
|
||||
const name = ui.window.document.querySelector(".repo-picker-name");
|
||||
expect(name.hasAttribute("title")).to.equal(false);
|
||||
name.dispatchEvent(new ui.window.MouseEvent("mouseenter"));
|
||||
expect(name.hasAttribute("title")).to.equal(false);
|
||||
Object.defineProperty(name, "scrollWidth", { configurable: true, value: 400 });
|
||||
Object.defineProperty(name, "clientWidth", { configurable: true, value: 200 });
|
||||
name.dispatchEvent(new ui.window.MouseEvent("mouseenter"));
|
||||
expect(name.getAttribute("title")).to.equal("org/short");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("states the redaction status beside the preview title and leads to the Terms field", async () => {
|
||||
ui = await browser("/anonymize", { ...repositorySource, "/api/user/default": { terms: [], options: {} },
|
||||
"/api/anonymize-preview": request => {
|
||||
const mask = text => (request.payload.options?.terms || []).includes("Private Author") ? text.replaceAll("Private Author", "XXXX-1") : text;
|
||||
return request.payload.contents ? { contents: request.payload.contents.map(mask) } : { content: mask(String(request.payload.content)) };
|
||||
} });
|
||||
const doc = ui.window.document;
|
||||
const state = doc.querySelector("#sourceUrl")._field.binding.state;
|
||||
state.sourceUrl = "https://github.com/owner/repo";
|
||||
await state.urlSelected(); await delay(450);
|
||||
const caption = doc.querySelector(".reviewer-preview .rp-caption");
|
||||
expect(caption.querySelector(".rp-title").textContent).to.equal("What reviewers will see");
|
||||
expect([...caption.querySelectorAll("button")].some(b => b.textContent.trim() === "Files")).to.equal(false);
|
||||
const chip = caption.querySelector(".rp-status-empty");
|
||||
expect(chip.textContent.replace(/\s+/g, " ").trim()).to.equal("Nothing redacted yet: add terms");
|
||||
state.mobilePane = "preview";
|
||||
chip.click(); await delay(20);
|
||||
expect(state.mobilePane).to.equal("settings");
|
||||
expect(doc.activeElement.id).to.equal("terms");
|
||||
state.terms = "Private Author"; await delay(450);
|
||||
expect(caption.querySelector(".rp-status-empty")).to.equal(null);
|
||||
expect(caption.querySelector(".rp-count").textContent.replace(/\s+/g, " ").trim()).to.equal("1 redacted");
|
||||
state.terms = "Nobody"; await delay(450);
|
||||
expect(caption.querySelector(".rp-count").textContent).to.equal("No terms found in this file");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("names the plan-limited date in the option and reveals the bounded input on Change date", async () => {
|
||||
ui = await browser("/anonymize", { ...repositorySource, "/api/billing/": { ...taskBilling, freeExpirationMonths: 5 },
|
||||
"/api/user/quota": { repository: { used: 1, total: 5 } } });
|
||||
const doc = ui.window.document;
|
||||
const state = doc.querySelector("#sourceUrl")._field.binding.state;
|
||||
state.sourceUrl = "https://github.com/owner/repo";
|
||||
await state.urlSelected(); await delay(60);
|
||||
const option = doc.querySelector(".expiration-choice span");
|
||||
expect(option.textContent).to.match(/^Expire on [A-Z][a-z]{2} \d{1,2}, \d{4}$/);
|
||||
const meta = () => doc.querySelector(".expiry-meta").textContent.replace(/\s+/g, " ").trim();
|
||||
expect(meta()).to.equal("In 5 months · Maximum on your plan");
|
||||
expect(doc.querySelector(".expiration-choice-row .expiry-change").textContent).to.equal("Change date");
|
||||
expect(doc.querySelector(".dated-options").textContent).not.to.match(/Expires|Then|Advanced/);
|
||||
expect(doc.querySelector(".hosting-property label").textContent).to.equal("After expiry");
|
||||
const row = doc.querySelector("#expirationDate").closest(".hosting-date");
|
||||
expect(row.style.display).to.equal("none");
|
||||
doc.querySelector(".expiry-change").click(); await delay(20);
|
||||
expect(row.style.display).to.equal("");
|
||||
expect(doc.activeElement.id).to.equal("expirationDate");
|
||||
expect(doc.querySelector(".expiry-change")).to.equal(null);
|
||||
const input = doc.querySelector("#expirationDate");
|
||||
expect(input.getAttribute("max")).to.equal(state.maxExpirationDate);
|
||||
expect(input.getAttribute("min")).to.equal(state.minExpirationDate);
|
||||
// An earlier pick is still named, without the "maximum" reason.
|
||||
const earlier = new Date(); earlier.setMonth(earlier.getMonth() + 2);
|
||||
state.options.expirationDate = new ui.window.Date(earlier.getTime()); await delay(20);
|
||||
expect(meta()).to.equal("In 2 months");
|
||||
state.options.expirationMode = "never"; await delay(20);
|
||||
expect(doc.querySelector(".dated-options")).to.equal(null);
|
||||
expect(option.textContent).to.equal("Expire on a date");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("reveals and focuses a hidden invalid date on submit", async () => {
|
||||
ui = await browser("/anonymize", { ...repositorySource, "/api/billing/": { ...taskBilling, freeExpirationMonths: 5 },
|
||||
"/api/user/quota": { repository: { used: 1, total: 5 } } });
|
||||
const doc = ui.window.document;
|
||||
const state = doc.querySelector("#sourceUrl")._field.binding.state;
|
||||
state.sourceUrl = "https://github.com/owner/repo";
|
||||
await state.urlSelected(); await delay(60);
|
||||
const input = doc.querySelector("#expirationDate");
|
||||
expect(input.closest(".hosting-date").style.display).to.equal("none");
|
||||
input.setCustomValidity("out of range");
|
||||
input.dispatchEvent(new ui.window.Event("reveal", { bubbles: true }));
|
||||
await delay(20);
|
||||
expect(state.expiryPickerOpen).to.equal(true);
|
||||
expect(input.closest(".hosting-date").style.display).to.equal("");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("keeps the plain date picker when no plan limit applies", async () => {
|
||||
ui = await browser("/anonymize", repositorySource);
|
||||
const doc = ui.window.document;
|
||||
const state = doc.querySelector("#sourceUrl")._field.binding.state;
|
||||
state.sourceUrl = "https://github.com/owner/repo";
|
||||
await state.urlSelected(); await delay(60);
|
||||
expect(doc.querySelector(".expiry-meta")).to.equal(null);
|
||||
expect(doc.querySelector(".expiration-choice span").textContent).to.equal("Expire on a date");
|
||||
expect(doc.querySelector("#expirationDate").closest(".hosting-date").style.display).to.equal("");
|
||||
const echo = doc.querySelector(".hosting-date .date-echo").textContent;
|
||||
expect(echo).not.to.match(/^Expires/);
|
||||
expect(echo).to.match(/· in \d+ months?$/);
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it("names the conference when its end date sets the expiry", async () => {
|
||||
const end = new Date(); end.setMonth(end.getMonth() + 9);
|
||||
ui = await browser("/anonymize", { ...repositorySource, "/api/billing/": { ...taskBilling, freeExpirationMonths: 5 },
|
||||
"/api/user/quota": { repository: { used: 1, total: 5 } },
|
||||
"/api/conferences/ICSE": { conferenceID: "ICSE", name: "ICSE 2027", startDate: new Date().toISOString(), endDate: end.toISOString(), options: {} } });
|
||||
const doc = ui.window.document;
|
||||
const state = doc.querySelector("#sourceUrl")._field.binding.state;
|
||||
state.sourceUrl = "https://github.com/owner/repo";
|
||||
await state.urlSelected(); await delay(60);
|
||||
state.conference = "ICSE"; await delay(60);
|
||||
expect(doc.querySelector(".expiry-meta").textContent).to.include("When ICSE 2027 ends");
|
||||
expect(ui.errors).to.deep.equal([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user