Reorganize test setup (#1132)

* Moved all e2e tests to 'api' folder

* Moved metadata test

* fix imports

* Add jest options for testing the different endpoint types separately

* Add check for empty test suites and return empt test to prevent jest from throwing an error

* Fix import paths

* Fix const tests for polkadot chains

* Update to latest Substrate 2.0 image

* Move contract files for e2e testing to e2e tesing folder

* reorder & fix promise query tests for all test nodes

* final fixes for promise query

* eslint fixes

* removed trailing space

* fix linting errors

* Address codeclimate "Function getWsEndpoints has a Cognitive Complexity of 7 (exceeds 5 allowed)."

* Fix contract ABI import paths

* linter endpoint types

* replace alice with alice_stash

* split off promise-queries file

* Remove apiType, smaller cleanups, added local to only: [] tests suites

* relative paths changed to `@polkadot` import

* moved contract wasm & abi's back to `api-contract`
This commit is contained in:
Stefanie Doll
2019-07-16 16:03:53 +02:00
committed by GitHub
parent 25e9805622
commit d57dca53f4
23 changed files with 533 additions and 469 deletions
@@ -0,0 +1,213 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import ApiPromise from '@polkadot/api/promise/Api';
import testingPairs from '@polkadot/keyring/testingPairs';
import { WsProvider } from '@polkadot/rpc-provider';
import { RewardDestination } from '@polkadot/types';
import { SubmittableResult } from '@polkadot/api';
import { HeaderExtended } from '@polkadot/api-derive/type';
import { DerivedBalances, DerivedFees, DerivedSessionInfo, DerivedStaking } from '@polkadot/api-derive/types';
const ALICE_STASH = testingPairs().alice_stash.address;
const WS = 'ws://127.0.0.1:9944/';
describe.skip('derive e2e', (): void => {
let api: ApiPromise;
beforeAll((): void => {
jest.setTimeout(30000);
});
beforeEach(async (done): Promise<void> => {
api = await ApiPromise.create(new WsProvider(WS));
done();
});
it('returns correct results', async (): Promise<void> => {
// https://github.com/polkadot-js/api/issues/777
const block1 = await api.derive.chain.bestNumber();
await new Promise((resolve): void => {
setTimeout(resolve, 15000);
});
const block2 = await api.derive.chain.bestNumber();
expect(block1.eq(block2)).toBe(false);
});
it('subscribes to newHead, retrieving the actual validator', (done): Promise<() => void> => {
return api.derive.chain.subscribeNewHead(({ author }: HeaderExtended): void => {
console.log('author', author && author.toString());
if (author) {
done();
}
});
});
it('retrieves the fees (api.queryMulti)', (done): Promise<() => void> => {
return api.derive.balances.fees((fees: DerivedFees): void => {
console.error('fees', JSON.stringify(fees));
done();
});
});
it('retrieves the balances', (done): Promise<() => void> => {
return api.derive.balances.all('5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y', (balance: DerivedBalances): void => {
console.error(JSON.stringify(balance));
if (balance.freeBalance.gtn(1)) {
done();
}
});
});
it('retrieves balances for a problematic account', (done): Promise<() => void> => {
return api.derive.balances.all('5F7BJL6Z4m8RLtK7nXEqqpEqhBbd535Z3CZeYF6ccvaQAY6N', (balance: DerivedBalances): void => {
console.error(JSON.stringify(balance));
if (balance.availableBalance.eqn(0)) {
done();
}
});
});
it('retrieves all session info', (done): Promise<() => void> => {
let count = 0;
return api.derive.session.info((info: DerivedSessionInfo): void => {
console.error(JSON.stringify(info));
// 5 blocks only, then go our merry way
if (++count === 5) {
done();
}
});
});
describe('staking', (): void => {
it('retrieves all staking info (for controller)', (done): Promise<() => void> => {
const accountId = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
return api.derive.staking.info(accountId, (info: DerivedStaking): void => {
console.error(JSON.stringify(info));
expect(info.accountId.eq(accountId)).toBe(true);
expect(info.controllerId!.eq(accountId)).toBe(true);
expect(info.stashId!.eq('5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY')).toBe(true);
expect(info.stashId!.eq(info.stakingLedger!.stash)).toBe(true);
done();
});
});
it('retrieves all staking info (for stash)', (done): Promise<() => void> => {
const accountId = '5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY';
return api.derive.staking.info(accountId, (info: DerivedStaking): void => {
console.error(JSON.stringify(info));
if (!info.stashId || !info.controllerId || !info.stakingLedger) {
done.fail(new Error('At least one of info.stashId, info.controllerId or info.stakingLedger is undefined.'));
return;
}
expect(info.accountId.eq(accountId)).toBe(true);
expect(info.controllerId.eq('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')).toBe(true);
expect(info.stashId.eq(accountId)).toBe(true);
expect(info.stashId.eq(info.stakingLedger.stash)).toBe(true);
done();
});
});
describe('verifies derive.staking.unlocking', (): void => {
const UNBOND_VALUE = 1;
const alicePair = testingPairs().alice;
it('unbonds dots for Alice (from Alice Stash)', (done): Promise<() => void> => {
return api.tx.staking.unbond(UNBOND_VALUE)
.signAndSend(alicePair, (result: SubmittableResult): void => {
if (result.status.isFinalized) {
done();
}
});
});
it('verifies that derive.staking.unlocking isn\'t empty/undefined', (): Promise<() => void> => {
return api.derive.staking.info(ALICE_STASH, (info: DerivedStaking): void => {
expect(info.unlocking).toBeDefined();
});
});
});
describe('verifies derive.staking.rewardDestination', (): void => {
const PAYEE = 2;
const alicePair = testingPairs().alice;
it('Set payee for ALICE to 2', (done): Promise<() => void> => {
return api.tx.staking
.setPayee(PAYEE)
.signAndSend(alicePair, (result: SubmittableResult): void => {
if (result.status.isFinalized) {
done();
}
});
});
it('verifies payee for ALICE_STASH', (done): Promise<() => void> => {
return api.derive.staking.info(ALICE_STASH, (info: DerivedStaking): void => {
if (!info.rewardDestination) {
return done.fail(new Error('rewardDestination is undefined.'));
} else {
expect(info.rewardDestination.toString()).toBe('Controller');
}
done();
});
});
it('staking.info updates itself after changing reward destination', async (done): Promise<void> => {
const stashId = testingPairs().alice_stash.address;
// start by setting the reqred to Staked, so we have a common starting point
await api.tx.staking
.setPayee(new RewardDestination('Staked'))
.signAndSend(testingPairs().alice, ({ status }): void => {
if (status.isFinalized) {
console.error('setPayee(Staked) isFinalized');
}
});
let count = 0; // The # of times we got a callback response from api.derive.staking.info
// Subscribe to staking.info
api.derive.staking.info(stashId, (result): void => {
++count;
console.error('***', count, JSON.stringify(result));
if (count >= 2 && result.rewardDestination!.toString() === 'Stash') {
done();
}
}).catch(console.error);
// Wait a bit, and change reward destination
setTimeout(async (): Promise<void> => {
await api.tx.staking
.setPayee(new RewardDestination('Stash'))
.signAndSend(testingPairs().alice, ({ status }): void => {
if (status.isFinalized) {
console.error('setPayee(Stash) isFinalized');
}
});
}, 5000);
});
});
});
});
+281
View File
@@ -0,0 +1,281 @@
// Copyright 2017-2019 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import ApiRx from '@polkadot/api/rx/Api';
import { HeaderExtended } from '@polkadot/api-derive';
import { DerivedBalances, DerivedContractFees, DerivedFees, DerivedSessionInfo } from '@polkadot/api-derive/types';
import { AccountId, AccountIndex, BlockNumber, Index } from '@polkadot/types';
import { WsProvider } from '@polkadot/rpc-provider';
const WS = 'ws://127.0.0.1:9944/';
// Dev account Alice
const ID = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
const IX = 'F7Hs';
describe.skip('Api-RX derive e2e', (): void => {
let api: ApiRx;
beforeAll((): void => {
jest.setTimeout(10000);
});
beforeEach(async (done): Promise<void> => {
api = await ApiRx.create(new WsProvider(WS)).toPromise();
done();
});
afterAll((): void => {
jest.setTimeout(10000);
});
// These derive.accounts tests only work on localhost, not the poc-3 URL
// (and it is assuming it sent at least 1 tx)
describe('derive.accounts', (): void => {
describe('idAndIndex', (): void => {
it('looks up AccountId & AccountIndex from AccountId', async (done): Promise<void> => {
// @ts-ignore silence warning until we have static types here
api.derive.accounts.idAndIndex(ID).subscribe(([accountId, accountIndex]): void => {
expect(accountId!.toString()).toEqual(ID);
// The first emitted value for ix is undefined when passing the ID
if (accountIndex) {
expect(accountIndex.toString()).toEqual(IX);
} else {
expect(accountIndex).toEqual(undefined);
}
done();
});
});
it('looks up AccountId & AccountIndex from AccountIndex', async (done): Promise<void> => {
// @ts-ignore silence warning until we have static types here
api.derive.accounts.idAndIndex(IX).subscribe(([accountId, accountIndex]): void => {
// The first emitted value for id is undefined when passing the IX
if (accountId) {
expect(accountId.toString()).toEqual(ID);
} else {
expect(accountId).toEqual(undefined);
}
expect(accountIndex!.toString()).toEqual(IX);
done();
});
});
});
describe('indexToId', (): void => {
it('looks up AccountId from AccountIndex', async (done): Promise<void> => {
// @ts-ignore silence warning until we have static types here
api.derive.accounts.indexToId(IX).subscribe((accountId): void => {
// The first emitted value for accountId is undefined when passing the IX
if (accountId) {
expect(accountId instanceof AccountId).toBe(true);
expect(accountId.toString()).toEqual(ID);
} else {
expect(accountId).toEqual(undefined);
}
done();
});
});
});
describe('idToIndex', (): void => {
it('looks up AccountIndex from AccountId', async (done): Promise<void> => {
// @ts-ignore silence warning until we have static types here
api.derive.accounts.idToIndex(ID).subscribe((accountIndex): void => {
// The first emitted value for AccountIndex is undefined when passing the ID
if (accountIndex) {
expect(accountIndex instanceof AccountIndex).toBe(true);
expect(accountIndex.toString()).toEqual(IX);
} else {
expect(accountIndex).toEqual(undefined);
}
done();
});
});
});
describe('indexes', (): void => {
it('looks up all AccountIndexes', async (done): Promise<void> => {
// @ts-ignore silence warning until we have static types here
api.derive.accounts.indexes().subscribe((accountIndexes): void => {
// A local dev chain should have the AccountIndex of Alice
expect(accountIndexes).toHaveProperty(
ID,
new AccountIndex(IX)
);
done();
});
});
});
});
// these only work on localhost, not the poc-3 URL
// (and it is assuming it sent at least 1 tx)
describe('derive.balances', (): void => {
describe('all', (): void => {
it('It returns an object with all relevant balance information of an account', async (done): Promise<void> => {
api.derive.balances.all(ID).subscribe((balances: DerivedBalances): void => {
expect(balances).toEqual(expect.objectContaining({
accountId: expect.any(AccountId),
accountNonce: expect.any(Index),
availableBalance: expect.any(BN),
freeBalance: expect.any(BN),
lockedBalance: expect.any(BN),
reservedBalance: expect.any(BN),
vestedBalance: expect.any(BN),
votingBalance: expect.any(BN)
}));
done();
});
});
});
describe('fees', (): void => {
it('fees: It returns an object with all relevant fees of type BN', async (done): Promise<void> => {
api.derive.balances.fees().subscribe((fees: DerivedFees): void => {
expect(fees).toEqual(expect.objectContaining({
creationFee: expect.any(BN),
existentialDeposit: expect.any(BN),
transactionBaseFee: expect.any(BN),
transactionByteFee: expect.any(BN),
transferFee: expect.any(BN)
}));
done();
});
});
});
});
describe('derive.chain', (): void => {
describe('bestNumber', (): void => {
it('Get the latest block number', async (done): Promise<void> => {
api.derive.chain.bestNumber().subscribe((blockNumber: BlockNumber): void => {
expect(blockNumber instanceof BlockNumber).toBe(true);
expect(blockNumber.gten(0)).toBe(true);
done();
});
});
});
describe('bestNumberFinalized', (): void => {
it('Get the latest finalised block number', async (done): Promise<void> => {
api.derive.chain.bestNumberFinalized().subscribe((blockNumber: BlockNumber): void => {
expect(blockNumber instanceof BlockNumber).toBe(true);
expect(blockNumber.gten(0)).toBe(true);
done();
});
});
});
describe('bestNumberLag', (): void => {
it('lag between finalised head and best head', async (done): Promise<void> => {
api.derive.chain.bestNumberLag().subscribe((numberLag: BlockNumber): void => {
expect(numberLag instanceof BlockNumber).toBe(true);
expect(numberLag.gten(0)).toBe(true);
done();
});
});
});
// FIXME https://github.com/polkadot-js/api/issues/868
describe.skip('getHeader', (): void => {
it('gets a specific block header and extended with it`s author', async (done): Promise<void> => {
api.derive.chain.getHeader('TODO').subscribe((headerExtended: HeaderExtended | undefined): void => {
// WIP
expect(headerExtended).toEqual(expect.arrayContaining([]));
done();
});
});
});
describe('subscribeNewHead', (): void => {
it('gets an observable of the current block header and it\'s author', async (done): Promise<void> => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
api.derive.chain.subscribeNewHead().subscribe((headerExtended: HeaderExtended): void => {
// WIP https://github.com/polkadot-js/api/issues/868
done();
});
});
});
});
describe('derive.contracts', (): void => {
describe('fees', (): void => {
it('fees: It returns an object with all relevant constract fees of type Balance', async (done): Promise<void> => {
api.derive.contracts.fees().subscribe((fees: DerivedContractFees): void => {
expect(fees).toEqual(expect.objectContaining({
callBaseFee: expect.any(BN),
contractFee: expect.any(BN),
createBaseFee: expect.any(BN),
creationFee: expect.any(BN),
rentByteFee: expect.any(BN),
rentDepositOffset: expect.any(BN),
tombstoneDeposit: expect.any(BN),
transactionBaseFee: expect.any(BN),
transactionByteFee: expect.any(BN),
transferFee: expect.any(BN)
}));
done();
});
});
});
});
describe('derive.session', (): void => {
describe('sessionProgress', (): void => {
it('derive.session.sessionProgress', async (done): Promise<void> => {
api.derive.session.sessionProgress().subscribe((progress: BN): void => {
expect(progress instanceof BN).toBe(true);
done();
});
});
});
describe('session.info', (): void => {
it('retrieves all session info', async (done): Promise<void> => {
api.derive.session.info().subscribe((info: DerivedSessionInfo): void => {
expect(info).toEqual(expect.objectContaining({
currentEra: expect.anything(),
currentIndex: expect.anything(),
eraLength: expect.anything(),
eraProgress: expect.anything(),
lastEraLengthChange: expect.anything(),
lastLengthChange: expect.anything(),
sessionLength: expect.anything(),
sessionsPerEra: expect.anything(),
sessionProgress: expect.anything()
}));
done();
});
});
});
describe('session.eraLength', (): void => {
it('derive.session.eraLength', async (done): Promise<void> => {
api.derive.session.eraLength().subscribe((length: BN): void => {
expect(length instanceof BN).toBe(true);
done();
});
});
});
describe('session.eraProgress', (): void => {
it('derive.session.eraProgress', async (done): Promise<void> => {
api.derive.session.eraProgress().subscribe((progress: BN): void => {
expect(progress instanceof BN).toBe(true);
done();
});
});
});
});
describe('derive.staking', (): void => {
describe('controllers', (): void => {
// @TODO https://github.com/polkadot-js/api/issues/868
});
});
});
@@ -0,0 +1,60 @@
// Copyright 2017-2019 @polkadot/api-metadata authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { RpcInterface } from '@polkadot/rpc-core/types';
import { SubmittableResult } from '@polkadot/api/SubmittableExtrinsic';
import Rpc from '@polkadot/rpc-core';
import WsProvider from '@polkadot/rpc-provider/ws';
import testingPairs from '@polkadot/keyring/testingPairs';
import extrinsics from '@polkadot/api-metadata/extrinsics/static';
const keyring = testingPairs({ type: 'ed25519' });
// @TODO 1: All three tests below are broken, fix or find better way to test transfers.
// @TODO 2: Move tests out of ./type-metadata to ./api folder
describe.skip('e2e transfer', (): void => {
let api: RpcInterface;
beforeAll((): void => {
api = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
});
beforeEach((): void => {
jest.setTimeout(30000);
});
// Error: [1002]: Inherent transactions cannot be queued.
it('inherent test', (done): void => {
const inherent = extrinsics.timestamp.set(Math.round(Date.now() / 1000));
api.author.submitExtrinsic(inherent.toU8a()).subscribe(done);
});
it('makes a transfer for a transaction', (done): void => {
api.chain
.getBlockHash(0)
.subscribe((genesisHash): void => {
const extrinsic = extrinsics.balances.transfer(keyring.bob.publicKey, 6969) as any;
extrinsic.sign(keyring.alice, { blockHash: genesisHash, nonce: 0 });
api.author.submitExtrinsic(extrinsic.toU8a()).subscribe(done);
});
});
it('makes a transfer via watch', (done): void => {
api.chain
.getBlockHash(0)
.subscribe((genesisHash): void => {
const extrinsic = extrinsics.balances.transfer(keyring.bob.publicKey, 6969) as any;
extrinsic.sign(keyring.alice, { blockHash: genesisHash, nonce: 0 });
api.author.submitAndWatchExtrinsic(extrinsic).subscribe((result: SubmittableResult): void => {
if (result.status.isFinalized) {
done();
}
});
});
});
});
@@ -5,12 +5,12 @@
import WsProvider from '@polkadot/rpc-provider/ws';
import { Extrinsic, SignedBlock } from '@polkadot/types';
import ApiPromise from '../../src/promise';
import describeE2E from '../util/describeE2E';
import ApiPromise from '../../../src/promise';
import describeE2E from '../../util/describeE2E';
describeE2E({
only: [] // To run these tests locally you need to run a Alexander full archive node locally
})('alex archive queries (local)', (wsUrl): void => {
})('Promise e2e alex archive queries (local)', (wsUrl): void => {
let api: ApiPromise;
beforeEach(async (done): Promise<void> => {
@@ -6,12 +6,12 @@ import { AccountId, EventRecord, Hash, Header, Option, Vector } from '@polkadot/
import WsProvider from '@polkadot/rpc-provider/ws';
import ApiPromise from '../../src/promise';
import describeE2E from '../util/describeE2E';
import ApiPromise from '../../../src/promise';
import describeE2E from '../../util/describeE2E';
describeE2E({
only: ['remote-polkadot-alexander']
})('alex queries', (wsUrl): void => {
only: ['docker-polkadot-alexander', 'remote-polkadot-alexander']
})('Promise e2e alex queries', (wsUrl): void => {
let api: ApiPromise;
beforeEach(async (done): Promise<void> => {
@@ -5,12 +5,17 @@
import WsProvider from '@polkadot/rpc-provider/ws';
import { BlockNumber } from '@polkadot/types';
import ApiPromise from '../../src/promise';
import describeE2E from '../util/describeE2E';
import ApiPromise from '../../../src/promise';
import describeE2E from '../../util/describeE2E';
describeE2E({
except: ['remote-substrate-1.0', 'substrate-1.0']
})('e2e consts', (wsUrl): void => {
only: [
'local',
'docker-polkadot-master',
'docker-substrate-master',
'docker-substrate-2.0'
]
})('Promise e2e consts', (wsUrl): void => {
let api: ApiPromise;
beforeEach(async (done): Promise<void> => {
@@ -21,6 +26,9 @@ describeE2E({
it('democracy.cooloffPeriod parameter type', (): void => {
expect(api.consts.democracy.cooloffPeriod).toBeInstanceOf(BlockNumber);
expect(api.consts.democracy.cooloffPeriod.eq(432000)).toBeTruthy();
expect(
api.consts.democracy.cooloffPeriod.eq(432000) || // Substrate
api.consts.democracy.cooloffPeriod.eq(259200) // Polkadot
).toBeTruthy();
});
});
@@ -6,16 +6,16 @@ import fs from 'fs';
import path from 'path';
import { Abi } from '@polkadot/api-contract';
import flipperAbi from '@polkadot/api-contract/test/contracts/flipper.json';
import testingPairs from '@polkadot/keyring/testingPairs';
import WsProvider from '@polkadot/rpc-provider/ws';
import { Address, Hash } from '@polkadot/types';
import { SubmittableResult } from '../../src';
import ApiPromise from '../../src/promise';
import describeE2E from '../util/describeE2E';
import { SubmittableResult } from '../../../src';
import ApiPromise from '../../../src/promise';
import describeE2E from '../../util/describeE2E';
const flipperCode = fs.readFileSync(path.join(__dirname, '../../../api-contract/test/contracts/flipper-pruned.wasm')).toString('hex');
import flipperAbi from '../../../../api-contract/test/contracts/flipper.json';
const flipperCode = fs.readFileSync(path.join(__dirname, '../../../../api-contract/test/contracts//flipper-pruned.wasm')).toString('hex');
describeE2E()('Promise e2e contracts', (wsUrl): void => {
let address: Address;
@@ -0,0 +1,205 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { DerivedBalances } from '@polkadot/api-derive/types';
import testingPairs from '@polkadot/keyring/testingPairs';
import WsProvider from '@polkadot/rpc-provider/ws';
import { Balance, Header, Index, Option, U32 } from '@polkadot/types';
import ApiPromise from '../../../src/promise';
import describeE2E from '../../util/describeE2E';
const ZERO = new BN(0);
// The following tests require a development node with the default funded testing accounts
describeE2E({
except: [
'remote-polkadot-alexander',
'remote-substrate-1.0'
]
})('Promise e2e development queries', (wsUrl): void => {
let api: ApiPromise;
beforeEach(async (done): Promise<void> => {
api = await ApiPromise.create(new WsProvider(wsUrl));
done();
});
const keyring = testingPairs({ type: 'ed25519' });
it('allows retrieval of an fallback entry (once-off query)', async (): Promise<void> => {
const nonce = await api.query.system.accountNonce('5DSo5RVtfrtgHoz2c7jK7Tca7FgJgpCzFnxoRVDeYUQcKPng');
expect(nonce.toHex()).toEqual('0x0000000000000000');
});
it('allows retrieval of fallback when at query is made', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const nonce = await api.query.system.accountNonce.at(header.hash, '5DSo5RVtfrtgHoz2c7jK7Tca7FgJgpCzFnxoRVDeYUQcKPng');
expect(nonce.toHex()).toEqual('0x0000000000000000');
});
it('queries state for a balance', async (): Promise<() => void> => {
return api.query.balances.freeBalance(keyring.alice_stash.address, (balance: Balance): void => {
expect(balance).toBeInstanceOf(BN);
expect(balance.isZero()).toBe(false);
});
});
it('subscribes to queries', (done): Promise<() => void> => {
return (
api.query.system.accountNonce(keyring.ferdie.address, (nonce: Index): void => {
expect(nonce instanceof BN).toBe(true);
done();
})
);
});
it('subscribes to queries (default)', (done): Promise<() => void> => {
return (
api.query.staking.minimumValidatorCount((defaultCount: U32): void => {
expect(defaultCount.toNumber()).toBe(1);
done();
})
);
});
it('subscribes to multiple results (freeBalance.multi)', (done): Promise<() => void> => {
return (
api.query.balances.freeBalance.multi([
keyring.alice.address,
keyring.bob.address,
'5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y',
keyring.ferdie.address
], (balances): void => {
expect(balances).toHaveLength(4);
done();
})
);
});
it('subscribes to multiple results (api.queryMulti)', (done): Promise<() => void> => {
return api.queryMulti([
[api.query.balances.freeBalance, keyring.alice.address],
[api.query.balances.freeBalance, keyring.bob.address],
[api.query.balances.freeBalance, '5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y'],
[api.query.balances.freeBalance, keyring.ferdie.address]
], (balances: Balance[]): void => {
expect(balances).toHaveLength(4);
done();
});
});
it('subscribes to derived balances (balances.all)', (done): Promise<() => void> => {
return (
api.derive.balances.all(
keyring.bob_stash.address,
(all: DerivedBalances): void => {
expect(all.accountId.toString()).toEqual(keyring.bob_stash.address);
expect(all.freeBalance).toBeDefined();
expect(all.freeBalance.gt(ZERO)).toBe(true);
expect(all.availableBalance).toBeDefined();
expect(all.availableBalance.gt(ZERO)).toBe(true);
expect(all.reservedBalance).toBeDefined();
expect(all.lockedBalance).toBeDefined();
expect(all.vestedBalance).toBeDefined();
done();
}
)
);
});
describe('with map type', (): void => {
it('queries correct value', async (): Promise<void> => {
const balance = await api.query.balances.freeBalance(keyring.bob_stash.address) as Balance;
expect(balance.isZero()).toBe(false);
});
it('queries correct value at a specified block', async (): Promise<void> => {
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
const balance = await api.query.balances.freeBalance(keyring.alice_stash.address);
const header = await api.rpc.chain.getHeader() as Header;
const balanceAt = await api.query.balances.freeBalance.at(header.hash, keyring.alice_stash.address) as Balance;
expect(balanceAt.isZero()).toBe(false);
expect(balanceAt.toString()).toEqual(balance.toString());
});
it('subscribes to query and get correct result', async (done): Promise<() => void> => {
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
const balance = await api.query.balances.freeBalance(keyring.alice_stash.address);
return api.query.balances.freeBalance(keyring.alice_stash.address, (balanceSubscribed: Balance): void => {
expect(balanceSubscribed.isZero()).toBe(false);
expect(balanceSubscribed.toString()).toEqual(balance.toString());
done();
});
});
it('queries correct hash', async (): Promise<void> => {
const hash = await api.query.balances.freeBalance.hash(keyring.alice.address);
expect(hash).toBeDefined();
});
it('gets correct key', async (): Promise<void> => {
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
const key = api.query.balances.freeBalance.key(keyring.alice_stash.address);
const balanceData = await api.rpc.state.getStorage(key) as Option<any>;
const balanceRPC = new Balance(balanceData.unwrapOr(undefined));
const balance = await api.query.balances.freeBalance(keyring.alice_stash.address);
expect(balanceRPC.isZero()).toBe(false);
expect(balanceRPC.toString()).toEqual(balance.toString());
});
it('queries multiple results', async (): Promise<void> => {
// assume the account Alice and Bob are only used in test(the balance of them do not change in this test case)
const balanceAlice = await api.query.balances.freeBalance(keyring.alice.address);
const balanceBob = await api.query.balances.freeBalance(keyring.bob.address);
const balances = await api.query.balances.freeBalance.multi([
keyring.alice.address,
keyring.bob.address
]);
expect(balances).toHaveLength(2);
expect((balances as any)[0].toString()).toEqual(balanceAlice.toString());
expect((balances as any)[1].toString()).toEqual(balanceBob.toString());
});
it('subscribes to multiple queries and get correct results', async (done): Promise<() => void> => {
// assume the account Alice and Bob are only used in test(the balance of them do not change in this test case)
const balanceAlice = await api.query.balances.freeBalance(keyring.alice.address);
const balanceBob = await api.query.balances.freeBalance(keyring.bob.address);
return api.query.balances.freeBalance.multi([
keyring.alice.address,
keyring.bob.address
], (balances): void => {
expect(balances).toHaveLength(2);
expect(balances[0].toString()).toEqual(balanceAlice.toString());
expect(balances[1].toString()).toEqual(balanceBob.toString());
done();
});
});
it('queries correct size', async (): Promise<void> => {
const size = await api.query.balances.freeBalance.size(keyring.alice_stash.address);
expect(size.toNumber()).not.toEqual(0);
});
});
});
@@ -0,0 +1,93 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import WsProvider from '@polkadot/rpc-provider/ws';
import { Header, Option } from '@polkadot/types';
import ApiPromise from '../../../src/promise';
import describeE2E from '../../util/describeE2E';
// The following tests only run on nodes that support doubleMapType introduced by metadata v5
describeE2E({
only: [
'local',
'docker-polkadot-master',
'docker-substrate-master',
'docker-substrate-2.0'
]
})('Promise e2e doubleMap queries (since Metadata v5)', (wsUrl): void => {
let api: ApiPromise;
beforeEach(async (done): Promise<void> => {
api = await ApiPromise.create(new WsProvider(wsUrl));
done();
});
// TODO Update ['any', '0x1234'] to the key of a known event topic and update EXPECTED_VALUE to the expected value
describe('with double map type', (): void => {
const KEY1 = 'any';
const KEY2 = '0x1234';
it('queries correct value', async (): Promise<void> => {
const eventTopics = await api.query.system.eventTopics(KEY1, KEY2);
expect(eventTopics.toJSON()).toEqual([]);
});
it('queries correct value at a specified block', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
// TODO check & fix: this will throw the error: Encoding for input doesn't match output, created 0x00 from 0x
const eventTopicsAt = await api.query.system.eventTopics.at(header.hash, KEY1, KEY2);
expect(eventTopicsAt.toJSON()).toEqual([]);
// const eventTopicsAt = await api.query.system.eventTopics.at(header.hash, KEY1, KEY2);
// expect(eventTopicsAt.toJSON()).toEqual([]);
});
it('subscribes to query and get correct result', async (done): Promise<() => void> => {
return api.query.system.eventTopics(KEY1, KEY2, (eventTopicsAt): void => {
expect(eventTopicsAt.toJSON()).toEqual([]);
done();
});
});
it('queries correct hash', async (): Promise<void> => {
const hash = await api.query.system.eventTopics(KEY1, KEY2);
expect(hash).toBeDefined();
});
it('gets correct key', async (): Promise<void> => {
const key = api.query.system.eventTopics.key(KEY1, KEY2);
const eventTopicsData = await api.rpc.state.getStorage(key) as Option<any>;
expect(eventTopicsData.unwrapOr(undefined)).toEqual(undefined);
});
it('queries multiple results', async (): Promise<void> => {
const eventTopicsList = await api.query.system.eventTopics.multi([
[KEY1, KEY2]
]);
expect(eventTopicsList).toHaveLength(1);
expect((eventTopicsList as any)[0].toJSON()).toEqual([]);
});
it('subscribes to multiple queries and get correct results', async (done): Promise<() => void> => {
return api.query.system.eventTopics.multi([
[KEY1, KEY2]
], (eventTopicsList): void => {
expect(eventTopicsList).toHaveLength(1);
expect(eventTopicsList[0].toJSON()).toEqual([]);
done();
});
});
it('queries correct size', async (): Promise<void> => {
const size = await api.query.system.eventTopics.size(KEY1, KEY2);
expect(size.toNumber()).toEqual(0);
});
});
});
@@ -0,0 +1,141 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { HeaderExtended } from '@polkadot/api-derive';
import WsProvider from '@polkadot/rpc-provider/ws';
import { LinkageResult } from '@polkadot/types/codec/Linkage';
import { EventRecord, Hash, Header, Option, SessionIndex, Vector } from '@polkadot/types';
import ApiPromise from '../../../src/promise';
import describeE2E from '../../util/describeE2E';
describeE2E()('Promise e2e queries', (wsUrl): void => {
let api: ApiPromise;
beforeEach(async (done): Promise<void> => {
api = await ApiPromise.create(new WsProvider(wsUrl));
done();
});
it('makes the runtime, rpc, state & extrinsics available', (): void => {
expect(api.genesisHash).toBeDefined();
expect(api.runtimeMetadata).toBeDefined();
expect(api.runtimeVersion).toBeDefined();
expect(api.rpc).toBeDefined();
expect(api.query).toBeDefined();
expect(api.tx).toBeDefined();
expect(api.derive).toBeDefined();
});
it('subscribes to rpc', (done): Promise<() => void> => {
return (
api.rpc.chain.subscribeNewHead((header: Header): void => {
expect(header.blockNumber.isZero()).toBe(false);
done();
})
);
});
it('subscribes to finalized', (done): Promise<() => void> => {
return (
api.rpc.chain.subscribeFinalizedHeads((header: Header): void => {
expect(header.blockNumber.isZero()).toBe(false);
done();
})
);
});
it('subscribes to derive', (done): Promise<() => void> => {
return (
api.derive.chain.subscribeNewHead((header: HeaderExtended): void => {
expect(header.blockNumber.isZero()).toBe(false);
done();
})
);
});
it('subscribes to a linked map (staking.validators)', (done): Promise<() => void> => {
return (
api.query.staking.validators((prefs: LinkageResult): void => {
expect(prefs instanceof LinkageResult).toBe(true);
done();
})
);
});
it('can retrive header by hash', async (): Promise<void> => {
const latest = await api.rpc.chain.getHeader() as Header;
const specific = await api.rpc.chain.getHeader(latest.hash) as Header;
expect(latest.hash).toEqual(specific.hash);
});
it('makes a query at a latest block (specified)', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const events = await api.query.system.events.at(header.hash) as Vector<EventRecord>;
expect(events.length).not.toEqual(0);
events.forEach(({ event: { data, method, section }, phase, topics }: EventRecord): void => {
console.error(phase.toString(), `: ${section}.${method}`, data.toString(), topics.toString());
});
});
it('subscribes to events', (done): Promise<() => void> => {
return (
api.query.system.events((events): void => {
expect(events).not.toHaveLength(0);
done();
})
);
});
describe('with plain type', (): void => {
it('queries a correct value', async (): Promise<void> => {
const sessionIndex = await api.query.session.currentIndex() as SessionIndex;
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
});
it('queries correct value at a specified block', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const sessionIndex = await api.query.session.currentIndex.at(header.hash) as SessionIndex;
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
});
it('subscribes to query and get correct result', (done): Promise<() => void> => {
return api.query.session.currentIndex((sessionIndex: SessionIndex): void => {
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
done();
});
});
it('queries correct hash', async (): Promise<void> => {
const hash: Hash = await api.query.session.currentIndex.hash();
expect(hash).toBeDefined();
});
it('gets correct key', async (): Promise<void> => {
const key = api.query.session.currentIndex.key();
const sessionIndexData = await api.rpc.state.getStorage(key) as Option<any>;
const sessionIndexRPC = new SessionIndex(sessionIndexData.unwrapOr(undefined));
expect(sessionIndexRPC.toNumber()).toBeGreaterThanOrEqual(0);
});
it('queries correct size', async (): Promise<void> => {
const size = await api.query.session.currentIndex.size();
expect(size).not.toHaveLength(0);
expect(size.toNumber()).toBeGreaterThanOrEqual(0);
});
});
});
@@ -8,11 +8,11 @@ import WsProvider from '@polkadot/rpc-provider/ws';
import { randomAsHex } from '@polkadot/util-crypto';
import { EventRecord, ExtrinsicEra, Hash, Header, Index, SignedBlock } from '@polkadot/types';
import { SubmittableResult } from './../../src';
import ApiPromise from '../../src/promise';
import { Signer } from './../../src/types';
import describeE2E from '../util/describeE2E';
import SingleAccountSigner from '../util/SingleAccountSigner';
import { SubmittableResult } from '../../../src';
import ApiPromise from '../../../src/promise';
import { Signer } from '../../../src/types';
import describeE2E from '../../util/describeE2E';
import SingleAccountSigner from '../../util/SingleAccountSigner';
// log all events for the transfare, calling done() when finalized
const logEvents = (done: () => {}): (r: SubmittableResult) => void =>
@@ -10,12 +10,10 @@ import { Balance, Header } from '@polkadot/types';
import testingPairs from '@polkadot/keyring/testingPairs';
import WsProvider from '@polkadot/rpc-provider/ws';
import ApiRx from '../../src/rx';
import describeE2E from '../util/describeE2E';
import ApiRx from '../../../src/rx';
import describeE2E from '../../util/describeE2E';
describeE2E({
apiType: 'rxjs'
})('Rx e2e queries', (wsUrl): void => {
describeE2E()('Rx e2e queries', (wsUrl): void => {
const keyring = testingPairs({ type: 'ed25519' });
let api: ApiRx;
@@ -36,7 +34,7 @@ describeE2E({
});
it('queries state for a balance', (done): void => {
api.query.balances.freeBalance(keyring.alice.address).subscribe((balance): void => {
api.query.balances.freeBalance(keyring.alice_stash.address).subscribe((balance): void => {
expect(balance).toBeInstanceOf(BN);
expect((balance as Balance).isZero()).toBe(false);
done();
@@ -9,13 +9,11 @@ import { Index } from '@polkadot/types';
import testingPairs from '@polkadot/keyring/testingPairs';
import WsProvider from '@polkadot/rpc-provider/ws';
import ApiRx from './../../src/rx';
import { SubmittableResult } from './../../src';
import describeE2E from '../util/describeE2E';
import ApiRx from '../../../src/rx';
import { SubmittableResult } from '../../../src';
import describeE2E from '../../util/describeE2E';
describeE2E({
apiType: 'rxjs'
})('Rx e2e transactions', (wsUrl): void => {
describeE2E()('Rx e2e transactions', (wsUrl): void => {
const keyring = testingPairs({ type: 'ed25519' });
let api: ApiRx;
@@ -1,388 +0,0 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { HeaderExtended } from '@polkadot/api-derive';
import { DerivedBalances } from '@polkadot/api-derive/types';
import testingPairs from '@polkadot/keyring/testingPairs';
import WsProvider from '@polkadot/rpc-provider/ws';
import { LinkageResult } from '@polkadot/types/codec/Linkage';
import { Balance, EventRecord, Hash, Header, Index, Option, SessionIndex, ValidatorPrefs, Vector } from '@polkadot/types';
import ApiPromise from '../../src/promise';
import describeE2E from '../util/describeE2E';
const ZERO = new BN(0);
describeE2E()('Promise e2e queries', (wsUrl): void => {
let api: ApiPromise;
beforeEach(async (done): Promise<void> => {
api = await ApiPromise.create(new WsProvider(wsUrl));
done();
});
const keyring = testingPairs({ type: 'ed25519' });
it('makes the runtime, rpc, state & extrinsics available', (): void => {
expect(api.genesisHash).toBeDefined();
expect(api.runtimeMetadata).toBeDefined();
expect(api.runtimeVersion).toBeDefined();
expect(api.rpc).toBeDefined();
expect(api.query).toBeDefined();
expect(api.tx).toBeDefined();
expect(api.derive).toBeDefined();
});
it('allows retrieval of an fallback entry (once-off query)', async (): Promise<void> => {
const nonce = await api.query.system.accountNonce('5DSo5RVtfrtgHoz2c7jK7Tca7FgJgpCzFnxoRVDeYUQcKPng');
expect(nonce.toHex()).toEqual('0x0000000000000000');
});
it('allows retrieval of fallback when at query is made', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const nonce = await api.query.system.accountNonce.at(header.hash, '5DSo5RVtfrtgHoz2c7jK7Tca7FgJgpCzFnxoRVDeYUQcKPng');
expect(nonce.toHex()).toEqual('0x0000000000000000');
});
it('queries state for a balance', async (): Promise<() => void> => {
return api.query.balances.freeBalance(keyring.alice.address, (balance: Balance): void => {
expect(balance).toBeInstanceOf(BN);
expect(balance.isZero()).toBe(false);
});
});
it('subscribes to rpc', (done): Promise<() => void> => {
return (
api.rpc.chain.subscribeNewHead((header: Header): void => {
expect(header.blockNumber.isZero()).toBe(false);
done();
})
);
});
it('subscribes to finalized', (done): Promise<() => void> => {
return (
api.rpc.chain.subscribeFinalizedHeads((header: Header): void => {
expect(header.blockNumber.isZero()).toBe(false);
done();
})
);
});
it('subscribes to derive', (done): Promise<() => void> => {
return (
api.derive.chain.subscribeNewHead((header: HeaderExtended): void => {
expect(header.blockNumber.isZero()).toBe(false);
done();
})
);
});
it('subscribes to queries', (done): Promise<() => void> => {
return (
api.query.system.accountNonce(keyring.ferdie.address, (nonce: Index): void => {
expect(nonce instanceof BN).toBe(true);
done();
})
);
});
it.skip('subscribes to queries (default)', (done): Promise<() => void> => {
return (
api.query.staking.validators(keyring.ferdie.address, (prefs: ValidatorPrefs): void => {
expect(prefs.unstakeThreshold.toNumber()).toBe(3);
done();
})
);
});
it('subscribes to a linked map (staking.validators)', (done): Promise<() => void> => {
return (
api.query.staking.validators((prefs: LinkageResult): void => {
expect(prefs instanceof LinkageResult).toBe(true);
done();
})
);
});
it('subscribes to multiple results (freeBalance.multi)', (done): Promise<() => void> => {
return (
api.query.balances.freeBalance.multi([
keyring.alice.address,
keyring.bob.address,
'5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y',
keyring.ferdie.address
], (balances): void => {
expect(balances).toHaveLength(4);
done();
})
);
});
it('subscribes to multiple results (api.queryMulti)', (done): Promise<() => void> => {
return api.queryMulti([
[api.query.balances.freeBalance, keyring.alice.address],
[api.query.balances.freeBalance, keyring.bob.address],
[api.query.balances.freeBalance, '5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y'],
[api.query.balances.freeBalance, keyring.ferdie.address]
], (balances: Balance[]): void => {
expect(balances).toHaveLength(4);
done();
});
});
it('subscribes to derived balances (balances.all)', (done): Promise<() => void> => {
return (
api.derive.balances.all(
keyring.alice.address,
(all: DerivedBalances): void => {
expect(all.accountId.toString()).toEqual(keyring.alice.address);
expect(all.freeBalance).toBeDefined();
expect(all.freeBalance.gt(ZERO)).toBe(true);
expect(all.availableBalance).toBeDefined();
expect(all.availableBalance.gt(ZERO)).toBe(true);
expect(all.reservedBalance).toBeDefined();
expect(all.lockedBalance).toBeDefined();
expect(all.vestedBalance).toBeDefined();
done();
}
)
);
});
it('can retrive header by hash', async (): Promise<void> => {
const latest = await api.rpc.chain.getHeader() as Header;
const specific = await api.rpc.chain.getHeader(latest.hash) as Header;
expect(latest.hash).toEqual(specific.hash);
});
it('makes a query at a latest block (specified)', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const events = await api.query.system.events.at(header.hash) as Vector<EventRecord>;
expect(events.length).not.toEqual(0);
events.forEach(({ event: { data, method, section }, phase, topics }: EventRecord): void => {
console.error(phase.toString(), `: ${section}.${method}`, data.toString(), topics.toString());
});
});
it('subscribes to events', (done): Promise<() => void> => {
return (
api.query.system.events((events): void => {
expect(events).not.toHaveLength(0);
done();
})
);
});
describe('with plain type', (): void => {
it('queries a correct value', async (): Promise<void> => {
const sessionIndex = await api.query.session.currentIndex() as SessionIndex;
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
});
it('queries correct value at a specified block', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
const sessionIndex = await api.query.session.currentIndex.at(header.hash) as SessionIndex;
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
});
it('subscribes to query and get correct result', (done): Promise<() => void> => {
return api.query.session.currentIndex((sessionIndex: SessionIndex): void => {
expect(sessionIndex.toNumber()).toBeGreaterThanOrEqual(0);
done();
});
});
it('queries correct hash', async (): Promise<void> => {
const hash: Hash = await api.query.session.currentIndex.hash();
expect(hash).toBeDefined();
});
it('gets correct key', async (): Promise<void> => {
const key = api.query.session.currentIndex.key();
const sessionIndexData = await api.rpc.state.getStorage(key) as Option<any>;
const sessionIndexRPC = new SessionIndex(sessionIndexData.unwrapOr(undefined));
expect(sessionIndexRPC.toNumber()).toBeGreaterThanOrEqual(0);
});
it('queries correct size', async (): Promise<void> => {
const size = await api.query.session.currentIndex.size();
expect(size).not.toHaveLength(0);
expect(size.toNumber()).toBeGreaterThanOrEqual(0);
});
});
describe('with map type', (): void => {
it('queries correct value', async (): Promise<void> => {
const balance = await api.query.balances.freeBalance(keyring.alice.address) as Balance;
expect(balance.isZero()).toBe(false);
});
it('queries correct value at a specified block', async (): Promise<void> => {
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
const balance = await api.query.balances.freeBalance(keyring.alice.address);
const header = await api.rpc.chain.getHeader() as Header;
const balanceAt = await api.query.balances.freeBalance.at(header.hash, keyring.alice.address) as Balance;
expect(balanceAt.isZero()).toBe(false);
expect(balanceAt.toString()).toEqual(balance.toString());
});
it('subscribes to query and get correct result', async (done): Promise<() => void> => {
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
const balance = await api.query.balances.freeBalance(keyring.alice.address);
return api.query.balances.freeBalance(keyring.alice.address, (balanceSubscribed: Balance): void => {
expect(balanceSubscribed.isZero()).toBe(false);
expect(balanceSubscribed.toString()).toEqual(balance.toString());
done();
});
});
it('queries correct hash', async (): Promise<void> => {
const hash = await api.query.balances.freeBalance.hash(keyring.alice.address);
expect(hash).toBeDefined();
});
it('gets correct key', async (): Promise<void> => {
// assume the account Alice is only used in test(the balance of Alice does not change in this test case)
const key = api.query.balances.freeBalance.key(keyring.alice.address);
const balanceData = await api.rpc.state.getStorage(key) as Option<any>;
const balanceRPC = new Balance(balanceData.unwrapOr(undefined));
const balance = await api.query.balances.freeBalance(keyring.alice.address);
expect(balanceRPC.isZero()).toBe(false);
expect(balanceRPC.toString()).toEqual(balance.toString());
});
it('queries multiple results', async (): Promise<void> => {
// assume the account Alice and Bob are only used in test(the balance of them do not change in this test case)
const balanceAlice = await api.query.balances.freeBalance(keyring.alice.address);
const balanceBob = await api.query.balances.freeBalance(keyring.bob.address);
const balances = await api.query.balances.freeBalance.multi([
keyring.alice.address,
keyring.bob.address
]);
expect(balances).toHaveLength(2);
expect((balances as any)[0].toString()).toEqual(balanceAlice.toString());
expect((balances as any)[1].toString()).toEqual(balanceBob.toString());
});
it('subscribes to multiple queries and get correct results', async (done): Promise<() => void> => {
// assume the account Alice and Bob are only used in test(the balance of them do not change in this test case)
const balanceAlice = await api.query.balances.freeBalance(keyring.alice.address);
const balanceBob = await api.query.balances.freeBalance(keyring.bob.address);
return api.query.balances.freeBalance.multi([
keyring.alice.address,
keyring.bob.address
], (balances): void => {
expect(balances).toHaveLength(2);
expect(balances[0].toString()).toEqual(balanceAlice.toString());
expect(balances[1].toString()).toEqual(balanceBob.toString());
done();
});
});
it('queries correct size', async (): Promise<void> => {
const size = await api.query.balances.freeBalance.size(keyring.alice.address);
expect(size.toNumber()).not.toEqual(0);
});
});
// TODO Update ['any', '0x1234'] to the key of a known event topic and update EXPECTED_VALUE to the expected value
describe('with double map type', (): void => {
const KEY1 = 'any';
const KEY2 = '0x1234';
it('queries correct value', async (): Promise<void> => {
const eventTopics = await api.query.system.eventTopics(KEY1, KEY2);
expect(eventTopics.toJSON()).toEqual([]);
});
it('queries correct value at a specified block', async (): Promise<void> => {
const header = await api.rpc.chain.getHeader() as Header;
// TODO check & fix: this will throw the error: Encoding for input doesn't match output, created 0x00 from 0x
const eventTopicsAt = await api.query.system.eventTopics.at(header.hash, KEY1, KEY2);
expect(eventTopicsAt.toJSON()).toEqual([]);
// const eventTopicsAt = await api.query.system.eventTopics.at(header.hash, KEY1, KEY2);
// expect(eventTopicsAt.toJSON()).toEqual([]);
});
it('subscribes to query and get correct result', async (done): Promise<() => void> => {
return api.query.system.eventTopics(KEY1, KEY2, (eventTopicsAt): void => {
expect(eventTopicsAt.toJSON()).toEqual([]);
done();
});
});
it('queries correct hash', async (): Promise<void> => {
const hash = await api.query.system.eventTopics(KEY1, KEY2);
expect(hash).toBeDefined();
});
it('gets correct key', async (): Promise<void> => {
const key = api.query.system.eventTopics.key(KEY1, KEY2);
const eventTopicsData = await api.rpc.state.getStorage(key) as Option<any>;
expect(eventTopicsData.unwrapOr(undefined)).toEqual(undefined);
});
it('queries multiple results', async (): Promise<void> => {
const eventTopicsList = await api.query.system.eventTopics.multi([
[KEY1, KEY2]
]);
expect(eventTopicsList).toHaveLength(1);
expect((eventTopicsList as any)[0].toJSON()).toEqual([]);
});
it('subscribes to multiple queries and get correct results', async (done): Promise<() => void> => {
return api.query.system.eventTopics.multi([
[KEY1, KEY2]
], (eventTopicsList): void => {
expect(eventTopicsList).toHaveLength(1);
expect(eventTopicsList[0].toJSON()).toEqual([]);
done();
});
});
it('queries correct size', async (): Promise<void> => {
const size = await api.query.system.eventTopics.size(KEY1, KEY2);
expect(size.toNumber()).toEqual(0);
});
});
});
@@ -0,0 +1,59 @@
// Copyright 2017-2019 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import storage from '@polkadot/api-metadata/storage/static';
import WsProvider from '@polkadot/rpc-provider/ws';
import { BlockNumber, Index, SignedBlock, StorageChangeSet } from '@polkadot/types';
import Rpc from '@polkadot/rpc-core';
const randomAccount = '5HTqyWJHAVUieZnpb1V8gK4T1E4mnhkrUVSSzWBQd6kYgsVJ';
describe.skip('e2e Alexander - Polkadot', (): void => {
let rpc: Rpc;
beforeEach((): void => {
jest.setTimeout(30000);
rpc = new Rpc(new WsProvider('wss://poc3-rpc.polkadot.io/'));
});
it('subscribes to storage', (done): void => {
rpc.state
.subscribeStorage([
[storage.system.accountNonce, randomAccount],
[storage.session.currentIndex]
])
.subscribe((data: StorageChangeSet): void => {
expect(data).toHaveLength(2);
expect(data).toEqual(
expect.arrayContaining([
expect.any(BlockNumber),
expect.any(Index)
])
);
done();
});
});
it('retrieves a block by hash (krumme lanke #1)', (done): void => {
rpc.chain
.getBlock('0x627847bffdf5f3e01ac440d057dec6a37a12a6f329db7ef8367665574b76b5df')
.subscribe((block: SignedBlock): void => {
expect(block).toBeDefined();
expect(block).toBeInstanceOf(SignedBlock);
done();
});
});
it('retrieves a block by hash (krumme lanke #2)', (done): void => {
rpc.chain
.getBlock('0x53416d53a4b1dfcae9165a89d193608e4aa770414f02267f5b2c4015a2e66091')
.subscribe((block: SignedBlock): void => {
expect(block).toBeDefined();
expect(block).toBeInstanceOf(SignedBlock);
done();
});
});
});
@@ -0,0 +1,36 @@
// Copyright 2017-2019 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ChainProperties, PendingExtrinsics } from '@polkadot/types';
import WsProvider from '@polkadot/rpc-provider/ws';
import Rpc from '@polkadot/rpc-core';
describe.skip('e2e basics', (): void => {
let rpc: Rpc;
beforeEach((): void => {
jest.setTimeout(30000);
rpc = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
});
it('retrieves the pending extrinsics', (done): void => {
rpc.author
.pendingExtrinsics()
.subscribe((extrinsics: PendingExtrinsics): void => {
expect(extrinsics).toBeInstanceOf(PendingExtrinsics);
done();
});
});
it('retrieves the system properties', (done): void => {
rpc.system
.properties()
.subscribe((properties: ChainProperties): void => {
expect(properties).toBeInstanceOf(ChainProperties);
console.log('properties', properties);
done();
});
});
});
@@ -0,0 +1,40 @@
// Copyright 2017-2019 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Header, RuntimeVersion } from '@polkadot/types';
import WsProvider from '@polkadot/rpc-provider/ws';
import Rpc from '@polkadot/rpc-core';
describe.skip('e2e chain', (): void => {
let rpc: Rpc;
beforeEach((): void => {
jest.setTimeout(30000);
rpc = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
});
it('subscribes via subscribeNewHead', (done): void => {
let count = 0;
rpc.chain
.subscribeNewHead()
.subscribe((header: Header): void => {
expect(header).toBeInstanceOf(Header);
if (++count === 3) {
done();
}
});
});
it('retrieves the runtime version', (done): void => {
rpc.chain
.getRuntimeVersion()
.subscribe((version: RuntimeVersion): void => {
expect(version).toBeInstanceOf(RuntimeVersion);
done();
});
});
});
@@ -0,0 +1,169 @@
// Copyright 2017-2019 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import fs from 'fs';
import path from 'path';
import { SubmittableResult } from '@polkadot/api';
import ApiPromise from '@polkadot/api/promise/Api';
import storage from '@polkadot/api-metadata/storage/static';
import { Abi } from '@polkadot/api-contract';
import testingPairs from '@polkadot/keyring/testingPairs';
import { KeyringPair } from '@polkadot/keyring/types';
import WsProvider from '@polkadot/rpc-provider/ws';
import { Balance, Bytes, Hash, Metadata, Moment, StorageData, StorageKey } from '@polkadot/types';
import Rpc from '@polkadot/rpc-core';
import flipperAbi from '../../../../api-contract/test/contracts/flipper.json';
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
const CODE = '0x3a636f6465'; // :code
const CHILD_STORAGE = '0x3a6368696c645f73746f726167653a'; // :child_storage:
describe.skip('e2e state', (): void => {
let rpc: Rpc;
beforeEach((): void => {
jest.setTimeout(30000);
rpc = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
});
it('getMetadata(): retrieves the wasm metadata', (done): void => {
rpc.state
.getMetadata()
.subscribe((meta: Metadata): void => {
console.error(JSON.stringify(meta.toJSON()));
done();
});
});
it('getKeys(): retrieves storage keys for ":code"', (done): void => {
rpc.state
.getKeys(CODE)
.subscribe((keys: StorageKey[]): void => {
expect(keys.length).toEqual(1);
done();
});
});
describe('test-suite getStorage()', (): void => {
it('retrieves code', (done): void => {
rpc.state
.getStorage([
storage.substrate.code
])
.subscribe((code: Bytes): void => {
console.error(code.toHex().substr(0, 256), '...');
done();
});
});
it('retrieves balances', (done): void => {
rpc.state
.getStorage([
storage.balances.freeBalance, ALICE
])
.subscribe((balance: Balance): void => {
console.error(balance);
expect(balance.isZero()).not.toEqual(true);
done();
});
});
it('retrieves timestamp', (done): void => {
rpc.state
.getStorage([
storage.timestamp.now
])
.subscribe((moment: Moment): void => {
console.error(moment);
expect(moment.toNumber()).not.toEqual(0);
done();
});
});
});
describe('e2e state child methods', (): void => {
// `child_storage` is currently not used anywhere in substrate, that's why we need to
// add a Smart Contract that is using `child_storage` before being able to test it.
let codeHash: Hash;
beforeAll(async (done): Promise<Hash> => {
const code: string = fs.readFileSync(path.join(__dirname, '../../../../api-contract/test/contracts/flipper-pruned.wasm')).toString('hex');
const abi = new Abi(flipperAbi);
const apiPromise: ApiPromise = await ApiPromise.create(new WsProvider('ws://127.0.0.1:9944'));
const keyring: Record<string, KeyringPair> = testingPairs({ type: 'sr25519' });
const putCode = apiPromise.tx.contract
.putCode(50000, `0x${code}`)
.signAndSend(keyring.eve, (result: SubmittableResult): void => {
if (result.status.isFinalized) {
const record = result.findRecord('contract', 'CodeStored');
if (record) {
codeHash = record.event.data[0] as Hash;
}
}
done();
});
return putCode.then((): Promise<Hash> => {
return apiPromise.tx.contract
.create(12345, 50000, codeHash, abi.deploy())
.signAndSend(keyring.bob);
});
});
it('getChildKeys(): retrieves :child_storage: keys for one deployed flipper contract', async (done):
Promise<void> => {
const storageKeys = await rpc.state.getKeys(CHILD_STORAGE).toPromise();
rpc.state
.getChildKeys(storageKeys[0], '0x')
.subscribe((keys: StorageKey[]): void => {
expect(keys.length).toBeGreaterThanOrEqual(1);
done();
});
});
it('getChildStorage(): retrieves the default value of the flipper smart contract', async (done): Promise<void> => {
const storageKeys = await rpc.state.getKeys(CHILD_STORAGE).toPromise();
const childStorageKeys = await rpc.state.getChildKeys(storageKeys[0], '0x').toPromise();
rpc.state
.getChildStorage(storageKeys[0], childStorageKeys[0])
.subscribe((storage: StorageData): void => {
expect(storage.toString()).toBe('0x00');
done();
});
});
it('getChildStorageHash(): retrieves the Hash of the flipper smart contract', async (done): Promise<void> => {
const storageKeys = await rpc.state.getKeys(CHILD_STORAGE).toPromise();
const childStorageKeys = await rpc.state.getChildKeys(storageKeys[0], '0x').toPromise();
rpc.state
.getChildStorageHash(storageKeys[0], childStorageKeys[0])
.subscribe((storage: StorageData): void => {
expect(storage.toString()).toBe('0x03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314');
done();
});
});
it('getChildStorageSize(): retrieves the size of the flipper smart contract', async (done): Promise<void> => {
const storageKeys = await rpc.state.getKeys(CHILD_STORAGE).toPromise();
const childStorageKeys = await rpc.state.getChildKeys(storageKeys[0], '0x').toPromise();
rpc.state
.getChildStorageSize(storageKeys[0], childStorageKeys[0])
.subscribe((storage: StorageData): void => {
expect(storage.toString()).toBe('1');
done();
});
});
});
});
@@ -0,0 +1,32 @@
// Copyright 2017-2019 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { StorageChangeSet } from '@polkadot/types';
import WsProvider from '@polkadot/rpc-provider/ws';
import storage from '@polkadot/api-metadata/storage/static';
import Rpc from '@polkadot/rpc-core';
describe.skip('e2e subscriptions', (): void => {
let rpc: Rpc;
beforeEach((): void => {
jest.setTimeout(30000);
rpc = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
});
it('retrieves current timestamp', (done): void => {
let count = 0;
rpc.state
.subscribeStorage([[storage.timestamp.now]])
.subscribe((data: StorageChangeSet): void => {
expect(data).toBeDefined();
if (++count === 3) {
done();
}
});
});
});
+39 -28
View File
@@ -4,11 +4,11 @@
const WS_ENDPOINTS = {
local: 'ws://127.0.0.1:9944/',
'substrate-master': 'ws://127.0.0.1:9945/',
'substrate-1.0': 'ws://127.0.0.1:9946/',
'substrate-2.0': 'ws://127.0.0.1:9947/',
'polkadot-master': 'ws://127.0.0.1:9948/',
'polkadot-alexander': 'ws://127.0.0.1:9949/',
'docker-substrate-master': 'ws://127.0.0.1:9945/',
'docker-substrate-1.0': 'ws://127.0.0.1:9946/',
'docker-substrate-2.0': 'ws://127.0.0.1:9947/',
'docker-polkadot-master': 'ws://127.0.0.1:9948/',
'docker-polkadot-alexander': 'ws://127.0.0.1:9949/',
'remote-polkadot-alexander': 'wss://poc3-rpc.polkadot.io/',
'remote-substrate-1.0': 'wss://substrate-rpc.parity.io/'
};
@@ -16,12 +16,22 @@ const WS_ENDPOINTS = {
type WsName = keyof typeof WS_ENDPOINTS;
interface Options {
except?: WsName[]; // Only one of the two keys `either` `only` should be set
except?: WsName[]; // Only one of the two keys `except` `only` should be set
only?: WsName[];
apiType?: 'promise' | 'rxjs';
}
// From the options and the WITH_DOCKER flag, calculate on which endpoints we
function filterProcessEnv (wsEndpoints: WsName[]): WsName[] {
// If there's a TEST_DOCKER flag, we only run tests to Docker endpoints
// If there's a TEST_REMOTE flag, we only run tests to remote endpoints
// If none of the two is present, we only run tests on local node
return process.env.TEST_REMOTE || process.env.TEST_DOCKER
? process.env.TEST_REMOTE
? wsEndpoints.filter((wsName): boolean => wsName.startsWith('remote-'))
: wsEndpoints.filter((wsName): boolean => wsName.startsWith('docker-'))
: wsEndpoints.filter((wsName): boolean => wsName === 'local');
}
// From the options and the TEST_DOCKER and TEST_REMOTE flags, calculate on which endpoints we
// should run the tests
function getWsEndpoints (options?: Options): WsName[] {
let wsEndpoints: WsName[] = []; // The ws endpoints to test
@@ -33,30 +43,31 @@ function getWsEndpoints (options?: Options): WsName[] {
.filter((wsName): boolean => !options || !options.except || !options.except.includes(wsName));
}
// If there's no WITH_DOCKER flag, we only run local node
if (!process.env.WITH_DOCKER) {
wsEndpoints = wsEndpoints.filter((wsName): boolean => wsName === 'local');
}
return wsEndpoints;
return filterProcessEnv(wsEndpoints);
}
export default function describeE2E (options?: Options): (message: string, inner: (wsUrl: string) => void) => void {
return function (message: string, inner: (wsUrl: string) => void): void {
getWsEndpoints(options)
.map((wsName): [string, string] => [wsName, WS_ENDPOINTS[wsName]])
.forEach(([wsName, wsUrl]): void => {
describe(`${message} on ${wsName}`, (): void => {
beforeAll((): void => {
jest.setTimeout(30000);
});
afterAll((): void => {
jest.setTimeout(5000);
});
inner(wsUrl);
});
const wsEndpoints = getWsEndpoints(options);
if (!wsEndpoints.length) {
describe(`Empty test Suite:`, (): void => {
it('No tests found for passed endpoints', (): void => {});
});
} else {
wsEndpoints.map((wsName): [string, string] => [wsName, WS_ENDPOINTS[wsName]])
.forEach(([wsName, wsUrl]): void => {
describe(`${message} on ${wsName}`, (): void => {
beforeAll((): void => {
jest.setTimeout(15000);
});
afterAll((): void => {
jest.setTimeout(5000);
});
inner(wsUrl);
});
});
}
};
}