aboutsummaryrefslogtreecommitdiffstats
path: root/test
diff options
context:
space:
mode:
authorDan <danjm.com@gmail.com>2018-05-14 21:30:50 +0800
committerDan <danjm.com@gmail.com>2018-05-14 22:14:50 +0800
commit6bc8cc819a16118acc010d0efdec90afbda14590 (patch)
tree2d2c35604af2e6a44c5f3ecb5c901a52980710d8 /test
parent0739618a61cfc383498e466f4fdeb5a25324598f (diff)
downloadtangerine-wallet-browser-6bc8cc819a16118acc010d0efdec90afbda14590.tar
tangerine-wallet-browser-6bc8cc819a16118acc010d0efdec90afbda14590.tar.gz
tangerine-wallet-browser-6bc8cc819a16118acc010d0efdec90afbda14590.tar.bz2
tangerine-wallet-browser-6bc8cc819a16118acc010d0efdec90afbda14590.tar.lz
tangerine-wallet-browser-6bc8cc819a16118acc010d0efdec90afbda14590.tar.xz
tangerine-wallet-browser-6bc8cc819a16118acc010d0efdec90afbda14590.tar.zst
tangerine-wallet-browser-6bc8cc819a16118acc010d0efdec90afbda14590.zip
Merge branch 'develop' into i3725-refactor-send-component-
Diffstat (limited to 'test')
-rw-r--r--test/e2e/chrome/metamask.spec.js314
-rw-r--r--test/e2e/firefox/metamask.spec.js322
-rw-r--r--test/e2e/func.js8
-rw-r--r--test/e2e/metamask.spec.js145
-rw-r--r--test/integration/lib/mascara-first-time.js19
-rw-r--r--test/integration/lib/send-new-ui.js59
-rw-r--r--test/integration/lib/tx-list-items.js4
-rw-r--r--test/screens/new-ui.js3
-rw-r--r--test/stub/provider.js24
-rw-r--r--test/unit/metamask-controller-test.js33
-rw-r--r--test/unit/nonce-tracker-test.js2
-rw-r--r--test/unit/pending-tx-test.js2
-rw-r--r--test/unit/tx-controller-test.js151
-rw-r--r--test/unit/tx-gas-util-test.js83
-rw-r--r--test/unit/tx-state-history-helper-test.js2
-rw-r--r--test/unit/tx-state-history-helper.js2
-rw-r--r--test/unit/tx-state-manager-test.js4
-rw-r--r--test/unit/tx-utils-test.js145
18 files changed, 945 insertions, 377 deletions
diff --git a/test/e2e/chrome/metamask.spec.js b/test/e2e/chrome/metamask.spec.js
new file mode 100644
index 000000000..d72ebe1a9
--- /dev/null
+++ b/test/e2e/chrome/metamask.spec.js
@@ -0,0 +1,314 @@
+const fs = require('fs')
+const mkdirp = require('mkdirp')
+const path = require('path')
+const assert = require('assert')
+const pify = require('pify')
+const webdriver = require('selenium-webdriver')
+const until = require('selenium-webdriver/lib/until')
+const By = webdriver.By
+const { delay, buildChromeWebDriver } = require('../func')
+
+describe('Metamask popup page', function () {
+ let driver, accountAddress, tokenAddress, extensionId
+
+ this.timeout(0)
+
+ before(async function () {
+ const extPath = path.resolve('dist/chrome')
+ driver = buildChromeWebDriver(extPath)
+ await driver.get('chrome://extensions')
+ await delay(500)
+ })
+
+ afterEach(async function () {
+ if (this.currentTest.state === 'failed') {
+ await verboseReportOnFailure(this.currentTest)
+ }
+ })
+
+ after(async function () {
+ await driver.quit()
+ })
+
+ describe('Setup', function () {
+
+ it('switches to Chrome extensions list', async function () {
+ const tabs = await driver.getAllWindowHandles()
+ await driver.switchTo().window(tabs[0])
+ await delay(300)
+ })
+
+ it(`selects MetaMask's extension id and opens it in the current tab`, async function () {
+ extensionId = await getExtensionId()
+ await driver.get(`chrome-extension://${extensionId}/popup.html`)
+ await delay(500)
+ })
+
+ it('sets provider type to localhost', async function () {
+ await driver.wait(until.elementLocated(By.css('#app-content')), 300)
+ await setProviderType('localhost')
+ })
+ })
+
+ describe('Account Creation', () => {
+
+ it('matches MetaMask title', async () => {
+ const title = await driver.getTitle()
+ assert.equal(title, 'MetaMask', 'title matches MetaMask')
+ })
+
+ it('shows privacy notice', async () => {
+ await driver.wait(async () => {
+ const privacyHeader = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div.flex-column.flex-center.flex-grow > h3')).getText()
+ assert.equal(privacyHeader, 'PRIVACY NOTICE', 'shows privacy notice')
+ return privacyHeader === 'PRIVACY NOTICE'
+ }, 300)
+ await driver.findElement(By.css('button')).click()
+ })
+
+ it('show terms of use', async () => {
+ await driver.wait(async () => {
+ const terms = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div.flex-column.flex-center.flex-grow > h3')).getText()
+ assert.equal(terms, 'TERMS OF USE', 'shows terms of use')
+ return terms === 'TERMS OF USE'
+ })
+ })
+
+ it('checks if the TOU button is disabled', async () => {
+ const button = await driver.findElement(By.css('button')).isEnabled()
+ assert.equal(button, false, 'disabled continue button')
+ const element = await driver.findElement(By.linkText('Attributions'))
+ await driver.executeScript('arguments[0].scrollIntoView(true)', element)
+ await delay(300)
+ })
+
+ it('allows the button to be clicked when scrolled to the bottom of TOU', async () => {
+ const button = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div.flex-column.flex-center.flex-grow > button'))
+ const buttonEnabled = await button.isEnabled()
+ assert.equal(buttonEnabled, true, 'enabled continue button')
+ await button.click()
+ })
+
+ it('accepts password with length of eight', async () => {
+ const passwordBox = await driver.findElement(By.id('password-box'))
+ const passwordBoxConfirm = await driver.findElement(By.id('password-box-confirm'))
+ const button = await driver.findElements(By.css('button'))
+
+ await passwordBox.sendKeys('123456789')
+ await passwordBoxConfirm.sendKeys('123456789')
+ await button[0].click()
+ await delay(500)
+ })
+
+ it('shows value was created and seed phrase', async () => {
+ await delay(300)
+ const seedPhrase = await driver.findElement(By.css('.twelve-word-phrase')).getText()
+ assert.equal(seedPhrase.split(' ').length, 12)
+ const continueAfterSeedPhrase = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > button:nth-child(4)'))
+ assert.equal(await continueAfterSeedPhrase.getText(), `I'VE COPIED IT SOMEWHERE SAFE`)
+ await continueAfterSeedPhrase.click()
+ await delay(300)
+ })
+
+ it('shows account address', async function () {
+ accountAddress = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > div > div:nth-child(1) > flex-column > div.flex-row > div')).getText()
+ })
+
+ it('logs out of the vault', async () => {
+ await driver.findElement(By.css('.sandwich-expando')).click()
+ await delay(500)
+ const logoutButton = await driver.findElement(By.css('#app-content > div > div:nth-child(3) > span > div > li:nth-child(3)'))
+ assert.equal(await logoutButton.getText(), 'Log Out')
+ await logoutButton.click()
+ })
+
+ it('accepts account password after lock', async () => {
+ await delay(500)
+ await driver.findElement(By.id('password-box')).sendKeys('123456789')
+ await driver.findElement(By.css('button')).click()
+ await delay(500)
+ })
+
+ it('shows QR code option', async () => {
+ await delay(300)
+ await driver.findElement(By.css('.fa-ellipsis-h')).click()
+ await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div > div:nth-child(1) > flex-column > div.name-label > div > span > i > div > div > li:nth-child(3)')).click()
+ await delay(300)
+ })
+
+ it('checks QR code address is the same as account details address', async () => {
+ const QRaccountAddress = await driver.findElement(By.css('.ellip-address')).getText()
+ assert.equal(accountAddress.toLowerCase(), QRaccountAddress)
+ await driver.findElement(By.css('.fa-arrow-left')).click()
+ await delay(500)
+ })
+ })
+
+ describe('Import Ganache seed phrase', function () {
+ it('logs out', async function () {
+ await driver.findElement(By.css('.sandwich-expando')).click()
+ await delay(200)
+ const logOut = await driver.findElement(By.css('#app-content > div > div:nth-child(3) > span > div > li:nth-child(3)'))
+ assert.equal(await logOut.getText(), 'Log Out')
+ await logOut.click()
+ await delay(300)
+ })
+
+ it('restores from seed phrase', async function () {
+ const restoreSeedLink = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > div.flex-row.flex-center.flex-grow > p'))
+ assert.equal(await restoreSeedLink.getText(), 'Restore from seed phrase')
+ await restoreSeedLink.click()
+ await delay(100)
+ })
+
+ it('adds seed phrase', async function () {
+ const testSeedPhrase = 'phrase upgrade clock rough situate wedding elder clever doctor stamp excess tent'
+ const seedTextArea = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > textarea'))
+ await seedTextArea.sendKeys(testSeedPhrase)
+
+ await driver.findElement(By.id('password-box')).sendKeys('123456789')
+ await driver.findElement(By.id('password-box-confirm')).sendKeys('123456789')
+ await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > div > button:nth-child(2)')).click()
+ await delay(500)
+ })
+
+ it('balance renders', async function () {
+ await delay(200)
+ const balance = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div > div.flex-row > div.ether-balance.ether-balance-amount > div > div > div:nth-child(1) > div:nth-child(1)'))
+ assert.equal(await balance.getText(), '100.000')
+ await delay(200)
+ })
+
+ it('sends transaction', async function () {
+ const sendButton = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div > div.flex-row > button:nth-child(4)'))
+ assert.equal(await sendButton.getText(), 'SEND')
+ await sendButton.click()
+ await delay(200)
+ })
+
+ it('adds recipient address and amount', async function () {
+ const sendTranscationScreen = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > h3:nth-child(2)')).getText()
+ assert.equal(sendTranscationScreen, 'SEND TRANSACTION')
+ const inputAddress = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section:nth-child(3) > div > input'))
+ const inputAmmount = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section:nth-child(4) > input'))
+ await inputAddress.sendKeys('0x2f318C334780961FB129D2a6c30D0763d9a5C970')
+ await inputAmmount.sendKeys('10')
+ await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section:nth-child(4) > button')).click()
+ await delay(300)
+ })
+
+ it('confirms transaction', async function () {
+ await delay(300)
+ await driver.findElement(By.css('#pending-tx-form > div.flex-row.flex-space-around.conf-buttons > input')).click()
+ await delay(500)
+ })
+
+ it('finds the transaction in the transactions list', async function () {
+ const tranasactionAmount = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > section > section > div > div > div > div.ether-balance.ether-balance-amount > div > div > div > div:nth-child(1)'))
+ assert.equal(await tranasactionAmount.getText(), '10.0')
+ })
+ })
+
+ describe('Token Factory', function () {
+
+ it('navigates to token factory', async function () {
+ await driver.get('http://tokenfactory.surge.sh/')
+ })
+
+ it('navigates to create token contract link', async function () {
+ const createToken = await driver.findElement(By.css('#bs-example-navbar-collapse-1 > ul > li:nth-child(3) > a'))
+ await createToken.click()
+ })
+
+ it('adds input for token', async function () {
+ const totalSupply = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > div:nth-child(5) > input'))
+ const tokenName = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > div:nth-child(6) > input'))
+ const tokenDecimal = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > div:nth-child(7) > input'))
+ const tokenSymbol = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > div:nth-child(8) > input'))
+ const createToken = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > button'))
+
+ await totalSupply.sendKeys('100')
+ await tokenName.sendKeys('Test')
+ await tokenDecimal.sendKeys('0')
+ await tokenSymbol.sendKeys('TST')
+ await createToken.click()
+ await delay(1000)
+ })
+
+ it('confirms transaction in MetaMask popup', async function () {
+ const windowHandles = await driver.getAllWindowHandles()
+ await driver.switchTo().window(windowHandles[2])
+ const metamaskSubmit = await driver.findElement(By.css('#pending-tx-form > div.flex-row.flex-space-around.conf-buttons > input'))
+ await metamaskSubmit.click()
+ await delay(1000)
+ })
+
+ it('switches back to Token Factory to grab the token contract address', async function () {
+ const windowHandles = await driver.getAllWindowHandles()
+ await driver.switchTo().window(windowHandles[0])
+ const tokenContactAddress = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > span:nth-child(3)'))
+ tokenAddress = await tokenContactAddress.getText()
+ await delay(500)
+ })
+
+ it('navigates back to MetaMask popup in the tab', async function () {
+ await driver.get(`chrome-extension://${extensionId}/popup.html`)
+ await delay(700)
+ })
+ })
+
+ describe('Add Token', function () {
+ it('switches to the add token screen', async function () {
+ const tokensTab = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section > div > div.inactiveForm.pointer'))
+ assert.equal(await tokensTab.getText(), 'TOKENS')
+ await tokensTab.click()
+ await delay(300)
+ })
+
+ it('navigates to the add token screen', async function () {
+ const addTokenButton = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section > div.full-flex-height > div > button'))
+ assert.equal(await addTokenButton.getText(), 'ADD TOKEN')
+ await addTokenButton.click()
+ })
+
+ it('checks add token screen rendered', async function () {
+ const addTokenScreen = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div.section-title.flex-row.flex-center > h2'))
+ assert.equal(await addTokenScreen.getText(), 'ADD TOKEN')
+ })
+
+ it('adds token parameters', async function () {
+ const tokenContractAddress = await driver.findElement(By.css('#token-address'))
+ await tokenContractAddress.sendKeys(tokenAddress)
+ await delay(300)
+ await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div.flex-column.flex-justify-center.flex-grow.select-none > div > button')).click()
+ await delay(100)
+ })
+
+ it('checks the token balance', async function () {
+ const tokenBalance = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > section > div.full-flex-height > ol > li:nth-child(2) > h3'))
+ assert.equal(await tokenBalance.getText(), '100 TST')
+ })
+ })
+
+ async function getExtensionId () {
+ const extension = await driver.executeScript('return document.querySelector("extensions-manager").shadowRoot.querySelector("extensions-view-manager extensions-item-list").shadowRoot.querySelector("#container > div.items-container > extensions-item:nth-child(2)").getAttribute("id")')
+ return extension
+ }
+
+ async function setProviderType (type) {
+ await driver.executeScript('window.metamask.setProviderType(arguments[0])', type)
+ }
+
+ async function verboseReportOnFailure (test) {
+ const artifactDir = `./test-artifacts/chrome/${test.title}`
+ const filepathBase = `${artifactDir}/test-failure`
+ await pify(mkdirp)(artifactDir)
+ // capture screenshot
+ const screenshot = await driver.takeScreenshot()
+ await pify(fs.writeFile)(`${filepathBase}-screenshot.png`, screenshot, { encoding: 'base64' })
+ // capture dom source
+ const htmlSource = await driver.getPageSource()
+ await pify(fs.writeFile)(`${filepathBase}-dom.html`, htmlSource)
+ }
+
+})
diff --git a/test/e2e/firefox/metamask.spec.js b/test/e2e/firefox/metamask.spec.js
new file mode 100644
index 000000000..20b8a5092
--- /dev/null
+++ b/test/e2e/firefox/metamask.spec.js
@@ -0,0 +1,322 @@
+const fs = require('fs')
+const mkdirp = require('mkdirp')
+const path = require('path')
+const assert = require('assert')
+const pify = require('pify')
+const webdriver = require('selenium-webdriver')
+const Command = require('selenium-webdriver/lib/command').Command
+const By = webdriver.By
+const { delay, buildFirefoxWebdriver } = require('../func')
+
+describe('', function () {
+ let driver, accountAddress, tokenAddress, extensionId
+
+ this.timeout(0)
+
+ before(async function () {
+ const extPath = path.resolve('dist/firefox')
+ driver = buildFirefoxWebdriver()
+ installWebExt(driver, extPath)
+ await delay(700)
+ })
+
+ afterEach(async function () {
+ if (this.currentTest.state === 'failed') {
+ await verboseReportOnFailure(this.currentTest)
+ }
+ })
+
+ after(async function () {
+ await driver.quit()
+ })
+
+ describe('Setup', function () {
+
+ it('switches to Firefox addon list', async function () {
+ await driver.get('about:debugging#addons')
+ await delay(1000)
+ })
+
+ it(`selects MetaMask's extension id and opens it in the current tab`, async function () {
+ const tabs = await driver.getAllWindowHandles()
+ await driver.switchTo().window(tabs[0])
+ extensionId = await driver.findElement(By.css('dd.addon-target-info-content:nth-child(6) > span:nth-child(1)')).getText()
+ await driver.get(`moz-extension://${extensionId}/popup.html`)
+ await delay(500)
+ })
+
+ it('sets provider type to localhost', async function () {
+ await setProviderType('localhost')
+ await delay(300)
+ })
+ })
+
+ describe('Account Creation', () => {
+
+ it('matches MetaMask title', async () => {
+ const title = await driver.getTitle()
+ assert.equal(title, 'MetaMask', 'title matches MetaMask')
+ })
+
+ it('shows privacy notice', async () => {
+ const privacy = await driver.findElement(By.css('.terms-header')).getText()
+ assert.equal(privacy, 'PRIVACY NOTICE', 'shows privacy notice')
+ await driver.findElement(By.css('button')).click()
+ await delay(300)
+ })
+
+ it('show terms of use', async () => {
+ await delay(300)
+ const terms = await driver.findElement(By.css('.terms-header')).getText()
+ assert.equal(terms, 'TERMS OF USE', 'shows terms of use')
+ await delay(300)
+ })
+
+ it('checks if the TOU button is disabled', async () => {
+ const button = await driver.findElement(By.css('button')).isEnabled()
+ assert.equal(button, false, 'disabled continue button')
+ const element = await driver.findElement(By.linkText('Attributions'))
+ await driver.executeScript('arguments[0].scrollIntoView(true)', element)
+ await delay(300)
+ })
+
+ it('allows the button to be clicked when scrolled to the bottom of TOU', async () => {
+ const button = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div.flex-column.flex-center.flex-grow > button'))
+ await delay(300)
+ const buttonEnabled = await button.isEnabled()
+ assert.equal(buttonEnabled, true, 'enabled continue button')
+ await delay(200)
+ await button.click()
+ })
+
+ it('accepts password with length of eight', async () => {
+ const passwordBox = await driver.findElement(By.id('password-box'))
+ const passwordBoxConfirm = await driver.findElement(By.id('password-box-confirm'))
+ const button = await driver.findElements(By.css('button'))
+
+ await passwordBox.sendKeys('123456789')
+ await passwordBoxConfirm.sendKeys('123456789')
+ await button[0].click()
+ await delay(500)
+ })
+
+ it('shows value was created and seed phrase', async () => {
+ await delay(300)
+ const seedPhrase = await driver.findElement(By.css('.twelve-word-phrase')).getText()
+ assert.equal(seedPhrase.split(' ').length, 12)
+ const continueAfterSeedPhrase = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > button:nth-child(4)'))
+ assert.equal(await continueAfterSeedPhrase.getText(), `I'VE COPIED IT SOMEWHERE SAFE`)
+ await continueAfterSeedPhrase.click()
+ await delay(300)
+ })
+
+ it('shows account address', async function () {
+ accountAddress = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > div > div:nth-child(1) > flex-column > div.flex-row > div')).getText()
+ })
+
+ it('logs out of the vault', async () => {
+ await driver.findElement(By.css('.sandwich-expando')).click()
+ await delay(500)
+ const logoutButton = await driver.findElement(By.css('#app-content > div > div:nth-child(3) > span > div > li:nth-child(3)'))
+ assert.equal(await logoutButton.getText(), 'Log Out')
+ await logoutButton.click()
+ })
+
+ it('accepts account password after lock', async () => {
+ await delay(500)
+ await driver.findElement(By.id('password-box')).sendKeys('123456789')
+ await driver.findElement(By.css('button')).click()
+ await delay(500)
+ })
+
+ it('shows QR code option', async () => {
+ await delay(300)
+ await driver.findElement(By.css('.fa-ellipsis-h')).click()
+ await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div > div:nth-child(1) > flex-column > div.name-label > div > span > i > div > div > li:nth-child(3)')).click()
+ await delay(300)
+ })
+
+ it('checks QR code address is the same as account details address', async () => {
+ const QRaccountAddress = await driver.findElement(By.css('.ellip-address')).getText()
+ assert.equal(accountAddress.toLowerCase(), QRaccountAddress)
+ await driver.findElement(By.css('.fa-arrow-left')).click()
+ await delay(500)
+ })
+ })
+
+ describe('Import Ganache seed phrase', function () {
+ it('logs out', async function () {
+ await driver.findElement(By.css('.sandwich-expando')).click()
+ await delay(200)
+ const logOut = await driver.findElement(By.css('#app-content > div > div:nth-child(3) > span > div > li:nth-child(3)'))
+ assert.equal(await logOut.getText(), 'Log Out')
+ await logOut.click()
+ await delay(300)
+ })
+
+ it('restores from seed phrase', async function () {
+ const restoreSeedLink = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > div.flex-row.flex-center.flex-grow > p'))
+ assert.equal(await restoreSeedLink.getText(), 'Restore from seed phrase')
+ await restoreSeedLink.click()
+ await delay(100)
+ })
+
+ it('adds seed phrase', async function () {
+ const testSeedPhrase = 'phrase upgrade clock rough situate wedding elder clever doctor stamp excess tent'
+ const seedTextArea = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > textarea'))
+ await seedTextArea.sendKeys(testSeedPhrase)
+
+ await driver.findElement(By.id('password-box')).sendKeys('123456789')
+ await driver.findElement(By.id('password-box-confirm')).sendKeys('123456789')
+ await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > div > button:nth-child(2)')).click()
+ await delay(500)
+ })
+
+ it('balance renders', async function () {
+ await delay(200)
+ const balance = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div > div.flex-row > div.ether-balance.ether-balance-amount > div > div > div:nth-child(1) > div:nth-child(1)'))
+ assert.equal(await balance.getText(), '100.000')
+ await delay(200)
+ })
+
+ it('sends transaction', async function () {
+ const sendButton = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div > div.flex-row > button:nth-child(4)'))
+ assert.equal(await sendButton.getText(), 'SEND')
+ await sendButton.click()
+ await delay(200)
+ })
+
+ it('adds recipient address and amount', async function () {
+ const sendTranscationScreen = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > h3:nth-child(2)')).getText()
+ assert.equal(sendTranscationScreen, 'SEND TRANSACTION')
+ const inputAddress = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section:nth-child(3) > div > input'))
+ const inputAmmount = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section:nth-child(4) > input'))
+ await inputAddress.sendKeys('0x2f318C334780961FB129D2a6c30D0763d9a5C970')
+ await inputAmmount.sendKeys('10')
+ await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section:nth-child(4) > button')).click()
+ await delay(300)
+ })
+
+ it('confirms transaction', async function () {
+ await delay(300)
+ await driver.findElement(By.css('#pending-tx-form > div.flex-row.flex-space-around.conf-buttons > input')).click()
+ await delay(500)
+ })
+
+ it('finds the transaction in the transactions list', async function () {
+ const tranasactionAmount = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > section > section > div > div > div > div.ether-balance.ether-balance-amount > div > div > div > div:nth-child(1)'))
+ assert.equal(await tranasactionAmount.getText(), '10.0')
+ })
+ })
+
+ describe('Token Factory', function () {
+
+ it('navigates to token factory', async function () {
+ await driver.get('http://tokenfactory.surge.sh/')
+ })
+
+ it('navigates to create token contract link', async function () {
+ const createToken = await driver.findElement(By.css('#bs-example-navbar-collapse-1 > ul > li:nth-child(3) > a'))
+ await createToken.click()
+ })
+
+ it('adds input for token', async function () {
+ const totalSupply = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > div:nth-child(5) > input'))
+ const tokenName = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > div:nth-child(6) > input'))
+ const tokenDecimal = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > div:nth-child(7) > input'))
+ const tokenSymbol = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > div:nth-child(8) > input'))
+ const createToken = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > div > button'))
+
+ await totalSupply.sendKeys('100')
+ await tokenName.sendKeys('Test')
+ await tokenDecimal.sendKeys('0')
+ await tokenSymbol.sendKeys('TST')
+ await createToken.click()
+ await delay(1000)
+ })
+
+ // There is an issue with blank confirmation window, but the button is still there and the driver is able to clicked (?.?)
+ it('confirms transaction in MetaMask popup', async function () {
+ const windowHandles = await driver.getAllWindowHandles()
+ await driver.switchTo().window(windowHandles[2])
+ const metamaskSubmit = await driver.findElement(By.css('#pending-tx-form > div.flex-row.flex-space-around.conf-buttons > input'))
+ await metamaskSubmit.click()
+ await delay(1000)
+ })
+
+ it('switches back to Token Factory to grab the token contract address', async function () {
+ const windowHandles = await driver.getAllWindowHandles()
+ await driver.switchTo().window(windowHandles[0])
+ const tokenContactAddress = await driver.findElement(By.css('#main > div > div > div > div:nth-child(2) > span:nth-child(3)'))
+ tokenAddress = await tokenContactAddress.getText()
+ await delay(500)
+ })
+
+ it('navigates back to MetaMask popup in the tab', async function () {
+ await driver.get(`moz-extension://${extensionId}/popup.html`)
+ await delay(700)
+ })
+ })
+
+ describe('Add Token', function () {
+ it('switches to the add token screen', async function () {
+ const tokensTab = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section > div > div.inactiveForm.pointer'))
+ assert.equal(await tokensTab.getText(), 'TOKENS')
+ await tokensTab.click()
+ await delay(300)
+ })
+
+ it('navigates to the add token screen', async function () {
+ const addTokenButton = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > section > div.full-flex-height > div > button'))
+ assert.equal(await addTokenButton.getText(), 'ADD TOKEN')
+ await addTokenButton.click()
+ })
+
+ it('checks add token screen rendered', async function () {
+ const addTokenScreen = await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div.section-title.flex-row.flex-center > h2'))
+ assert.equal(await addTokenScreen.getText(), 'ADD TOKEN')
+ })
+
+ it('adds token parameters', async function () {
+ const tokenContractAddress = await driver.findElement(By.css('#token-address'))
+ await tokenContractAddress.sendKeys(tokenAddress)
+ await delay(300)
+ await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div.flex-column.flex-justify-center.flex-grow.select-none > div > button')).click()
+ await delay(100)
+ })
+
+ it('checks the token balance', async function () {
+ const tokenBalance = await driver.findElement(By.css('#app-content > div > div.app-primary.from-left > div > section > div.full-flex-height > ol > li:nth-child(2) > h3'))
+ assert.equal(await tokenBalance.getText(), '100 TST')
+ })
+ })
+
+ async function setProviderType(type) {
+ await driver.executeScript('window.metamask.setProviderType(arguments[0])', type)
+ }
+
+ async function verboseReportOnFailure(test) {
+ const artifactDir = `./test-artifacts/firefox/${test.title}`
+ const filepathBase = `${artifactDir}/test-failure`
+ await pify(mkdirp)(artifactDir)
+ // capture screenshot
+ const screenshot = await driver.takeScreenshot()
+ await pify(fs.writeFile)(`${filepathBase}-screenshot.png`, screenshot, { encoding: 'base64' })
+ // capture dom source
+ const htmlSource = await driver.getPageSource()
+ await pify(fs.writeFile)(`${filepathBase}-dom.html`, htmlSource)
+ }
+
+})
+
+async function installWebExt (driver, extension) {
+ const cmd = await new Command('moz-install-web-ext')
+ .setParameter('path', path.resolve(extension))
+ .setParameter('temporary', true)
+
+ await driver.getExecutor()
+ .defineCommand(cmd.getName(), 'POST', '/session/:sessionId/moz/addon/install')
+
+ return await driver.schedule(cmd, 'installWebExt(' + extension + ')')
+}
+
diff --git a/test/e2e/func.js b/test/e2e/func.js
index 733225565..4ad0ea615 100644
--- a/test/e2e/func.js
+++ b/test/e2e/func.js
@@ -1,4 +1,5 @@
require('chromedriver')
+require('geckodriver')
const webdriver = require('selenium-webdriver')
exports.delay = function delay (time) {
@@ -6,13 +7,16 @@ exports.delay = function delay (time) {
}
-exports.buildWebDriver = function buildWebDriver (extPath) {
+exports.buildChromeWebDriver = function buildChromeWebDriver (extPath) {
return new webdriver.Builder()
.withCapabilities({
chromeOptions: {
args: [`load-extension=${extPath}`],
},
})
- .forBrowser('chrome')
.build()
}
+
+exports.buildFirefoxWebdriver = function buildFirefoxWebdriver (extPath) {
+ return new webdriver.Builder().build()
+}
diff --git a/test/e2e/metamask.spec.js b/test/e2e/metamask.spec.js
deleted file mode 100644
index e0ff2a57e..000000000
--- a/test/e2e/metamask.spec.js
+++ /dev/null
@@ -1,145 +0,0 @@
-const fs = require('fs')
-const mkdirp = require('mkdirp')
-const path = require('path')
-const assert = require('assert')
-const pify = require('pify')
-const webdriver = require('selenium-webdriver')
-const By = webdriver.By
-const { delay, buildWebDriver } = require('./func')
-
-describe('Metamask popup page', function () {
- let driver
- this.seedPhase
- this.accountAddress
- this.timeout(0)
-
- before(async function () {
- const extPath = path.resolve('dist/chrome')
- driver = buildWebDriver(extPath)
- await driver.get('chrome://extensions-frame')
- const elems = await driver.findElements(By.css('.extension-list-item-wrapper'))
- const extensionId = await elems[1].getAttribute('id')
- await driver.get(`chrome-extension://${extensionId}/popup.html`)
- await delay(500)
- })
-
- afterEach(async function () {
- if (this.currentTest.state === 'failed') {
- await verboseReportOnFailure(this.currentTest)
- }
- })
-
- after(async function () {
- await driver.quit()
- })
-
- describe('#onboarding', () => {
- it('should open Metamask.io', async function () {
- const tabs = await driver.getAllWindowHandles()
- await driver.switchTo().window(tabs[0])
- await delay(300)
- await setProviderType('localhost')
- await delay(300)
- })
-
- it('should match title', async () => {
- const title = await driver.getTitle()
- assert.equal(title, 'MetaMask', 'title matches MetaMask')
- })
-
- it('should show privacy notice', async () => {
- const privacy = await driver.findElement(By.css('.terms-header')).getText()
- assert.equal(privacy, 'PRIVACY NOTICE', 'shows privacy notice')
- driver.findElement(By.css('button')).click()
- await delay(300)
- })
-
- it('should show terms of use', async () => {
- await delay(300)
- const terms = await driver.findElement(By.css('.terms-header')).getText()
- assert.equal(terms, 'TERMS OF USE', 'shows terms of use')
- await delay(300)
- })
-
- it('should be unable to continue without scolling throught the terms of use', async () => {
- const button = await driver.findElement(By.css('button')).isEnabled()
- assert.equal(button, false, 'disabled continue button')
- const element = driver.findElement(By.linkText(
- 'Attributions'
- ))
- await driver.executeScript('arguments[0].scrollIntoView(true)', element)
- await delay(300)
- })
-
- it('should be able to continue when scrolled to the bottom of terms of use', async () => {
- const button = await driver.findElement(By.css('button'))
- const buttonEnabled = await button.isEnabled()
- await delay(500)
- assert.equal(buttonEnabled, true, 'enabled continue button')
- await button.click()
- await delay(300)
- })
-
- it('should accept password with length of eight', async () => {
- const passwordBox = await driver.findElement(By.id('password-box'))
- const passwordBoxConfirm = await driver.findElement(By.id('password-box-confirm'))
- const button = driver.findElement(By.css('button'))
-
- passwordBox.sendKeys('123456789')
- passwordBoxConfirm.sendKeys('123456789')
- await delay(500)
- await button.click()
- })
-
- it('should show value was created and seed phrase', async () => {
- await delay(700)
- this.seedPhase = await driver.findElement(By.css('.twelve-word-phrase')).getText()
- const continueAfterSeedPhrase = await driver.findElement(By.css('button'))
- await continueAfterSeedPhrase.click()
- await delay(300)
- })
-
- it('should show lock account', async () => {
- await driver.findElement(By.css('.sandwich-expando')).click()
- await delay(500)
- await driver.findElement(By.css('#app-content > div > div:nth-child(3) > span > div > li:nth-child(3)')).click()
- })
-
- it('should accept account password after lock', async () => {
- await delay(500)
- await driver.findElement(By.id('password-box')).sendKeys('123456789')
- await driver.findElement(By.css('button')).click()
- await delay(500)
- })
-
- it('should show QR code option', async () => {
- await delay(300)
- await driver.findElement(By.css('.fa-ellipsis-h')).click()
- await driver.findElement(By.css('#app-content > div > div.app-primary.from-right > div > div > div:nth-child(1) > flex-column > div.name-label > div > span > i > div > div > li:nth-child(3)')).click()
- await delay(300)
- })
-
- it('should show the account address', async () => {
- this.accountAddress = await driver.findElement(By.css('.ellip-address')).getText()
- await driver.findElement(By.css('.fa-arrow-left')).click()
- await delay(500)
- })
- })
-
- async function setProviderType(type) {
- await driver.executeScript('window.metamask.setProviderType(arguments[0])', type)
- }
-
- async function verboseReportOnFailure(test) {
- const artifactDir = `./test-artifacts/${test.title}`
- const filepathBase = `${artifactDir}/test-failure`
- await pify(mkdirp)(artifactDir)
- // capture screenshot
- const screenshot = await driver.takeScreenshot()
- await pify(fs.writeFile)(`${filepathBase}-screenshot.png`, screenshot, { encoding: 'base64' })
- // capture dom source
- const htmlSource = await driver.getPageSource()
- await pify(fs.writeFile)(`${filepathBase}-dom.html`, htmlSource)
- }
-
-})
diff --git a/test/integration/lib/mascara-first-time.js b/test/integration/lib/mascara-first-time.js
index 5e07ab0b4..d86703277 100644
--- a/test/integration/lib/mascara-first-time.js
+++ b/test/integration/lib/mascara-first-time.js
@@ -71,10 +71,23 @@ async function runFirstTimeUsageTest (assert, done) {
assert.ok(lock, 'Lock menu item found')
lock.click()
- const pwBox2 = (await findAsync(app, '#password-box'))[0]
- pwBox2.value = PASSWORD
+ await timeout(1000)
- const createButton2 = (await findAsync(app, 'button.primary'))[0]
+ const pwBox2 = (await findAsync(app, '#password'))[0]
+ pwBox2.focus()
+ await timeout(1000)
+
+ // Used to set values on TextField input component
+ const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
+ window.HTMLInputElement.prototype, 'value'
+ ).set
+
+ nativeInputValueSetter.call(pwBox2, PASSWORD)
+
+ var ev2 = new Event('input', { bubbles: true})
+ pwBox2.dispatchEvent(ev2)
+
+ const createButton2 = (await findAsync(app, 'button[type="submit"]'))[0]
createButton2.click()
const detail2 = (await findAsync(app, '.wallet-view'))[0]
diff --git a/test/integration/lib/send-new-ui.js b/test/integration/lib/send-new-ui.js
index 09a074750..3da3f4f95 100644
--- a/test/integration/lib/send-new-ui.js
+++ b/test/integration/lib/send-new-ui.js
@@ -23,6 +23,37 @@ global.ethQuery = {
global.ethereumProvider = {}
+async function customizeGas (assert, price, limit, ethFee, usdFee) {
+ const sendGasOpenCustomizeModalButton = await queryAsync($, '.sliders-icon-container')
+ sendGasOpenCustomizeModalButton[0].click()
+
+ const customizeGasModal = await queryAsync($, '.send-v2__customize-gas')
+ assert.ok(customizeGasModal[0], 'should render the customize gas modal')
+
+ const customizeGasPriceInput = (await queryAsync($, '.send-v2__gas-modal-card')).first().find('input')
+ customizeGasPriceInput.val(price)
+ reactTriggerChange(customizeGasPriceInput[0])
+ const customizeGasLimitInput = (await queryAsync($, '.send-v2__gas-modal-card')).last().find('input')
+ customizeGasLimitInput.val(limit)
+ reactTriggerChange(customizeGasLimitInput[0])
+
+ const customizeGasSaveButton = await queryAsync($, '.send-v2__customize-gas__save')
+ customizeGasSaveButton[0].click()
+ const sendGasField = await queryAsync($, '.send-v2__gas-fee-display')
+
+ assert.equal(
+ (await findAsync(sendGasField, '.currency-display__input-wrapper > input')).val(),
+ ethFee,
+ 'send gas field should show customized gas total'
+ )
+
+ assert.equal(
+ (await findAsync(sendGasField, '.currency-display__converted-value'))[0].textContent,
+ usdFee,
+ 'send gas field should show customized gas total converted to USD'
+ )
+}
+
async function runSendFlowTest(assert, done) {
console.log('*** start runSendFlowTest')
const selectState = await queryAsync($, 'select')
@@ -95,32 +126,8 @@ async function runSendFlowTest(assert, done) {
'send gas field should show estimated gas total converted to USD'
)
- const sendGasOpenCustomizeModalButton = await queryAsync($, '.sliders-icon-container')
- sendGasOpenCustomizeModalButton[0].click()
-
- const customizeGasModal = await queryAsync($, '.send-v2__customize-gas')
- assert.ok(customizeGasModal[0], 'should render the customize gas modal')
-
- const customizeGasPriceInput = (await queryAsync($, '.send-v2__gas-modal-card')).first().find('input')
- customizeGasPriceInput.val(50)
- reactTriggerChange(customizeGasPriceInput[0])
- const customizeGasLimitInput = (await queryAsync($, '.send-v2__gas-modal-card')).last().find('input')
- customizeGasLimitInput.val(60000)
- reactTriggerChange(customizeGasLimitInput[0])
-
- const customizeGasSaveButton = await queryAsync($, '.send-v2__customize-gas__save')
- customizeGasSaveButton[0].click()
-
- assert.equal(
- (await findAsync(sendGasField, '.currency-display__input-wrapper > input')).val(),
- '0.003',
- 'send gas field should show customized gas total'
- )
- assert.equal(
- (await findAsync(sendGasField, '.currency-display__converted-value'))[0].textContent,
- '$3.60 USD',
- 'send gas field should show customized gas total converted to USD'
- )
+ await customizeGas(assert, 0, 21000, '0', '$0.00 USD')
+ await customizeGas(assert, 500, 60000, '0.003', '$3.60 USD')
const sendButton = await queryAsync($, 'button.btn-primary--lg.page-container__footer-button')
assert.equal(sendButton[0].textContent, 'Next', 'next button rendered')
diff --git a/test/integration/lib/tx-list-items.js b/test/integration/lib/tx-list-items.js
index 0c0c5a77f..4856b3852 100644
--- a/test/integration/lib/tx-list-items.js
+++ b/test/integration/lib/tx-list-items.js
@@ -21,7 +21,7 @@ async function runTxListItemsTest(assert, done) {
selectState.val('tx list items')
reactTriggerChange(selectState[0])
- const metamaskLogo = await queryAsync($, '.left-menu-wrapper')
+ const metamaskLogo = await queryAsync($, '.app-header__logo-container')
assert.ok(metamaskLogo[0], 'metamask logo present')
metamaskLogo[0].click()
@@ -46,7 +46,7 @@ async function runTxListItemsTest(assert, done) {
const failedTx = txListItems[4]
const failedTxRenderedStatus = await findAsync($(failedTx), '.tx-list-status')
assert.equal(failedTxRenderedStatus[0].textContent, 'Failed', 'failedTx has correct label')
-
+
const shapeShiftTx = txListItems[5]
const shapeShiftTxStatus = await findAsync($(shapeShiftTx), '.flex-column div:eq(1)')
assert.equal(shapeShiftTxStatus[0].textContent, 'No deposits received', 'shapeShiftTx has correct status')
diff --git a/test/screens/new-ui.js b/test/screens/new-ui.js
index 91b3a9633..e176da529 100644
--- a/test/screens/new-ui.js
+++ b/test/screens/new-ui.js
@@ -39,8 +39,7 @@ async function captureAllScreens() {
const extPath = path.resolve('dist/chrome')
driver = buildWebDriver(extPath)
await driver.get('chrome://extensions-frame')
- const elems = await driver.findElements(By.css('.extension-list-item-wrapper'))
- const extensionId = await elems[1].getAttribute('id')
+ const extensionId = await driver.executeScript('return document.querySelector("extensions-manager").shadowRoot.querySelector("extensions-view-manager extensions-item-list").shadowRoot.querySelector("#container > div.items-container > extensions-item:nth-child(2)").getAttribute("id")')
await driver.get(`chrome-extension://${extensionId}/home.html`)
await delay(500)
tabs = await driver.getAllWindowHandles()
diff --git a/test/stub/provider.js b/test/stub/provider.js
index e77db4e28..a1c70486d 100644
--- a/test/stub/provider.js
+++ b/test/stub/provider.js
@@ -1,14 +1,28 @@
const JsonRpcEngine = require('json-rpc-engine')
const scaffoldMiddleware = require('eth-json-rpc-middleware/scaffold')
-const TestBlockchain = require('eth-block-tracker/test/util/testBlockMiddleware')
+const providerAsMiddleware = require('eth-json-rpc-middleware/providerAsMiddleware')
+const GanacheCore = require('ganache-core')
module.exports = {
createEngineForTestData,
providerFromEngine,
scaffoldMiddleware,
createTestProviderTools,
+ getTestSeed,
+ getTestAccounts,
}
+function getTestSeed () {
+ return 'people carpet cluster attract ankle motor ozone mass dove original primary mask'
+}
+
+function getTestAccounts () {
+ return [
+ { address: '0x88bb7F89eB5e5b30D3e15a57C68DBe03C6aCCB21', key: Buffer.from('254A8D551474F35CCC816388B4ED4D20B945C96B7EB857A68064CB9E9FB2C092', 'hex') },
+ { address: '0x1fe9aAB565Be19629fF4e8541ca2102fb42D7724', key: Buffer.from('6BAB5A4F2A6911AF8EE2BD32C6C05F6643AC48EF6C939CDEAAAE6B1620805A9B', 'hex') },
+ { address: '0xbda5c89aa6bA1b352194291AD6822C92AbC87c7B', key: Buffer.from('9B11D7F833648F26CE94D544855558D7053ECD396E4F4563968C232C012879B0', 'hex') },
+ ]
+}
function createEngineForTestData () {
return new JsonRpcEngine()
@@ -21,11 +35,13 @@ function providerFromEngine (engine) {
function createTestProviderTools (opts = {}) {
const engine = createEngineForTestData()
- const testBlockchain = new TestBlockchain()
// handle provided hooks
engine.push(scaffoldMiddleware(opts.scaffold || {}))
// handle block tracker methods
- engine.push(testBlockchain.createMiddleware())
+ engine.push(providerAsMiddleware(GanacheCore.provider({
+ mnemonic: getTestSeed(),
+ })))
+ // wrap in standard provider interface
const provider = providerFromEngine(engine)
- return { provider, engine, testBlockchain }
+ return { provider, engine }
}
diff --git a/test/unit/metamask-controller-test.js b/test/unit/metamask-controller-test.js
index adeca9b5f..18c3f9ab9 100644
--- a/test/unit/metamask-controller-test.js
+++ b/test/unit/metamask-controller-test.js
@@ -6,6 +6,12 @@ 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()
@@ -87,17 +93,28 @@ describe('MetaMaskController', function () {
describe('#createNewVaultAndRestore', function () {
it('should be able to call newVaultAndRestore despite a mistake.', async function () {
-
const password = 'what-what-what'
- const wrongSeed = 'debris dizzy just program just float decrease vacant alarm reduce speak stadiu'
- const rightSeed = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
- await metamaskController.createNewVaultAndRestore(password, wrongSeed)
- .catch((e) => {
- return
- })
- await metamaskController.createNewVaultAndRestore(password, rightSeed)
+ 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/nonce-tracker-test.js b/test/unit/nonce-tracker-test.js
index 5a27882ef..cf26945d3 100644
--- a/test/unit/nonce-tracker-test.js
+++ b/test/unit/nonce-tracker-test.js
@@ -1,5 +1,5 @@
const assert = require('assert')
-const NonceTracker = require('../../app/scripts/lib/nonce-tracker')
+const NonceTracker = require('../../app/scripts/controllers/transactions/nonce-tracker')
const MockTxGen = require('../lib/mock-tx-gen')
let providerResultStub = {}
diff --git a/test/unit/pending-tx-test.js b/test/unit/pending-tx-test.js
index f0b4e3bfc..001b86dd1 100644
--- a/test/unit/pending-tx-test.js
+++ b/test/unit/pending-tx-test.js
@@ -4,7 +4,7 @@ const EthTx = require('ethereumjs-tx')
const ObservableStore = require('obs-store')
const clone = require('clone')
const { createTestProviderTools } = require('../stub/provider')
-const PendingTransactionTracker = require('../../app/scripts/lib/pending-tx-tracker')
+const PendingTransactionTracker = require('../../app/scripts/controllers/transactions/pending-tx-tracker')
const MockTxGen = require('../lib/mock-tx-gen')
const sinon = require('sinon')
const noop = () => true
diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js
index 824574ff2..ddd921652 100644
--- a/test/unit/tx-controller-test.js
+++ b/test/unit/tx-controller-test.js
@@ -5,17 +5,16 @@ 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/lib/tx-gas-utils')
-const { createTestProviderTools } = require('../stub/provider')
+const TxGasUtils = require('../../app/scripts/controllers/transactions/tx-gas-utils')
+const { createTestProviderTools, getTestAccounts } = require('../stub/provider')
const noop = () => true
const currentNetworkId = 42
const otherNetworkId = 36
-const privKey = new Buffer('8718b9618a37d1fc78c436511fc6df3c8258d3250635bba617f33003270ec03e', 'hex')
describe('Transaction Controller', function () {
- let txController, provider, providerResultStub, testBlockchain
+ let txController, provider, providerResultStub, query, fromAccount
beforeEach(function () {
providerResultStub = {
@@ -24,9 +23,9 @@ describe('Transaction Controller', function () {
// by default, all accounts are external accounts (not contracts)
eth_getCode: '0x',
}
- const providerTools = createTestProviderTools({ scaffold: providerResultStub })
- provider = providerTools.provider
- testBlockchain = providerTools.testBlockchain
+ provider = createTestProviderTools({ scaffold: providerResultStub }).provider
+ query = new EthjsQuery(provider)
+ fromAccount = getTestAccounts()[0]
txController = new TransactionController({
provider,
@@ -34,13 +33,43 @@ describe('Transaction Controller', function () {
txHistoryLimit: 10,
blockTracker: { getCurrentBlock: noop, on: noop, once: noop },
signTransaction: (ethTx) => new Promise((resolve) => {
- ethTx.sign(privKey)
+ ethTx.sign(fromAccount.key)
resolve()
}),
})
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()
@@ -188,7 +217,7 @@ describe('Transaction Controller', function () {
})
- describe('#addTxDefaults', function () {
+ describe('#addTxGasDefaults', function () {
it('should add the tx defaults if their are none', function (done) {
const txMeta = {
'txParams': {
@@ -199,7 +228,7 @@ describe('Transaction Controller', function () {
providerResultStub.eth_gasPrice = '4a817c800'
providerResultStub.eth_getBlockByNumber = { gasLimit: '47b784' }
providerResultStub.eth_estimateGas = '5209'
- txController.addTxDefaults(txMeta)
+ txController.addTxGasDefaults(txMeta)
.then((txMetaWithDefaults) => {
assert(txMetaWithDefaults.txParams.value, '0x0', 'should have added 0x0 as the value')
assert(txMetaWithDefaults.txParams.gasPrice, 'should have added the gas price')
@@ -210,99 +239,6 @@ describe('Transaction Controller', function () {
})
})
- describe('#_validateTxParams', function () {
- it('does not throw for positive values', function () {
- var sample = {
- from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
- value: '0x01',
- }
- txController._validateTxParams(sample)
- })
-
- it('returns error for negative values', function () {
- var sample = {
- from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
- value: '-0x01',
- }
- try {
- txController._validateTxParams(sample)
- } catch (err) {
- assert.ok(err, 'error')
- }
- })
- })
-
- describe('#_normalizeTxParams', () => {
- it('should normalize txParams', () => {
- let txParams = {
- chainId: '0x1',
- from: 'a7df1beDBF813f57096dF77FCd515f0B3900e402',
- to: null,
- data: '68656c6c6f20776f726c64',
- random: 'hello world',
- }
-
- let normalizedTxParams = txController._normalizeTxParams(txParams)
-
- assert(!normalizedTxParams.chainId, 'their should be no chainId')
- assert(!normalizedTxParams.to, 'their should be no to address if null')
- assert.equal(normalizedTxParams.from.slice(0, 2), '0x', 'from should be hexPrefixd')
- assert.equal(normalizedTxParams.data.slice(0, 2), '0x', 'data should be hexPrefixd')
- assert(!('random' in normalizedTxParams), 'their should be no random key in normalizedTxParams')
-
- txParams.to = 'a7df1beDBF813f57096dF77FCd515f0B3900e402'
- normalizedTxParams = txController._normalizeTxParams(txParams)
- assert.equal(normalizedTxParams.to.slice(0, 2), '0x', 'to should be hexPrefixd')
-
- })
- })
-
- describe('#_validateRecipient', () => {
- it('removes recipient for txParams with 0x when contract data is provided', function () {
- const zeroRecipientandDataTxParams = {
- from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
- to: '0x',
- data: 'bytecode',
- }
- const sanitizedTxParams = txController._validateRecipient(zeroRecipientandDataTxParams)
- assert.deepEqual(sanitizedTxParams, { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', data: 'bytecode' }, 'no recipient with 0x')
- })
-
- it('should error when recipient is 0x', function () {
- const zeroRecipientTxParams = {
- from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
- to: '0x',
- }
- assert.throws(() => { txController._validateRecipient(zeroRecipientTxParams) }, Error, 'Invalid recipient address')
- })
- })
-
-
- describe('#_validateFrom', () => {
- it('should error when from is not a hex string', function () {
-
- // where from is undefined
- const txParams = {}
- assert.throws(() => { txController._validateFrom(txParams) }, Error, `Invalid from address ${txParams.from} not a string`)
-
- // where from is array
- txParams.from = []
- assert.throws(() => { txController._validateFrom(txParams) }, Error, `Invalid from address ${txParams.from} not a string`)
-
- // where from is a object
- txParams.from = {}
- assert.throws(() => { txController._validateFrom(txParams) }, Error, `Invalid from address ${txParams.from} not a string`)
-
- // where from is a invalid address
- txParams.from = 'im going to fail'
- assert.throws(() => { txController._validateFrom(txParams) }, Error, `Invalid from address`)
-
- // should run
- txParams.from ='0x1678a085c290ebd122dc42cba69373b5953b831d'
- txController._validateFrom(txParams)
- })
- })
-
describe('#addTx', function () {
it('should emit updates', function (done) {
const txMeta = {
@@ -391,12 +327,12 @@ describe('Transaction Controller', function () {
describe('#updateAndApproveTransaction', function () {
let txMeta
- beforeEach(function () {
+ beforeEach(() => {
txMeta = {
id: 1,
status: 'unapproved',
txParams: {
- from: '0xc684832530fcbddae4b4230a47e991ddcec2831d',
+ from: fromAccount.address,
to: '0x1678a085c290ebd122dc42cba69373b5953b831d',
gasPrice: '0x77359400',
gas: '0x7b0d',
@@ -405,11 +341,12 @@ describe('Transaction Controller', function () {
metamaskNetworkId: currentNetworkId,
}
})
- it('should update and approve transactions', function () {
+ it('should update and approve transactions', async () => {
txController.txStateManager.addTx(txMeta)
- txController.updateAndApproveTransaction(txMeta)
+ const approvalPromise = txController.updateAndApproveTransaction(txMeta)
const tx = txController.txStateManager.getTx(1)
assert.equal(tx.status, 'approved')
+ await approvalPromise
})
})
diff --git a/test/unit/tx-gas-util-test.js b/test/unit/tx-gas-util-test.js
index 40ea8a7d6..c1d5966da 100644
--- a/test/unit/tx-gas-util-test.js
+++ b/test/unit/tx-gas-util-test.js
@@ -1,14 +1,77 @@
const assert = require('assert')
-const TxGasUtils = require('../../app/scripts/lib/tx-gas-utils')
-const { createTestProviderTools } = require('../stub/provider')
-
-describe('Tx Gas Util', function () {
- let txGasUtil, provider, providerResultStub
- beforeEach(function () {
- providerResultStub = {}
- provider = createTestProviderTools({ scaffold: providerResultStub }).provider
- txGasUtil = new TxGasUtils({
- provider,
+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')
+
+
+describe('txUtils', function () {
+ let txUtils
+
+ before(function () {
+ txUtils = new TxUtils(new Proxy({}, {
+ get: (obj, name) => {
+ return () => {}
+ },
+ }))
+ })
+
+ describe('chain Id', function () {
+ it('prepares a transaction with the provided chainId', function () {
+ const txParams = {
+ to: '0x70ad465e0bab6504002ad58c744ed89c7da38524',
+ from: '0x69ad465e0bab6504002ad58c744ed89c7da38525',
+ value: '0x0',
+ gas: '0x7b0c',
+ gasPrice: '0x199c82cc00',
+ data: '0x',
+ nonce: '0x3',
+ chainId: 42,
+ }
+ const ethTx = new Transaction(txParams)
+ assert.equal(ethTx.getChainId(), 42, 'chainId is set from tx params')
+ })
+ })
+
+ describe('addGasBuffer', function () {
+ it('multiplies by 1.5, when within block gas limit', function () {
+ // naive estimatedGas: 0x16e360 (1.5 mil)
+ const inputHex = '0x16e360'
+ // dummy gas limit: 0x3d4c52 (4 mil)
+ const blockGasLimitHex = '0x3d4c52'
+ const output = txUtils.addGasBuffer(inputHex, blockGasLimitHex)
+ const inputBn = hexToBn(inputHex)
+ const outputBn = hexToBn(output)
+ const expectedBn = inputBn.muln(1.5)
+ assert(outputBn.eq(expectedBn), 'returns 1.5 the input value')
+ })
+
+ it('uses original estimatedGas, when above block gas limit', function () {
+ // naive estimatedGas: 0x16e360 (1.5 mil)
+ const inputHex = '0x16e360'
+ // dummy gas limit: 0x0f4240 (1 mil)
+ const blockGasLimitHex = '0x0f4240'
+ const output = txUtils.addGasBuffer(inputHex, blockGasLimitHex)
+ // const inputBn = hexToBn(inputHex)
+ const outputBn = hexToBn(output)
+ const expectedBn = hexToBn(inputHex)
+ assert(outputBn.eq(expectedBn), 'returns the original estimatedGas value')
+ })
+
+ it('buffers up to recommend gas limit recommended ceiling', function () {
+ // naive estimatedGas: 0x16e360 (1.5 mil)
+ const inputHex = '0x16e360'
+ // dummy gas limit: 0x1e8480 (2 mil)
+ const blockGasLimitHex = '0x1e8480'
+ const blockGasLimitBn = hexToBn(blockGasLimitHex)
+ const ceilGasLimitBn = blockGasLimitBn.muln(0.9)
+ const output = txUtils.addGasBuffer(inputHex, blockGasLimitHex)
+ // const inputBn = hexToBn(inputHex)
+ // const outputBn = hexToBn(output)
+ const expectedHex = bnToHex(ceilGasLimitBn)
+ assert.equal(output, expectedHex, 'returns the gas limit recommended ceiling value')
})
})
})
diff --git a/test/unit/tx-state-history-helper-test.js b/test/unit/tx-state-history-helper-test.js
index 90cb10713..35e9ef188 100644
--- a/test/unit/tx-state-history-helper-test.js
+++ b/test/unit/tx-state-history-helper-test.js
@@ -1,6 +1,6 @@
const assert = require('assert')
const clone = require('clone')
-const txStateHistoryHelper = require('../../app/scripts/lib/tx-state-history-helper')
+const txStateHistoryHelper = require('../../app/scripts/controllers/transactions/lib/tx-state-history-helper')
describe('deepCloneFromTxMeta', function () {
it('should clone deep', function () {
diff --git a/test/unit/tx-state-history-helper.js b/test/unit/tx-state-history-helper.js
index 79ee26d6e..35f7dac57 100644
--- a/test/unit/tx-state-history-helper.js
+++ b/test/unit/tx-state-history-helper.js
@@ -1,5 +1,5 @@
const assert = require('assert')
-const txStateHistoryHelper = require('../../app/scripts/lib/tx-state-history-helper')
+const txStateHistoryHelper = require('../../app/scripts/controllers/transactions/lib/tx-state-history-helper')
const testVault = require('../data/v17-long-history.json')
diff --git a/test/unit/tx-state-manager-test.js b/test/unit/tx-state-manager-test.js
index a5ac13664..e5fe68d0b 100644
--- a/test/unit/tx-state-manager-test.js
+++ b/test/unit/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/lib/tx-state-manager')
-const txStateHistoryHelper = require('../../app/scripts/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/tx-utils-test.js
index 8ca13412e..be16225ba 100644
--- a/test/unit/tx-utils-test.js
+++ b/test/unit/tx-utils-test.js
@@ -1,77 +1,98 @@
const assert = require('assert')
-const Transaction = require('ethereumjs-tx')
-const BN = require('bn.js')
-
-
-const { hexToBn, bnToHex } = require('../../app/scripts/lib/util')
-const TxUtils = require('../../app/scripts/lib/tx-gas-utils')
+const txUtils = require('../../app/scripts/controllers/transactions/lib/util')
describe('txUtils', function () {
- let txUtils
-
- before(function () {
- txUtils = new TxUtils(new Proxy({}, {
- get: (obj, name) => {
- return () => {}
- },
- }))
- })
+ describe('#validateTxParams', function () {
+ it('does not throw for positive values', function () {
+ var sample = {
+ from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
+ value: '0x01',
+ }
+ txUtils.validateTxParams(sample)
+ })
- describe('chain Id', function () {
- it('prepares a transaction with the provided chainId', function () {
- const txParams = {
- to: '0x70ad465e0bab6504002ad58c744ed89c7da38524',
- from: '0x69ad465e0bab6504002ad58c744ed89c7da38525',
- value: '0x0',
- gas: '0x7b0c',
- gasPrice: '0x199c82cc00',
- data: '0x',
- nonce: '0x3',
- chainId: 42,
+ it('returns error for negative values', function () {
+ var sample = {
+ from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
+ value: '-0x01',
+ }
+ try {
+ txUtils.validateTxParams(sample)
+ } catch (err) {
+ assert.ok(err, 'error')
}
- const ethTx = new Transaction(txParams)
- assert.equal(ethTx.getChainId(), 42, 'chainId is set from tx params')
})
})
- describe('addGasBuffer', function () {
- it('multiplies by 1.5, when within block gas limit', function () {
- // naive estimatedGas: 0x16e360 (1.5 mil)
- const inputHex = '0x16e360'
- // dummy gas limit: 0x3d4c52 (4 mil)
- const blockGasLimitHex = '0x3d4c52'
- const output = txUtils.addGasBuffer(inputHex, blockGasLimitHex)
- const inputBn = hexToBn(inputHex)
- const outputBn = hexToBn(output)
- const expectedBn = inputBn.muln(1.5)
- assert(outputBn.eq(expectedBn), 'returns 1.5 the input value')
+ describe('#normalizeTxParams', () => {
+ it('should normalize txParams', () => {
+ let txParams = {
+ chainId: '0x1',
+ from: 'a7df1beDBF813f57096dF77FCd515f0B3900e402',
+ to: null,
+ data: '68656c6c6f20776f726c64',
+ random: 'hello world',
+ }
+
+ let normalizedTxParams = txUtils.normalizeTxParams(txParams)
+
+ assert(!normalizedTxParams.chainId, 'their should be no chainId')
+ assert(!normalizedTxParams.to, 'their should be no to address if null')
+ assert.equal(normalizedTxParams.from.slice(0, 2), '0x', 'from should be hexPrefixd')
+ assert.equal(normalizedTxParams.data.slice(0, 2), '0x', 'data should be hexPrefixd')
+ assert(!('random' in normalizedTxParams), 'their should be no random key in normalizedTxParams')
+
+ txParams.to = 'a7df1beDBF813f57096dF77FCd515f0B3900e402'
+ normalizedTxParams = txUtils.normalizeTxParams(txParams)
+ assert.equal(normalizedTxParams.to.slice(0, 2), '0x', 'to should be hexPrefixd')
+
})
+ })
- it('uses original estimatedGas, when above block gas limit', function () {
- // naive estimatedGas: 0x16e360 (1.5 mil)
- const inputHex = '0x16e360'
- // dummy gas limit: 0x0f4240 (1 mil)
- const blockGasLimitHex = '0x0f4240'
- const output = txUtils.addGasBuffer(inputHex, blockGasLimitHex)
- // const inputBn = hexToBn(inputHex)
- const outputBn = hexToBn(output)
- const expectedBn = hexToBn(inputHex)
- assert(outputBn.eq(expectedBn), 'returns the original estimatedGas value')
+ describe('#validateRecipient', () => {
+ it('removes recipient for txParams with 0x when contract data is provided', function () {
+ const zeroRecipientandDataTxParams = {
+ from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
+ to: '0x',
+ data: 'bytecode',
+ }
+ const sanitizedTxParams = txUtils.validateRecipient(zeroRecipientandDataTxParams)
+ assert.deepEqual(sanitizedTxParams, { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', data: 'bytecode' }, 'no recipient with 0x')
})
- it('buffers up to recommend gas limit recommended ceiling', function () {
- // naive estimatedGas: 0x16e360 (1.5 mil)
- const inputHex = '0x16e360'
- // dummy gas limit: 0x1e8480 (2 mil)
- const blockGasLimitHex = '0x1e8480'
- const blockGasLimitBn = hexToBn(blockGasLimitHex)
- const ceilGasLimitBn = blockGasLimitBn.muln(0.9)
- const output = txUtils.addGasBuffer(inputHex, blockGasLimitHex)
- // const inputBn = hexToBn(inputHex)
- // const outputBn = hexToBn(output)
- const expectedHex = bnToHex(ceilGasLimitBn)
- assert.equal(output, expectedHex, 'returns the gas limit recommended ceiling value')
+ it('should error when recipient is 0x', function () {
+ const zeroRecipientTxParams = {
+ from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
+ to: '0x',
+ }
+ assert.throws(() => { txUtils.validateRecipient(zeroRecipientTxParams) }, Error, 'Invalid recipient address')
})
})
-}) \ No newline at end of file
+
+
+ describe('#validateFrom', () => {
+ it('should error when from is not a hex string', function () {
+
+ // where from is undefined
+ const txParams = {}
+ assert.throws(() => { txUtils.validateFrom(txParams) }, Error, `Invalid from address ${txParams.from} not a string`)
+
+ // where from is array
+ txParams.from = []
+ assert.throws(() => { txUtils.validateFrom(txParams) }, Error, `Invalid from address ${txParams.from} not a string`)
+
+ // where from is a object
+ txParams.from = {}
+ assert.throws(() => { txUtils.validateFrom(txParams) }, Error, `Invalid from address ${txParams.from} not a string`)
+
+ // where from is a invalid address
+ txParams.from = 'im going to fail'
+ assert.throws(() => { txUtils.validateFrom(txParams) }, Error, `Invalid from address`)
+
+ // should run
+ txParams.from ='0x1678a085c290ebd122dc42cba69373b5953b831d'
+ txUtils.validateFrom(txParams)
+ })
+ })
+})