Add CLI tooling to create seed fixtures on the fly

Signed-off-by: Sebastian Martinez <me@sebastinez.dev>
This commit is contained in:
Sebastian Martinez
2023-05-12 14:23:10 +02:00
parent 45c6f20855
commit c32b303744
20 changed files with 1073 additions and 458 deletions
+4 -5
View File
@@ -1,8 +1,10 @@
import type { Page } from "@playwright/test";
import {
expect,
projectFixtureUrl,
rid,
seedRemote,
test,
} from "@tests/support/fixtures.js";
@@ -35,7 +37,7 @@ test("copy to clipboard", async ({ page, browserName, context }) => {
const clipboardContent = await page.evaluate<string>(
"navigator.clipboard.readText()",
);
expect(clipboardContent).toBe(`${rid}`);
expect(clipboardContent).toBe(rid);
}
// `rad clone` URL.
@@ -78,10 +80,7 @@ test("copy to clipboard", async ({ page, browserName, context }) => {
// Seed address.
{
await page.locator(".clipboard").first().click();
await expectClipboard(
"z6Mkk7oqY4pPxhMmGEotDYsFo97vhCj85BLY1H256HrJmjN8@127.0.0.1:8776",
page,
);
await expectClipboard(`${seedRemote}@127.0.0.1:8776`, page);
}
// Clear the system clipboard contents so developers don't wonder why there's
+3 -2
View File
@@ -1,4 +1,5 @@
import type { Page } from "@playwright/test";
import {
aliceMainHead,
aliceRemote,
@@ -341,10 +342,10 @@ test("peer and branch switching", async ({ page }) => {
// Default `main` branch.
{
await expect(page.getByTitle("Current branch")).toContainText(
"main 1e0bb83",
"main ec5eb0b",
);
await expectCounts({ commits: 9, contributors: 2 }, page);
await expect(page.locator("text=1e0bb83 Update readme")).toBeVisible();
await expect(page.locator("text=ec5eb0b Update readme")).toBeVisible();
}
}
});
+3 -2
View File
@@ -3,11 +3,12 @@ import {
expect,
projectFixtureUrl,
bobRemote,
bobHead,
} from "@tests/support/fixtures.js";
const modifiedFileFixture = `${projectFixtureUrl}/remotes/${bobRemote.substring(
8,
)}/commits/1e0bb83a89b63da815f2fc24e7ae3c5ceb30e0eb`;
)}/commits/${bobHead}`;
test("navigation from commit list", async ({ page }) => {
await page.goto(projectFixtureUrl);
@@ -43,7 +44,7 @@ test("modified file", async ({ page }) => {
const header = page.locator(".commit .header");
await expect(header.locator("text=Update readme")).toBeVisible();
await expect(
header.locator("text=1e0bb83a89b63da815f2fc24e7ae3c5ceb30e0eb"),
header.locator("text=ec5eb0b5efb73da17a2d25454cc47eea3967f328"),
).toBeVisible();
}
+2 -2
View File
@@ -76,7 +76,7 @@ test("peer and branch switching", async ({ page }) => {
const latestCommit = page.locator(".teaser").first();
await expect(latestCommit).toContainText("Update readme");
await expect(latestCommit).toContainText("1e0bb83");
await expect(latestCommit).toContainText("ec5eb0b");
const earliestCommit = page.locator(".teaser").last();
await expect(earliestCommit).toContainText(
@@ -109,7 +109,7 @@ test("relative timestamps", async ({ page }) => {
);
const latestCommit = page.locator(".teaser").first();
await expect(latestCommit).toContainText("Bob Belcher committed now");
await expect(latestCommit).toContainText("1e0bb83");
await expect(latestCommit).toContainText("ec5eb0b");
const earliestCommit = page.locator(".teaser").last();
await expect(earliestCommit).toContainText(
"Alice Liddell committed last month",
Binary file not shown.
+106 -38
View File
@@ -1,13 +1,25 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type * as Stream from "node:stream";
import * as Fs from "node:fs/promises";
import * as FsSync from "node:fs";
import * as Path from "node:path";
import { dirname } from "path";
import { fileURLToPath } from "url";
import { test as base, expect } from "@playwright/test";
import * as Process from "./process.js";
import * as logLabel from "@tests/support/logLabel.js";
import { createPeerManager } from "./peerManager.js";
import { sleep } from "@app/lib/sleep";
export { expect };
const filename = fileURLToPath(import.meta.url);
export const supportDir = dirname(filename);
export const tmpDir = Path.resolve(supportDir, "..", "./tmp");
const fixturesDir = Path.resolve(supportDir, "..", "./fixtures");
export const test = base.extend<{
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
forAllTests: void;
@@ -135,39 +147,6 @@ function log(text: string, label: string, outputLog: Stream.Writable) {
}
}
export function configFixture() {
window.APP_CONFIG = {
reactions: [],
seeds: {
defaultHttpdPort: 8080,
defaultHttpdScheme: "http",
defaultNodePort: 8776,
pinned: [
{
baseUrl: {
hostname: "127.0.0.1",
port: 8080,
scheme: "http",
},
},
],
},
projects: {
pinned: [
{
name: "source-browsing",
id: "rad:git:hnrkdi8be7n4hhqoz9rpzrgd68u9dr3zsxgmy",
baseUrl: {
hostname: "127.0.0.1",
port: 8080,
scheme: "http",
},
},
],
},
};
}
export function appConfigWithFixture() {
window.APP_CONFIG = {
reactions: [],
@@ -189,7 +168,7 @@ export function appConfigWithFixture() {
pinned: [
{
name: "source-browsing",
id: "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT",
id: "rad:z4BwwjPCFNVP27FwVbDFgwVwkjcir",
baseUrl: {
hostname: "127.0.0.1",
port: 8080,
@@ -201,12 +180,101 @@ export function appConfigWithFixture() {
};
}
export async function startPalmHttpd() {
const peerManager = await createPeerManager({
dataDir: Path.resolve(Path.join(tmpDir, "peers")),
outputLog: FsSync.createWriteStream(Path.resolve(Path.join(tmpDir, "log"))),
});
const palm = await peerManager.startPeer({ name: "palm" });
await palm.startHttpd();
}
export async function createSeedFixture() {
const projectName = "source-browsing";
const sourceBrowsingDir = Path.join(tmpDir, "repos", projectName);
await Fs.mkdir(sourceBrowsingDir, { recursive: true });
await Process.spawn("tar", [
"-xf",
Path.join(fixturesDir, `repos/${projectName}.tar.bz2`),
"-C",
sourceBrowsingDir,
]);
const peerManager = await createPeerManager({
dataDir: Path.resolve(Path.join(tmpDir, "peers")),
outputLog: FsSync.createWriteStream(Path.join(tmpDir, "log")),
});
const palm = await peerManager.startPeer({ name: "palm" });
await palm.startHttpd();
const alice = await peerManager.startPeer({
name: "alice",
gitOptions: gitOptions["alice"],
});
const bob = await peerManager.startPeer({
name: "bob",
gitOptions: gitOptions["bob"],
});
await palm.startNode({ trackingPolicy: "track", trackingScope: "all" });
await alice.startNode({ connect: palm });
await bob.startNode({ connect: palm });
await sleep(1000);
await alice.git(["clone", sourceBrowsingDir], { cwd: alice.checkoutPath });
await alice.git(["checkout", "main"]);
await alice.rad([
"init",
"--name",
projectName,
"--default-branch",
"main",
"--description",
"Git repository for source browsing tests",
"--announce",
]);
await alice.git(["checkout", "feature/branch"]);
await alice.git(["push", "rad"]);
await alice.git(["checkout", "orphaned-branch"]);
await alice.git(["push", "rad"]);
const { stdout: rid } = await alice.rad(["inspect"]);
await alice.rad(["track", bob.nodeId]);
await sleep(2000);
await bob.rad(["clone", rid], { cwd: bob.checkoutPath });
await sleep(2000);
await Fs.writeFile(
Path.join(bob.checkoutPath, "source-browsing", "README.md"),
"Updated readme",
);
await bob.git(["add", "README.md"]);
await bob.git([
"commit",
"--message",
"Update readme",
"--date",
"Mon Dec 21 14:00 2022 +0100",
]);
await bob.git(["push", "rad"]);
}
export const aliceMainHead = "fcc929424b82984b7cbff9c01d2e20d9b1249842";
export const aliceRemote =
"did:key:z6MknSLrJoTcukLrE435hVNQT4JUhbvWLX4kUzqkEStBU8Vi";
"did:key:z6MkqGC3nWZhYieEVTVDKW5v588CiGfsDSmRVG9ZwwWTvLSK";
export const bobRemote =
"did:key:z6MksMTThc1aDU2Ztc43jJUivuyBLNWiLsDf4X65rABe7HbA";
export const rid = "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT";
"did:key:z6Mkg49NtQR2LyYRDCQFK4w1VVHqhypZSSRo7HsyuN7SV7v5";
export const bobHead = "ec5eb0b5efb73da17a2d25454cc47eea3967f328";
export const rid = "rad:z4BwwjPCFNVP27FwVbDFgwVwkjcir";
export const projectFixtureUrl = `/seeds/127.0.0.1/${rid}`;
export const seedPort = 8080;
export const seedRemote = "z6Mkk7oqY4pPxhMmGEotDYsFo97vhCj85BLY1H256HrJmjN8";
export const seedRemote = "z6MktULudTtAsAhRegYPiZ6631RV3viv12qd4GQF8z1xB22S";
export const gitOptions = {
alice: {
GIT_AUTHOR_NAME: "Alice Liddell",
GIT_AUTHOR_EMAIL: "alice@radicle.xyz",
GIT_COMMITTER_NAME: "Alice Liddell",
GIT_COMMITTER_EMAIL: "alice@radicle.xyz",
},
bob: {
GIT_AUTHOR_NAME: "Bob Belcher",
GIT_AUTHOR_EMAIL: "bob@radicle.xyz",
GIT_COMMITTER_NAME: "Bob Belcher",
GIT_COMMITTER_EMAIL: "bob@radicle.xyz",
GIT_COMMITTER_DATE: "Mon Dec 21 14:00 2022 +0100",
},
};
+77 -22
View File
@@ -1,31 +1,86 @@
import type { FullConfig } from "@playwright/test";
import { seedPort, seedRemote } from "@tests/support/fixtures.js";
import * as Fs from "node:fs/promises";
import * as Path from "node:path";
import * as readline from "node:readline/promises";
import { execa } from "execa";
import {
createSeedFixture,
supportDir,
startPalmHttpd,
tmpDir,
} from "./fixtures.js";
const workspacePaths = [Path.join(tmpDir, "peers"), Path.join(tmpDir, "repos")];
export default async function globalSetup(_config: FullConfig): Promise<void> {
await assertHttpApiRunning();
}
// Assert that the test http-api is running. If it is not running, throw an
// error that explains how to run it.
async function assertHttpApiRunning(): Promise<void> {
const notRunningMessage =
"The http-api server with test fixtures needs to be running.\n" +
"👉 You can start it with `./scripts/run-httpd-with-fixtures`\n";
let nodeId: string | undefined = undefined;
try {
const response = await fetch(`http://0.0.0.0:${seedPort}/api/v1`);
const data = await response.json();
nodeId = data.node.id;
} catch (err) {
console.error(err);
throw new Error(notRunningMessage);
await assertRadInstalled();
} catch (error) {
console.error(error);
process.exit(1);
}
if (nodeId !== seedRemote) {
const wrongSeedMessage = `The server on port ${seedPort} doesn't have the right fixtures.\n`;
throw new Error(wrongSeedMessage + notRunningMessage);
if (!process.env.SKIP_FIXTURE_CREATION) {
console.log("Setting up global test environment");
if (!process.env.CI) {
await promptWorkspaceRemoval();
}
await removeWorkspace();
console.log("Creating seed fixture");
await createSeedFixture();
console.log("Running tests");
} else {
await startPalmHttpd();
}
}
// Assert that the `rad` CLI is installed and has the correct version.
async function assertRadInstalled(): Promise<void> {
const versionConstraint = (
await Fs.readFile(`${supportDir}/heartwood-version`, "utf8")
).substring(0, 7);
const { stdout: version } = await execa("rad", ["--version"]);
if (!version.includes(versionConstraint)) {
throw new Error(
`rad version ${version} does not satisfy ${versionConstraint}`,
);
}
}
async function promptWorkspaceRemoval(): Promise<void> {
console.log("");
console.log("This will irrevocably destroy the following directories:");
console.log("");
workspacePaths.forEach(path => console.log(path));
console.log("");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const result = await rl.question(
"Are you sure you want to continue? [yes/no]: ",
);
rl.close();
if (result.toLowerCase() === "yes") {
console.log("Done");
return;
}
console.log("Ok, I won't touch your data.");
process.exit(1);
}
async function removeWorkspace(): Promise<void> {
for (const path of workspacePaths) {
await Fs.rm(path, {
recursive: true,
force: true,
});
}
}
+1
View File
@@ -0,0 +1 @@
a6a3290833f6da4a7785a426bed342df069ce47f
+217
View File
@@ -0,0 +1,217 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type { ExecaChildProcess, Options } from "execa";
import * as Fs from "node:fs/promises";
import * as Path from "node:path";
import * as Stream from "node:stream";
import getPort from "get-port";
import waitOn from "wait-on";
import { execa } from "execa";
import * as Process from "./process.js";
interface PeerManagerParams {
dataPath: string;
seed: string;
name: string;
gitOptions?: Record<string, string>;
outputLog: Stream.Writable;
}
export interface PeerManager {
startPeer(params: {
name: string;
gitOptions?: Record<string, string>;
}): Promise<RadiclePeer>;
}
export function generateSeed(index: number) {
return Array(64).fill(index.toString()).join("");
}
export async function createPeerManager(createParams: {
dataDir: string;
outputLog?: Stream.Writable;
}): Promise<PeerManager> {
let outputLog: Stream.Writable;
let outputLogFile: Fs.FileHandle;
if (createParams.outputLog) {
outputLog = createParams.outputLog;
} else {
outputLogFile = await Fs.open(
Path.join(createParams.dataDir, "peer-manager.log"),
"a",
);
outputLog = outputLogFile.createWriteStream();
}
const nodes: RadiclePeer[] = [];
return {
// Starts a new node and registers it.
async startPeer(params) {
const peer = await RadiclePeer.create({
dataPath: createParams.dataDir,
name: params.name,
gitOptions: params.gitOptions,
seed: generateSeed(nodes.length + 1),
outputLog,
});
nodes.push(peer);
return peer;
},
};
}
export class RadiclePeer {
public checkoutPath: string;
public nodeId: string;
#seed: string;
#radHome: string;
#outputLog: Stream.Writable;
#gitOptions?: Record<string, string>;
#listenSocketAddr?: string;
private constructor(props: {
checkoutPath: string;
nodeId: string;
seed: string;
gitOptions?: Record<string, string>;
radHome: string;
logFile: Stream.Writable;
}) {
this.checkoutPath = props.checkoutPath;
this.nodeId = props.nodeId;
this.#gitOptions = props.gitOptions;
this.#seed = props.seed;
this.#radHome = props.radHome;
this.#outputLog = props.logFile;
}
public static async create({
dataPath,
name,
gitOptions,
seed,
outputLog: logFile,
}: PeerManagerParams): Promise<RadiclePeer> {
const checkoutPath = Path.join(dataPath, name, "copy");
await Fs.mkdir(checkoutPath, { recursive: true });
const radHome = Path.join(dataPath, name, "home");
await Fs.mkdir(radHome, { recursive: true });
const env = {
...gitOptions,
RAD_HOME: radHome,
RAD_PASSPHRASE: "asdf",
RAD_SEED: seed,
};
await execa("rad", ["auth"], { env });
const { stdout: nodeId } = await execa("rad", ["self", "--nid"], { env });
return new RadiclePeer({
checkoutPath,
gitOptions,
seed,
nodeId,
radHome,
logFile,
});
}
public async startHttpd() {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.spawn("radicle-httpd");
await waitOn({
resources: ["tcp:127.0.0.1:8080"],
timeout: 7000,
});
}
public async startNode(params?: {
connect?: RadiclePeer;
trackingScope?: "trusted" | "all";
trackingPolicy?: "track" | "block";
}) {
const gitPort = await getPort();
const gitSocketAddr = `0.0.0.0:${gitPort}`;
const listenPort = await getPort();
this.#listenSocketAddr = `0.0.0.0:${listenPort}`;
const args = [
"--git-daemon",
gitSocketAddr,
"--listen",
this.#listenSocketAddr,
];
if (params?.connect) {
args.push(
"--connect",
`${params.connect.nodeId}@${params.connect.#listenSocketAddr}`,
);
}
if (params?.trackingScope) {
args.push("--tracking-scope", params.trackingScope);
}
if (params?.trackingPolicy) {
args.push("--tracking-policy", params.trackingPolicy);
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.spawn("radicle-node", args);
await waitOn({
resources: [`tcp:${this.#listenSocketAddr}`],
timeout: 7000,
});
}
public uiUrl(): string {
return `/seeds/127.0.0.1:8080`;
}
public ridUrl(rid: string): string {
return `/seeds/127.0.0.1:8080/${rid}`;
}
public git(args: string[] = [], opts?: Options): ExecaChildProcess {
return this.spawn("git", args, {
cwd: Path.join(this.checkoutPath, "source-browsing"),
...opts,
});
}
public rad(args: string[] = [], opts?: Options): ExecaChildProcess {
return this.spawn("rad", args, {
cwd: Path.join(this.checkoutPath, "source-browsing"),
...opts,
});
}
public spawn(
cmd: string,
args: string[] = [],
opts?: Options,
): ExecaChildProcess {
opts = {
...opts,
env: {
...opts?.env,
...this.#gitOptions,
GIT_CONFIG_GLOBAL: "/dev/null",
GIT_CONFIG_NOSYSTEM: "1",
RAD_HOME: this.#radHome,
RAD_PASSPHRASE: "asdf",
RAD_SEED: this.#seed,
},
};
const childProcess = Process.spawn(cmd, args, opts);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Process.prefixOutput(childProcess, this.nodeId, this.#outputLog);
return childProcess;
}
}
+83
View File
@@ -0,0 +1,83 @@
import type { ExecaChildProcess, Options } from "execa";
import * as Stream from "node:stream";
import onExit from "exit-hook";
import { StringDecoder } from "string_decoder";
import { execa } from "execa";
import { make } from "./logLabel.js";
// Processes that should be SIGKILLed when the Node process shutsdown.
// We add all proxy and seed instances that we spawn to this list.
const processes: ExecaChildProcess[] = [];
onExit(killAllProcesses);
// Kill all processes with SIGKILL
export function killAllProcesses(): void {
for (const process of processes) {
if (process.exitCode === null) {
process.kill("SIGKILL");
}
}
}
// Spawn a process with `execa` and register it.
//
// The process will be killed by `killAllProcesses`.
export function spawn(
bin: string,
args: string[],
options?: Options,
): ExecaChildProcess {
const child = execa(bin, args, options);
processes.push(child);
return child;
}
// Forwards piped `stdout` and `stderr` of a child process to `output`
// and prefixes it with the given label. The prefix is colored.
export function prefixOutput(
childProcess: ExecaChildProcess,
label: string,
output: Stream.Writable,
): ExecaChildProcess {
const pref = make(label);
if (childProcess.stdout) {
const stdoutPrefix = new LinePrefix(pref);
childProcess.stdout.pipe(stdoutPrefix).pipe(output, { end: false });
}
if (childProcess.stderr) {
const stderrPrefix = new LinePrefix(pref);
childProcess.stderr.pipe(stderrPrefix).pipe(output, { end: false });
}
return childProcess;
}
// A transform that prefixes each line from the source with the given
// string and pushes it to the sink.
class LinePrefix extends Stream.Transform {
private buffer: string = "";
private stringDecoder = new StringDecoder();
public constructor(private prefix: string) {
super();
}
public _transform(data: Buffer, _encoding: string, next: () => void): void {
const str = this.buffer + this.stringDecoder.write(data);
const lines = str.split(/\r?\n/);
this.buffer = lines.pop() || "";
lines.forEach(line => this.push(`${this.prefix}${line}\n`));
next();
}
public _flush(done: () => void): void {
const rest = `${this.buffer}${this.stringDecoder.end()}`;
if (rest) {
this.push(`${this.prefix}${rest}\n`);
}
done();
}
}