cleanup test infra

This commit is contained in:
Niccolo Borgioli 2024-07-29 16:14:12 +02:00
parent 72a31ab3e2
commit c485d5c715
18 changed files with 2247 additions and 1771 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
node_modules
dist
docs
__screenshots__

View File

@ -1,21 +0,0 @@
module.exports = function (config) {
config.set({
frameworks: ['mocha'],
plugins: ['karma-mocha', '@endyjasmi/karma-playwright-launcher'],
basePath: '',
files: [
{ pattern: 'node_modules/chai/chai.js', type: 'module' },
{ pattern: 'dist/**/*.js', type: 'module' },
{ pattern: 'test/**/*.js', type: 'module' },
],
browsers: ['ChromiumHeadless', 'FirefoxHeadless', 'WebKitHeadless'],
preprocessors: {},
reporters: ['progress'],
singleRun: false,
concurrency: Infinity,
})
}

View File

@ -1,4 +0,0 @@
spec:
- test/**/*.spec.js
require:
- test/hooks.js

2
.nvmrc
View File

@ -1 +1 @@
v20
v22.5.1

View File

@ -31,30 +31,26 @@
],
"scripts": {
"docs": "typedoc",
"test:node": "mocha",
"test:browser": "karma start .karma.cjs --single-run",
"test": "run-s build test:*",
"test:node": "vitest",
"test:browsers": "zx test.browsers.js",
"test": "CI=1 run-s build test:*",
"build": "tsc",
"clean": "rm -rf ./dist",
"dev": "run-p -ln dev:*",
"dev:build": "tsc -w",
"dev:test:node": "mocha --parallel --watch",
"dev:test:browser": "karma start .karma.cjs",
"prepublishOnly": "run-s clean build"
"dev": "vitest",
"prepublishOnly": "run-s clean test"
},
"devDependencies": {
"@endyjasmi/karma-playwright-launcher": "^0.0.4",
"@types/node": "^20.11.30",
"chai": "^4.4.1",
"karma": "^6.4.3",
"karma-mocha": "^2.0.1",
"mocha": "^10.3.0",
"@tsconfig/strictest": "^2.0.5",
"@types/node": "^22.0.0",
"@vitest/browser": "^2.0.4",
"npm-run-all": "^4.1.5",
"playwright": "^1.42.1",
"typedoc": "^0.25.12",
"typescript": "^5.4.2"
"playwright": "^1.45.3",
"typedoc": "^0.26.5",
"typescript": "^5.5.4",
"vitest": "^2.0.4",
"zx": "^8.1.4"
},
"packageManager": "pnpm@8.15.5",
"packageManager": "pnpm@9.6.0",
"engines": {
"node": ">=16",
"npm": "please-use-pnpm",

File diff suppressed because it is too large Load Diff

10
test.browsers.js Executable file
View File

@ -0,0 +1,10 @@
#!/usr/bin/env zx
import 'zx/globals'
$.verbose = true
const BROWSERS = ['firefox', 'chromium', 'webkit']
await Promise.all([
BROWSERS.map((browser) => $`pnpm vitest --browser.provider=playwright --browser.name=${browser} --browser.headless`),
])

View File

@ -0,0 +1,5 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Random > Should throw error on empty array 1`] = `[Error: Invalid number of bytes]`;
exports[`Random > Should throw error on negative bytes 1`] = `[Error: Invalid number of bytes]`;

View File

@ -0,0 +1,5 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`RSA > Generate keys > Should not be able to generate a key below 2048bit 1`] = `[Error: bit sizes below 2048 are considered insecure.]`;
exports[`RSA > Generate keys > Should not be able to generate a key below 2048bit 2`] = `[Error: bit sizes below 2048 are considered insecure.]`;

View File

@ -1,3 +1,4 @@
import { describe, expect, it } from 'vitest'
import { AES, Bytes, Hashes, Hex } from '../dist/index.js'
import { Precomputed } from './values.js'
@ -15,10 +16,10 @@ describe('AES', () => {
length: keySize,
salt: Hex.decode(Precomputed.Crypto.Bytes[16]),
})
const ciphertext = await AES.encrypt(data, key, AES.Modes.GCM)
const ciphertext = await AES.encrypt(data, key, AES.Modes.AES_GCM)
const plaintext = await AES.decrypt(ciphertext, key)
chai.expect(data).to.be.deep.equal(plaintext)
chai.expect(message).to.be.equal(Bytes.decode(plaintext))
expect(data.buffer).toEqual(plaintext.buffer)
expect(message).toEqual(Bytes.decode(plaintext))
})
}
})
@ -28,15 +29,15 @@ describe('AES', () => {
const data = Bytes.encode(message)
const ciphertext = await AES.encrypt(data, key)
const plaintext = await AES.decrypt(ciphertext, key)
chai.expect(data).to.be.deep.equal(plaintext)
chai.expect(message).to.be.equal(Bytes.decode(plaintext))
expect(data.buffer).toEqual(plaintext.buffer)
expect(message).toEqual(Bytes.decode(plaintext))
})
it('Easy API', async () => {
const password = 'foobar'
const encrypted = await AES.encryptEasy(message, password)
const decrypted = await AES.decryptEasy(encrypted, password)
chai.expect(message).to.be.equal(decrypted)
expect(message).toEqual(decrypted)
})
})
}

View File

@ -1,15 +1,15 @@
import { describe, expect, it } from 'vitest'
import { Base64, Bytes, Hex } from '../dist/index.js'
import { compareArrayLike } from './utils.js'
import { Precomputed } from './values.js'
describe('Encoding', () => {
describe('Bytes', () => {
for (const [input, output] of Object.entries(Precomputed.Encoding.Bytes)) {
it(`Should encode ${input} to ${output}`, async () => {
compareArrayLike(Bytes.encode(input), output)
expect(Bytes.encode(input).buffer).toEqual(output.buffer)
})
it(`Should decode ${output} to ${input}`, async () => {
compareArrayLike(await Bytes.decode(output), input)
expect(Bytes.decode(output)).toEqual(input)
})
}
})
@ -17,10 +17,10 @@ describe('Encoding', () => {
for (const [input, output] of Object.entries(Precomputed.Encoding.Hex)) {
const buffer = Bytes.encode(input)
it(`Should encode ${input} to ${output}`, async () => {
chai.expect(await Hex.encode(buffer)).to.equal(output)
expect(Hex.encode(buffer)).toEqual(output)
})
it(`Should decode ${output} to ${input}`, async () => {
chai.expect(await Hex.decode(output)).to.deep.equal(buffer)
expect(Hex.decode(output).buffer).toEqual(buffer.buffer)
})
}
})
@ -28,10 +28,10 @@ describe('Encoding', () => {
for (const [input, output] of Object.entries(Precomputed.Encoding.Base64)) {
const buffer = Bytes.encode(input)
it(`Should encode ${input} to ${output}`, async () => {
chai.expect(await Base64.encode(buffer)).to.equal(output)
expect(await Base64.encode(buffer)).toEqual(output)
})
it(`Should decode ${output} to ${input}`, async () => {
chai.expect(await Base64.decode(output)).to.deep.equal(buffer)
expect((await Base64.decode(output)).buffer).toEqual(buffer.buffer)
})
}
})

View File

@ -1,3 +1,4 @@
import { describe, expect, it } from 'vitest'
import { Bytes, Hash, Hashes, Hex } from '../dist/index.js'
import { Precomputed } from './values.js'
@ -6,16 +7,18 @@ describe('Hash', () => {
describe(type, () => {
const values = Precomputed.Hash[type]
for (const [input, output] of Object.entries(values)) {
if (typeof output !== 'string') throw new Error('Bad test data')
it(`Should hash "${input}" to "${output.slice(0, 8)}..."`, async () => {
const hashed = await Hash.hash(input, Hashes[type])
chai.expect(hashed).to.equal(output)
expect(hashed).toEqual(output)
})
it(`Should hash "${input}" to "${output.slice(0, 8)}..." as buffer`, async () => {
const outputBuffer = Hex.decode(output)
const inputBuffer = Bytes.encode(input)
const hashed = await Hash.hash(inputBuffer, Hashes[type])
chai.expect(hashed).to.deep.equal(outputBuffer)
expect(hashed).toEqual(outputBuffer)
})
}
})

View File

@ -1,12 +0,0 @@
/**
* Hook for mocha tests in node
* Initialises chai and chai-as-promised as global variables
*/
export const mochaHooks = {
async beforeEach() {
if (typeof chai === 'undefined') {
global.chai = await import('chai')
}
},
}

View File

@ -1,18 +1,18 @@
import { describe, expect, it } from 'vitest'
import { getRandomBytes } from '../dist/index.js'
import { Promises } from './utils.js'
describe('Random', () => {
it('Should be able to create random values', async () => {
const buffer = await getRandomBytes(8)
chai.expect(buffer).to.be.instanceOf(Uint8Array)
chai.expect(buffer.byteLength).to.equal(8)
expect(buffer).instanceOf(Uint8Array)
expect(buffer.byteLength).toEqual(8)
})
it('Should throw error on empty array', async () => {
await Promises.reject(() => getRandomBytes(0))
await expect(() => getRandomBytes(0)).rejects.toThrowErrorMatchingSnapshot()
})
it('Should throw error on negative bytes', async () => {
await Promises.reject(() => getRandomBytes(-1))
await expect(() => getRandomBytes(-1)).rejects.toThrowErrorMatchingSnapshot()
})
})

View File

@ -1,11 +1,11 @@
import { describe } from 'vitest'
import { Bytes, RSA } from '../dist/index.js'
import { Promises } from './utils.js'
import { Precomputed } from './values.js'
import { it } from 'vitest'
import { expect } from 'vitest'
describe('RSA', () => {
describe('Generate keys', function () {
this.timeout(10_000)
it('Should be able to generate a keypair', async () => {
await RSA.generateKeyPair()
})
@ -16,10 +16,10 @@ describe('RSA', () => {
await RSA.generateKeyPair(4096)
})
it('Should not be able to generate a key below 2048bit', async () => {
await Promises.reject(() => RSA.generateKeyPair(1024))
await expect(() => RSA.generateKeyPair(1024)).rejects.toThrowErrorMatchingSnapshot()
})
it('Should not be able to generate a key below 2048bit', async () => {
await Promises.reject(() => RSA.generateKeyPair(-1))
await expect(() => RSA.generateKeyPair(-1)).rejects.toThrowErrorMatchingSnapshot()
})
})
@ -30,10 +30,9 @@ describe('RSA', () => {
const bytes = Bytes.encode(message)
try {
const encrypted = await RSA.encrypt(bytes, pair.public)
chai.expect.fail('Should have thrown error')
const decrypted = await RSA.decrypt(encrypted, pair.private)
chai.expect(decrypted).to.be.deep.equal(bytes)
chai.expect(message).to.be.equal(Bytes.decode(decrypted))
expect(decrypted).toEqual(bytes)
expect(message).toEqual(Bytes.decode(decrypted))
} catch {}
})
}

View File

@ -1,15 +0,0 @@
export class Promises {
static async reject(fn) {
try {
await fn()
chai.expect.fail('Should have thrown error')
} catch {}
}
}
export function compareArrayLike(a, b) {
chai.expect(a.length).to.equal(b.length)
for (let i = 0; i < a.length; i++) {
chai.expect(a[i]).to.equal(b[i])
}
}

View File

@ -57,4 +57,4 @@ export const Precomputed = {
'Marvelous intentions joy deceptions overcome sexuality spirit against. Selfish of marvelous play dead war snare eternal-return ultimate. Reason aversion suicide.',
},
},
}
} as const

View File

@ -1,104 +1,16 @@
{
"extends": ["@tsconfig/strictest"],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "ES2015" /* Specify what module code is generated. */,
"rootDir": "./src" /* Specify the root folder within your source files. */,
"moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
"declarationMap": true /* Create sourcemaps for d.ts files. */,
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
"sourceMap": true /* Create source map files for emitted JavaScript files. */,
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied 'any' type. */,
"strictNullChecks": true /* When type checking, take into account 'null' and 'undefined'. */,
"strictFunctionTypes": true /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */,
"strictBindCallApply": true /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */,
"strictPropertyInitialization": true /* Check for class properties that are declared but not set in the constructor. */,
"noImplicitThis": true /* Enable error reporting when 'this' is given the type 'any'. */,
"useUnknownInCatchVariables": true /* Default catch clause variables as 'unknown' instead of 'any'. */,
"alwaysStrict": true /* Ensure 'use strict' is always emitted. */,
"noUnusedLocals": true /* Enable error reporting when local variables aren't read. */,
"noUnusedParameters": true /* Raise an error when a function parameter isn't read. */,
"exactOptionalPropertyTypes": true /* Interpret optional property types as written, rather than adding 'undefined'. */,
"noImplicitReturns": true /* Enable error reporting for codepaths that do not explicitly return in a function. */,
"noFallthroughCasesInSwitch": true /* Enable error reporting for fallthrough cases in switch statements. */,
"noUncheckedIndexedAccess": true /* Add 'undefined' to a type when accessed using an index. */,
"noImplicitOverride": true /* Ensure overriding members in derived classes are marked with an override modifier. */,
"noPropertyAccessFromIndexSignature": true /* Enforces using indexed accessors for keys declared using an indexed type. */,
"allowUnusedLabels": false /* Disable error reporting for unused labels. */,
"allowUnreachableCode": false /* Disable error reporting for unreachable code. */,
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
"isolatedModules": false
},
"include": ["src/**/*"]
}