git.delta.rocks / unique-network / refs/commits / a797a1d4ce63

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.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 MINIMUM_DONOR_FUND = 4_000_000n;93export const DONOR_FUNDING = 4_000_000n;9495// App-promotion periods:96export const LOCKING_PERIOD = 12n; // 12 blocks of relay97export const UNLOCKING_PERIOD = 6n; // 6 blocks of parachain9899// Native contracts100export const COLLECTION_HELPER = '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f';101export const CONTRACT_HELPER = '0x842899ECF380553E8a4de75bF534cdf6fBF64049';102103export enum Pallets {104  Inflation = 'inflation',105  ReFungible = 'refungible',106  Fungible = 'fungible',107  NFT = 'nonfungible',108  Scheduler = 'scheduler',109  UniqueScheduler = 'uniqueScheduler',110  AppPromotion = 'apppromotion',111  CollatorSelection = 'collatorselection',112  Session = 'session',113  Identity = 'identity',114  Democracy = 'democracy',115  Council = 'council',116  //CouncilMembership = 'councilmembership',117  TechnicalCommittee = 'technicalcommittee',118  Fellowship = 'fellowshipcollective',119  Preimage = 'preimage',120  Maintenance = 'maintenance',121  TestUtils = 'testutils',122}123124export function requirePalletsOrSkip(test: Context, helper: DevUniqueHelper, requiredPallets: readonly string[]) {125  const missingPallets = helper.fetchMissingPalletNames(requiredPallets);126127  if(missingPallets.length > 0) {128    const skipMsg = `\tSkipping test '${test.test?.title}'.\n\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;129    console.warn('\x1b[38:5:208m%s\x1b[0m', skipMsg);130    test.skip();131  }132}133134export function itSub(name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: readonly string[] } = {}) {135  (opts.only ? it.only :136    opts.skip ? it.skip : it)(name, async function () {137    await usingPlaygrounds(async (helper, privateKey) => {138      if(opts.requiredPallets) {139        requirePalletsOrSkip(this, helper, opts.requiredPallets);140      }141142      await cb({helper, privateKey});143    });144  });145}146export 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[] } = {}) {147  return itSub(name, cb, {requiredPallets: required, ...opts});148}149itSub.only = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSub(name, cb, {only: true});150itSub.skip = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSub(name, cb, {skip: true});151152itSubIfWithPallet.only = (name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {only: true});153itSubIfWithPallet.skip = (name: string, required: readonly string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});154itSub.ifWithPallets = itSubIfWithPallet;155156export type SchedKind = 'anon' | 'named';157158export function itSched(159  name: string,160  cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any,161  opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},162) {163  itSub(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);164  itSub(name + ' (named scheduling)', (apis) => cb('named', apis), opts);165}166itSched.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {only: true});167itSched.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {skip: true});168itSched.ifWithPallets = itSchedIfWithPallets;169170function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {171  return itSched(name, cb, {requiredPallets: required, ...opts});172}173174export function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {175  (process.env.RUN_XCM_TESTS && !opts.skip176    ? describe177    : describe.skip)(title, fn);178}179180describeXCM.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeXCM(name, fn, {skip: true});181182export function describeGov(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {183  (process.env.RUN_GOV_TESTS && !opts.skip184    ? describe185    : describe.skip)(title, fn);186}187188describeGov.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeGov(name, fn, {skip: true});189190export function sizeOfInt(i: number) {191  if(i < 0 || i > 0xffffffff) throw new Error('out of range');192  if(i < 0b11_1111) {193    return 1;194  } else if(i < 0b11_1111_1111_1111) {195    return 2;196  } else if(i < 0b11_1111_1111_1111_1111_1111_1111_1111) {197    return 4;198  } else {199    return 5;200  }201}202203const UTF8_ENCODER = new TextEncoder();204export function sizeOfEncodedStr(v: string) {205  const encoded = UTF8_ENCODER.encode(v);206  return sizeOfInt(encoded.length) + encoded.length;207}208209export function sizeOfProperty(prop: {key: string, value: string}) {210  return sizeOfEncodedStr(prop.key) + sizeOfEncodedStr(prop.value);211}212213export function makeNames(url: string) {214  const filename = fileURLToPath(url);215  return {216    filename,217    dirname: dirname(filename),218  };219}