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

test: add compatibility tests for browser, node and bun #36

Merged
merged 2 commits into from
Apr 22, 2024
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
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ jobs:
- uses: denoland/setup-deno@v1
with:
deno-version: v1.x
- uses: oven-sh/setup-bun@v1
with:
bun-version: 1.x
- uses: actions/setup-node@v4
with:
node-version: 20.x
- run: deno task ci

analyze:
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
coverage
utils/tests/assets/x-*.xml
utils/tests/assets/x-*.xml
utils/tests/compatibility/_example.node.mjs
10 changes: 6 additions & 4 deletions deno.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,18 @@
},
"tasks": {
"ci": "deno fmt --check && deno task test && deno task bench",
"test": "deno fmt && deno test --coverage --doc && deno coverage && deno lint",
"bench": "deno bench --allow-read --allow-write=utils/tests/assets"
"test": "deno fmt && deno test --coverage --doc --allow-read --allow-env --allow-run=node,bun --allow-write=utils/tests --allow-net=deno.land && deno coverage && deno lint",
"bench": "deno bench --allow-read --allow-write=utils/tests"
},
"lint": {
"rules": {
"exclude": ["no-extra-semi"]
}
},
"exclude": ["utils/tests/compatibility/_example.node.mjs"]
},
"fmt": {
"lineWidth": 120,
"semiColons": false
"semiColons": false,
"exclude": ["utils/tests/compatibility/_example.node.mjs"]
}
}
65 changes: 64 additions & 1 deletion deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

48 changes: 48 additions & 0 deletions utils/tests/compatibility/_compatibility.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { expect } from "https://deno.land/std@0.223.0/expect/expect.ts"
import { fromFileUrl } from "https://deno.land/std@0.223.0/path/from_file_url.ts"
import { bundle } from "https://deno.land/x/libs@0.4.0/bundle.ts"

const example = {
url: new URL("./_example.mjs", import.meta.url),
path: {
bun: fromFileUrl(new URL("./_example.mjs", import.meta.url)),
node: fromFileUrl(new URL("./_example.node.mjs", import.meta.url)),
},
}

export async function test(runtime: "node" | "bun") {
try {
const binary = new Deno.Command(runtime)
await binary.output()
let args = []
switch (runtime) {
case "node":
// We also need to transpile to javascript for node
await Deno.writeTextFile(example.path.node, await bundle(example.url))
args = [example.path.node]
break
case "bun":
args = ["run", example.path.bun]
break
default:
throw new Error(`Unknown runtime: ${runtime}`)
}
Deno.test(`compatibility: ${runtime}`, async () => {
const command = new Deno.Command(runtime, { args, stdout: "piped", stderr: "piped" })
const { code, stdout, stderr, success } = await command.output()
if (!success) {
console.log(`Command: ${runtime} ${args.join(" ")}`)
console.error(`Exit code: ${code}`)
console.log(new TextDecoder().decode(stdout))
console.error(new TextDecoder().decode(stderr))
}
expect(code).toBe(0)
expect(success).toBe(true)
})
} catch (error) {
if ((!(error instanceof Deno.errors.NotFound)) && (!(error instanceof Deno.errors.PermissionDenied))) {
throw error
}
Deno.test.ignore(`compatibility: ${runtime} (${error})`, () => {})
}
}
44 changes: 44 additions & 0 deletions utils/tests/compatibility/_example.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* This script is used to test the compatibility of the library with other runtime environments.
*
* Rather than running all the unit tests, it simply checks if the library is able to parse and
* stringify the content of some XML files. If it can, then we assume that the remaining unit
* tests would succeed as well since there aren't any dependencies or runtime-specific code.
*/
import { parse, stringify } from "../../../mod.ts"

for (const file of ["small.xml", "medium.xml"]) {
let content = ""
for (const _ of ["fetch", "retry"]) {
try {
content = await fetch(new URL(`../assets/${file}`, import.meta.url)).then((response) => response.text())
break
} // NODEJS: fetch does not support the file protocol, polyfill it with fs on the fly
catch (error) {
if ((!(error instanceof TypeError)) || (_ === "retry")) {
throw error
}
const fs = await import("node:fs/promises")
// deno-lint-ignore no-global-assign
fetch = async (url) => {
// Fix the local path on windows
url.pathname = url.pathname.replace(/^\/[A-Z]:\//, "/")
return new Response(await fs.readFile(url.pathname))
}
}
}
content = content.replaceAll("\r\n", "\n").trim()
try {
if (!content) {
throw new Error("Content is empty")
}
if (stringify(parse(content)) !== content) {
throw new Error("The parsed content is not equal to the original content")
}
} catch (error) {
console.error(`${file}: ko`)
console.error(error)
throw error
}
console.log(`${file}: ok`)
}
31 changes: 31 additions & 0 deletions utils/tests/compatibility/browser_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { expect } from "https://deno.land/std@0.223.0/expect/expect.ts"
import { encodeBase64 } from "https://deno.land/std@0.223.0/encoding/base64.ts"

Deno.test("compatibility: browser", async () => {
// Simulate browser environment by removing Deno namespace insided worker
const mod = new URL("../../../mod.ts", import.meta.url)
const worker = new Worker(
new URL(`data:application/typescript;base64,${
encodeBase64(`
delete globalThis.Deno;
import { parse, stringify } from "${mod.href}";
onmessage = () => {
try {
parse("<root/>")
stringify({ root: null })
postMessage(true)
}
catch {
postMessage(false)
}
}
`)
}`),
{ type: "module" },
)
const promise = new Promise<void>((resolve, reject) => {
worker.onmessage = ({ data }) => data ? resolve() : reject()
})
worker.postMessage(null)
await expect(promise).not.resolves.toThrow()
})
2 changes: 2 additions & 0 deletions utils/tests/compatibility/bun_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { test } from "./_compatibility.ts"
await test("bun")
2 changes: 2 additions & 0 deletions utils/tests/compatibility/node_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { test } from "./_compatibility.ts"
await test("node")