git.delta.rocks / unique-network / refs/commits / 1a4aa2d6346d

difftreelog

source

tests/src/util/index.ts10.9 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import * as path from 'path';5import * as crypto from 'crypto';6import {IKeyringPair} from '@polkadot/types/types/interfaces';7import chai from 'chai';8import chaiAsPromised from 'chai-as-promised';9import chaiSubset from 'chai-subset';10import {Context} from 'mocha';11import config from '../config';12import {ChainHelperBase} from './playgrounds/unique';13import {ILogger} from './playgrounds/types';14import {DevUniqueHelper, SilentLogger, SilentConsole, DevMoonbeamHelper, DevMoonriverHelper, DevAcalaHelper, DevKaruraHelper, DevRelayHelper, DevWestmintHelper, DevStatemineHelper, DevStatemintHelper, DevAstarHelper, DevShidenHelper} from './playgrounds/unique.dev';15import {dirname} from 'path';16import {fileURLToPath} from 'url';1718chai.use(chaiAsPromised);19chai.use(chaiSubset);20export const expect = chai.expect;2122const getTestHash = (filename: string) => crypto.createHash('md5').update(filename).digest('hex');2324export const getTestSeed = (filename: string) => `//Alice+${getTestHash(filename)}`;2526async function usingPlaygroundsGeneral<T extends ChainHelperBase, R = void>(27  helperType: new (logger: ILogger) => T,28  url: string,29  code: (helper: T, privateKey: (seed: string | { filename?: string, url?: string, ignoreFundsPresence?: boolean }) => Promise<IKeyringPair>) => Promise<R>,30): Promise<R> {31  const silentConsole = new SilentConsole();32  silentConsole.enable();3334  const helper = new helperType(new SilentLogger());35  let result;36  try {37    await helper.connect(url);38    const ss58Format = helper.chain.getChainProperties().ss58Format;39    const privateKey = async (seed: string | {filename?: string, url?: string, ignoreFundsPresence?: boolean}) => {40      if(typeof seed === 'string') {41        return helper.util.fromSeed(seed, ss58Format);42      }43      if(seed.url) {44        const {filename} = makeNames(seed.url);45        seed.filename = filename;46      } else if(seed.filename) {47        // Pass48      } else {49        throw new Error('no url nor filename set');50      }51      const actualSeed = getTestSeed(seed.filename);52      let account = helper.util.fromSeed(actualSeed, ss58Format);53      // here's to hoping that no54      if(!seed.ignoreFundsPresence && ((helper as any)['balance'] == undefined || await (helper as any).balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND)) {55        console.warn(`${path.basename(seed.filename)}: Not enough funds present on the filename account. Using the default one as the donor instead.`);56        account = helper.util.fromSeed('//Alice', ss58Format);57      }58      return account;59    };60    result = await code(helper, privateKey);61  }62  finally {63    await helper.disconnect();64    silentConsole.disable();65  }66  return result as any as R;67}6869export const usingPlaygrounds = <R = void>(code: (helper: DevUniqueHelper, privateKey: (seed: string | {filename?: string, url?: string, ignoreFundsPresence?: boolean}) => Promise<IKeyringPair>) => Promise<R>, url: string = config.substrateUrl) => usingPlaygroundsGeneral<DevUniqueHelper, R>(DevUniqueHelper, url, code);7071export const usingWestmintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevWestmintHelper>(DevWestmintHelper, url, code);7273export const usingStateminePlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevStatemineHelper>(DevWestmintHelper, url, code);7475export const usingStatemintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevStatemintHelper>(DevWestmintHelper, url, code);7677export const usingRelayPlaygrounds = (url: string, code: (helper: DevRelayHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevRelayHelper>(DevRelayHelper, url, code);7879export const usingAcalaPlaygrounds = (url: string, code: (helper: DevAcalaHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevAcalaHelper>(DevAcalaHelper, url, code);8081export const usingKaruraPlaygrounds = (url: string, code: (helper: DevKaruraHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevKaruraHelper>(DevAcalaHelper, url, code);8283export const usingMoonbeamPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevMoonbeamHelper>(DevMoonbeamHelper, url, code);8485export const usingMoonriverPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevMoonriverHelper>(DevMoonriverHelper, url, code);8687export const usingAstarPlaygrounds = (url: string, code: (helper: DevAstarHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevAstarHelper>(DevAstarHelper, url, code);8889export const usingShidenPlaygrounds = (url: string, code: (helper: DevShidenHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevShidenHelper>(DevShidenHelper, url, code);9091export const MINIMUM_DONOR_FUND = 4_000_000n;92export const DONOR_FUNDING = 4_000_000n;9394// App-promotion periods:95export const LOCKING_PERIOD = 12n; // 12 blocks of relay96export const UNLOCKING_PERIOD = 6n; // 6 blocks of parachain9798// Native contracts99export const COLLECTION_HELPER = '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f';100export const CONTRACT_HELPER = '0x842899ECF380553E8a4de75bF534cdf6fBF64049';101102export enum Pallets {103  Inflation = 'inflation',104  ReFungible = 'refungible',105  Fungible = 'fungible',106  NFT = 'nonfungible',107  Scheduler = 'scheduler',108  UniqueScheduler = 'uniqueScheduler',109  AppPromotion = 'apppromotion',110  CollatorSelection = 'collatorselection',111  Session = 'session',112  Identity = 'identity',113  Democracy = 'democracy',114  Council = 'council',115  //CouncilMembership = 'councilmembership',116  TechnicalCommittee = 'technicalcommittee',117  Fellowship = 'fellowshipcollective',118  Preimage = 'preimage',119  Maintenance = 'maintenance',120  TestUtils = 'testutils',121}122123export function requirePalletsOrSkip(test: Context, helper: DevUniqueHelper, requiredPallets: readonly string[]) {124  const missingPallets = helper.fetchMissingPalletNames(requiredPallets);125126  if(missingPallets.length > 0) {127    const skipMsg = `\tSkipping test '${test.test?.title}'.\n\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;128    console.warn('\x1b[38:5:208m%s\x1b[0m', skipMsg);129    test.skip();130  }131}132133export function itSub(name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: readonly string[] } = {}) {134  (opts.only ? it.only :135    opts.skip ? it.skip : it)(name, async function () {136    await usingPlaygrounds(async (helper, privateKey) => {137      if(opts.requiredPallets) {138        requirePalletsOrSkip(this, helper, opts.requiredPallets);139      }140141      await cb({helper, privateKey});142    });143  });144}145export function itSubIfWithPallet(name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: readonly string[] } = {}) {146  return itSub(name, cb, {requiredPallets: required, ...opts});147}148itSub.only = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSub(name, cb, {only: true});149itSub.skip = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSub(name, cb, {skip: true});150151itSubIfWithPallet.only = (name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {only: true});152itSubIfWithPallet.skip = (name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});153itSub.ifWithPallets = itSubIfWithPallet;154155export type SchedKind = 'anon' | 'named';156157export function itSched(158  name: string,159  cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any,160  opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},161) {162  itSub(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);163  itSub(name + ' (named scheduling)', (apis) => cb('named', apis), opts);164}165itSched.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {only: true});166itSched.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {skip: true});167itSched.ifWithPallets = itSchedIfWithPallets;168169function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {170  return itSched(name, cb, {requiredPallets: required, ...opts});171}172173export function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {174  (process.env.RUN_XCM_TESTS && !opts.skip175    ? describe176    : describe.skip)(title, fn);177}178179describeXCM.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeXCM(name, fn, {skip: true});180181export function describeGov(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {182  (process.env.RUN_GOV_TESTS && !opts.skip183    ? describe184    : describe.skip)(title, fn);185}186187describeGov.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeGov(name, fn, {skip: true});188189export function sizeOfInt(i: number) {190  if(i < 0 || i > 0xffffffff) throw new Error('out of range');191  if(i < 0b11_1111) {192    return 1;193  } else if(i < 0b11_1111_1111_1111) {194    return 2;195  } else if(i < 0b11_1111_1111_1111_1111_1111_1111_1111) {196    return 4;197  } else {198    return 5;199  }200}201202const UTF8_ENCODER = new TextEncoder();203export function sizeOfEncodedStr(v: string) {204  const encoded = UTF8_ENCODER.encode(v);205  return sizeOfInt(encoded.length) + encoded.length;206}207208export function sizeOfProperty(prop: {key: string, value: string}) {209  return sizeOfEncodedStr(prop.key) + sizeOfEncodedStr(prop.value);210}211212export function makeNames(url: string) {213  const filename = fileURLToPath(url);214  return {215    filename,216    dirname: dirname(filename),217  };218}