diff options
| author | 2023-03-15 17:34:11 -0700 | |
|---|---|---|
| committer | 2023-03-15 17:34:23 -0700 | |
| commit | 976ef924731149b17bb997cd43d8aedf392e6b50 (patch) | |
| tree | d2236a0a616a0dcf114e3f489db9d59af83c323a | |
| parent | abd34abf0886866208fe607901f57efb83770150 (diff) | |
| download | bun-976ef924731149b17bb997cd43d8aedf392e6b50.tar.gz bun-976ef924731149b17bb997cd43d8aedf392e6b50.tar.zst bun-976ef924731149b17bb997cd43d8aedf392e6b50.zip | |
Improve reliability of generated tests
27 files changed, 921 insertions, 821 deletions
diff --git a/test/js/deno/.gitignore b/test/js/deno/.gitignore deleted file mode 100644 index 2fb5beae2..000000000 --- a/test/js/deno/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.deno.* diff --git a/test/js/deno/abort/abort-controller.test.ts b/test/js/deno/abort/abort-controller.test.ts index 32f33a15d..3e201f387 100644 --- a/test/js/deno/abort/abort-controller.test.ts +++ b/test/js/deno/abort/abort-controller.test.ts @@ -1,7 +1,9 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/abort_controller_test.ts -import { assert, assertEquals } from "deno:harness"; -Deno.test(function basicAbortController() { +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals } = createDenoTest(import.meta.path); +test(function basicAbortController() { const controller = new AbortController(); assert(controller); const { signal } = controller; @@ -10,7 +12,7 @@ Deno.test(function basicAbortController() { controller.abort(); assertEquals(signal.aborted, true); }); -Deno.test(function signalCallsOnabort() { +test(function signalCallsOnabort() { const controller = new AbortController(); const { signal } = controller; let called = false; @@ -22,7 +24,7 @@ Deno.test(function signalCallsOnabort() { controller.abort(); assert(called); }); -Deno.test(function signalEventListener() { +test(function signalEventListener() { const controller = new AbortController(); const { signal } = controller; let called = false; @@ -34,7 +36,7 @@ Deno.test(function signalEventListener() { controller.abort(); assert(called); }); -Deno.test(function onlyAbortsOnce() { +test(function onlyAbortsOnce() { const controller = new AbortController(); const { signal } = controller; let called = 0; @@ -47,11 +49,11 @@ Deno.test(function onlyAbortsOnce() { controller.abort(); assertEquals(called, 2); }); -Deno.test(function controllerHasProperToString() { +test(function controllerHasProperToString() { const actual = Object.prototype.toString.call(new AbortController()); assertEquals(actual, "[object AbortController]"); }); -Deno.test(function abortReason() { +test(function abortReason() { const signal = AbortSignal.abort("hey!"); assertEquals(signal.aborted, true); assertEquals(signal.reason, "hey!"); diff --git a/test/js/deno/crypto/random.test.ts b/test/js/deno/crypto/random.test.ts index 09258b3f5..0d80e129d 100644 --- a/test/js/deno/crypto/random.test.ts +++ b/test/js/deno/crypto/random.test.ts @@ -1,52 +1,54 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/get_random_values_test.ts -import { assertNotEquals, assertStrictEquals } from "deno:harness"; -Deno.test(function getRandomValuesInt8Array() { +import { createDenoTest } from "deno:harness"; +const { test, assertNotEquals, assertStrictEquals } = createDenoTest(import.meta.path); +test(function getRandomValuesInt8Array() { const arr = new Int8Array(32); crypto.getRandomValues(arr); assertNotEquals(arr, new Int8Array(32)); }); -Deno.test(function getRandomValuesUint8Array() { +test(function getRandomValuesUint8Array() { const arr = new Uint8Array(32); crypto.getRandomValues(arr); assertNotEquals(arr, new Uint8Array(32)); }); -Deno.test(function getRandomValuesUint8ClampedArray() { +test(function getRandomValuesUint8ClampedArray() { const arr = new Uint8ClampedArray(32); crypto.getRandomValues(arr); assertNotEquals(arr, new Uint8ClampedArray(32)); }); -Deno.test(function getRandomValuesInt16Array() { +test(function getRandomValuesInt16Array() { const arr = new Int16Array(4); crypto.getRandomValues(arr); assertNotEquals(arr, new Int16Array(4)); }); -Deno.test(function getRandomValuesUint16Array() { +test(function getRandomValuesUint16Array() { const arr = new Uint16Array(4); crypto.getRandomValues(arr); assertNotEquals(arr, new Uint16Array(4)); }); -Deno.test(function getRandomValuesInt32Array() { +test(function getRandomValuesInt32Array() { const arr = new Int32Array(8); crypto.getRandomValues(arr); assertNotEquals(arr, new Int32Array(8)); }); -Deno.test(function getRandomValuesBigInt64Array() { +test(function getRandomValuesBigInt64Array() { const arr = new BigInt64Array(8); crypto.getRandomValues(arr); assertNotEquals(arr, new BigInt64Array(8)); }); -Deno.test(function getRandomValuesUint32Array() { +test(function getRandomValuesUint32Array() { const arr = new Uint32Array(8); crypto.getRandomValues(arr); assertNotEquals(arr, new Uint32Array(8)); }); -Deno.test(function getRandomValuesBigUint64Array() { +test(function getRandomValuesBigUint64Array() { const arr = new BigUint64Array(8); crypto.getRandomValues(arr); assertNotEquals(arr, new BigUint64Array(8)); }); -Deno.test(function getRandomValuesReturnValue() { +test(function getRandomValuesReturnValue() { const arr = new Uint32Array(8); const rtn = crypto.getRandomValues(arr); assertNotEquals(arr, new Uint32Array(8)); diff --git a/test/js/deno/crypto/webcrypto.test.ts b/test/js/deno/crypto/webcrypto.test.ts index d8a4e0bd7..ea55e936f 100644 --- a/test/js/deno/crypto/webcrypto.test.ts +++ b/test/js/deno/crypto/webcrypto.test.ts @@ -1,7 +1,9 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/webcrypto_test.ts -import { assert, assertEquals, assertNotEquals, assertRejects } from "deno:harness"; -Deno.test(async function testImportArrayBufferKey() { +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals, assertNotEquals, assertRejects } = createDenoTest(import.meta.path); +test(async function testImportArrayBufferKey() { const subtle = window.crypto.subtle; assert(subtle); const key = new Uint8Array([ @@ -33,7 +35,7 @@ Deno.test(async function testImportArrayBufferKey() { name: "HMAC" }, cryptoKey, new Uint8Array(8)); }); -Deno.test(async function testSignVerify() { +test(async function testSignVerify() { const subtle = window.crypto.subtle; assert(subtle); for (const algorithm of [ @@ -316,7 +318,7 @@ const hashPlainTextVector = [ plainText: plainText.slice(0, 126) } ]; -Deno.test(async function testEncryptDecrypt() { +test(async function testEncryptDecrypt() { const subtle = window.crypto.subtle; assert(subtle); for (const { hash , plainText } of hashPlainTextVector){ @@ -356,7 +358,7 @@ Deno.test(async function testEncryptDecrypt() { }, DOMException); } }); -Deno.test(async function testGenerateRSAKey() { +test(async function testGenerateRSAKey() { const subtle = window.crypto.subtle; assert(subtle); const keyPair = await subtle.generateKey({ @@ -377,7 +379,7 @@ Deno.test(async function testGenerateRSAKey() { assertEquals(keyPair.privateKey.extractable, true); assert(keyPair.privateKey.usages.includes("sign")); }); -Deno.test(async function testGenerateHMACKey() { +test(async function testGenerateHMACKey() { const key = await window.crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-512" @@ -389,7 +391,7 @@ Deno.test(async function testGenerateHMACKey() { assertEquals(key.extractable, true); assert(key.usages.includes("sign")); }); -Deno.test(async function testECDSASignVerify() { +test(async function testECDSASignVerify() { const key = await window.crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-384" @@ -413,7 +415,7 @@ Deno.test(async function testECDSASignVerify() { }, key.publicKey, signature, encoded); assert(verified); }); -Deno.test(async function testECDSASignVerifyFail() { +test(async function testECDSASignVerifyFail() { const key = await window.crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-384" @@ -447,7 +449,7 @@ Deno.test(async function testECDSASignVerifyFail() { throw new TypeError("unreachable"); }, DOMException); }); -Deno.test(async function testSignRSASSAKey() { +test(async function testSignRSASSAKey() { const subtle = window.crypto.subtle; assert(subtle); const keyPair = await subtle.generateKey({ @@ -501,7 +503,7 @@ const jwk: JsonWebKey = { "sign" ] }; -Deno.test(async function subtleCryptoHmacImportExport() { +test(async function subtleCryptoHmacImportExport() { const key1 = await crypto.subtle.importKey("raw", rawKey, { name: "HMAC", hash: "SHA-256" @@ -571,7 +573,7 @@ Deno.test(async function subtleCryptoHmacImportExport() { const exportedKey2 = await crypto.subtle.exportKey("jwk", key2); assertEquals(exportedKey2, jwk); }); -Deno.test(async function generateImportHmacJwk() { +test(async function generateImportHmacJwk() { const key = await crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-512" @@ -600,7 +602,7 @@ const pkcs8TestVectors = [ hash: "SHA-256" } ]; -Deno.test({ +test({ permissions: { read: true } @@ -652,7 +654,7 @@ const nonInteroperableVectors = [ hash: "SHA-1" } ]; -Deno.test({ +test({ permissions: { read: true } @@ -695,7 +697,7 @@ const asn1AlgorithmIdentifier = new Uint8Array([ 0x05, 0x00 ]); -Deno.test(async function rsaExport() { +test(async function rsaExport() { for (const algorithm of [ "RSASSA-PKCS1-v1_5", "RSA-PSS", @@ -732,7 +734,7 @@ Deno.test(async function rsaExport() { assertEquals(spki.slice(4, asn1AlgorithmIdentifier.byteLength + 1), asn1AlgorithmIdentifier.slice(3)); } }); -Deno.test(async function testHkdfDeriveBits() { +test(async function testHkdfDeriveBits() { const rawKey = crypto.getRandomValues(new Uint8Array(16)); const key = await crypto.subtle.importKey("raw", rawKey, { name: "HKDF", @@ -750,7 +752,7 @@ Deno.test(async function testHkdfDeriveBits() { }, key, 128); assertEquals(result.byteLength, 128 / 8); }); -Deno.test(async function testHkdfDeriveBitsWithLargeKeySize() { +test(async function testHkdfDeriveBitsWithLargeKeySize() { const key = await crypto.subtle.importKey("raw", new Uint8Array([ 0x00 ]), "HKDF", false, [ @@ -763,7 +765,7 @@ Deno.test(async function testHkdfDeriveBitsWithLargeKeySize() { info: new Uint8Array() }, key, ((20 * 255) << 3) + 8), DOMException, "The length provided for HKDF is too large"); }); -Deno.test(async function testEcdhDeriveBitsWithShorterLength() { +test(async function testEcdhDeriveBitsWithShorterLength() { const keypair = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-384" @@ -777,7 +779,7 @@ Deno.test(async function testEcdhDeriveBitsWithShorterLength() { }, keypair.privateKey, 256); assertEquals(result.byteLength * 8, 256); }); -Deno.test(async function testEcdhDeriveBitsWithLongerLength() { +test(async function testEcdhDeriveBitsWithLongerLength() { const keypair = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-384" @@ -790,7 +792,7 @@ Deno.test(async function testEcdhDeriveBitsWithLongerLength() { public: keypair.publicKey }, keypair.privateKey, 512), DOMException, "Invalid length"); }); -Deno.test(async function testEcdhDeriveBitsWithNullLength() { +test(async function testEcdhDeriveBitsWithNullLength() { const keypair = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-384" @@ -804,7 +806,7 @@ Deno.test(async function testEcdhDeriveBitsWithNullLength() { }, keypair.privateKey, null); assertEquals(result.byteLength * 8, 384); }); -Deno.test(async function testDeriveKey() { +test(async function testDeriveKey() { const rawKey = crypto.getRandomValues(new Uint8Array(16)); const key = await crypto.subtle.importKey("raw", rawKey, "PBKDF2", false, [ "deriveKey", @@ -833,7 +835,7 @@ Deno.test(async function testDeriveKey() { assertEquals(algorithm.hash.name, "SHA-256"); assertEquals(algorithm.length, 512); }); -Deno.test(async function testAesCbcEncryptDecrypt() { +test(async function testAesCbcEncryptDecrypt() { const key = await crypto.subtle.generateKey({ name: "AES-CBC", length: 128 @@ -870,7 +872,7 @@ Deno.test(async function testAesCbcEncryptDecrypt() { 6 ])); }); -Deno.test(async function testAesCtrEncryptDecrypt() { +test(async function testAesCtrEncryptDecrypt() { async function aesCtrRoundTrip(key: CryptoKey, counter: Uint8Array, length: number, plainText: Uint8Array) { const cipherText = await crypto.subtle.encrypt({ name: "AES-CTR", @@ -943,7 +945,7 @@ Deno.test(async function testAesCtrEncryptDecrypt() { } } }); -Deno.test(async function testECDH() { +test(async function testECDH() { for (const keySize of [ 256, 384 @@ -962,7 +964,7 @@ Deno.test(async function testECDH() { assertEquals(derivedKey.byteLength, keySize / 8); } }); -Deno.test(async function testWrapKey() { +test(async function testWrapKey() { const key = await crypto.subtle.generateKey({ name: "RSA-OAEP", modulusLength: 4096, @@ -990,7 +992,7 @@ Deno.test(async function testWrapKey() { assert(wrappedKey instanceof ArrayBuffer); assertEquals(wrappedKey.byteLength, 512); }); -Deno.test.ignore(async function testAesKeyGen() { +test.ignore(async function testAesKeyGen() { const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 @@ -1009,7 +1011,7 @@ Deno.test.ignore(async function testAesKeyGen() { assertEquals(algorithm.name, "AES-GCM"); assertEquals(algorithm.length, 256); }); -Deno.test.ignore(async function testUnwrapKey() { +test.ignore(async function testUnwrapKey() { const subtle = crypto.subtle; const AES_KEY: AesKeyAlgorithm & AesCbcParams = { name: "AES-CBC", @@ -1058,7 +1060,7 @@ Deno.test.ignore(async function testUnwrapKey() { "decrypt" ]); }); -Deno.test(async function testDecryptWithInvalidIntializationVector() { +test(async function testDecryptWithInvalidIntializationVector() { const data = new Uint8Array([ 42, 42, @@ -1189,7 +1191,7 @@ const jwtRSAKeys = { } } }; -Deno.test(async function testImportRsaJwk() { +test(async function testImportRsaJwk() { const subtle = window.crypto.subtle; assert(subtle); for (const [_key, jwkData] of Object.entries(jwtRSAKeys)){ @@ -1420,7 +1422,7 @@ function equalJwk(expected: JWK, got: JWK): boolean { } return true; } -Deno.test(async function testImportExportEcDsaJwk() { +test(async function testImportExportEcDsaJwk() { const subtle = crypto.subtle; assert(subtle); for (const [_key, keyData] of Object.entries(jwtECKeys)){ @@ -1476,7 +1478,7 @@ Deno.test(async function testImportExportEcDsaJwk() { assert(verifyECDSA); } }); -Deno.test(async function testImportEcDhJwk() { +test(async function testImportEcDhJwk() { const subtle = crypto.subtle; assert(subtle); for (const [_key, jwkData] of Object.entries(jwtECKeys)){ @@ -2233,7 +2235,7 @@ const ecTestKeys = [ ]) } ]; -Deno.test(async function testImportEcSpkiPkcs8() { +test(async function testImportEcSpkiPkcs8() { const subtle = window.crypto.subtle; assert(subtle); for (const { namedCurve , raw , spki , pkcs8 , signatureLength } of ecTestKeys){ @@ -2318,7 +2320,7 @@ Deno.test(async function testImportEcSpkiPkcs8() { } } }); -Deno.test(async function testAesGcmEncrypt() { +test(async function testAesGcmEncrypt() { const key = await crypto.subtle.importKey("raw", new Uint8Array(16), { name: "AES-GCM", length: 256 @@ -2435,7 +2437,7 @@ async function roundTripSecretJwk(jwk: JsonWebKey, algId: AlgorithmIdentifier | const exportedKey = await crypto.subtle.exportKey("jwk", key); validateKeys(key, jwk, exportedKey); } -Deno.test(async function testSecretJwkBase64Url() { +test(async function testSecretJwkBase64Url() { const keyData = `{ "kty": "oct", "k": "xxx", @@ -2526,7 +2528,7 @@ Deno.test(async function testSecretJwkBase64Url() { assertEquals(exp.k, "_____________________w"); }); }); -Deno.test(async function testAESWrapKey() { +test(async function testAESWrapKey() { const key = await crypto.subtle.generateKey({ name: "AES-KW", length: 128 @@ -2560,7 +2562,7 @@ Deno.test(async function testAESWrapKey() { const unwrappedKeyBytes = await crypto.subtle.exportKey("raw", unwrappedKey); assertEquals(new Uint8Array(hmacKeyBytes), new Uint8Array(unwrappedKeyBytes)); }); -Deno.test(async function testAesGcmTagLength() { +test(async function testAesGcmTagLength() { const key = await crypto.subtle.importKey("raw", new Uint8Array(32), "AES-GCM", false, [ "encrypt", "decrypt" @@ -2579,7 +2581,7 @@ Deno.test(async function testAesGcmTagLength() { }, key, encrypted); }); }); -Deno.test(async function ecPrivateKeyMaterialExportSpki() { +test(async function ecPrivateKeyMaterialExportSpki() { const keys = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" @@ -2592,7 +2594,7 @@ Deno.test(async function ecPrivateKeyMaterialExportSpki() { const spki = await crypto.subtle.exportKey("spki", keys.publicKey); assert(spki instanceof ArrayBuffer); }); -Deno.test(async function importJwkWithUse() { +test(async function importJwkWithUse() { const jwk = { "kty": "EC", "use": "sig", @@ -2609,7 +2611,7 @@ Deno.test(async function importJwkWithUse() { ]); assert(key instanceof CryptoKey); }); -Deno.test(async function exportKeyNotExtractable() { +test(async function exportKeyNotExtractable() { const key = await crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-512" @@ -2623,7 +2625,7 @@ Deno.test(async function exportKeyNotExtractable() { await crypto.subtle.exportKey("raw", key); }, DOMException); }); -Deno.test(async function testImportLeadingZeroesKey() { +test(async function testImportLeadingZeroesKey() { const alg = { name: "ECDSA", namedCurve: "P-256" @@ -2646,7 +2648,7 @@ Deno.test(async function testImportLeadingZeroesKey() { assert(key instanceof CryptoKey); assertEquals(key.type, "private"); }); -Deno.test(async function testECspkiRoundTrip() { +test(async function testECspkiRoundTrip() { const alg = { name: "ECDH", namedCurve: "P-256" @@ -2657,7 +2659,7 @@ Deno.test(async function testECspkiRoundTrip() { const spki = await crypto.subtle.exportKey("spki", publicKey); await crypto.subtle.importKey("spki", spki, alg, true, []); }); -Deno.test(async function testHmacJwkImport() { +test(async function testHmacJwkImport() { await crypto.subtle.importKey("jwk", { kty: "oct", use: "sig", diff --git a/test/js/deno/encoding/encoding.test.ts b/test/js/deno/encoding/encoding.test.ts index cffe93c5d..50956e673 100644 --- a/test/js/deno/encoding/encoding.test.ts +++ b/test/js/deno/encoding/encoding.test.ts @@ -1,17 +1,19 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/text_encoding_test.ts -import { assert, assertEquals, assertThrows } from "deno:harness"; -Deno.test(function btoaSuccess() { +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals, assertThrows } = createDenoTest(import.meta.path); +test(function btoaSuccess() { const text = "hello world"; const encoded = btoa(text); assertEquals(encoded, "aGVsbG8gd29ybGQ="); }); -Deno.test(function atobSuccess() { +test(function atobSuccess() { const encoded = "aGVsbG8gd29ybGQ="; const decoded = atob(encoded); assertEquals(decoded, "hello world"); }); -Deno.test(function atobWithAsciiWhitespace() { +test(function atobWithAsciiWhitespace() { const encodedList = [ " aGVsbG8gd29ybGQ=", " aGVsbG8gd29ybGQ=", @@ -26,7 +28,7 @@ Deno.test(function atobWithAsciiWhitespace() { assertEquals(decoded, "hello world"); } }); -Deno.test(function atobThrows() { +test(function atobThrows() { let threw = false; try { atob("aGVsbG8gd29ybGQ=="); @@ -35,7 +37,7 @@ Deno.test(function atobThrows() { } assert(threw); }); -Deno.test(function atobThrows2() { +test(function atobThrows2() { let threw = false; try { atob("aGVsbG8gd29ybGQ==="); @@ -44,7 +46,7 @@ Deno.test(function atobThrows2() { } assert(threw); }); -Deno.test(function atobThrows3() { +test(function atobThrows3() { let threw = false; try { atob("foobar!!"); @@ -55,13 +57,13 @@ Deno.test(function atobThrows3() { } assert(threw); }); -Deno.test(function btoaFailed() { +test(function btoaFailed() { const text = "ä½ å„½"; assertThrows(()=>{ btoa(text); }, DOMException); }); -Deno.test(function textDecoder2() { +test(function textDecoder2() { const fixture = new Uint8Array([ 0xf0, 0x9d, @@ -83,7 +85,7 @@ Deno.test(function textDecoder2() { const decoder = new TextDecoder(); assertEquals(decoder.decode(fixture), "š½š®šš½"); }); -Deno.test(function textDecoderASCII() { +test(function textDecoderASCII() { const fixture = new Uint8Array([ 0x89, 0x95, @@ -93,7 +95,7 @@ Deno.test(function textDecoderASCII() { const decoder = new TextDecoder("ascii"); assertEquals(decoder.decode(fixture), "ā°ā¢ÅøĀæ"); }); -Deno.test.ignore(function textDecoderErrorEncoding() { +test.ignore(function textDecoderErrorEncoding() { let didThrow = false; try { new TextDecoder("Foo"); @@ -104,7 +106,7 @@ Deno.test.ignore(function textDecoderErrorEncoding() { } assert(didThrow); }); -Deno.test(function textEncoder() { +test(function textEncoder() { const fixture = "š½š®šš½"; const encoder = new TextEncoder(); assertEquals(Array.from(encoder.encode(fixture)), [ @@ -126,7 +128,7 @@ Deno.test(function textEncoder() { 0xbd ]); }); -Deno.test(function textEncodeInto() { +test(function textEncodeInto() { const fixture = "text"; const encoder = new TextEncoder(); const bytes = new Uint8Array(5); @@ -141,7 +143,7 @@ Deno.test(function textEncodeInto() { 0x00 ]); }); -Deno.test(function textEncodeInto2() { +test(function textEncodeInto2() { const fixture = "š½š®šš½"; const encoder = new TextEncoder(); const bytes = new Uint8Array(17); @@ -168,7 +170,7 @@ Deno.test(function textEncodeInto2() { 0x00 ]); }); -Deno.test(function textEncodeInto3() { +test(function textEncodeInto3() { const fixture = "š½š®šš½"; const encoder = new TextEncoder(); const bytes = new Uint8Array(5); @@ -183,7 +185,7 @@ Deno.test(function textEncodeInto3() { 0x00 ]); }); -Deno.test(function loneSurrogateEncodeInto() { +test(function loneSurrogateEncodeInto() { const fixture = "loneš\ud888surrogate"; const encoder = new TextEncoder(); const bytes = new Uint8Array(20); @@ -213,7 +215,7 @@ Deno.test(function loneSurrogateEncodeInto() { 0x65 ]); }); -Deno.test(function loneSurrogateEncodeInto2() { +test(function loneSurrogateEncodeInto2() { const fixture = "\ud800"; const encoder = new TextEncoder(); const bytes = new Uint8Array(3); @@ -226,7 +228,7 @@ Deno.test(function loneSurrogateEncodeInto2() { 0xbd ]); }); -Deno.test(function loneSurrogateEncodeInto3() { +test(function loneSurrogateEncodeInto3() { const fixture = "\udc00"; const encoder = new TextEncoder(); const bytes = new Uint8Array(3); @@ -239,7 +241,7 @@ Deno.test(function loneSurrogateEncodeInto3() { 0xbd ]); }); -Deno.test(function swappedSurrogatePairEncodeInto4() { +test(function swappedSurrogatePairEncodeInto4() { const fixture = "\udc00\ud800"; const encoder = new TextEncoder(); const bytes = new Uint8Array(8); @@ -257,7 +259,7 @@ Deno.test(function swappedSurrogatePairEncodeInto4() { 0x00 ]); }); -Deno.test(function textDecoderSharedUint8Array() { +test(function textDecoderSharedUint8Array() { const ab = new SharedArrayBuffer(6); const dataView = new DataView(ab); const charCodeA = "A".charCodeAt(0); @@ -269,7 +271,7 @@ Deno.test(function textDecoderSharedUint8Array() { const actual = decoder.decode(ui8); assertEquals(actual, "ABCDEF"); }); -Deno.test(function textDecoderSharedInt32Array() { +test(function textDecoderSharedInt32Array() { const ab = new SharedArrayBuffer(8); const dataView = new DataView(ab); const charCodeA = "A".charCodeAt(0); @@ -281,13 +283,13 @@ Deno.test(function textDecoderSharedInt32Array() { const actual = decoder.decode(i32); assertEquals(actual, "ABCDEFGH"); }); -Deno.test(function toStringShouldBeWebCompatibility() { +test(function toStringShouldBeWebCompatibility() { const encoder = new TextEncoder(); assertEquals(encoder.toString(), "[object TextEncoder]"); const decoder = new TextDecoder(); assertEquals(decoder.toString(), "[object TextDecoder]"); }); -Deno.test(function textEncoderShouldCoerceToString() { +test(function textEncoderShouldCoerceToString() { const encoder = new TextEncoder(); const fixutreText = "text"; const fixture = { @@ -300,7 +302,7 @@ Deno.test(function textEncoderShouldCoerceToString() { const decoded = decoder.decode(bytes); assertEquals(decoded, fixutreText); }); -Deno.test.ignore(function binaryEncode() { +test.ignore(function binaryEncode() { const ops = Deno[Deno.internal].core.ops; function asBinaryString(bytes: Uint8Array): string { return Array.from(bytes).map((v: number)=>String.fromCodePoint(v)).join(""); diff --git a/test/js/deno/event/custom-event.test.ts b/test/js/deno/event/custom-event.test.ts index 29bb0dbc9..4abd3ea7d 100644 --- a/test/js/deno/event/custom-event.test.ts +++ b/test/js/deno/event/custom-event.test.ts @@ -1,7 +1,9 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/custom_event_test.ts -import { assertEquals } from "deno:harness"; -Deno.test(function customEventInitializedWithDetail() { +import { createDenoTest } from "deno:harness"; +const { test, assertEquals } = createDenoTest(import.meta.path); +test(function customEventInitializedWithDetail() { const type = "touchstart"; const detail = { message: "hello" @@ -20,7 +22,7 @@ Deno.test(function customEventInitializedWithDetail() { assertEquals(event.target, null); assertEquals(event.type, type); }); -Deno.test(function toStringShouldBeWebCompatibility() { +test(function toStringShouldBeWebCompatibility() { const type = "touchstart"; const event = new CustomEvent(type, {}); assertEquals(event.toString(), "[object CustomEvent]"); diff --git a/test/js/deno/event/event-target.test.ts b/test/js/deno/event/event-target.test.ts index 85d7c0918..2ab578663 100644 --- a/test/js/deno/event/event-target.test.ts +++ b/test/js/deno/event/event-target.test.ts @@ -1,13 +1,15 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/event_target_test.ts -import { assertEquals, assertThrows } from "deno:harness"; -Deno.test(function addEventListenerTest() { +import { createDenoTest } from "deno:harness"; +const { test, assertEquals, assertThrows } = createDenoTest(import.meta.path); +test(function addEventListenerTest() { const document = new EventTarget(); assertEquals(document.addEventListener("x", null, false), undefined); assertEquals(document.addEventListener("x", null, true), undefined); assertEquals(document.addEventListener("x", null), undefined); }); -Deno.test(function constructedEventTargetCanBeUsedAsExpected() { +test(function constructedEventTargetCanBeUsedAsExpected() { const target = new EventTarget(); const event = new Event("foo", { bubbles: true, @@ -27,7 +29,7 @@ Deno.test(function constructedEventTargetCanBeUsedAsExpected() { target.dispatchEvent(event); assertEquals(callCount, 2); }); -Deno.test(function anEventTargetCanBeSubclassed() { +test(function anEventTargetCanBeSubclassed() { class NicerEventTarget extends EventTarget { on(type: string, callback: ((e: Event) => void) | null, options?: AddEventListenerOptions) { this.addEventListener(type, callback, options); @@ -50,13 +52,13 @@ Deno.test(function anEventTargetCanBeSubclassed() { target.off("foo", listener); assertEquals(callCount, 0); }); -Deno.test(function removingNullEventListenerShouldSucceed() { +test(function removingNullEventListenerShouldSucceed() { const document = new EventTarget(); assertEquals(document.removeEventListener("x", null, false), undefined); assertEquals(document.removeEventListener("x", null, true), undefined); assertEquals(document.removeEventListener("x", null), undefined); }); -Deno.test(function constructedEventTargetUseObjectPrototype() { +test(function constructedEventTargetUseObjectPrototype() { const target = new EventTarget(); const event = new Event("toString", { bubbles: true, @@ -76,11 +78,11 @@ Deno.test(function constructedEventTargetUseObjectPrototype() { target.dispatchEvent(event); assertEquals(callCount, 2); }); -Deno.test(function toStringShouldBeWebCompatible() { +test(function toStringShouldBeWebCompatible() { const target = new EventTarget(); assertEquals(target.toString(), "[object EventTarget]"); }); -Deno.test(function dispatchEventShouldNotThrowError() { +test(function dispatchEventShouldNotThrowError() { let hasThrown = false; try { const target = new EventTarget(); @@ -96,7 +98,7 @@ Deno.test(function dispatchEventShouldNotThrowError() { } assertEquals(hasThrown, false); }); -Deno.test.ignore(function eventTargetThisShouldDefaultToWindow() { +test.ignore(function eventTargetThisShouldDefaultToWindow() { const { addEventListener , dispatchEvent , removeEventListener } = EventTarget.prototype; let n = 1; const event = new Event("hello"); @@ -118,7 +120,7 @@ Deno.test.ignore(function eventTargetThisShouldDefaultToWindow() { dispatchEvent(event); assertEquals(n, 1); }); -Deno.test(function eventTargetShouldAcceptEventListenerObject() { +test(function eventTargetShouldAcceptEventListenerObject() { const target = new EventTarget(); const event = new Event("foo", { bubbles: true, @@ -140,7 +142,7 @@ Deno.test(function eventTargetShouldAcceptEventListenerObject() { target.dispatchEvent(event); assertEquals(callCount, 2); }); -Deno.test(function eventTargetShouldAcceptAsyncFunction() { +test(function eventTargetShouldAcceptAsyncFunction() { const target = new EventTarget(); const event = new Event("foo", { bubbles: true, @@ -160,7 +162,7 @@ Deno.test(function eventTargetShouldAcceptAsyncFunction() { target.dispatchEvent(event); assertEquals(callCount, 2); }); -Deno.test(function eventTargetShouldAcceptAsyncFunctionForEventListenerObject() { +test(function eventTargetShouldAcceptAsyncFunctionForEventListenerObject() { const target = new EventTarget(); const event = new Event("foo", { bubbles: true, @@ -182,14 +184,14 @@ Deno.test(function eventTargetShouldAcceptAsyncFunctionForEventListenerObject() target.dispatchEvent(event); assertEquals(callCount, 2); }); -Deno.test(function eventTargetDispatchShouldSetTargetNoListener() { +test(function eventTargetDispatchShouldSetTargetNoListener() { const target = new EventTarget(); const event = new Event("foo"); assertEquals(event.target, null); target.dispatchEvent(event); assertEquals(event.target, target); }); -Deno.test(function eventTargetDispatchShouldSetTargetInListener() { +test(function eventTargetDispatchShouldSetTargetInListener() { const target = new EventTarget(); const event = new Event("foo"); assertEquals(event.target, null); @@ -201,7 +203,7 @@ Deno.test(function eventTargetDispatchShouldSetTargetInListener() { target.dispatchEvent(event); assertEquals(called, true); }); -Deno.test(function eventTargetAddEventListenerGlobalAbort() { +test(function eventTargetAddEventListenerGlobalAbort() { return new Promise((resolve)=>{ const c = new AbortController(); c.signal.addEventListener("abort", ()=>resolve()); @@ -211,7 +213,7 @@ Deno.test(function eventTargetAddEventListenerGlobalAbort() { c.abort(); }); }); -Deno.test(function eventTargetBrandChecking() { +test(function eventTargetBrandChecking() { const self = {}; assertThrows(()=>{ EventTarget.prototype.addEventListener.call(self, "test", null); diff --git a/test/js/deno/event/event.test.ts b/test/js/deno/event/event.test.ts index cd23b5215..633ba51da 100644 --- a/test/js/deno/event/event.test.ts +++ b/test/js/deno/event/event.test.ts @@ -1,7 +1,9 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/event_test.ts -import { assert, assertEquals, assertStringIncludes } from "deno:harness"; -Deno.test(function eventInitializedWithType() { +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals, assertStringIncludes } = createDenoTest(import.meta.path); +test(function eventInitializedWithType() { const type = "click"; const event = new Event(type); assertEquals(event.isTrusted, false); @@ -11,7 +13,7 @@ Deno.test(function eventInitializedWithType() { assertEquals(event.bubbles, false); assertEquals(event.cancelable, false); }); -Deno.test(function eventInitializedWithTypeAndDict() { +test(function eventInitializedWithTypeAndDict() { const init = "submit"; const eventInit = { bubbles: true, @@ -25,27 +27,27 @@ Deno.test(function eventInitializedWithTypeAndDict() { assertEquals(event.bubbles, true); assertEquals(event.cancelable, true); }); -Deno.test(function eventComposedPathSuccess() { +test(function eventComposedPathSuccess() { const type = "click"; const event = new Event(type); const composedPath = event.composedPath(); assertEquals(composedPath, []); }); -Deno.test(function eventStopPropagationSuccess() { +test(function eventStopPropagationSuccess() { const type = "click"; const event = new Event(type); assertEquals(event.cancelBubble, false); event.stopPropagation(); assertEquals(event.cancelBubble, true); }); -Deno.test(function eventStopImmediatePropagationSuccess() { +test(function eventStopImmediatePropagationSuccess() { const type = "click"; const event = new Event(type); assertEquals(event.cancelBubble, false); event.stopImmediatePropagation(); assertEquals(event.cancelBubble, true); }); -Deno.test(function eventPreventDefaultSuccess() { +test(function eventPreventDefaultSuccess() { const type = "click"; const event = new Event(type); assertEquals(event.defaultPrevented, false); @@ -60,7 +62,7 @@ Deno.test(function eventPreventDefaultSuccess() { cancelableEvent.preventDefault(); assertEquals(cancelableEvent.defaultPrevented, true); }); -Deno.test(function eventInitializedWithNonStringType() { +test(function eventInitializedWithNonStringType() { const type: any = undefined; const event = new Event(type); assertEquals(event.isTrusted, false); @@ -70,7 +72,7 @@ Deno.test(function eventInitializedWithNonStringType() { assertEquals(event.bubbles, false); assertEquals(event.cancelable, false); }); -Deno.test(function eventIsTrusted() { +test(function eventIsTrusted() { const desc1 = Object.getOwnPropertyDescriptor(new Event("x"), "isTrusted"); assert(desc1); assertEquals(typeof desc1.get, "function"); @@ -79,7 +81,7 @@ Deno.test(function eventIsTrusted() { assertEquals(typeof desc2!.get, "function"); assertEquals(desc1!.get, desc2!.get); }); -Deno.test(function eventInspectOutput() { +test.ignore(function eventInspectOutput() { const cases: Array<[any, (event: any) => string]> = [ [ new Event("test"), @@ -106,7 +108,7 @@ Deno.test(function eventInspectOutput() { assertEquals(Deno.inspect(event), outputProvider(event)); } }); -Deno.test(function inspectEvent() { +test.ignore(function inspectEvent() { assertEquals(Deno.inspect(Event.prototype), `Event { bubbles: [Getter], cancelable: [Getter], diff --git a/test/js/deno/fetch/blob.test.ts b/test/js/deno/fetch/blob.test.ts index 8c9c7318c..5a6c2fb80 100644 --- a/test/js/deno/fetch/blob.test.ts +++ b/test/js/deno/fetch/blob.test.ts @@ -1,8 +1,9 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/blob_test.ts -import { assert, assertEquals, assertStringIncludes } from "deno:harness"; -import { concat } from "deno:harness"; -Deno.test(function blobString() { +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals, assertStringIncludes, concat } = createDenoTest(import.meta.path); +test(function blobString() { const b1 = new Blob([ "Hello World" ]); @@ -13,7 +14,7 @@ Deno.test(function blobString() { ]); assertEquals(b2.size, b1.size + str.length); }); -Deno.test(function blobBuffer() { +test(function blobBuffer() { const buffer = new ArrayBuffer(12); const u8 = new Uint8Array(buffer); const f1 = new Float32Array(buffer); @@ -28,7 +29,7 @@ Deno.test(function blobBuffer() { ]); assertEquals(b2.size, 3 * u8.length); }); -Deno.test(function blobSlice() { +test(function blobSlice() { const blob = new Blob([ "Deno", "Foo" @@ -44,7 +45,7 @@ Deno.test(function blobSlice() { const b4 = blob.slice(0, 10); assertEquals(b4.size, blob.size); }); -Deno.test(function blobInvalidType() { +test(function blobInvalidType() { const blob = new Blob([ "foo" ], { @@ -52,7 +53,7 @@ Deno.test(function blobInvalidType() { }); assertEquals(blob.type, ""); }); -Deno.test(function blobShouldNotThrowError() { +test(function blobShouldNotThrowError() { let hasThrown = false; try { const options1: any = { @@ -71,13 +72,13 @@ Deno.test(function blobShouldNotThrowError() { } assertEquals(hasThrown, false); }); -Deno.test(async function blobText() { +test(async function blobText() { const blob = new Blob([ "Hello World" ]); assertEquals(await blob.text(), "Hello World"); }); -Deno.test(async function blobStream() { +test(async function blobStream() { const blob = new Blob([ "Hello World" ]); @@ -96,7 +97,7 @@ Deno.test(async function blobStream() { const decoder = new TextDecoder(); assertEquals(decoder.decode(bytes), "Hello World"); }); -Deno.test(async function blobArrayBuffer() { +test(async function blobArrayBuffer() { const uint = new Uint8Array([ 102, 111, @@ -107,11 +108,11 @@ Deno.test(async function blobArrayBuffer() { ]); assertEquals(await blob.arrayBuffer(), uint.buffer); }); -Deno.test(function blobConstructorNameIsBlob() { +test(function blobConstructorNameIsBlob() { const blob = new Blob(); assertEquals(blob.constructor.name, "Blob"); }); -Deno.test.ignore(function blobCustomInspectFunction() { +test.ignore(function blobCustomInspectFunction() { const blob = new Blob(); assertEquals(Deno.inspect(blob), `Blob { size: 0, type: "" }`); assertStringIncludes(Deno.inspect(Blob.prototype), "Blob"); diff --git a/test/js/deno/fetch/body.test.ts b/test/js/deno/fetch/body.test.ts index 87966bc48..6aa6cbb73 100644 --- a/test/js/deno/fetch/body.test.ts +++ b/test/js/deno/fetch/body.test.ts @@ -1,6 +1,8 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/body_test.ts -import { assert, assertEquals } from "deno:harness"; +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals } = createDenoTest(import.meta.path); function buildBody(body: any, headers?: Headers): Body { const stub = new Request("http://foo/", { body: body, @@ -20,7 +22,7 @@ const intArrays = [ Float32Array, Float64Array ]; -Deno.test(async function arrayBufferFromByteArrays() { +test(async function arrayBufferFromByteArrays() { const buffer = new TextEncoder().encode("ahoyhoy8").buffer; for (const type of intArrays){ const body = buildBody(new type(buffer)); @@ -28,7 +30,7 @@ Deno.test(async function arrayBufferFromByteArrays() { assertEquals(text, "ahoyhoy8"); } }); -Deno.test({ +test({ permissions: { net: true } @@ -42,7 +44,7 @@ Deno.test({ assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n"); assert(formData.has("field_2")); }); -Deno.test({ +test({ permissions: { net: true } @@ -57,7 +59,7 @@ Deno.test({ assert(formData.has("field_2")); assertEquals(formData.get("field_2")!.toString(), "<Deno>"); }); -Deno.test({ +test({ permissions: {} }, async function bodyURLSearchParams() { const body = buildBody(new URLSearchParams({ @@ -66,7 +68,7 @@ Deno.test({ const text = await body.text(); assertEquals(text, "hello=world"); }); -Deno.test(async function bodyArrayBufferMultipleParts() { +test(async function bodyArrayBufferMultipleParts() { const parts: Uint8Array[] = []; let size = 0; for(let i = 0; i <= 150000; i++){ diff --git a/test/js/deno/fetch/headers.test.ts b/test/js/deno/fetch/headers.test.ts index 1bac1b93c..ee2466e32 100644 --- a/test/js/deno/fetch/headers.test.ts +++ b/test/js/deno/fetch/headers.test.ts @@ -1,11 +1,13 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/headers_test.ts -import { assert, assertEquals, assertThrows } from "deno:harness"; +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals, assertThrows } = createDenoTest(import.meta.path); const { inspectArgs } = Deno[Deno.internal]; -Deno.test(function headersHasCorrectNameProp() { +test(function headersHasCorrectNameProp() { assertEquals(Headers.name, "Headers"); }); -Deno.test(function newHeaderTest() { +test(function newHeaderTest() { new Headers(); new Headers(undefined); new Headers({}); @@ -29,48 +31,48 @@ for (const [name, value] of Object.entries(headerDict)){ value ]); } -Deno.test(function newHeaderWithSequence() { +test(function newHeaderWithSequence() { const headers = new Headers(headerSeq); for (const [name, value] of Object.entries(headerDict)){ assertEquals(headers.get(name), String(value)); } assertEquals(headers.get("length"), null); }); -Deno.test(function newHeaderWithRecord() { +test(function newHeaderWithRecord() { const headers = new Headers(headerDict); for (const [name, value] of Object.entries(headerDict)){ assertEquals(headers.get(name), String(value)); } }); -Deno.test(function newHeaderWithHeadersInstance() { +test(function newHeaderWithHeadersInstance() { const headers = new Headers(headerDict); const headers2 = new Headers(headers); for (const [name, value] of Object.entries(headerDict)){ assertEquals(headers2.get(name), String(value)); } }); -Deno.test(function headerAppendSuccess() { +test(function headerAppendSuccess() { const headers = new Headers(); for (const [name, value] of Object.entries(headerDict)){ headers.append(name, value); assertEquals(headers.get(name), String(value)); } }); -Deno.test(function headerSetSuccess() { +test(function headerSetSuccess() { const headers = new Headers(); for (const [name, value] of Object.entries(headerDict)){ headers.set(name, value); assertEquals(headers.get(name), String(value)); } }); -Deno.test(function headerHasSuccess() { +test(function headerHasSuccess() { const headers = new Headers(headerDict); for (const name of Object.keys(headerDict)){ assert(headers.has(name), "headers has name " + name); assert(!headers.has("nameNotInHeaders"), "headers do not have header: nameNotInHeaders"); } }); -Deno.test(function headerDeleteSuccess() { +test(function headerDeleteSuccess() { const headers = new Headers(headerDict); for (const name of Object.keys(headerDict)){ assert(headers.has(name), "headers have a header: " + name); @@ -78,14 +80,14 @@ Deno.test(function headerDeleteSuccess() { assert(!headers.has(name), "headers do not have anymore a header: " + name); } }); -Deno.test(function headerGetSuccess() { +test(function headerGetSuccess() { const headers = new Headers(headerDict); for (const [name, value] of Object.entries(headerDict)){ assertEquals(headers.get(name), String(value)); assertEquals(headers.get("nameNotInHeaders"), null); } }); -Deno.test(function headerEntriesSuccess() { +test(function headerEntriesSuccess() { const headers = new Headers(headerDict); const iterators = headers.entries(); for (const it of iterators){ @@ -95,14 +97,14 @@ Deno.test(function headerEntriesSuccess() { assertEquals(value, headers.get(key)); } }); -Deno.test(function headerKeysSuccess() { +test(function headerKeysSuccess() { const headers = new Headers(headerDict); const iterators = headers.keys(); for (const it of iterators){ assert(headers.has(it)); } }); -Deno.test(function headerValuesSuccess() { +test(function headerValuesSuccess() { const headers = new Headers(headerDict); const iterators = headers.values(); const entries = headers.entries(); @@ -122,7 +124,7 @@ const headerEntriesDict: Record<string, string> = { "Content-Typ": "value5", "Content-Types": "value6" }; -Deno.test(function headerForEachSuccess() { +test(function headerForEachSuccess() { const headers = new Headers(headerEntriesDict); const keys = Object.keys(headerEntriesDict); keys.forEach((key)=>{ @@ -138,7 +140,7 @@ Deno.test(function headerForEachSuccess() { }); assertEquals(callNum, keys.length); }); -Deno.test(function headerSymbolIteratorSuccess() { +test(function headerSymbolIteratorSuccess() { assert(Symbol.iterator in Headers.prototype); const headers = new Headers(headerEntriesDict); for (const header of headers){ @@ -148,14 +150,14 @@ Deno.test(function headerSymbolIteratorSuccess() { assertEquals(value, headers.get(key)); } }); -Deno.test(function headerTypesAvailable() { +test(function headerTypesAvailable() { function newHeaders(): Headers { return new Headers(); } const headers = newHeaders(); assert(headers instanceof Headers); }); -Deno.test(function headerIllegalReject() { +test(function headerIllegalReject() { let errorCount = 0; try { new Headers({ @@ -214,7 +216,7 @@ Deno.test(function headerIllegalReject() { "He-y": "o k" }); }); -Deno.test(function headerParamsShouldThrowTypeError() { +test(function headerParamsShouldThrowTypeError() { let hasThrown = 0; try { new Headers(([ @@ -232,7 +234,7 @@ Deno.test(function headerParamsShouldThrowTypeError() { } assertEquals(hasThrown, 2); }); -Deno.test(function headerParamsArgumentsCheck() { +test(function headerParamsArgumentsCheck() { const methodRequireOneParam = [ "delete", "get", @@ -286,7 +288,7 @@ Deno.test(function headerParamsArgumentsCheck() { assertEquals(hasThrown, 2); }); }); -Deno.test(function headersInitMultiple() { +test(function headersInitMultiple() { const headers = new Headers([ [ "Set-Cookie", @@ -323,7 +325,7 @@ Deno.test(function headersInitMultiple() { ] ]); }); -Deno.test(function headerInitWithPrototypePollution() { +test(function headerInitWithPrototypePollution() { const originalExec = RegExp.prototype.exec; try { RegExp.prototype.exec = ()=>{ @@ -343,7 +345,7 @@ Deno.test(function headerInitWithPrototypePollution() { RegExp.prototype.exec = originalExec; } }); -Deno.test(function headersAppendMultiple() { +test(function headersAppendMultiple() { const headers = new Headers([ [ "Set-Cookie", @@ -374,7 +376,7 @@ Deno.test(function headersAppendMultiple() { ] ]); }); -Deno.test(function headersAppendDuplicateSetCookieKey() { +test(function headersAppendDuplicateSetCookieKey() { const headers = new Headers([ [ "Set-Cookie", @@ -401,7 +403,7 @@ Deno.test(function headersAppendDuplicateSetCookieKey() { ] ]); }); -Deno.test(function headersGetSetCookie() { +test(function headersGetSetCookie() { const headers = new Headers([ [ "Set-Cookie", @@ -414,14 +416,14 @@ Deno.test(function headersGetSetCookie() { ]); assertEquals(headers.get("SET-COOKIE"), "foo=bar, bar=qat"); }); -Deno.test(function toStringShouldBeWebCompatibility() { +test(function toStringShouldBeWebCompatibility() { const headers = new Headers(); assertEquals(headers.toString(), "[object Headers]"); }); function stringify(...args: unknown[]): string { return inspectArgs(args).replace(/\n$/, ""); } -Deno.test.ignore(function customInspectReturnsCorrectHeadersFormat() { +test.ignore(function customInspectReturnsCorrectHeadersFormat() { const blankHeaders = new Headers(); assertEquals(stringify(blankHeaders), "Headers {}"); const singleHeader = new Headers([ @@ -443,7 +445,7 @@ Deno.test.ignore(function customInspectReturnsCorrectHeadersFormat() { ]); assertEquals(stringify(multiParamHeader), `Headers { "content-length": "1337", "content-type": "application/json" }`); }); -Deno.test(function invalidHeadersFlaky() { +test(function invalidHeadersFlaky() { assertThrows(()=>new Headers([ [ "x", diff --git a/test/js/deno/fetch/request.test.ts b/test/js/deno/fetch/request.test.ts index d1a444196..3f182c77c 100644 --- a/test/js/deno/fetch/request.test.ts +++ b/test/js/deno/fetch/request.test.ts @@ -1,7 +1,9 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/request_test.ts -import { assertEquals, assertStringIncludes } from "deno:harness"; -Deno.test(async function fromInit() { +import { createDenoTest } from "deno:harness"; +const { test, assertEquals, assertStringIncludes } = createDenoTest(import.meta.path); +test(async function fromInit() { const req = new Request("http://foo/", { body: "ahoyhoy", method: "POST", @@ -13,7 +15,7 @@ Deno.test(async function fromInit() { assertEquals(req.url, "http://foo/"); assertEquals(req.headers.get("test-header"), "value"); }); -Deno.test(function requestNonString() { +test(function requestNonString() { const nonString = { toString () { return "http://foo/"; @@ -21,15 +23,15 @@ Deno.test(function requestNonString() { }; assertEquals(new Request(nonString).url, "http://foo/"); }); -Deno.test(function methodNonString() { +test(function methodNonString() { assertEquals(new Request("http://foo/", { method: undefined }).method, "GET"); }); -Deno.test.ignore(function requestRelativeUrl() { +test.ignore(function requestRelativeUrl() { assertEquals(new Request("relative-url").url, "http://js-unit-tests/foo/relative-url"); }); -Deno.test(async function cloneRequestBodyStream() { +test(async function cloneRequestBodyStream() { const stream = new Request("http://foo/", { body: "a test body", method: "POST" @@ -43,7 +45,7 @@ Deno.test(async function cloneRequestBodyStream() { const b2 = await r2.text(); assertEquals(b1, b2); }); -Deno.test.ignore(function customInspectFunction() { +test.ignore(function customInspectFunction() { const request = new Request("https://example.com"); assertEquals(Deno.inspect(request), `Request { bodyUsed: false, @@ -54,6 +56,6 @@ Deno.test.ignore(function customInspectFunction() { }`); assertStringIncludes(Deno.inspect(Request.prototype), "Request"); }); -Deno.test(function requestConstructorTakeURLObjectAsParameter() { +test(function requestConstructorTakeURLObjectAsParameter() { assertEquals(new Request(new URL("http://foo/")).url, "http://foo/"); }); diff --git a/test/js/deno/fetch/response.test.ts b/test/js/deno/fetch/response.test.ts index 2e83ed0d8..a8066c75b 100644 --- a/test/js/deno/fetch/response.test.ts +++ b/test/js/deno/fetch/response.test.ts @@ -1,7 +1,9 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/response_test.ts -import { assert, assertEquals, assertStringIncludes, assertThrows } from "deno:harness"; -Deno.test(async function responseText() { +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals, assertStringIncludes, assertThrows } = createDenoTest(import.meta.path); +test(async function responseText() { const response = new Response("hello world"); const textPromise = response.text(); assert(textPromise instanceof Promise); @@ -9,7 +11,7 @@ Deno.test(async function responseText() { assert(typeof text === "string"); assertEquals(text, "hello world"); }); -Deno.test(async function responseArrayBuffer() { +test(async function responseArrayBuffer() { const response = new Response(new Uint8Array([ 1, 2, @@ -25,7 +27,7 @@ Deno.test(async function responseArrayBuffer() { 3 ])); }); -Deno.test(async function responseJson() { +test(async function responseJson() { const response = new Response('{"hello": "world"}'); const jsonPromise = response.json(); assert(jsonPromise instanceof Promise); @@ -35,7 +37,7 @@ Deno.test(async function responseJson() { hello: "world" }); }); -Deno.test(async function responseBlob() { +test(async function responseBlob() { const response = new Response(new Uint8Array([ 1, 2, @@ -52,7 +54,7 @@ Deno.test(async function responseBlob() { 3 ]).buffer); }); -Deno.test(async function responseFormData() { +test(async function responseFormData() { const input = new FormData(); input.append("hello", "world"); const response = new Response(input); @@ -68,7 +70,7 @@ Deno.test(async function responseFormData() { ...input ]); }); -Deno.test(function responseInvalidInit() { +test(function responseInvalidInit() { assertThrows(()=>new Response("", 0)); assertThrows(()=>new Response("", { status: 0 @@ -77,11 +79,11 @@ Deno.test(function responseInvalidInit() { status: null })); }); -Deno.test(function responseNullInit() { +test(function responseNullInit() { const response = new Response("", null); assertEquals(response.status, 200); }); -Deno.test.ignore(function customInspectFunction() { +test.ignore(function customInspectFunction() { const response = new Response(); assertEquals(Deno.inspect(response), `Response { body: null, @@ -95,7 +97,7 @@ Deno.test.ignore(function customInspectFunction() { }`); assertStringIncludes(Deno.inspect(Response.prototype), "Response"); }); -Deno.test(async function responseBodyUsed() { +test(async function responseBodyUsed() { const response = new Response("body"); assert(!response.bodyUsed); await response.text(); diff --git a/test/js/deno/harness.ts b/test/js/deno/harness.ts index 01924758d..22e5f9077 100644 --- a/test/js/deno/harness.ts +++ b/test/js/deno/harness.ts @@ -1,50 +1,415 @@ -export * from "./harness/test.js"; -export * from "./harness/util.js"; -export * from "./harness/assert.js"; -export * from "./harness/fixture.js"; - -import { readTextFile } from "./harness/fixture.js"; -import { callerSourceOrigin } from "bun:jsc"; -import { test } from "./harness/test.js"; +import type { Server } from "bun"; +import { serve, deepEquals, concatArrayBuffers } from "bun"; import { hideFromStackTrace } from "harness"; +import resources from "./resources.json"; -const internalSymbol = Symbol("Deno[internal]"); -class BrokenTest extends Error { - constructor(message) { - super(message); - this.name = "BrokenTest"; - } -} - -hideFromStackTrace(BrokenTest.prototype.constructor); - -const handler = { - get(target: any, prop: string) { - throw new BrokenTest( - "Deno[Deno.internal]." + - String(prop) + - " accessed in " + - callerSourceOrigin() + - ".\n\nThis test should not be included in the test harness. Please skip or remove it from the test runner.", - ); - }, +type Fn = () => void | Promise<unknown>; +type Options = { + permissions?: + | "none" + | { + net?: boolean; + read?: boolean; + }; + ignore?: boolean; }; -hideFromStackTrace(handler.get); +/** + * @example + * const { test, assert } = createDenoTest(import.meta.path); + * test(function testAssert() { + * assert(true); + * }); + */ +export function createDenoTest(path: string) { + const { expect, test, beforeAll, afterAll } = Bun.jest(path); -export const Deno = { - test, - readTextFile, - internal: internalSymbol, - [internalSymbol]: new Proxy({}, handler), -}; + let server: Server; -// @ts-expect-error -globalThis["Deno"] = Deno; + beforeAll(() => { + server = serve({ + port: 4545, + fetch(request: Request): Response { + const { url } = request; + const { pathname, search } = new URL(url); + if (pathname === "/echo_server") { + return new Response(request.body, request); + } + const target = new URL(`${pathname}${search}`, resources.baseUrl); + return Response.redirect(target.toString()); + }, + }); + }); -export const window = { - crypto: crypto, -}; + afterAll(() => { + if (server) { + server.stop(true); + } + }); + + // https://deno.land/api@v1.31.2?s=Deno.test + + const denoTest = (arg0: Fn | Options, arg1?: Fn) => { + if (typeof arg0 === "function") { + test(arg0.name, arg0); + } else if (typeof arg1 === "function") { + if ( + arg0?.ignore === true || + arg0?.permissions === "none" || + arg0?.permissions?.net === false || + arg0?.permissions?.read === false + ) { + test.skip(arg1.name, arg1); + } else { + test(arg1.name, arg1); + } + } else { + unimplemented(`test(${typeof arg0}, ${typeof arg1})`); + } + }; + + denoTest.ignore = (arg0: Fn | Options, arg1?: Fn) => { + if (typeof arg0 === "function") { + test.skip(arg0.name, arg0); + } else if (typeof arg1 === "function") { + test.skip(arg1.name, arg1); + } else { + unimplemented(`test.ignore(${typeof arg0}, ${typeof arg1})`); + } + }; + + // Deno's assertions implemented using expect(). + // https://github.com/denoland/deno/blob/main/cli/tests/unit/test_util.ts + + const assert = (condition: unknown, message?: string) => { + if (message) { + test(message, () => assert(condition)); + } else { + expect(condition).toBeTruthy(); + } + }; + + const assertFalse = (condition: unknown, message?: string) => { + if (message) { + test(message, () => assertFalse(condition)); + } else { + expect(condition).toBeFalsy(); + } + }; + + const assertEquals = (actual: unknown, expected: unknown, message?: string) => { + if (message) { + test(message, () => assertEquals(actual, expected)); + } else { + expect(actual).toEqual(expected); + } + }; + + const assertExists = (value: unknown, message?: string) => { + if (message) { + test(message, () => assertExists(value)); + } else { + expect(value).toBeDefined(); + } + }; + + const assertNotEquals = (actual: unknown, expected: unknown, message?: string) => { + if (message) { + test(message, () => assertNotEquals(actual, expected)); + } else { + expect(actual).not.toEqual(expected); + } + }; + + const assertStrictEquals = (actual: unknown, expected: unknown, message?: string) => { + if (message) { + test(message, () => assertStrictEquals(actual, expected)); + } else { + expect(actual).toStrictEqual(expected); + } + }; + + const assertNotStrictEquals = (actual: unknown, expected: unknown, message?: string) => { + if (message) { + test(message, () => assertNotStrictEquals(actual, expected)); + } else { + expect(actual).not.toStrictEqual(expected); + } + }; + + const assertAlmostEquals = (actual: unknown, expected: number, epsilon: number = 1e-7, message?: string) => { + if (message) { + test(message, () => assertAlmostEquals(actual, expected)); + } else if (typeof actual === "number") { + // TODO: toBeCloseTo() + expect(Math.abs(actual - expected)).toBeLessThanOrEqual(epsilon); + } else { + expect(typeof actual).toBe("number"); + } + }; + + const assertInstanceOf = (actual: unknown, expected: unknown, message?: string) => { + if (message) { + test(message, () => assertInstanceOf(actual, expected)); + } else { + expect(actual).toBeInstanceOf(expected); + } + }; + + const assertNotInstanceOf = (actual: unknown, expected: unknown, message?: string) => { + if (message) { + test(message, () => assertNotInstanceOf(actual, expected)); + } else if (typeof actual === "object") { + if (actual !== null) { + expect(actual).not.toHaveProperty("constructor", expected); + } else { + expect(actual).not.toBeNull(); + } + } else { + expect(typeof actual).toBe("object"); + } + }; + + const assertStringIncludes = (actual: unknown, expected: string, message?: string) => { + if (message) { + test(message, () => assertStringIncludes(actual, expected)); + } else if (typeof actual === "string") { + expect(actual).toContain(expected); + } else { + expect(typeof actual).toBe("string"); + } + }; + + const assertArrayIncludes = (actual: unknown, expected: unknown[], message?: string) => { + if (message) { + test(message, () => assertArrayIncludes(actual, expected)); + } else if (Array.isArray(actual)) { + for (const value of expected) { + expect(actual).toContain(value); + } + } else { + expect(Array.isArray(actual)).toBe(true); + } + }; + + const assertMatch = (actual: unknown, expected: RegExp, message?: string) => { + if (message) { + test(message, () => assertMatch(actual, expected)); + } else if (typeof actual === "string") { + expect(expected.test(actual)).toBe(true); + } else { + expect(typeof actual).toBe("string"); + } + }; + + const assertNotMatch = (actual: unknown, expected: RegExp, message?: string) => { + if (message) { + test(message, () => assertNotMatch(actual, expected)); + } else if (typeof actual === "string") { + expect(expected.test(actual)).toBe(false); + } else { + expect(typeof actual).toBe("string"); + } + }; + + const assertObjectMatch = (actual: unknown, expected: Record<PropertyKey, unknown>, message?: string) => { + if (message) { + test(message, () => assertObjectMatch(actual, expected)); + } else if (typeof actual === "object") { + // TODO: toMatchObject() + if (actual !== null) { + const expectedKeys = Object.keys(expected); + for (const key of Object.keys(actual)) { + if (!expectedKeys.includes(key)) { + // @ts-ignore + delete actual[key]; + } + } + expect(actual).toEqual(expected); + } else { + expect(actual).not.toBeNull(); + } + } else { + expect(typeof actual).toBe("object"); + } + }; + + const assertThrows = (fn: () => void, message?: string) => { + if (message) { + test(message, () => assertThrows(fn)); + } else { + try { + fn(); + } catch (error) { + expect(error).toBeDefined(); + return; + } + throw new Error("Expected an error to be thrown"); + } + }; -// @ts-expect-error -globalThis["window"] = window; + const assertRejects = async (fn: () => Promise<unknown>, message?: string) => { + if (message) { + test(message, () => assertRejects(fn)); + } else { + try { + await fn(); + } catch (error) { + expect(error).toBeDefined(); + return; + } + throw new Error("Expected an error to be thrown"); + } + }; + + const equal = (a: unknown, b: unknown) => { + return deepEquals(a, b); + }; + + const fail = (message: string): never => { + throw new Error(message); + }; + + const unimplemented = (message: string): never => { + throw new Error(`Unimplemented: ${message}`); + }; + + const unreachable = (): never => { + throw new Error("Unreachable"); + }; + + // Copyright 2018+ the Deno authors. All rights reserved. MIT license. + // https://github.com/denoland/deno/blob/main/ext/node/polyfills/_util/async.ts + + const deferred = () => { + let methods; + let state = "pending"; + const promise = new Promise((resolve, reject) => { + methods = { + async resolve(value: unknown) { + await value; + state = "fulfilled"; + resolve(value); + }, + reject(reason?: unknown) { + state = "rejected"; + reject(reason); + }, + }; + }); + Object.defineProperty(promise, "state", { get: () => state }); + return Object.assign(promise, methods); + }; + + const delay = async (ms: number, options: { signal?: AbortSignal } = {}) => { + const { signal } = options; + if (signal?.aborted) { + return Promise.reject(new DOMException("Delay was aborted.", "AbortError")); + } + return new Promise<void>((resolve, reject) => { + const abort = () => { + clearTimeout(i); + reject(new DOMException("Delay was aborted.", "AbortError")); + }; + const done = () => { + signal?.removeEventListener("abort", abort); + resolve(); + }; + const i = setTimeout(done, ms); + signal?.addEventListener("abort", abort, { once: true }); + }); + }; + + // https://deno.land/std@0.171.0/bytes/concat.ts + + const concat = (...buffers: Uint8Array[]): Uint8Array => { + return new Uint8Array(concatArrayBuffers(buffers)); + }; + + // https://deno.land/api@v1.31.1?s=Deno.readTextFile + + const readTextFile = async (path: string): Promise<string> => { + const url = new URL(path, resources.baseUrl); + const response = await fetch(url); + if (!response.ok) { + throw new Error(`${response.status}: ${response.url}`); + } + return response.text(); + }; + + // Globals + + const window = { + crypto, + }; + + // @ts-ignore + globalThis.window = window; + + const internal = Symbol("Deno[internal]"); + const mockInternal = { + get(target: unknown, property: unknown) { + if (property === "inspectArgs") { + return {}; + } + throw new Error(`Deno[Deno.internal].${property}`); + }, + }; + hideFromStackTrace(mockInternal.get); + + const mockInspect = () => { + throw new Error("Deno.inspect()"); + }; + hideFromStackTrace(mockInspect); + + const Deno = { + test: denoTest, + readTextFile, + internal, + [internal]: new Proxy({}, mockInternal), + inspect: mockInspect, + }; + + // @ts-ignore + globalThis.Deno = Deno; + + const exports = { + test: denoTest, + assert, + assertFalse, + assertEquals, + assertExists, + assertNotEquals, + assertStrictEquals, + assertNotStrictEquals, + assertAlmostEquals, + assertInstanceOf, + assertNotInstanceOf, + assertStringIncludes, + assertArrayIncludes, + assertMatch, + assertNotMatch, + assertObjectMatch, + assertThrows, + assertRejects, + equal, + fail, + unimplemented, + unreachable, + deferred, + delay, + concat, + }; + + for (const property of [...Object.values(exports), ...Object.values(Deno)]) { + if (typeof property === "function") { + hideFromStackTrace(property); + } + } + + return exports; +} + +declare namespace Bun { + function jest(path: string): typeof import("bun:test"); +} diff --git a/test/js/deno/harness/assert.ts b/test/js/deno/harness/assert.ts deleted file mode 100644 index ba3570115..000000000 --- a/test/js/deno/harness/assert.ts +++ /dev/null @@ -1,207 +0,0 @@ -// Deno's test assertions implemented using expect(). -// https://github.com/denoland/deno/blob/main/cli/tests/unit/test_util.ts - -import { test, expect } from "bun:test"; - -export function assert(condition: unknown, message?: string): asserts condition is true { - if (message) { - test(message, () => assert(condition)); - } else { - expect(condition).toBeTruthy(); - } -} - -export function assertFalse(condition: unknown, message?: string): asserts condition is false { - if (message) { - test(message, () => assertFalse(condition)); - } else { - expect(condition).toBeFalsy(); - } -} - -export function assertEquals(actual: unknown, expected: unknown, message?: string): void { - if (message) { - test(message, () => assertEquals(actual, expected)); - } else { - expect(actual).toEqual(expected); - } -} - -export function assertExists(value: unknown, message?: string): void { - if (message) { - test(message, () => assertExists(value)); - } else { - expect(value).toBeDefined(); - } -} - -export function assertNotEquals(actual: unknown, expected: unknown, message?: string): void { - if (message) { - test(message, () => assertNotEquals(actual, expected)); - } else { - expect(actual).not.toEqual(expected); - } -} - -export function assertStrictEquals(actual: unknown, expected: unknown, message?: string): void { - if (message) { - test(message, () => assertStrictEquals(actual, expected)); - } else { - expect(actual).toStrictEqual(expected); - } -} - -export function assertNotStrictEquals(actual: unknown, expected: unknown, message?: string): void { - if (message) { - test(message, () => assertNotStrictEquals(actual, expected)); - } else { - expect(actual).not.toStrictEqual(expected); - } -} - -export function assertAlmostEquals(actual: unknown, expected: number, epsilon: number = 1e-7, message?: string): void { - if (message) { - test(message, () => assertAlmostEquals(actual, expected)); - } else if (typeof actual === "number") { - // TODO: toBeCloseTo() - expect(Math.abs(actual - expected)).toBeLessThanOrEqual(epsilon); - } else { - expect(typeof actual).toBe("number"); - } -} - -export function assertInstanceOf(actual: unknown, expected: unknown, message?: string): void { - if (message) { - test(message, () => assertInstanceOf(actual, expected)); - } else if (typeof actual === "object") { - if (actual !== null) { - expect(actual).toHaveProperty("constructor", expected); - } else { - expect(actual).not.toBeNull(); - } - } else { - expect(typeof actual).toBe("object"); - } -} - -export function assertNotInstanceOf(actual: unknown, expected: unknown, message?: string): void { - if (message) { - test(message, () => assertNotInstanceOf(actual, expected)); - } else if (typeof actual === "object") { - if (actual !== null) { - expect(actual).not.toHaveProperty("constructor", expected); - } else { - expect(actual).not.toBeNull(); - } - } else { - expect(typeof actual).toBe("object"); - } -} - -export function assertStringIncludes(actual: unknown, expected: string, message?: string): void { - if (message) { - test(message, () => assertStringIncludes(actual, expected)); - } else if (typeof actual === "string") { - expect(actual).toContain(expected); - } else { - expect(typeof actual).toBe("string"); - } -} - -export function assertArrayIncludes(actual: unknown, expected: unknown[], message?: string): void { - if (message) { - test(message, () => assertArrayIncludes(actual, expected)); - } else if (Array.isArray(actual)) { - for (const value of expected) { - expect(actual).toContain(value); - } - } else { - expect(Array.isArray(actual)).toBe(true); - } -} - -export function assertMatch(actual: unknown, expected: RegExp, message?: string): void { - if (message) { - test(message, () => assertMatch(actual, expected)); - } else if (typeof actual === "string") { - expect(expected.test(actual)).toBe(true); - } else { - expect(typeof actual).toBe("string"); - } -} - -export function assertNotMatch(actual: unknown, expected: RegExp, message?: string): void { - if (message) { - test(message, () => assertNotMatch(actual, expected)); - } else if (typeof actual === "string") { - expect(expected.test(actual)).toBe(false); - } else { - expect(typeof actual).toBe("string"); - } -} - -export function assertObjectMatch(actual: unknown, expected: Record<PropertyKey, unknown>, message?: string): void { - if (message) { - test(message, () => assertObjectMatch(actual, expected)); - } else if (typeof actual === "object") { - // TODO: toMatchObject() - if (actual !== null) { - const expectedKeys = Object.keys(expected); - for (const key of Object.keys(actual)) { - if (!expectedKeys.includes(key)) { - // @ts-ignore - delete actual[key]; - } - } - expect(actual).toEqual(expected); - } else { - expect(actual).not.toBeNull(); - } - } else { - expect(typeof actual).toBe("object"); - } -} - -export function assertThrows(fn: () => void, message?: string): void { - if (message) { - test(message, () => assertThrows(fn)); - } else { - try { - fn(); - } catch (error) { - expect(error).toBeDefined(); - return; - } - throw new Error("Expected an error to be thrown"); - } -} - -export async function assertRejects(fn: () => Promise<unknown>, message?: string): Promise<void> { - if (message) { - test(message, () => assertRejects(fn)); - } else { - try { - await fn(); - } catch (error) { - expect(error).toBeDefined(); - return; - } - throw new Error("Expected an error to be thrown"); - } -} - -export function equal(a: unknown, b: unknown): boolean { - return Bun.deepEquals(a, b); -} - -export function fail(message: string): never { - throw new Error(message); -} - -export function unimplemented(message: string): never { - throw new Error(`Unimplemented: ${message}`); -} - -export function unreachable(): never { - throw new Error("Unreachable"); -} diff --git a/test/js/deno/harness/fixture.ts b/test/js/deno/harness/fixture.ts deleted file mode 100644 index 6917fc893..000000000 --- a/test/js/deno/harness/fixture.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { Server } from "bun"; -import { serve } from "bun"; -import { afterAll, beforeAll } from "bun:test"; -import baseUrl from "../resources/url.json"; - -let server: Server; - -beforeAll(() => { - server = serve({ - port: 4545, - fetch(request: Request): Response { - const { url } = request; - const { pathname, search } = new URL(url); - if (pathname === "/echo_server") { - return new Response(request.body, request); - } - const redirect = new URL(`${pathname}?${search}`, baseUrl); - return Response.redirect(redirect.toString()); - }, - }); -}); - -afterAll(() => { - if (server) { - server.stop(true); - } -}); - -export async function readTextFile(path: string): Promise<string> { - const url = new URL(path, baseUrl); - const response = await fetch(url); - if (response.ok) { - return response.text(); - } - throw new Error(`${response.status}: ${response.url}`); -} diff --git a/test/js/deno/harness/test.ts b/test/js/deno/harness/test.ts deleted file mode 100644 index cbe73c52d..000000000 --- a/test/js/deno/harness/test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { test as bunTest } from "bun:test"; - -type Fn = () => void | Promise<unknown>; -type Options = { - permissions?: - | "none" - | { - net?: boolean; - read?: boolean; - }; - ignore?: boolean; -}; - -export function test(arg0: Fn | Options, arg1?: Fn): void { - if (typeof arg0 === "function") { - bunTest(arg0.name, arg0); - } else if (typeof arg1 === "function") { - if ( - arg0?.ignore === true || - arg0?.permissions === "none" || - arg0?.permissions?.net === false || - arg0?.permissions?.read === false - ) { - bunTest.skip(arg1.name, arg1); - } else { - bunTest(arg1.name, arg1); - } - } else { - throw new Error("Unimplemented"); - } -} - -test.ignore = (arg0: Fn | Options, arg1?: Fn) => { - if (typeof arg0 === "function") { - bunTest.skip(arg0.name, arg0); - } else if (typeof arg1 === "function") { - bunTest.skip(arg1.name, arg1); - } else { - throw new Error("Unimplemented"); - } -}; diff --git a/test/js/deno/harness/util.ts b/test/js/deno/harness/util.ts deleted file mode 100644 index 422d6b34c..000000000 --- a/test/js/deno/harness/util.ts +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2018+ the Deno authors. All rights reserved. MIT license. -// https://github.com/denoland/deno/blob/main/ext/node/polyfills/_util/async.ts - -import { concatArrayBuffers } from "bun"; - -export function concat(...buffers: Uint8Array[]): Uint8Array { - return new Uint8Array(concatArrayBuffers(buffers)); -} - -export function deferred<T>() { - let methods; - let state = "pending"; - const promise = new Promise<T>((resolve, reject) => { - methods = { - async resolve(value: T | PromiseLike<T>) { - await value; - state = "fulfilled"; - resolve(value); - }, - reject(reason?: any) { - state = "rejected"; - reject(reason); - }, - }; - }); - Object.defineProperty(promise, "state", { get: () => state }); - return Object.assign(promise, methods); -} - -export function delay(ms: number, options: { signal?: AbortSignal } = {}): Promise<void> { - const { signal } = options; - if (signal?.aborted) { - return Promise.reject(new DOMException("Delay was aborted.", "AbortError")); - } - return new Promise((resolve, reject) => { - const abort = () => { - clearTimeout(i); - reject(new DOMException("Delay was aborted.", "AbortError")); - }; - const done = () => { - signal?.removeEventListener("abort", abort); - resolve(); - }; - const i = setTimeout(done, ms); - signal?.addEventListener("abort", abort, { once: true }); - }); -} diff --git a/test/js/deno/resources.json b/test/js/deno/resources.json new file mode 100644 index 000000000..fdb48acfa --- /dev/null +++ b/test/js/deno/resources.json @@ -0,0 +1,98 @@ +{ + "baseUrl": "https://raw.githubusercontent.com/denoland/deno/main/", + "imports": { + "test_util.ts": "deno:harness", + "test_util/std/bytes/concat.ts": "deno:harness", + "test_util/std/io/buffer.ts": "deno:harness" + }, + "tests": [ + { + "path": "abort/abort-controller.test.ts", + "remotePath": "cli/tests/unit/abort_controller_test.ts" + }, + { + "path": "url/url.test.ts", + "remotePath": "cli/tests/unit/url_test.ts", + "skipTests": ["customInspectFunction"] + }, + { + "path": "url/urlsearchparams.test.ts", + "remotePath": "cli/tests/unit/url_search_params_test.ts" + }, + { + "path": "event/event.test.ts", + "remotePath": "cli/tests/unit/event_test.ts", + "skipTests": [ + "eventInspectOutput", + "inspectEvent" + ] + }, + { + "path": "event/event-target.test.ts", + "remotePath": "cli/tests/unit/event_target_test.ts", + "skipTests": [ + "eventTargetThisShouldDefaultToWindow" + ] + }, + { + "path": "event/custom-event.test.ts", + "remotePath": "cli/tests/unit/custom_event_test.ts" + }, + { + "path": "fetch/body.test.ts", + "remotePath": "cli/tests/unit/body_test.ts" + }, + { + "path": "fetch/blob.test.ts", + "remotePath": "cli/tests/unit/blob_test.ts", + "skipTests": ["blobCustomInspectFunction"] + }, + { + "path": "fetch/file.test.ts", + "remotePath": "cli/tests/unit/file_test.ts", + "skip": true + }, + { + "path": "fetch/headers.test.ts", + "remotePath": "cli/tests/unit/headers_test.ts", + "skipTests": ["customInspectReturnsCorrectHeadersFormat"] + }, + { + "path": "fetch/request.test.ts", + "remotePath": "cli/tests/unit/request_test.ts", + "skipTests": [ + "customInspectFunction", + "requestRelativeUrl" + ] + }, + { + "path": "fetch/response.test.ts", + "remotePath": "cli/tests/unit/response_test.ts", + "skipTests": ["customInspectFunction"] + }, + { + "path": "crypto/random.test.ts", + "remotePath": "cli/tests/unit/get_random_values_test.ts" + }, + { + "path": "crypto/webcrypto.test.ts", + "remotePath": "cli/tests/unit/webcrypto_test.ts", + "skipTests": [ + "testUnwrapKey", + "testAesKeyGen" + ] + }, + { + "path": "encoding/encoding.test.ts", + "remotePath": "cli/tests/unit/text_encoding_test.ts", + "skipTests": [ + "textDecoderErrorEncoding", + "binaryEncode" + ] + }, + { + "path": "v8/error.test.ts", + "remotePath": "cli/tests/unit/error_stack_test.ts" + } + ] +} diff --git a/test/js/deno/resources/imports.json b/test/js/deno/resources/imports.json deleted file mode 100644 index 182555661..000000000 --- a/test/js/deno/resources/imports.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - "test_util.ts", - "test_util/std/bytes/concat.ts", - "test_util/std/io/buffer.ts" -] diff --git a/test/js/deno/resources/tests.json b/test/js/deno/resources/tests.json deleted file mode 100644 index b74d6b3d6..000000000 --- a/test/js/deno/resources/tests.json +++ /dev/null @@ -1,86 +0,0 @@ -[ - { - "path": "abort/abort-controller.test.ts", - "remotePath": "cli/tests/unit/abort_controller_test.ts" - }, - { - "path": "url/url.test.ts", - "remotePath": "cli/tests/unit/url_test.ts", - "skip": ["customInspectFunction"] - }, - { - "path": "url/urlsearchparams.test.ts", - "remotePath": "cli/tests/unit/url_search_params_test.ts" - }, - { - "path": "event/event.test.ts", - "remotePath": "cli/tests/unit/event_test.ts" - }, - { - "path": "event/event-target.test.ts", - "remotePath": "cli/tests/unit/event_target_test.ts", - "skip": [ - "eventTargetThisShouldDefaultToWindow" - ] - }, - { - "path": "event/custom-event.test.ts", - "remotePath": "cli/tests/unit/custom_event_test.ts" - }, - { - "path": "fetch/body.test.ts", - "remotePath": "cli/tests/unit/body_test.ts" - }, - { - "path": "fetch/blob.test.ts", - "remotePath": "cli/tests/unit/blob_test.ts", - "skip": ["blobCustomInspectFunction"] - }, - { - "path": "fetch/file.test.ts", - "remotePath": "cli/tests/unit/file_test.ts", - "skip": true - }, - { - "path": "fetch/headers.test.ts", - "remotePath": "cli/tests/unit/headers_test.ts", - "skip": ["customInspectReturnsCorrectHeadersFormat"] - }, - { - "path": "fetch/request.test.ts", - "remotePath": "cli/tests/unit/request_test.ts", - "skip": [ - "customInspectFunction", - "requestRelativeUrl" - ] - }, - { - "path": "fetch/response.test.ts", - "remotePath": "cli/tests/unit/response_test.ts", - "skip": ["customInspectFunction"] - }, - { - "path": "crypto/random.test.ts", - "remotePath": "cli/tests/unit/get_random_values_test.ts" - }, - { - "path": "crypto/webcrypto.test.ts", - "remotePath": "cli/tests/unit/webcrypto_test.ts", - "skip": [ - "testUnwrapKey", - "testAesKeyGen" - ] - }, - { - "path": "encoding/encoding.test.ts", - "remotePath": "cli/tests/unit/text_encoding_test.ts", - "skip": [ - "textDecoderErrorEncoding", - "binaryEncode" - ] - }, - { - "path": "v8/error.test.ts", - "remotePath": "cli/tests/unit/error_stack_test.ts" - } -] diff --git a/test/js/deno/resources/url.json b/test/js/deno/resources/url.json deleted file mode 100644 index 348c6daf7..000000000 --- a/test/js/deno/resources/url.json +++ /dev/null @@ -1 +0,0 @@ -"https://raw.githubusercontent.com/denoland/deno/main/" diff --git a/test/js/deno/scripts/generate.ts b/test/js/deno/scripts/generate.ts new file mode 100644 index 000000000..c6cf814c7 --- /dev/null +++ b/test/js/deno/scripts/generate.ts @@ -0,0 +1,139 @@ +// Downloads tests from Deno and does AST transformation to convert APIs +// like Deno.test() to use Bun's test() and expect() APIs. + +import { mkdirSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { parse, print } from "@swc/core"; +import type { ImportDeclaration, ExpressionStatement, CallExpression } from "@swc/core"; +import resources from "../resources.json"; + +type Test = { + path: string; + remotePath: string; + skip?: boolean; + skipTests?: string[]; +}; + +type ParsedTest = Test & { + src: string; + testCount: number; + tests: string[]; +}; + +async function downloadTest(test: Test): Promise<ParsedTest> { + const path = join(import.meta.dir, "..", test.path); + const url = new URL(test.remotePath, resources.baseUrl); + const response = await fetch(url); + if (!response.ok) { + throw new Error(`${response.status}: ${url}`); + } + const src = await response.text(); + if (test.skip) { + return { + ...test, + tests: [], + testCount: 0, + src, + }; + } + const headers = [ + "// GENERATED - DO NOT EDIT", + "// Copyright 2018+ the Deno authors. All rights reserved. MIT license.", + `// ${url}`, + `import { createDenoTest } from "deno:harness";`, + ]; + const ast = await parse(src, { + syntax: "typescript", + target: "esnext", + dynamicImport: true, + }); + let tests: string[] = []; + const harness = new Set(["test"]); + for (const item of ast.body) { + if (item.type === "ImportDeclaration") { + const found = visitImport(item); + if (found?.path === "deno:harness") { + ast.body = ast.body.filter(i => i !== item); + for (const specifier of found.specifiers) { + harness.add(specifier); + } + } else if (found) { + item.source.raw = `"${found.path}"`; + } + } + if (item.type === "ExpressionStatement") { + for (const name of visitExpression(item, test)) { + tests.push(name); + } + } + } + headers.push(`const { ${Array.from(harness).join(", ")} } = createDenoTest(import.meta.path);`); + const { code } = await print(ast, { + isModule: true, + }); + const dst = [...headers, code].join("\n"); + try { + mkdirSync(dirname(path)); + } catch {} + await Bun.write(path, dst); + return { + ...test, + tests, + testCount: tests.length, + src: dst, + }; +} + +type Import = { + path: string; + specifiers: string[]; +}; + +function visitImport(item: ImportDeclaration): Import | null { + const src = item.source.value; + let dst = ""; + for (const [from, to] of Object.entries(resources.imports)) { + if (src.endsWith(from)) { + dst = to; + break; + } + } + if (!dst) { + console.warn("Unknown import:", dst); + return null; + } + return { + path: dst, + specifiers: item.specifiers.map(specifier => specifier.local.value), + }; +} + +function* visitExpression(item: ExpressionStatement, test: Test): Generator<string> { + if ( + item.expression.type === "CallExpression" && + item.expression.callee.type === "MemberExpression" && + item.expression.callee.object.type === "Identifier" && + item.expression.callee.object.value === "Deno" + ) { + if (item.expression.callee.property.type === "Identifier" && item.expression.callee.property.value === "test") { + yield* visitTest(item.expression, test); + item.expression.callee = item.expression.callee.property; + } + } +} + +function* visitTest(item: CallExpression, test: Test): Generator<string> { + for (const argument of item.arguments) { + if (argument.expression.type === "FunctionExpression") { + const fn = argument.expression.identifier?.value; + if (fn && test.skipTests && test.skipTests.includes(fn)) { + // @ts-ignore + item.callee.property.value = "test.ignore"; + } + } + } +} + +for (const test of resources.tests) { + await downloadTest(test); +} diff --git a/test/js/deno/scripts/postinstall.ts b/test/js/deno/scripts/postinstall.ts deleted file mode 100644 index 624fb9fad..000000000 --- a/test/js/deno/scripts/postinstall.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { mkdirSync } from "node:fs"; -import { join, dirname } from "node:path"; -import { parse, print } from "@swc/core"; -import type { ImportDeclaration, ExpressionStatement, CallExpression } from "@swc/core"; -import imports from "../resources/imports.json"; -import tests from "../resources/tests.json"; -import baseUrl from "../resources/url.json"; - -// FIXME: https://github.com/oven-sh/bun/issues/2350 -// import * as harness from "deno:harness"; - -for (const test of tests) { - if (test.skip) { - continue; - } - const path = join(import.meta.dir, "..", test.path); - const url = new URL(test.remotePath, baseUrl); - const response = await fetch(url); - console.log(response.status, url.toString(), "->", test.path); - if (!response.ok) { - continue; - } - const src = await response.text(); - const dst = await visit(src, test); - try { - mkdirSync(dirname(path)); - } catch {} - await Bun.write(path.replace(".test.", ".deno."), src); - await Bun.write(path, dst); -} - -async function visit(src: string, test: any): Promise<string> { - const ast = await parse(src, { - syntax: "typescript", - target: "esnext", - dynamicImport: true, - }); - for (const item of ast.body) { - if (item.type === "ImportDeclaration") { - visitImport(item); - } - if (item.type === "ExpressionStatement") { - visitExpression(item); - } - } - const url = new URL(test.remotePath, baseUrl); - const header = `// Copyright 2018+ the Deno authors. All rights reserved. MIT license.\n// ${url}\n`; - const { code } = await print(ast, { - isModule: true, - }); - return header + code; -} - -function visitImport(item: ImportDeclaration): void { - const src = item.source.value; - let match = false; - for (const name of imports) { - if (src.endsWith(name)) { - match = true; - break; - } - } - if (!match) { - console.warn("Unknown import:", src); - return; - } - item.source.raw = '"deno:harness"'; - // FIXME: https://github.com/oven-sh/bun/issues/2350 - /*let missing = []; - for (const specifier of item.specifiers) { - const name = specifier.local.value; - if (!(name in harness)) { - missing.push(name); - } - } - if (missing.length) { - console.warn("Harness does not contain exports:", missing); - }*/ -} - -function visitExpression(item: ExpressionStatement): void { - if ( - item.expression.type === "CallExpression" && - item.expression.callee.type === "MemberExpression" && - item.expression.callee.object.type === "Identifier" && - item.expression.callee.object.value === "Deno" - ) { - if (item.expression.callee.property.type === "Identifier" && item.expression.callee.property.value === "test") { - visitTest(item.expression); - } - } -} - -function visitTest(item: CallExpression): void { - for (const argument of item.arguments) { - if (argument.expression.type === "FunctionExpression") { - const fn = argument.expression.identifier?.value; - if (fn) { - const pattern = new RegExp(tests.flatMap(test => test.skip ?? []).join("|"), "i"); - if (pattern.test(fn)) { - // @ts-ignore - item.callee.property.value = "test.ignore"; - } - } - } - } -} diff --git a/test/js/deno/url/url.test.ts b/test/js/deno/url/url.test.ts index 66d6e853d..3c6061346 100644 --- a/test/js/deno/url/url.test.ts +++ b/test/js/deno/url/url.test.ts @@ -1,7 +1,9 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/url_test.ts -import { assert, assertEquals, assertStrictEquals, assertThrows } from "deno:harness"; -Deno.test(function urlParsing() { +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals, assertStrictEquals, assertThrows } = createDenoTest(import.meta.path); +test(function urlParsing() { const url = new URL("https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"); assertEquals(url.hash, "#qat"); assertEquals(url.host, "baz.qat:8000"); @@ -22,7 +24,7 @@ Deno.test(function urlParsing() { assertEquals(url.username, "foo"); assertEquals(String(url), "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"); }); -Deno.test(function urlProtocolParsing() { +test(function urlProtocolParsing() { assertEquals(new URL("Aa+-.1://foo").protocol, "aa+-.1:"); assertEquals(new URL("aA+-.1://foo").protocol, "aa+-.1:"); assertThrows(()=>new URL("1://foo"), TypeError, "Invalid URL: '1://foo'"); @@ -40,7 +42,7 @@ Deno.test(function urlProtocolParsing() { assertThrows(()=>new URL("*://foo"), TypeError, "Invalid URL: '*://foo'"); assertThrows(()=>new URL("!:", "*://foo"), TypeError, "Invalid URL: '!:' with base '*://foo'"); }); -Deno.test(function urlAuthenticationParsing() { +test(function urlAuthenticationParsing() { const specialUrl = new URL("http://foo:bar@baz"); assertEquals(specialUrl.username, "foo"); assertEquals(specialUrl.password, "bar"); @@ -51,7 +53,7 @@ Deno.test(function urlAuthenticationParsing() { assertEquals(nonSpecialUrl.password, "bar"); assertEquals(nonSpecialUrl.hostname, "baz"); }); -Deno.test(function urlHostnameParsing() { +test(function urlHostnameParsing() { assertEquals(new URL("http://[::1]").hostname, "[::1]"); assertEquals(new URL("file://[::1]").hostname, "[::1]"); assertEquals(new URL("abcd://[::1]").hostname, "[::1]"); @@ -83,7 +85,7 @@ Deno.test(function urlHostnameParsing() { assertEquals(new URL("http://4294967295").hostname, "255.255.255.255"); assertThrows(()=>new URL("http://4294967296"), TypeError, "Invalid URL"); }); -Deno.test(function urlPortParsing() { +test(function urlPortParsing() { const specialUrl = new URL("http://foo:8000"); assertEquals(specialUrl.hostname, "foo"); assertEquals(specialUrl.port, "8000"); @@ -92,7 +94,7 @@ Deno.test(function urlPortParsing() { assertEquals(nonSpecialUrl.hostname, "foo"); assertEquals(nonSpecialUrl.port, "8000"); }); -Deno.test(function urlModifications() { +test(function urlModifications() { const url = new URL("https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"); url.hash = ""; assertEquals(url.href, "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12"); @@ -123,7 +125,7 @@ Deno.test(function urlModifications() { url.searchParams.append("foo", "bar"); assertEquals(url.href, "http://foo%40bar:qux@foo.bar/foo/bar%qat?bar=qat&foo=bar"); }); -Deno.test(function urlModifyHref() { +test(function urlModifyHref() { const url = new URL("http://example.com/"); url.href = "https://foo:bar@example.com:8080/baz/qat#qux"; assertEquals(url.protocol, "https:"); @@ -134,12 +136,12 @@ Deno.test(function urlModifyHref() { assertEquals(url.pathname, "/baz/qat"); assertEquals(url.hash, "#qux"); }); -Deno.test(function urlNormalize() { +test(function urlNormalize() { const url = new URL("http://example.com"); assertEquals(url.pathname, "/"); assertEquals(url.href, "http://example.com/"); }); -Deno.test(function urlModifyPathname() { +test(function urlModifyPathname() { const url = new URL("http://foo.bar/baz%qat/qux%quux"); assertEquals(url.pathname, "/baz%qat/qux%quux"); url.pathname = url.pathname; @@ -151,24 +153,24 @@ Deno.test(function urlModifyPathname() { url.pathname = "\\a\\b\\c"; assertEquals(url.pathname, "/a/b/c"); }); -Deno.test(function urlModifyHash() { +test(function urlModifyHash() { const url = new URL("http://foo.bar"); url.hash = "%foo bar/qat%qux#bar"; assertEquals(url.hash, "#%foo%20bar/qat%qux#bar"); url.hash = url.hash; assertEquals(url.hash, "#%foo%20bar/qat%qux#bar"); }); -Deno.test(function urlSearchParamsReuse() { +test(function urlSearchParamsReuse() { const url = new URL("https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"); const sp = url.searchParams; url.host = "baz.qat"; assert(sp === url.searchParams, "Search params should be reused."); }); -Deno.test(function urlBackSlashes() { +test(function urlBackSlashes() { const url = new URL("https:\\\\foo:bar@baz.qat:8000\\qux\\quux?foo=bar&baz=12#qat"); assertEquals(url.href, "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"); }); -Deno.test(function urlProtocolSlashes() { +test(function urlProtocolSlashes() { assertEquals(new URL("http:foo").href, "http://foo/"); assertEquals(new URL("http://foo").href, "http://foo/"); assertEquals(new URL("file:foo").href, "file:///foo"); @@ -176,7 +178,7 @@ Deno.test(function urlProtocolSlashes() { assertEquals(new URL("abcd:foo").href, "abcd:foo"); assertEquals(new URL("abcd://foo").href, "abcd://foo"); }); -Deno.test(function urlRequireHost() { +test(function urlRequireHost() { assertEquals(new URL("file:///").href, "file:///"); assertThrows(()=>new URL("ftp:///"), TypeError, "Invalid URL"); assertThrows(()=>new URL("http:///"), TypeError, "Invalid URL"); @@ -184,30 +186,30 @@ Deno.test(function urlRequireHost() { assertThrows(()=>new URL("ws:///"), TypeError, "Invalid URL"); assertThrows(()=>new URL("wss:///"), TypeError, "Invalid URL"); }); -Deno.test(function urlDriveLetter() { +test(function urlDriveLetter() { assertEquals(new URL("file:///C:").href, "file:///C:"); assertEquals(new URL("file:///C:/").href, "file:///C:/"); assertEquals(new URL("file:///C:/..").href, "file:///C:/"); assertEquals(new URL("file://foo/C:").href, "file:///C:"); }); -Deno.test(function urlHostnameUpperCase() { +test(function urlHostnameUpperCase() { assertEquals(new URL("http://EXAMPLE.COM").href, "http://example.com/"); assertEquals(new URL("abcd://EXAMPLE.COM").href, "abcd://EXAMPLE.COM"); }); -Deno.test(function urlEmptyPath() { +test(function urlEmptyPath() { assertEquals(new URL("http://foo").pathname, "/"); assertEquals(new URL("file://foo").pathname, "/"); assertEquals(new URL("abcd://foo").pathname, ""); }); -Deno.test(function urlPathRepeatedSlashes() { +test(function urlPathRepeatedSlashes() { assertEquals(new URL("http://foo//bar//").pathname, "//bar//"); assertEquals(new URL("file://foo///bar//").pathname, "/bar//"); assertEquals(new URL("abcd://foo//bar//").pathname, "//bar//"); }); -Deno.test(function urlTrim() { +test(function urlTrim() { assertEquals(new URL(" http://example.com ").href, "http://example.com/"); }); -Deno.test(function urlEncoding() { +test(function urlEncoding() { assertEquals(new URL("http://a !$&*()=,;+'\"@example.com").username, "a%20!$&*()%3D,%3B+'%22"); assertEquals(new URL("http://:a !$&*()=,;+'\"@example.com").password, "a%20!$&*()%3D,%3B+'%22"); assertEquals(new URL("http://maƱana/c?d#e").hostname, "xn--maana-pta"); @@ -217,7 +219,7 @@ Deno.test(function urlEncoding() { assertEquals(new URL("abcd://example.com?a ~!@$&*()=:/,;?+'\"\\").search, "?a%20~!@$&*()=:/,;?+'%22\\"); assertEquals(new URL("http://example.com#a ~!@#$&*()=:/,;?+'\"\\").hash, "#a%20~!@#$&*()=:/,;?+'%22\\"); }); -Deno.test(function urlBase() { +test(function urlBase() { assertEquals(new URL("d", new URL("http://foo/a?b#c")).href, "http://foo/d"); assertEquals(new URL("", "http://foo/a/b?c#d").href, "http://foo/a/b?c"); assertEquals(new URL("", "file://foo/a/b?c#d").href, "file://foo/a/b?c"); @@ -248,11 +250,11 @@ Deno.test(function urlBase() { assertEquals(new URL("efgh:", "abcd://foo/a/b?c#d").href, "efgh:"); assertEquals(new URL("/foo", "abcd:/").href, "abcd:/foo"); }); -Deno.test(function urlDriveLetterBase() { +test(function urlDriveLetterBase() { assertEquals(new URL("/b", "file:///C:/a/b").href, "file:///C:/b"); assertEquals(new URL("/D:", "file:///C:/a/b").href, "file:///D:"); }); -Deno.test(function urlSameProtocolBase() { +test(function urlSameProtocolBase() { assertEquals(new URL("http:", "http://foo/a").href, "http://foo/a"); assertEquals(new URL("file:", "file://foo/a").href, "file://foo/a"); assertEquals(new URL("abcd:", "abcd://foo/a").href, "abcd:"); @@ -260,28 +262,28 @@ Deno.test(function urlSameProtocolBase() { assertEquals(new URL("file:b", "file://foo/a").href, "file://foo/b"); assertEquals(new URL("abcd:b", "abcd://foo/a").href, "abcd:b"); }); -Deno.test(function deletingAllParamsRemovesQuestionMarkFromURL() { +test(function deletingAllParamsRemovesQuestionMarkFromURL() { const url = new URL("http://example.com/?param1¶m2"); url.searchParams.delete("param1"); url.searchParams.delete("param2"); assertEquals(url.href, "http://example.com/"); assertEquals(url.search, ""); }); -Deno.test(function removingNonExistentParamRemovesQuestionMarkFromURL() { +test(function removingNonExistentParamRemovesQuestionMarkFromURL() { const url = new URL("http://example.com/?"); assertEquals(url.href, "http://example.com/?"); url.searchParams.delete("param1"); assertEquals(url.href, "http://example.com/"); assertEquals(url.search, ""); }); -Deno.test(function sortingNonExistentParamRemovesQuestionMarkFromURL() { +test(function sortingNonExistentParamRemovesQuestionMarkFromURL() { const url = new URL("http://example.com/?"); assertEquals(url.href, "http://example.com/?"); url.searchParams.sort(); assertEquals(url.href, "http://example.com/"); assertEquals(url.search, ""); }); -Deno.test.ignore(function customInspectFunction() { +test.ignore(function customInspectFunction() { const url = new URL("http://example.com/?"); assertEquals(Deno.inspect(url), `URL { href: "http://example.com/?", @@ -297,13 +299,13 @@ Deno.test.ignore(function customInspectFunction() { search: "" }`); }); -Deno.test(function protocolNotHttpOrFile() { +test(function protocolNotHttpOrFile() { const url = new URL("about:blank"); assertEquals(url.href, "about:blank"); assertEquals(url.protocol, "about:"); assertEquals(url.origin, "null"); }); -Deno.test(function throwForInvalidPortConstructor() { +test(function throwForInvalidPortConstructor() { const urls = [ `https://baz.qat:${2 ** 16}`, "https://baz.qat:-32", @@ -317,13 +319,13 @@ Deno.test(function throwForInvalidPortConstructor() { new URL("https://baz.qat:65535"); new URL("https://baz.qat:0"); }); -Deno.test(function doNotOverridePortIfInvalid() { +test(function doNotOverridePortIfInvalid() { const initialPort = "3000"; const url = new URL(`https://deno.land:${initialPort}`); url.port = `${2 ** 16}`; assertEquals(url.port, initialPort); }); -Deno.test(function emptyPortForSchemeDefaultPort() { +test(function emptyPortForSchemeDefaultPort() { const nonDefaultPort = "3500"; const url = new URL("ftp://baz.qat:21"); assertEquals(url.port, ""); @@ -342,21 +344,21 @@ Deno.test(function emptyPortForSchemeDefaultPort() { url2.protocol = "http"; assertEquals(url2.port, ""); }); -Deno.test(function assigningPortPropertyAffectsReceiverOnly() { +test(function assigningPortPropertyAffectsReceiverOnly() { const u1 = new URL("http://google.com/"); const u2 = new URL(u1 as any); u2.port = "123"; assertStrictEquals(u1.port, ""); assertStrictEquals(u2.port, "123"); }); -Deno.test(function urlSearchParamsIdentityPreserved() { +test(function urlSearchParamsIdentityPreserved() { const u = new URL("http://foo.com/"); const sp1 = u.searchParams; u.href = "http://bar.com/?baz=42"; const sp2 = u.searchParams; assertStrictEquals(sp1, sp2); }); -Deno.test(function urlTakeURLObjectAsParameter() { +test(function urlTakeURLObjectAsParameter() { const url = new URL(new URL("https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat")); assertEquals(url.href, "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"); }); diff --git a/test/js/deno/url/urlsearchparams.test.ts b/test/js/deno/url/urlsearchparams.test.ts index 792a92a54..04e5359f5 100644 --- a/test/js/deno/url/urlsearchparams.test.ts +++ b/test/js/deno/url/urlsearchparams.test.ts @@ -1,14 +1,16 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/url_search_params_test.ts -import { assert, assertEquals } from "deno:harness"; -Deno.test(function urlSearchParamsWithMultipleSpaces() { +import { createDenoTest } from "deno:harness"; +const { test, assert, assertEquals } = createDenoTest(import.meta.path); +test(function urlSearchParamsWithMultipleSpaces() { const init = { str: "this string has spaces in it" }; const searchParams = new URLSearchParams(init).toString(); assertEquals(searchParams, "str=this+string+has+spaces+in+it"); }); -Deno.test(function urlSearchParamsWithExclamation() { +test(function urlSearchParamsWithExclamation() { const init = [ [ "str", @@ -18,7 +20,7 @@ Deno.test(function urlSearchParamsWithExclamation() { const searchParams = new URLSearchParams(init).toString(); assertEquals(searchParams, "str=hello%2C+world%21"); }); -Deno.test(function urlSearchParamsWithQuotes() { +test(function urlSearchParamsWithQuotes() { const init = [ [ "str", @@ -28,7 +30,7 @@ Deno.test(function urlSearchParamsWithQuotes() { const searchParams = new URLSearchParams(init).toString(); assertEquals(searchParams, "str=%27hello+world%27"); }); -Deno.test(function urlSearchParamsWithBraket() { +test(function urlSearchParamsWithBraket() { const init = [ [ "str", @@ -38,7 +40,7 @@ Deno.test(function urlSearchParamsWithBraket() { const searchParams = new URLSearchParams(init).toString(); assertEquals(searchParams, "str=%28hello+world%29"); }); -Deno.test(function urlSearchParamsWithTilde() { +test(function urlSearchParamsWithTilde() { const init = [ [ "str", @@ -48,12 +50,12 @@ Deno.test(function urlSearchParamsWithTilde() { const searchParams = new URLSearchParams(init).toString(); assertEquals(searchParams, "str=hello%7Eworld"); }); -Deno.test(function urlSearchParamsInitString() { +test(function urlSearchParamsInitString() { const init = "c=4&a=2&b=3&%C3%A1=1"; const searchParams = new URLSearchParams(init); assert(init === searchParams.toString(), "The init query string does not match"); }); -Deno.test(function urlSearchParamsInitStringWithPlusCharacter() { +test(function urlSearchParamsInitStringWithPlusCharacter() { let params = new URLSearchParams("q=a+b"); assertEquals(params.toString(), "q=a+b"); assertEquals(params.get("q"), "a b"); @@ -61,7 +63,7 @@ Deno.test(function urlSearchParamsInitStringWithPlusCharacter() { assertEquals(params.toString(), "q=a+b+c"); assertEquals(params.get("q"), "a b c"); }); -Deno.test(function urlSearchParamsInitStringWithMalformedParams() { +test(function urlSearchParamsInitStringWithMalformedParams() { let params = new URLSearchParams("id=0&value=%"); assert(params != null, "constructor returned non-null value."); assert(params.has("id"), 'Search params object has name "id"'); @@ -81,7 +83,7 @@ Deno.test(function urlSearchParamsInitStringWithMalformedParams() { assert(params.has("b"), 'Search params object has name "b"'); assertEquals(params.get("b"), "%*"); }); -Deno.test(function urlSearchParamsInitIterable() { +test(function urlSearchParamsInitIterable() { const init = [ [ "a", @@ -95,7 +97,7 @@ Deno.test(function urlSearchParamsInitIterable() { const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "a=54&b=true"); }); -Deno.test(function urlSearchParamsInitRecord() { +test(function urlSearchParamsInitRecord() { const init = { a: "54", b: "true" @@ -103,24 +105,24 @@ Deno.test(function urlSearchParamsInitRecord() { const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "a=54&b=true"); }); -Deno.test(function urlSearchParamsInit() { +test(function urlSearchParamsInit() { const params1 = new URLSearchParams("a=b"); assertEquals(params1.toString(), "a=b"); const params2 = new URLSearchParams(params1); assertEquals(params2.toString(), "a=b"); }); -Deno.test(function urlSearchParamsAppendSuccess() { +test(function urlSearchParamsAppendSuccess() { const searchParams = new URLSearchParams(); searchParams.append("a", "true"); assertEquals(searchParams.toString(), "a=true"); }); -Deno.test(function urlSearchParamsDeleteSuccess() { +test(function urlSearchParamsDeleteSuccess() { const init = "a=54&b=true"; const searchParams = new URLSearchParams(init); searchParams.delete("b"); assertEquals(searchParams.toString(), "a=54"); }); -Deno.test(function urlSearchParamsGetAllSuccess() { +test(function urlSearchParamsGetAllSuccess() { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.getAll("a"), [ @@ -132,39 +134,39 @@ Deno.test(function urlSearchParamsGetAllSuccess() { ]); assertEquals(searchParams.getAll("c"), []); }); -Deno.test(function urlSearchParamsGetSuccess() { +test(function urlSearchParamsGetSuccess() { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get("a"), "54"); assertEquals(searchParams.get("b"), "true"); assertEquals(searchParams.get("c"), null); }); -Deno.test(function urlSearchParamsHasSuccess() { +test(function urlSearchParamsHasSuccess() { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); assert(searchParams.has("a")); assert(searchParams.has("b")); assert(!searchParams.has("c")); }); -Deno.test(function urlSearchParamsSetReplaceFirstAndRemoveOthers() { +test(function urlSearchParamsSetReplaceFirstAndRemoveOthers() { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); searchParams.set("a", "false"); assertEquals(searchParams.toString(), "a=false&b=true"); }); -Deno.test(function urlSearchParamsSetAppendNew() { +test(function urlSearchParamsSetAppendNew() { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); searchParams.set("c", "foo"); assertEquals(searchParams.toString(), "a=54&b=true&a=true&c=foo"); }); -Deno.test(function urlSearchParamsSortSuccess() { +test(function urlSearchParamsSortSuccess() { const init = "c=4&a=2&b=3&a=1"; const searchParams = new URLSearchParams(init); searchParams.sort(); assertEquals(searchParams.toString(), "a=2&a=1&b=3&c=4"); }); -Deno.test(function urlSearchParamsForEachSuccess() { +test(function urlSearchParamsForEachSuccess() { const init = [ [ "a", @@ -185,30 +187,30 @@ Deno.test(function urlSearchParamsForEachSuccess() { }); assertEquals(callNum, init.length); }); -Deno.test(function urlSearchParamsMissingName() { +test(function urlSearchParamsMissingName() { const init = "=4"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get(""), "4"); assertEquals(searchParams.toString(), "=4"); }); -Deno.test(function urlSearchParamsMissingValue() { +test(function urlSearchParamsMissingValue() { const init = "4="; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get("4"), ""); assertEquals(searchParams.toString(), "4="); }); -Deno.test(function urlSearchParamsMissingEqualSign() { +test(function urlSearchParamsMissingEqualSign() { const init = "4"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get("4"), ""); assertEquals(searchParams.toString(), "4="); }); -Deno.test(function urlSearchParamsMissingPair() { +test(function urlSearchParamsMissingPair() { const init = "c=4&&a=54&"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "c=4&a=54"); }); -Deno.test(function urlSearchParamsForShortEncodedChar() { +test(function urlSearchParamsForShortEncodedChar() { const init = { linefeed: "\n", tab: "\t" @@ -216,7 +218,7 @@ Deno.test(function urlSearchParamsForShortEncodedChar() { const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "linefeed=%0A&tab=%09"); }); -Deno.test(function urlSearchParamsShouldThrowTypeError() { +test(function urlSearchParamsShouldThrowTypeError() { let hasThrown = 0; try { new URLSearchParams([ @@ -251,7 +253,7 @@ Deno.test(function urlSearchParamsShouldThrowTypeError() { } assertEquals(hasThrown, 2); }); -Deno.test(function urlSearchParamsAppendArgumentsCheck() { +test(function urlSearchParamsAppendArgumentsCheck() { const methodRequireOneParam = [ "delete", "getAll", @@ -294,7 +296,7 @@ Deno.test(function urlSearchParamsAppendArgumentsCheck() { assertEquals(hasThrown, 2); }); }); -Deno.test(function urlSearchParamsDeletingAppendedMultiple() { +test(function urlSearchParamsDeletingAppendedMultiple() { const params = new URLSearchParams(); params.append("first", (1 as unknown) as string); assert(params.has("first")); @@ -306,7 +308,7 @@ Deno.test(function urlSearchParamsDeletingAppendedMultiple() { params.delete("first"); assertEquals(params.has("first"), false); }); -Deno.test(function urlSearchParamsCustomSymbolIterator() { +test(function urlSearchParamsCustomSymbolIterator() { const params = new URLSearchParams(); params[Symbol.iterator] = function*(): IterableIterator<[string, string]> { yield [ @@ -317,7 +319,7 @@ Deno.test(function urlSearchParamsCustomSymbolIterator() { const params1 = new URLSearchParams((params as unknown) as string[][]); assertEquals(params1.get("a"), "b"); }); -Deno.test(function urlSearchParamsCustomSymbolIteratorWithNonStringParams() { +test(function urlSearchParamsCustomSymbolIteratorWithNonStringParams() { const params = {}; (params as any)[Symbol.iterator] = function*(): IterableIterator<[number, number]> { yield [ @@ -328,7 +330,7 @@ Deno.test(function urlSearchParamsCustomSymbolIteratorWithNonStringParams() { const params1 = new URLSearchParams((params as unknown) as string[][]); assertEquals(params1.get("1"), "2"); }); -Deno.test(function urlSearchParamsOverridingAppendNotChangeConstructorAndSet() { +test(function urlSearchParamsOverridingAppendNotChangeConstructorAndSet() { let overridedAppendCalled = 0; class CustomSearchParams extends URLSearchParams { append(name: string, value: string) { @@ -349,7 +351,7 @@ Deno.test(function urlSearchParamsOverridingAppendNotChangeConstructorAndSet() { new CustomSearchParams().set("foo", "bar"); assertEquals(overridedAppendCalled, 0); }); -Deno.test(function urlSearchParamsOverridingEntriesNotChangeForEach() { +test(function urlSearchParamsOverridingEntriesNotChangeForEach() { class CustomSearchParams extends URLSearchParams { *entries(): IterableIterator<[string, string]> { yield* []; diff --git a/test/js/deno/v8/error.test.ts b/test/js/deno/v8/error.test.ts index d036c5eb9..06567ac3b 100644 --- a/test/js/deno/v8/error.test.ts +++ b/test/js/deno/v8/error.test.ts @@ -1,7 +1,9 @@ +// GENERATED - DO NOT EDIT // Copyright 2018+ the Deno authors. All rights reserved. MIT license. // https://raw.githubusercontent.com/denoland/deno/main/cli/tests/unit/error_stack_test.ts -import { assertEquals, assertMatch } from "deno:harness"; -Deno.test(function errorStackMessageLine() { +import { createDenoTest } from "deno:harness"; +const { test, assertEquals, assertMatch } = createDenoTest(import.meta.path); +test(function errorStackMessageLine() { const e1 = new Error(); e1.name = "Foo"; e1.message = "bar"; @@ -27,7 +29,7 @@ Deno.test(function errorStackMessageLine() { e6.message = null; assertMatch(e6.stack!, /^null: null\n/); }); -Deno.test(function captureStackTrace() { +test(function captureStackTrace() { function foo() { const error = new Error(); const stack1 = error.stack!; |
