Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Further wrangler init tests (and refactorings) #124

Merged
merged 7 commits into from
Dec 17, 2021
Merged
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
11 changes: 11 additions & 0 deletions .changeset/forty-cooks-flash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"wrangler": patch
---

Error and exit if the `--type` option is used for the `init` command.

The `--type` option is no longer needed, nor supported.

The type of a project is implicitly javascript, even if it includes a wasm (e.g. built from rust).

Projects that would have had the `webpack` type need to be configured separately to have a custom build.
5 changes: 5 additions & 0 deletions .changeset/short-humans-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wrangler": patch
---

Allow the developer to exit `init` if there is already a toml file
1 change: 1 addition & 0 deletions packages/wrangler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"node": ">=16.7.0"
},
"jest": {
"restoreMocks": true,
petebacondarwin marked this conversation as resolved.
Show resolved Hide resolved
"testRegex": ".*.(test|spec)\\.[jt]sx?$",
"transformIgnorePatterns": [
"node_modules/(?!node-fetch|fetch-blob|find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|data-uri-to-buffer|formdata-polyfill|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream)"
Expand Down
133 changes: 94 additions & 39 deletions packages/wrangler/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,33 @@ import * as path from "node:path";
import * as TOML from "@iarna/toml";
import { main } from "../index";
import { setMock, unsetAllMocks } from "./mock-cfetch";
import { existsSync } from "node:fs";
import { dialogs } from "../dialogs";

jest.mock("../cfetch", () => jest.requireActual("./mock-cfetch"));

async function w(cmd: void | string, options?: { tap: boolean }) {
const tapped = options?.tap ? tap() : undefined;
await main([...(cmd ? cmd.split(" ") : [])]);
tapped?.off();
return { stdout: tapped?.out, stderr: tapped?.err };
}

function tap() {
const oldLog = console.log;
const oldError = console.error;

const toReturn = {
off: () => {
console.log = oldLog;
console.error = oldError;
},
out: "",
err: "",
};

console.log = (...args) => {
toReturn.out += args.join("");
oldLog.apply(console, args);
// console.trace(...args); // use this if you want to find the true source of your console.log
};
console.error = (...args) => {
toReturn.err += args.join("");
oldError.apply(console, args);
};

return toReturn;
async function w(cmd?: string) {
const logSpy = jest.spyOn(console, "log").mockImplementation();
const errorSpy = jest.spyOn(console, "error").mockImplementation();
const warnSpy = jest.spyOn(console, "warn").mockImplementation();
try {
await main(cmd?.split(" ") ?? []);
return {
stdout: logSpy.mock.calls.flat(2).join("\n"),
stderr: errorSpy.mock.calls.flat(2).join("\n"),
warnings: warnSpy.mock.calls.flat(2).join("\n"),
};
} finally {
logSpy.mockRestore();
errorSpy.mockRestore();
warnSpy.mockRestore();
}
}

describe("wrangler", () => {
describe("no command", () => {
it("should display a list of available commands", async () => {
const { stdout, stderr } = await w(undefined, { tap: true });
const { stdout, stderr } = await w();

expect(stdout).toMatchInlineSnapshot(`
"wrangler
Expand All @@ -68,13 +55,13 @@ describe("wrangler", () => {
-l, --local Run on my machine [boolean] [default: false]"
`);

expect(stderr).toEqual("");
expect(stderr).toMatchInlineSnapshot(`""`);
});
});

describe("invalid command", () => {
it("should display an error", async () => {
const { stdout, stderr } = await w("invalid-command", { tap: true });
const { stdout, stderr } = await w("invalid-command");

expect(stdout).toMatchInlineSnapshot(`
"wrangler
Expand Down Expand Up @@ -114,7 +101,9 @@ describe("wrangler", () => {
});

afterEach(async () => {
await fsp.rm("./wrangler.toml");
if (existsSync("./wrangler.toml")) {
await fsp.rm("./wrangler.toml");
}
process.chdir(ogcwd);
});

Expand All @@ -124,10 +113,57 @@ describe("wrangler", () => {
expect(typeof parsed.compatibility_date).toBe("string");
});

it("should error when wrangler.toml already exists", async () => {
it("should display warning when wrangler.toml already exists, and exit if user does not want to carry on", async () => {
fs.closeSync(fs.openSync("./wrangler.toml", "w"));
const { stderr } = await w("init", { tap: true });
expect(stderr.endsWith("wrangler.toml already exists.")).toBe(true);
mockConfirm({
text: "Do you want to continue initializing this project?",
result: false,
});
const { stderr } = await w("init");
expect(stderr).toContain("wrangler.toml file already exists!");
const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
expect(typeof parsed.compatibility_date).toBe("undefined");
});

it("should display warning when wrangler.toml already exists, but continue if user does want to carry on", async () => {
fs.closeSync(fs.openSync("./wrangler.toml", "w"));
mockConfirm({
text: "Do you want to continue initializing this project?",
result: true,
});
const { stderr } = await w("init");
expect(stderr).toContain("wrangler.toml file already exists!");
const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
expect(typeof parsed.compatibility_date).toBe("string");
});

it("should error if `--type` is used", async () => {
const noValue = await w("init --type");
expect(noValue.stderr).toMatchInlineSnapshot(
`"The --type option is no longer supported."`
);
});

it("should error if `--type javascript` is used", async () => {
const javascriptValue = await w("init --type javascript");
expect(javascriptValue.stderr).toMatchInlineSnapshot(
`"The --type option is no longer supported."`
);
});

it("should error if `--type rust` is used", async () => {
const rustValue = await w("init --type rust");
expect(rustValue.stderr).toMatchInlineSnapshot(
`"The --type option is no longer supported."`
);
});

it("should error if `--type webpack` is used", async () => {
const webpackValue = await w("init --type webpack");
expect(webpackValue.stderr).toMatchInlineSnapshot(`
"The --type option is no longer supported.
If you wish to use webpack then you will need to create a custom build."
`);
});
});

Expand Down Expand Up @@ -160,7 +196,7 @@ describe("wrangler", () => {
return KVNamespaces;
}
);
const { stdout } = await w("kv:namespace list", { tap: true });
const { stdout } = await w("kv:namespace list");
const namespaces = JSON.parse(stdout);
createdNamespace = namespaces.find(
(ns) => ns.title === "worker-UnitTestNamespace"
Expand All @@ -186,3 +222,22 @@ describe("wrangler", () => {
});
});
});

/**
* Create a mock version of `confirm()` that will respond with configured results
* for configured confirmation text messages.
*
* If there is a call to `confirm()` that does not match any of the expectations
* then an error is thrown.
*/
function mockConfirm(...expectations: { text: string; result: boolean }[]) {
const mockImplementation = async (text: string) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dope mock, solves the input problem neatly.

for (const { text: expectedText, result } of expectations) {
if (text === expectedText) {
return result;
}
}
throw new Error(`Unexpected confirmation message: ${text}`);
};
return jest.spyOn(dialogs, "confirm").mockImplementation(mockImplementation);
}
10 changes: 8 additions & 2 deletions packages/wrangler/src/dialogs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function Confirm(props: ConfirmProps) {
);
}

export function confirm(text: string): Promise<boolean> {
function confirm(text: string): Promise<boolean> {
return new Promise((resolve) => {
const { unmount } = render(
<Confirm
Expand Down Expand Up @@ -61,7 +61,7 @@ function Prompt(props: PromptProps) {
);
}

export async function prompt(text: string, type: "text" | "password" = "text") {
async function prompt(text: string, type: "text" | "password" = "text") {
return new Promise((resolve) => {
const { unmount } = render(
<Prompt
Expand All @@ -83,3 +83,9 @@ export async function prompt(text: string, type: "text" | "password" = "text") {
// ): Promise<{ label: string; value: string }>{

// }

// Export as an object so that it is easier to mock for testing
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't be necessary, but I'll swing by next week and figure out mocking that'll let us keep the original exports. (Dropping this comment here to remind myself)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried a number of different ways to achieve this by "mocking" the module. But it either didn't work or was really messy. I would be interested to see your approach.

export const dialogs = {
confirm,
prompt,
};
63 changes: 43 additions & 20 deletions packages/wrangler/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type yargs from "yargs";
import { findUp } from "find-up";
import TOML from "@iarna/toml";
import type { Config } from "./config";
import { confirm, prompt } from "./dialogs";
import { dialogs } from "./dialogs";
import { version as wranglerVersion } from "../package.json";
import {
login,
Expand Down Expand Up @@ -187,32 +187,51 @@ export async function main(argv: string[]): Promise<void> {
type: "string",
});
},
async () => {
async (args) => {
if ("type" in args) {
let message = "The --type option is no longer supported.";
if (args.type === "webpack") {
message +=
"\nIf you wish to use webpack then you will need to create a custom build.";
// TODO: Add a link to docs
}
console.error(message);
return;
}

const destination = path.join(process.cwd(), "wrangler.toml");
if (fs.existsSync(destination)) {
console.error(`${destination} already exists.`);
} else {
const compatibilityDate = new Date().toISOString().substring(0, 10);
try {
await writeFile(
destination,
`compatibility_date = "${compatibilityDate}"` + "\n"
);
console.log(`✨ Succesfully created wrangler.toml`);
// TODO: suggest next steps?
} catch (err) {
console.error(`Failed to create wrangler.toml`);
console.error(err);
throw err;
console.error(`${destination} file already exists!`);
const result = await dialogs.confirm(
"Do you want to continue initializing this project?"
);
if (!result) {
return;
}
}

const compatibilityDate = new Date().toISOString().substring(0, 10);
try {
await writeFile(
destination,
`compatibility_date = "${compatibilityDate}"` + "\n"
);
console.log(`✨ Succesfully created wrangler.toml`);
// TODO: suggest next steps?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the future, this might be a great place to suggest a list of "starters" and automatically make a src with contents. This may be a good replacement for the generate command.

} catch (err) {
console.error(`Failed to create wrangler.toml`);
console.error(err);
throw err;
}

// if no package.json, ask, and if yes, create one
let pathToPackageJson = await findUp("package.json");

if (!pathToPackageJson) {
if (
await confirm("No package.json found. Would you like to create one?")
await dialogs.confirm(
"No package.json found. Would you like to create one?"
)
) {
await writeFile(
path.join(process.cwd(), "package.json"),
Expand All @@ -237,7 +256,7 @@ export async function main(argv: string[]): Promise<void> {
// and make a tsconfig?
let pathToTSConfig = await findUp("tsconfig.json");
if (!pathToTSConfig) {
if (await confirm("Would you like to use typescript?")) {
if (await dialogs.confirm("Would you like to use typescript?")) {
await writeFile(
path.join(process.cwd(), "tsconfig.json"),
JSON.stringify(
Expand Down Expand Up @@ -896,7 +915,7 @@ export async function main(argv: string[]): Promise<void> {

// -- snip, end --

const secretValue = await prompt(
const secretValue = await dialogs.prompt(
"Enter a secret value:",
"password"
);
Expand Down Expand Up @@ -996,7 +1015,11 @@ export async function main(argv: string[]): Promise<void> {

// -- snip, end --

if (await confirm("Are you sure you want to delete this secret?")) {
if (
await dialogs.confirm(
"Are you sure you want to delete this secret?"
)
) {
console.log(
`Deleting the secret ${args.key} on script ${scriptName}.`
);
Expand Down