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

difftreelog

test SilentConsole cls instead of multiple decorations

Andrey2022-09-04parent: #c9f3344.patch.diff
in: master

4 files changed

modifiedtests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/index.ts
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -6,7 +6,7 @@
 import config from '../../../config';
 
 import {EthUniqueHelper} from './unique.dev';
-import {SilentLogger} from '../../../util/playgrounds/unique.dev';
+import {SilentLogger, SilentConsole} from '../../../util/playgrounds/unique.dev';
 
 export {EthUniqueHelper} from './unique.dev';
 
@@ -16,25 +16,9 @@
 export const expect = chai.expect;
 
 export const usingEthPlaygrounds = async (code: (helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
-  // TODO: Remove, this is temporary: Filter unneeded API output
-  // (Jaco promised it will be removed in the next version)
-  const consoleErr = console.error;
-  const consoleLog = console.log;
-  const consoleWarn = console.warn;
-
-  const outFn = (printer: any) => (...args: any[]) => {
-    for (const arg of args) {
-      if (typeof arg !== 'string')
-        continue;
-      if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
-        return;
-    }
-    printer(...args);
-  };
+  const silentConsole = new SilentConsole();
+  silentConsole.enable();
 
-  console.error = outFn(consoleErr.bind(console));
-  console.log = outFn(consoleLog.bind(console));
-  console.warn = outFn(consoleWarn.bind(console));
   const helper = new EthUniqueHelper(new SilentLogger());
 
   try {
@@ -47,9 +31,7 @@
   finally {
     await helper.disconnect();
     await helper.disconnectWeb3();
-    console.error = consoleErr;
-    console.log = consoleLog;
-    console.warn = consoleWarn;
+    silentConsole.disable();
   }
 }
   
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -25,6 +25,8 @@
 import privateKey from './privateKey';
 import promisifySubstrate from './promisify-substrate';
 
+import {SilentConsole} from '../util/playgrounds/unique.dev';
+
 
 
 function defaultApiOptions(): ApiOptions {
@@ -74,26 +76,9 @@
   settings = settings || defaultApiOptions();
   const api: ApiPromise = new ApiPromise(settings);
   let result: T = null as unknown as T;
-
-  // TODO: Remove, this is temporary: Filter unneeded API output
-  // (Jaco promised it will be removed in the next version)
-  const consoleErr = console.error;
-  const consoleLog = console.log;
-  const consoleWarn = console.warn;
 
-  const outFn = (printer: any) => (...args: any[]) => {
-    for (const arg of args) {
-      if (typeof arg !== 'string')
-        continue;
-      if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))
-        return;
-    }
-    printer(...args);
-  };
-
-  console.error = outFn(consoleErr.bind(console));
-  console.log = outFn(consoleLog.bind(console));
-  console.warn = outFn(consoleWarn.bind(console));
+  const silentConsole = new SilentConsole();
+  silentConsole.enable();
 
   try {
     await promisifySubstrate(api, async () => {
@@ -106,9 +91,7 @@
     })();
   } finally {
     await api.disconnect();
-    console.error = consoleErr;
-    console.log = consoleLog;
-    console.warn = consoleWarn;
+    silentConsole.disable();
   }
   return result as T;
 }
modifiedtests/src/util/playgrounds/index.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -4,37 +4,13 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import config from '../../config';
 import '../../interfaces/augment-api-events';
-import {DevUniqueHelper} from './unique.dev';
+import {DevUniqueHelper, SilentLogger, SilentConsole} from './unique.dev';
 
-class SilentLogger {
-  log(msg: any, level: any): void { }
-  level = {
-    ERROR: 'ERROR' as const,
-    WARNING: 'WARNING' as const,
-    INFO: 'INFO' as const,
-  };
-}
 
 export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
-  // TODO: Remove, this is temporary: Filter unneeded API output
-  // (Jaco promised it will be removed in the next version)
-  const consoleErr = console.error;
-  const consoleLog = console.log;
-  const consoleWarn = console.warn;
+  const silentConsole = new SilentConsole();
+  silentConsole.enable();
 
-  const outFn = (printer: any) => (...args: any[]) => {
-    for (const arg of args) {
-      if (typeof arg !== 'string')
-        continue;
-      if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))
-        return;
-    }
-    printer(...args);
-  };
-
-  console.error = outFn(consoleErr.bind(console));
-  console.log = outFn(consoleLog.bind(console));
-  console.warn = outFn(consoleWarn.bind(console));
   const helper = new DevUniqueHelper(new SilentLogger());
 
   try {
@@ -45,8 +21,6 @@
   }
   finally {
     await helper.disconnect();
-    console.error = consoleErr;
-    console.log = consoleLog;
-    console.warn = consoleWarn;
+    silentConsole.disable();
   }
 };
\ No newline at end of file
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {mnemonicGenerate} from '@polkadot/util-crypto';5import {UniqueHelper} from './unique';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {TSigner} from './types';9import {IKeyringPair} from '@polkadot/types/types';101112export class DevUniqueHelper extends UniqueHelper {13  /**14   * Arrange methods for tests15   */16  arrange: ArrangeGroup;1718  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {19    super(logger);20    this.arrange = new ArrangeGroup(this);21  }2223  async connect(wsEndpoint: string, listeners?: any): Promise<void> {24    const wsProvider = new WsProvider(wsEndpoint);25    this.api = new ApiPromise({26      provider: wsProvider,27      signedExtensions: {28        ContractHelpers: {29          extrinsic: {},30          payload: {},31        },32        FakeTransactionFinalizer: {33          extrinsic: {},34          payload: {},35        },36      },37      rpc: {38        unique: defs.unique.rpc,39        rmrk: defs.rmrk.rpc,40        eth: {41          feeHistory: {42            description: 'Dummy',43            params: [],44            type: 'u8',45          },46          maxPriorityFeePerGas: {47            description: 'Dummy',48            params: [],49            type: 'u8',50          },51        },52      },53    });54    await this.api.isReadyOrError;55    this.network = await UniqueHelper.detectNetwork(this.api);56  }57}5859class ArrangeGroup {60  helper: UniqueHelper;6162  constructor(helper: UniqueHelper) {63    this.helper = helper;64  }6566  /**67   * Generates accounts with the specified UNQ token balance 68   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.69   * @param donor donor account for balances70   * @returns array of newly created accounts71   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 72   */73  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {74    let nonce = await this.helper.chain.getNonce(donor.address);75    const tokenNominal = this.helper.balance.getOneTokenNominal();76    const transactions = [];77    const accounts: IKeyringPair[] = [];78    for (const balance of balances) {79      const recepient = this.helper.util.fromSeed(mnemonicGenerate());80      accounts.push(recepient);81      if (balance !== 0n) {82        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, balance * tokenNominal]);83        transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));84        nonce++;85      }86    }8788    await Promise.all(transactions).catch(e => {});89    90    //#region TODO remove this region, when nonce problem will be solved91    const checkBalances = async () => {92      let isSuccess = true;93      for (let i = 0; i < balances.length; i++) {94        const balance = await this.helper.balance.getSubstrate(accounts[i].address);95        if (balance !== balances[i] * tokenNominal) {96          isSuccess = false;97          break;98        }99      }100      return isSuccess;101    };102103    let accountsCreated = false;104    // checkBalances retry up to 5 blocks105    for (let index = 0; index < 5; index++) {106      console.log(await this.helper.chain.getLatestBlockNumber());107      accountsCreated = await checkBalances();108      if(accountsCreated) break;109      await this.waitNewBlocks(1);110    }111112    if (!accountsCreated) throw Error('Accounts generation failed');113    //#endregion114115    return accounts;116  };117118  /**119   * Wait for specified bnumber of blocks120   * @param blocksCount number of blocks to wait121   * @returns 122   */123  async waitNewBlocks(blocksCount = 1): Promise<void> {124    const promise = new Promise<void>(async (resolve) => {125      const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {126        if (blocksCount > 0) {127          blocksCount--;128        } else {129          unsubscribe();130          resolve();131        }132      });133    });134    return promise;135  }136}