test: run address-codec tests in the browser (#2466)

Update tests to use jasmine compatible functions.

This means changing `test` to `it`, `toStrictEqual` to `toEqual` (which
is still strict), `toThrowError` to `toError`, and updating the param
for toError to pass an `Error` object.

Remove the need to specify --single-run.
This commit is contained in:
Caleb Kniffen
2023-09-19 14:57:34 -05:00
parent 83870acbfb
commit c143dc3e99
15 changed files with 213 additions and 235 deletions

28
karma.config.js Normal file
View File

@@ -0,0 +1,28 @@
module.exports = function (config) {
config.set({
plugins: ["karma-webpack", "karma-jasmine", "karma-chrome-launcher"],
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ["jasmine"],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
// Use webpack to bundle our test files
"test/**/*.test.ts": ["webpack"],
},
browsers: ["ChromeHeadless"],
// runs only one browser at a time
concurrency: 1,
// CI mode
singleRun: true,
client: {
jasmine: {
// ensures that tests are run in order instead of a random order
random: false,
},
},
});
};

View File

@@ -6,6 +6,9 @@
* Remove Node 14 support
* Remove `assert` dependency. If you were catching `AssertionError` you need to change to `Error`.
### Changes
* Execute test in a browser in addition to node
## 4.3.1 (2023-09-27)
### Fixed
* Fix source-maps not finding their designated source

View File

@@ -0,0 +1,15 @@
const baseKarmaConfig = require('../../karma.config')
const webpackConfig = require('./test/webpack.config')
delete webpackConfig.entry
module.exports = function (config) {
baseKarmaConfig(config)
config.set({
base: '',
webpack: webpackConfig,
// list of files / patterns to load in the browser
files: ['test/**/*.test.ts'],
})
}

View File

@@ -28,6 +28,7 @@
"scripts": {
"build": "tsc --build tsconfig.build.json",
"test": "jest --verbose false --silent=false ./test/*.test.ts",
"test:browser": "npm run build && karma start ./karma.config.js",
"lint": "eslint . --ext .ts",
"clean": "rm -rf ./dist ./coverage ./test/testCompiledForWeb tsconfig.build.tsbuildinfo"
},

View File

@@ -159,7 +159,7 @@ const testCases: AddressTestCase[] = [
const classicAddress = testCase[0]
const tag = testCase[1] === false ? false : testCase[1]
const xAddress = isTestAddress ? testCase[3] : testCase[2]
test(`Converts ${classicAddress}${
it(`Converts ${classicAddress}${
tag ? `:${tag}` : ''
} to ${xAddress}${network}`, () => {
expect(classicAddressToXAddress(classicAddress, tag, isTestAddress)).toBe(
@@ -179,19 +179,19 @@ const testCases: AddressTestCase[] = [
const classicAddress = 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf'
const tag = MAX_32_BIT_UNSIGNED_INT + 1
test(`Converting ${classicAddress}:${tag}${network} throws`, () => {
it(`Converting ${classicAddress}:${tag}${network} throws`, () => {
expect(() => {
classicAddressToXAddress(classicAddress, tag, isTestAddress)
}).toThrowError(new Error('Invalid tag'))
}).toThrow(new Error('Invalid tag'))
})
}
{
const classicAddress = 'r'
test(`Invalid classic address: Converting ${classicAddress}${network} throws`, () => {
it(`Invalid classic address: Converting ${classicAddress}${network} throws`, () => {
expect(() => {
classicAddressToXAddress(classicAddress, false, isTestAddress)
}).toThrowError(
}).toThrow(
new Error('invalid_input_size: decoded data must have length >= 5'),
)
})
@@ -215,7 +215,7 @@ const testCases: AddressTestCase[] = [
tagTestCases.forEach((testCase) => {
const tag = testCase || false
const xAddress = encodeXAddress(accountId, tag, isTestAddress)
test(`Encoding ${accountId.toString('hex')}${
it(`Encoding ${accountId.toString('hex')}${
tag ? `:${tag}` : ''
} to ${xAddress} has expected length`, () => {
expect(xAddress.length).toBe(47)
@@ -227,23 +227,23 @@ const testCases: AddressTestCase[] = [
{
const xAddress = 'XVLhHMPHU98es4dbozjVtdWzVrDjtV5fdx1mHp98tDMoQXa'
test(`Invalid X-address (bad checksum): Converting ${xAddress} throws`, () => {
it(`Invalid X-address (bad checksum): Converting ${xAddress} throws`, () => {
expect(() => {
xAddressToClassicAddress(xAddress)
}).toThrowError(new Error('checksum_invalid'))
}).toThrow(new Error('checksum_invalid'))
})
}
{
const xAddress = 'dGzKGt8CVpWoa8aWL1k18tAdy9Won3PxynvbbpkAqp3V47g'
test(`Invalid X-address (bad prefix): Converting ${xAddress} throws`, () => {
it(`Invalid X-address (bad prefix): Converting ${xAddress} throws`, () => {
expect(() => {
xAddressToClassicAddress(xAddress)
}).toThrowError(new Error('Invalid X-address: bad prefix'))
}).toThrow(new Error('Invalid X-address: bad prefix'))
})
}
test(`Invalid X-address (64-bit tag) throws`, () => {
it(`Invalid X-address (64-bit tag) throws`, () => {
expect(() => {
// Encoded from:
// {
@@ -251,22 +251,22 @@ test(`Invalid X-address (64-bit tag) throws`, () => {
// tag: MAX_32_BIT_UNSIGNED_INT + 1
// }
xAddressToClassicAddress('XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8zeUygYrCgrPh')
}).toThrowError('Unsupported X-address')
}).toThrow(new Error('Unsupported X-address'))
})
test(`Invalid Account ID throws`, () => {
it(`Invalid Account ID throws`, () => {
expect(() => {
encodeXAddress(Buffer.from('00'.repeat(19), 'hex'), false, false)
}).toThrowError('Account ID must be 20 bytes')
}).toThrow(new Error('Account ID must be 20 bytes'))
})
test(`isValidXAddress returns false for invalid X-address`, () => {
it(`isValidXAddress returns false for invalid X-address`, () => {
expect(
isValidXAddress('XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8zeUygYrCgrPh'),
).toBe(false)
})
test(`Converts X7AcgcsBL6XDcUb... to r9cZA1mLK5R5A... and tag: false`, () => {
it(`Converts X7AcgcsBL6XDcUb... to r9cZA1mLK5R5A... and tag: false`, () => {
const classicAddress = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59'
// eslint-disable-next-line @typescript-eslint/naming-convention -- tag can be false or a number
const tag = false

View File

@@ -1,42 +1,42 @@
import { seqEqual, concatArgs } from '../src/utils'
test('two sequences are equal', () => {
it('two sequences are equal', () => {
expect(seqEqual([1, 2, 3], [1, 2, 3])).toBe(true)
})
test('elements must be in the same order', () => {
it('elements must be in the same order', () => {
expect(seqEqual([3, 2, 1], [1, 2, 3])).toBe(false)
})
test('sequences do not need to be the same type', () => {
it('sequences do not need to be the same type', () => {
expect(seqEqual(Buffer.from([1, 2, 3]), [1, 2, 3])).toBe(true)
expect(seqEqual(Buffer.from([1, 2, 3]), new Uint8Array([1, 2, 3]))).toBe(true)
})
test('sequences with a single element', () => {
it('sequences with a single element', () => {
expect(seqEqual(Buffer.from([1]), [1])).toBe(true)
expect(seqEqual(Buffer.from([1]), new Uint8Array([1]))).toBe(true)
})
test('empty sequences', () => {
it('empty sequences', () => {
expect(seqEqual(Buffer.from([]), [])).toBe(true)
expect(seqEqual(Buffer.from([]), new Uint8Array([]))).toBe(true)
})
test('plain numbers are concatenated', () => {
expect(concatArgs(10, 20, 30, 40)).toStrictEqual([10, 20, 30, 40])
it('plain numbers are concatenated', () => {
expect(concatArgs(10, 20, 30, 40)).toEqual([10, 20, 30, 40])
})
test('a variety of values are concatenated', () => {
it('a variety of values are concatenated', () => {
expect(
concatArgs(1, [2, 3], Buffer.from([4, 5]), new Uint8Array([6, 7])),
).toStrictEqual([1, 2, 3, 4, 5, 6, 7])
).toEqual([1, 2, 3, 4, 5, 6, 7])
})
test('a single value is returned as an array', () => {
expect(concatArgs(Buffer.from([7]))).toStrictEqual([7])
it('a single value is returned as an array', () => {
expect(concatArgs(Buffer.from([7]))).toEqual([7])
})
test('no arguments returns an empty array', () => {
expect(concatArgs()).toStrictEqual([])
it('no arguments returns an empty array', () => {
expect(concatArgs()).toEqual([])
})

View File

@@ -0,0 +1,9 @@
'use strict'
const { merge } = require('webpack-merge')
const { webpackForTest } = require('../../../weback.test.config')
const { getDefaultConfiguration } = require('../../../webpack.config')
module.exports = merge(
getDefaultConfiguration(),
webpackForTest('./test/index.ts', __dirname),
)

View File

@@ -34,11 +34,11 @@ function makeEncodeDecodeTest(
base58: string,
hex: string,
): void {
test(`can translate between ${hex} and ${base58}`, function () {
it(`can translate between ${hex} and ${base58}`, function () {
const actual = encoder(toBytes(hex))
expect(actual).toBe(base58)
})
test(`can translate between ${base58} and ${hex})`, function () {
it(`can translate between ${base58} and ${hex})`, function () {
const buf = decoder(base58)
expect(toHex(buf)).toBe(hex)
})
@@ -65,7 +65,7 @@ makeEncodeDecodeTest(
'023693F15967AE357D0327974AD46FE3C127113B1110D6044FD41E723689F81CC6',
)
test('can decode arbitrary seeds', function () {
it('can decode arbitrary seeds', function () {
const decoded = decodeSeed('sEdTM1uX8pu2do5XvTnutH6HsouMaM2')
expect(toHex(decoded.bytes)).toBe('4C3A1D213FBDFB14C7C28D609469B341')
expect(decoded.type).toBe('ed25519')
@@ -75,7 +75,7 @@ test('can decode arbitrary seeds', function () {
expect(decoded2.type).toBe('secp256k1')
})
test('can pass a type as second arg to encodeSeed', function () {
it('can pass a type as second arg to encodeSeed', function () {
const edSeed = 'sEdTM1uX8pu2do5XvTnutH6HsouMaM2'
const decoded = decodeSeed(edSeed)
const type = 'ed25519'
@@ -84,21 +84,21 @@ test('can pass a type as second arg to encodeSeed', function () {
expect(encodeSeed(decoded.bytes, type)).toBe(edSeed)
})
test('isValidClassicAddress - secp256k1 address valid', function () {
it('isValidClassicAddress - secp256k1 address valid', function () {
expect(isValidClassicAddress('rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1')).toBe(true)
})
test('isValidClassicAddress - ed25519 address valid', function () {
it('isValidClassicAddress - ed25519 address valid', function () {
expect(isValidClassicAddress('rLUEXYuLiQptky37CqLcm9USQpPiz5rkpD')).toBe(true)
})
test('isValidClassicAddress - invalid', function () {
it('isValidClassicAddress - invalid', function () {
expect(isValidClassicAddress('rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw2')).toBe(
false,
)
})
test('isValidClassicAddress - empty', function () {
it('isValidClassicAddress - empty', function () {
expect(isValidClassicAddress('')).toBe(false)
})
@@ -151,22 +151,22 @@ describe('encodeSeed', function () {
expect(result).toBe('sEdV19BLfeQeKdEXyYA4NhjPJe6XBfG')
})
test('attempting to encode a seed with less than 16 bytes of entropy throws', function () {
it('attempting to encode a seed with less than 16 bytes of entropy throws', function () {
expect(() => {
encodeSeed(
Buffer.from('CF2DE378FBDD7E2EE87D486DFB5A7B', 'hex'),
'secp256k1',
)
}).toThrow('entropy must have length 16')
}).toThrow(new Error('entropy must have length 16'))
})
test('attempting to encode a seed with more than 16 bytes of entropy throws', function () {
it('attempting to encode a seed with more than 16 bytes of entropy throws', function () {
expect(() => {
encodeSeed(
Buffer.from('CF2DE378FBDD7E2EE87D486DFB5A7BFFFF', 'hex'),
'secp256k1',
)
}).toThrow('entropy must have length 16')
}).toThrow(new Error('entropy must have length 16'))
})
})
@@ -192,11 +192,13 @@ describe('encodeAccountID', function () {
expect(encoded).toBe('rJrRMgiRgrU6hDF4pgu5DXQdWyPbY35ErN')
})
test('unexpected length should throw', function () {
it('unexpected length should throw', function () {
expect(() => {
encodeAccountID(Buffer.from('ABCDEF', 'hex'))
}).toThrow(
'unexpected_payload_length: bytes.length does not match expectedLength',
new Error(
'unexpected_payload_length: bytes.length does not match expectedLength. Ensure that the bytes are a Buffer.',
),
)
})
})
@@ -212,7 +214,7 @@ describe('decodeNodePublic', function () {
})
})
test('encodes 123456789 with version byte of 0', () => {
it('encodes 123456789 with version byte of 0', () => {
expect(
codec.encode(Buffer.from('123456789'), {
versions: [0],
@@ -221,83 +223,93 @@ test('encodes 123456789 with version byte of 0', () => {
).toBe('rnaC7gW34M77Kneb78s')
})
test('multiple versions with no expected length should throw', () => {
it('multiple versions with no expected length should throw', () => {
expect(() => {
codec.decode('rnaC7gW34M77Kneb78s', {
versions: [0, 1],
})
}).toThrow(
new Error(
'expectedLength is required because there are >= 2 possible versions',
),
)
})
test('attempting to decode data with length < 5 should throw', () => {
it('attempting to decode data with length < 5 should throw', () => {
expect(() => {
codec.decode('1234', {
versions: [0],
})
}).toThrow('invalid_input_size: decoded data must have length >= 5')
}).toThrow(
new Error('invalid_input_size: decoded data must have length >= 5'),
)
})
test('attempting to decode data with unexpected version should throw', () => {
it('attempting to decode data with unexpected version should throw', () => {
expect(() => {
codec.decode('rnaC7gW34M77Kneb78s', {
versions: [2],
})
}).toThrow(
new Error(
'version_invalid: version bytes do not match any of the provided version(s)',
),
)
})
test('invalid checksum should throw', () => {
it('invalid checksum should throw', () => {
expect(() => {
codec.decode('123456789', {
versions: [0, 1],
})
}).toThrow('checksum_invalid')
}).toThrow(new Error('checksum_invalid'))
})
test('empty payload should throw', () => {
it('empty payload should throw', () => {
expect(() => {
codec.decode('', {
versions: [0, 1],
})
}).toThrow('invalid_input_size: decoded data must have length >= 5')
}).toThrow(
new Error('invalid_input_size: decoded data must have length >= 5'),
)
})
test('decode data', () => {
it('decode data', () => {
expect(
codec.decode('rnaC7gW34M77Kneb78s', {
versions: [0],
}),
).toStrictEqual({
).toEqual({
version: [0],
bytes: Buffer.from('123456789'),
type: null,
})
})
test('decode data with expected length', function () {
it('decode data with expected length', function () {
expect(
codec.decode('rnaC7gW34M77Kneb78s', {
versions: [0],
expectedLength: 9,
}),
).toStrictEqual({
).toEqual({
version: [0],
bytes: Buffer.from('123456789'),
type: null,
})
})
test('decode data with wrong expected length should throw', function () {
it('decode data with wrong expected length should throw', function () {
expect(() => {
codec.decode('rnaC7gW34M77Kneb78s', {
versions: [0],
expectedLength: 8,
})
}).toThrow(
new Error(
'version_invalid: version bytes do not match any of the provided version(s)',
),
)
expect(() => {
codec.decode('rnaC7gW34M77Kneb78s', {
@@ -305,6 +317,8 @@ test('decode data with wrong expected length should throw', function () {
expectedLength: 10,
})
}).toThrow(
new Error(
'version_invalid: version bytes do not match any of the provided version(s)',
),
)
})

View File

@@ -1,39 +1,14 @@
const webpackConfig = require("./test/webpack.config");
const baseKarmaConfig = require("../../karma.config");
delete webpackConfig.entry;
module.exports = function (config) {
config.set({
plugins: ["karma-webpack", "karma-jasmine", "karma-chrome-launcher"],
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: "",
webpack: webpackConfig,
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ["jasmine"],
// list of files / patterns to load in the browser
files: ["build/xrplf-secret-numbers-latest.js", "test/*.test.ts"],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
// Use webpack to bundle our test files
"test/*.test.ts": ["webpack"],
},
browsers: ["ChromeHeadless"],
// runs only one browser at a time
concurrency: 1,
// CI mode
singleRun: true,
client: {
jasmine: {
// ensures that tests are run in order instead of a random order
random: false,
},
},
});
baseKarmaConfig(config);
};

View File

@@ -10,7 +10,7 @@
"prepublish": "npm run clean && npm run lint && npm run test && npm run test:browser && npm run build",
"clean": "rm -rf ./dist ./coverage ./test/testCompiledForWeb tsconfig.build.tsbuildinfo",
"test": "jest --verbose",
"test:browser": "npm run build && npm run build:browserTests && karma start ./karma.config.js --single-run",
"test:browser": "npm run build && npm run build:browserTests && karma start ./karma.config.js",
"build": "run-s build:lib build:web",
"build:lib": "tsc --build tsconfig.build.json",
"build:web": "webpack",

View File

@@ -1,61 +1,9 @@
"use strict";
const assert = require("assert");
const path = require("path");
const webpack = require("webpack");
const { merge } = require("webpack-merge");
const { webpackForTest } = require("../../../weback.test.config");
const baseConfig = require("../webpack.base.config");
function webpackForTest(testFileName) {
const match = testFileName.match(/\/?([^\/]*)\.ts$/);
if (!match) {
assert(false, "wrong filename:" + testFileName);
}
const test = merge(require("../webpack.base.config"), {
mode: "production",
cache: true,
entry: testFileName,
output: {
library: match[1].replace(/-/g, "_"),
path: path.join(__dirname, "./testCompiledForWeb/"),
filename: match[1] + ".js",
},
plugins: [
new webpack.DefinePlugin({
"process.stdout": {},
}),
],
module: {
rules: [
// Compile the tests
{
test: /\.ts$/,
use: [
{
loader: "ts-loader",
options: {
compilerOptions: {
lib: ["esnext", "dom"],
composite: false,
declaration: false,
declarationMap: false,
},
},
},
],
},
],
},
node: {
global: true,
__filename: false,
__dirname: true,
},
resolve: {
extensions: [".ts", ".js", ".json"],
},
});
return test;
}
module.exports = webpackForTest("./test/index.ts");
module.exports = merge(
baseConfig,
webpackForTest("./test/index.ts", __dirname)
);

View File

@@ -1,39 +1,14 @@
const webpackConfig = require('./test/webpack.config')[0]()
const baseKarmaConfig = require('../../karma.config')
const webpackConfig = require('./test/webpack.config')
delete webpackConfig.entry
module.exports = function (config) {
config.set({
plugins: ['karma-webpack', 'karma-jasmine', 'karma-chrome-launcher'],
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
webpack: webpackConfig,
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: ['build/xrpl-latest.js', 'test/integration/**/*.test.ts'],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
// Use webpack to bundle our test files
'test/integration/**/*.test.ts': ['webpack'],
},
browsers: ['ChromeHeadless'],
// runs only one browser at a time
concurrency: 1,
// CI mode
singleRun: true,
client: {
jasmine: {
// ensures that tests are run in order instead of a random order
random: false,
},
},
})
baseKarmaConfig(config)
}

View File

@@ -61,7 +61,7 @@
"prepublish": "run-s clean build",
"test": "jest --config=jest.config.unit.js --verbose false --silent=false",
"test:integration": "TS_NODE_PROJECT=tsconfig.build.json jest --config=jest.config.integration.js --verbose false --silent=false --runInBand",
"test:browser": "npm run build && npm run build:browserTests && karma start ./karma.config.js --single-run",
"test:browser": "npm run build && npm run build:browserTests && karma start ./karma.config.js",
"test:watch": "jest --watch --verbose false --silent=false --runInBand ./test/**/*.test.ts --testPathIgnorePatterns=./test/integration --testPathIgnorePatterns=./test/fixtures",
"format": "prettier --write '{src,test}/**/*.ts'",
"lint": "eslint . --ext .ts --max-warnings 0",

View File

@@ -1,64 +1,14 @@
'use strict'
const assert = require('assert')
const path = require('path')
const webpack = require('webpack')
const { merge } = require('webpack-merge')
const { webpackForTest } = require('../../../weback.test.config')
function webpackForTest(testFileName) {
const match = testFileName.match(/\/?([^\/]*)\.ts$/)
if (!match) {
assert(false, 'wrong filename:' + testFileName)
}
return merge(require('../webpack.base.config'), {
mode: 'production',
cache: true,
module.exports = merge(
require('../webpack.base.config'),
webpackForTest('./test/integration/index.ts', __dirname),
{
externals: [
{
net: 'null', // net is used in tests to setup mock server
},
],
entry: testFileName,
output: {
library: match[1].replace(/-/g, '_'),
path: path.join(__dirname, './testCompiledForWeb/'),
filename: match[1] + '.js',
},
plugins: [
new webpack.DefinePlugin({
'process.stdout': {},
}),
],
module: {
rules: [
// Compile the tests
{
test: /\.ts$/,
use: [
{
loader: 'ts-loader',
options: {
compilerOptions: {
lib: ['esnext', 'dom'],
composite: false,
declaration: false,
declarationMap: false,
},
},
},
],
},
],
},
node: {
global: true,
__filename: false,
__dirname: true,
},
resolve: {
extensions: ['.ts', '.js', '.json'],
},
})
}
module.exports = [(env, argv) => webpackForTest('./test/integration/index.ts')]
)

60
weback.test.config.js Normal file
View File

@@ -0,0 +1,60 @@
"use strict";
const assert = require("assert");
const path = require("path");
const webpack = require("webpack");
function webpackForTest(testFileName, basePath) {
const match = testFileName.match(/\/?([^\/]*)\.ts$/);
if (!match) {
assert(false, "wrong filename:" + testFileName);
}
return {
mode: "production",
cache: true,
entry: testFileName,
output: {
library: match[1].replace(/-/g, "_"),
path: path.join(basePath, "./testCompiledForWeb/"),
filename: match[1] + ".js",
},
plugins: [
new webpack.DefinePlugin({
"process.stdout": {},
}),
],
module: {
rules: [
// Compile compile the tests
{
test: /\.ts$/,
use: [
{
loader: "ts-loader",
options: {
compilerOptions: {
lib: ["esnext", "dom"],
composite: false,
declaration: false,
declarationMap: false,
},
},
},
],
},
],
},
node: {
global: true,
__filename: false,
__dirname: true,
},
resolve: {
extensions: [".ts", ".js", ".json"],
},
};
}
module.exports = {
webpackForTest,
};