diff options
Merge branch 'develop' of github.com:MetaMask/metamask-extension into network-remove-provider-engine
Diffstat (limited to 'test/unit')
38 files changed, 939 insertions, 307 deletions
diff --git a/test/unit/actions/save_account_label_test.js b/test/unit/actions/save_account_label_test.js deleted file mode 100644 index c5ffd6cbf..000000000 --- a/test/unit/actions/save_account_label_test.js +++ /dev/null @@ -1,35 +0,0 @@ -// var jsdom = require('mocha-jsdom') -var assert = require('assert') -var freeze = require('deep-freeze-strict') -var path = require('path') - -var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) -var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) - -describe('SAVE_ACCOUNT_LABEL', function () { - it('updates the state.metamask.identities[:i].name property of the state to the action.value.label', function () { - var initialState = { - metamask: { - identities: { - foo: { - name: 'bar', - }, - }, - }, - } - freeze(initialState) - - const action = { - type: actions.SAVE_ACCOUNT_LABEL, - value: { - account: 'foo', - label: 'baz', - }, - } - freeze(action) - - var resultingState = reducers(initialState, action) - assert.equal(resultingState.metamask.identities.foo.name, action.value.label) - }) -}) - diff --git a/test/unit/actions/set_account_label_test.js b/test/unit/actions/set_account_label_test.js new file mode 100644 index 000000000..53ea1d130 --- /dev/null +++ b/test/unit/actions/set_account_label_test.js @@ -0,0 +1,34 @@ +const assert = require('assert') +const freeze = require('deep-freeze-strict') +const path = require('path') + +const actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) +const reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) + +describe('SET_ACCOUNT_LABEL', function () { + it('updates the state.metamask.identities[:i].name property of the state to the action.value.label', function () { + const initialState = { + metamask: { + identities: { + foo: { + name: 'bar', + }, + }, + }, + } + freeze(initialState) + + const action = { + type: actions.SET_ACCOUNT_LABEL, + value: { + account: 'foo', + label: 'baz', + }, + } + freeze(action) + + const resultingState = reducers(initialState, action) + assert.equal(resultingState.metamask.identities.foo.name, action.value.label) + }) +}) + diff --git a/test/unit/actions/tx_test.js b/test/unit/actions/tx_test.js index b6a691860..c110f71fc 100644 --- a/test/unit/actions/tx_test.js +++ b/test/unit/actions/tx_test.js @@ -9,7 +9,7 @@ var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'redu describe('tx confirmation screen', function () { beforeEach(function () { - this.sinon = sinon.sandbox.create() + this.sinon = sinon.createSandbox() }) afterEach(function () { diff --git a/test/unit/ComposableObservableStore.js b/test/unit/app/ComposableObservableStore.js index 3fba200c1..aa8abd463 100644 --- a/test/unit/ComposableObservableStore.js +++ b/test/unit/app/ComposableObservableStore.js @@ -1,5 +1,5 @@ const assert = require('assert') -const ComposableObservableStore = require('../../app/scripts/lib/ComposableObservableStore') +const ComposableObservableStore = require('../../../app/scripts/lib/ComposableObservableStore') const ObservableStore = require('obs-store') describe('ComposableObservableStore', () => { diff --git a/test/unit/app/account-import-strategies.spec.js b/test/unit/app/account-import-strategies.spec.js new file mode 100644 index 000000000..83cfaeb3e --- /dev/null +++ b/test/unit/app/account-import-strategies.spec.js @@ -0,0 +1,31 @@ +const assert = require('assert') +const path = require('path') +const accountImporter = require('../../../app/scripts/account-import-strategies/index') +const ethUtil = require('ethereumjs-util') + +describe('Account Import Strategies', function () { + const privkey = '0x4cfd3e90fc78b0f86bf7524722150bb8da9c60cd532564d7ff43f5716514f553' + const json = '{"version":3,"id":"dbb54385-0a99-437f-83c0-647de9f244c3","address":"a7f92ce3fba24196cf6f4bd2e1eb3db282ba998c","Crypto":{"ciphertext":"bde13d9ade5c82df80281ca363320ce254a8a3a06535bbf6ffdeaf0726b1312c","cipherparams":{"iv":"fbf93718a57f26051b292f072f2e5b41"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"dklen":32,"salt":"7ffe00488319dec48e4c49a120ca49c6afbde9272854c64d9541c83fc6acdffe","n":8192,"r":8,"p":1},"mac":"2adfd9c4bc1cdac4c85bddfb31d9e21a684e0e050247a70c5698facf6b7d4681"}}' + + it('imports a private key and strips 0x prefix', async function () { + const importPrivKey = await accountImporter.importAccount('Private Key', [ privkey ]) + assert.equal(importPrivKey, ethUtil.stripHexPrefix(privkey)) + }) + + it('fails when password is incorrect for keystore', async function () { + const wrongPassword = 'password2' + + try { + await accountImporter.importAccount('JSON File', [ json, wrongPassword]) + } catch (error) { + assert.equal(error.message, 'Key derivation failed - possibly wrong passphrase') + } + }) + + it('imports json string and password to return a private key', async function () { + const fileContentsPassword = 'password1' + const importJson = await accountImporter.importAccount('JSON File', [ json, fileContentsPassword]) + assert.equal(importJson, '0x5733876abe94146069ce8bcbabbde2677f2e35fa33e875e92041ed2ac87e5bc7') + }) + +}) diff --git a/test/unit/app/buy-eth-url.spec.js b/test/unit/app/buy-eth-url.spec.js new file mode 100644 index 000000000..36646fa68 --- /dev/null +++ b/test/unit/app/buy-eth-url.spec.js @@ -0,0 +1,48 @@ +const assert = require('assert') +const getBuyEthUrl = require('../../../app/scripts/lib/buy-eth-url') + +describe('', function () { + const mainnet = { + network: '1', + amount: 5, + address: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc', + } + const ropsten = { + network: '3', + } + const rinkeby = { + network: '4', + } + const kovan = { + network: '42', + } + + it('returns coinbase url with amount and address for network 1', function () { + const coinbaseUrl = getBuyEthUrl(mainnet) + const coinbase = coinbaseUrl.match(/(https:\/\/buy.coinbase.com)/) + const amount = coinbaseUrl.match(/(amount)\D\d/) + const address = coinbaseUrl.match(/(address)(.*)(?=&)/) + + assert.equal(coinbase[0], 'https://buy.coinbase.com') + assert.equal(amount[0], 'amount=5') + assert.equal(address[0], 'address=0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc') + + }) + + it('returns metamask ropsten faucet for network 3', function () { + const ropstenUrl = getBuyEthUrl(ropsten) + assert.equal(ropstenUrl, 'https://faucet.metamask.io/') + }) + + it('returns rinkeby dapp for network 4', function () { + const rinkebyUrl = getBuyEthUrl(rinkeby) + assert.equal(rinkebyUrl, 'https://www.rinkeby.io/') + }) + + it('returns kovan github test faucet for network 42', function () { + const kovanUrl = getBuyEthUrl(kovan) + assert.equal(kovanUrl, 'https://github.com/kovan-testnet/faucet') + }) + +}) + diff --git a/test/unit/address-book-controller.js b/test/unit/app/controllers/address-book-controller.js index 655c9022c..dc4b8e3ff 100644 --- a/test/unit/address-book-controller.js +++ b/test/unit/app/controllers/address-book-controller.js @@ -1,26 +1,26 @@ const assert = require('assert') -const AddressBookController = require('../../app/scripts/controllers/address-book') +const AddressBookController = require('../../../../app/scripts/controllers/address-book') -const mockKeyringController = { - memStore: { - getState: function () { - return { - identities: { - '0x0aaa': { - address: '0x0aaa', - name: 'owned', - }, +const stubPreferencesStore = { + getState: function () { + return { + identities: { + '0x0aaa': { + address: '0x0aaa', + name: 'owned', }, - } - }, + }, + } }, -} +}; describe('address-book-controller', function () { var addressBookController beforeEach(function () { - addressBookController = new AddressBookController({}, mockKeyringController) + addressBookController = new AddressBookController({ + preferencesStore: stubPreferencesStore, + }) }) describe('addres book management', function () { diff --git a/test/unit/blacklist-controller-test.js b/test/unit/app/controllers/blacklist-controller-test.js index cbf73d3e5..085641777 100644 --- a/test/unit/blacklist-controller-test.js +++ b/test/unit/app/controllers/blacklist-controller-test.js @@ -1,5 +1,5 @@ const assert = require('assert') -const BlacklistController = require('../../app/scripts/controllers/blacklist') +const BlacklistController = require('../../../../app/scripts/controllers/blacklist') describe('blacklist controller', function () { let blacklistController diff --git a/test/unit/currency-controller-test.js b/test/unit/app/controllers/currency-controller-test.js index 63ab60f9e..1941d1c43 100644 --- a/test/unit/currency-controller-test.js +++ b/test/unit/app/controllers/currency-controller-test.js @@ -3,7 +3,7 @@ global.fetch = global.fetch || require('isomorphic-fetch') const assert = require('assert') const nock = require('nock') -const CurrencyController = require('../../app/scripts/controllers/currency') +const CurrencyController = require('../../../../app/scripts/controllers/currency') describe('currency-controller', function () { var currencyController @@ -45,7 +45,6 @@ describe('currency-controller', function () { currencyController.updateConversionRate() .then(function () { var result = currencyController.getConversionRate() - console.log('currencyController.getConversionRate:', result) assert.equal(typeof result, 'number') done() }).catch(function (err) { diff --git a/test/unit/infura-controller-test.js b/test/unit/app/controllers/infura-controller-test.js index 605305efa..7bd95dd4b 100644 --- a/test/unit/infura-controller-test.js +++ b/test/unit/app/controllers/infura-controller-test.js @@ -1,6 +1,6 @@ const assert = require('assert') const sinon = require('sinon') -const InfuraController = require('../../app/scripts/controllers/infura') +const InfuraController = require('../../../../app/scripts/controllers/infura') describe('infura-controller', function () { let infuraController, sandbox, networkStatus @@ -8,7 +8,7 @@ describe('infura-controller', function () { before(async function () { infuraController = new InfuraController() - sandbox = sinon.sandbox.create() + sandbox = sinon.createSandbox() sinon.stub(infuraController, 'checkInfuraNetworkStatus').resolves(response) networkStatus = await infuraController.checkInfuraNetworkStatus() }) diff --git a/test/unit/app/controllers/metamask-controller-test.js b/test/unit/app/controllers/metamask-controller-test.js new file mode 100644 index 000000000..4bc16e65e --- /dev/null +++ b/test/unit/app/controllers/metamask-controller-test.js @@ -0,0 +1,550 @@ +const assert = require('assert') +const sinon = require('sinon') +const clone = require('clone') +const nock = require('nock') +const createThoughStream = require('through2').obj +const MetaMaskController = require('../../../../app/scripts/metamask-controller') +const blacklistJSON = require('eth-phishing-detect/src/config') +const firstTimeState = require('../../../../app/scripts/first-time-state') + +const currentNetworkId = 42 +const DEFAULT_LABEL = 'Account 1' +const TEST_SEED = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium' +const TEST_ADDRESS = '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc' +const TEST_SEED_ALT = 'setup olympic issue mobile velvet surge alcohol burger horse view reopen gentle' +const TEST_ADDRESS_ALT = '0xc42edfcc21ed14dda456aa0756c153f7985d8813' + +describe('MetaMaskController', function () { + let metamaskController + const sandbox = sinon.createSandbox() + const noop = () => {} + + beforeEach(function () { + + nock('https://api.infura.io') + .persist() + .get('/v2/blacklist') + .reply(200, blacklistJSON) + + nock('https://api.infura.io') + .get('/v1/ticker/ethusd') + .reply(200, '{"base": "ETH", "quote": "USD", "bid": 288.45, "ask": 288.46, "volume": 112888.17569277, "exchange": "bitfinex", "total_volume": 272175.00106721005, "num_exchanges": 8, "timestamp": 1506444677}') + + nock('https://api.infura.io') + .get('/v1/ticker/ethjpy') + .reply(200, '{"base": "ETH", "quote": "JPY", "bid": 32300.0, "ask": 32400.0, "volume": 247.4616071, "exchange": "kraken", "total_volume": 247.4616071, "num_exchanges": 1, "timestamp": 1506444676}') + + nock('https://api.infura.io') + .persist() + .get(/.*/) + .reply(200) + + metamaskController = new MetaMaskController({ + showUnapprovedTx: noop, + showUnconfirmedMessage: noop, + encryptor: { + encrypt: function (password, object) { + this.object = object + return Promise.resolve() + }, + decrypt: function () { + return Promise.resolve(this.object) + }, + }, + initState: clone(firstTimeState), + }) + sandbox.spy(metamaskController.keyringController, 'createNewVaultAndKeychain') + sandbox.spy(metamaskController.keyringController, 'createNewVaultAndRestore') + }) + + afterEach(function () { + nock.cleanAll() + sandbox.restore() + }) + + describe('#getGasPrice', function () { + + it('gives the 50th percentile lowest accepted gas price from recentBlocksController', async function () { + const realRecentBlocksController = metamaskController.recentBlocksController + metamaskController.recentBlocksController = { + store: { + getState: () => { + return { + recentBlocks: [ + { gasPrices: [ '0x3b9aca00', '0x174876e800'] }, + { gasPrices: [ '0x3b9aca00', '0x174876e800'] }, + { gasPrices: [ '0x174876e800', '0x174876e800' ]}, + { gasPrices: [ '0x174876e800', '0x174876e800' ]}, + ], + } + }, + }, + } + + const gasPrice = metamaskController.getGasPrice() + assert.equal(gasPrice, '0x3b9aca00', 'accurately estimates 50th percentile accepted gas price') + + metamaskController.recentBlocksController = realRecentBlocksController + }) + }) + + describe('#createNewVaultAndKeychain', function () { + it('can only create new vault on keyringController once', async function () { + const selectStub = sandbox.stub(metamaskController, 'selectFirstIdentity') + + const password = 'a-fake-password' + + await metamaskController.createNewVaultAndKeychain(password) + await metamaskController.createNewVaultAndKeychain(password) + + assert(metamaskController.keyringController.createNewVaultAndKeychain.calledOnce) + + selectStub.reset() + }) + }) + + describe('#createNewVaultAndRestore', function () { + it('should be able to call newVaultAndRestore despite a mistake.', async function () { + const password = 'what-what-what' + await metamaskController.createNewVaultAndRestore(password, TEST_SEED.slice(0, -1)).catch((e) => null) + await metamaskController.createNewVaultAndRestore(password, TEST_SEED) + + assert(metamaskController.keyringController.createNewVaultAndRestore.calledTwice) + }) + + it('should clear previous identities after vault restoration', async () => { + await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED) + assert.deepEqual(metamaskController.getState().identities, { + [TEST_ADDRESS]: { address: TEST_ADDRESS, name: DEFAULT_LABEL }, + }) + + await metamaskController.preferencesController.setAccountLabel(TEST_ADDRESS, 'Account Foo') + assert.deepEqual(metamaskController.getState().identities, { + [TEST_ADDRESS]: { address: TEST_ADDRESS, name: 'Account Foo' }, + }) + + await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT) + assert.deepEqual(metamaskController.getState().identities, { + [TEST_ADDRESS_ALT]: { address: TEST_ADDRESS_ALT, name: DEFAULT_LABEL }, + }) + }) + }) + + describe('#getApi', function () { + let getApi, state + + beforeEach(function () { + getApi = metamaskController.getApi() + }) + + it('getState', function (done) { + getApi.getState((err, res) => { + if (err) { + done(err) + } else { + state = res + } + }) + assert.deepEqual(state, metamaskController.getState()) + done() + }) + + }) + + describe('preferencesController', function () { + + it('defaults useBlockie to false', function () { + assert.equal(metamaskController.preferencesController.store.getState().useBlockie, false) + }) + + it('setUseBlockie to true', function () { + metamaskController.setUseBlockie(true, noop) + assert.equal(metamaskController.preferencesController.store.getState().useBlockie, true) + }) + + }) + + describe('#selectFirstIdentity', function () { + let identities, address + + beforeEach(function () { + address = '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc' + identities = { + '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc': { + 'address': address, + 'name': 'Account 1', + }, + '0xc42edfcc21ed14dda456aa0756c153f7985d8813': { + 'address': '0xc42edfcc21ed14dda456aa0756c153f7985d8813', + 'name': 'Account 2', + }, + } + metamaskController.preferencesController.store.updateState({ identities }) + metamaskController.selectFirstIdentity() + }) + + it('changes preferences controller select address', function () { + const preferenceControllerState = metamaskController.preferencesController.store.getState() + assert.equal(preferenceControllerState.selectedAddress, address) + }) + + it('changes metamask controller selected address', function () { + const metamaskState = metamaskController.getState() + assert.equal(metamaskState.selectedAddress, address) + }) + }) + + describe('#setCustomRpc', function () { + const customRPC = 'https://custom.rpc/' + let rpcTarget + + beforeEach(function () { + + nock('https://custom.rpc') + .post('/') + .reply(200) + + rpcTarget = metamaskController.setCustomRpc(customRPC) + }) + + afterEach(function () { + nock.cleanAll() + }) + + it('returns custom RPC that when called', async function () { + assert.equal(await rpcTarget, customRPC) + }) + + it('changes the network controller rpc', function () { + const networkControllerState = metamaskController.networkController.store.getState() + assert.equal(networkControllerState.provider.rpcTarget, customRPC) + }) + }) + + describe('#setCurrentCurrency', function () { + let defaultMetaMaskCurrency + + beforeEach(function () { + defaultMetaMaskCurrency = metamaskController.currencyController.getCurrentCurrency() + }) + + it('defaults to usd', function () { + assert.equal(defaultMetaMaskCurrency, 'usd') + }) + + it('sets currency to JPY', function () { + metamaskController.setCurrentCurrency('JPY', noop) + assert.equal(metamaskController.currencyController.getCurrentCurrency(), 'JPY') + }) + }) + + describe('#createShapeshifttx', function () { + let depositAddress, depositType, shapeShiftTxList + + beforeEach(function () { + nock('https://shapeshift.io') + .get('/txStat/3EevLFfB4H4XMWQwYCgjLie1qCAGpd2WBc') + .reply(200, '{"status": "no_deposits", "address": "3EevLFfB4H4XMWQwYCgjLie1qCAGpd2WBc"}') + + depositAddress = '3EevLFfB4H4XMWQwYCgjLie1qCAGpd2WBc' + depositType = 'ETH' + shapeShiftTxList = metamaskController.shapeshiftController.store.getState().shapeShiftTxList + }) + + it('creates a shapeshift tx', async function () { + metamaskController.createShapeShiftTx(depositAddress, depositType) + assert.equal(shapeShiftTxList[0].depositAddress, depositAddress) + }) + + }) + + describe('#addNewAccount', function () { + let addNewAccount + + beforeEach(function () { + addNewAccount = metamaskController.addNewAccount() + }) + + it('errors when an primary keyring is does not exist', async function () { + try { + await addNewAccount + assert.equal(1 === 0) + } catch (e) { + assert.equal(e.message, 'MetamaskController - No HD Key Tree found') + } + }) + }) + + describe('#verifyseedPhrase', function () { + let seedPhrase, getConfigSeed + + it('errors when no keying is provided', async function () { + try { + await metamaskController.verifySeedPhrase() + } catch (error) { + assert.equal(error.message, 'MetamaskController - No HD Key Tree found') + } + }) + + beforeEach(async function () { + await metamaskController.createNewVaultAndKeychain('password') + seedPhrase = await metamaskController.verifySeedPhrase() + }) + + it('#placeSeedWords should match the initially created vault seed', function () { + + metamaskController.placeSeedWords((err, result) => { + if (err) { + console.log(err) + } else { + getConfigSeed = metamaskController.configManager.getSeedWords() + assert.equal(result, seedPhrase) + assert.equal(result, getConfigSeed) + } + }) + assert.equal(getConfigSeed, undefined) + }) + + it('#addNewAccount', async function () { + await metamaskController.addNewAccount() + const getAccounts = await metamaskController.keyringController.getAccounts() + assert.equal(getAccounts.length, 2) + }) + }) + + describe('#resetAccount', function () { + + beforeEach(function () { + const selectedAddressStub = sinon.stub(metamaskController.preferencesController, 'getSelectedAddress') + const getNetworkstub = sinon.stub(metamaskController.txController.txStateManager, 'getNetwork') + + selectedAddressStub.returns('0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc') + getNetworkstub.returns(42) + + metamaskController.txController.txStateManager._saveTxList([ + { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {from: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'} }, + { id: 2, status: 'rejected', metamaskNetworkId: 32, txParams: {} }, + { id: 3, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {from: '0xB09d8505E1F4EF1CeA089D47094f5DD3464083d4'} }, + ]) + }) + + it('wipes transactions from only the correct network id and with the selected address', async function () { + await metamaskController.resetAccount() + assert.equal(metamaskController.txController.txStateManager.getTx(1), undefined) + }) + }) + + describe('#clearSeedWordCache', function () { + + it('should have set seed words', function () { + metamaskController.configManager.setSeedWords('test words') + const getConfigSeed = metamaskController.configManager.getSeedWords() + assert.equal(getConfigSeed, 'test words') + }) + + it('should clear config seed phrase', function () { + metamaskController.configManager.setSeedWords('test words') + metamaskController.clearSeedWordCache((err, result) => { + if (err) console.log(err) + }) + const getConfigSeed = metamaskController.configManager.getSeedWords() + assert.equal(getConfigSeed, null) + }) + + }) + + describe('#setCurrentLocale', function () { + + it('checks the default currentLocale', function () { + const preferenceCurrentLocale = metamaskController.preferencesController.store.getState().currentLocale + assert.equal(preferenceCurrentLocale, undefined) + }) + + it('sets current locale in preferences controller', function () { + metamaskController.setCurrentLocale('ja', noop) + const preferenceCurrentLocale = metamaskController.preferencesController.store.getState().currentLocale + assert.equal(preferenceCurrentLocale, 'ja') + }) + + }) + + describe('#newUnsignedMessage', function () { + + let msgParams, metamaskMsgs, messages, msgId + + const address = '0xc42edfcc21ed14dda456aa0756c153f7985d8813' + const data = '0x43727970746f6b697474696573' + + beforeEach(async function () { + + await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT) + + msgParams = { + 'from': address, + 'data': data, + } + + metamaskController.newUnsignedMessage(msgParams, noop) + metamaskMsgs = metamaskController.messageManager.getUnapprovedMsgs() + messages = metamaskController.messageManager.messages + msgId = Object.keys(metamaskMsgs)[0] + messages[0].msgParams.metamaskId = parseInt(msgId) + }) + + it('persists address from msg params', function () { + assert.equal(metamaskMsgs[msgId].msgParams.from, address) + }) + + it('persists data from msg params', function () { + assert.equal(metamaskMsgs[msgId].msgParams.data, data) + }) + + it('sets the status to unapproved', function () { + assert.equal(metamaskMsgs[msgId].status, 'unapproved') + }) + + it('sets the type to eth_sign', function () { + assert.equal(metamaskMsgs[msgId].type, 'eth_sign') + }) + + it('rejects the message', function () { + const msgIdInt = parseInt(msgId) + metamaskController.cancelMessage(msgIdInt, noop) + assert.equal(messages[0].status, 'rejected') + }) + + it('errors when signing a message', async function () { + try { + await metamaskController.signMessage(messages[0].msgParams) + } catch (error) { + assert.equal(error.message, 'message length is invalid') + } + }) + }) + + describe('#newUnsignedPersonalMessage', function () { + + it('errors with no from in msgParams', function () { + const msgParams = { + 'data': data, + } + metamaskController.newUnsignedPersonalMessage(msgParams, function (error) { + assert.equal(error.message, 'MetaMask Message Signature: from field is required.') + }) + }) + + let msgParams, metamaskPersonalMsgs, personalMessages, msgId + + const address = '0xc42edfcc21ed14dda456aa0756c153f7985d8813' + const data = '0x43727970746f6b697474696573' + + beforeEach(async function () { + + await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT) + + msgParams = { + 'from': address, + 'data': data, + } + + metamaskController.newUnsignedPersonalMessage(msgParams, noop) + metamaskPersonalMsgs = metamaskController.personalMessageManager.getUnapprovedMsgs() + personalMessages = metamaskController.personalMessageManager.messages + msgId = Object.keys(metamaskPersonalMsgs)[0] + personalMessages[0].msgParams.metamaskId = parseInt(msgId) + }) + + it('persists address from msg params', function () { + assert.equal(metamaskPersonalMsgs[msgId].msgParams.from, address) + }) + + it('persists data from msg params', function () { + assert.equal(metamaskPersonalMsgs[msgId].msgParams.data, data) + }) + + it('sets the status to unapproved', function () { + assert.equal(metamaskPersonalMsgs[msgId].status, 'unapproved') + }) + + it('sets the type to personal_sign', function () { + assert.equal(metamaskPersonalMsgs[msgId].type, 'personal_sign') + }) + + it('rejects the message', function () { + const msgIdInt = parseInt(msgId) + metamaskController.cancelPersonalMessage(msgIdInt, noop) + assert.equal(personalMessages[0].status, 'rejected') + }) + + it('errors when signing a message', async function () { + await metamaskController.signPersonalMessage(personalMessages[0].msgParams) + assert.equal(metamaskPersonalMsgs[msgId].status, 'signed') + assert.equal(metamaskPersonalMsgs[msgId].rawSig, '0x6a1b65e2b8ed53cf398a769fad24738f9fbe29841fe6854e226953542c4b6a173473cb152b6b1ae5f06d601d45dd699a129b0a8ca84e78b423031db5baa734741b') + }) + }) + + describe('#setupUntrustedCommunication', function () { + let streamTest + + const phishingUrl = 'decentral.market' + + afterEach(function () { + streamTest.end() + }) + + it('sets up phishing stream for untrusted communication ', async function () { + await metamaskController.blacklistController.updatePhishingList() + + streamTest = createThoughStream((chunk, enc, cb) => { + assert.equal(chunk.name, 'phishing') + assert.equal(chunk.data.hostname, phishingUrl) + cb() + }) + // console.log(streamTest) + metamaskController.setupUntrustedCommunication(streamTest, phishingUrl) + }) + }) + + describe('#setupTrustedCommunication', function () { + let streamTest + + afterEach(function () { + streamTest.end() + }) + + it('sets up controller dnode api for trusted communication', function (done) { + streamTest = createThoughStream((chunk, enc, cb) => { + assert.equal(chunk.name, 'controller') + cb() + done() + }) + + metamaskController.setupTrustedCommunication(streamTest, 'mycrypto.com') + }) + }) + + describe('#markAccountsFound', function () { + it('adds lost accounts to config manager data', function () { + metamaskController.markAccountsFound(noop) + const configManagerData = metamaskController.configManager.getData() + assert.deepEqual(configManagerData.lostAccounts, []) + }) + }) + + describe('#markPasswordForgotten', function () { + it('adds and sets forgottenPassword to config data to true', function () { + metamaskController.markPasswordForgotten(noop) + const configManagerData = metamaskController.configManager.getData() + assert.equal(configManagerData.forgottenPassword, true) + }) + }) + + describe('#unMarkPasswordForgotten', function () { + it('adds and sets forgottenPassword to config data to false', function () { + metamaskController.unMarkPasswordForgotten(noop) + const configManagerData = metamaskController.configManager.getData() + assert.equal(configManagerData.forgottenPassword, false) + }) + }) + +}) diff --git a/test/unit/network-contoller-test.js b/test/unit/app/controllers/network-contoller-test.js index 54cd3c7f4..701eb5718 100644 --- a/test/unit/network-contoller-test.js +++ b/test/unit/app/controllers/network-contoller-test.js @@ -1,11 +1,11 @@ const assert = require('assert') const nock = require('nock') -const NetworkController = require('../../app/scripts/controllers/network') +const NetworkController = require('../../../../app/scripts/controllers/network') const { getNetworkDisplayName, -} = require('../../app/scripts/controllers/network/util') +} = require('../../../../app/scripts/controllers/network/util') -const { createTestProviderTools } = require('../stub/provider') +const { createTestProviderTools } = require('../../../stub/provider') const providerResultStub = {} describe('# Network Controller', function () { diff --git a/test/unit/notice-controller-test.js b/test/unit/app/controllers/notice-controller-test.js index 09eeda15c..e78b69623 100644 --- a/test/unit/notice-controller-test.js +++ b/test/unit/app/controllers/notice-controller-test.js @@ -1,6 +1,6 @@ const assert = require('assert') -const configManagerGen = require('../lib/mock-config-manager') -const NoticeController = require('../../app/scripts/notice-controller') +const configManagerGen = require('../../../lib/mock-config-manager') +const NoticeController = require('../../../../app/scripts/notice-controller') describe('notice-controller', function () { var noticeController diff --git a/test/unit/app/controllers/preferences-controller-test.js b/test/unit/app/controllers/preferences-controller-test.js new file mode 100644 index 000000000..e5e751b57 --- /dev/null +++ b/test/unit/app/controllers/preferences-controller-test.js @@ -0,0 +1,162 @@ +const assert = require('assert') +const PreferencesController = require('../../../../app/scripts/controllers/preferences') + +describe('preferences controller', function () { + let preferencesController + + beforeEach(() => { + preferencesController = new PreferencesController() + }) + + describe('setAddresses', function () { + it('should keep a map of addresses to names and addresses in the store', function () { + preferencesController.setAddresses([ + '0xda22le', + '0x7e57e2', + ]) + + const {identities} = preferencesController.store.getState() + assert.deepEqual(identities, { + '0xda22le': { + name: 'Account 1', + address: '0xda22le', + }, + '0x7e57e2': { + name: 'Account 2', + address: '0x7e57e2', + }, + }) + }) + + it('should replace its list of addresses', function () { + preferencesController.setAddresses([ + '0xda22le', + '0x7e57e2', + ]) + preferencesController.setAddresses([ + '0xda22le77', + '0x7e57e277', + ]) + + const {identities} = preferencesController.store.getState() + assert.deepEqual(identities, { + '0xda22le77': { + name: 'Account 1', + address: '0xda22le77', + }, + '0x7e57e277': { + name: 'Account 2', + address: '0x7e57e277', + }, + }) + }) + }) + + describe('setAccountLabel', function () { + it('should update a label for the given account', function () { + preferencesController.setAddresses([ + '0xda22le', + '0x7e57e2', + ]) + + assert.deepEqual(preferencesController.store.getState().identities['0xda22le'], { + name: 'Account 1', + address: '0xda22le', + }) + + + preferencesController.setAccountLabel('0xda22le', 'Dazzle') + assert.deepEqual(preferencesController.store.getState().identities['0xda22le'], { + name: 'Dazzle', + address: '0xda22le', + }) + }) + }) + + describe('getTokens', function () { + it('should return an empty list initially', async function () { + await preferencesController.setSelectedAddress('0x7e57e2') + + const tokens = preferencesController.getTokens() + assert.equal(tokens.length, 0, 'empty list of tokens') + }) + }) + + describe('addToken', function () { + it('should add that token to its state', async function () { + const address = '0xabcdef1234567' + const symbol = 'ABBR' + const decimals = 5 + + await preferencesController.setSelectedAddress('0x7e57e2') + await preferencesController.addToken(address, symbol, decimals) + + const tokens = preferencesController.getTokens() + assert.equal(tokens.length, 1, 'one token added') + + const added = tokens[0] + assert.equal(added.address, address, 'set address correctly') + assert.equal(added.symbol, symbol, 'set symbol correctly') + assert.equal(added.decimals, decimals, 'set decimals correctly') + }) + + it('should allow updating a token value', async function () { + const address = '0xabcdef1234567' + const symbol = 'ABBR' + const decimals = 5 + + await preferencesController.setSelectedAddress('0x7e57e2') + await preferencesController.addToken(address, symbol, decimals) + + const newDecimals = 6 + await preferencesController.addToken(address, symbol, newDecimals) + + const tokens = preferencesController.getTokens() + assert.equal(tokens.length, 1, 'one token added') + + const added = tokens[0] + assert.equal(added.address, address, 'set address correctly') + assert.equal(added.symbol, symbol, 'set symbol correctly') + assert.equal(added.decimals, newDecimals, 'updated decimals correctly') + }) + + it('should allow adding tokens to two separate addresses', async function () { + const address = '0xabcdef1234567' + const symbol = 'ABBR' + const decimals = 5 + + await preferencesController.setSelectedAddress('0x7e57e2') + await preferencesController.addToken(address, symbol, decimals) + assert.equal(preferencesController.getTokens().length, 1, 'one token added for 1st address') + + await preferencesController.setSelectedAddress('0xda22le') + await preferencesController.addToken(address, symbol, decimals) + assert.equal(preferencesController.getTokens().length, 1, 'one token added for 2nd address') + }) + }) + + describe('removeToken', function () { + it('should remove the only token from its state', async function () { + await preferencesController.setSelectedAddress('0x7e57e2') + await preferencesController.addToken('0xa', 'A', 5) + await preferencesController.removeToken('0xa') + + const tokens = preferencesController.getTokens() + assert.equal(tokens.length, 0, 'one token removed') + }) + + it('should remove a token from its state', async function () { + await preferencesController.setSelectedAddress('0x7e57e2') + await preferencesController.addToken('0xa', 'A', 4) + await preferencesController.addToken('0xb', 'B', 5) + await preferencesController.removeToken('0xa') + + const tokens = preferencesController.getTokens() + assert.equal(tokens.length, 1, 'one token removed') + + const [token1] = tokens + assert.deepEqual(token1, {address: '0xb', symbol: 'B', decimals: 5}) + }) + }) +}) + diff --git a/test/unit/token-rates-controller.js b/test/unit/app/controllers/token-rates-controller.js index a49547313..28e583d8d 100644 --- a/test/unit/token-rates-controller.js +++ b/test/unit/app/controllers/token-rates-controller.js @@ -1,6 +1,6 @@ const assert = require('assert') const sinon = require('sinon') -const TokenRatesController = require('../../app/scripts/controllers/token-rates') +const TokenRatesController = require('../../../../app/scripts/controllers/token-rates') const ObservableStore = require('obs-store') describe('TokenRatesController', () => { diff --git a/test/unit/nonce-tracker-test.js b/test/unit/app/controllers/transactions/nonce-tracker-test.js index b9e6a5947..78d637706 100644 --- a/test/unit/nonce-tracker-test.js +++ b/test/unit/app/controllers/transactions/nonce-tracker-test.js @@ -1,6 +1,6 @@ const assert = require('assert') -const NonceTracker = require('../../app/scripts/controllers/transactions/nonce-tracker') -const MockTxGen = require('../lib/mock-tx-gen') +const NonceTracker = require('../../../../../app/scripts/controllers/transactions/nonce-tracker') +const MockTxGen = require('../../../../lib/mock-tx-gen') let providerResultStub = {} describe('Nonce Tracker', function () { diff --git a/test/unit/pending-tx-test.js b/test/unit/app/controllers/transactions/pending-tx-test.js index 001b86dd1..e7705c594 100644 --- a/test/unit/pending-tx-test.js +++ b/test/unit/app/controllers/transactions/pending-tx-test.js @@ -3,9 +3,9 @@ const ethUtil = require('ethereumjs-util') const EthTx = require('ethereumjs-tx') const ObservableStore = require('obs-store') const clone = require('clone') -const { createTestProviderTools } = require('../stub/provider') -const PendingTransactionTracker = require('../../app/scripts/controllers/transactions/pending-tx-tracker') -const MockTxGen = require('../lib/mock-tx-gen') +const { createTestProviderTools } = require('../../../../stub/provider') +const PendingTransactionTracker = require('../../../../../app/scripts/controllers/transactions/pending-tx-tracker') +const MockTxGen = require('../../../../lib/mock-tx-gen') const sinon = require('sinon') const noop = () => true const currentNetworkId = 42 @@ -294,7 +294,7 @@ describe('PendingTransactionTracker', function () { }) afterEach(() => { - pendingTxTracker.publishTransaction.reset() + pendingTxTracker.publishTransaction.restore() }) it('should publish the transaction', function (done) { diff --git a/test/unit/tx-controller-test.js b/test/unit/app/controllers/transactions/tx-controller-test.js index ddd921652..1f32a0f37 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/app/controllers/transactions/tx-controller-test.js @@ -4,9 +4,9 @@ const EthTx = require('ethereumjs-tx') const EthjsQuery = require('ethjs-query') const ObservableStore = require('obs-store') const sinon = require('sinon') -const TransactionController = require('../../app/scripts/controllers/transactions') -const TxGasUtils = require('../../app/scripts/controllers/transactions/tx-gas-utils') -const { createTestProviderTools, getTestAccounts } = require('../stub/provider') +const TransactionController = require('../../../../../app/scripts/controllers/transactions') +const TxGasUtils = require('../../../../../app/scripts/controllers/transactions/tx-gas-utils') +const { createTestProviderTools, getTestAccounts } = require('../../../../stub/provider') const noop = () => true const currentNetworkId = 42 @@ -40,36 +40,6 @@ describe('Transaction Controller', function () { txController.nonceTracker.getNonceLock = () => Promise.resolve({ nextNonce: 0, releaseLock: noop }) }) - describe('#isNonceTaken', function () { - it('should return true', function (done) { - txController.txStateManager._saveTxList([ - { id: 1, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {nonce: 0, from: '0x8ACCE2391C0d510a6C5E5D8f819A678F79B7E675'} }, - { id: 2, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {nonce: 0, from: '0x8ACCE2391C0d510a6C5E5D8f819A678F79B7E675'} }, - { id: 3, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {nonce: 0, from: '0x8ACCE2391C0d510a6C5E5D8f819A678F79B7E675'} }, - ]) - txController.isNonceTaken({txParams: {nonce:0, from:'0x8ACCE2391C0d510a6C5E5D8f819A678F79B7E675'}}) - .then((isNonceTaken) => { - assert(isNonceTaken) - done() - }).catch(done) - - }) - it('should return false', function (done) { - txController.txStateManager._saveTxList([ - { id: 1, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {nonce: 0, from: '0x8ACCE2391C0d510a6C5E5D8f819A678F79B7E675'} }, - { id: 2, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {nonce: 0, from: '0x8ACCE2391C0d510a6C5E5D8f819A678F79B7E675'} }, - { id: 3, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {nonce: 0, from: '0x8ACCE2391C0d510a6C5E5D8f819A678F79B7E675'} }, - ]) - - txController.isNonceTaken({txParams: {nonce:0, from:'0x8ACCE2391C0d510a6C5E5D8f819A678F79B7E675'}}) - .then((isNonceTaken) => { - assert(!isNonceTaken) - done() - }).catch(done) - - }) - }) - describe('#getState', function () { it('should return a state object with the right keys and datat types', function () { const exposedState = txController.getState() diff --git a/test/unit/tx-gas-util-test.js b/test/unit/app/controllers/transactions/tx-gas-util-test.js index c1d5966da..d1ee86033 100644 --- a/test/unit/tx-gas-util-test.js +++ b/test/unit/app/controllers/transactions/tx-gas-util-test.js @@ -3,8 +3,8 @@ const Transaction = require('ethereumjs-tx') const BN = require('bn.js') -const { hexToBn, bnToHex } = require('../../app/scripts/lib/util') -const TxUtils = require('../../app/scripts/controllers/transactions/tx-gas-utils') +const { hexToBn, bnToHex } = require('../../../../../app/scripts/lib/util') +const TxUtils = require('../../../../../app/scripts/controllers/transactions/tx-gas-utils') describe('txUtils', function () { diff --git a/test/unit/tx-helper-test.js b/test/unit/app/controllers/transactions/tx-helper-test.js index cc6543c30..ce54ef483 100644 --- a/test/unit/tx-helper-test.js +++ b/test/unit/app/controllers/transactions/tx-helper-test.js @@ -1,5 +1,5 @@ const assert = require('assert') -const txHelper = require('../../ui/lib/tx-helper') +const txHelper = require('../../../../../ui/lib/tx-helper') describe('txHelper', function () { it('always shows the oldest tx first', function () { diff --git a/test/unit/tx-state-history-helper-test.js b/test/unit/app/controllers/transactions/tx-state-history-helper-test.js index 5ad014dbb..f4c3a6be1 100644 --- a/test/unit/tx-state-history-helper-test.js +++ b/test/unit/app/controllers/transactions/tx-state-history-helper-test.js @@ -1,6 +1,6 @@ const assert = require('assert') -const txStateHistoryHelper = require('../../app/scripts/controllers/transactions/lib/tx-state-history-helper') -const testVault = require('../data/v17-long-history.json') +const txStateHistoryHelper = require('../../../../../app/scripts/controllers/transactions/lib/tx-state-history-helper') +const testVault = require('../../../../data/v17-long-history.json') describe ('Transaction state history helper', function () { diff --git a/test/unit/tx-state-manager-test.js b/test/unit/app/controllers/transactions/tx-state-manager-test.js index 179542f90..20bc08b94 100644 --- a/test/unit/tx-state-manager-test.js +++ b/test/unit/app/controllers/transactions/tx-state-manager-test.js @@ -1,8 +1,8 @@ const assert = require('assert') const clone = require('clone') const ObservableStore = require('obs-store') -const TxStateManager = require('../../app/scripts/controllers/transactions/tx-state-manager') -const txStateHistoryHelper = require('../../app/scripts/controllers/transactions/lib/tx-state-history-helper') +const TxStateManager = require('../../../../../app/scripts/controllers/transactions/tx-state-manager') +const txStateHistoryHelper = require('../../../../../app/scripts/controllers/transactions/lib/tx-state-history-helper') const noop = () => true describe('TransactionStateManager', function () { diff --git a/test/unit/tx-utils-test.js b/test/unit/app/controllers/transactions/tx-utils-test.js index be16225ba..115127f85 100644 --- a/test/unit/tx-utils-test.js +++ b/test/unit/app/controllers/transactions/tx-utils-test.js @@ -1,5 +1,5 @@ const assert = require('assert') -const txUtils = require('../../app/scripts/controllers/transactions/lib/util') +const txUtils = require('../../../../../app/scripts/controllers/transactions/lib/util') describe('txUtils', function () { diff --git a/test/unit/edge-encryptor-test.js b/test/unit/app/edge-encryptor-test.js index d3f014d74..cc9777389 100644 --- a/test/unit/edge-encryptor-test.js +++ b/test/unit/app/edge-encryptor-test.js @@ -1,6 +1,6 @@ const assert = require('assert') -const EdgeEncryptor = require('../../app/scripts/edge-encryptor') +const EdgeEncryptor = require('../../../app/scripts/edge-encryptor') var password = 'passw0rd1' var data = 'some random data' diff --git a/test/unit/message-manager-test.js b/test/unit/app/message-manager-test.js index 5e7039841..36ef6c29f 100644 --- a/test/unit/message-manager-test.js +++ b/test/unit/app/message-manager-test.js @@ -1,5 +1,5 @@ const assert = require('assert') -const MessageManager = require('../../app/scripts/lib/message-manager') +const MessageManager = require('../../../app/scripts/lib/message-manager') describe('Message Manager', function () { let messageManager diff --git a/test/unit/nodeify-test.js b/test/unit/app/nodeify-test.js index c7b127889..901603c8b 100644 --- a/test/unit/nodeify-test.js +++ b/test/unit/app/nodeify-test.js @@ -1,5 +1,5 @@ const assert = require('assert') -const nodeify = require('../../app/scripts/lib/nodeify') +const nodeify = require('../../../app/scripts/lib/nodeify') describe('nodeify', function () { var obj = { diff --git a/test/unit/pending-balance-test.js b/test/unit/app/pending-balance-test.js index dc4c1c3e4..1418e4a4e 100644 --- a/test/unit/pending-balance-test.js +++ b/test/unit/app/pending-balance-test.js @@ -1,6 +1,6 @@ const assert = require('assert') -const PendingBalanceCalculator = require('../../app/scripts/lib/pending-balance-calculator') -const MockTxGen = require('../lib/mock-tx-gen') +const PendingBalanceCalculator = require('../../../app/scripts/lib/pending-balance-calculator') +const MockTxGen = require('../../lib/mock-tx-gen') const BN = require('ethereumjs-util').BN let providerResultStub = {} diff --git a/test/unit/personal-message-manager-test.js b/test/unit/app/personal-message-manager-test.js index ec2f9a4d1..b07167bff 100644 --- a/test/unit/personal-message-manager-test.js +++ b/test/unit/app/personal-message-manager-test.js @@ -1,6 +1,6 @@ const assert = require('assert') -const PersonalMessageManager = require('../../app/scripts/lib/personal-message-manager') +const PersonalMessageManager = require('../../../app/scripts/lib/personal-message-manager') describe('Personal Message Manager', function () { let messageManager diff --git a/test/unit/seed-phrase-verifier-test.js b/test/unit/app/seed-phrase-verifier-test.js index 4e314806b..b0da534da 100644 --- a/test/unit/seed-phrase-verifier-test.js +++ b/test/unit/app/seed-phrase-verifier-test.js @@ -1,9 +1,9 @@ const assert = require('assert') const clone = require('clone') const KeyringController = require('eth-keyring-controller') -const firstTimeState = require('../../app/scripts/first-time-state') -const seedPhraseVerifier = require('../../app/scripts/lib/seed-phrase-verifier') -const mockEncryptor = require('../lib/mock-encryptor') +const firstTimeState = require('../../../app/scripts/first-time-state') +const seedPhraseVerifier = require('../../../app/scripts/lib/seed-phrase-verifier') +const mockEncryptor = require('../../lib/mock-encryptor') describe('SeedPhraseVerifier', function () { diff --git a/test/unit/util-test.js b/test/unit/app/util-test.js index 6da185b2c..670bc4d22 100644 --- a/test/unit/util-test.js +++ b/test/unit/app/util-test.js @@ -1,5 +1,5 @@ const assert = require('assert') -const { sufficientBalance } = require('../../app/scripts/lib/util') +const { sufficientBalance } = require('../../../app/scripts/lib/util') describe('SufficientBalance', function () { diff --git a/test/unit/metamask-controller-test.js b/test/unit/metamask-controller-test.js deleted file mode 100644 index 18c3f9ab9..000000000 --- a/test/unit/metamask-controller-test.js +++ /dev/null @@ -1,120 +0,0 @@ -const assert = require('assert') -const sinon = require('sinon') -const clone = require('clone') -const nock = require('nock') -const MetaMaskController = require('../../app/scripts/metamask-controller') -const blacklistJSON = require('../stub/blacklist') -const firstTimeState = require('../../app/scripts/first-time-state') - -const DEFAULT_LABEL = 'Account 1' -const TEST_SEED = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium' -const TEST_ADDRESS = '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc' -const TEST_SEED_ALT = 'setup olympic issue mobile velvet surge alcohol burger horse view reopen gentle' -const TEST_ADDRESS_ALT = '0xc42edfcc21ed14dda456aa0756c153f7985d8813' - -describe('MetaMaskController', function () { - let metamaskController - const sandbox = sinon.sandbox.create() - const noop = () => { } - - beforeEach(function () { - - nock('https://api.infura.io') - .persist() - .get('/v2/blacklist') - .reply(200, blacklistJSON) - - nock('https://api.infura.io') - .persist() - .get(/.*/) - .reply(200) - - metamaskController = new MetaMaskController({ - showUnapprovedTx: noop, - encryptor: { - encrypt: function (password, object) { - this.object = object - return Promise.resolve() - }, - decrypt: function () { - return Promise.resolve(this.object) - }, - }, - initState: clone(firstTimeState), - }) - sandbox.spy(metamaskController.keyringController, 'createNewVaultAndKeychain') - sandbox.spy(metamaskController.keyringController, 'createNewVaultAndRestore') - }) - - afterEach(function () { - nock.cleanAll() - sandbox.restore() - }) - - describe('#getGasPrice', function () { - it('gives the 50th percentile lowest accepted gas price from recentBlocksController', async function () { - const realRecentBlocksController = metamaskController.recentBlocksController - metamaskController.recentBlocksController = { - store: { - getState: () => { - return { - recentBlocks: [ - { gasPrices: [ '0x3b9aca00', '0x174876e800'] }, - { gasPrices: [ '0x3b9aca00', '0x174876e800'] }, - { gasPrices: [ '0x174876e800', '0x174876e800' ]}, - { gasPrices: [ '0x174876e800', '0x174876e800' ]}, - ], - } - }, - }, - } - - const gasPrice = metamaskController.getGasPrice() - assert.equal(gasPrice, '0x3b9aca00', 'accurately estimates 50th percentile accepted gas price') - - metamaskController.recentBlocksController = realRecentBlocksController - }) - }) - - describe('#createNewVaultAndKeychain', function () { - it('can only create new vault on keyringController once', async function () { - const selectStub = sandbox.stub(metamaskController, 'selectFirstIdentity') - - const password = 'a-fake-password' - - await metamaskController.createNewVaultAndKeychain(password) - await metamaskController.createNewVaultAndKeychain(password) - - assert(metamaskController.keyringController.createNewVaultAndKeychain.calledOnce) - - selectStub.reset() - }) - }) - - describe('#createNewVaultAndRestore', function () { - it('should be able to call newVaultAndRestore despite a mistake.', async function () { - const password = 'what-what-what' - await metamaskController.createNewVaultAndRestore(password, TEST_SEED.slice(0, -1)).catch((e) => null) - await metamaskController.createNewVaultAndRestore(password, TEST_SEED) - - assert(metamaskController.keyringController.createNewVaultAndRestore.calledTwice) - }) - - it('should clear previous identities after vault restoration', async () => { - await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED) - assert.deepEqual(metamaskController.getState().identities, { - [TEST_ADDRESS]: { address: TEST_ADDRESS, name: DEFAULT_LABEL }, - }) - - await metamaskController.keyringController.saveAccountLabel(TEST_ADDRESS, 'Account Foo') - assert.deepEqual(metamaskController.getState().identities, { - [TEST_ADDRESS]: { address: TEST_ADDRESS, name: 'Account Foo' }, - }) - - await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT) - assert.deepEqual(metamaskController.getState().identities, { - [TEST_ADDRESS_ALT]: { address: TEST_ADDRESS_ALT, name: DEFAULT_LABEL }, - }) - }) - }) -}) diff --git a/test/unit/migrations/026-test.js b/test/unit/migrations/026-test.js new file mode 100644 index 000000000..b3f5470cf --- /dev/null +++ b/test/unit/migrations/026-test.js @@ -0,0 +1,41 @@ +const assert = require('assert') +const migration26 = require('../../../app/scripts/migrations/026') +const oldStorage = { + 'meta': {'version': 25}, + 'data': { + 'PreferencesController': {}, + 'KeyringController': { + 'walletNicknames': { + '0x1e77e2': 'Test Account 1', + '0x7e57e2': 'Test Account 2', + }, + }, + }, +} + +describe('migration #26', () => { + it('should move the identities from KeyringController', (done) => { + migration26.migrate(oldStorage) + .then((newStorage) => { + const identities = newStorage.data.PreferencesController.identities + assert.deepEqual(identities, { + '0x1e77e2': {name: 'Test Account 1', address: '0x1e77e2'}, + '0x7e57e2': {name: 'Test Account 2', address: '0x7e57e2'}, + }) + assert.strictEqual(newStorage.data.KeyringController.walletNicknames, undefined) + done() + }) + .catch(done) + }) + + it('should successfully migrate first time state', (done) => { + migration26.migrate({ + meta: {}, + data: require('../../../app/scripts/first-time-state'), + }) + .then((migratedData) => { + assert.equal(migratedData.meta.version, migration26.version) + done() + }).catch(done) + }) +}) diff --git a/test/unit/migrations-test.js b/test/unit/migrations/migrations-test.js index 5bad25a45..50afd9c2e 100644 --- a/test/unit/migrations-test.js +++ b/test/unit/migrations/migrations-test.js @@ -1,22 +1,22 @@ const assert = require('assert') const path = require('path') -const wallet1 = require(path.join('..', 'lib', 'migrations', '001.json')) -const vault4 = require(path.join('..', 'lib', 'migrations', '004.json')) +const wallet1 = require(path.join('..', '..', 'lib', 'migrations', '001.json')) +const vault4 = require(path.join('..', '..', 'lib', 'migrations', '004.json')) let vault5, vault6, vault7, vault8, vault9 // vault10, vault11 -const migration2 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '002')) -const migration3 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '003')) -const migration4 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '004')) -const migration5 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '005')) -const migration6 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '006')) -const migration7 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '007')) -const migration8 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '008')) -const migration9 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '009')) -const migration10 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '010')) -const migration11 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '011')) -const migration12 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '012')) -const migration13 = require(path.join('..', '..', 'app', 'scripts', 'migrations', '013')) +const migration2 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '002')) +const migration3 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '003')) +const migration4 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '004')) +const migration5 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '005')) +const migration6 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '006')) +const migration7 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '007')) +const migration8 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '008')) +const migration9 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '009')) +const migration10 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '010')) +const migration11 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '011')) +const migration12 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '012')) +const migration13 = require(path.join('..', '..', '..', 'app', 'scripts', 'migrations', '013')) const oldTestRpc = 'https://rawtestrpc.metamask.io/' diff --git a/test/unit/migrator-test.js b/test/unit/migrations/migrator-test.js index 4404e1dc4..a9374dff1 100644 --- a/test/unit/migrator-test.js +++ b/test/unit/migrations/migrator-test.js @@ -1,7 +1,7 @@ const assert = require('assert') const clone = require('clone') -const Migrator = require('../../app/scripts/lib/migrator/') -const liveMigrations = require('../../app/scripts/migrations/') +const Migrator = require('../../../app/scripts/lib/migrator/') +const liveMigrations = require('../../../app/scripts/migrations/') const stubMigrations = [ { version: 1, @@ -33,7 +33,7 @@ const versionedData = {meta: {version: 0}, data: {hello: 'world'}} const firstTimeState = { meta: { version: 0 }, - data: require('../../app/scripts/first-time-state'), + data: require('../../../app/scripts/first-time-state'), } describe('Migrator', () => { diff --git a/test/unit/nameForAccount_test.js b/test/unit/nameForAccount_test.js index 32af49e9d..9bb02c6bc 100644 --- a/test/unit/nameForAccount_test.js +++ b/test/unit/nameForAccount_test.js @@ -6,7 +6,7 @@ var contractNamer = require(path.join(__dirname, '..', '..', 'old-ui', 'lib', 'c describe('contractNamer', function () { beforeEach(function () { - this.sinon = sinon.sandbox.create() + this.sinon = sinon.createSandbox() }) afterEach(function () { diff --git a/test/unit/preferences-controller-test.js b/test/unit/preferences-controller-test.js deleted file mode 100644 index 9fb5e4251..000000000 --- a/test/unit/preferences-controller-test.js +++ /dev/null @@ -1,48 +0,0 @@ -const assert = require('assert') -const PreferencesController = require('../../app/scripts/controllers/preferences') - -describe('preferences controller', function () { - let preferencesController - - before(() => { - preferencesController = new PreferencesController() - }) - - describe('addToken', function () { - it('should add that token to its state', async function () { - const address = '0xabcdef1234567' - const symbol = 'ABBR' - const decimals = 5 - - await preferencesController.addToken(address, symbol, decimals) - - const tokens = preferencesController.getTokens() - assert.equal(tokens.length, 1, 'one token added') - - const added = tokens[0] - assert.equal(added.address, address, 'set address correctly') - assert.equal(added.symbol, symbol, 'set symbol correctly') - assert.equal(added.decimals, decimals, 'set decimals correctly') - }) - - it('should allow updating a token value', async function () { - const address = '0xabcdef1234567' - const symbol = 'ABBR' - const decimals = 5 - - await preferencesController.addToken(address, symbol, decimals) - - const newDecimals = 6 - await preferencesController.addToken(address, symbol, newDecimals) - - const tokens = preferencesController.getTokens() - assert.equal(tokens.length, 1, 'one token added') - - const added = tokens[0] - assert.equal(added.address, address, 'set address correctly') - assert.equal(added.symbol, symbol, 'set symbol correctly') - assert.equal(added.decimals, newDecimals, 'updated decimals correctly') - }) - }) -}) - diff --git a/test/unit/reducers/unlock_vault_test.js b/test/unit/reducers/unlock_vault_test.js index 2b7d70b2c..d66e8edbb 100644 --- a/test/unit/reducers/unlock_vault_test.js +++ b/test/unit/reducers/unlock_vault_test.js @@ -10,7 +10,7 @@ var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'redu describe('#unlockMetamask(selectedAccount)', function () { beforeEach(function () { // sinon allows stubbing methods that are easily verified - this.sinon = sinon.sandbox.create() + this.sinon = sinon.createSandbox() }) afterEach(function () { diff --git a/test/unit/util_test.js b/test/unit/util_test.js index 59048975a..39473854f 100644 --- a/test/unit/util_test.js +++ b/test/unit/util_test.js @@ -10,7 +10,7 @@ describe('util', function () { for (var i = 0; i < 18; i++) { ethInWei += '0' } beforeEach(function () { - this.sinon = sinon.sandbox.create() + this.sinon = sinon.createSandbox() }) afterEach(function () { |