tests(init): remove MockTTY (#2974)

These changes simplify implementation logic of the init workflow and
mock `prompt()` and `console()` functionality in a more direct manner.
This makes things easier to reason about by jumping through fewer mental
hoops.
This commit is contained in:
Asher Gomez
2025-05-19 10:56:16 +02:00
committed by GitHub
parent 3776ef3154
commit cc93a1f469
2 changed files with 74 additions and 120 deletions
+25 -64
View File
@@ -1,3 +1,4 @@
// deno-lint-ignore-file no-console
import * as colors from "@std/fmt/colors"; import * as colors from "@std/fmt/colors";
import * as path from "@std/path"; import * as path from "@std/path";
@@ -7,14 +8,6 @@ const FRESH_TAILWIND_VERSION = "0.0.1-alpha.7";
const PREACT_VERSION = "10.26.6"; const PREACT_VERSION = "10.26.6";
const PREACT_SIGNALS_VERSION = "2.0.4"; const PREACT_SIGNALS_VERSION = "2.0.4";
export const enum InitStep {
ProjectName = "ProjectName",
Force = "Force",
Tailwind = "Tailwind",
VSCode = "VSCode",
Docker = "Docker",
}
function css(strs: TemplateStringsArray, ...exprs: string[]): string { function css(strs: TemplateStringsArray, ...exprs: string[]): string {
let out = ""; let out = "";
@@ -29,8 +22,8 @@ function css(strs: TemplateStringsArray, ...exprs: string[]): string {
export class InitError extends Error {} export class InitError extends Error {}
function error(tty: MockTTY, message: string): never { function error(message: string): never {
tty.logError(`%cerror%c: ${message}`, "color: red; font-weight: bold", ""); console.error(`%cerror%c: ${message}`, "color: red; font-weight: bold", "");
throw new InitError(); throw new InitError();
} }
@@ -55,33 +48,12 @@ OPTIONS:
--docker Setup Project to use Docker --docker Setup Project to use Docker
`; `;
export interface MockTTY { export const CONFIRM_EMPTY_MESSAGE =
prompt( "The target directory is not empty (files could get overwritten). Do you want to continue anyway?";
step: InitStep, export const CONFIRM_TAILWIND_MESSAGE = `Set up ${
message?: string | undefined, colors.cyan("Tailwind CSS")
_default?: string | undefined, } for styling?`;
): string | null; export const CONFIRM_VSCODE_MESSAGE = `Do you use ${colors.cyan("VS Code")}?`;
confirm(step: InitStep, message?: string | undefined): boolean;
log(...args: unknown[]): void;
logError(...args: unknown[]): void;
}
const realTTY: MockTTY = {
prompt(_step, message, _default) {
return prompt(message, _default);
},
confirm(_step, message) {
return confirm(message);
},
log(...args) {
// deno-lint-ignore no-console
console.log(...args);
},
logError(...args) {
// deno-lint-ignore no-console
console.error(...args);
},
};
export async function initProject( export async function initProject(
cwd = Deno.cwd(), cwd = Deno.cwd(),
@@ -92,34 +64,29 @@ export async function initProject(
tailwind?: boolean | null; tailwind?: boolean | null;
vscode?: boolean | null; vscode?: boolean | null;
} = {}, } = {},
tty: MockTTY = realTTY,
): Promise<void> { ): Promise<void> {
tty.log(); console.log();
tty.log( console.log(
colors.bgRgb8( colors.bgRgb8(
colors.rgb8(" 🍋 Fresh: The next-gen web framework. ", 0), colors.rgb8(" 🍋 Fresh: The next-gen web framework. ", 0),
121, 121,
), ),
); );
tty.log(); console.log();
let unresolvedDirectory = Deno.args[0]; let unresolvedDirectory = Deno.args[0];
if (input.length !== 1) { if (input.length !== 1) {
const userInput = tty.prompt( const userInput = prompt(
InitStep.ProjectName,
"Project Name:", "Project Name:",
"fresh-project", "fresh-project",
); );
if (!userInput) { if (!userInput) {
error(tty, HELP_TEXT); error(HELP_TEXT);
} }
unresolvedDirectory = userInput; unresolvedDirectory = userInput;
} }
const CONFIRM_EMPTY_MESSAGE =
"The target directory is not empty (files could get overwritten). Do you want to continue anyway?";
const projectDir = path.resolve(cwd, unresolvedDirectory); const projectDir = path.resolve(cwd, unresolvedDirectory);
try { try {
@@ -128,11 +95,9 @@ export async function initProject(
dir.length === 1 && dir[0].name === ".git"; dir.length === 1 && dir[0].name === ".git";
if ( if (
!isEmpty && !isEmpty &&
!(flags.force === null !(flags.force === null ? confirm(CONFIRM_EMPTY_MESSAGE) : flags.force)
? tty.confirm(InitStep.Force, CONFIRM_EMPTY_MESSAGE)
: flags.force)
) { ) {
error(tty, "Directory is not empty."); error("Directory is not empty.");
} }
} catch (err) { } catch (err) {
if (!(err instanceof Deno.errors.NotFound)) { if (!(err instanceof Deno.errors.NotFound)) {
@@ -144,18 +109,14 @@ export async function initProject(
let useTailwind = flags.tailwind || false; let useTailwind = flags.tailwind || false;
if (flags.tailwind == null) { if (flags.tailwind == null) {
if ( if (
tty.confirm( confirm(CONFIRM_TAILWIND_MESSAGE)
InitStep.Tailwind,
`Set up ${colors.cyan("Tailwind CSS")} for styling?`,
)
) { ) {
useTailwind = true; useTailwind = true;
} }
} }
const USE_VSCODE_MESSAGE = `Do you use ${colors.cyan("VS Code")}?`;
const useVSCode = flags.vscode == null const useVSCode = flags.vscode == null
? tty.confirm(InitStep.VSCode, USE_VSCODE_MESSAGE) ? confirm(CONFIRM_VSCODE_MESSAGE)
: flags.vscode; : flags.vscode;
const writeFile = async ( const writeFile = async (
@@ -715,30 +676,30 @@ This will watch the project directory and restart as necessary.`;
// Specifically print unresolvedDirectory, rather than resolvedDirectory in order to // Specifically print unresolvedDirectory, rather than resolvedDirectory in order to
// not leak personal info (e.g. `/Users/MyName`) // not leak personal info (e.g. `/Users/MyName`)
tty.log("\n%cProject initialized!\n", "color: green; font-weight: bold"); console.log("\n%cProject initialized!\n", "color: green; font-weight: bold");
if (unresolvedDirectory !== ".") { if (unresolvedDirectory !== ".") {
tty.log( console.log(
`Enter your project directory using %ccd ${unresolvedDirectory}%c.`, `Enter your project directory using %ccd ${unresolvedDirectory}%c.`,
"color: cyan", "color: cyan",
"", "",
); );
} }
tty.log( console.log(
"Run %cdeno task start%c to start the project. %cCTRL-C%c to stop.", "Run %cdeno task start%c to start the project. %cCTRL-C%c to stop.",
"color: cyan", "color: cyan",
"", "",
"color: cyan", "color: cyan",
"", "",
); );
tty.log(); console.log();
tty.log( console.log(
"Stuck? Join our Discord %chttps://discord.gg/deno", "Stuck? Join our Discord %chttps://discord.gg/deno",
"color: cyan", "color: cyan",
"", "",
); );
tty.log(); console.log();
tty.log( console.log(
"%cHappy hacking! 🦕", "%cHappy hacking! 🦕",
"color: gray", "color: gray",
); );
+49 -56
View File
@@ -1,9 +1,26 @@
import { expect } from "@std/expect"; import { expect } from "@std/expect";
import { initProject, InitStep, type MockTTY } from "./init.ts"; import {
CONFIRM_TAILWIND_MESSAGE,
CONFIRM_VSCODE_MESSAGE,
initProject,
} from "./init.ts";
import * as path from "@std/path"; import * as path from "@std/path";
import { getStdOutput, withBrowser } from "../../tests/test_utils.tsx"; import { getStdOutput, withBrowser } from "../../tests/test_utils.tsx";
import { waitForText } from "../../tests/test_utils.tsx"; import { waitForText } from "../../tests/test_utils.tsx";
import { withChildProcessServer } from "../../tests/test_utils.tsx"; import { withChildProcessServer } from "../../tests/test_utils.tsx";
import { stub } from "@std/testing/mock";
function stubPrompt(result: string) {
return stub(globalThis, "prompt", () => result);
}
function stubConfirm(steps: Record<string, boolean> = {}) {
return stub(
globalThis,
"confirm",
(message) => message ? steps[message] : false,
);
}
async function withTmpDir(fn: (dir: string) => void | Promise<void>) { async function withTmpDir(fn: (dir: string) => void | Promise<void>) {
const hash = crypto.randomUUID().replaceAll(/-/g, ""); const hash = crypto.randomUUID().replaceAll(/-/g, "");
@@ -32,29 +49,6 @@ async function patchProject(dir: string): Promise<void> {
await Deno.writeTextFile(jsonPath, JSON.stringify(json, null, 2) + "\n"); await Deno.writeTextFile(jsonPath, JSON.stringify(json, null, 2) + "\n");
} }
function mockUserInput(steps: Record<string, unknown>) {
const errorOutput: unknown[][] = [];
const tty: MockTTY = {
confirm(step, _msg) {
return Boolean(steps[step]);
},
prompt(step, _msg, def) {
const setting = typeof steps[step] === "string"
? steps[step] as string
: null;
return setting ?? def ?? null;
},
log: () => {},
logError: (...args) => {
errorOutput.push(args);
},
};
return {
errorOutput,
tty,
};
}
async function expectProjectFile(dir: string, pathname: string) { async function expectProjectFile(dir: string, pathname: string) {
const filePath = path.join(dir, ...pathname.split("/").filter(Boolean)); const filePath = path.join(dir, ...pathname.split("/").filter(Boolean));
const stat = await Deno.stat(filePath); const stat = await Deno.stat(filePath);
@@ -71,15 +65,17 @@ async function readProjectFile(dir: string, pathname: string): Promise<string> {
Deno.test("init - new project", async () => { Deno.test("init - new project", async () => {
await withTmpDir(async (dir) => { await withTmpDir(async (dir) => {
const mock = mockUserInput({}); using _promptStub = stubPrompt("fresh-init");
await initProject(dir, [], {}, mock.tty); using _confirmStub = stubConfirm();
await initProject(dir, [], {});
}); });
}); });
Deno.test("init - create project dir", async () => { Deno.test("init - create project dir", async () => {
await withTmpDir(async (dir) => { await withTmpDir(async (dir) => {
const mock = mockUserInput({ [InitStep.ProjectName]: "fresh-init" }); using _promptStub = stubPrompt("fresh-init");
await initProject(dir, [], {}, mock.tty); using _confirmStub = stubConfirm();
await initProject(dir, [], {});
const root = path.join(dir, "fresh-init"); const root = path.join(dir, "fresh-init");
await expectProjectFile(root, "deno.json"); await expectProjectFile(root, "deno.json");
@@ -92,11 +88,11 @@ Deno.test("init - create project dir", async () => {
Deno.test("init - with tailwind", async () => { Deno.test("init - with tailwind", async () => {
await withTmpDir(async (dir) => { await withTmpDir(async (dir) => {
const mock = mockUserInput({ using _promptStub = stubPrompt(".");
[InitStep.ProjectName]: ".", using _confirmStub = stubConfirm({
[InitStep.Tailwind]: true, [CONFIRM_TAILWIND_MESSAGE]: true,
}); });
await initProject(dir, [], {}, mock.tty); await initProject(dir, [], {});
const css = await readProjectFile(dir, "static/styles.css"); const css = await readProjectFile(dir, "static/styles.css");
expect(css).toMatch(/@tailwind/); expect(css).toMatch(/@tailwind/);
@@ -110,11 +106,11 @@ Deno.test("init - with tailwind", async () => {
Deno.test("init - with vscode", async () => { Deno.test("init - with vscode", async () => {
await withTmpDir(async (dir) => { await withTmpDir(async (dir) => {
const mock = mockUserInput({ using _promptStub = stubPrompt(".");
[InitStep.ProjectName]: ".", using _confirmStub = stubConfirm({
[InitStep.VSCode]: true, [CONFIRM_VSCODE_MESSAGE]: true,
}); });
await initProject(dir, [], {}, mock.tty); await initProject(dir, [], {});
await expectProjectFile(dir, ".vscode/settings.json"); await expectProjectFile(dir, ".vscode/settings.json");
await expectProjectFile(dir, ".vscode/extensions.json"); await expectProjectFile(dir, ".vscode/extensions.json");
@@ -128,10 +124,9 @@ Deno.test({
ignore: Deno.version.deno.includes("+"), ignore: Deno.version.deno.includes("+"),
fn: async () => { fn: async () => {
await withTmpDir(async (dir) => { await withTmpDir(async (dir) => {
const mock = mockUserInput({ using _promptStub = stubPrompt(".");
[InitStep.ProjectName]: ".", using _confirmStub = stubConfirm();
}); await initProject(dir, [], {});
await initProject(dir, [], {}, mock.tty);
await expectProjectFile(dir, "main.ts"); await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts"); await expectProjectFile(dir, "dev.ts");
@@ -150,11 +145,12 @@ Deno.test({
Deno.test("init with tailwind - fmt, lint, and type check project", async () => { Deno.test("init with tailwind - fmt, lint, and type check project", async () => {
await withTmpDir(async (dir) => { await withTmpDir(async (dir) => {
const mock = mockUserInput({ using _promptStub = stubPrompt(".");
[InitStep.ProjectName]: ".", using _confirmStub = stubConfirm({
[InitStep.Tailwind]: true, [CONFIRM_TAILWIND_MESSAGE]: true,
}); });
await initProject(dir, [], {}, mock.tty);
await initProject(dir, [], {});
await expectProjectFile(dir, "main.ts"); await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts"); await expectProjectFile(dir, "dev.ts");
@@ -172,10 +168,9 @@ Deno.test("init with tailwind - fmt, lint, and type check project", async () =>
Deno.test("init - can start dev server", async () => { Deno.test("init - can start dev server", async () => {
await withTmpDir(async (dir) => { await withTmpDir(async (dir) => {
const mock = mockUserInput({ using _promptStub = stubPrompt(".");
[InitStep.ProjectName]: ".", using _confirmStub = stubConfirm();
}); await initProject(dir, [], {});
await initProject(dir, [], {}, mock.tty);
await expectProjectFile(dir, "main.ts"); await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts"); await expectProjectFile(dir, "dev.ts");
@@ -196,10 +191,9 @@ Deno.test("init - can start dev server", async () => {
Deno.test("init - can start built project", async () => { Deno.test("init - can start built project", async () => {
await withTmpDir(async (dir) => { await withTmpDir(async (dir) => {
const mock = mockUserInput({ using _promptStub = stubPrompt(".");
[InitStep.ProjectName]: ".", using _confirmStub = stubConfirm();
}); await initProject(dir, [], {});
await initProject(dir, [], {}, mock.tty);
await expectProjectFile(dir, "main.ts"); await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts"); await expectProjectFile(dir, "dev.ts");
@@ -230,10 +224,9 @@ Deno.test("init - can start built project", async () => {
Deno.test("init - errors on missing build cache in prod", async () => { Deno.test("init - errors on missing build cache in prod", async () => {
await withTmpDir(async (dir) => { await withTmpDir(async (dir) => {
const mock = mockUserInput({ using _promptStub = stubPrompt(".");
[InitStep.ProjectName]: ".", using _confirmStub = stubConfirm();
}); await initProject(dir, [], {});
await initProject(dir, [], {}, mock.tty);
await expectProjectFile(dir, "main.ts"); await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts"); await expectProjectFile(dir, "dev.ts");