msportalfx-mock
The Azure Portal Mocking Framework provides extension teams the ability to dynamically record arbitrary network requests while running E2E tests and replay them during subsequent runs to prevent long-running or costly operations from being performed with each test run.
The Framework spawns a NodeJS Express server and patches Portal to redirect specified network requests to the server which acts as a proxy to the target when recording and as a mock provider when replaying.
It includes several built-in target handlers for ARM, storage data plane, and static data fixtures and provides interfaces for defining additional custom target handlers.
Benefits
- Reduces load on back-end services thus improving capacity and reducing costs
- While in use within the IaaS extension team, framework eliminated on average 300k-500k network requests and 9k-13k ARM deployments per day.
- Speeds test execution
- For long-running operations like deployments, replaying them is almost immediate. So 10+ minute runs are reduced to less than a minute.
- Easily refresh test data
- Rather than having static data fixtures saved into a repository, by loading and storing mock data to a storage account, teams can easily refresh the data periodically to quickly catch breaking changes to back-end APIs.
- Invisible to tests
- Typically won't require any changes to existing tests since it just acts as a middle-man between Portal and the targets.
Back to top
Installation
npm install --save-dev msportalfx-mock
Back to top
Usage
Server
MockFx starts up a NodeJS Express server running on a specified port to mock a set of targets:
const armTarget = createARMTarget({
host: "management.azure.com",
loadRequests: async (context: MockFx.Context): Promise<MockFx.Request[]> => {
return [];
},
storeRequests: async (context: MockFx.Context, requests: MockFx.Request[]): void => {
},
});
const mockFx = await MockFx.create({
port: 5000,
targets: [armTarget],
});
await mockFx.start();
Back to top
Certificates
MockFx handles creating, installing, and managing self-signed SSL certificates for the server to use:
Issued To | Issued By | Friendly Name | Expiration | Install Location(s) |
---|
localhost | MockFx Server Root | MockFx Server | Every 90 days | Cert:\LocalMachine\My |
MockFx Server Root | MockFx Server Root | | Every 90 days | Cert:\LocalMachine\My Cert:\LocalMachine\CA Cert:\LocalMachine\Root |
Back to top
Registering Tests
Since MockFx stands up a single server for all tests, in order to support running tests in parallel, we require 2 keys to register a test with the server:
- A unique run ID which splits up concurrent test runs. This can usually just be a random string.
- A unique test ID within a run. Usually the test name or relative filepath to the test in source control.
Every test in a run must be registered by calling either mockFx.registerTest(context)
directly or over HTTPS POST using the register end-point
from MockFx.getEndpoints(...).registerTest
with the test's context object as its body. If using the network API, the MockFx server must be started first with mockFx.start()
.
const runId = 'uniqueRunID';
const testId = 'testID';
await mockFx.registerTest({
mode: MockFx.Mode.Record,
runId,
testId,
targets: [armTarget.name],
});
or
await mockFx.start();
const mockFxPort = 5000;
const runId = 'uniqueRunID';
const testId = 'testID';
const registerEndpoint = MockFx.getEndpoints(mockFxPort, runId, testId).registerTest;
const context: MockFx.Context = {
mode: MockFx.Mode.Record,
runId,
testId,
targets: [armTarget.name],
};
const body = JSON.stringify(context);
const request = https.request({
...url.parse(registerEndpoint),
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': body.length
}
});
request.write(body);
request.end();
Back to top
Mocking Portal Requests
To mock requests from Portal, client code must be executed in the browser in both Portal's execution context and in every extension's context.
We can use the Portal's patch query parameter to automatically inject the client plug-in into all extensions loaded in a session. The plug-in overrides the
global XMLHttpRequest.open
method (which is used to specify the URL for a request), and based on the request's URL, conditionally redirects
the request to the mock server if its host matches a registered target. This method works with direct XHR requests and when using Axios or the
Portal's request methods that use jQuery since they all use XHRs under the hood. It does not support the fetch API, but that could
be easily supported in the future if the need arises.
MockFx provides an end-point that serves the client code at MockFx.getEndpoints(...).plugin
. You can pass this URL into Portal's patch
parameter so that whenever an
extension is loaded, the client code will automatically be executed:
const clientPluginURL = MockFx.getEndpoints(mockFxPort, runId, testId).plugin;
const portalURL = 'https://portal.azure.com/' +
'?feature.canmodifyextensions=true' +
'&feature.prewarming=false' +
'#home?patch=["' + encodeURI(clientPluginURL) + '"]';
To patch Portal itself, you can get the client plug-in code directly with mockFx.getPluginCode(...)
and use your web driver to execute the code in the main execution context:
const clientPluginCode = mockFx.getPluginCode(runId, testId);
webdriver.executeScript(clientPluginCode);
Back to top
Client Plug-in Code
(function () {
const config = {
hosts: ["MANAGEMENT.AZURE.COM"],
runId: "uniqueRunID",
testId: "testID",
port: 5000
};
var realOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
var parsedURL = new URL(url, document.baseURI);
var originalHost = parsedURL.host;
var shouldRedirect = config.hosts.some(function (host) { return originalHost.toUpperCase().includes(host); });
if (shouldRedirect) {
parsedURL.protocol = "https";
parsedURL.host = "localhost:" + config.port;
url = parsedURL.toString();
}
realOpen.call(this, method, url, async, user, password);
if (shouldRedirect) {
this.setRequestHeader("x-mockfx-run-id", config.runId);
this.setRequestHeader("x-mockfx-test-id", config.testId);
this.setRequestHeader("x-mockfx-original-host", originalHost);
this.setRequestHeader("x-mockfx-source", "portal");
}
};
})();
Back to top
Finalizing Tests
Once your test run is finished, finalize it to instruct MockFx to call its targets' storeRequests
methods for the test to
store the recorded data and then free up the memory used by the test instance. You can call mockFx.finalizeTest(...)
directly or
over HTTPS POST using the finalize end-point from MockFx.getEndpoints(...).finalizeTest
with the test's finalization object as its body.
const runId = 'uniqueRunID';
const testId = 'testID';
const testPassed = true;
await mockFx.finalizeTest({
runId,
testId,
shouldStore: testPassed
});
or
const mockFxPort = 5000;
const runId = 'uniqueRunID';
const testId = 'testID';
const testPassed = true;
const finalizationEndpoint = MockFx.getEndpoints(mockFxPort, runId, testId).finalizeTest;
const finalization: MockFx.Context = {
runId,
testId,
shouldStore: testPassed
};
const body = JSON.stringify(finalization);
const request = https.request({
...url.parse(finalizationEndpoint),
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': body.length
}
});
request.write(body);
request.end();
Back to top
Stopping MockFx
Once all tests have finished, stop the server to close all connections:
await mockFx.stop();
Back to top
Logging
You can subscribe to MockFx logs with MockFx.logger
:
Note: logger
is a static property on the MockFx
class.
MockFx.logger.on("log", (level: MockFx.LogLevel, message: string) => {
switch (level) {
case MockFx.LogLevel.Debug:
case MockFx.LogLevel.Info:
case MockFx.LogLevel.Warn:
console.log(level, message);
}
});
MockFx.logger.on("error", (error: Error) => {
console.error(error);
});
MockFx.logger.on("telemetry", (telemetry: MockFx.Telemetry) => {
console.log(JSON.stringify(telemetry, null, 4));
});
Be sure to subscribe to the logging events before performing any other commands with MockFx to catch everything.
Back to top
Example
import { createARMTarget, MockFx } from "msportalfx-mock";
import { WebDriver } from "selenium-webdriver";
import * as url from 'url';
let mockFx: MockFx;
const mockFxPort = 5000;
const runId = 'uniqueRunID';
const testsToRun = ['testID'];
const armTarget = createARMTarget({
host: "management.azure.com",
loadRequests: async (context: MockFx.Context): Promise<MockFx.Request[]> => {
return [];
},
storeRequests: async (context: MockFx.Context, requests: MockFx.Request[]) => {
},
});
(async () => {
MockFx.logger.on("log", (level: MockFx.LogLevel, message: string) => {
switch (level) {
case MockFx.LogLevel.Debug:
case MockFx.LogLevel.Info:
case MockFx.LogLevel.Warn:
default:
console.log(level, message);
}
});
MockFx.logger.on("error", (error: Error) => {
console.error(error);
});
MockFx.logger.on("telemetry", (telemetry: MockFx.Telemetry) => {
console.log(JSON.stringify(telemetry, null, 4));
});
mockFx = await MockFx.create({
port: mockFxPort,
targets: [armTarget],
});
await mockFx.start();
await Promise.all(testsToRun.map((testId) => runTest(testId)));
await mockFx.stop();
})();
async function runTest(testId: string) {
await mockFx.registerTest({
mode: MockFx.Mode.Record,
runId,
testId,
targets: [armTarget.name]
});
const webdriver: WebDriver = new WebDriver();
const clientPluginCode = mockFx.getPluginCode(runId, testId);
const clientPluginURL = MockFx.getEndpoints(mockFxPort, runId, testId).plugin;
await webdriver.get('https://portal.azure.com/' +
'?feature.canmodifyextensions=true' +
'&feature.prewarming=false' +
'#home?patch=["' + encodeURI(clientPluginURL) + '"]'
);
await webdriver.executeScript(clientPluginCode);
const testPassed = true;
await mockFx.finalizeTest({
runId,
testId,
shouldStore: testPassed
});
}
Back to top
MockFx API
Note: MockFx has a direct API for registering and finalizing tests, but they're also exposed through the server to enable
registering and finalizing tests from other processes/threads than the one MockFx is running from. Rather than hard-coding the end-points,
use MockFx.getEndpoints(...)
to query them to make upgrading easier.
class MockFx {
static version: string;
static logger: LoggerType = logger;
static create(config: MockFx.Configuration): Promise<MockFx>;
static getEndpoints(port: number, runId: string, testId: string): MockFx.Endpoints;
start(): Promise<void>;
stop(): Promise<void>;
getPluginCode(runId: string, testId: string): string;
registerStage(stageContext: MockFx.Stage): Promise<void>;
registerTest(context: MockFx.Context): Promise<void>;
finalizeStage(stageContext: MockFx.Stage): Promise<void>
finalizeTest(finalization: MockFx.Finalization): Promise<void>
}
Back to top
MockFx Configuration
interface Configuration {
logToConsole?: boolean;
port: number;
targets: TargetDefinition[];
}
Back to top
MockFx End-points
Returned from MockFx.getEndpoints(...)
. Use these end-points to register, load client plug-in code for, and finalize your test runs.
interface Endpoints {
finalizeStage: string;
finalizeTest: string;
plugin: string;
registerStage: string;
registerTest: string;
}
Back to top
Target Definition
A target definition describes how the framework should intercept requests for a service, how to handle its requests and responses, and how to load and store mock data for it.
A few target definitions are built into the framework for targetting ARM, storage data plane, and handling local static mock data.
If your team desires to target other services, it's possible to write your own definition by using the following interface:
interface TargetDefinition {
name: string;
hosts: string[];
getRequestMetadata?: (request: ExpressRequest, response: IncomingMessage) => Promise<Record<string, any>>;
getRouter?: () => Router;
loadRequests: (context: Context) => Promise<MockFx.Request[]>;
matchRequest: (
request: ExpressRequest,
unmatchedRequests: MockFx.Request[]
) => Promise<MockFx.Request | undefined>;
onBeforeRequestMatch?: (
request: ExpressRequest,
context: MockFx.Context,
storedRequests: MockFx.Request[]
) => Promise<MockFx.Request[]>;
parseResponse?: (response: IncomingMessage, responseBody: Buffer) => Promise<any>;
storeRequests: (context: MockFx.Context, requests: MockFx.Request[]) => Promise<void>;
}
Back to top
Mock Request
interface Request {
url: string;
method: string;
metadata: Record<string, any>;
request: any;
response: any;
responseHeaders: Record<string, string>;
responseSize: number;
responseCode: number;
}
Back to top
Test Context
interface Context {
mode: MockFx.Mode;
runId: string;
testId: string;
targets: string[];
metadata?: any;
proxyUnmatched?: boolean;
}
Back to top
Test Finalization
interface Finalization {
runId: string;
testId: string;
shouldStore?: boolean;
}
Back to top
Stage Context
interface Stage {
runId: string;
testId: string;
stage: string;
}
Back to top
Telemetry
interface Telemetry {
context: MockFx.Context;
source: string;
target: string;
originalHost: string;
time: string;
url: string;
method: string;
isMatch: boolean;
responseSizeInBytes: number;
metadata?: Record<string, string>;
}
Back to top
License
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Back to top