Class-ify and cleanup mock provider (#347)

This commit is contained in:
Jaco Greeff
2018-10-25 14:05:43 +02:00
committed by Amaury Martiny
parent d6b6713418
commit b1e13b20c8
15 changed files with 340 additions and 362 deletions
+177 -22
View File
@@ -3,33 +3,188 @@
// of the ISC license. See the LICENSE file for details.
import { ProviderInterface, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
import { MockState$Subscriptions, MockState$Subscription$Callback, MockState$Db } from './types';
import mocks from './mocks';
import on from './on';
import send from './send';
import state from './state';
import subscribe from './subscribe';
import unsubscribe from './unsubscribe';
import BN from 'bn.js';
import EventEmitter from 'eventemitter3';
import interfaces from '@polkadot/jsonrpc/index';
import testKeyring from '@polkadot/keyring/testing';
import storage from '@polkadot/storage/static';
import { Base } from '@polkadot/types/codec';
import { Header } from '@polkadot/types/index';
import { bnToU8a, logger, u8aToHex } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
const INTERVAL = 1000;
const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply(
[], Object.values(interfaces).map((area) =>
Object
.values(area.methods)
.filter((method) =>
method.isSubscription
)
.map(({ method, section }) =>
`${section}_${method}`
)
)
);
const keyring = testKeyring();
const l = logger('api-mock');
/**
* A mock provider mainly used for testing.
* @return {ProviderInterface} The mock provider
*/
export default function mockProvider (): ProviderInterface {
const self = state();
mocks(self);
return {
isConnected: (): boolean =>
true,
on: (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void =>
on(self, type, sub),
send: (method: string, params: Array<any>): Promise<any> =>
send(self, method, params),
subscribe: (type: string, method: string, ...params: Array<any>): Promise<number> =>
subscribe(self, type, method, params),
unsubscribe: (type: string, method: string, id: number): Promise<boolean> =>
unsubscribe(self, type, method, id)
export default class Mock implements ProviderInterface {
private db: MockState$Db = {};
private emitter = new EventEmitter();
public isUpdating: boolean = true;
private requests: { [index: string]: (...params: any[]) => string } = {
'state_getStorage': (storage: MockState$Db, params: Array<any>): string => {
return u8aToHex(
storage[(params[0] as string)]
);
},
'system_chain': (): string => 'mockChain',
'system_name': (): string => 'mockClient',
'system_version': (): string => '9.8.7'
};
public subscriptions: MockState$Subscriptions = SUBSCRIPTIONS.reduce((subs, name) => {
subs[name] = {
callbacks: {},
lastValue: null
};
return subs;
}, ({} as MockState$Subscriptions));
private subscriptionId: number = 0;
private subscriptionMap: {
[index: number]: string
} = {};
constructor () {
this.init();
}
isConnected (): boolean {
return true;
}
on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
this.emitter.on(type, sub);
}
async send (method: string, params: Array<any>): Promise<any> {
if (!this.requests[method]) {
throw new Error(`provider.send: Invalid method '${method}'`);
}
return this.requests[method](this.db, params);
}
async subscribe (type: string, method: string, ...params: Array<any>): Promise<number> {
l.debug(() => ['subscribe', method, params]);
if (this.subscriptions[method]) {
const callback: MockState$Subscription$Callback = params.pop();
const id = ++this.subscriptionId;
this.subscriptions[method].callbacks[id] = callback;
this.subscriptionMap[id] = method;
if (this.subscriptions[method].lastValue !== null) {
callback(null, this.subscriptions[method].lastValue);
}
return id;
}
throw new Error(`provider.subscribe: Invalid method '${method}'`);
}
async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
const sub = this.subscriptionMap[id];
l.debug(() => ['unsubscribe', id, sub]);
if (!sub) {
throw new Error(`Unable to find subscription for ${id}`);
}
delete this.subscriptionMap[id];
delete this.subscriptions[sub].callbacks[id];
return true;
}
private init () {
const emitEvents: Array<ProviderInterface$Emitted> = ['connected', 'disconnected'];
let emitIndex = 0;
let newHead = this.makeBlockHeader(new BN(-1));
let counter = -1;
// Do something every 1 seconds
setInterval(() => {
if (!this.isUpdating) {
return false;
}
// create a new header (next block)
newHead = this.makeBlockHeader(newHead.blockNumber.toBn());
// increment the balances and nonce for each account
keyring.getPairs().forEach(({ publicKey }, index) => {
this.setStateBn(storage.balances.freeBalance(publicKey()), newHead.blockNumber.mul(3).iaddn(index));
this.setStateBn(storage.system.accountNonce(publicKey()), newHead.blockNumber.add(index));
});
// set the timestamp for the current block
this.setStateBn(storage.timestamp.now(), Math.floor(Date.now() / 1000));
this.updateSubs('chain_subscribeNewHead', newHead);
// We emit connected/disconnected at intervals
if (++counter % 2 === 1) {
if (++emitIndex === emitEvents.length) {
emitIndex = 0;
}
this.emitter.emit(emitEvents[emitIndex]);
}
}, INTERVAL);
}
private makeBlockHeader (prevNumber: BN): Header {
const blockNumber = prevNumber.addn(1);
return new Header({
digest: {
logs: []
},
extrinsicsRoot: randomAsU8a(),
number: blockNumber,
parentHash: blockNumber.isZero()
? new Uint8Array(32)
: bnToU8a(prevNumber, 256, false),
stateRoot: bnToU8a(blockNumber, 256, false)
});
}
private setStateBn (key: Uint8Array, value: BN | number): void {
this.db[u8aToHex(key)] = bnToU8a(value, 64, true);
}
private updateSubs (method: string, value: Base<any>) {
this.subscriptions[method].lastValue = value;
Object
.values(this.subscriptions[method].callbacks)
.forEach((cb) => {
try {
cb(null, value.toJSON());
} catch (error) {
console.error(`Error on '${method}' subscription`, error);
}
});
}
}
-83
View File
@@ -1,83 +0,0 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// FIXME: This file is way too long and way too messy
import { StorageFunction } from '@polkadot/types/StorageKey';
import { KeyringPair } from '@polkadot/keyring/types';
import { ProviderInterface$Emitted } from '../types';
import { MockState, MockState$Db, MockState$Subscriptions } from './types';
import BN from 'bn.js';
import storage from '@polkadot/storage/static';
import Header from '@polkadot/types/Header';
import { bnToU8a, u8aToHex } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
import testKeyring from '@polkadot/keyring/testing';
const keyring = testKeyring();
const emitEvents: Array<ProviderInterface$Emitted> = ['connected', 'disconnected'];
let emitIndex = 0;
function makeBlockHeader (prevNumber: BN) {
const blockNumber = prevNumber.addn(1);
return {
digest: {
logs: []
},
extrinsicsRoot: randomAsU8a(),
number: blockNumber,
parentHash: prevNumber.eqn(-1)
? new Uint8Array(32)
: bnToU8a(prevNumber, 256, false),
stateRoot: bnToU8a(blockNumber, 256, false)
};
}
function updateSubs (subscriptions: MockState$Subscriptions, method: string, value: any) {
subscriptions[method].lastValue = value;
Object
.values(subscriptions[method].callbacks)
.forEach((cb) => {
try {
cb(null, value);
} catch (error) {
console.error(`Error on '${method}' subscription`, error);
}
});
}
function setStorageBn (db: MockState$Db, createKey: StorageFunction, value: BN | number, ...keyParams: Array<Uint8Array>): void {
const keyValue = u8aToHex(
createKey(...keyParams)
);
db[keyValue] = bnToU8a(value, 64, true);
}
export default function mocks ({ emitter, db, subscriptions }: MockState): void {
let newHead = makeBlockHeader(new BN(-1));
setInterval(() => {
if (++emitIndex === emitEvents.length) {
emitIndex = 0;
}
emitter.emit(emitEvents[emitIndex]);
newHead = makeBlockHeader(newHead.number);
keyring.getPairs().forEach(({ publicKey }: KeyringPair, index: number) => {
setStorageBn(db, storage.balances.freeBalance, newHead.number.muln(3).iaddn(index), publicKey());
setStorageBn(db, storage.system.accountNonce, newHead.number.addn(index), publicKey());
});
setStorageBn(db, storage.timestamp.now, Math.floor(Date.now() / 1000));
updateSubs(subscriptions, 'chain_subscribeNewHead', new Header(newHead).toJSON());
}, 5000);
}
+31
View File
@@ -0,0 +1,31 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { ProviderInterface$Emitted } from '../types';
import Mock from './index';
describe('on', () => {
let mock: Mock;
beforeEach(() => {
mock = new Mock();
});
it('it emits both connected and disconnected events', (done) => {
const events: { [index: string]: boolean } = { connected: false, disconnected: false };
const handler = (type: ProviderInterface$Emitted) => {
mock.on(type, () => {
events[type] = true;
if (Object.values(events).filter((value) => value).length === 2) {
done();
}
});
};
handler('connected');
handler('disconnected');
});
});
-10
View File
@@ -1,10 +0,0 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
import { MockState } from './types';
export default function on (self: MockState, type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
self.emitter.on(type, sub);
}
@@ -0,0 +1,29 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import Mock from './index';
describe('send', () => {
let mock: Mock;
beforeEach(() => {
mock = new Mock();
});
it('fails on non-supported methods', () => {
return mock
.send('something_invalid', [])
.catch((error) => {
expect(error.message).toMatch(/Invalid method/);
});
});
it('returns values for mocked requests', () => {
return mock
.send('system_name', [])
.then((result) => {
expect(result).toBe('mockClient');
});
});
});
-13
View File
@@ -1,13 +0,0 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { MockState } from './types';
export default async function send ({ requests, db }: MockState, method: string, params: Array<any>): Promise<any> {
if (!requests[method]) {
throw new Error(`provider.send: Invalid method '${method}'`);
}
return requests[method](db, params);
}
@@ -1,33 +0,0 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import createState from './state';
describe('state', () => {
let state;
beforeEach(() => {
state = createState();
});
it('generates a sane initial state', () => {
expect(
state
).toMatchObject({
subscriptionId: 0,
subscriptionMap: {}
});
});
it('generates a proper section_method map', () => {
expect(
state.subscriptions
).toMatchObject({
'chain_subscribeNewHead': {
callbacks: {},
lastValue: null
}
});
});
});
-57
View File
@@ -1,57 +0,0 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { MockState, MockState$Db, MockState$Subscriptions } from './types';
import E3 from 'eventemitter3';
import interfaces from '@polkadot/jsonrpc/index';
import { logger, u8aToHex } from '@polkadot/util';
const l = logger('api-mock');
const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply(
[], Object.values(interfaces).map((area) =>
Object
.values(area.methods)
.filter((method) =>
method.isSubscription
)
.map(({ method, section }) =>
`${section}_${method}`
)
)
);
const REQUESTS = {
'state_getStorage': (storage: MockState$Db, params: Array<any>): string => {
return u8aToHex(
storage[(params[0] as string)]
);
},
'system_chain': (): string => 'mockChain',
'system_name': (): string => 'mockClient',
'system_version': (): string => '9.8.7'
};
export default function state (): MockState {
const db = {};
const subscriptions: MockState$Subscriptions = SUBSCRIPTIONS.reduce((subs, name) => {
subs[name] = {
callbacks: {},
lastValue: null
};
return subs;
}, ({} as MockState$Subscriptions));
return {
emitter: new E3.EventEmitter(),
l,
requests: Object.assign({}, REQUESTS),
db,
subscriptionId: 0,
subscriptionMap: {},
subscriptions
};
}
@@ -1,44 +0,0 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import createState from './state';
import subscribe from './subscribe';
describe('subscribe', () => {
let state;
beforeEach(() => {
state = createState();
});
it('fails on unknown methods', () => {
return subscribe(state, 'test', 'test_notFound').catch((error) => {
expect(error.message).toMatch(/Invalid method 'test_notFound'/);
});
});
it('returns a subscription id', () => {
return subscribe(state, 'chain_newHead', 'chain_subscribeNewHead', [() => void 0]).then((id) => {
expect(id).toEqual(state.subscriptionId);
});
});
it('stores the mapping values', () => {
const cb = () => void 0;
return subscribe(state, 'chain_newHead', 'chain_subscribeNewHead', [cb]).then((id) => {
expect(state.subscriptionMap[id]).toEqual('chain_subscribeNewHead');
expect(state.subscriptions['chain_subscribeNewHead'].callbacks[id]).toEqual(cb);
});
});
it('calls back with the last known value', (done) => {
state.subscriptions['chain_subscribeNewHead'].lastValue = 'testValue';
subscribe(state, 'chain_newHead', 'chain_subscribeNewHead', [(_, value) => {
expect(value).toEqual('testValue');
done();
}]);
});
});
@@ -0,0 +1,63 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import Mock from './index';
describe('subscribe', () => {
let mock: Mock;
beforeEach(() => {
mock = new Mock();
});
it('fails on unknown methods', () => {
return mock
.subscribe('test', 'test_notFound')
.catch((error) => {
expect(error.message).toMatch(/Invalid method 'test_notFound'/);
});
});
it('returns a subscription id', () => {
return mock
.subscribe('chain_newHead', 'chain_subscribeNewHead', () => void 0)
.then((id) => {
expect(id).toEqual(1);
});
});
it('calls back with the last known value', (done) => {
mock.isUpdating = false;
mock.subscriptions['chain_subscribeNewHead'].lastValue = 'testValue';
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, value: string) => {
expect(value).toEqual('testValue');
done();
});
});
it('calls back with new headers', (done) => {
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any) => {
if (header.number === 4) {
done();
}
});
});
it('handles errors withing callbacks gracefully', (done) => {
let hasThrown: boolean = false;
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any) => {
if (!hasThrown) {
hasThrown = true;
throw new Error('testing');
}
if (header.number === 3) {
done();
}
});
});
});
@@ -1,23 +0,0 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { MockState, MockState$Subscription$Callback } from './types';
export default async function subscribe (self: MockState, type: string, method: string, params: Array<any>): Promise<number> {
self.l.debug(() => ['subscribe', method, params]);
if (self.subscriptions[method]) {
const callback: MockState$Subscription$Callback = params.pop();
const id = ++self.subscriptionId;
self.subscriptions[method].callbacks[id] = callback;
self.subscriptionMap[id] = method;
callback(null, self.subscriptions[method].lastValue);
return id;
}
throw new Error(`provider.subscribe: Invalid method '${method}'`);
}
-12
View File
@@ -23,15 +23,3 @@ export type MockState$Db = {
export type MockState$Requests = {
[index: string]: (db: MockState$Db, params: Array<any>) => string
};
export type MockState = {
emitter: EventEmitter,
l: Logger,
requests: MockState$Requests,
db: MockState$Db,
subscriptionId: number,
subscriptionMap: {
[index: number]: string
},
subscriptions: MockState$Subscriptions
};
@@ -1,45 +0,0 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import createState from './state';
import subscribe from './subscribe';
import unsubscribe from './unsubscribe';
describe('unsubscribe', () => {
let state;
let id;
beforeEach(() => {
state = createState();
return subscribe(state, 'chain_newHead', 'chain_subscribeNewHead', [() => void 0]).then((_id) => {
id = _id;
});
});
it('fails on unknown ids', () => {
return unsubscribe(state, 'chain_newHead', 'chain_subscribeNewHead', 5).catch((error) => {
expect(error.message).toMatch(/Unable to find/);
});
});
it('unsubscribes successfully', () => {
return unsubscribe(state, 'chain_newHead', 'chain_subscribeNewHead', id);
});
it('fails on double unsubscribe', () => {
return unsubscribe(state, 'chain_newHead', 'chain_subscribeNewHead', id)
.then(() => unsubscribe(state, id))
.catch((error) => {
expect(error.message).toMatch(/Unable to find/);
});
});
it('clears the subscriptions', () => {
return unsubscribe(state, 'chain_newHead', 'chain_subscribeNewHead', id).then(() => {
expect(state.subscriptionMap[id]).not.toBeDefined();
expect(state.subscriptions['chain_subscribeNewHead'].callbacks[id]).not.toBeDefined();
});
});
});
@@ -0,0 +1,40 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import Mock from './index';
describe('unsubscribe', () => {
let mock: Mock;
let id: number;
beforeEach(() => {
mock = new Mock();
return mock
.subscribe('chain_newHead', 'chain_subscribeNewHead', () => void 0)
.then((_id) => {
id = _id;
});
});
it('fails on unknown ids', () => {
return mock
.unsubscribe('chain_newHead', 'chain_subscribeNewHead', 5)
.catch((error) => {
expect(error.message).toMatch(/Unable to find/);
});
});
it('unsubscribes successfully', () => {
return mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id);
});
it('fails on double unsubscribe', () => {
return mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id)
.then(() => mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id))
.catch((error) => {
expect(error.message).toMatch(/Unable to find/);
});
});
});
@@ -1,20 +0,0 @@
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { MockState } from './types';
export default async function unsubscribe (self: MockState, type: string, name: string, id: number): Promise<boolean> {
const method = self.subscriptionMap[id];
self.l.debug(() => ['unsubscribe', id, method]);
if (!method) {
throw new Error(`Unable to find subscription for ${id}`);
}
delete self.subscriptionMap[id];
delete self.subscriptions[method].callbacks[id];
return true;
}