1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-23 03:36:18 +02:00
metamask-extension/test/e2e/fixture-server.js
Mark Stacey eadeaa7883 End-to-end test state fixtures (#7663)
* Add network store for testing

An alternative persistent state store has been created for use with e2e
tests. Instead of reading state from disk, it tries to load state from
a local fixture server running on port `12345` and serving state from
the path `/state.json`, and returns a blank state otherwise.

* Add e2e test fixture server

A fixture server has been added for serving background state, which the
background will read upon startup as part of restoring persisted state.

The `signature-request` e2e test has been updated to use a fixture to
bypass the registration step. The fixture used (`imported-account`) was
generated by pausing midway through that test run
2019-12-11 09:26:20 -08:00

75 lines
1.8 KiB
JavaScript

const fs = require('fs').promises
const Koa = require('koa')
const path = require('path')
const CURRENT_STATE_KEY = '__CURRENT__'
const DEFAULT_STATE_KEY = '__DEFAULT__'
const FIXTURE_SERVER_HOST = 'localhost'
const FIXTURE_SERVER_PORT = 12345
class FixtureServer {
constructor () {
this._app = new Koa()
this._stateMap = new Map([
[DEFAULT_STATE_KEY, Object.create(null)],
])
this._initialStateCache = new Map()
this._app.use(async (ctx) => {
// Firefox is _super_ strict about needing CORS headers
ctx.set('Access-Control-Allow-Origin', '*')
if (this._isStateRequest(ctx)) {
ctx.body = this._stateMap.get(CURRENT_STATE_KEY)
}
})
}
async start () {
const options = {
host: FIXTURE_SERVER_HOST,
port: FIXTURE_SERVER_PORT,
exclusive: true,
}
return new Promise((resolve, reject) => {
this._server = this._app.listen(options)
this._server.once('error', reject)
this._server.once('listening', resolve)
})
}
async stop () {
if (!this._server) {
return
}
return new Promise((resolve, reject) => {
this._server.close()
this._server.once('error', reject)
this._server.once('close', resolve)
})
}
async loadState (directory) {
const statePath = path.resolve(__dirname, directory, 'state.json')
let state
if (this._initialStateCache.has(statePath)) {
state = this._initialStateCache.get(statePath)
} else {
const data = await fs.readFile(statePath)
state = JSON.parse(data.toString('utf-8'))
this._initialStateCache.set(statePath, state)
}
this._stateMap.set(CURRENT_STATE_KEY, state)
}
_isStateRequest (ctx) {
return ctx.method === 'GET' && ctx.path === '/state.json'
}
}
module.exports = FixtureServer