difftreelog
Fix tests
in: master
Add waiter function Remove global before script Remove useless logs Fix refungible tests
3 files changed
tests/src/app-promotion.test.tsdiffbeforeafterboth--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -28,6 +28,7 @@
import {encodeAddress} from '@polkadot/util-crypto';
import {stringToU8a} from '@polkadot/util';
import {SponsoringMode, contractHelpers, createEthAccountWithBalance, deployFlipper, itWeb3, transferBalanceToEth} from './eth/util/helpers';
+import {DevUniqueHelper} from './util/playgrounds/unique.dev';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -40,9 +41,9 @@
const UNLOCKING_PERIOD = 10n; // 20 blocks of parachain
const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);
-before(async function () {
+const beforeEach = async (context: Mocha.Context) => {
await usingPlaygrounds(async (helper, privateKey) => {
- if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();
+ if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) context.skip();
alice = privateKey('//Alice');
palletAdmin = privateKey('//Charlie'); // TODO use custom address
await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
@@ -51,9 +52,13 @@
await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);
accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests
});
-});
+};
describe('app-promotions.stake extrinsic', () => {
+ before(async function () {
+ await beforeEach(this);
+ });
+
it('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async () => {
await usingPlaygrounds(async (helper) => {
const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
@@ -128,6 +133,10 @@
});
describe('unstake balance extrinsic', () => {
+ before(async function () {
+ await beforeEach(this);
+ });
+
it('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async () => {
await usingPlaygrounds(async helper => {
const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
@@ -247,6 +256,10 @@
});
describe('Admin adress', () => {
+ before(async function () {
+ await beforeEach(this);
+ });
+
it('can be set by sudo only', async () => {
await usingPlaygrounds(async (helper) => {
const nonAdmin = accounts.pop()!;
@@ -291,6 +304,7 @@
describe('App-promotion collection sponsoring', () => {
before(async function () {
+ await beforeEach(this);
await usingPlaygrounds(async (helper) => {
const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
await helper.signTransaction(alice, tx);
@@ -394,6 +408,10 @@
});
describe('app-promotion stopSponsoringCollection', () => {
+ before(async function () {
+ await beforeEach(this);
+ });
+
it('can not be called by non-admin', async () => {
await usingPlaygrounds(async (helper) => {
const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
@@ -450,6 +468,10 @@
});
describe('app-promotion contract sponsoring', () => {
+ before(async function () {
+ await beforeEach(this);
+ });
+
itWeb3('should set palletes address as a sponsor', async ({api, web3, privateKeyWrapper}) => {
await usingPlaygrounds(async (helper) => {
const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
@@ -570,6 +592,10 @@
});
describe('app-promotion stopSponsoringContract', () => {
+ before(async function () {
+ await beforeEach(this);
+ });
+
itWeb3('should remove pallet address from contract sponsors', async ({api, web3, privateKeyWrapper}) => {
await usingPlaygrounds(async (helper) => {
const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -624,6 +650,10 @@
});
describe('app-promotion rewards', () => {
+ before(async function () {
+ await beforeEach(this);
+ });
+
it('can not be called by non admin', async () => {
await usingPlaygrounds(async (helper) => {
const nonAdmin = accounts.pop()!;
@@ -634,11 +664,13 @@
it('should credit 0.05% for staking period', async () => {
await usingPlaygrounds(async helper => {
const staker = accounts.pop()!;
+
+ await waitPromotionPeriodDoesntEnd(helper);
await helper.staking.stake(staker, 100n * nominal);
await helper.staking.stake(staker, 200n * nominal);
- // wair rewards are available:
+ // wait rewards are available:
const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[1][0];
await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock));
@@ -688,7 +720,6 @@
});
it('should bring compound interest', async () => {
- // TODO flaky test
await usingPlaygrounds(async helper => {
const staker = accounts.pop()!;
@@ -756,3 +787,14 @@
return calculateIncome(income, calcPeriod, iter - 1);
} else return income;
}
+
+// Wait while promotion period less than specified block, to avoid boundary cases
+// 0 if this should be the beginning of the period.
+async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {
+ const relayBlockNumber = (await helper.api!.query.parachainSystem.validationData()).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();
+ const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;
+
+ if (currentPeriodBlock > waitBlockLessThan) {
+ await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);
+ }
+}
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -245,8 +245,8 @@
section: 'common',
index: '0x4202',
data: [
- collection.collectionId.toString(),
- token.tokenId.toString(),
+ helper.api!.createType('u32', collection.collectionId).toHuman(),
+ helper.api!.createType('u32', token.tokenId).toHuman(),
{Substrate: alice.address},
'100',
],
@@ -265,8 +265,8 @@
section: 'common',
index: '0x4203',
data: [
- collection.collectionId.toString(),
- token.tokenId.toString(),
+ helper.api!.createType('u32', collection.collectionId).toHuman(),
+ helper.api!.createType('u32', token.tokenId).toHuman(),
{Substrate: alice.address},
'50',
],
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth1// 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 {IKeyringPair} from '@polkadot/types/types';91011export class SilentLogger {12 log(_msg: any, _level: any): void { }13 level = {14 ERROR: 'ERROR' as const,15 WARNING: 'WARNING' as const,16 INFO: 'INFO' as const,17 };18}1920export class SilentConsole {21 // TODO: Remove, this is temporary: Filter unneeded API output22 // (Jaco promised it will be removed in the next version)23 consoleErr: any;24 consoleLog: any;25 consoleWarn: any;2627 constructor() {28 this.consoleErr = console.error;29 this.consoleLog = console.log;30 this.consoleWarn = console.warn;31 }3233 enable() { 34 const outFn = (printer: any) => (...args: any[]) => {35 for (const arg of args) {36 if (typeof arg !== 'string')37 continue;38 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')39 return;40 }41 printer(...args);42 };43 44 console.error = outFn(this.consoleErr.bind(console));45 console.log = outFn(this.consoleLog.bind(console));46 console.warn = outFn(this.consoleWarn.bind(console));47 }4849 disable() {50 console.error = this.consoleErr;51 console.log = this.consoleLog;52 console.warn = this.consoleWarn;53 }54}555657export class DevUniqueHelper extends UniqueHelper {58 /**59 * Arrange methods for tests60 */61 arrange: ArrangeGroup;62 wait: WaitGroup;6364 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {65 super(logger);66 this.arrange = new ArrangeGroup(this);67 this.wait = new WaitGroup(this);68 }6970 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {71 const wsProvider = new WsProvider(wsEndpoint);72 this.api = new ApiPromise({73 provider: wsProvider,74 signedExtensions: {75 ContractHelpers: {76 extrinsic: {},77 payload: {},78 },79 FakeTransactionFinalizer: {80 extrinsic: {},81 payload: {},82 },83 },84 rpc: {85 unique: defs.unique.rpc,86 appPromotion: defs.appPromotion.rpc,87 rmrk: defs.rmrk.rpc,88 eth: {89 feeHistory: {90 description: 'Dummy',91 params: [],92 type: 'u8',93 },94 maxPriorityFeePerGas: {95 description: 'Dummy',96 params: [],97 type: 'u8',98 },99 },100 },101 });102 await this.api.isReadyOrError;103 this.network = await UniqueHelper.detectNetwork(this.api);104 }105}106107class ArrangeGroup {108 helper: UniqueHelper;109110 constructor(helper: UniqueHelper) {111 this.helper = helper;112 }113114 /**115 * Generates accounts with the specified UNQ token balance 116 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.117 * @param donor donor account for balances118 * @returns array of newly created accounts119 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 120 */121 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {122 let nonce = await this.helper.chain.getNonce(donor.address);123 const tokenNominal = this.helper.balance.getOneTokenNominal();124 const transactions = [];125 const accounts: IKeyringPair[] = [];126 for (const balance of balances) {127 const recepient = this.helper.util.fromSeed(mnemonicGenerate());128 accounts.push(recepient);129 if (balance !== 0n) {130 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, balance * tokenNominal]);131 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));132 nonce++;133 }134 }135136 await Promise.all(transactions).catch(_e => {});137 138 //#region TODO remove this region, when nonce problem will be solved139 const checkBalances = async () => {140 let isSuccess = true;141 for (let i = 0; i < balances.length; i++) {142 const balance = await this.helper.balance.getSubstrate(accounts[i].address);143 if (balance !== balances[i] * tokenNominal) {144 isSuccess = false;145 break;146 }147 }148 return isSuccess;149 };150151 let accountsCreated = false;152 // checkBalances retry up to 5 blocks153 for (let index = 0; index < 5; index++) {154 accountsCreated = await checkBalances();155 if(accountsCreated) break;156 157 }158159 if (!accountsCreated) throw Error('Accounts generation failed');160 //#endregion161162 return accounts;163 };164165 // TODO combine this method and createAccounts into one166 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 167 const createAsManyAsCan = async () => {168 let transactions: any = [];169 const accounts: IKeyringPair[] = [];170 let nonce = await this.helper.chain.getNonce(donor.address);171 const tokenNominal = this.helper.balance.getOneTokenNominal();172 for (let i = 0; i < accountsToCreate; i++) {173 if (i === 500) { // if there are too many accounts to create174 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 175 transactions = []; //176 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 177 }178 const recepient = this.helper.util.fromSeed(mnemonicGenerate());179 accounts.push(recepient);180 if (withBalance !== 0n) {181 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);182 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));183 nonce++;184 }185 }186 187 const fullfilledAccounts = [];188 await Promise.allSettled(transactions);189 for (const account of accounts) {190 const accountBalance = await this.helper.balance.getSubstrate(account.address);191 if (accountBalance === withBalance * tokenNominal) {192 fullfilledAccounts.push(account);193 }194 }195 return fullfilledAccounts;196 };197198 199 const crowd: IKeyringPair[] = [];200 // do up to 5 retries201 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {202 const asManyAsCan = await createAsManyAsCan();203 crowd.push(...asManyAsCan);204 accountsToCreate -= asManyAsCan.length;205 }206207 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);208209 return crowd;210 };211212 isDevNode = async () => {213 const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));214 const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));215 const findCreationDate = async (block: any) => {216 const humanBlock = block.toHuman();217 let date;218 humanBlock.block.extrinsics.forEach((ext: any) => {219 if(ext.method.section === 'timestamp') {220 date = Number(ext.method.args.now.replaceAll(',', ''));221 }222 });223 return date;224 };225 const block1date = await findCreationDate(block1);226 const block2date = await findCreationDate(block2);227 if(block2date! - block1date! < 9000) return true;228 };229}230231class WaitGroup {232 helper: UniqueHelper;233234 constructor(helper: UniqueHelper) {235 this.helper = helper;236 }237238 /**239 * Wait for specified bnumber of blocks240 * @param blocksCount number of blocks to wait241 * @returns 242 */243 async newBlocks(blocksCount = 1): Promise<void> {244 // eslint-disable-next-line no-async-promise-executor245 const promise = new Promise<void>(async (resolve) => {246 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {247 if (blocksCount > 0) {248 blocksCount--;249 } else {250 unsubscribe();251 resolve();252 }253 });254 });255 return promise;256 }257258 async forParachainBlockNumber(blockNumber: bigint) {259 return new Promise<void>(async (resolve) => {260 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {261 if (data.number.toNumber() >= blockNumber) {262 unsubscribe();263 resolve();264 }265 });266 });267 }268 269 async forRelayBlockNumber(blockNumber: bigint) {270 return new Promise<void>(async (resolve) => {271 const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {272 if (data.value.relayParentNumber.toNumber() >= blockNumber) {273 // @ts-ignore274 unsubscribe();275 resolve();276 }277 });278 });279 }280}