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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 52 additions & 5 deletions src/browser/commands/switchToRepl.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import path from "node:path";
import type repl from "node:repl";
import repl from "node:repl";
import net from "node:net";
import { Writable, Readable } from "node:stream";
import { getEventListeners } from "node:events";
import chalk from "chalk";
import RuntimeConfig from "../../config/runtime-config";
Expand Down Expand Up @@ -39,11 +41,17 @@ export default (browser: Browser): void => {
});
};

const broadcastMessage = (message: string, sockets: net.Socket[]): void => {
for (const s of sockets) {
s.write(message);
}
};

session.addCommand("switchToRepl", async function (ctx: Record<string, unknown> = {}) {
const runtimeCfg = RuntimeConfig.getInstance();
const { onReplMode } = browser.state;

if (!runtimeCfg.replMode?.enabled) {
if (!runtimeCfg.replMode || !runtimeCfg.replMode.enabled) {
throw new Error(
'Command "switchToRepl" available only in REPL mode, which can be started using cli option: "--repl", "--repl-before-test" or "--repl-on-fail"',
);
Expand All @@ -54,23 +62,62 @@ export default (browser: Browser): void => {
return;
}

logger.log(chalk.yellow("You have entered to REPL mode via terminal (test execution timeout is disabled)."));
logger.log(
chalk.yellow(
`You have entered to REPL mode via terminal (test execution timeout is disabled). Port to connect to REPL from other terminals: ${runtimeCfg.replMode.port}`,
),
);

const currCwd = process.cwd();
const testCwd = path.dirname(session.executionContext.ctx.currentTest.file!);
process.chdir(testCwd);

const replServer = await import("node:repl").then(m => m.start({ prompt: "> " }));
let allSockets: net.Socket[] = [];

browser.applyState({ onReplMode: true });
const input = new Readable({ read(): void {} });
const output = new Writable({
write(chunk, _, callback): void {
broadcastMessage(chunk.toString(), [...allSockets, process.stdout]);
callback();
},
});

const replServer = repl.start({ prompt: "> ", input, output });

const netServer = net
.createServer(socket => {
allSockets.push(socket);

socket.on("data", data => {
broadcastMessage(data.toString(), [...allSockets.filter(s => s !== socket), process.stdout]);
input.push(data);
});

socket.on("close", () => {
allSockets = allSockets.filter(s => s !== socket);
});
})
.listen(runtimeCfg.replMode.port);

process.stdin.on("data", data => {
broadcastMessage(data.toString(), allSockets);
input.push(data);
});

browser.applyState({ onReplMode: true });
runtimeCfg.extend({ replServer });

applyContext(replServer, ctx);
handleLines(replServer);

return new Promise<void>(resolve => {
return replServer.on("exit", () => {
netServer.close();

for (const socket of allSockets) {
socket.end("The server was closed after the REPL was exited");
}

process.chdir(currCwd);
browser.applyState({ onReplMode: false });
resolve();
Expand Down
27 changes: 25 additions & 2 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from "node:path";
import { Command } from "@gemini-testing/commander";
import getPort from "get-port";

import defaults from "../config/defaults";
import { configOverriding } from "./info";
Expand Down Expand Up @@ -75,6 +76,12 @@ export const run = async (opts: TestplaneRunOpts = {}): Promise<void> => {
)
.option("--repl-before-test [type]", "open repl interface before test run", Boolean, false)
.option("--repl-on-fail [type]", "open repl interface on test fail only", Boolean, false)
.option(
"--repl-port <number>",
"run net server on port to exchange messages with repl (used free random port by default)",
Number,
0,
)
.option("--devtools", "switches the browser to the devtools mode with using CDP protocol")
.option("--local", "use local browsers, managed by testplane (same as 'gridUrl': 'local')")
.option("--keep-browser", "do not close browser session after test completion")
Expand All @@ -90,7 +97,6 @@ export const run = async (opts: TestplaneRunOpts = {}): Promise<void> => {
updateRefs,
inspect,
inspectBrk,
repl,
replBeforeTest,
replOnFail,
devtools,
Expand All @@ -108,9 +114,10 @@ export const run = async (opts: TestplaneRunOpts = {}): Promise<void> => {
requireModules,
inspectMode: (inspect || inspectBrk) && { inspect, inspectBrk },
replMode: {
enabled: repl || replBeforeTest || replOnFail,
enabled: isReplModeEnabled(program),
beforeTest: replBeforeTest,
onFail: replOnFail,
port: await getReplPort(program),
},
devtools: devtools || false,
local: local || false,
Expand Down Expand Up @@ -148,3 +155,19 @@ function preparseOption(program: Command, option: string): unknown {
configFileParser.parse(process.argv);
return configFileParser[option];
}

function isReplModeEnabled(program: Command): boolean {
const { repl, replBeforeTest, replOnFail } = program;

return repl || replBeforeTest || replOnFail;
}

async function getReplPort(program: Command): Promise<number> {
let { replPort } = program;

if (isReplModeEnabled(program) && !replPort) {
replPort = await getPort();
}

return replPort;
}
1 change: 1 addition & 0 deletions src/testplane.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ interface RunOpts {
enabled: boolean;
beforeTest: boolean;
onFail: boolean;
port: number;
};
devtools: boolean;
local: boolean;
Expand Down
159 changes: 153 additions & 6 deletions test/src/browser/commands/switchToRepl.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import repl, { type REPLServer } from "node:repl";
import net from "node:net";
import { PassThrough } from "node:stream";
import { EventEmitter } from "node:events";
import proxyquire from "proxyquire";
import chalk from "chalk";
Expand All @@ -11,12 +13,17 @@ import type { ExistingBrowser as ExistingBrowserOriginal } from "src/browser/exi

describe('"switchToRepl" command', () => {
const sandbox = sinon.createSandbox();
const stdinStub = new PassThrough();
const stdoutStub = new PassThrough();
const originalStdin = process.stdin;
const originalStdout = process.stdout;

let ExistingBrowser: typeof ExistingBrowserOriginal;
let logStub: SinonStub;
let warnStub: SinonStub;
let webdriverioAttachStub: SinonStub;
let clientBridgeBuildStub;
let netCreateServerCb: (socket: net.Socket) => void;

const initBrowser_ = ({
browser = mkBrowser_(undefined, undefined, ExistingBrowser),
Expand All @@ -39,6 +46,28 @@ describe('"switchToRepl" command', () => {
return replServer;
};

const mkNetServer_ = (): net.Server => {
const netServer = new EventEmitter() as net.Server;
netServer.listen = sandbox.stub().named("listen").returnsThis();
netServer.close = sandbox.stub().named("close").returnsThis();

(sandbox.stub(net, "createServer") as SinonStub).callsFake(cb => {
netCreateServerCb = cb;
return netServer;
});

return netServer;
};

const mkSocket_ = (): net.Socket => {
const socket = new EventEmitter() as net.Socket;

socket.write = sandbox.stub().named("write").returns(true);
socket.end = sandbox.stub().named("end").returnsThis();

return socket;
};

const switchToRepl_ = async ({
session = mkSessionStub_(),
replServer = mkReplServer_(),
Expand Down Expand Up @@ -72,9 +101,24 @@ describe('"switchToRepl" command', () => {

sandbox.stub(RuntimeConfig, "getInstance").returns({ replMode: { enabled: false }, extend: sinon.stub() });
sandbox.stub(process, "chdir");

Object.defineProperty(process, "stdin", {
value: stdinStub,
configurable: true,
});
Object.defineProperty(process, "stdout", {
value: stdoutStub,
configurable: true,
});
sandbox.stub(stdoutStub, "write");
});

afterEach(() => sandbox.restore());
afterEach(() => {
sandbox.restore();

Object.defineProperty(process, "stdin", { value: originalStdin });
Object.defineProperty(process, "sdout", { value: originalStdout });
});

it("should add command", async () => {
const session = mkSessionStub_();
Expand All @@ -97,8 +141,14 @@ describe('"switchToRepl" command', () => {
});

describe("in REPL mode", async () => {
let netServer!: net.Server;

beforeEach(() => {
(RuntimeConfig.getInstance as SinonStub).returns({ replMode: { enabled: true }, extend: sinon.stub() });
netServer = mkNetServer_();
(RuntimeConfig.getInstance as SinonStub).returns({
replMode: { enabled: true, port: 12345 },
extend: sinon.stub(),
});
});

it("should inform that user entered to repl server before run it", async () => {
Expand All @@ -107,12 +157,13 @@ describe('"switchToRepl" command', () => {
await initBrowser_({ session });
await switchToRepl_({ session });

assert.callOrder(
(logStub as SinonStub).withArgs(
chalk.yellow("You have entered to REPL mode via terminal (test execution timeout is disabled)."),
assert.calledOnceWith(
logStub,
chalk.yellow(
"You have entered to REPL mode via terminal (test execution timeout is disabled). Port to connect to REPL from other terminals: 12345",
),
repl.start as SinonStub,
);
assert.callOrder(logStub as SinonStub, repl.start as SinonStub);
});

it("should change cwd to test directory before run repl server", async () => {
Expand Down Expand Up @@ -256,5 +307,101 @@ describe('"switchToRepl" command', () => {
});
});
});

describe("net server", () => {
it("should create server with listen port from runtime config", async () => {
const runtimeCfg = { replMode: { enabled: true, port: 33333 }, extend: sinon.stub() };
(RuntimeConfig.getInstance as SinonStub).returns(runtimeCfg);

const session = mkSessionStub_();

await initBrowser_({ session });
await switchToRepl_({ session });

assert.calledOnceWith(netServer.listen, 33333);
});

it("should broadcast message from stdin to connected sockets", async () => {
const socket1 = mkSocket_();
const socket2 = mkSocket_();
const session = mkSessionStub_();

await initBrowser_({ session });
await switchToRepl_({ session });

netCreateServerCb(socket1);
netCreateServerCb(socket2);
stdinStub.write("o.O");

assert.calledOnceWith(socket1.write, "o.O");
assert.calledOnceWith(socket2.write, "o.O");
});

it("should broadcast message from socket to other sockets and stdin", async () => {
const socket1 = mkSocket_();
const socket2 = mkSocket_();
const session = mkSessionStub_();

await initBrowser_({ session });
await switchToRepl_({ session });

netCreateServerCb(socket1);
netCreateServerCb(socket2);
socket1.emit("data", Buffer.from("o.O"));

assert.notCalled(socket1.write as SinonStub);
assert.calledOnceWith(socket2.write, "o.O");
assert.calledOnceWith(process.stdout.write, "o.O");
});

it("should not broadcast message to closed socket", async () => {
const socket1 = mkSocket_();
const socket2 = mkSocket_();
const session = mkSessionStub_();

await initBrowser_({ session });
await switchToRepl_({ session });

netCreateServerCb(socket1);
netCreateServerCb(socket2);

socket1.emit("close");
stdinStub.write("o.O");

assert.notCalled(socket1.write as SinonStub);
assert.calledOnceWith(socket2.write, "o.O");
});

it("should close net server on exit from repl", async () => {
const session = mkSessionStub_();
const replServer = mkReplServer_();

await initBrowser_({ session });
const promise = session.switchToRepl();
replServer.emit("exit");
await promise;

assert.calledOnceWith(netServer.close);
});

it("should end sockets on exit from repl", async () => {
const socket1 = mkSocket_();
const socket2 = mkSocket_();
const session = mkSessionStub_();
const replServer = mkReplServer_();

await initBrowser_({ session });
const promise = session.switchToRepl();

netCreateServerCb(socket1);
netCreateServerCb(socket2);

replServer.emit("exit");
await promise;

assert.calledOnceWith(socket1.end, "The server was closed after the REPL was exited");
assert.calledOnceWith(socket2.end, "The server was closed after the REPL was exited");
});
});
});
});
Loading
Loading