1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 01:39:44 +01:00

Lint tests

This commit is contained in:
Thomas Huang 2017-05-04 14:35:10 -07:00
parent 8f5334e4ac
commit 0b13429daf
32 changed files with 439 additions and 482 deletions

View File

@ -155,7 +155,7 @@ ConfigManager.prototype.getCurrentRpcAddress = function () {
case 'kovan': case 'kovan':
return KOVAN_RPC return KOVAN_RPC
case 'rinkeby': case 'rinkeby':
return RINKEBY_RPC return RINKEBY_RPC

View File

@ -20,14 +20,12 @@ window.localStorage = {}
if (!window.crypto) window.crypto = {} if (!window.crypto) window.crypto = {}
if (!window.crypto.getRandomValues) window.crypto.getRandomValues = require('polyfill-crypto.getrandomvalues') if (!window.crypto.getRandomValues) window.crypto.getRandomValues = require('polyfill-crypto.getrandomvalues')
function enableFailureOnUnhandledPromiseRejection () {
function enableFailureOnUnhandledPromiseRejection() {
// overwrite node's promise with the stricter Bluebird promise // overwrite node's promise with the stricter Bluebird promise
global.Promise = require('bluebird') global.Promise = require('bluebird')
// modified from https://github.com/mochajs/mocha/issues/1926#issuecomment-180842722 // modified from https://github.com/mochajs/mocha/issues/1926#issuecomment-180842722
// rethrow unhandledRejections // rethrow unhandledRejections
if (typeof process !== 'undefined') { if (typeof process !== 'undefined') {
process.on('unhandledRejection', function (reason) { process.on('unhandledRejection', function (reason) {
@ -51,4 +49,4 @@ function enableFailureOnUnhandledPromiseRejection() {
typeof (console.error || console.log) === 'function') { typeof (console.error || console.log) === 'function') {
(console.error || console.log)('Unhandled rejections will be ignored!') (console.error || console.log)('Unhandled rejections will be ignored!')
} }
} }

View File

@ -1,6 +1,6 @@
function wait(time) { function wait(time) {
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
setTimeout(function() { setTimeout(function () {
resolve() resolve()
}, time * 3 || 1500) }, time * 3 || 1500)
}) })

View File

@ -1,10 +1,10 @@
var fs = require('fs') var fs = require('fs')
var path = require('path') var path = require('path')
var browserify = require('browserify'); var browserify = require('browserify')
var tests = fs.readdirSync(path.join(__dirname, 'lib')) var tests = fs.readdirSync(path.join(__dirname, 'lib'))
var bundlePath = path.join(__dirname, 'bundle.js') var bundlePath = path.join(__dirname, 'bundle.js')
var b = browserify(); var b = browserify()
// Remove old bundle // Remove old bundle
try { try {
@ -13,9 +13,9 @@ try {
var writeStream = fs.createWriteStream(bundlePath) var writeStream = fs.createWriteStream(bundlePath)
tests.forEach(function(fileName) { tests.forEach(function (fileName) {
b.add(path.join(__dirname, 'lib', fileName)) b.add(path.join(__dirname, 'lib', fileName))
}) })
b.bundle().pipe(writeStream); b.bundle().pipe(writeStream)

View File

@ -2,9 +2,9 @@ const ObservableStore = require('obs-store')
const clone = require('clone') const clone = require('clone')
const ConfigManager = require('../../app/scripts/lib/config-manager') const ConfigManager = require('../../app/scripts/lib/config-manager')
const firstTimeState = require('../../app/scripts/first-time-state') const firstTimeState = require('../../app/scripts/first-time-state')
const STORAGE_KEY = 'metamask-config' // const STORAGE_KEY = 'metamask-config'
module.exports = function() { module.exports = function () {
let store = new ObservableStore(clone(firstTimeState)) const store = new ObservableStore(clone(firstTimeState))
return new ConfigManager({ store }) return new ConfigManager({ store })
} }

View File

@ -4,28 +4,28 @@ let cacheVal
module.exports = { module.exports = {
encrypt(password, dataObj) { encrypt (password, dataObj) {
cacheVal = dataObj cacheVal = dataObj
return Promise.resolve(mockHex) return Promise.resolve(mockHex)
}, },
decrypt(password, text) { decrypt (password, text) {
return Promise.resolve(cacheVal || {}) return Promise.resolve(cacheVal || {})
}, },
encryptWithKey(key, dataObj) { encryptWithKey (key, dataObj) {
return this.encrypt(key, dataObj) return this.encrypt(key, dataObj)
}, },
decryptWithKey(key, text) { decryptWithKey (key, text) {
return this.decrypt(key, text) return this.decrypt(key, text)
}, },
keyFromPassword(password) { keyFromPassword (password) {
return Promise.resolve(mockKey) return Promise.resolve(mockKey)
}, },
generateSalt() { generateSalt () {
return 'WHADDASALT!' return 'WHADDASALT!'
}, },

View File

@ -6,32 +6,32 @@ const type = 'Simple Key Pair'
module.exports = class MockSimpleKeychain { module.exports = class MockSimpleKeychain {
static type() { return type } static type () { return type }
constructor(opts) { constructor (opts) {
this.type = type this.type = type
this.opts = opts || {} this.opts = opts || {}
this.wallets = [] this.wallets = []
} }
serialize() { serialize () {
return [ fakeWallet.privKey ] return [ fakeWallet.privKey ]
} }
deserialize(data) { deserialize (data) {
if (!Array.isArray(data)) { if (!Array.isArray(data)) {
throw new Error('Simple keychain deserialize requires a privKey array.') throw new Error('Simple keychain deserialize requires a privKey array.')
} }
this.wallets = [ fakeWallet ] this.wallets = [ fakeWallet ]
} }
addAccounts(n = 1) { addAccounts (n = 1) {
for(var i = 0; i < n; i++) { for (var i = 0; i < n; i++) {
this.wallets.push(fakeWallet) this.wallets.push(fakeWallet)
} }
} }
getAccounts() { getAccounts () {
return this.wallets.map(w => w.address) return this.wallets.map(w => w.address)
} }

View File

@ -1,18 +1,16 @@
var assert = require('assert') var assert = require('assert')
var linkGen = require('../../ui/lib/account-link') var linkGen = require('../../ui/lib/account-link')
describe('account-link', function() { describe('account-link', function () {
it('adds ropsten prefix to ropsten test network', function () {
it('adds ropsten prefix to ropsten test network', function() {
var result = linkGen('account', '3') var result = linkGen('account', '3')
assert.notEqual(result.indexOf('ropsten'), -1, 'ropsten included') assert.notEqual(result.indexOf('ropsten'), -1, 'ropsten included')
assert.notEqual(result.indexOf('account'), -1, 'account included') assert.notEqual(result.indexOf('account'), -1, 'account included')
}) })
it('adds kovan prefix to kovan test network', function() { it('adds kovan prefix to kovan test network', function () {
var result = linkGen('account', '42') var result = linkGen('account', '42')
assert.notEqual(result.indexOf('kovan'), -1, 'kovan included') assert.notEqual(result.indexOf('kovan'), -1, 'kovan included')
assert.notEqual(result.indexOf('account'), -1, 'account included') assert.notEqual(result.indexOf('account'), -1, 'account included')
}) })
}) })

View File

@ -1,36 +1,34 @@
var jsdom = require('mocha-jsdom') // var jsdom = require('mocha-jsdom')
var assert = require('assert') var assert = require('assert')
var freeze = require('deep-freeze-strict') var freeze = require('deep-freeze-strict')
var path = require('path') var path = require('path')
var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js'))
var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js'))
describe ('config view actions', function() {
describe('config view actions', function () {
var initialState = { var initialState = {
metamask: { metamask: {
rpcTarget: 'foo', rpcTarget: 'foo',
frequentRpcList: [] frequentRpcList: [],
}, },
appState: { appState: {
currentView: { currentView: {
name: 'accounts', name: 'accounts',
} },
} },
} }
freeze(initialState) freeze(initialState)
describe('SHOW_CONFIG_PAGE', function() { describe('SHOW_CONFIG_PAGE', function () {
it('should set appState.currentView.name to config', function() { it('should set appState.currentView.name to config', function () {
var result = reducers(initialState, actions.showConfigPage()) var result = reducers(initialState, actions.showConfigPage())
assert.equal(result.appState.currentView.name, 'config') assert.equal(result.appState.currentView.name, 'config')
}) })
}) })
describe('SET_RPC_TARGET', function() { describe('SET_RPC_TARGET', function () {
it('sets the state.metamask.rpcTarget property of the state to the action.value', function () {
it('sets the state.metamask.rpcTarget property of the state to the action.value', function() {
const action = { const action = {
type: actions.SET_RPC_TARGET, type: actions.SET_RPC_TARGET,
value: 'foo', value: 'foo',
@ -41,5 +39,4 @@ describe ('config view actions', function() {
assert.equal(result.metamask.provider.rpcTarget, 'foo') assert.equal(result.metamask.provider.rpcTarget, 'foo')
}) })
}) })
}) })

View File

@ -1,22 +1,21 @@
var jsdom = require('mocha-jsdom') // var jsdom = require('mocha-jsdom')
var assert = require('assert') var assert = require('assert')
var freeze = require('deep-freeze-strict') var freeze = require('deep-freeze-strict')
var path = require('path') var path = require('path')
var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js'))
var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js'))
describe('SAVE_ACCOUNT_LABEL', function() { describe('SAVE_ACCOUNT_LABEL', function () {
it('updates the state.metamask.identities[:i].name property of the state to the action.value.label', function () {
it('updates the state.metamask.identities[:i].name property of the state to the action.value.label', function() {
var initialState = { var initialState = {
metamask: { metamask: {
identities: { identities: {
foo: { foo: {
name: 'bar' name: 'bar',
} },
}, },
} },
} }
freeze(initialState) freeze(initialState)
@ -24,13 +23,13 @@ describe('SAVE_ACCOUNT_LABEL', function() {
type: actions.SAVE_ACCOUNT_LABEL, type: actions.SAVE_ACCOUNT_LABEL,
value: { value: {
account: 'foo', account: 'foo',
label: 'baz' label: 'baz',
}, },
} }
freeze(action) freeze(action)
var resultingState = reducers(initialState, action) var resultingState = reducers(initialState, action)
assert.equal(resultingState.metamask.identities.foo.name, action.value.label) assert.equal(resultingState.metamask.identities.foo.name, action.value.label)
}); })
}); })

View File

@ -1,18 +1,17 @@
var jsdom = require('mocha-jsdom') // var jsdom = require('mocha-jsdom')
var assert = require('assert') var assert = require('assert')
var freeze = require('deep-freeze-strict') var freeze = require('deep-freeze-strict')
var path = require('path') var path = require('path')
var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js'))
var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js'))
describe('SET_SELECTED_ACCOUNT', function() { describe('SET_SELECTED_ACCOUNT', function () {
it('sets the state.appState.activeAddress property of the state to the action.value', function () {
it('sets the state.appState.activeAddress property of the state to the action.value', function() {
var initialState = { var initialState = {
appState: { appState: {
activeAddress: 'foo', activeAddress: 'foo',
} },
} }
freeze(initialState) freeze(initialState)
@ -24,15 +23,15 @@ describe('SET_SELECTED_ACCOUNT', function() {
var resultingState = reducers(initialState, action) var resultingState = reducers(initialState, action)
assert.equal(resultingState.appState.activeAddress, action.value) assert.equal(resultingState.appState.activeAddress, action.value)
}); })
}); })
describe('SHOW_ACCOUNT_DETAIL', function() { describe('SHOW_ACCOUNT_DETAIL', function () {
it('updates metamask state', function() { it('updates metamask state', function () {
var initialState = { var initialState = {
metamask: { metamask: {
selectedAddress: 'foo' selectedAddress: 'foo',
} },
} }
freeze(initialState) freeze(initialState)

View File

@ -1,29 +1,27 @@
var jsdom = require('mocha-jsdom') // var jsdom = require('mocha-jsdom')
var assert = require('assert') var assert = require('assert')
var freeze = require('deep-freeze-strict') var freeze = require('deep-freeze-strict')
var path = require('path') var path = require('path')
var sinon = require('sinon') var sinon = require('sinon')
var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js'))
var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js'))
describe('tx confirmation screen', function() { describe('tx confirmation screen', function () {
beforeEach(function () {
this.sinon = sinon.sandbox.create()
})
beforeEach(function() { afterEach(function () {
this.sinon = sinon.sandbox.create(); this.sinon.restore()
}); })
afterEach(function(){
this.sinon.restore();
});
var initialState, result var initialState, result
describe('when there is only one tx', function() { describe('when there is only one tx', function () {
var firstTxId = 1457634084250832 var firstTxId = 1457634084250832
beforeEach(function() { beforeEach(function () {
initialState = { initialState = {
appState: { appState: {
currentView: { currentView: {
@ -34,70 +32,66 @@ describe('tx confirmation screen', function() {
unapprovedTxs: { unapprovedTxs: {
'1457634084250832': { '1457634084250832': {
id: 1457634084250832, id: 1457634084250832,
status: "unconfirmed", status: 'unconfirmed',
time: 1457634084250, time: 1457634084250,
} },
}, },
} },
} }
freeze(initialState) freeze(initialState)
}) })
describe('cancelTx', function() { describe('cancelTx', function () {
before(function (done) {
before(function(done) {
actions._setBackgroundConnection({ actions._setBackgroundConnection({
approveTransaction(txId, cb) { cb('An error!') }, approveTransaction (txId, cb) { cb('An error!') },
cancelTransaction(txId) { /* noop */ }, cancelTransaction (txId) { /* noop */ },
clearSeedWordCache(cb) { cb() }, clearSeedWordCache (cb) { cb() },
}) })
let action = actions.cancelTx({value: firstTxId}) const action = actions.cancelTx({value: firstTxId})
result = reducers(initialState, action) result = reducers(initialState, action)
done() done()
}) })
it('should transition to the account detail view', function() { it('should transition to the account detail view', function () {
assert.equal(result.appState.currentView.name, 'accountDetail') assert.equal(result.appState.currentView.name, 'accountDetail')
}) })
it('should have no unconfirmed txs remaining', function() { it('should have no unconfirmed txs remaining', function () {
var count = getUnconfirmedTxCount(result) var count = getUnconfirmedTxCount(result)
assert.equal(count, 0) assert.equal(count, 0)
}) })
}) })
describe('sendTx', function() { describe('sendTx', function () {
var result var result
describe('when there is an error', function() { describe('when there is an error', function () {
before(function (done) {
before(function(done) {
alert = () => {/* noop */}
actions._setBackgroundConnection({ actions._setBackgroundConnection({
approveTransaction(txId, cb) { cb({message: 'An error!'}) }, approveTransaction (txId, cb) { cb({message: 'An error!'}) },
}) })
actions.sendTx({id: firstTxId})(function(action) { actions.sendTx({id: firstTxId})(function (action) {
result = reducers(initialState, action) result = reducers(initialState, action)
done() done()
}) })
}) })
it('should stay on the page', function() { it('should stay on the page', function () {
assert.equal(result.appState.currentView.name, 'confTx') assert.equal(result.appState.currentView.name, 'confTx')
}) })
it('should set errorMessage on the currentView', function() { it('should set errorMessage on the currentView', function () {
assert(result.appState.currentView.errorMessage) assert(result.appState.currentView.errorMessage)
}) })
}) })
describe('when there is success', function() { describe('when there is success', function () {
it('should complete tx and go home', function() { it('should complete tx and go home', function () {
actions._setBackgroundConnection({ actions._setBackgroundConnection({
approveTransaction(txId, cb) { cb() }, approveTransaction (txId, cb) { cb() },
}) })
var dispatchExpect = sinon.mock() var dispatchExpect = sinon.mock()
@ -108,10 +102,10 @@ describe('tx confirmation screen', function() {
}) })
}) })
describe('when there are two pending txs', function() { describe('when there are two pending txs', function () {
var firstTxId = 1457634084250832 var firstTxId = 1457634084250832
var result, initialState var result, initialState
before(function(done) { before(function (done) {
initialState = { initialState = {
appState: { appState: {
currentView: { currentView: {
@ -122,42 +116,42 @@ describe('tx confirmation screen', function() {
unapprovedTxs: { unapprovedTxs: {
'1457634084250832': { '1457634084250832': {
id: firstTxId, id: firstTxId,
status: "unconfirmed", status: 'unconfirmed',
time: 1457634084250, time: 1457634084250,
}, },
'1457634084250833': { '1457634084250833': {
id: 1457634084250833, id: 1457634084250833,
status: "unconfirmed", status: 'unconfirmed',
time: 1457634084255, time: 1457634084255,
}, },
}, },
} },
} }
freeze(initialState) freeze(initialState)
// Mocking a background connection: // Mocking a background connection:
actions._setBackgroundConnection({ actions._setBackgroundConnection({
approveTransaction(firstTxId, cb) { cb() }, approveTransaction (firstTxId, cb) { cb() },
}) })
let action = actions.sendTx({id: firstTxId})(function(action) { actions.sendTx({id: firstTxId})(function (action) {
result = reducers(initialState, action) result = reducers(initialState, action)
}) })
done() done()
}) })
it('should stay on the confTx view', function() { it('should stay on the confTx view', function () {
assert.equal(result.appState.currentView.name, 'confTx') assert.equal(result.appState.currentView.name, 'confTx')
}) })
it('should transition to the first tx', function() { it('should transition to the first tx', function () {
assert.equal(result.appState.currentView.context, 0) assert.equal(result.appState.currentView.context, 0)
}) })
}) })
}) })
}); })
function getUnconfirmedTxCount(state) { function getUnconfirmedTxCount (state) {
var txs = state.metamask.unapprovedTxs var txs = state.metamask.unapprovedTxs
var count = Object.keys(txs).length var count = Object.keys(txs).length
return count return count

View File

@ -1,23 +1,22 @@
var jsdom = require('mocha-jsdom') // var jsdom = require('mocha-jsdom')
var assert = require('assert') var assert = require('assert')
var freeze = require('deep-freeze-strict') var freeze = require('deep-freeze-strict')
var path = require('path') var path = require('path')
var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js'))
var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js'))
describe('SHOW_INFO_PAGE', function() { describe('SHOW_INFO_PAGE', function () {
it('sets the state.appState.currentView.name property to info', function () {
it('sets the state.appState.currentView.name property to info', function() {
var initialState = { var initialState = {
appState: { appState: {
activeAddress: 'foo', activeAddress: 'foo',
} },
} }
freeze(initialState) freeze(initialState)
const action = actions.showInfoPage() const action = actions.showInfoPage()
var resultingState = reducers(initialState, action) var resultingState = reducers(initialState, action)
assert.equal(resultingState.appState.currentView.name, 'info') assert.equal(resultingState.appState.currentView.name, 'info')
}); })
}); })

View File

@ -1,14 +1,13 @@
var jsdom = require('mocha-jsdom') // var jsdom = require('mocha-jsdom')
var assert = require('assert') var assert = require('assert')
var freeze = require('deep-freeze-strict') var freeze = require('deep-freeze-strict')
var path = require('path') var path = require('path')
var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js'))
var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js'))
describe('action DISPLAY_WARNING', function() { describe('action DISPLAY_WARNING', function () {
it('sets appState.warning to provided value', function () {
it('sets appState.warning to provided value', function() {
var initialState = { var initialState = {
appState: {}, appState: {},
} }
@ -20,5 +19,5 @@ describe('action DISPLAY_WARNING', function() {
const resultingState = reducers(initialState, action) const resultingState = reducers(initialState, action)
assert.equal(resultingState.appState.warning, warningText, 'warning text set') assert.equal(resultingState.appState.warning, warningText, 'warning text set')
}); })
}); })

View File

@ -1,5 +1,5 @@
const assert = require('assert') const assert = require('assert')
const extend = require('xtend') // const extend = require('xtend')
const AddressBookController = require('../../app/scripts/controllers/address-book') const AddressBookController = require('../../app/scripts/controllers/address-book')
const mockKeyringController = { const mockKeyringController = {
@ -7,21 +7,20 @@ const mockKeyringController = {
getState: function () { getState: function () {
return { return {
identities: { identities: {
'0x0aaa' : { '0x0aaa': {
address: '0x0aaa', address: '0x0aaa',
name: 'owned', name: 'owned',
} },
} },
} }
} },
} },
} }
describe('address-book-controller', function () {
describe('address-book-controller', function() {
var addressBookController var addressBookController
beforeEach(function() { beforeEach(function () {
addressBookController = new AddressBookController({}, mockKeyringController) addressBookController = new AddressBookController({}, mockKeyringController)
}) })

View File

@ -1,24 +1,22 @@
var assert = require('assert') var assert = require('assert')
var BinaryRenderer = require('../../../ui/app/components/binary-renderer') var BinaryRenderer = require('../../../ui/app/components/binary-renderer')
describe('BinaryRenderer', function() { describe('BinaryRenderer', function () {
let binaryRenderer let binaryRenderer
const message = 'Hello, world!' const message = 'Hello, world!'
const buffer = new Buffer(message, 'utf8') const buffer = new Buffer(message, 'utf8')
const hex = buffer.toString('hex') const hex = buffer.toString('hex')
beforeEach(function() { beforeEach(function () {
binaryRenderer = new BinaryRenderer() binaryRenderer = new BinaryRenderer()
}) })
it('recovers message', function() { it('recovers message', function () {
const result = binaryRenderer.hexToText(hex) const result = binaryRenderer.hexToText(hex)
assert.equal(result, message) assert.equal(result, message)
}) })
it('recovers message with hex prefix', function () {
it('recovers message with hex prefix', function() {
const result = binaryRenderer.hexToText('0x' + hex) const result = binaryRenderer.hexToText('0x' + hex)
assert.equal(result, message) assert.equal(result, message)
}) })

View File

@ -2,26 +2,25 @@
global.fetch = global.fetch || require('isomorphic-fetch') global.fetch = global.fetch || require('isomorphic-fetch')
const assert = require('assert') const assert = require('assert')
const extend = require('xtend') // const extend = require('xtend')
const rp = require('request-promise') // const rp = require('request-promise')
const nock = require('nock') // const nock = require('nock')
const configManagerGen = require('../lib/mock-config-manager') const configManagerGen = require('../lib/mock-config-manager')
describe('config-manager', function() { describe('config-manager', function () {
var configManager var configManager
beforeEach(function() { beforeEach(function () {
configManager = configManagerGen() configManager = configManagerGen()
}) })
describe('#setConfig', function() { describe('#setConfig', function () {
it('should set the config key', function () { it('should set the config key', function () {
var testConfig = { var testConfig = {
provider: { provider: {
type: 'rpc', type: 'rpc',
rpcTarget: 'foobar' rpcTarget: 'foobar',
} },
} }
configManager.setConfig(testConfig) configManager.setConfig(testConfig)
var result = configManager.getData() var result = configManager.getData()
@ -30,17 +29,17 @@ describe('config-manager', function() {
assert.equal(result.config.provider.rpcTarget, testConfig.provider.rpcTarget) assert.equal(result.config.provider.rpcTarget, testConfig.provider.rpcTarget)
}) })
it('setting wallet should not overwrite config', function() { it('setting wallet should not overwrite config', function () {
var testConfig = { var testConfig = {
provider: { provider: {
type: 'rpc', type: 'rpc',
rpcTarget: 'foobar' rpcTarget: 'foobar',
}, },
} }
configManager.setConfig(testConfig) configManager.setConfig(testConfig)
var testWallet = { var testWallet = {
name: 'this is my fake wallet' name: 'this is my fake wallet',
} }
configManager.setWallet(testWallet) configManager.setWallet(testWallet)
@ -58,13 +57,13 @@ describe('config-manager', function() {
}) })
}) })
describe('wallet nicknames', function() { describe('wallet nicknames', function () {
it('should return null when no nicknames are saved', function() { it('should return null when no nicknames are saved', function () {
var nick = configManager.nicknameForWallet('0x0') var nick = configManager.nicknameForWallet('0x0')
assert.equal(nick, null, 'no nickname returned') assert.equal(nick, null, 'no nickname returned')
}) })
it('should persist nicknames', function() { it('should persist nicknames', function () {
var account = '0x0' var account = '0x0'
var nick1 = 'foo' var nick1 = 'foo'
var nick2 = 'bar' var nick2 = 'bar'
@ -79,8 +78,8 @@ describe('config-manager', function() {
}) })
}) })
describe('rpc manipulations', function() { describe('rpc manipulations', function () {
it('changing rpc should return a different rpc', function() { it('changing rpc should return a different rpc', function () {
var firstRpc = 'first' var firstRpc = 'first'
var secondRpc = 'second' var secondRpc = 'second'
@ -94,21 +93,21 @@ describe('config-manager', function() {
}) })
}) })
describe('transactions', function() { describe('transactions', function () {
beforeEach(function() { beforeEach(function () {
configManager.setTxList([]) configManager.setTxList([])
}) })
describe('#getTxList', function() { describe('#getTxList', function () {
it('when new should return empty array', function() { it('when new should return empty array', function () {
var result = configManager.getTxList() var result = configManager.getTxList()
assert.ok(Array.isArray(result)) assert.ok(Array.isArray(result))
assert.equal(result.length, 0) assert.equal(result.length, 0)
}) })
}) })
describe('#setTxList', function() { describe('#setTxList', function () {
it('saves the submitted data to the tx list', function() { it('saves the submitted data to the tx list', function () {
var target = [{ foo: 'bar' }] var target = [{ foo: 'bar' }]
configManager.setTxList(target) configManager.setTxList(target)
var result = configManager.getTxList() var result = configManager.getTxList()

View File

@ -2,26 +2,25 @@
global.fetch = global.fetch || require('isomorphic-fetch') global.fetch = global.fetch || require('isomorphic-fetch')
const assert = require('assert') const assert = require('assert')
const extend = require('xtend') // const extend = require('xtend')
const rp = require('request-promise') // const rp = require('request-promise')
const nock = require('nock') const nock = require('nock')
const CurrencyController = require('../../app/scripts/controllers/currency') const CurrencyController = require('../../app/scripts/controllers/currency')
describe('currency-controller', function() { describe('currency-controller', function () {
var currencyController var currencyController
beforeEach(function() { beforeEach(function () {
currencyController = new CurrencyController() currencyController = new CurrencyController()
}) })
describe('currency conversions', function() { describe('currency conversions', function () {
describe('#setCurrentCurrency', function () {
describe('#setCurrentCurrency', function() { it('should return USD as default', function () {
it('should return USD as default', function() {
assert.equal(currencyController.getCurrentCurrency(), 'USD') assert.equal(currencyController.getCurrentCurrency(), 'USD')
}) })
it('should be able to set to other currency', function() { it('should be able to set to other currency', function () {
assert.equal(currencyController.getCurrentCurrency(), 'USD') assert.equal(currencyController.getCurrentCurrency(), 'USD')
currencyController.setCurrentCurrency('JPY') currencyController.setCurrentCurrency('JPY')
var result = currencyController.getCurrentCurrency() var result = currencyController.getCurrentCurrency()
@ -29,39 +28,38 @@ describe('currency-controller', function() {
}) })
}) })
describe('#getConversionRate', function() { describe('#getConversionRate', function () {
it('should return undefined if non-existent', function() { it('should return undefined if non-existent', function () {
var result = currencyController.getConversionRate() var result = currencyController.getConversionRate()
assert.ok(!result) assert.ok(!result)
}) })
}) })
describe('#updateConversionRate', function() { describe('#updateConversionRate', function () {
it('should retrieve an update for ETH to USD and set it in memory', function(done) { it('should retrieve an update for ETH to USD and set it in memory', function (done) {
this.timeout(15000) this.timeout(15000)
var usdMock = nock('https://www.cryptonator.com') nock('https://www.cryptonator.com')
.get('/api/ticker/eth-USD') .get('/api/ticker/eth-USD')
.reply(200, '{"ticker":{"base":"ETH","target":"USD","price":"11.02456145","volume":"44948.91745289","change":"-0.01472534"},"timestamp":1472072136,"success":true,"error":""}') .reply(200, '{"ticker":{"base":"ETH","target":"USD","price":"11.02456145","volume":"44948.91745289","change":"-0.01472534"},"timestamp":1472072136,"success":true,"error":""}')
assert.equal(currencyController.getConversionRate(), 0) assert.equal(currencyController.getConversionRate(), 0)
currencyController.setCurrentCurrency('USD') currencyController.setCurrentCurrency('USD')
currencyController.updateConversionRate() currencyController.updateConversionRate()
.then(function() { .then(function () {
var result = currencyController.getConversionRate() var result = currencyController.getConversionRate()
console.log('currencyController.getConversionRate:', result) console.log('currencyController.getConversionRate:', result)
assert.equal(typeof result, 'number') assert.equal(typeof result, 'number')
done() done()
}).catch(function(err) { }).catch(function (err) {
done(err) done(err)
}) })
}) })
it('should work for JPY as well.', function() { it('should work for JPY as well.', function () {
this.timeout(15000) this.timeout(15000)
assert.equal(currencyController.getConversionRate(), 0) assert.equal(currencyController.getConversionRate(), 0)
var jpyMock = nock('https://www.cryptonator.com') nock('https://www.cryptonator.com')
.get('/api/ticker/eth-JPY') .get('/api/ticker/eth-JPY')
.reply(200, '{"ticker":{"base":"ETH","target":"JPY","price":"11.02456145","volume":"44948.91745289","change":"-0.01472534"},"timestamp":1472072136,"success":true,"error":""}') .reply(200, '{"ticker":{"base":"ETH","target":"JPY","price":"11.02456145","volume":"44948.91745289","change":"-0.01472534"},"timestamp":1472072136,"success":true,"error":""}')
@ -69,19 +67,18 @@ describe('currency-controller', function() {
var promise = new Promise( var promise = new Promise(
function (resolve, reject) { function (resolve, reject) {
currencyController.setCurrentCurrency('JPY') currencyController.setCurrentCurrency('JPY')
currencyController.updateConversionRate().then(function() { currencyController.updateConversionRate().then(function () {
resolve() resolve()
}) })
}) })
promise.then(function() { promise.then(function () {
var result = currencyController.getConversionRate() var result = currencyController.getConversionRate()
assert.equal(typeof result, 'number') assert.equal(typeof result, 'number')
}).catch(function(err) { }).catch(function (done, err) {
done(err) done(err)
}) })
}) })
}) })
}) })
}) })

View File

@ -1,14 +1,13 @@
var assert = require('assert') var assert = require('assert')
var linkGen = require('../../ui/lib/explorer-link') var linkGen = require('../../ui/lib/explorer-link')
describe('explorer-link', function() { describe('explorer-link', function () {
it('adds ropsten prefix to ropsten test network', function () {
it('adds ropsten prefix to ropsten test network', function() {
var result = linkGen('hash', '3') var result = linkGen('hash', '3')
assert.notEqual(result.indexOf('ropsten'), -1, 'ropsten injected') assert.notEqual(result.indexOf('ropsten'), -1, 'ropsten injected')
}) })
it('adds kovan prefix to kovan test network', function() { it('adds kovan prefix to kovan test network', function () {
var result = linkGen('hash', '42') var result = linkGen('hash', '42')
assert.notEqual(result.indexOf('kovan'), -1, 'kovan injected') assert.notEqual(result.indexOf('kovan'), -1, 'kovan injected')
}) })

View File

@ -3,21 +3,20 @@ const KeyringController = require('../../app/scripts/keyring-controller')
const configManagerGen = require('../lib/mock-config-manager') const configManagerGen = require('../lib/mock-config-manager')
const ethUtil = require('ethereumjs-util') const ethUtil = require('ethereumjs-util')
const BN = ethUtil.BN const BN = ethUtil.BN
const async = require('async') // const async = require('async')
const mockEncryptor = require('../lib/mock-encryptor') const mockEncryptor = require('../lib/mock-encryptor')
const MockSimpleKeychain = require('../lib/mock-simple-keychain') // const MockSimpleKeychain = require('../lib/mock-simple-keychain')
const sinon = require('sinon') const sinon = require('sinon')
describe('KeyringController', function() { describe('KeyringController', function () {
let keyringController
const password = 'password123'
const seedWords = 'puzzle seed penalty soldier say clay field arctic metal hen cage runway'
const addresses = ['eF35cA8EbB9669A35c31b5F6f249A9941a812AC1'.toLowerCase()]
const accounts = []
// let originalKeystore
let keyringController, state beforeEach(function (done) {
let password = 'password123'
let seedWords = 'puzzle seed penalty soldier say clay field arctic metal hen cage runway'
let addresses = ['eF35cA8EbB9669A35c31b5F6f249A9941a812AC1'.toLowerCase()]
let accounts = []
let originalKeystore
beforeEach(function(done) {
this.sinon = sinon.sandbox.create() this.sinon = sinon.sandbox.create()
window.localStorage = {} // Hacking localStorage support into JSDom window.localStorage = {} // Hacking localStorage support into JSDom
@ -25,10 +24,10 @@ describe('KeyringController', function() {
configManager: configManagerGen(), configManager: configManagerGen(),
txManager: { txManager: {
getTxList: () => [], getTxList: () => [],
getUnapprovedTxList: () => [] getUnapprovedTxList: () => [],
}, },
ethStore: { ethStore: {
addAccount(acct) { accounts.push(ethUtil.addHexPrefix(acct)) }, addAccount (acct) { accounts.push(ethUtil.addHexPrefix(acct)) },
}, },
}) })
@ -38,7 +37,7 @@ describe('KeyringController', function() {
keyringController.createNewVaultAndKeychain(password) keyringController.createNewVaultAndKeychain(password)
.then(function (newState) { .then(function (newState) {
state = newState newState
done() done()
}) })
.catch((err) => { .catch((err) => {
@ -46,7 +45,7 @@ describe('KeyringController', function() {
}) })
}) })
afterEach(function() { afterEach(function () {
// Cleanup mocks // Cleanup mocks
this.sinon.restore() this.sinon.restore()
}) })
@ -54,7 +53,7 @@ describe('KeyringController', function() {
describe('#createNewVaultAndKeychain', function () { describe('#createNewVaultAndKeychain', function () {
this.timeout(10000) this.timeout(10000)
it('should set a vault on the configManager', function(done) { it('should set a vault on the configManager', function (done) {
keyringController.store.updateState({ vault: null }) keyringController.store.updateState({ vault: null })
assert(!keyringController.store.getState().vault, 'no previous vault') assert(!keyringController.store.getState().vault, 'no previous vault')
keyringController.createNewVaultAndKeychain(password) keyringController.createNewVaultAndKeychain(password)
@ -69,15 +68,14 @@ describe('KeyringController', function() {
}) })
}) })
describe('#restoreKeyring', function() { describe('#restoreKeyring', function () {
it(`should pass a keyring's serialized data back to the correct type.`, function (done) {
it(`should pass a keyring's serialized data back to the correct type.`, function(done) {
const mockSerialized = { const mockSerialized = {
type: 'HD Key Tree', type: 'HD Key Tree',
data: { data: {
mnemonic: seedWords, mnemonic: seedWords,
numberOfAccounts: 1, numberOfAccounts: 1,
} },
} }
const mock = this.sinon.mock(keyringController) const mock = this.sinon.mock(keyringController)
@ -100,8 +98,8 @@ describe('KeyringController', function() {
}) })
}) })
describe('#createNickname', function() { describe('#createNickname', function () {
it('should add the address to the identities hash', function() { it('should add the address to the identities hash', function () {
const fakeAddress = '0x12345678' const fakeAddress = '0x12345678'
keyringController.createNickname(fakeAddress) keyringController.createNickname(fakeAddress)
const identities = keyringController.memStore.getState().identities const identities = keyringController.memStore.getState().identities
@ -110,8 +108,8 @@ describe('KeyringController', function() {
}) })
}) })
describe('#saveAccountLabel', function() { describe('#saveAccountLabel', function () {
it ('sets the nickname', function(done) { it('sets the nickname', function (done) {
const account = addresses[0] const account = addresses[0]
var nick = 'Test nickname' var nick = 'Test nickname'
const identities = keyringController.memStore.getState().identities const identities = keyringController.memStore.getState().identities
@ -134,31 +132,30 @@ describe('KeyringController', function() {
}) })
}) })
describe('#getAccounts', function() { describe('#getAccounts', function () {
it('returns the result of getAccounts for each keyring', function(done) { it('returns the result of getAccounts for each keyring', function (done) {
keyringController.keyrings = [ keyringController.keyrings = [
{ getAccounts() { return Promise.resolve([1,2,3]) } }, { getAccounts () { return Promise.resolve([1, 2, 3]) } },
{ getAccounts() { return Promise.resolve([4,5,6]) } }, { getAccounts () { return Promise.resolve([4, 5, 6]) } },
] ]
keyringController.getAccounts() keyringController.getAccounts()
.then((result) => { .then((result) => {
assert.deepEqual(result, [1,2,3,4,5,6]) assert.deepEqual(result, [1, 2, 3, 4, 5, 6])
done() done()
}) })
}) })
}) })
describe('#addGasBuffer', function() { describe('#addGasBuffer', function () {
it('adds 100k gas buffer to estimates', function() { it('adds 100k gas buffer to estimates', function () {
const gas = '0x04ee59' // Actual estimated gas example const gas = '0x04ee59' // Actual estimated gas example
const tooBigOutput = '0x80674f9' // Actual bad output const tooBigOutput = '0x80674f9' // Actual bad output
const bnGas = new BN(ethUtil.stripHexPrefix(gas), 16) const bnGas = new BN(ethUtil.stripHexPrefix(gas), 16)
const correctBuffer = new BN('100000', 10) const correctBuffer = new BN('100000', 10)
const correct = bnGas.add(correctBuffer) const correct = bnGas.add(correctBuffer)
const tooBig = new BN(tooBigOutput, 16) // const tooBig = new BN(tooBigOutput, 16)
const result = keyringController.addGasBuffer(gas) const result = keyringController.addGasBuffer(gas)
const bnResult = new BN(ethUtil.stripHexPrefix(result), 16) const bnResult = new BN(ethUtil.stripHexPrefix(result), 16)

View File

@ -1,9 +1,9 @@
// LINTING: // LINTING:
const lint = require('mocha-eslint'); const lint = require('mocha-eslint')
const lintPaths = ['app/**/*.js', 'ui/**/*.js', '!node_modules/**', '!dist/**', '!docs/**', '!app/scripts/chromereload.js'] const lintPaths = ['app/**/*.js', 'ui/**/*.js', 'test/**/*.js', '!node_modules/**', '!dist/**', '!docs/**', '!app/scripts/chromereload.js']
const lintOptions = { const lintOptions = {
strict: false, strict: false,
} }
lint(lintPaths, lintOptions) lint(lintPaths, lintOptions)

View File

@ -1,29 +1,29 @@
const assert = require('assert') const assert = require('assert')
const extend = require('xtend') // const extend = require('xtend')
const EventEmitter = require('events') // const EventEmitter = require('events')
const MessageManger = require('../../app/scripts/lib/message-manager') const MessageManger = require('../../app/scripts/lib/message-manager')
describe('Transaction Manager', function() { describe('Transaction Manager', function () {
let messageManager let messageManager
beforeEach(function() { beforeEach(function () {
messageManager = new MessageManger () messageManager = new MessageManger()
}) })
describe('#getMsgList', function() { describe('#getMsgList', function () {
it('when new should return empty array', function() { it('when new should return empty array', function () {
var result = messageManager.messages var result = messageManager.messages
assert.ok(Array.isArray(result)) assert.ok(Array.isArray(result))
assert.equal(result.length, 0) assert.equal(result.length, 0)
}) })
it('should also return transactions from local storage if any', function() { it('should also return transactions from local storage if any', function () {
}) })
}) })
describe('#addMsg', function() { describe('#addMsg', function () {
it('adds a Msg returned in getMsgList', function() { it('adds a Msg returned in getMsgList', function () {
var Msg = { id: 1, status: 'approved', metamaskNetworkId: 'unit test' } var Msg = { id: 1, status: 'approved', metamaskNetworkId: 'unit test' }
messageManager.addMsg(Msg) messageManager.addMsg(Msg)
var result = messageManager.messages var result = messageManager.messages
@ -33,8 +33,8 @@ describe('Transaction Manager', function() {
}) })
}) })
describe('#setMsgStatusApproved', function() { describe('#setMsgStatusApproved', function () {
it('sets the Msg status to approved', function() { it('sets the Msg status to approved', function () {
var Msg = { id: 1, status: 'unapproved', metamaskNetworkId: 'unit test' } var Msg = { id: 1, status: 'unapproved', metamaskNetworkId: 'unit test' }
messageManager.addMsg(Msg) messageManager.addMsg(Msg)
messageManager.setMsgStatusApproved(1) messageManager.setMsgStatusApproved(1)
@ -45,8 +45,8 @@ describe('Transaction Manager', function() {
}) })
}) })
describe('#rejectMsg', function() { describe('#rejectMsg', function () {
it('sets the Msg status to rejected', function() { it('sets the Msg status to rejected', function () {
var Msg = { id: 1, status: 'unapproved', metamaskNetworkId: 'unit test' } var Msg = { id: 1, status: 'unapproved', metamaskNetworkId: 'unit test' }
messageManager.addMsg(Msg) messageManager.addMsg(Msg)
messageManager.rejectMsg(1) messageManager.rejectMsg(1)
@ -57,8 +57,8 @@ describe('Transaction Manager', function() {
}) })
}) })
describe('#_updateMsg', function() { describe('#_updateMsg', function () {
it('replaces the Msg with the same id', function() { it('replaces the Msg with the same id', function () {
messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' })
messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' })
messageManager._updateMsg({ id: '1', status: 'blah', hash: 'foo', metamaskNetworkId: 'unit test' }) messageManager._updateMsg({ id: '1', status: 'blah', hash: 'foo', metamaskNetworkId: 'unit test' })
@ -67,19 +67,19 @@ describe('Transaction Manager', function() {
}) })
}) })
describe('#getUnapprovedMsgs', function() { describe('#getUnapprovedMsgs', function () {
it('returns unapproved Msgs in a hash', function() { it('returns unapproved Msgs in a hash', function () {
messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' })
messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' })
let result = messageManager.getUnapprovedMsgs() const result = messageManager.getUnapprovedMsgs()
assert.equal(typeof result, 'object') assert.equal(typeof result, 'object')
assert.equal(result['1'].status, 'unapproved') assert.equal(result['1'].status, 'unapproved')
assert.equal(result['2'], undefined) assert.equal(result['2'], undefined)
}) })
}) })
describe('#getMsg', function() { describe('#getMsg', function () {
it('returns a Msg with the requested id', function() { it('returns a Msg with the requested id', function () {
messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' })
messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' })
assert.equal(messageManager.getMsg('1').status, 'unapproved') assert.equal(messageManager.getMsg('1').status, 'unapproved')

View File

@ -4,11 +4,11 @@ const clone = require('clone')
const MetaMaskController = require('../../app/scripts/metamask-controller') const MetaMaskController = require('../../app/scripts/metamask-controller')
const firstTimeState = require('../../app/scripts/first-time-state') const firstTimeState = require('../../app/scripts/first-time-state')
const STORAGE_KEY = 'metamask-config' // const STORAGE_KEY = 'metamask-config'
describe('MetaMaskController', function() { describe('MetaMaskController', function () {
const noop = () => {} const noop = () => {}
let controller = new MetaMaskController({ const metamaskController = new MetaMaskController({
showUnconfirmedMessage: noop, showUnconfirmedMessage: noop,
unlockAccountMessage: noop, unlockAccountMessage: noop,
showUnapprovedTx: noop, showUnapprovedTx: noop,
@ -16,14 +16,18 @@ describe('MetaMaskController', function() {
initState: clone(firstTimeState), initState: clone(firstTimeState),
}) })
beforeEach(function() { beforeEach(function () {
// sinon allows stubbing methods that are easily verified // sinon allows stubbing methods that are easily verified
this.sinon = sinon.sandbox.create() this.sinon = sinon.sandbox.create()
}) })
afterEach(function() { afterEach(function () {
// sinon requires cleanup otherwise it will overwrite context // sinon requires cleanup otherwise it will overwrite context
this.sinon.restore() this.sinon.restore()
}) })
}) describe('Metamask Controller', function () {
assert(metamaskController)
})
})

View File

@ -3,7 +3,7 @@ const path = require('path')
const wallet1 = require(path.join('..', 'lib', 'migrations', '001.json')) const wallet1 = require(path.join('..', 'lib', 'migrations', '001.json'))
const vault4 = require(path.join('..', 'lib', 'migrations', '004.json')) const vault4 = require(path.join('..', 'lib', 'migrations', '004.json'))
let vault5, vault6, vault7, vault8, vault9, vault10, vault11 let vault5, vault6, vault7, vault8, vault9 // vault10, vault11
const migration2 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '002')) const migration2 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '002'))
const migration3 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '003')) const migration3 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '003'))
@ -23,7 +23,6 @@ const newTestRpc = 'https://testrpc.metamask.io/'
describe('wallet1 is migrated successfully', () => { describe('wallet1 is migrated successfully', () => {
it('should convert providers', () => { it('should convert providers', () => {
wallet1.data.config.provider = { type: 'etherscan', rpcTarget: null } wallet1.data.config.provider = { type: 'etherscan', rpcTarget: null }
return migration2.migrate(wallet1) return migration2.migrate(wallet1)
@ -99,6 +98,5 @@ describe('wallet1 is migrated successfully', () => {
assert.equal(twelfthResult.data.NoticeController.noticesList[0].body, '', 'notices that have been read should have an empty body.') assert.equal(twelfthResult.data.NoticeController.noticesList[0].body, '', 'notices that have been read should have an empty body.')
assert.equal(twelfthResult.data.NoticeController.noticesList[1].body, 'nonempty', 'notices that have not been read should not have an empty body.') assert.equal(twelfthResult.data.NoticeController.noticesList[1].body, 'nonempty', 'notices that have not been read should not have an empty body.')
}) })
}) })
}) })

View File

@ -4,25 +4,23 @@ var sinon = require('sinon')
var path = require('path') var path = require('path')
var contractNamer = require(path.join(__dirname, '..', '..', 'ui', 'lib', 'contract-namer.js')) var contractNamer = require(path.join(__dirname, '..', '..', 'ui', 'lib', 'contract-namer.js'))
describe('contractNamer', function() { describe('contractNamer', function () {
beforeEach(function () {
beforeEach(function() {
this.sinon = sinon.sandbox.create() this.sinon = sinon.sandbox.create()
}) })
afterEach(function() { afterEach(function () {
this.sinon.restore() this.sinon.restore()
}) })
describe('naming a contract', function() { describe('naming a contract', function () {
it('should return nothing for an unknown random account', function () {
it('should return nothing for an unknown random account', function() {
const input = '0x2386F26FC10000' const input = '0x2386F26FC10000'
const output = contractNamer(input) const output = contractNamer(input)
assert.deepEqual(output, null) assert.deepEqual(output, null)
}) })
it('should accept identities as an optional second parameter', function() { it('should accept identities as an optional second parameter', function () {
const input = '0x2386F26FC10000'.toLowerCase() const input = '0x2386F26FC10000'.toLowerCase()
const expected = 'bar' const expected = 'bar'
const identities = {} const identities = {}
@ -31,7 +29,7 @@ describe('contractNamer', function() {
assert.deepEqual(output, expected) assert.deepEqual(output, expected)
}) })
it('should check for identities case insensitively', function() { it('should check for identities case insensitively', function () {
const input = '0x2386F26FC10000'.toLowerCase() const input = '0x2386F26FC10000'.toLowerCase()
const expected = 'bar' const expected = 'bar'
const identities = {} const identities = {}
@ -39,6 +37,5 @@ describe('contractNamer', function() {
const output = contractNamer(input.toUpperCase(), identities) const output = contractNamer(input.toUpperCase(), identities)
assert.deepEqual(output, expected) assert.deepEqual(output, expected)
}) })
}) })
}) })

View File

@ -1,22 +1,20 @@
const assert = require('assert') const assert = require('assert')
const nodeify = require('../../app/scripts/lib/nodeify') const nodeify = require('../../app/scripts/lib/nodeify')
describe('nodeify', function() { describe('nodeify', function () {
var obj = { var obj = {
foo: 'bar', foo: 'bar',
promiseFunc: function (a) { promiseFunc: function (a) {
var solution = this.foo + a var solution = this.foo + a
return Promise.resolve(solution) return Promise.resolve(solution)
} },
} }
it('should retain original context', function(done) { it('should retain original context', function (done) {
var nodified = nodeify(obj.promiseFunc).bind(obj) var nodified = nodeify(obj.promiseFunc).bind(obj)
nodified('baz', function (err, res) { nodified('baz', function (err, res) {
assert.equal(res, 'barbaz') assert.equal(res, 'barbaz')
done() done()
}) })
}) })
}) })

View File

@ -1,42 +1,42 @@
const assert = require('assert') const assert = require('assert')
const extend = require('xtend') // const extend = require('xtend')
const rp = require('request-promise') // const rp = require('request-promise')
const nock = require('nock') // const nock = require('nock')
const configManagerGen = require('../lib/mock-config-manager') const configManagerGen = require('../lib/mock-config-manager')
const NoticeController = require('../../app/scripts/notice-controller') const NoticeController = require('../../app/scripts/notice-controller')
const STORAGE_KEY = 'metamask-persistence-key' // const STORAGE_KEY = 'metamask-persistence-key'
describe('notice-controller', function() { describe('notice-controller', function () {
var noticeController var noticeController
beforeEach(function() { beforeEach(function () {
// simple localStorage polyfill // simple localStorage polyfill
let configManager = configManagerGen() const configManager = configManagerGen()
noticeController = new NoticeController({ noticeController = new NoticeController({
configManager: configManager, configManager: configManager,
}) })
}) })
describe('notices', function() { describe('notices', function () {
describe('#getNoticesList', function() { describe('#getNoticesList', function () {
it('should return an empty array when new', function(done) { it('should return an empty array when new', function (done) {
var testList = [{ // const testList = [{
id:0, // id: 0,
read:false, // read: false,
title:"Futuristic Notice" // title: 'Futuristic Notice',
}] // }]
var result = noticeController.getNoticesList() var result = noticeController.getNoticesList()
assert.equal(result.length, 0) assert.equal(result.length, 0)
done() done()
}) })
}) })
describe('#setNoticesList', function() { describe('#setNoticesList', function () {
it('should set data appropriately', function (done) { it('should set data appropriately', function (done) {
var testList = [{ var testList = [{
id:0, id: 0,
read:false, read: false,
title:"Futuristic Notice" title: 'Futuristic Notice',
}] }]
noticeController.setNoticesList(testList) noticeController.setNoticesList(testList)
var testListId = noticeController.getNoticesList()[0].id var testListId = noticeController.getNoticesList()[0].id
@ -45,12 +45,12 @@ describe('notice-controller', function() {
}) })
}) })
describe('#updateNoticeslist', function() { describe('#updateNoticeslist', function () {
it('should integrate the latest changes from the source', function(done) { it('should integrate the latest changes from the source', function (done) {
var testList = [{ var testList = [{
id:55, id: 55,
read:false, read: false,
title:"Futuristic Notice" title: 'Futuristic Notice',
}] }]
noticeController.setNoticesList(testList) noticeController.setNoticesList(testList)
noticeController.updateNoticesList().then(() => { noticeController.updateNoticesList().then(() => {
@ -62,14 +62,14 @@ describe('notice-controller', function() {
}) })
it('should not overwrite any existing fields', function (done) { it('should not overwrite any existing fields', function (done) {
var testList = [{ var testList = [{
id:0, id: 0,
read:false, read: false,
title:"Futuristic Notice" title: 'Futuristic Notice',
}] }]
noticeController.setNoticesList(testList) noticeController.setNoticesList(testList)
var newList = noticeController.getNoticesList() var newList = noticeController.getNoticesList()
assert.equal(newList[0].id, 0) assert.equal(newList[0].id, 0)
assert.equal(newList[0].title, "Futuristic Notice") assert.equal(newList[0].title, 'Futuristic Notice')
assert.equal(newList.length, 1) assert.equal(newList.length, 1)
done() done()
}) })
@ -78,9 +78,9 @@ describe('notice-controller', function() {
describe('#markNoticeRead', function () { describe('#markNoticeRead', function () {
it('should mark a notice as read', function (done) { it('should mark a notice as read', function (done) {
var testList = [{ var testList = [{
id:0, id: 0,
read:false, read: false,
title:"Futuristic Notice" title: 'Futuristic Notice',
}] }]
noticeController.setNoticesList(testList) noticeController.setNoticesList(testList)
noticeController.markNoticeRead(testList[0]) noticeController.markNoticeRead(testList[0])
@ -93,9 +93,9 @@ describe('notice-controller', function() {
describe('#getLatestUnreadNotice', function () { describe('#getLatestUnreadNotice', function () {
it('should retrieve the latest unread notice', function (done) { it('should retrieve the latest unread notice', function (done) {
var testList = [ var testList = [
{id:0,read:true,title:"Past Notice"}, {id: 0, read: true, title: 'Past Notice'},
{id:1,read:false,title:"Current Notice"}, {id: 1, read: false, title: 'Current Notice'},
{id:2,read:false,title:"Future Notice"}, {id: 2, read: false, title: 'Future Notice'},
] ]
noticeController.setNoticesList(testList) noticeController.setNoticesList(testList)
var latestUnread = noticeController.getLatestUnreadNotice() var latestUnread = noticeController.getLatestUnreadNotice()
@ -104,9 +104,9 @@ describe('notice-controller', function() {
}) })
it('should return undefined if no unread notices exist.', function (done) { it('should return undefined if no unread notices exist.', function (done) {
var testList = [ var testList = [
{id:0,read:true,title:"Past Notice"}, {id: 0, read: true, title: 'Past Notice'},
{id:1,read:true,title:"Current Notice"}, {id: 1, read: true, title: 'Current Notice'},
{id:2,read:true,title:"Future Notice"}, {id: 2, read: true, title: 'Future Notice'},
] ]
noticeController.setNoticesList(testList) noticeController.setNoticesList(testList)
var latestUnread = noticeController.getLatestUnreadNotice() var latestUnread = noticeController.getLatestUnreadNotice()
@ -115,5 +115,4 @@ describe('notice-controller', function() {
}) })
}) })
}) })
}) })

View File

@ -1,29 +1,29 @@
const assert = require('assert') const assert = require('assert')
const extend = require('xtend') // const extend = require('xtend')
const EventEmitter = require('events') // const EventEmitter = require('events')
const PersonalMessageManager = require('../../app/scripts/lib/personal-message-manager') const PersonalMessageManager = require('../../app/scripts/lib/personal-message-manager')
describe('Personal Message Manager', function() { describe('Personal Message Manager', function () {
let messageManager let messageManager
beforeEach(function() { beforeEach(function () {
messageManager = new PersonalMessageManager() messageManager = new PersonalMessageManager()
}) })
describe('#getMsgList', function() { describe('#getMsgList', function () {
it('when new should return empty array', function() { it('when new should return empty array', function () {
var result = messageManager.messages var result = messageManager.messages
assert.ok(Array.isArray(result)) assert.ok(Array.isArray(result))
assert.equal(result.length, 0) assert.equal(result.length, 0)
}) })
it('should also return transactions from local storage if any', function() { it('should also return transactions from local storage if any', function () {
}) })
}) })
describe('#addMsg', function() { describe('#addMsg', function () {
it('adds a Msg returned in getMsgList', function() { it('adds a Msg returned in getMsgList', function () {
var Msg = { id: 1, status: 'approved', metamaskNetworkId: 'unit test' } var Msg = { id: 1, status: 'approved', metamaskNetworkId: 'unit test' }
messageManager.addMsg(Msg) messageManager.addMsg(Msg)
var result = messageManager.messages var result = messageManager.messages
@ -33,8 +33,8 @@ describe('Personal Message Manager', function() {
}) })
}) })
describe('#setMsgStatusApproved', function() { describe('#setMsgStatusApproved', function () {
it('sets the Msg status to approved', function() { it('sets the Msg status to approved', function () {
var Msg = { id: 1, status: 'unapproved', metamaskNetworkId: 'unit test' } var Msg = { id: 1, status: 'unapproved', metamaskNetworkId: 'unit test' }
messageManager.addMsg(Msg) messageManager.addMsg(Msg)
messageManager.setMsgStatusApproved(1) messageManager.setMsgStatusApproved(1)
@ -45,8 +45,8 @@ describe('Personal Message Manager', function() {
}) })
}) })
describe('#rejectMsg', function() { describe('#rejectMsg', function () {
it('sets the Msg status to rejected', function() { it('sets the Msg status to rejected', function () {
var Msg = { id: 1, status: 'unapproved', metamaskNetworkId: 'unit test' } var Msg = { id: 1, status: 'unapproved', metamaskNetworkId: 'unit test' }
messageManager.addMsg(Msg) messageManager.addMsg(Msg)
messageManager.rejectMsg(1) messageManager.rejectMsg(1)
@ -57,8 +57,8 @@ describe('Personal Message Manager', function() {
}) })
}) })
describe('#_updateMsg', function() { describe('#_updateMsg', function () {
it('replaces the Msg with the same id', function() { it('replaces the Msg with the same id', function () {
messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' })
messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' })
messageManager._updateMsg({ id: '1', status: 'blah', hash: 'foo', metamaskNetworkId: 'unit test' }) messageManager._updateMsg({ id: '1', status: 'blah', hash: 'foo', metamaskNetworkId: 'unit test' })
@ -67,19 +67,19 @@ describe('Personal Message Manager', function() {
}) })
}) })
describe('#getUnapprovedMsgs', function() { describe('#getUnapprovedMsgs', function () {
it('returns unapproved Msgs in a hash', function() { it('returns unapproved Msgs in a hash', function () {
messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' })
messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' })
let result = messageManager.getUnapprovedMsgs() const result = messageManager.getUnapprovedMsgs()
assert.equal(typeof result, 'object') assert.equal(typeof result, 'object')
assert.equal(result['1'].status, 'unapproved') assert.equal(result['1'].status, 'unapproved')
assert.equal(result['2'], undefined) assert.equal(result['2'], undefined)
}) })
}) })
describe('#getMsg', function() { describe('#getMsg', function () {
it('returns a Msg with the requested id', function() { it('returns a Msg with the requested id', function () {
messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '1', status: 'unapproved', metamaskNetworkId: 'unit test' })
messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' }) messageManager.addMsg({ id: '2', status: 'approved', metamaskNetworkId: 'unit test' })
assert.equal(messageManager.getMsg('1').status, 'unapproved') assert.equal(messageManager.getMsg('1').status, 'unapproved')
@ -87,24 +87,23 @@ describe('Personal Message Manager', function() {
}) })
}) })
describe('#normalizeMsgData', function() { describe('#normalizeMsgData', function () {
it('converts text to a utf8 hex string', function() { it('converts text to a utf8 hex string', function () {
var input = 'hello' var input = 'hello'
var output = messageManager.normalizeMsgData(input) var output = messageManager.normalizeMsgData(input)
assert.equal(output, '0x68656c6c6f', 'predictably hex encoded') assert.equal(output, '0x68656c6c6f', 'predictably hex encoded')
}) })
it('tolerates a hex prefix', function() { it('tolerates a hex prefix', function () {
var input = '0x12' var input = '0x12'
var output = messageManager.normalizeMsgData(input) var output = messageManager.normalizeMsgData(input)
assert.equal(output, '0x12', 'un modified') assert.equal(output, '0x12', 'un modified')
}) })
it('tolerates normal hex', function() { it('tolerates normal hex', function () {
var input = '12' var input = '12'
var output = messageManager.normalizeMsgData(input) var output = messageManager.normalizeMsgData(input)
assert.equal(output, '0x12', 'adds prefix') assert.equal(output, '0x12', 'adds prefix')
}) })
}) })
}) })

View File

@ -1,32 +1,31 @@
var jsdom = require('mocha-jsdom') // var jsdom = require('mocha-jsdom')
var assert = require('assert') var assert = require('assert')
var freeze = require('deep-freeze-strict') // var freeze = require('deep-freeze-strict')
var path = require('path') var path = require('path')
var sinon = require('sinon') var sinon = require('sinon')
var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js'))
var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js'))
describe('#unlockMetamask(selectedAccount)', function() { describe('#unlockMetamask(selectedAccount)', function () {
beforeEach(function () {
beforeEach(function() {
// sinon allows stubbing methods that are easily verified // sinon allows stubbing methods that are easily verified
this.sinon = sinon.sandbox.create() this.sinon = sinon.sandbox.create()
}) })
afterEach(function() { afterEach(function () {
// sinon requires cleanup otherwise it will overwrite context // sinon requires cleanup otherwise it will overwrite context
this.sinon.restore() this.sinon.restore()
}) })
describe('after an error', function() { describe('after an error', function () {
it('clears warning', function() { it('clears warning', function () {
const warning = 'this is the wrong warning' const warning = 'this is the wrong warning'
const account = 'foo_account' const account = 'foo_account'
const initialState = { const initialState = {
appState: { appState: {
warning: warning, warning: warning,
} },
} }
const resultState = reducers(initialState, actions.unlockMetamask(account)) const resultState = reducers(initialState, actions.unlockMetamask(account))
@ -34,14 +33,14 @@ describe('#unlockMetamask(selectedAccount)', function() {
}) })
}) })
describe('going home after an error', function() { describe('going home after an error', function () {
it('clears warning', function() { it('clears warning', function () {
const warning = 'this is the wrong warning' const warning = 'this is the wrong warning'
const account = 'foo_account' // const account = 'foo_account'
const initialState = { const initialState = {
appState: { appState: {
warning: warning, warning: warning,
} },
} }
const resultState = reducers(initialState, actions.goHome()) const resultState = reducers(initialState, actions.goHome())

View File

@ -1,20 +1,20 @@
const assert = require('assert') const assert = require('assert')
const extend = require('xtend') // const extend = require('xtend')
const EventEmitter = require('events') const EventEmitter = require('events')
const ethUtil = require('ethereumjs-util') const ethUtil = require('ethereumjs-util')
const EthTx = require('ethereumjs-tx') const EthTx = require('ethereumjs-tx')
const ObservableStore = require('obs-store') const ObservableStore = require('obs-store')
const STORAGE_KEY = 'metamask-persistance-key' // const STORAGE_KEY = 'metamask-persistance-key'
const TransactionManager = require('../../app/scripts/transaction-manager') const TransactionManager = require('../../app/scripts/transaction-manager')
const noop = () => true const noop = () => true
const currentNetworkId = 42 const currentNetworkId = 42
const otherNetworkId = 36 const otherNetworkId = 36
const privKey = new Buffer('8718b9618a37d1fc78c436511fc6df3c8258d3250635bba617f33003270ec03e', 'hex') const privKey = new Buffer('8718b9618a37d1fc78c436511fc6df3c8258d3250635bba617f33003270ec03e', 'hex')
describe('Transaction Manager', function() { describe('Transaction Manager', function () {
let txManager let txManager
beforeEach(function() { beforeEach(function () {
txManager = new TransactionManager({ txManager = new TransactionManager({
networkStore: new ObservableStore({ network: currentNetworkId }), networkStore: new ObservableStore({ network: currentNetworkId }),
txHistoryLimit: 10, txHistoryLimit: 10,
@ -22,43 +22,43 @@ describe('Transaction Manager', function() {
signTransaction: (ethTx) => new Promise((resolve) => { signTransaction: (ethTx) => new Promise((resolve) => {
ethTx.sign(privKey) ethTx.sign(privKey)
resolve() resolve()
}) }),
}) })
}) })
describe('#validateTxParams', function () { describe('#validateTxParams', function () {
it('returns null for positive values', function() { it('returns null for positive values', function () {
var sample = { var sample = {
value: '0x01' value: '0x01',
} }
var res = txManager.txProviderUtils.validateTxParams(sample, (err) => { txManager.txProviderUtils.validateTxParams(sample, (err) => {
assert.equal(err, null, 'no error') assert.equal(err, null, 'no error')
}) })
}) })
it('returns error for negative values', function() { it('returns error for negative values', function () {
var sample = { var sample = {
value: '-0x01' value: '-0x01',
} }
var res = txManager.txProviderUtils.validateTxParams(sample, (err) => { txManager.txProviderUtils.validateTxParams(sample, (err) => {
assert.ok(err, 'error') assert.ok(err, 'error')
}) })
}) })
}) })
describe('#getTxList', function() { describe('#getTxList', function () {
it('when new should return empty array', function() { it('when new should return empty array', function () {
var result = txManager.getTxList() var result = txManager.getTxList()
assert.ok(Array.isArray(result)) assert.ok(Array.isArray(result))
assert.equal(result.length, 0) assert.equal(result.length, 0)
}) })
it('should also return transactions from local storage if any', function() { it('should also return transactions from local storage if any', function () {
}) })
}) })
describe('#addTx', function() { describe('#addTx', function () {
it('adds a tx returned in getTxList', function() { it('adds a tx returned in getTxList', function () {
var tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } var tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
txManager.addTx(tx, noop) txManager.addTx(tx, noop)
var result = txManager.getTxList() var result = txManager.getTxList()
@ -67,7 +67,7 @@ describe('Transaction Manager', function() {
assert.equal(result[0].id, 1) assert.equal(result[0].id, 1)
}) })
it('does not override txs from other networks', function() { it('does not override txs from other networks', function () {
var tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } var tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
var tx2 = { id: 2, status: 'confirmed', metamaskNetworkId: otherNetworkId, txParams: {} } var tx2 = { id: 2, status: 'confirmed', metamaskNetworkId: otherNetworkId, txParams: {} }
txManager.addTx(tx, noop) txManager.addTx(tx, noop)
@ -78,10 +78,10 @@ describe('Transaction Manager', function() {
assert.equal(result2.length, 1, 'incorrect number of txs on network.') assert.equal(result2.length, 1, 'incorrect number of txs on network.')
}) })
it('cuts off early txs beyond a limit', function() { it('cuts off early txs beyond a limit', function () {
const limit = txManager.txHistoryLimit const limit = txManager.txHistoryLimit
for (let i = 0; i < limit + 1; i++) { for (let i = 0; i < limit + 1; i++) {
let tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } const tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
txManager.addTx(tx, noop) txManager.addTx(tx, noop)
} }
var result = txManager.getTxList() var result = txManager.getTxList()
@ -89,10 +89,10 @@ describe('Transaction Manager', function() {
assert.equal(result[0].id, 1, 'early txs truncted') assert.equal(result[0].id, 1, 'early txs truncted')
}) })
it('cuts off early txs beyond a limit whether or not it is confirmed or rejected', function() { it('cuts off early txs beyond a limit whether or not it is confirmed or rejected', function () {
const limit = txManager.txHistoryLimit const limit = txManager.txHistoryLimit
for (let i = 0; i < limit + 1; i++) { for (let i = 0; i < limit + 1; i++) {
let tx = { id: i, time: new Date(), status: 'rejected', metamaskNetworkId: currentNetworkId, txParams: {} } const tx = { id: i, time: new Date(), status: 'rejected', metamaskNetworkId: currentNetworkId, txParams: {} }
txManager.addTx(tx, noop) txManager.addTx(tx, noop)
} }
var result = txManager.getTxList() var result = txManager.getTxList()
@ -100,12 +100,12 @@ describe('Transaction Manager', function() {
assert.equal(result[0].id, 1, 'early txs truncted') assert.equal(result[0].id, 1, 'early txs truncted')
}) })
it('cuts off early txs beyond a limit but does not cut unapproved txs', function() { it('cuts off early txs beyond a limit but does not cut unapproved txs', function () {
var unconfirmedTx = { id: 0, time: new Date(), status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } var unconfirmedTx = { id: 0, time: new Date(), status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txManager.addTx(unconfirmedTx, noop) txManager.addTx(unconfirmedTx, noop)
const limit = txManager.txHistoryLimit const limit = txManager.txHistoryLimit
for (let i = 1; i < limit + 1; i++) { for (let i = 1; i < limit + 1; i++) {
let tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } const tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
txManager.addTx(tx, noop) txManager.addTx(tx, noop)
} }
var result = txManager.getTxList() var result = txManager.getTxList()
@ -116,8 +116,8 @@ describe('Transaction Manager', function() {
}) })
}) })
describe('#setTxStatusSigned', function() { describe('#setTxStatusSigned', function () {
it('sets the tx status to signed', function() { it('sets the tx status to signed', function () {
var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txManager.addTx(tx, noop) txManager.addTx(tx, noop)
txManager.setTxStatusSigned(1) txManager.setTxStatusSigned(1)
@ -130,7 +130,7 @@ describe('Transaction Manager', function() {
it('should emit a signed event to signal the exciton of callback', (done) => { it('should emit a signed event to signal the exciton of callback', (done) => {
this.timeout(10000) this.timeout(10000)
var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
let noop = function () { const noop = function () {
assert(true, 'event listener has been triggered and noop executed') assert(true, 'event listener has been triggered and noop executed')
done() done()
} }
@ -140,8 +140,8 @@ describe('Transaction Manager', function() {
}) })
}) })
describe('#setTxStatusRejected', function() { describe('#setTxStatusRejected', function () {
it('sets the tx status to rejected', function() { it('sets the tx status to rejected', function () {
var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txManager.addTx(tx) txManager.addTx(tx)
txManager.setTxStatusRejected(1) txManager.setTxStatusRejected(1)
@ -155,18 +155,17 @@ describe('Transaction Manager', function() {
this.timeout(10000) this.timeout(10000)
var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txManager.addTx(tx) txManager.addTx(tx)
let noop = function (err, txId) { const noop = function (err, txId) {
assert(true, 'event listener has been triggered and noop executed') assert(true, 'event listener has been triggered and noop executed')
done() done()
} }
txManager.on('1:rejected', noop) txManager.on('1:rejected', noop)
txManager.setTxStatusRejected(1) txManager.setTxStatusRejected(1)
}) })
}) })
describe('#updateTx', function() { describe('#updateTx', function () {
it('replaces the tx with the same id', function() { it('replaces the tx with the same id', function () {
txManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) txManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop)
txManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) txManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop)
txManager.updateTx({ id: '1', status: 'blah', hash: 'foo', metamaskNetworkId: currentNetworkId, txParams: {} }) txManager.updateTx({ id: '1', status: 'blah', hash: 'foo', metamaskNetworkId: currentNetworkId, txParams: {} })
@ -175,19 +174,19 @@ describe('Transaction Manager', function() {
}) })
}) })
describe('#getUnapprovedTxList', function() { describe('#getUnapprovedTxList', function () {
it('returns unapproved txs in a hash', function() { it('returns unapproved txs in a hash', function () {
txManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) txManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop)
txManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) txManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop)
let result = txManager.getUnapprovedTxList() const result = txManager.getUnapprovedTxList()
assert.equal(typeof result, 'object') assert.equal(typeof result, 'object')
assert.equal(result['1'].status, 'unapproved') assert.equal(result['1'].status, 'unapproved')
assert.equal(result['2'], undefined) assert.equal(result['2'], undefined)
}) })
}) })
describe('#getTx', function() { describe('#getTx', function () {
it('returns a tx with the requested id', function() { it('returns a tx with the requested id', function () {
txManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) txManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop)
txManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) txManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop)
assert.equal(txManager.getTx('1').status, 'unapproved') assert.equal(txManager.getTx('1').status, 'unapproved')
@ -195,19 +194,19 @@ describe('Transaction Manager', function() {
}) })
}) })
describe('#getFilteredTxList', function() { describe('#getFilteredTxList', function () {
it('returns a tx with the requested data', function() { it('returns a tx with the requested data', function () {
let txMetas = [ const txMetas = [
{ id: 0, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, { id: 0, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId },
{ id: 1, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, { id: 1, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId },
{ id: 2, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, { id: 2, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId },
{ id: 3, status: 'unapproved', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, { id: 3, status: 'unapproved', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId },
{ id: 4, status: 'unapproved', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, { id: 4, status: 'unapproved', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId },
{ id: 5, status: 'confirmed', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, { id: 5, status: 'confirmed', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId },
{ id: 6, status: 'confirmed', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, { id: 6, status: 'confirmed', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId },
{ id: 7, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, { id: 7, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId },
{ id: 8, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, { id: 8, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId },
{ id: 9, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, { id: 9, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId },
] ]
txMetas.forEach((txMeta) => txManager.addTx(txMeta, noop)) txMetas.forEach((txMeta) => txManager.addTx(txMeta, noop))
let filterParams let filterParams
@ -227,8 +226,8 @@ describe('Transaction Manager', function() {
}) })
}) })
describe('#sign replay-protected tx', function() { describe('#sign replay-protected tx', function () {
it('prepares a tx with the chainId set', function() { it('prepares a tx with the chainId set', function () {
txManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) txManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop)
txManager.signTransaction('1', (err, rawTx) => { txManager.signTransaction('1', (err, rawTx) => {
if (err) return assert.fail('it should not fail') if (err) return assert.fail('it should not fail')
@ -237,5 +236,4 @@ describe('Transaction Manager', function() {
}) })
}) })
}) })
}) })

View File

@ -5,15 +5,15 @@ const BN = ethUtil.BN
const TxUtils = require('../../app/scripts/lib/tx-utils') const TxUtils = require('../../app/scripts/lib/tx-utils')
describe('txUtils', function() { describe('txUtils', function () {
let txUtils let txUtils
before(function() { before(function () {
txUtils = new TxUtils() txUtils = new TxUtils()
}) })
describe('chain Id', function() { describe('chain Id', function () {
it('prepares a transaction with the provided chainId', function() { it('prepares a transaction with the provided chainId', function () {
const txParams = { const txParams = {
to: '0x70ad465e0bab6504002ad58c744ed89c7da38524', to: '0x70ad465e0bab6504002ad58c744ed89c7da38524',
from: '0x69ad465e0bab6504002ad58c744ed89c7da38525', from: '0x69ad465e0bab6504002ad58c744ed89c7da38525',
@ -29,8 +29,8 @@ describe('txUtils', function() {
}) })
}) })
describe('addGasBuffer', function() { describe('addGasBuffer', function () {
it('multiplies by 1.5, when within block gas limit', function() { it('multiplies by 1.5, when within block gas limit', function () {
// naive estimatedGas: 0x16e360 (1.5 mil) // naive estimatedGas: 0x16e360 (1.5 mil)
const inputHex = '0x16e360' const inputHex = '0x16e360'
// dummy gas limit: 0x3d4c52 (4 mil) // dummy gas limit: 0x3d4c52 (4 mil)
@ -41,20 +41,20 @@ describe('txUtils', function() {
const expectedBn = inputBn.muln(1.5) const expectedBn = inputBn.muln(1.5)
assert(outputBn.eq(expectedBn), 'returns 1.5 the input value') assert(outputBn.eq(expectedBn), 'returns 1.5 the input value')
}) })
it('uses original estimatedGas, when above block gas limit', function() { it('uses original estimatedGas, when above block gas limit', function () {
// naive estimatedGas: 0x16e360 (1.5 mil) // naive estimatedGas: 0x16e360 (1.5 mil)
const inputHex = '0x16e360' const inputHex = '0x16e360'
// dummy gas limit: 0x0f4240 (1 mil) // dummy gas limit: 0x0f4240 (1 mil)
const blockGasLimitHex = '0x0f4240' const blockGasLimitHex = '0x0f4240'
const output = txUtils.addGasBuffer(inputHex, blockGasLimitHex) const output = txUtils.addGasBuffer(inputHex, blockGasLimitHex)
const inputBn = hexToBn(inputHex) // const inputBn = hexToBn(inputHex)
const outputBn = hexToBn(output) const outputBn = hexToBn(output)
const expectedBn = hexToBn(inputHex) const expectedBn = hexToBn(inputHex)
assert(outputBn.eq(expectedBn), 'returns the original estimatedGas value') assert(outputBn.eq(expectedBn), 'returns the original estimatedGas value')
}) })
it('buffers up to reccomend gas limit reccomended ceiling', function() { it('buffers up to reccomend gas limit reccomended ceiling', function () {
// naive estimatedGas: 0x16e360 (1.5 mil) // naive estimatedGas: 0x16e360 (1.5 mil)
const inputHex = '0x16e360' const inputHex = '0x16e360'
// dummy gas limit: 0x1e8480 (2 mil) // dummy gas limit: 0x1e8480 (2 mil)
@ -72,10 +72,10 @@ describe('txUtils', function() {
// util // util
function hexToBn(inputHex) { function hexToBn (inputHex) {
return new BN(ethUtil.stripHexPrefix(inputHex), 16) return new BN(ethUtil.stripHexPrefix(inputHex), 16)
} }
function bnToHex(inputBn) { function bnToHex (inputBn) {
return ethUtil.addHexPrefix(inputBn.toString(16)) return ethUtil.addHexPrefix(inputBn.toString(16))
} }

View File

@ -5,96 +5,96 @@ const ethUtil = require('ethereumjs-util')
var path = require('path') var path = require('path')
var util = require(path.join(__dirname, '..', '..', 'ui', 'app', 'util.js')) var util = require(path.join(__dirname, '..', '..', 'ui', 'app', 'util.js'))
describe('util', function() { describe('util', function () {
var ethInWei = '1' var ethInWei = '1'
for (var i = 0; i < 18; i++ ) { ethInWei += '0' } for (var i = 0; i < 18; i++) { ethInWei += '0' }
beforeEach(function() { beforeEach(function () {
this.sinon = sinon.sandbox.create() this.sinon = sinon.sandbox.create()
}) })
afterEach(function() { afterEach(function () {
this.sinon.restore() this.sinon.restore()
}) })
describe('#parseBalance', function() { describe('#parseBalance', function () {
it('should render 0.01 eth correctly', function() { it('should render 0.01 eth correctly', function () {
const input = '0x2386F26FC10000' const input = '0x2386F26FC10000'
const output = util.parseBalance(input) const output = util.parseBalance(input)
assert.deepEqual(output, ['0', '01']) assert.deepEqual(output, ['0', '01'])
}) })
it('should render 12.023 eth correctly', function() { it('should render 12.023 eth correctly', function () {
const input = 'A6DA46CCA6858000' const input = 'A6DA46CCA6858000'
const output = util.parseBalance(input) const output = util.parseBalance(input)
assert.deepEqual(output, ['12', '023']) assert.deepEqual(output, ['12', '023'])
}) })
it('should render 0.0000000342422 eth correctly', function() { it('should render 0.0000000342422 eth correctly', function () {
const input = '0x7F8FE81C0' const input = '0x7F8FE81C0'
const output = util.parseBalance(input) const output = util.parseBalance(input)
assert.deepEqual(output, ['0', '0000000342422']) assert.deepEqual(output, ['0', '0000000342422'])
}) })
it('should render 0 eth correctly', function() { it('should render 0 eth correctly', function () {
const input = '0x0' const input = '0x0'
const output = util.parseBalance(input) const output = util.parseBalance(input)
assert.deepEqual(output, ['0', '0']) assert.deepEqual(output, ['0', '0'])
}) })
}) })
describe('#addressSummary', function() { describe('#addressSummary', function () {
it('should add case-sensitive checksum', function() { it('should add case-sensitive checksum', function () {
var address = '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825' var address = '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825'
var result = util.addressSummary(address) var result = util.addressSummary(address)
assert.equal(result, '0xFDEa65C8...b825') assert.equal(result, '0xFDEa65C8...b825')
}) })
it('should accept arguments for firstseg, lastseg, and keepPrefix', function() { it('should accept arguments for firstseg, lastseg, and keepPrefix', function () {
var address = '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825' var address = '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825'
var result = util.addressSummary(address, 4, 4, false) var result = util.addressSummary(address, 4, 4, false)
assert.equal(result, 'FDEa...b825') assert.equal(result, 'FDEa...b825')
}) })
}) })
describe('#isValidAddress', function() { describe('#isValidAddress', function () {
it('should allow 40-char non-prefixed hex', function() { it('should allow 40-char non-prefixed hex', function () {
var address = 'fdea65c8e26263f6d9a1b5de9555d2931a33b825' var address = 'fdea65c8e26263f6d9a1b5de9555d2931a33b825'
var result = util.isValidAddress(address) var result = util.isValidAddress(address)
assert.ok(result) assert.ok(result)
}) })
it('should allow 42-char non-prefixed hex', function() { it('should allow 42-char non-prefixed hex', function () {
var address = '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825' var address = '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825'
var result = util.isValidAddress(address) var result = util.isValidAddress(address)
assert.ok(result) assert.ok(result)
}) })
it('should not allow less non hex-prefixed', function() { it('should not allow less non hex-prefixed', function () {
var address = 'fdea65c8e26263f6d9a1b5de9555d2931a33b85' var address = 'fdea65c8e26263f6d9a1b5de9555d2931a33b85'
var result = util.isValidAddress(address) var result = util.isValidAddress(address)
assert.ok(!result) assert.ok(!result)
}) })
it('should not allow less hex-prefixed', function() { it('should not allow less hex-prefixed', function () {
var address = '0xfdea65ce26263f6d9a1b5de9555d2931a33b85' var address = '0xfdea65ce26263f6d9a1b5de9555d2931a33b85'
var result = util.isValidAddress(address) var result = util.isValidAddress(address)
assert.ok(!result) assert.ok(!result)
}) })
it('should recognize correct capitalized checksum', function() { it('should recognize correct capitalized checksum', function () {
var address = '0xFDEa65C8e26263F6d9A1B5de9555D2931A33b825' var address = '0xFDEa65C8e26263F6d9A1B5de9555D2931A33b825'
var result = util.isValidAddress(address) var result = util.isValidAddress(address)
assert.ok(result) assert.ok(result)
}) })
it('should recognize incorrect capitalized checksum', function() { it('should recognize incorrect capitalized checksum', function () {
var address = '0xFDea65C8e26263F6d9A1B5de9555D2931A33b825' var address = '0xFDea65C8e26263F6d9A1B5de9555D2931A33b825'
var result = util.isValidAddress(address) var result = util.isValidAddress(address)
assert.ok(!result) assert.ok(!result)
}) })
it('should recognize this sample hashed address', function() { it('should recognize this sample hashed address', function () {
const address = '0x5Fda30Bb72B8Dfe20e48A00dFc108d0915BE9Bb0' const address = '0x5Fda30Bb72B8Dfe20e48A00dFc108d0915BE9Bb0'
const result = util.isValidAddress(address) const result = util.isValidAddress(address)
const hashed = ethUtil.toChecksumAddress(address.toLowerCase()) const hashed = ethUtil.toChecksumAddress(address.toLowerCase())
@ -103,60 +103,57 @@ describe('util', function() {
}) })
}) })
describe('#numericBalance', function() { describe('#numericBalance', function () {
it('should return a BN 0 if given nothing', function () {
it('should return a BN 0 if given nothing', function() {
var result = util.numericBalance() var result = util.numericBalance()
assert.equal(result.toString(10), 0) assert.equal(result.toString(10), 0)
}) })
it('should work with hex prefix', function() { it('should work with hex prefix', function () {
var result = util.numericBalance('0x012') var result = util.numericBalance('0x012')
assert.equal(result.toString(10), '18') assert.equal(result.toString(10), '18')
}) })
it('should work with no hex prefix', function() { it('should work with no hex prefix', function () {
var result = util.numericBalance('012') var result = util.numericBalance('012')
assert.equal(result.toString(10), '18') assert.equal(result.toString(10), '18')
}) })
}) })
describe('#formatBalance', function() { describe('#formatBalance', function () {
it('when given nothing', function () {
it('when given nothing', function() {
var result = util.formatBalance() var result = util.formatBalance()
assert.equal(result, 'None', 'should return "None"') assert.equal(result, 'None', 'should return "None"')
}) })
it('should return eth as string followed by ETH', function() { it('should return eth as string followed by ETH', function () {
var input = new ethUtil.BN(ethInWei, 10).toJSON() var input = new ethUtil.BN(ethInWei, 10).toJSON()
var result = util.formatBalance(input, 4) var result = util.formatBalance(input, 4)
assert.equal(result, '1.0000 ETH') assert.equal(result, '1.0000 ETH')
}) })
it('should return eth as string followed by ETH', function() { it('should return eth as string followed by ETH', function () {
var input = new ethUtil.BN(ethInWei, 10).div(new ethUtil.BN('2', 10)).toJSON() var input = new ethUtil.BN(ethInWei, 10).div(new ethUtil.BN('2', 10)).toJSON()
var result = util.formatBalance(input, 3) var result = util.formatBalance(input, 3)
assert.equal(result, '0.500 ETH') assert.equal(result, '0.500 ETH')
}) })
it('should display specified decimal points', function() { it('should display specified decimal points', function () {
var input = "0x128dfa6a90b28000" var input = '0x128dfa6a90b28000'
var result = util.formatBalance(input, 2) var result = util.formatBalance(input, 2)
assert.equal(result, '1.33 ETH') assert.equal(result, '1.33 ETH')
}) })
it('should default to 3 decimal points', function() { it('should default to 3 decimal points', function () {
var input = "0x128dfa6a90b28000" var input = '0x128dfa6a90b28000'
var result = util.formatBalance(input) var result = util.formatBalance(input)
assert.equal(result, '1.337 ETH') assert.equal(result, '1.337 ETH')
}) })
it('should show 2 significant digits for tiny balances', function() { it('should show 2 significant digits for tiny balances', function () {
var input = "0x1230fa6a90b28" var input = '0x1230fa6a90b28'
var result = util.formatBalance(input) var result = util.formatBalance(input)
assert.equal(result, '0.00032 ETH') assert.equal(result, '0.00032 ETH')
}) })
it('should not parse the balance and return value with 2 decimal points with ETH at the end', function() { it('should not parse the balance and return value with 2 decimal points with ETH at the end', function () {
var value = '1.2456789' var value = '1.2456789'
var needsParse = false var needsParse = false
var result = util.formatBalance(value, 2, needsParse) var result = util.formatBalance(value, 2, needsParse)
@ -164,17 +161,16 @@ describe('util', function() {
}) })
}) })
describe('normalizing values', function() { describe('normalizing values', function () {
describe('#normalizeToWei', function () {
describe('#normalizeToWei', function() { it('should convert an eth to the appropriate equivalent values', function () {
it('should convert an eth to the appropriate equivalent values', function() {
var valueTable = { var valueTable = {
wei: '1000000000000000000', wei: '1000000000000000000',
kwei: '1000000000000000', kwei: '1000000000000000',
mwei: '1000000000000', mwei: '1000000000000',
gwei: '1000000000', gwei: '1000000000',
szabo: '1000000', szabo: '1000000',
finney:'1000', finney: '1000',
ether: '1', ether: '1',
// kether:'0.001', // kether:'0.001',
// mether:'0.000001', // mether:'0.000001',
@ -185,8 +181,7 @@ describe('util', function() {
} }
var oneEthBn = new ethUtil.BN(ethInWei, 10) var oneEthBn = new ethUtil.BN(ethInWei, 10)
for(var currency in valueTable) { for (var currency in valueTable) {
var value = new ethUtil.BN(valueTable[currency], 10) var value = new ethUtil.BN(valueTable[currency], 10)
var output = util.normalizeToWei(value, currency) var output = util.normalizeToWei(value, currency)
assert.equal(output.toString(10), valueTable.wei, `value of ${output.toString(10)} ${currency} should convert to ${oneEthBn}`) assert.equal(output.toString(10), valueTable.wei, `value of ${output.toString(10)} ${currency} should convert to ${oneEthBn}`)
@ -194,60 +189,58 @@ describe('util', function() {
}) })
}) })
describe('#normalizeEthStringToWei', function() { describe('#normalizeEthStringToWei', function () {
it('should convert decimal eth to pure wei BN', function() { it('should convert decimal eth to pure wei BN', function () {
var input = '1.23456789' var input = '1.23456789'
var output = util.normalizeEthStringToWei(input) var output = util.normalizeEthStringToWei(input)
assert.equal(output.toString(10), '1234567890000000000') assert.equal(output.toString(10), '1234567890000000000')
}) })
it('should convert 1 to expected wei', function() { it('should convert 1 to expected wei', function () {
var input = '1' var input = '1'
var output = util.normalizeEthStringToWei(input) var output = util.normalizeEthStringToWei(input)
assert.equal(output.toString(10), ethInWei) assert.equal(output.toString(10), ethInWei)
}) })
}) })
describe('#normalizeNumberToWei', function() { describe('#normalizeNumberToWei', function () {
it('should handle a simple use case', function () {
it('should handle a simple use case', function() {
var input = 0.0002 var input = 0.0002
var output = util.normalizeNumberToWei(input, 'ether') var output = util.normalizeNumberToWei(input, 'ether')
var str = output.toString(10) var str = output.toString(10)
assert.equal(str, '200000000000000') assert.equal(str, '200000000000000')
}) })
it('should convert a kwei number to the appropriate equivalent wei', function() { it('should convert a kwei number to the appropriate equivalent wei', function () {
var result = util.normalizeNumberToWei(1.111, 'kwei') var result = util.normalizeNumberToWei(1.111, 'kwei')
assert.equal(result.toString(10), '1111', 'accepts decimals') assert.equal(result.toString(10), '1111', 'accepts decimals')
}) })
it('should convert a ether number to the appropriate equivalent wei', function() { it('should convert a ether number to the appropriate equivalent wei', function () {
var result = util.normalizeNumberToWei(1.111, 'ether') var result = util.normalizeNumberToWei(1.111, 'ether')
assert.equal(result.toString(10), '1111000000000000000', 'accepts decimals') assert.equal(result.toString(10), '1111000000000000000', 'accepts decimals')
}) })
}) })
describe('#isHex', function(){ describe('#isHex', function () {
it('should return true when given a hex string', function() { it('should return true when given a hex string', function () {
var result = util.isHex('c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2') var result = util.isHex('c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2')
assert(result) assert(result)
}) })
it('should return false when given a non-hex string', function() { it('should return false when given a non-hex string', function () {
var result = util.isHex('c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714imnotreal') var result = util.isHex('c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714imnotreal')
assert(!result) assert(!result)
}) })
it('should return false when given a string containing a non letter/number character', function() { it('should return false when given a string containing a non letter/number character', function () {
var result = util.isHex('c3ab8ff13720!8ad9047dd39466b3c%8974e592c2fa383d4a396071imnotreal') var result = util.isHex('c3ab8ff13720!8ad9047dd39466b3c%8974e592c2fa383d4a396071imnotreal')
assert(!result) assert(!result)
}) })
it('should return true when given a hex string with hex-prefix', function() { it('should return true when given a hex string with hex-prefix', function () {
var result = util.isHex('0xc3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2') var result = util.isHex('0xc3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2')
assert(result) assert(result)
}) })
}) })
}) })
}) })