### Start Mountebank Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of starting Mountebank with specific port, injection enabled, and debug logging. ```bash mb start --port 3000 --allowInjection --loglevel debug ``` -------------------------------- ### Example: Use a startup RC file Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of starting Mountebank with a startup configuration file. ```bash mb start --rcfile .mbrc ``` -------------------------------- ### create Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/mountebank.md Example of how to create and start the Mountebank server in one operation, including signal handling for graceful shutdown. ```javascript const mountebank = require('@mbtest/mountebank'); const options = { port: 2525, allowInjection: false, log: { transports: { console: {}, file: { path: 'mb.log' } } } }; const server = await mountebank.create(options); // Register signal handlers process.on('SIGINT', () => { server.close(() => { console.log('Server closed'); process.exit(0); }); }); ``` -------------------------------- ### listen Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/mountebank.md Example of how to start an express application with Mountebank and shut it down. ```javascript const server = await mountebank.listen(app, options); // Later, to shut down server.close(() => { console.log('Mountebank shut down'); }); ``` -------------------------------- ### Create and Start Server Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/README.md Example of creating and starting a Mountebank server with custom options. ```javascript const mountebank = require('@mbtest/mountebank'); const options = { port: 2525, allowInjection: false, log: { transports: { console: {}, file: { path: 'mb.log' } } } }; const server = await mountebank.create(options); // Shutdown server.close(() => { console.log('Server stopped'); }); ``` -------------------------------- ### Help Command Examples Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Examples of how to display help information for Mountebank commands. ```bash mb --help mb start --help mb stop --help mb save --help ``` -------------------------------- ### Example: Load custom protocols Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of loading custom protocol implementations from a file. ```bash mb --protofile ./protocols.json ``` -------------------------------- ### Production Setup Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Starts Mountebank in production mode, listening on all interfaces, logging to a file, and with IP whitelisting and an API key. ```bash mb start \ --port 2525 \ --host 0.0.0.0 \ --loglevel info \ --logfile /var/log/mountebank.log \ --pidfile /var/run/mb.pid \ --ipWhitelist '10.0.0.0/8' \ --apikey production-key-123 ``` -------------------------------- ### Get All Imposters Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of retrieving all imposters. ```javascript const imposters = await repository.all(); console.log(`${imposters.length} imposters running`); ``` -------------------------------- ### Start Mountebank with API Key Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/README.md Example of starting Mountebank with an API key for authentication. ```bash mb start --apikey secret-key-123 ``` -------------------------------- ### Replay Mountebank Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of replaying Mountebank configuration. ```bash mb replay ``` -------------------------------- ### Start Mountebank Server Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Starts the Mountebank server with specified options. ```bash mb start [options...] # or simply: mb [options...] ``` -------------------------------- ### Get Imposter Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of retrieving a specific imposter by port. ```javascript const imposter = await repository.get(3000); if (imposter) { console.log(`Found imposter on port ${imposter.port}`); } ``` -------------------------------- ### Example: Set API key for authentication Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of setting an API key for Mountebank authentication. ```bash mb --apikey secret-key-123 ``` -------------------------------- ### Start Mountebank with IP Whitelist Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/README.md Example of starting Mountebank with an IP whitelist to restrict connections. ```bash mb start --ipWhitelist '192.168.1.0/24|10.0.0.0/8' ``` -------------------------------- ### Example: Specify data directory Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of specifying a directory for Mountebank to persist imposter data. ```bash mb --datadir ./mountebank-data ``` -------------------------------- ### Start Mountebank Server Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/mountebank.md Starts the Mountebank server with specified options. ```bash mb start --port 2525 --allowInjection --loglevel debug ``` -------------------------------- ### Example: Bind to a specific host Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of binding Mountebank to a specific host. ```bash mb --host 0.0.0.0 ``` -------------------------------- ### Example: Prevent EJS rendering Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of starting Mountebank with a config file but preventing EJS template rendering. ```bash mb --configfile config.json --noParse ``` -------------------------------- ### Restart Mountebank Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of restarting Mountebank on a specific port. ```bash mb restart --port 3000 ``` -------------------------------- ### Example: Bind to a specific port Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of binding Mountebank to a specific port. ```bash mb --port 3000 ``` -------------------------------- ### Run Commands File (RC File) Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example content of an Mountebank RC file containing startup options. ```text --port 3000 --host 0.0.0.0 --configfile imposters.json --loglevel debug ``` -------------------------------- ### Example: Load configuration from EJS template Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of loading Mountebank imposters from an EJS template file. ```bash mb --configfile imposters.ejs ``` -------------------------------- ### getResponseFor Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposter.md Demonstrates how to use getResponseFor to get a response for a given request, including request details and logging the response status code and body. ```javascript const request = { method: 'GET', path: '/api/users', headers: { 'Host': 'example.com' }, query: { id: '1' }, body: '', ip: '127.0.0.1' }; const response = await imposter.getResponseFor(request); console.log(response.statusCode, response.body); ``` -------------------------------- ### createApp Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/mountebank.md Example of how to create an express application with Mountebank. ```javascript const mountebank = require('@mbtest/mountebank'); const options = { port: 2525, allowInjection: false, ipWhitelist: ['*'], log: { transports: { console: {}, file: { path: 'mb.log' } } } }; const app = await mountebank.createApp(options); // app is an express application ready to be used or passed to listen() ``` -------------------------------- ### Example: Restrict connections to localhost Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of restricting Mountebank connections to localhost only. ```bash mb --localOnly ``` -------------------------------- ### Example: Specify save file for `mb save` Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of specifying the file to save imposters to when using the `mb save` command. ```bash mb save --savefile backup.json ``` -------------------------------- ### Example: Specify log file path Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of specifying the path for the Mountebank log file. ```bash mb --logfile /var/log/mountebank.log ``` -------------------------------- ### Example: Use a custom formatter Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of using a custom formatter module for Mountebank configuration files. ```bash mb --formatter ./custom-formatter.js ``` -------------------------------- ### Example: Custom logging configuration Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of providing a custom logging configuration for Mountebank via a file. ```bash mb --log ./log-config.json ``` -------------------------------- ### Example: Set log level to debug Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of setting the Mountebank logging level to debug. ```bash mb --loglevel debug ``` -------------------------------- ### Example: Specify IP whitelist Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of specifying a pipe-delimited list of allowed IP addresses for Mountebank. ```bash mb --ipWhitelist '192.168.1.20|192.168.1.21' ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md An example of an Mountebank imposters configuration file in JSON format. ```json { "imposters": [ { "protocol": "http", "port": 3000, "name": "API Mock", "stubs": [ { "predicates": [ { "equals": { "method": "GET", "path": "/api/users" } } ], "responses": [ { "is": { "statusCode": 200, "headers": { "content-type": "application/json" }, "body": "[\"id\": 1, \"name\": \"Alice\"]" } } ] } ] } ] } ``` -------------------------------- ### Install Mountebank Source: https://github.com/mountebank-testing/mountebank/blob/master/README.md Command to install Mountebank globally using npm. ```bash npm install -g @mbtest/mountebank ``` -------------------------------- ### Stop Mountebank Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of stopping Mountebank using a PID file. ```bash mb stop --pidfile mb.pid ``` -------------------------------- ### Example: Remove proxies when saving Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of using the `--removeProxies` option with `mb save` to switch from record to replay mode. ```bash mb save --removeProxies ``` -------------------------------- ### Example: Specify PID file location Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of specifying the location for the Mountebank process ID file. ```bash mb --pidfile /var/run/mb.pid ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/mountebank-testing/mountebank/blob/master/README.md Commands to install all dependencies and run all tests for building Mountebank. ```bash npm install npm test ``` -------------------------------- ### Create HTTP Server Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/http-server.md Example of creating an HTTP server with custom options and a response function. ```javascript const httpServer = require('./models/http/httpServer.js'); const options = { port: 3000, host: 'localhost', defaultResponse: { statusCode: 404, headers: { 'content-type': 'application/json' }, body: '{"error": "Not found"}' }, allowCORS: true }; const server = await httpServer.create(options, logger, async (request) => { // Process request and return response return { statusCode: 200, headers: { 'content-type': 'text/plain' }, body: 'Hello, World!' }; }); console.log(`HTTP server listening on port ${server.port}`); ``` -------------------------------- ### Example: Disable file logging Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of disabling file-based logging in Mountebank. ```bash mb --nologfile ``` -------------------------------- ### Get stubs for an imposter and find the first matching stub Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of retrieving stubs for an imposter and then finding the first stub that matches a specific request predicate. ```javascript const stubs = repository.stubsFor(3000); const firstMatchingStub = await stubs.first(request => { return request.predicates.every(p => evaluate(p)); }); ``` -------------------------------- ### Add Imposter Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of adding an imposter to the repository. ```javascript const imposter = await httpProtocol.createImposterFrom(creationRequest); await repository.add(imposter); ``` -------------------------------- ### Example: Enable JavaScript injection Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of enabling JavaScript injection in Mountebank responses and predicates. ```bash mb --allowInjection ``` -------------------------------- ### Save Mountebank Configuration Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of saving Mountebank configuration to a file, removing proxies, and specifying the port. ```bash mb save --savefile config.json --removeProxies --port 3000 ``` -------------------------------- ### HTTPS Server Creation Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/http-server.md Example of creating an HTTPS server with key and certificate options. ```javascript const httpsServer = require('./models/https/httpsServer.js'); const options = { port: 443, key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt') }; const server = await httpsServer.create(options, logger, responseFn); ``` -------------------------------- ### Load Protocols Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/protocols.md Example of how to load protocols using the loadProtocols function. ```javascript const protocols = require('./models/protocols.js'); const protocolsMap = protocols.loadProtocols( options, 'http://localhost:2525', logger, isAllowedConnection, imposters ); // protocolsMap = { // http: ProtocolHandler, // https: ProtocolHandler, // tcp: ProtocolHandler, // smtp: ProtocolHandler, // grpc: ProtocolHandler // if custom // } ``` -------------------------------- ### Starting Mountebank with Custom Protocols Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/protocols.md Command to start Mountebank with a custom protocols file. ```bash mb start --protofile protocols.json ``` -------------------------------- ### Delete All Imposters Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of deleting all imposters. ```javascript await repository.deleteAll(); console.log('All imposters deleted'); ``` -------------------------------- ### create Function Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/response-resolver.md Example usage of the responseResolver.create function. ```javascript const responseResolver = require('./models/responseResolver.js'); const stubs = impostersRepository.stubsFor(port); const resolver = responseResolver.create(stubs, httpProxy, callbackURL); ``` -------------------------------- ### Example: Set CORS origin Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of setting a safe origin for CORS requests in Mountebank. ```bash mb --origin 'http://localhost:3000' ``` -------------------------------- ### Headers Map Utility Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/http-server.md Example demonstrating the usage of the case-insensitive headersMap utility. ```javascript const headersMap = require('./models/http/headersMap.js'); const map = headersMap.of({ 'Content-Type': 'application/json', 'X-Custom-Header': 'value' }); // Case-insensitive access map.get('content-type'); // Returns 'application/json' map.set('X-NEW-HEADER', 'newValue'); ``` -------------------------------- ### Loading RC File Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Command to start Mountebank using an RC file. ```bash mb --rcfile .mbrc ``` -------------------------------- ### startsWith predicate configuration Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/predicates.md Configuration example for the startsWith predicate. ```json { startsWith: { path: '/api/' } } ``` -------------------------------- ### EJS Templating Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md An example of an Mountebank imposters configuration file using EJS templating for dynamic values. ```ejs { "imposters": [ { "protocol": "http", "port": <%= process.env.MB_PORT || 3000 %>, "stubs": [ { "predicates": [ { "equals": { "path": "/api/v<%= apiVersion %>" } } ], "responses": [ { "is": { "statusCode": 200, "body": "API v<%= apiVersion %>" } } ] } ] } ] } ``` -------------------------------- ### Example: Save configuration with debug option Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example of saving Mountebank configuration with debug option enabled to include stub match information. ```bash mb --debug ``` -------------------------------- ### Configuration Precedence Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Demonstrates that a command-line argument overrides an RC file setting. ```bash # CLI option overrides RC file mb --rcfile .mbrc --port 4000 ``` -------------------------------- ### CORS Support Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/http-server.md Example of enabling CORS support for the HTTP server. ```javascript const options = { port: 3000, allowCORS: true }; // The server will respond to OPTIONS requests with appropriate CORS headers ``` -------------------------------- ### Token Replacement Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md Example of how tokens are used within response bodies for dynamic content replacement. ```javascript { statusCode: 200, body: '{\"user\": \'${user_id}\"', status: \'${status}\'}' } ``` -------------------------------- ### Run Mountebank Source: https://github.com/mountebank-testing/mountebank/blob/master/README.md Command to run Mountebank after installation. ```bash mb ``` -------------------------------- ### Direct Response Type Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/response-resolver.md Example of a direct response configuration. ```json { "is": { "statusCode": 200, "headers": { "content-type": "text/plain" }, "body": "Hello, World!" } } ``` -------------------------------- ### TCP Server Create Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/tcp-server.md Example of creating a TCP server with custom options. ```javascript const tcpServer = require('./models/tcp/tcpServer.js'); const options = { port: 4000, host: 'localhost', mode: 'text', defaultResponse: { data: '' }, endOfRequestResolver: { inject: "function(requestData) { return true; }" // End after first packet } }; const server = await tcpServer.create(options, logger, async (request) => { return { data: 'ACK' }; }); console.log(`TCP server listening on port ${server.port}`); ``` -------------------------------- ### resolve Function Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/response-resolver.md Example of using the resolver.resolve function to get a response. ```javascript const responseConfig = { is: { statusCode: 200, headers: { 'content-type': 'application/json' }, body: '{"status": "ok"}' }, behaviors: [ { wait: 100 } ] }; const response = await resolver.resolve( responseConfig, request, logger, imposterState ); // Returns: // { // statusCode: 200, // headers: { 'content-type': 'application/json' }, // body: '{"status": "ok"}' // } ``` -------------------------------- ### Copy Behavior - Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md Example of copying the request path to the response body using regex. ```javascript { copy: { from: { path: true }, into: '${path}', using: { method: 'regex', selector: '^/([^/]+)' } } } ``` -------------------------------- ### Lookup Behavior Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md An alternative example of the 'lookup' behavior configuration, using a different key extraction method and data source path. ```javascript { lookup: { key: { from: 'query', using: { method: 'regex', selector: 'user=([^&]+)' } }, fromDataSource: { csv: { path: 'users.csv', keyColumn: 'name' } }, into: '${user_id}' } } ``` -------------------------------- ### Out-of-Process Execution Command Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/protocols.md Example of the 'createCommand' field for spawning a custom protocol process. ```javascript { createCommand: "node ./custom-protocol", // Command is executed as: node ./custom-protocol [JSON config] } ``` -------------------------------- ### State Management Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md Example of using the 'imposterState' object within a 'decorate' behavior to persist state across requests. ```javascript { decorate: ` function(request, response, behaviors, logger, imposterState) { imposterState.requestCount = (imposterState.requestCount || 0) + 1; response.headers['X-Request-Number'] = imposterState.requestCount; return response; } ` } ``` -------------------------------- ### Decorate Behavior - Advanced Example with State Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md Example of using the 'decorate' behavior with access to request, state, and logger. ```javascript { decorate: ` function(config, injectState, logger, done, imposterState) { // config.request - request // config.state - old state object (deprecated) // config.logger - logger // config.callback - done function // imposterState - current state return modified_response; } ` } ``` -------------------------------- ### Inject predicate example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/predicates.md Example of an inject predicate function that checks if the request path starts with '/api/v'. ```javascript { inject: ` function(request, logger) { logger.debug('Evaluating request: ' + request.path); return request.path.startsWith('/api/v'); } ` } ``` -------------------------------- ### Filesystem Repository Usage Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of creating a filesystem imposters repository. ```javascript const repository = repositoryModule.create({ datadir: './mountebank-data' }, logger); ``` -------------------------------- ### Complex Behavior Chain Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md A comprehensive example demonstrating a chain of behaviors including wait, copy, lookup, and decorate. ```javascript behaviors: [ { wait: 200 // Add latency }, { copy: { from: { query: { userId: true } }, into: '${userId}', using: { method: 'regex', selector: '(.+)' } } }, { lookup: { key: { from: 'body', using: { method: 'jsonpath', selector: '$.id' } }, fromDataSource: { csv: { path: 'data.csv', keyColumn: 'id' } }, into: '${userData}' } }, { decorate: ` function(request, response) { var body = JSON.parse(response.body); body.userId = '\'${userId}\''; body.data = '\'${userData}\''; body.timestamp = new Date().toISOString(); response.body = JSON.stringify(body, null, 2); response.headers['X-Modified'] = 'true'; return response; } ` } ] ``` -------------------------------- ### Wait Behavior Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/README.md Example of using the 'wait' behavior to introduce latency in responses. ```javascript { is: { statusCode: 200 }, behaviors: [{ wait: 500 }] } ``` -------------------------------- ### Binary Response Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/http-server.md Example of sending a binary response body encoded in base64. ```json { "statusCode": 200, "headers": { "content-type": "application/octet-stream" }, "body": "SGVsbG8gV29ybGQ=", // base64 encoded "Hello World" "_mode": "binary" } ``` -------------------------------- ### Decorate Behavior - Basic Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md Example of modifying response headers using the 'decorate' behavior. ```javascript { decorate: ` function(request, response) { // Modify response response.headers['X-Custom'] = 'Added by decorate'; return response; } ` } ``` -------------------------------- ### Loading Custom Protocol Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Command to start Mountebank with a custom protocol definition file. ```bash mb --protofile protocols.json ``` -------------------------------- ### matches predicate configuration Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/predicates.md Configuration example for the matches predicate. ```json { matches: { path: '/api/.*', body: '.*error.*' } } ``` -------------------------------- ### Custom Protocol Definition Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/protocols.md Example JSON configuration for a custom gRPC protocol. ```json { "grpc": { "createCommand": "node ./grpc-imposter", "testRequest": { "service": "com.example.Service", "method": "GetUser", "body": "" }, "testProxyResponse": { "service": "com.example.Service", "method": "GetUser", "statusCode": 200, "body": "" } } } ``` -------------------------------- ### GET /imposters Response Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/endpoints.md Example JSON response for the GET /imposters endpoint, showing a list of active imposters. ```json { "imposters": [ { "protocol": "http", "port": 3000, "name": "My API", "url": "/imposters/3000", "numberOfRequests": 42, "requests": [ { "method": "GET", "path": "/api/users", "headers": { "host": "localhost:3000" }, "query": { "id": "1" }, "body": "", "timestamp": "2024-01-15T10:30:00.000Z" } ], "stubs": [ { "predicates": [ { "equals": { "path": "/api/users", "method": "GET" } } ], "responses": [ { "is": { "statusCode": 200, "headers": { "content-type": "application/json" }, "body": "[{\"id\": 1, \"name\": \"Alice\"}]" } } ] } ], "_links": { "self": { "href": "/imposters/3000" }, "stubs": { "href": "/imposters/3000/stubs" } } } ] } ``` -------------------------------- ### getProxyResponseFor Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposter.md Shows an example of using getProxyResponseFor to process a proxy response received from a downstream server, including the downstream response object and a proxy resolution key. ```javascript // After proxy request completes and response arrives const downstreamResponse = { statusCode: 200, headers: { 'content-type': 'application/json' }, body: '[{"id": 1}]' }; const resolvedResponse = await imposter.getProxyResponseFor( downstreamResponse, 'key123' ); ``` -------------------------------- ### Imposter Object Methods: toJSON Examples Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposter.md Examples of how to use the toJSON method on an imposter object with different options. ```javascript // Get full imposter state const fullState = await imposter.toJSON(); // Get replayable configuration (without requests) const replayable = await imposter.toJSON({ replayable: true }); // Get without proxies const noProxies = await imposter.toJSON({ removeProxies: true }); ``` -------------------------------- ### Custom Repository Usage Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of creating a custom imposters repository. ```javascript const repository = repositoryModule.create({ impostersRepository: './custom-repository.js' }, logger); ``` -------------------------------- ### equals predicate configuration Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/predicates.md Configuration example for the equals predicate. ```json { equals: { headers: { 'content-type': 'application/json' } } } ``` -------------------------------- ### Protocol Implementation Request Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/endpoints.md Example request format for protocol implementations to get a response for a request. ```json { "request": { "method": "GET", "path": "/api/users", ... } } ``` -------------------------------- ### Order of Execution Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md Illustrates the order in which behaviors are executed within an array. ```javascript behaviors: [ { wait: 100 }, // Execute first { copy: { ... } }, // Execute second { decorate: "..." }, // Execute third { shellTransform: "..." } // Execute last ] ``` -------------------------------- ### Shell Transform Example Script Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md An example shell script that processes Mountebank request and response environment variables and outputs a modified JSON response. ```bash #!/bin/bash REQUEST=$(echo "$MB_REQUEST" | jq .) RESPONSE=$(echo "$MB_RESPONSE" | jq .) # Modify response MODIFIED=$(echo "$RESPONSE" | jq '.body |= . + " - modified"') echo "$MODIFIED" ``` -------------------------------- ### Injection Function Return Value Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/response-resolver.md Example demonstrating how to return a response directly or use the callback in an injection function. ```javascript inject: " function(request, state, logger, done, imposterState) { // Return directly return { statusCode: 200, body: 'response' }; // OR use callback done({ statusCode: 200, body: 'response' }); } " ``` -------------------------------- ### Decorate Behavior - Example with JSON Manipulation Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md Example of parsing JSON, adding a timestamp, and stringifying the response body using 'decorate'. ```javascript { decorate: ` function(request, response) { var json = JSON.parse(response.body); json.requestPath = request.path; json.timestamp = new Date().toISOString(); response.body = JSON.stringify(json, null, 2); return response; } ` } ``` -------------------------------- ### UnauthorizedError Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/errors.md Example of creating an UnauthorizedError. ```javascript const error = errors.UnauthorizedError(); ``` -------------------------------- ### DatabaseError Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/errors.md Example of creating a DatabaseError. ```javascript const error = errors.DatabaseError('Cannot write to data file'); ``` -------------------------------- ### ProtocolError Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/errors.md Example of creating a ProtocolError. ```javascript const error = errors.ProtocolError( 'Invalid configuration for protocol "grpc": cannot run "./grpc-server"', { source: './grpc-server', details: error } ); ``` -------------------------------- ### exists predicate configuration Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/predicates.md Configuration example for the exists predicate. ```json { exists: { query: true, // query object exists body: false // body does not exist } } ``` -------------------------------- ### CommunicationError Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/errors.md Example of creating a CommunicationError. ```javascript const error = errors.CommunicationError(undefined, { details: 'ECONNREFUSED' }); ``` -------------------------------- ### InvalidJSONError Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/errors.md Example of creating an InvalidJSONError. ```javascript const error = errors.InvalidJSONError({ source: '{invalid json}' }); ``` -------------------------------- ### deepEquals predicate configuration Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/predicates.md Configuration example for the deepEquals predicate. ```json { deepEquals: { method: 'POST', path: '/api/users', body: { name: 'Alice', age: 30 } } } ``` -------------------------------- ### Delete Imposter Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of deleting a specific imposter. ```javascript await repository.del(3000); console.log('Imposter on port 3000 deleted'); ``` -------------------------------- ### In-Memory Repository Usage Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of creating an in-memory imposters repository. ```javascript const repository = repositoryModule.create({}, logger); ``` -------------------------------- ### Recording from Live Service Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Starts Mountebank in mock mode to record requests while proxying to a live service. ```bash mb start \ --port 3000 \ --configfile imposters.json \ --mock # Record requests during proxy ``` -------------------------------- ### Switching to Replay Mode Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Saves recorded requests and then starts Mountebank in replay mode using the saved file. ```bash mb save --savefile recorded.json --removeProxies --port 3000 mb start --configfile recorded.json --port 3000 ``` -------------------------------- ### resolveProxy Function Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/response-resolver.md Example of using the resolver.resolveProxy function. ```javascript // Downstream service returns: const downstreamResponse = { statusCode: 200, headers: { 'content-type': 'application/json' }, body: '[{"id": 1}]' }; const resolved = await resolver.resolveProxy( downstreamResponse, 'proxy-key-123', logger, {} ); ``` -------------------------------- ### Complex Predicate Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/predicates.md An example demonstrating a complex predicate structure with AND and OR logic. ```javascript [ { and: [ { equals: { method: 'POST' } }, { or: [ { equals: { path: '/api/users' } }, { equals: { path: '/api/accounts' } } ] }, { jsonpath: { selector: '$.type' }, matches: { body: '.*"type":"premium".*' } } ] } ] ``` -------------------------------- ### Testing with File Persistence Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Starts Mountebank for testing with data stored in a specific directory and debug mode enabled. ```bash mb start \ --port 3000 \ --configfile test-imposters.json \ --datadir ./test-data \ --debug ``` -------------------------------- ### Injection Response Type Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/response-resolver.md Example of an injection response configuration. ```javascript { "inject": " function(request, state) { return { statusCode: 200, body: JSON.stringify({ timestamp: new Date().toISOString() }) }; } " } ``` -------------------------------- ### Execute Behaviors Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md Demonstrates how to use the `behaviors.execute` function with wait and decorate behaviors. ```javascript const behaviors = require('./models/behaviors.js'); const response = { statusCode: 200, body: '{\"id\": 1, \"name\": \"Original\"}' }; const behaviorConfig = [ { wait: 1000 // Wait 1 second }, { decorate: ` function(request, response) { response.body = JSON.parse(response.body); response.body.timestamp = new Date().toISOString(); response.body = JSON.stringify(response.body); return response; } ` } ]; const processedResponse = await behaviors.execute( request, response, behaviorConfig, logger, {} ); ``` -------------------------------- ### Proxy Response Type Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/response-resolver.md Example of a proxy response configuration. ```json { "proxy": { "to": "http://downstream.example.com", "predicateGenerators": [ { "matches": { "path": true, "method": true }, "caseSensitive": true } ], "addWaitBehavior": true, "mode": "proxyAlways" } } ``` -------------------------------- ### Create an HTTP Imposter Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposter.md This example demonstrates how to create an HTTP imposter with a basic stub. ```javascript const imposterModule = require('./models/imposter.js'); const httpServer = require('./models/http/httpServer.js'); const creationRequest = { protocol: 'http', port: 3000, name: 'My API Mock', recordRequests: false, stubs: [ { predicates: [ { equals: { path: '/api/users' } } ], responses: [ { is: { statusCode: 200, body: JSON.stringify([{ id: 1, name: 'Alice' }]) } } ] } ] }; const imposter = await imposterModule.create( httpServer, creationRequest, logger, { recordRequests: false }, (ip, log) => true ); console.log(`Imposter listening on port ${imposter.port}`); ``` -------------------------------- ### details Function Return Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/errors.md Example of the return value of the details function. ```javascript const error = new Error('Something failed'); error.code = 'test'; const serializable = errors.details(error); // { // code: 'test', // message: 'Something failed', // stack: '...', // name: 'Error' // } ``` -------------------------------- ### Validate Function Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/behaviors.md Example usage of the 'validate' function to check for invalid behavior configurations. ```javascript const errors = behaviors.validate({ wait: -100 // Invalid: negative }); if (errors.length > 0) { errors.forEach(error => console.log(error.message)); } ``` -------------------------------- ### Mountebank CLI Usage Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md The `mb` command is the primary entry point for Mountebank. ```bash mb [command] [options...] ``` -------------------------------- ### stop Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposter.md Demonstrates how to stop an imposter and close all its connections using the stop method. ```javascript await imposter.stop(); console.log('Imposter stopped'); ``` -------------------------------- ### Custom Protocol Definition Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Example JSON structure for defining a custom protocol (e.g., gRPC). ```json { "grpc": { "createCommand": "node ./grpc-imposter", "testRequest": { "service": "", "method": "", "body": "" }, "testProxyResponse": { "service": "", "method": "", "body": "" } } } ``` -------------------------------- ### evaluate function example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/predicates.md Example of using the evaluate function to check if a predicate matches a request. ```javascript const predicates = require('./models/predicates.js'); const predicate = { equals: { path: '/api/users', method: 'GET' } }; const request = { method: 'GET', path: '/api/users', query: {}, body: '' }; const matches = predicates.evaluate(predicate, request, 'utf8', logger); console.log(matches); // true ``` -------------------------------- ### Create Imposters Repository Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of creating an imposters repository with persistent storage and a logger. ```javascript const repositoryModule = require('./models/impostersRepository.js'); const repository = repositoryModule.create( { datadir: './mountebank-data', logger: logger }, logger ); // Add a new imposter await repository.add(imposter); // Get all imposters const allImposters = await repository.all(); // Delete an imposter await repository.del(port); ``` -------------------------------- ### Injection Behavior Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/README.md Example of using the 'inject' behavior for dynamic response generation. ```javascript { inject: " function(request) { return { statusCode: 200, body: JSON.stringify({ timestamp: new Date().toISOString(), path: request.path }) }; } " } ``` -------------------------------- ### Testing (Filesystem) Repository Configuration Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/imposters-repository.md Example of creating a Mountebank repository configured to use the filesystem for persistence. ```javascript const repository = repositoryModule.create({ datadir: './test-data' }, logger); ``` -------------------------------- ### State Management Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/response-resolver.md Demonstrates how the imposterState object is shared across requests to an imposter, allowing for stateful behavior like counting requests. ```javascript // Request 1 injectionResponse = ` function(request, state, logger, done, imposterState) { imposterState.requestCount = (imposterState.requestCount || 0) + 1; done({ statusCode: 200, body: imposterState.requestCount }); } `; // Request 2 // imposterState.requestCount will be 2 ``` -------------------------------- ### Binary Mode Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/tcp-server.md Configuration for Mountebank TCP server in binary mode. ```javascript const options = { port: 4000, mode: 'binary' }; // Request/Response data is base64 encoded // Example: 'SGVsbG8gV29ybGQ=' represents binary data ``` -------------------------------- ### Development with JavaScript Injection Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Starts Mountebank with JavaScript injection enabled, debugging enabled, and a specified config file. ```bash mb start \ --port 3000 \ --allowInjection \ --loglevel debug \ --configfile imposters.js ``` -------------------------------- ### Save Imposter Configuration Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/configuration.md Saves the current imposter configuration to a file. ```bash mb save [options...] ``` -------------------------------- ### Documentation Test Scenario - Using Change Element Source: https://github.com/mountebank-testing/mountebank/blob/master/CONTRIBUTING.md An example demonstrating the use of the 'change' element in documentation tests to handle dynamic data like ports. ```xml
curl -X DELETE http://localhost:2525/imposters/4545
curl -X DELETE http://localhost:2525/imposters/5555
``` -------------------------------- ### Custom Protocol Server Implementation (grpc-server.js) Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/protocols.md Example 'grpc-server.js' file for a custom gRPC protocol. ```javascript const config = JSON.parse(process.argv[2]); console.log(JSON.stringify({ port: config.port })); // Start gRPC server on config.port // Handle callbacks to http://{host}/imposters/{port}/_requests ``` -------------------------------- ### Spawned Process Output Example Source: https://github.com/mountebank-testing/mountebank/blob/master/_autodocs/api-reference/protocols.md The JSON object that a spawned custom protocol process should output to stdout. ```javascript { port: number, // Actual port if different encoding: string, // 'utf8' or 'base64' // ... protocol-specific metadata } ```