git.delta.rocks / unique-network / refs/commits / 02e004a3917b

difftreelog

tests(util): fix mocha setup breaking context in case of dynamically skipped tests

Fahrrader2022-10-13parent: #7c2f408.patch.diff
in: master

2 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -21,23 +21,24 @@
   },
   "mocha": {
     "timeout": 9999999,
-    "require": ["ts-node/register", "./src/util/globalSetup.ts"]
+    "require": ["ts-node/register"]
   },
   "scripts": {
     "lint": "eslint --ext .ts,.js src/",
     "fix": "eslint --ext .ts,.js src/ --fix",
+    "setup": "ts-node ./src/util/globalSetup.ts",
 
-    "test": "mocha --timeout 9999999 -r ts-node/register './src/**/*.*test.ts'",
+    "test": "yarn setup && mocha --timeout 9999999 -r ts-node/register './src/**/*.*test.ts'",
     "testParallelFull": "yarn testParallel && yarn testSequential",
-    "testParallel": "mocha --parallel --timeout 9999999 -r ts-node/register './src/**/*.test.ts'",
-    "testSequential": "mocha --timeout 9999999 -r ts-node/register './src/**/*.seqtest.ts'",
-    "testStructure": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/*.*test.ts",
-    "testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.*test.ts'",
-    "testEthNesting": "mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.*test.ts'",
-    "testEthFractionalizer": "mocha --timeout 9999999 -r ts-node/register './**/eth/fractionalizer/**/*.*test.ts'",
-    "testEthMarketplace": "mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.*test.ts'",
-    "testEvent": "mocha --timeout 9999999 -r ts-node/register ./src/check-event/*.*test.ts",
-    "testRmrk": "mocha --timeout 9999999 -r ts-node/register ./**/rmrk/*.*test.ts",
+    "testParallel": "yarn setup && mocha --parallel --timeout 9999999 -r ts-node/register './src/**/*.test.ts'",
+    "testSequential": "yarn setup && mocha --timeout 9999999 -r ts-node/register './src/**/*.seqtest.ts'",
+    "testStructure": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./**/nesting/*.*test.ts",
+    "testEth": "yarn setup && mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.*test.ts'",
+    "testEthNesting": "yarn setup && mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.*test.ts'",
+    "testEthFractionalizer": "yarn setup && mocha --timeout 9999999 -r ts-node/register './**/eth/fractionalizer/**/*.*test.ts'",
+    "testEthMarketplace": "yarn setup && mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.*test.ts'",
+    "testEvent": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./src/check-event/*.*test.ts",
+    "testRmrk": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./**/rmrk/*.*test.ts",
 
     "testEthPayable": "mocha --timeout 9999999 -r ts-node/register './**/eth/payable.test.ts'",
     "testEthTokenProperties": "mocha --timeout 9999999 -r ts-node/register ./**/eth/tokenProperties.test.ts",
@@ -92,7 +93,7 @@
     "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",
     "testEthFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/fungible.test.ts",
     "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",
-    "testPromotion": "mocha --timeout 9999999 -r ts-node/register ./**/app-promotion.test.ts",
+    "testPromotion": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./**/app-promotion.test.ts",
 
     "testXcmUnique": "RUN_XCM_TESTS=1 mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmUnique.test.ts",
     "testXcmQuartz": "RUN_XCM_TESTS=1 mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmQuartz.test.ts",
modifiedtests/src/util/globalSetup.tsdiffbeforeafterboth
before · tests/src/util/globalSetup.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {usingPlaygrounds, Pallets} from './index';5import * as path from 'path';6import {promises as fs} from 'fs';78// This file is used in the mocha package.json section9export async function mochaGlobalSetup() {10  await usingPlaygrounds(async (helper, privateKey) => {11    try {12      // 1. Create donors for test files13      await fundFilenamesWithRetries(3)14        .then((result) => {15          if (!result) process.exit(1);16        });1718      // 2. Set up App Promotion admin 19      const missingPallets = helper.fetchMissingPalletNames([Pallets.AppPromotion]);20      if (missingPallets.length === 0) {21        const superuser = await privateKey('//Alice');22        const palletAddress = helper.arrange.calculatePalletAddress('appstake');23        const palletAdmin = await privateKey('//PromotionAdmin');24        const api = helper.getApi();25        await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));26        const nominal = helper.balance.getOneTokenNominal();27        await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 1000n * nominal);28        await helper.balance.transferToSubstrate(superuser, palletAddress, 1000n * nominal);29      }30    } catch (error) {31      console.error(error);32      process.exit(1);33    }34  });35}3637async function getFiles(rootPath: string): Promise<string[]> {38  const files = await fs.readdir(rootPath, {withFileTypes: true});39  const filenames: string[] = [];40  for (const entry of files) {41    const res = path.resolve(rootPath, entry.name);42    if (entry.isDirectory()) {43      filenames.push(...await getFiles(res));44    } else {45      filenames.push(res);46    }47  }48  return filenames;49}5051const fundFilenames = async () => {52  await usingPlaygrounds(async (helper, privateKey) => {53    const oneToken = helper.balance.getOneTokenNominal();54    const alice = await privateKey('//Alice');55    const nonce = await helper.chain.getNonce(alice.address);56    const filenames = await getFiles(path.resolve(__dirname, '..'));5758    // batching is actually undesireable, it takes away the time while all the transactions actually succeed59    const batchSize = 300;60    let balanceGrantedCounter = 0;61    for (let b = 0; b < filenames.length; b += batchSize) {62      const tx = [];63      let batchBalanceGrantedCounter = 0;64      for (let i = 0; batchBalanceGrantedCounter < batchSize && b + i < filenames.length; i++) {65        const f = filenames[b + i];66        if (!f.endsWith('.test.ts') && !f.endsWith('seqtest.ts') || f.includes('.outdated')) continue;67        const account = await privateKey({filename: f, ignoreFundsPresence: true});68        const aliceBalance = await helper.balance.getSubstrate(account.address);6970        if (aliceBalance < 100_000n * oneToken) {71          tx.push(helper.executeExtrinsic(72            alice, 73            'api.tx.balances.transfer',74            [account.address, 1_000_000n * oneToken],75            true,76            {nonce: nonce + balanceGrantedCounter++},77          ).then(() => true).catch(() => {console.error(`Transaction to ${path.basename(f)} registered as failed. Strange.`); return false;}));78          batchBalanceGrantedCounter++;79        }80      }8182      if(tx.length > 0) {83        console.log(`Granting funds to ${batchBalanceGrantedCounter} filename accounts.`);84        const result = await Promise.all(tx);85        if (result && result.lastIndexOf(false) > -1) throw new Error('The transactions actually probably succeeded, should check the balances.');86      }87    }8889    if (balanceGrantedCounter == 0) console.log('No account needs additional funding.');90  });91};9293const fundFilenamesWithRetries = async (retriesLeft: number): Promise<boolean> => {94  if (retriesLeft <= 0) return Promise.resolve(false);95  return fundFilenames()96    .then(() => Promise.resolve(true))97    .catch(e => {98      console.error(e);99      console.error(`Some transactions might have failed. ${retriesLeft > 1 ? 'Retrying...' : 'Something is wrong.'}\n`);100      return fundFilenamesWithRetries(--retriesLeft);101    });102};
after · tests/src/util/globalSetup.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {usingPlaygrounds, Pallets} from './index';5import * as path from 'path';6import {promises as fs} from 'fs';78// This function should be called before running test suites.9const globalSetup = async (): Promise<void> => {10  await usingPlaygrounds(async (helper, privateKey) => {11    try {12      // 1. Create donors for test files13      await fundFilenamesWithRetries(3)14        .then((result) => {15          if (!result) Promise.reject();16        });1718      // 2. Set up App Promotion admin 19      const missingPallets = helper.fetchMissingPalletNames([Pallets.AppPromotion]);20      if (missingPallets.length === 0) {21        const superuser = await privateKey('//Alice');22        const palletAddress = helper.arrange.calculatePalletAddress('appstake');23        const palletAdmin = await privateKey('//PromotionAdmin');24        const api = helper.getApi();25        await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));26        const nominal = helper.balance.getOneTokenNominal();27        await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 1000n * nominal);28        await helper.balance.transferToSubstrate(superuser, palletAddress, 1000n * nominal);29      }30    } catch (error) {31      console.error(error);32      Promise.reject();33    }34  });35};3637async function getFiles(rootPath: string): Promise<string[]> {38  const files = await fs.readdir(rootPath, {withFileTypes: true});39  const filenames: string[] = [];40  for (const entry of files) {41    const res = path.resolve(rootPath, entry.name);42    if (entry.isDirectory()) {43      filenames.push(...await getFiles(res));44    } else {45      filenames.push(res);46    }47  }48  return filenames;49}5051const fundFilenames = async () => {52  await usingPlaygrounds(async (helper, privateKey) => {53    const oneToken = helper.balance.getOneTokenNominal();54    const alice = await privateKey('//Alice');55    const nonce = await helper.chain.getNonce(alice.address);56    const filenames = await getFiles(path.resolve(__dirname, '..'));5758    // batching is actually undesireable, it takes away the time while all the transactions actually succeed59    const batchSize = 300;60    let balanceGrantedCounter = 0;61    for (let b = 0; b < filenames.length; b += batchSize) {62      const tx = [];63      let batchBalanceGrantedCounter = 0;64      for (let i = 0; batchBalanceGrantedCounter < batchSize && b + i < filenames.length; i++) {65        const f = filenames[b + i];66        if (!f.endsWith('.test.ts') && !f.endsWith('seqtest.ts') || f.includes('.outdated')) continue;67        const account = await privateKey({filename: f, ignoreFundsPresence: true});68        const aliceBalance = await helper.balance.getSubstrate(account.address);6970        if (aliceBalance < 100_000n * oneToken) {71          tx.push(helper.executeExtrinsic(72            alice, 73            'api.tx.balances.transfer',74            [account.address, 1_000_000n * oneToken],75            true,76            {nonce: nonce + balanceGrantedCounter++},77          ).then(() => true).catch(() => {console.error(`Transaction to ${path.basename(f)} registered as failed. Strange.`); return false;}));78          batchBalanceGrantedCounter++;79        }80      }8182      if(tx.length > 0) {83        console.log(`Granting funds to ${batchBalanceGrantedCounter} filename accounts.`);84        const result = await Promise.all(tx);85        if (result && result.lastIndexOf(false) > -1) throw new Error('The transactions actually probably succeeded, should check the balances.');86      }87    }8889    if (balanceGrantedCounter == 0) console.log('No account needs additional funding.');90  });91};9293const fundFilenamesWithRetries = async (retriesLeft: number): Promise<boolean> => {94  if (retriesLeft <= 0) return Promise.resolve(false);95  return fundFilenames()96    .then(() => Promise.resolve(true))97    .catch(e => {98      console.error(e);99      console.error(`Some transactions might have failed. ${retriesLeft > 1 ? 'Retrying...' : 'Something is wrong.'}\n`);100      return fundFilenamesWithRetries(--retriesLeft);101    });102};103104globalSetup().catch(() => process.exit(1));