test: use disposable tmp dirs (#2983)

Replaces the patterns below with consistent `AsyncDisposable` and `await
using` resource management for automatic cleanup.

- `await withTmpDir(async (dir) => { ... })` with `finally`
  - Makes code a bit flatter, and reduces callback-hell a bit
- `await Deno.makeTempDir()` + `Deno.remove()`
- `await Deno.makeTempDir()`

Helps be more consistent in removing temporary folders. Among others,
ensures temp folders are removed in the tests below:

- `src/build_cache_test.ts`
- `src/dev/builder_test.ts`
- `src/dev/dev_build_cache_test.ts`

## TODO's

The `Deno.makeTempDir()` method is still used by `buildProd` as well,
but this method is used in the top module scope, where it does not work
correctly with `Deno.test` (it runs before the test methods). I removed
this part from the PR and leave this for later to avoid making the PR
too big.

-
https://github.com/csvn/fresh/blob/test%2Fdisposable-tmp-dirs/tests/test_utils.tsx/#L64
-
https://github.com/csvn/fresh/blob/test%2Fdisposable-tmp-dirs/www/main_test.ts/#L7
This commit is contained in:
Christian Svensson
2025-05-21 11:13:02 +02:00
committed by GitHub
parent db142115ec
commit 17257dd1c2
7 changed files with 482 additions and 491 deletions
+135 -139
View File
@@ -8,6 +8,7 @@ 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 { withTmpDir as withTmpDirBase } from "../../src/test_utils.ts";
import { stub } from "@std/testing/mock"; import { stub } from "@std/testing/mock";
function stubPrompt(result: string) { function stubPrompt(result: string) {
@@ -22,16 +23,11 @@ function stubConfirm(steps: Record<string, boolean> = {}) {
); );
} }
async function withTmpDir(fn: (dir: string) => void | Promise<void>) { function withTmpDir(): Promise<{ dir: string } & AsyncDisposable> {
const hash = crypto.randomUUID().replaceAll(/-/g, ""); return withTmpDirBase({
const dir = path.join(import.meta.dirname!, "..", "..", `tmp_${hash}`); dir: path.join(import.meta.dirname!, "..", ".."),
await Deno.mkdir(dir, { recursive: true }); prefix: "tmp_",
});
try {
await fn(dir);
} finally {
await Deno.remove(dir, { recursive: true });
}
} }
async function patchProject(dir: string): Promise<void> { async function patchProject(dir: string): Promise<void> {
@@ -64,57 +60,57 @@ 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 using tmp = await withTmpDir();
using _promptStub = stubPrompt("fresh-init"); using _promptStub = stubPrompt("fresh-init");
using _confirmStub = stubConfirm(); using _confirmStub = stubConfirm();
await initProject(dir, [], {});
}); await initProject(tmp.dir, [], {});
}); });
Deno.test("init - create project dir", async () => { Deno.test("init - create project dir", async () => {
await withTmpDir(async (dir) => { await using tmp = await withTmpDir();
using _promptStub = stubPrompt("fresh-init"); const dir = tmp.dir;
using _confirmStub = stubConfirm(); using _promptStub = stubPrompt("fresh-init");
await initProject(dir, [], {}); 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");
await expectProjectFile(root, "main.ts"); await expectProjectFile(root, "main.ts");
await expectProjectFile(root, "dev.ts"); await expectProjectFile(root, "dev.ts");
await expectProjectFile(root, ".gitignore"); await expectProjectFile(root, ".gitignore");
await expectProjectFile(root, "static/styles.css"); await expectProjectFile(root, "static/styles.css");
});
}); });
Deno.test("init - with tailwind", async () => { Deno.test("init - with tailwind", async () => {
await withTmpDir(async (dir) => { await using tmp = await withTmpDir();
using _promptStub = stubPrompt("."); const dir = tmp.dir;
using _confirmStub = stubConfirm({ using _promptStub = stubPrompt(".");
[CONFIRM_TAILWIND_MESSAGE]: true, using _confirmStub = stubConfirm({
}); [CONFIRM_TAILWIND_MESSAGE]: true,
await initProject(dir, [], {});
const css = await readProjectFile(dir, "static/styles.css");
expect(css).toMatch(/@tailwind/);
const main = await readProjectFile(dir, "main.ts");
const dev = await readProjectFile(dir, "dev.ts");
expect(main).not.toMatch(/tailwind/);
expect(dev).toMatch(/tailwind/);
}); });
await initProject(dir, [], {});
const css = await readProjectFile(dir, "static/styles.css");
expect(css).toMatch(/@tailwind/);
const main = await readProjectFile(dir, "main.ts");
const dev = await readProjectFile(dir, "dev.ts");
expect(main).not.toMatch(/tailwind/);
expect(dev).toMatch(/tailwind/);
}); });
Deno.test("init - with vscode", async () => { Deno.test("init - with vscode", async () => {
await withTmpDir(async (dir) => { await using tmp = await withTmpDir();
using _promptStub = stubPrompt("."); const dir = tmp.dir;
using _confirmStub = stubConfirm({ using _promptStub = stubPrompt(".");
[CONFIRM_VSCODE_MESSAGE]: true, using _confirmStub = stubConfirm({
}); [CONFIRM_VSCODE_MESSAGE]: true,
await initProject(dir, [], {});
await expectProjectFile(dir, ".vscode/settings.json");
await expectProjectFile(dir, ".vscode/extensions.json");
}); });
await initProject(dir, [], {});
await expectProjectFile(dir, ".vscode/settings.json");
await expectProjectFile(dir, ".vscode/extensions.json");
}); });
Deno.test({ Deno.test({
@@ -123,33 +119,10 @@ Deno.test({
// behaviours when the formatter changes. // behaviours when the formatter changes.
ignore: Deno.version.deno.includes("+"), ignore: Deno.version.deno.includes("+"),
fn: async () => { fn: async () => {
await withTmpDir(async (dir) => { await using tmp = await withTmpDir();
using _promptStub = stubPrompt("."); const dir = tmp.dir;
using _confirmStub = stubConfirm();
await initProject(dir, [], {});
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
const check = await new Deno.Command(Deno.execPath(), {
args: ["task", "check"],
cwd: dir,
stderr: "inherit",
stdout: "inherit",
}).output();
expect(check.code).toEqual(0);
});
},
});
Deno.test("init with tailwind - fmt, lint, and type check project", async () => {
await withTmpDir(async (dir) => {
using _promptStub = stubPrompt("."); using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({ using _confirmStub = stubConfirm();
[CONFIRM_TAILWIND_MESSAGE]: true,
});
await initProject(dir, [], {}); await initProject(dir, [], {});
await expectProjectFile(dir, "main.ts"); await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts"); await expectProjectFile(dir, "dev.ts");
@@ -163,86 +136,109 @@ Deno.test("init with tailwind - fmt, lint, and type check project", async () =>
stdout: "inherit", stdout: "inherit",
}).output(); }).output();
expect(check.code).toEqual(0); expect(check.code).toEqual(0);
},
});
Deno.test("init with tailwind - fmt, lint, and type check project", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({
[CONFIRM_TAILWIND_MESSAGE]: true,
}); });
await initProject(dir, [], {});
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
const check = await new Deno.Command(Deno.execPath(), {
args: ["task", "check"],
cwd: dir,
stderr: "inherit",
stdout: "inherit",
}).output();
expect(check.code).toEqual(0);
}); });
Deno.test("init - can start dev server", async () => { Deno.test("init - can start dev server", async () => {
await withTmpDir(async (dir) => { await using tmp = await withTmpDir();
using _promptStub = stubPrompt("."); const dir = tmp.dir;
using _confirmStub = stubConfirm(); using _promptStub = stubPrompt(".");
await initProject(dir, [], {}); using _confirmStub = stubConfirm();
await expectProjectFile(dir, "main.ts"); await initProject(dir, [], {});
await expectProjectFile(dir, "dev.ts"); await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir); await patchProject(dir);
await withChildProcessServer( await withChildProcessServer(
dir, dir,
"dev", "dev",
async (address) => { async (address) => {
await withBrowser(async (page) => { await withBrowser(async (page) => {
await page.goto(address); await page.goto(address);
await page.locator("button").click(); await page.locator("button").click();
await waitForText(page, "button + p", "2"); await waitForText(page, "button + p", "2");
}); });
}, },
); );
});
}); });
Deno.test("init - can start built project", async () => { Deno.test("init - can start built project", async () => {
await withTmpDir(async (dir) => { await using tmp = await withTmpDir();
using _promptStub = stubPrompt("."); const dir = tmp.dir;
using _confirmStub = stubConfirm(); using _promptStub = stubPrompt(".");
await initProject(dir, [], {}); using _confirmStub = stubConfirm();
await expectProjectFile(dir, "main.ts"); await initProject(dir, [], {});
await expectProjectFile(dir, "dev.ts"); await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir); await patchProject(dir);
// Build // Build
await new Deno.Command(Deno.execPath(), { await new Deno.Command(Deno.execPath(), {
args: ["task", "build"], args: ["task", "build"],
stdin: "null", stdin: "null",
stdout: "piped", stdout: "piped",
stderr: "piped", stderr: "piped",
cwd: dir, cwd: dir,
}).output(); }).output();
await withChildProcessServer( await withChildProcessServer(
dir, dir,
"start", "start",
async (address) => { async (address) => {
await withBrowser(async (page) => { await withBrowser(async (page) => {
await page.goto(address); await page.goto(address);
await page.locator("button").click(); await page.locator("button").click();
await waitForText(page, "button + p", "2"); await waitForText(page, "button + p", "2");
}); });
}, },
); );
});
}); });
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 using tmp = await withTmpDir();
using _promptStub = stubPrompt("."); const dir = tmp.dir;
using _confirmStub = stubConfirm(); using _promptStub = stubPrompt(".");
await initProject(dir, [], {}); using _confirmStub = stubConfirm();
await expectProjectFile(dir, "main.ts"); await initProject(dir, [], {});
await expectProjectFile(dir, "dev.ts"); await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir); await patchProject(dir);
const cp = await new Deno.Command(Deno.execPath(), { const cp = await new Deno.Command(Deno.execPath(), {
args: ["task", "start"], args: ["task", "start"],
stdin: "null", stdin: "null",
stdout: "piped", stdout: "piped",
stderr: "piped", stderr: "piped",
cwd: dir, cwd: dir,
}).output(); }).output();
const { stderr } = getStdOutput(cp); const { stderr } = getStdOutput(cp);
expect(cp.code).toEqual(1); expect(cp.code).toEqual(1);
expect(stderr).toMatch(/Found 1 islands, but did not/); expect(stderr).toMatch(/Found 1 islands, but did not/);
});
}); });
+3 -1
View File
@@ -1,6 +1,7 @@
import { expect } from "@std/expect"; import { expect } from "@std/expect";
import * as path from "@std/path"; import * as path from "@std/path";
import { ProdBuildCache, type StaticFile } from "./build_cache.ts"; import { ProdBuildCache, type StaticFile } from "./build_cache.ts";
import { withTmpDir } from "./test_utils.ts";
import type { ResolvedFreshConfig } from "./mod.ts"; import type { ResolvedFreshConfig } from "./mod.ts";
async function getContent(readResult: Promise<StaticFile | null>) { async function getContent(readResult: Promise<StaticFile | null>) {
@@ -13,7 +14,8 @@ async function getContent(readResult: Promise<StaticFile | null>) {
Deno.test({ Deno.test({
name: "ProdBuildCache - should error if reading outside of staticDir", name: "ProdBuildCache - should error if reading outside of staticDir",
fn: async () => { fn: async () => {
const tmp = await Deno.makeTempDir(); await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const config: ResolvedFreshConfig = { const config: ResolvedFreshConfig = {
root: tmp, root: tmp,
mode: "production", mode: "production",
+13 -6
View File
@@ -4,6 +4,7 @@ import { Builder } from "./builder.ts";
import { App } from "../app.ts"; import { App } from "../app.ts";
import { RemoteIsland } from "@marvinh-test/fresh-island"; import { RemoteIsland } from "@marvinh-test/fresh-island";
import { BUILD_ID } from "../runtime/build_id.ts"; import { BUILD_ID } from "../runtime/build_id.ts";
import { withTmpDir } from "../test_utils.ts";
Deno.test({ Deno.test({
name: "Builder - chain onTransformStaticFile", name: "Builder - chain onTransformStaticFile",
@@ -29,7 +30,8 @@ Deno.test({
}, },
); );
const tmp = await Deno.makeTempDir(); await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }"); await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }");
const app = new App({ const app = new App({
staticDir: tmp, staticDir: tmp,
@@ -49,7 +51,8 @@ Deno.test({
name: "Builder - handles Windows paths", name: "Builder - handles Windows paths",
fn: async () => { fn: async () => {
const builder = new Builder(); const builder = new Builder();
const tmp = await Deno.makeTempDir(); await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
await Deno.mkdir(path.join(tmp, "images")); await Deno.mkdir(path.join(tmp, "images"));
await Deno.writeTextFile( await Deno.writeTextFile(
path.join(tmp, "images", "batman.svg"), path.join(tmp, "images", "batman.svg"),
@@ -76,7 +79,8 @@ Deno.test({
name: "Builder - hashes CSS urls by default", name: "Builder - hashes CSS urls by default",
fn: async () => { fn: async () => {
const builder = new Builder(); const builder = new Builder();
const tmp = await Deno.makeTempDir(); await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
await Deno.writeTextFile( await Deno.writeTextFile(
path.join(tmp, "foo.css"), path.join(tmp, "foo.css"),
"body { background: url('/foo.jpg'); }", "body { background: url('/foo.jpg'); }",
@@ -103,7 +107,8 @@ Deno.test({
name: "Builder - hashes CSS urls by default", name: "Builder - hashes CSS urls by default",
fn: async () => { fn: async () => {
const builder = new Builder(); const builder = new Builder();
const tmp = await Deno.makeTempDir(); await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
await Deno.writeTextFile( await Deno.writeTextFile(
path.join(tmp, "foo.css"), path.join(tmp, "foo.css"),
`:root { --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(76, 154.5, 137.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E"); }`, `:root { --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(76, 154.5, 137.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E"); }`,
@@ -131,7 +136,8 @@ Deno.test({
name: "Builder - can bundle islands from JSR", name: "Builder - can bundle islands from JSR",
fn: async () => { fn: async () => {
const builder = new Builder(); const builder = new Builder();
const tmp = await Deno.makeTempDir(); await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const app = new App({ const app = new App({
staticDir: tmp, staticDir: tmp,
build: { build: {
@@ -190,7 +196,8 @@ Deno.test({
}, },
); );
const tmp = await Deno.makeTempDir(); await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }"); await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }");
await Deno.writeTextFile( await Deno.writeTextFile(
path.join(tmp, "bar.css"), path.join(tmp, "bar.css"),
+3 -2
View File
@@ -2,13 +2,14 @@ import { expect } from "@std/expect";
import * as path from "@std/path"; import * as path from "@std/path";
import { MemoryBuildCache } from "./dev_build_cache.ts"; import { MemoryBuildCache } from "./dev_build_cache.ts";
import { FreshFileTransformer } from "./file_transformer.ts"; import { FreshFileTransformer } from "./file_transformer.ts";
import { createFakeFs } from "../test_utils.ts"; import { createFakeFs, withTmpDir } from "../test_utils.ts";
import type { ResolvedFreshConfig } from "../mod.ts"; import type { ResolvedFreshConfig } from "../mod.ts";
Deno.test({ Deno.test({
name: "MemoryBuildCache - should error if reading outside of staticDir", name: "MemoryBuildCache - should error if reading outside of staticDir",
fn: async () => { fn: async () => {
const tmp = await Deno.makeTempDir(); await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const config: ResolvedFreshConfig = { const config: ResolvedFreshConfig = {
root: tmp, root: tmp,
mode: "development", mode: "development",
+30 -47
View File
@@ -3,6 +3,7 @@ import denoJson from "../../deno.json" with { type: "json" };
import { WEEK } from "@std/datetime"; import { WEEK } from "@std/datetime";
import { getStdOutput } from "../../tests/test_utils.tsx"; import { getStdOutput } from "../../tests/test_utils.tsx";
import { expect } from "@std/expect"; import { expect } from "@std/expect";
import { withTmpDir } from "../test_utils.ts";
import type { CheckFile } from "./update_check.ts"; import type { CheckFile } from "./update_check.ts";
const CURRENT_VERSION = denoJson.version; const CURRENT_VERSION = denoJson.version;
@@ -10,8 +11,8 @@ const CURRENT_VERSION = denoJson.version;
const cwd = import.meta.dirname!; const cwd = import.meta.dirname!;
Deno.test("stores update check file in $HOME/fresh", async () => { Deno.test("stores update check file in $HOME/fresh", async () => {
const tmpDirName = await Deno.makeTempDir(); await using tmp = await withTmpDir();
const filePath = path.join(tmpDirName, "latest.json"); const filePath = path.join(tmp.dir, "latest.json");
await new Deno.Command(Deno.execPath(), { await new Deno.Command(Deno.execPath(), {
args: [ args: [
@@ -22,7 +23,7 @@ Deno.test("stores update check file in $HOME/fresh", async () => {
cwd, cwd,
env: { env: {
CI: "false", CI: "false",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
}, },
}).output(); }).output();
@@ -33,8 +34,6 @@ Deno.test("stores update check file in $HOME/fresh", async () => {
last_checked: text.last_checked, last_checked: text.last_checked,
last_shown: text.last_shown, last_shown: text.last_shown,
}); });
await Deno.remove(tmpDirName, { recursive: true });
}); });
Deno.test("skips update check on specific environment variables", async (t) => { Deno.test("skips update check on specific environment variables", async (t) => {
@@ -42,7 +41,7 @@ Deno.test("skips update check on specific environment variables", async (t) => {
for (const env of envs) { for (const env of envs) {
await t.step(`checking ${env}`, async () => { await t.step(`checking ${env}`, async () => {
const tmpDirName = await Deno.makeTempDir(); await using tmp = await withTmpDir();
const out = await new Deno.Command(Deno.execPath(), { const out = await new Deno.Command(Deno.execPath(), {
args: [ args: [
"run", "run",
@@ -52,7 +51,7 @@ Deno.test("skips update check on specific environment variables", async (t) => {
cwd, cwd,
env: { env: {
[env]: "true", [env]: "true",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
LATEST_VERSION: "1.30.0", LATEST_VERSION: "1.30.0",
}, },
stderr: "piped", stderr: "piped",
@@ -61,15 +60,13 @@ Deno.test("skips update check on specific environment variables", async (t) => {
const { stdout } = getStdOutput(out); const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh 1\.30\.0 is available/); expect(stdout).not.toMatch(/Fresh 1\.30\.0 is available/);
await Deno.remove(tmpDirName, { recursive: true });
}); });
} }
}); });
Deno.test("shows update message on version mismatch", async () => { Deno.test("shows update message on version mismatch", async () => {
const tmpDirName = await Deno.makeTempDir(); await using tmp = await withTmpDir();
const filePath = path.join(tmpDirName, "latest.json"); const filePath = path.join(tmp.dir, "latest.json");
await Deno.writeTextFile( await Deno.writeTextFile(
filePath, filePath,
@@ -89,7 +86,7 @@ Deno.test("shows update message on version mismatch", async () => {
cwd, cwd,
env: { env: {
CI: "false", CI: "false",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
LATEST_VERSION: "999.999.0", LATEST_VERSION: "999.999.0",
}, },
stderr: "piped", stderr: "piped",
@@ -107,12 +104,10 @@ Deno.test("shows update message on version mismatch", async () => {
last_checked: text.last_checked, last_checked: text.last_checked,
last_shown: text.last_shown, last_shown: text.last_shown,
}); });
await Deno.remove(tmpDirName, { recursive: true });
}); });
Deno.test("only fetch new version defined by interval", async (t) => { Deno.test("only fetch new version defined by interval", async (t) => {
const tmpDirName = await Deno.makeTempDir(); await using tmp = await withTmpDir();
await t.step("fetches latest version initially", async () => { await t.step("fetches latest version initially", async () => {
const out = await new Deno.Command(Deno.execPath(), { const out = await new Deno.Command(Deno.execPath(), {
@@ -125,7 +120,7 @@ Deno.test("only fetch new version defined by interval", async (t) => {
env: { env: {
CI: "false", CI: "false",
UPDATE_INTERVAL: "100000", UPDATE_INTERVAL: "100000",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
LATEST_VERSION: "1.30.0", LATEST_VERSION: "1.30.0",
}, },
stderr: "piped", stderr: "piped",
@@ -147,7 +142,7 @@ Deno.test("only fetch new version defined by interval", async (t) => {
env: { env: {
CI: "false", CI: "false",
UPDATE_INTERVAL: "100000", UPDATE_INTERVAL: "100000",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
LATEST_VERSION: "1.30.0", LATEST_VERSION: "1.30.0",
}, },
stderr: "piped", stderr: "piped",
@@ -169,7 +164,7 @@ Deno.test("only fetch new version defined by interval", async (t) => {
env: { env: {
CI: "false", CI: "false",
UPDATE_INTERVAL: "1 ", UPDATE_INTERVAL: "1 ",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
LATEST_VERSION: "1.30.0", LATEST_VERSION: "1.30.0",
}, },
}).output(); }).output();
@@ -177,12 +172,10 @@ Deno.test("only fetch new version defined by interval", async (t) => {
const { stdout } = getStdOutput(out); const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/fetching latest version/); expect(stdout).toMatch(/fetching latest version/);
}); });
await Deno.remove(tmpDirName, { recursive: true });
}); });
Deno.test("updates current version in cache file", async () => { Deno.test("updates current version in cache file", async () => {
const tmpDirName = await Deno.makeTempDir(); await using tmp = await withTmpDir();
const checkFile: CheckFile = { const checkFile: CheckFile = {
current_version: "1.2.0", current_version: "1.2.0",
@@ -191,7 +184,7 @@ Deno.test("updates current version in cache file", async () => {
}; };
await Deno.writeTextFile( await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"), path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2), JSON.stringify(checkFile, null, 2),
); );
@@ -204,7 +197,7 @@ Deno.test("updates current version in cache file", async () => {
cwd, cwd,
env: { env: {
CI: "false", CI: "false",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
LATEST_VERSION: CURRENT_VERSION, LATEST_VERSION: CURRENT_VERSION,
}, },
stderr: "piped", stderr: "piped",
@@ -213,12 +206,10 @@ Deno.test("updates current version in cache file", async () => {
const { stdout } = getStdOutput(out); const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh .* is available/); expect(stdout).not.toMatch(/Fresh .* is available/);
await Deno.remove(tmpDirName, { recursive: true });
}); });
Deno.test("only shows update message when current < latest", async () => { Deno.test("only shows update message when current < latest", async () => {
const tmpDirName = await Deno.makeTempDir(); await using tmp = await withTmpDir();
const checkFile: CheckFile = { const checkFile: CheckFile = {
current_version: "9999.999.0", current_version: "9999.999.0",
@@ -227,7 +218,7 @@ Deno.test("only shows update message when current < latest", async () => {
}; };
await Deno.writeTextFile( await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"), path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2), JSON.stringify(checkFile, null, 2),
); );
@@ -240,7 +231,7 @@ Deno.test("only shows update message when current < latest", async () => {
cwd, cwd,
env: { env: {
CI: "false", CI: "false",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
LATEST_VERSION: CURRENT_VERSION, LATEST_VERSION: CURRENT_VERSION,
CURRENT_VERSION: "99999.9999.0", CURRENT_VERSION: "99999.9999.0",
}, },
@@ -250,12 +241,10 @@ Deno.test("only shows update message when current < latest", async () => {
const { stdout } = getStdOutput(out); const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh .* is available/); expect(stdout).not.toMatch(/Fresh .* is available/);
await Deno.remove(tmpDirName, { recursive: true });
}); });
Deno.test("migrates to last_shown property", async () => { Deno.test("migrates to last_shown property", async () => {
const tmpDirName = await Deno.makeTempDir(); await using tmp = await withTmpDir();
const checkFile: CheckFile = { const checkFile: CheckFile = {
latest_version: "1.4.0", latest_version: "1.4.0",
@@ -264,7 +253,7 @@ Deno.test("migrates to last_shown property", async () => {
}; };
await Deno.writeTextFile( await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"), path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2), JSON.stringify(checkFile, null, 2),
); );
@@ -277,7 +266,7 @@ Deno.test("migrates to last_shown property", async () => {
cwd, cwd,
env: { env: {
CI: "false", CI: "false",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
CURRENT_VERSION: "1.2.0", CURRENT_VERSION: "1.2.0",
LATEST_VERSION: "99999.9999.0", LATEST_VERSION: "99999.9999.0",
}, },
@@ -290,18 +279,16 @@ Deno.test("migrates to last_shown property", async () => {
const checkFileAfter = JSON.parse( const checkFileAfter = JSON.parse(
await Deno.readTextFile( await Deno.readTextFile(
path.join(tmpDirName, "latest.json"), path.join(tmp.dir, "latest.json"),
), ),
); );
// Check if last version was written // Check if last version was written
expect(typeof checkFileAfter.last_shown).toEqual("string"); expect(typeof checkFileAfter.last_shown).toEqual("string");
await Deno.remove(tmpDirName, { recursive: true });
}); });
Deno.test("doesn't show update if last_shown + interval >= today", async () => { Deno.test("doesn't show update if last_shown + interval >= today", async () => {
const tmpDirName = await Deno.makeTempDir(); await using tmp = await withTmpDir();
const todayMinus1Hour = new Date(); const todayMinus1Hour = new Date();
todayMinus1Hour.setHours(todayMinus1Hour.getHours() - 1); todayMinus1Hour.setHours(todayMinus1Hour.getHours() - 1);
@@ -314,7 +301,7 @@ Deno.test("doesn't show update if last_shown + interval >= today", async () => {
}; };
await Deno.writeTextFile( await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"), path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2), JSON.stringify(checkFile, null, 2),
); );
@@ -327,7 +314,7 @@ Deno.test("doesn't show update if last_shown + interval >= today", async () => {
cwd, cwd,
env: { env: {
CI: "false", CI: "false",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
CURRENT_VERSION: "1.2.0", CURRENT_VERSION: "1.2.0",
LATEST_VERSION: "99999.9999.0", LATEST_VERSION: "99999.9999.0",
}, },
@@ -337,14 +324,12 @@ Deno.test("doesn't show update if last_shown + interval >= today", async () => {
const { stdout } = getStdOutput(out); const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh .* is available/); expect(stdout).not.toMatch(/Fresh .* is available/);
await Deno.remove(tmpDirName, { recursive: true });
}); });
Deno.test( Deno.test(
"shows update if last_shown + interval < today", "shows update if last_shown + interval < today",
async () => { async () => {
const tmpDirName = await Deno.makeTempDir(); await using tmp = await withTmpDir();
const yesterday = new Date(); const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1); yesterday.setDate(yesterday.getDate() - 1);
@@ -357,7 +342,7 @@ Deno.test(
}; };
await Deno.writeTextFile( await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"), path.join(tmp.dir, "latest.json"),
JSON.stringify(checkFile, null, 2), JSON.stringify(checkFile, null, 2),
); );
@@ -370,7 +355,7 @@ Deno.test(
cwd, cwd,
env: { env: {
CI: "false", CI: "false",
TEST_HOME: tmpDirName, TEST_HOME: tmp.dir,
CURRENT_VERSION: CURRENT_VERSION, CURRENT_VERSION: CURRENT_VERSION,
LATEST_VERSION: "99999.9999.0", LATEST_VERSION: "99999.9999.0",
}, },
@@ -383,12 +368,10 @@ Deno.test(
const checkFileAfter = JSON.parse( const checkFileAfter = JSON.parse(
await Deno.readTextFile( await Deno.readTextFile(
path.join(tmpDirName, "latest.json"), path.join(tmp.dir, "latest.json"),
), ),
); );
expect(checkFileAfter.last_shown).not.toEqual(yesterday.toISOString()); expect(checkFileAfter.last_shown).not.toEqual(yesterday.toISOString());
await Deno.remove(tmpDirName, { recursive: true });
}, },
); );
+12
View File
@@ -117,3 +117,15 @@ export function createFakeFs(files: Record<string, unknown>): FsAdapter {
} }
export const delay = (ms: number) => new Promise((r) => setTimeout(r, ms)); export const delay = (ms: number) => new Promise((r) => setTimeout(r, ms));
export async function withTmpDir(
options?: Deno.MakeTempOptions,
): Promise<{ dir: string } & AsyncDisposable> {
const dir = await Deno.makeTempDir(options);
return {
dir,
async [Symbol.asyncDispose]() {
await Deno.remove(dir, { recursive: true });
},
};
}
+286 -296
View File
@@ -6,17 +6,8 @@ import {
updateProject, updateProject,
} from "./update.ts"; } from "./update.ts";
import { expect } from "@std/expect"; import { expect } from "@std/expect";
import { walk } from "https://deno.land/std@0.93.0/fs/walk.ts"; import { walk } from "@std/fs/walk";
import { withTmpDir } from "../../src/test_utils.ts";
async function withTmpDir(fn: (dir: string) => void | Promise<void>) {
const dir = await Deno.makeTempDir();
try {
await fn(dir);
} finally {
await Deno.remove(dir, { recursive: true });
}
}
async function writeFiles(dir: string, files: Record<string, string>) { async function writeFiles(dir: string, files: Record<string, string>) {
const entries = Object.entries(files); const entries = Object.entries(files);
@@ -49,77 +40,77 @@ async function readFiles(dir: string): Promise<Record<string, string>> {
} }
Deno.test("update - remove JSX pragma import", async () => { Deno.test("update - remove JSX pragma import", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `import { h, Fragment } from "preact"; "/deno.json": `{}`,
"/routes/index.tsx": `import { h, Fragment } from "preact";
/** @jsx h */ /** @jsx h */
/** @jsxFrag Fragment */ /** @jsxFrag Fragment */
export default function Foo() { export default function Foo() {
return null; return null;
}`, }`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`export default function Foo() { .toEqual(`export default function Foo() {
return null; return null;
}`); }`);
});
}); });
Deno.test("update - 1.x project deno.json", async () => { Deno.test("update - 1.x project deno.json", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
}); "/deno.json": `{}`,
await updateProject(dir);
const files = await readFiles(dir);
expect(JSON.parse(files["/deno.json"]))
.toEqual({
imports: {
"fresh": `jsr:@fresh/core@^${FRESH_VERSION}`,
"@preact/signals": `npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`,
"preact": `npm:preact@^${PREACT_VERSION}`,
},
});
}); });
await updateProject(dir);
const files = await readFiles(dir);
expect(JSON.parse(files["/deno.json"]))
.toEqual({
imports: {
"fresh": `jsr:@fresh/core@^${FRESH_VERSION}`,
"@preact/signals": `npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`,
"preact": `npm:preact@^${PREACT_VERSION}`,
},
});
}); });
Deno.test("update - 1.x project deno.json with imports", async () => { Deno.test("update - 1.x project deno.json with imports", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{ await writeFiles(dir, {
"/deno.json": `{
"imports": { "imports": {
"$fresh/": "foo" "$fresh/": "foo"
} }
}`, }`,
});
await updateProject(dir);
const files = await readFiles(dir);
expect(JSON.parse(files["/deno.json"]))
.toEqual({
imports: {
"fresh": `jsr:@fresh/core@^${FRESH_VERSION}`,
"@preact/signals": `npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`,
"preact": `npm:preact@^${PREACT_VERSION}`,
},
});
}); });
await updateProject(dir);
const files = await readFiles(dir);
expect(JSON.parse(files["/deno.json"]))
.toEqual({
imports: {
"fresh": `jsr:@fresh/core@^${FRESH_VERSION}`,
"@preact/signals": `npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`,
"preact": `npm:preact@^${PREACT_VERSION}`,
},
});
}); });
Deno.test("update - 1.x project middlewares", async () => { Deno.test("update - 1.x project middlewares", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": "{}", await writeFiles(dir, {
"/routes/_middleware.ts": "/deno.json": "{}",
`import { FreshContext } from "$fresh/server.ts"; "/routes/_middleware.ts": `import { FreshContext } from "$fresh/server.ts";
interface State { interface State {
data: string; data: string;
@@ -135,13 +126,13 @@ export async function handler(
resp.headers.set("server", "fresh server"); resp.headers.set("server", "fresh server");
return resp; return resp;
}`, }`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/_middleware.ts"]) expect(files["/routes/_middleware.ts"])
.toEqual(`import { FreshContext } from "fresh"; .toEqual(`import { FreshContext } from "fresh";
interface State { interface State {
data: string; data: string;
@@ -158,61 +149,61 @@ export async function handler(
resp.headers.set("server", "fresh server"); resp.headers.set("server", "fresh server");
return resp; return resp;
}`); }`);
});
}); });
Deno.test("update - 1.x project middlewares one arg", async () => { Deno.test("update - 1.x project middlewares one arg", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": "{}", await writeFiles(dir, {
"/routes/_middleware.ts": `export async function handler(req: Request) { "/deno.json": "{}",
"/routes/_middleware.ts": `export async function handler(req: Request) {
return new Response("hello world from: " + req.url); return new Response("hello world from: " + req.url);
}`, }`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/_middleware.ts"]) expect(files["/routes/_middleware.ts"])
.toEqual(`import { FreshContext } from "fresh"; .toEqual(`import { FreshContext } from "fresh";
export async function handler(ctx: FreshContext) { export async function handler(ctx: FreshContext) {
const req = ctx.req; const req = ctx.req;
return new Response("hello world from: " + req.url); return new Response("hello world from: " + req.url);
}`); }`);
});
}); });
Deno.test("update - 1.x update '$fresh/*' imports", async () => { Deno.test("update - 1.x update '$fresh/*' imports", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `import { PageProps } from "$fresh/server.ts"; "/deno.json": `{}`,
"/routes/index.tsx": `import { PageProps } from "$fresh/server.ts";
export default function Foo(props: PageProps) { export default function Foo(props: PageProps) {
return null; return null;
}`, }`,
"/routes/foo.tsx": `import { asset, Head } from "$fresh/runtime.ts";`, "/routes/foo.tsx": `import { asset, Head } from "$fresh/runtime.ts";`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`import { PageProps } from "fresh"; .toEqual(`import { PageProps } from "fresh";
export default function Foo(props: PageProps) { export default function Foo(props: PageProps) {
return null; return null;
}`); }`);
expect(files["/routes/foo.tsx"]) expect(files["/routes/foo.tsx"])
.toEqual(`import { asset, Head } from "fresh/runtime";`); .toEqual(`import { asset, Head } from "fresh/runtime";`);
});
}); });
Deno.test("update - 1.x update handler signature", async () => { Deno.test("update - 1.x update handler signature", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts"; "/deno.json": `{}`,
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(req, ctx) {}, async GET(req, ctx) {},
@@ -221,7 +212,7 @@ export const handler: Handlers = {
async PUT(req, ctx) {}, async PUT(req, ctx) {},
async DELETE(req, ctx) {}, async DELETE(req, ctx) {},
};`, };`,
"/routes/foo.tsx": `import { Handlers } from "$fresh/server.ts"; "/routes/foo.tsx": `import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(_req, ctx) {}, async GET(_req, ctx) {},
@@ -230,7 +221,7 @@ export const handler: Handlers = {
async PUT(_req, ctx) {}, async PUT(_req, ctx) {},
async DELETE(_req, ctx) {}, async DELETE(_req, ctx) {},
};`, };`,
"/routes/name.tsx": `import { Handlers } from "$fresh/server.ts"; "/routes/name.tsx": `import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(request, ctx) {}, async GET(request, ctx) {},
@@ -239,7 +230,7 @@ export const handler: Handlers = {
async PUT(request, ctx) {}, async PUT(request, ctx) {},
async DELETE(request, ctx) {}, async DELETE(request, ctx) {},
};`, };`,
"/routes/name-unused.tsx": `import { Handlers } from "$fresh/server.ts"; "/routes/name-unused.tsx": `import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(_request, ctx) {}, async GET(_request, ctx) {},
@@ -248,152 +239,152 @@ export const handler: Handlers = {
async PUT(_request, ctx) {}, async PUT(_request, ctx) {},
async DELETE(_request, ctx) {}, async DELETE(_request, ctx) {},
};`, };`,
});
await updateProject(dir);
const files = await readFiles(dir);
expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "fresh/compat";
export const handler: Handlers = {
async GET(ctx) {
const req = ctx.req;
},
async POST(ctx) {
const req = ctx.req;
},
async PATCH(ctx) {
const req = ctx.req;
},
async PUT(ctx) {
const req = ctx.req;
},
async DELETE(ctx) {
const req = ctx.req;
},
};`);
expect(files["/routes/foo.tsx"])
.toEqual(`import { Handlers } from "fresh/compat";
export const handler: Handlers = {
async GET(ctx) {},
async POST(ctx) {},
async PATCH(ctx) {},
async PUT(ctx) {},
async DELETE(ctx) {},
};`);
expect(files["/routes/name.tsx"])
.toEqual(`import { Handlers } from "fresh/compat";
export const handler: Handlers = {
async GET(ctx) {
const request = ctx.req;
},
async POST(ctx) {
const request = ctx.req;
},
async PATCH(ctx) {
const request = ctx.req;
},
async PUT(ctx) {
const request = ctx.req;
},
async DELETE(ctx) {
const request = ctx.req;
},
};`);
expect(files["/routes/name-unused.tsx"])
.toEqual(`import { Handlers } from "fresh/compat";
export const handler: Handlers = {
async GET(ctx) {},
async POST(ctx) {},
async PATCH(ctx) {},
async PUT(ctx) {},
async DELETE(ctx) {},
};`);
}); });
await updateProject(dir);
const files = await readFiles(dir);
expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "fresh/compat";
export const handler: Handlers = {
async GET(ctx) {
const req = ctx.req;
},
async POST(ctx) {
const req = ctx.req;
},
async PATCH(ctx) {
const req = ctx.req;
},
async PUT(ctx) {
const req = ctx.req;
},
async DELETE(ctx) {
const req = ctx.req;
},
};`);
expect(files["/routes/foo.tsx"])
.toEqual(`import { Handlers } from "fresh/compat";
export const handler: Handlers = {
async GET(ctx) {},
async POST(ctx) {},
async PATCH(ctx) {},
async PUT(ctx) {},
async DELETE(ctx) {},
};`);
expect(files["/routes/name.tsx"])
.toEqual(`import { Handlers } from "fresh/compat";
export const handler: Handlers = {
async GET(ctx) {
const request = ctx.req;
},
async POST(ctx) {
const request = ctx.req;
},
async PATCH(ctx) {
const request = ctx.req;
},
async PUT(ctx) {
const request = ctx.req;
},
async DELETE(ctx) {
const request = ctx.req;
},
};`);
expect(files["/routes/name-unused.tsx"])
.toEqual(`import { Handlers } from "fresh/compat";
export const handler: Handlers = {
async GET(ctx) {},
async POST(ctx) {},
async PATCH(ctx) {},
async PUT(ctx) {},
async DELETE(ctx) {},
};`);
}); });
Deno.test( Deno.test(
"update - 1.x update handler signature method one arg", "update - 1.x update handler signature method one arg",
async () => { async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `export const handler: Handlers = { "/deno.json": `{}`,
"/routes/index.tsx": `export const handler: Handlers = {
GET(req) { GET(req) {
return Response.redirect(req.url); return Response.redirect(req.url);
}, },
};`, };`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`export const handler: Handlers = { .toEqual(`export const handler: Handlers = {
GET(ctx) { GET(ctx) {
const req = ctx.req; const req = ctx.req;
return Response.redirect(req.url); return Response.redirect(req.url);
}, },
};`); };`);
});
}, },
); );
Deno.test.ignore( Deno.test.ignore(
"update - 1.x update handler signature variable", "update - 1.x update handler signature variable",
async () => { async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `export const handler: Handlers = { "/deno.json": `{}`,
"/routes/index.tsx": `export const handler: Handlers = {
GET: (req) => Response.redirect(req.url) GET: (req) => Response.redirect(req.url)
};`, };`,
"/routes/foo.tsx": `export const handler: Handlers = { "/routes/foo.tsx": `export const handler: Handlers = {
GET: (req, ctx) => Response.redirect(req.url), GET: (req, ctx) => Response.redirect(req.url),
};`, };`,
});
await updateProject(dir);
const files = await readFiles(dir);
expect(files["/routes/index.tsx"])
.toEqual(`export const handler: Handlers = {
GET: (ctx) => {
const req = ctx.req;
return Response.redirect(req.url);
},
};`);
expect(files["/routes/foo.tsx"])
.toEqual(`export const handler: Handlers = {
GET: (ctx) => {
const req = ctx.req;
return Response.redirect(req.url);
},
};`);
}); });
await updateProject(dir);
const files = await readFiles(dir);
expect(files["/routes/index.tsx"])
.toEqual(`export const handler: Handlers = {
GET: (ctx) => {
const req = ctx.req;
return Response.redirect(req.url);
},
};`);
expect(files["/routes/foo.tsx"])
.toEqual(`export const handler: Handlers = {
GET: (ctx) => {
const req = ctx.req;
return Response.redirect(req.url);
},
};`);
}, },
); );
Deno.test( Deno.test(
"update - 1.x update handler signature non-inferred", "update - 1.x update handler signature non-inferred",
async () => { async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `export const handler = { "/deno.json": `{}`,
"/routes/index.tsx": `export const handler = {
GET(req: Request){ GET(req: Request){
return Response.redirect(req.url); return Response.redirect(req.url);
} }
};`, };`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`import { FreshContext } from "fresh"; .toEqual(`import { FreshContext } from "fresh";
export const handler = { export const handler = {
GET(ctx: FreshContext) { GET(ctx: FreshContext) {
@@ -402,17 +393,17 @@ export const handler = {
return Response.redirect(req.url); return Response.redirect(req.url);
}, },
};`); };`);
});
}, },
); );
Deno.test( Deno.test(
"update - 1.x update handler signature with destructure", "update - 1.x update handler signature with destructure",
async () => { async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts"; "/deno.json": `{}`,
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(req, { params, render, remoteAddr }) {}, async GET(req, { params, render, remoteAddr }) {},
@@ -421,11 +412,11 @@ export const handler: Handlers = {
async PUT(req, { params, render, remoteAddr }) {}, async PUT(req, { params, render, remoteAddr }) {},
async DELETE(req, { params, render, remoteAddr }) {}, async DELETE(req, { params, render, remoteAddr }) {},
};`, };`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "fresh/compat"; .toEqual(`import { Handlers } from "fresh/compat";
export const handler: Handlers = { export const handler: Handlers = {
async GET({ params, render, info, req }) { async GET({ params, render, info, req }) {
@@ -444,66 +435,66 @@ export const handler: Handlers = {
const remoteAddr = info.remoteAddr; const remoteAddr = info.remoteAddr;
}, },
};`); };`);
});
}, },
); );
Deno.test("update - 1.x update define* handler signatures", async () => { Deno.test("update - 1.x update define* handler signatures", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/_app.tsx": `import { defineApp } from "$fresh/server.ts"; "/deno.json": `{}`,
"/routes/_app.tsx": `import { defineApp } from "$fresh/server.ts";
export default defineApp(async (req, ctx) => { export default defineApp(async (req, ctx) => {
return null; return null;
});`, });`,
"/routes/_layout.tsx": `import { defineLayout } from "$fresh/server.ts"; "/routes/_layout.tsx": `import { defineLayout } from "$fresh/server.ts";
export default defineLayout(async (req, ctx) => { export default defineLayout(async (req, ctx) => {
return null; return null;
});`, });`,
"/routes/foo.tsx": `import { defineRoute } from "$fresh/server.ts"; "/routes/foo.tsx": `import { defineRoute } from "$fresh/server.ts";
export default defineRoute(async (req, ctx) => { export default defineRoute(async (req, ctx) => {
return null; return null;
});`, });`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/_app.tsx"]) expect(files["/routes/_app.tsx"])
.toEqual(`import { defineApp } from "fresh/compat"; .toEqual(`import { defineApp } from "fresh/compat";
export default defineApp(async (ctx) => { export default defineApp(async (ctx) => {
const req = ctx.req; const req = ctx.req;
return null; return null;
});`); });`);
expect(files["/routes/_layout.tsx"]) expect(files["/routes/_layout.tsx"])
.toEqual(`import { defineLayout } from "fresh/compat"; .toEqual(`import { defineLayout } from "fresh/compat";
export default defineLayout(async (ctx) => { export default defineLayout(async (ctx) => {
const req = ctx.req; const req = ctx.req;
return null; return null;
});`); });`);
expect(files["/routes/foo.tsx"]) expect(files["/routes/foo.tsx"])
.toEqual(`import { defineRoute } from "fresh/compat"; .toEqual(`import { defineRoute } from "fresh/compat";
export default defineRoute(async (ctx) => { export default defineRoute(async (ctx) => {
const req = ctx.req; const req = ctx.req;
return null; return null;
});`); });`);
});
}); });
Deno.test( Deno.test(
"update - 1.x update component signature async", "update - 1.x update component signature async",
async () => { async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": "/deno.json": `{}`,
`export default async function Index(req: Request, ctx: RouteContext) { "/routes/index.tsx":
`export default async function Index(req: Request, ctx: RouteContext) {
if (true) { if (true) {
return ctx.renderNotFound(); return ctx.renderNotFound();
} }
@@ -513,11 +504,11 @@ Deno.test(
} }
return new Response(req.url); return new Response(req.url);
}`, }`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`import { FreshContext } from "fresh"; .toEqual(`import { FreshContext } from "fresh";
export default async function Index(ctx: FreshContext) { export default async function Index(ctx: FreshContext) {
const req = ctx.req; const req = ctx.req;
@@ -531,33 +522,33 @@ export default async function Index(ctx: FreshContext) {
} }
return new Response(req.url); return new Response(req.url);
}`); }`);
});
}, },
); );
Deno.test.ignore( Deno.test.ignore(
"update - 1.x ctx.renderNotFound() -> ctx.throw()", "update - 1.x ctx.renderNotFound() -> ctx.throw()",
async () => { async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts"; "/deno.json": `{}`,
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(_req, ctx) { async GET(_req, ctx) {
return ctx.renderNotFound(); return ctx.renderNotFound();
}, },
};`, };`,
"/routes/foo.tsx": `export const handler = (ctx) => { "/routes/foo.tsx": `export const handler = (ctx) => {
return ctx.renderNotFound(); return ctx.renderNotFound();
}`, }`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "fresh"; .toEqual(`import { Handlers } from "fresh";
export const handler: Handlers = { export const handler: Handlers = {
async GET(ctx) { async GET(ctx) {
@@ -565,21 +556,21 @@ export const handler: Handlers = {
}, },
};`); };`);
expect(files["/routes/foo.tsx"]) expect(files["/routes/foo.tsx"])
.toEqual(`export const handler = (ctx) => { .toEqual(`export const handler = (ctx) => {
throw HttpError(404); throw HttpError(404);
};`); };`);
});
}, },
); );
Deno.test.ignore( Deno.test.ignore(
"update - 1.x ctx.remoteAddr -> ctx.info.remoteAddr", "update - 1.x ctx.remoteAddr -> ctx.info.remoteAddr",
async () => { async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts"; "/deno.json": `{}`,
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(_req, ctx) { async GET(_req, ctx) {
@@ -588,13 +579,13 @@ export const handler: Handlers = {
return new Response(msg); return new Response(msg);
}, },
};`, };`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "fresh"; .toEqual(`import { Handlers } from "fresh";
export const handler: Handlers = { export const handler: Handlers = {
async GET(ctx) { async GET(ctx) {
@@ -603,15 +594,15 @@ export const handler: Handlers = {
return new Response(msg); return new Response(msg);
}, },
};`); };`);
});
}, },
); );
Deno.test.ignore("update - 1.x destructured ctx members", async () => { Deno.test.ignore("update - 1.x destructured ctx members", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts"; "/deno.json": `{}`,
"/routes/index.tsx": `import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(_req, { url, renderNotFound, remoteAddr }) { async GET(_req, { url, renderNotFound, remoteAddr }) {
@@ -623,13 +614,13 @@ export const handler: Handlers = {
} }
}, },
};`, };`,
}); });
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "fresh"; .toEqual(`import { Handlers } from "fresh";
export const handler: Handlers = { export const handler: Handlers = {
async GET({ url, throw, info }) { async GET({ url, throw, info }) {
@@ -644,40 +635,39 @@ export const handler: Handlers = {
} }
}, },
};`); };`);
});
}); });
Deno.test("update - 1.x remove reference comments", async () => { Deno.test("update - 1.x remove reference comments", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/routes/main.ts": `/// <reference no-default-lib="true" /> "/deno.json": `{}`,
"/routes/main.ts": `/// <reference no-default-lib="true" />
/// <reference lib="dom" /> /// <reference lib="dom" />
/// <reference lib="dom.iterable" /> /// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" /> /// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" /> /// <reference lib="deno.ns" />
`, `,
});
await updateProject(dir);
const files = await readFiles(dir);
expect(files["/routes/main.ts"]).toEqual("");
}); });
await updateProject(dir);
const files = await readFiles(dir);
expect(files["/routes/main.ts"]).toEqual("");
}); });
Deno.test("update - island files", async () => { Deno.test("update - island files", async () => {
await withTmpDir(async (dir) => { await using _tmp = await withTmpDir();
await writeFiles(dir, { const dir = _tmp.dir;
"/deno.json": `{}`, await writeFiles(dir, {
"/islands/foo.tsx": `import { IS_BROWSER } from "$fresh/runtime.ts";`, "/deno.json": `{}`,
}); "/islands/foo.tsx": `import { IS_BROWSER } from "$fresh/runtime.ts";`,
await updateProject(dir);
const files = await readFiles(dir);
expect(files["/islands/foo.tsx"]).toEqual(
`import { IS_BROWSER } from "fresh/runtime";`,
);
}); });
await updateProject(dir);
const files = await readFiles(dir);
expect(files["/islands/foo.tsx"]).toEqual(
`import { IS_BROWSER } from "fresh/runtime";`,
);
}); });