Adding in unit tests for dev_funds (WIP)

This commit is contained in:
emizzle 2018-07-30 23:09:12 +10:00
parent c577ad6b16
commit 12304eac16
4 changed files with 299 additions and 28 deletions

View File

@ -1,33 +1,29 @@
const async = require('async');
const Web3 = require('web3');
const {getWeiBalanceFromString, buildUrl} = require('../../utils/utils.js');
const {readFileSync, dappPath} = require('../../core/fs');
const { getWeiBalanceFromString, buildUrl } = require('../../utils/utils.js');
const { readFileSync, dappPath } = require('../../core/fs');
class DevFunds {
constructor(blockchainConfig) {
// TODO: temporary to avoid nasty suprises, should be removed
try {
this.web3 = null;
this.blockchainConfig = blockchainConfig;
this.accounts = [];
this.numAccounts = this.blockchainConfig.account.numAccounts || 0;
this.password = readFileSync(dappPath(blockchainConfig.account.password), 'utf8').replace('\n', '');
this.web3 = new Web3();
this.networkId = null;
this.balance = Web3.utils.toWei("1", "ether");
if (this.blockchainConfig.account.balance) {
this.balance = getWeiBalanceFromString(this.blockchainConfig.account.balance, this.web3);
}
} catch(_err) {
// empty for now
constructor(blockchainConfig, provider, logger) {
this.blockchainConfig = blockchainConfig;
this.accounts = [];
this.numAccounts = this.blockchainConfig.account.numAccounts || 0;
this.password = blockchainConfig.account.password ? readFileSync(dappPath(blockchainConfig.account.password), 'utf8').replace('\n', '') : 'dev_password';
this.networkId = null;
this.balance = Web3.utils.toWei("1", "ether");
this.provider = provider || new Web3.providers.WebsocketProvider(buildUrl('ws', this.blockchainConfig.wsHost, this.blockchainConfig.wsPort), { headers: { Origin: "http://localhost:8000" } });
this.web3 = new Web3(provider);
if (this.blockchainConfig.account.balance) {
this.balance = getWeiBalanceFromString(this.blockchainConfig.account.balance, this.web3);
}
this.logger = logger || console;
}
_sendTx() {
if (this.networkId !== 1337) {
return;
}
this.web3.eth.sendTransaction({value: "1000000000000000", to: "0xA2817254cb8E7b6269D1689c3E0eBadbB78889d1", from: this.web3.eth.defaultAccount});
this.web3.eth.sendTransaction({ value: "1000000000000000", to: "0xA2817254cb8E7b6269D1689c3E0eBadbB78889d1", from: this.web3.eth.defaultAccount });
}
// trigger regular txs due to a bug in geth and stuck transactions in --dev mode
@ -39,7 +35,7 @@ class DevFunds {
return;
}
setInterval(function() { self._sendTx(); }, 1500);
setInterval(function () { self._sendTx(); }, 1500);
if (cb) {
cb();
}
@ -48,12 +44,10 @@ class DevFunds {
regularUnlocks() {
const self = this;
setInterval(function() { self.unlockAccounts(self.password, () => {}); }, 20000);
setInterval(function () { self.unlockAccounts(self.password, () => { }); }, 20000);
}
connectToNode(cb) {
this.web3.setProvider(new Web3.providers.WebsocketProvider(buildUrl('ws', this.blockchainConfig.wsHost, this.blockchainConfig.wsPort), {headers: {Origin: "http://localhost:8000"}}));
getCurrentAccounts(cb) {
this.web3.eth.getAccounts().then((accounts) => {
this.web3.eth.defaultAccount = accounts[0];
@ -86,16 +80,24 @@ class DevFunds {
}
fundAccounts(balance, cb) {
this.logger.info('[dev_funds]: funding accounts');
async.each(this.accounts, (account, next) => {
this.logger.info('[dev_funds]: funding acct ' + account);
this.web3.eth.getBalance(account).then(currBalance => {
this.logger.info('[dev_funds]: acct ' + account + ' current balance ' + currBalance);
const remainingBalance = balance - currBalance;
if (remainingBalance <= 0) return next();
this.web3.eth.sendTransaction({to: account, value: remainingBalance}).then((_result) => {
this.logger.info('[dev_funds]: funding acct ' + account + ' with ' + remainingBalance);
this.web3.eth.sendTransaction({ to: account, value: remainingBalance }).then((_result) => {
this.logger.info('[dev_funds]: funding result ' + JSON.stringify(_result));
next();
}).catch(next);
}, cb);
}, (err) => {
this.logger.info('[dev_funds]: done funding');
cb(err);
});
});
}
@ -105,7 +107,7 @@ class DevFunds {
}
async.waterfall([
(next) => {
this.connectToNode(next);
this.getCurrentAccounts(next);
},
(next) => {
this.createAccounts(this.numAccounts, this.password, next);

125
test/devFunds.js Normal file
View File

@ -0,0 +1,125 @@
/*global describe, it*/
const assert = require('assert');
let TestLogger = require('../lib/tests/test_logger.js');
const Web3 = require('web3');
const i18n = require('../lib/i18n/i18n.js');
const constants = require('../lib/constants.json');
const Test = require('../lib/tests/test');
const DevFunds = require('../lib/cmds/blockchain/dev_funds');
const async = require('async');
const FakeIpcProvider = require('./helpers/fakeIpcProvider');
const utils = require('../lib/utils/utils');
i18n.setOrDetectLocale('en');
describe('embark.DevFunds', function () {
let config = {
networkType: 'livenet',
genesisBlock: 'foo/bar/genesis.json',
geth_bin: 'geth',
datadir: '/foo/datadir/',
mineWhenNeeded: true,
rpcHost: 'someserver',
rpcPort: 12345,
rpcApi: ['eth', 'web3', 'net', 'debug'],
rpcCorsDomain: true,
networkId: 1,
port: 123456,
nodiscover: true,
maxpeers: 25,
mine: true,
vmdebug: false,
whisper: false,
account: {
password: './test/test1/password',
numAccounts: 3,
balance: "5 ether"
},
bootnodes: "",
wsApi: ["eth", "web3", "net", "shh", "debug"],
wsHost: "localhost",
wsOrigins: false,
wsPort: 8546,
wsRPC: true,
targetGasLimit: false,
syncMode: undefined,
syncmode: undefined,
verbosity: undefined,
proxy: true
};
if (config.proxy) {
config.wsPort += constants.blockchain.servicePortOnProxy;
config.rpcPort += constants.blockchain.servicePortOnProxy;
}
// TODO put default config
const test = new Test({ loglevel: 'trace' });
test.initWeb3Provider((err) => {
if (err) throw err;
describe('#create, fund, and unlock accounts', function () {
let provider = new FakeIpcProvider();
let devFunds = new DevFunds(config, provider, new TestLogger({}));
const web3 = new Web3(provider);
it('should create correct number of accounts', function (done) {
provider.injectResult(['0x47d33b27bb249a2dbab4c0612bf9caf4c1950855']); // getAccounts - return --dev account
devFunds.getCurrentAccounts(() => {
provider.injectResult('0x11f4d0a3c12e86b4b5f39b213f7e19d048276dae'); // createAccount #1
provider.injectResult('0x22f4d0a3c12e86b4b5f39b213f7e19d048276dab'); // createAccount #2
devFunds.createAccounts(config.account.numAccounts, 'test_password', (err) => {
assert.equal(err, null);
provider.injectResult(['0x47d33b27bb249a2dbab4c0612bf9caf4c1950855', '0x11f4d0a3c12e86b4b5f39b213f7e19d048276dae', '0x22f4d0a3c12e86b4b5f39b213f7e19d048276dab']);
web3.eth.getAccounts().then((accts) => {
console.log('got accts: ' + JSON.stringify(accts));
assert.equal(accts.length, config.account.numAccounts);
assert.strictEqual(accts[0], '0x47D33b27Bb249a2DBab4C0612BF9CaF4C1950855');
assert.strictEqual(accts[1], '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe');
assert.strictEqual(accts[2], '0x22F4d0A3C12E86b4b5F39B213f7e19D048276DAb');
done();
});
});
});
});
it('should fund accounts', function (done) {
console.dir('funding accounts...');
provider.injectResult('1234567890'); // account #1 balance
provider.injectResult('1234567890'); // account #2 balance
provider.injectResult('0xfff12345678976543213456786543212345675432'); // send tx #1
provider.injectResult('0xfff12345678976543213456786543212345675433'); // send tx #2
try {
devFunds.fundAccounts(devFunds.balance, (err) => {
console.dir('accounts funded...');
assert.equal(err, null);
provider.injectResult(['0x47d33b27bb249a2dbab4c0612bf9caf4c1950855', '0x11f4d0a3c12e86b4b5f39b213f7e19d048276dae', '0x22f4d0a3c12e86b4b5f39b213f7e19d048276dab']);
web3.eth.getAccounts().then((accts) => {
console.log('got accts: ' + JSON.stringify(accts));
const weiFromConfig = utils.getWeiBalanceFromString(config.account.balance);
async.each(accts, (acct, cb) => {
provider.injectResult(web3.utils.numberToHex(weiFromConfig));
devFunds.web3.eth.getBalance(acct).then((wei) => {
assert.equal(wei, weiFromConfig);
cb();
}).catch(cb);
}, function(err) { done(); });
}).catch(() => {
done();
});
});
} catch (errFundAccts) {
throw errFundAccts;
}
});
});
});
});

View File

@ -0,0 +1,143 @@
var assert = require('assert');
var _ = require('lodash');
var FakeIpcProvider = function IpcProvider() {
var _this = this;
this.countId = 1;
this.notificationCount = 1;
this.getResponseStub = function () {
return {
jsonrpc: '2.0',
id: _this.countId,
result: null
};
};
this.getErrorStub = function () {
return {
jsonrpc: '2.0',
id: _this.countId,
error: {
code: 1234,
message: 'Stub error'
}
};
};
this.response = [];
this.error = [];
this.validation = [];
this.notificationCallbacks = [];
};
FakeIpcProvider.prototype.send = function (payload, callback) {
var _this = this;
// set id
if(payload.id)
this.countId = payload.id;
// else
// this.countId++;
assert.equal(_.isArray(payload) || _.isObject(payload), true);
assert.equal(_.isFunction(callback), true);
var validation = this.validation.shift();
if (validation) {
// imitate plain json object
validation(JSON.parse(JSON.stringify(payload)), callback);
}
var response = this.getResponseOrError('response', payload);
var error = this.getResponseOrError('error', payload);
setTimeout(function(){
callback(error, response);
}, 1);
};
FakeIpcProvider.prototype.on = function (type, callback) {
if(type === 'data') {
this.notificationCallbacks.push(callback);
}
};
FakeIpcProvider.prototype.getResponseOrError = function (type, payload) {
var _this = this;
var response;
if(type === 'error') {
response = this.error.shift();
} else {
response = this.response.shift() || this.getResponseStub();
}
if(response) {
if(_.isArray(response)) {
response = response.map(function(resp, index) {
resp.id = payload[index] ? payload[index].id : _this.countId++;
return resp;
});
} else
response.id = payload.id;
}
return response;
};
FakeIpcProvider.prototype.injectNotification = function (notification) {
var _this = this;
setTimeout(function(){
_this.notificationCallbacks.forEach(function(cb){
if(notification && cb)
cb(null, notification);
});
}, 100 + this.notificationCount);
this.notificationCount += 10;
};
// FakeHttpProvider.prototype.injectResponse = function (response) {
// this.response = response;
// };
FakeIpcProvider.prototype.injectBatchResults = function (results, error) {
var _this = this;
this.response.push(results.map(function (r) {
if(error) {
var response = _this.getErrorStub();
response.error.message = r;
} else {
var response = _this.getResponseStub();
response.result = r;
}
return response;
}));
};
FakeIpcProvider.prototype.injectResult = function (result) {
var response = this.getResponseStub();
response.result = result;
this.response.push(response);
};
FakeIpcProvider.prototype.injectError = function (error) {
var errorStub = this.getErrorStub();
errorStub.error = error; // message, code
this.error.push(errorStub);
};
FakeIpcProvider.prototype.injectValidation = function (callback) {
this.validation.push(callback);
};
module.exports = FakeIpcProvider;

1
test/test1/password Normal file
View File

@ -0,0 +1 @@
dev_password