Skip to content

Commit

Permalink
test(unenv-preset): move tests from nodejs-hybrid-app
Browse files Browse the repository at this point in the history
  • Loading branch information
vicb committed Jan 9, 2025
1 parent 78bdec5 commit 10a88d6
Show file tree
Hide file tree
Showing 7 changed files with 191 additions and 92 deletions.
4 changes: 0 additions & 4 deletions fixtures/nodejs-hybrid-app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { Stream } from "node:stream";
import { Context } from "vm";
import { Client } from "pg";
import { s } from "./dep.cjs";
import { testUnenvPreset } from "./unenv-preset";

testBasicNodejsProperties();

Expand All @@ -29,8 +28,6 @@ export default {
return testX509Certificate();
case "/test-require-alias":
return testRequireUenvAliasedPackages();
case "/test-unenv-preset":
return await testUnenvPreset();
}

return new Response(
Expand All @@ -39,7 +36,6 @@ export default {
<a href="test-random">Test getRandomValues()</a>
<a href="test-x509-certificate">Test X509Certificate</a>
<a href="test-require-alias">Test require unenv aliased packages</a>
<a href="test-unenv-preset">Test unenv preset</a>
`,
{ headers: { "Content-Type": "text/html; charset=utf-8" } }
);
Expand Down
6 changes: 0 additions & 6 deletions fixtures/nodejs-hybrid-app/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,4 @@ describe("nodejs compat", () => {
const response = await fetch(`http://${ip}:${port}/test-require-alias`);
await expect(response.text()).resolves.toBe(`"OK!"`);
});

test("unenv preset", async ({ expect }) => {
const { ip, port } = wrangler;
const response = await fetch(`http://${ip}:${port}/test-unenv-preset`);
await expect(response.text()).resolves.toBe("OK!");
});
});
11 changes: 8 additions & 3 deletions packages/unenv-preset/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,21 @@
"scripts": {
"build": "unbuild",
"check:lint": "eslint",
"check:type": "tsc --noEmit"
"check:type": "tsc --noEmit",
"test:ci": "vitest run",
"test:watch": "vitest"
},
"devDependencies": {
"@types/node": "*",
"typescript": "catalog:default",
"unbuild": "^2.0.0"
"unbuild": "^2.0.0",
"undici": "catalog:default",
"vitest": "catalog:default",
"wrangler": "workspace:*"
},
"peerDependencies": {
"unenv": "npm:unenv-nightly@*",
"workerd": "^1.20241216.0"
"workerd": "^1.20241230.0"
},
"peerDependenciesMeta": {
"workerd": {
Expand Down
66 changes: 66 additions & 0 deletions packages/unenv-preset/tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import fs from "node:fs";
import path from "node:path";
import { platform } from "node:process";
import { fileURLToPath } from "node:url";
import { fetch } from "undici";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { runWranglerDev } from "../../../fixtures/shared/src/run-wrangler-long-lived";
import { TESTS } from "./worker/index";

// Root of the current package
const pkgDir = path.resolve(fileURLToPath(import.meta.url), "../..");
// workerd binary
const localWorkerdPath = path.join(pkgDir, "node_modules/.bin/", "workerd");
// Base path for resolving `@cloudflare/unenv-preset` files
const localPresetResolveBaseDir = path.join(pkgDir, "package.json");
// Base path for resolving `unjs/unenv` files
const localUnenvResolveBaseDir = path.join(
pkgDir,
"node_modules/unenv/package.json"
);

// `runWranglerDev` + `MINIFLARE_WORKERD_PATH` is not supported on Windows
// See https://github.com/nodejs/node/issues/52554
describe.skipIf(platform === "win32")(
`@cloudflare/unenv-preset ${platform} ${localWorkerdPath} ${fs.existsSync(localWorkerdPath)}`,
() => {
let wrangler: Awaited<ReturnType<typeof runWranglerDev>> | undefined;

beforeAll(async () => {
// Use workerd binary install in `@cloudflare/unenv-preset`
// rather than the one bundled with wrangler.
const MINIFLARE_WORKERD_PATH = localWorkerdPath;

// Use the preset from the local `@cloudflare/unenv-preset` and `unjs/unenv`
// rather than the one bundled with wrangler.
const WRANGLER_UNENV_RESOLVE_PATHS = [
localPresetResolveBaseDir,
localUnenvResolveBaseDir,
].join(",");

console.log({ MINIFLARE_WORKERD_PATH, WRANGLER_UNENV_RESOLVE_PATHS });

wrangler = await runWranglerDev(
path.join(__dirname, "worker"),
["--port=0", "--inspector-port=0"],
{
MINIFLARE_WORKERD_PATH,
WRANGLER_UNENV_RESOLVE_PATHS,
}
);
}, 30000);

afterAll(async () => {
await wrangler?.stop();
wrangler = undefined;
});

test.for(Object.keys(TESTS))("%s", async (testName) => {
expect(wrangler).toBeDefined();
const { ip, port } = wrangler!;
const response = await fetch(`http://${ip}:${port}/${testName}`);
const body = await response.text();
expect(body).toMatch("OK!");
});
}
);
Original file line number Diff line number Diff line change
@@ -1,21 +1,41 @@
import assert from "node:assert";

// TODO: move to `@cloudflare/unenv-preset`
// See: https://github.com/cloudflare/workers-sdk/issues/7579
export async function testUnenvPreset() {
try {
await testCryptoGetRandomValues();
await testWorkerdImplementsBuffer();
await testWorkerdModules();
await testUtilImplements();
await testWorkerdPath();
await testWorkerdDns();
} catch (e) {
return new Response(String(e));
}
// List all the test functions.
// The test can be executing by fetching the `/${testName}` url.
export const TESTS = {
testCryptoGetRandomValues,
testImplementsBuffer,
testModules,
testUtilImplements,
testPath,
testDns,
};

return new Response("OK!");
}
export default {
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
const testName = url.pathname.slice(1);
const test = TESTS[testName];
if (!test) {
return new Response(
`<h1>${testName ? `${testName} not found!` : `Pick a test to run`} </h1>
<ul>
${Object.keys(TESTS)
.map((name) => `<li><a href="/${name}">${name}</a></li>`)
.join("")}
</ul>`,
{ headers: { "Content-Type": "text/html; charset=utf-8" } }
);
}
try {
await test();
} catch (e) {
return new Response(String(e));
}

return new Response("OK!");
},
};

async function testCryptoGetRandomValues() {
const crypto = await import("node:crypto");
Expand All @@ -26,7 +46,7 @@ async function testCryptoGetRandomValues() {
assert(array.every((v) => v >= 0 && v <= 0xff_ff_ff_ff));
}

async function testWorkerdImplementsBuffer() {
async function testImplementsBuffer() {
const encoder = new TextEncoder();
const buffer = await import("node:buffer");
const Buffer = buffer.Buffer;
Expand All @@ -53,7 +73,7 @@ async function testWorkerdImplementsBuffer() {
assert.strictEqual(typeof buffer.resolveObjectURL, "function");
}

async function testWorkerdModules() {
async function testModules() {
const module = await import("node:module");
// @ts-expect-error exposed by workerd
const require = module.createRequire("/");
Expand Down Expand Up @@ -89,7 +109,7 @@ async function testUtilImplements() {
assert.strictEqual(types.isAnyArrayBuffer(new ArrayBuffer(0)), true);
}

async function testWorkerdPath() {
async function testPath() {
const pathWin32 = await import("node:path/win32");
assert.strictEqual(pathWin32.sep, "\\");
assert.strictEqual(pathWin32.delimiter, ";");
Expand All @@ -98,7 +118,7 @@ async function testWorkerdPath() {
assert.strictEqual(pathPosix.delimiter, ":");
}

async function testWorkerdDns() {
async function testDns() {
const dns = await import("node:dns");
await new Promise((resolve, reject) => {
dns.resolveTxt("nodejs.org", (error, results) => {
Expand Down
6 changes: 6 additions & 0 deletions packages/unenv-preset/tests/worker/wrangler.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "cloudflare-unenv-preset-test",
"main": "./index.ts",
"compatibility_date": "2024-12-16",
"compatibility_flags": ["nodejs_compat"]
}
Loading

0 comments on commit 10a88d6

Please sign in to comment.