git.delta.rocks / unique-network / refs/commits / 17703e6a9d58

difftreelog

source

tests/src/util/index.ts11.2 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, DevPolkadexHelper} from './playgrounds/unique.dev';15import {dirname} from 'path';16import {fileURLToPath} from 'url';1718chai.config.truncateThreshold = 0;19chai.use(chaiAsPromised);20chai.use(chaiSubset);21export const expect = chai.expect;2223const getTestHash = (filename: string) => crypto.createHash('md5').update(filename).digest('hex');2425export const getTestSeed = (filename: string) => `//Alice+${getTestHash(filename)}`;2627async function usingPlaygroundsGeneral<T extends ChainHelperBase, R = void>(28  helperType: new (logger: ILogger) => T,29  url: string,30  code: (helper: T, privateKey: (seed: string | { filename?: string, url?: string, ignoreFundsPresence?: boolean }) => Promise<IKeyringPair>) => Promise<R>,31): Promise<R> {32  const silentConsole = new SilentConsole();33  silentConsole.enable();3435  const helper = new helperType(new SilentLogger());36  let result;37  try {38    await helper.connect(url);39    const ss58Format = helper.chain.getChainProperties().ss58Format;40    const privateKey = async (seed: string | {filename?: string, url?: string, ignoreFundsPresence?: boolean}) => {41      if(typeof seed === 'string') {42        return helper.util.fromSeed(seed, ss58Format);43      }44      if(seed.url) {45        const {filename} = makeNames(seed.url);46        seed.filename = filename;47      } else if(seed.filename) {48        // Pass49      } else {50        throw new Error('no url nor filename set');51      }52      const actualSeed = getTestSeed(seed.filename);53      let account = helper.util.fromSeed(actualSeed, ss58Format);54      // here's to hoping that no55      if(!seed.ignoreFundsPresence && ((helper as any)['balance'] == undefined || await (helper as any).balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND)) {56        console.warn(`${path.basename(seed.filename)}: Not enough funds present on the filename account. Using the default one as the donor instead.`);57        account = helper.util.fromSeed('//Alice', ss58Format);58      }59      return account;60    };61    result = await code(helper, privateKey);62  }63  finally {64    await helper.disconnect();65    silentConsole.disable();66  }67  return result as any as R;68}6970export 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);7172export const usingWestmintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevWestmintHelper>(DevWestmintHelper, url, code);7374export const usingStateminePlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevStatemineHelper>(DevWestmintHelper, url, code);7576export const usingStatemintPlaygrounds = (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevStatemintHelper>(DevWestmintHelper, url, code);7778export const usingRelayPlaygrounds = (url: string, code: (helper: DevRelayHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevRelayHelper>(DevRelayHelper, url, code);7980export const usingAcalaPlaygrounds = (url: string, code: (helper: DevAcalaHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevAcalaHelper>(DevAcalaHelper, url, code);8182export const usingKaruraPlaygrounds = (url: string, code: (helper: DevKaruraHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevKaruraHelper>(DevAcalaHelper, url, code);8384export const usingMoonbeamPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevMoonbeamHelper>(DevMoonbeamHelper, url, code);8586export const usingMoonriverPlaygrounds = (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevMoonriverHelper>(DevMoonriverHelper, url, code);8788export const usingAstarPlaygrounds = (url: string, code: (helper: DevAstarHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevAstarHelper>(DevAstarHelper, url, code);8990export const usingShidenPlaygrounds = (url: string, code: (helper: DevShidenHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevShidenHelper>(DevShidenHelper, url, code);9192export const usingPolkadexPlaygrounds = (url: string, code: (helper: DevPolkadexHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => usingPlaygroundsGeneral<DevPolkadexHelper>(DevPolkadexHelper, url, code);9394export const MINIMUM_DONOR_FUND = 4_000_000n;95export const DONOR_FUNDING = 4_000_000n;9697// App-promotion periods:98export const LOCKING_PERIOD = 12n; // 12 blocks of relay99export const UNLOCKING_PERIOD = 6n; // 6 blocks of parachain100101// Native contracts102export const COLLECTION_HELPER = '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f';103export const CONTRACT_HELPER = '0x842899ECF380553E8a4de75bF534cdf6fBF64049';104105export enum Pallets {106  Inflation = 'inflation',107  ReFungible = 'refungible',108  Fungible = 'fungible',109  NFT = 'nonfungible',110  Scheduler = 'scheduler',111  UniqueScheduler = 'uniqueScheduler',112  AppPromotion = 'apppromotion',113  CollatorSelection = 'collatorselection',114  Session = 'session',115  Identity = 'identity',116  Democracy = 'democracy',117  Council = 'council',118  //CouncilMembership = 'councilmembership',119  TechnicalCommittee = 'technicalcommittee',120  Fellowship = 'fellowshipcollective',121  Preimage = 'preimage',122  Maintenance = 'maintenance',123  TestUtils = 'testutils',124}125126export function requirePalletsOrSkip(test: Context, helper: DevUniqueHelper, requiredPallets: readonly string[]) {127  const missingPallets = helper.fetchMissingPalletNames(requiredPallets);128129  if(missingPallets.length > 0) {130    const skipMsg = `\tSkipping test '${test.test?.title}'.\n\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;131    console.warn('\x1b[38:5:208m%s\x1b[0m', skipMsg);132    test.skip();133  }134}135136export function itSub(name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: readonly string[] } = {}) {137  (opts.only ? it.only :138    opts.skip ? it.skip : it)(name, async function () {139    await usingPlaygrounds(async (helper, privateKey) => {140      if(opts.requiredPallets) {141        requirePalletsOrSkip(this, helper, opts.requiredPallets);142      }143144      await cb({helper, privateKey});145    });146  });147}148export 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[] } = {}) {149  return itSub(name, cb, {requiredPallets: required, ...opts});150}151itSub.only = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSub(name, cb, {only: true});152itSub.skip = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSub(name, cb, {skip: true});153154itSubIfWithPallet.only = (name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {only: true});155itSubIfWithPallet.skip = (name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});156itSub.ifWithPallets = itSubIfWithPallet;157158export type SchedKind = 'anon' | 'named';159160export function itSched(161  name: string,162  cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any,163  opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},164) {165  itSub(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);166  itSub(name + ' (named scheduling)', (apis) => cb('named', apis), opts);167}168itSched.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {only: true});169itSched.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {skip: true});170itSched.ifWithPallets = itSchedIfWithPallets;171172function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {173  return itSched(name, cb, {requiredPallets: required, ...opts});174}175176export function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {177  (process.env.RUN_XCM_TESTS && !opts.skip178    ? describe179    : describe.skip)(title, fn);180}181182describeXCM.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeXCM(name, fn, {skip: true});183184export function describeGov(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {185  (process.env.RUN_GOV_TESTS && !opts.skip186    ? describe187    : describe.skip)(title, fn);188}189190describeGov.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeGov(name, fn, {skip: true});191192export function sizeOfInt(i: number) {193  if(i < 0 || i > 0xffffffff) throw new Error('out of range');194  if(i < 0b11_1111) {195    return 1;196  } else if(i < 0b11_1111_1111_1111) {197    return 2;198  } else if(i < 0b11_1111_1111_1111_1111_1111_1111_1111) {199    return 4;200  } else {201    return 5;202  }203}204205const UTF8_ENCODER = new TextEncoder();206export function sizeOfEncodedStr(v: string) {207  const encoded = UTF8_ENCODER.encode(v);208  return sizeOfInt(encoded.length) + encoded.length;209}210211export function sizeOfProperty(prop: {key: string, value: string}) {212  return sizeOfEncodedStr(prop.key) + sizeOfEncodedStr(prop.value);213}214215export function makeNames(url: string) {216  const filename = fileURLToPath(url);217  return {218    filename,219    dirname: dirname(filename),220  };221}