Repository: CyberAgent/node-easymock
Branch: master
Commit: edee190c6989
Files: 62
Total size: 66.7 KB
Directory structure:
gitextract_gdmbmqx0/
├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── bin/
│ └── easymock
├── index.js
├── lib/
│ ├── access_log.js
│ ├── config.json
│ ├── easymock.js
│ ├── static/
│ │ ├── documentation.css
│ │ └── documentation.js
│ └── views/
│ ├── documentation.jade
│ ├── layout.jade
│ └── logs.jade
├── package.json
└── test/
├── cors.test.coffee
├── documentation.test.coffee
├── errors.test.coffee
├── jsonp.test.coffee
├── lag.test.coffee
├── logs.test.coffee
├── mock.test.coffee
├── mock_data/
│ ├── .test1_get.json.test
│ ├── _errors/
│ │ ├── general.json
│ │ └── test.json
│ ├── _templates/
│ │ ├── Nested.json
│ │ ├── Nested2.json
│ │ ├── Object1.json
│ │ ├── ObjectWithParam.json
│ │ └── ObjectWithParams.json
│ ├── config.json
│ ├── config_with_cors.json
│ ├── config_with_error_rate_zero.json
│ ├── config_with_errors.json
│ ├── config_with_general_errors.json
│ ├── config_with_general_errors_own_rates.json
│ ├── config_with_jsonp.json
│ ├── config_with_lag.json
│ ├── config_with_lag_object.json
│ ├── config_with_random_lag.json
│ ├── groups/
│ │ ├── groupid/
│ │ │ ├── show_get.json
│ │ │ └── users/
│ │ │ └── userid_get.json
│ │ └── groupid_get.json
│ ├── groups_get.json
│ ├── proxy_get.json
│ ├── redirect_get.json
│ ├── test1_get.json
│ ├── test1_patch.json
│ ├── test1_post.json
│ ├── test2.json
│ ├── test_headers_get.json
│ ├── with_error_get.json
│ ├── with_error_rate_get.json
│ ├── with_template_get.json
│ ├── with_template_param_get.json
│ ├── with_template_params_get.json
│ ├── with_variable_HOST_get.json
│ ├── with_variable_QUERY_STRING_get.json
│ ├── with_variable_get.json
│ └── with_variable_within_variable_get.json
└── utils.coffee
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.DS_Store
.idea
node_modules/
lib-cov/
coverage.html
access_logs.db
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- "0.10"
================================================
FILE: LICENSE
================================================
(MIT License)
Copyright (C) 2012 CyberAgent
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.
================================================
FILE: Makefile
================================================
TESTS = $(shell find test -name "*.test.coffee")
REPORTER = dot
tests:
@NODE_ENV=testing ./node_modules/.bin/mocha --compilers coffee:coffee-script --reporter $(REPORTER) $(TESTS)
test-cov: lib-cov
@EASYMOCK_COV=1 $(MAKE) tests REPORTER=html-cov > coverage.html
lib-cov:
@jscoverage lib lib-cov
clean:
rm -R lib-cov
rm coverage.html
================================================
FILE: README.md
================================================
# EasyMock Server
## Usage
$ npm install -g easymock
$ easymock
## Files
All files from the running folder are present as static files. So place anything in there and it is accessible with GET filename.
### Differentiating GET/POST/PUT/PATCH/DELETE
If you want to use advanced serving features like GET/POST/PUT/PATCH/DELETE or templates in json, provide files like in the example below:
GET /items/1 => items/1_get.json
POST /items/1 => items/1_post.json
...
## config.json
If you want to configure routes, proxy or lag, create a config.json file which looks kind of like this:
{
"simulated-lag": 1000,
"cors": false,
"jsonp": false,
"proxy": {
"server": "http://yourrealapi.com",
"default": false,
"calls": {
"/items/1": { "get": true, "post": false },
"/items": false
}
},
"variables": {
"name": "My name"
},
"routes": [
"/user/:userid",
"/user/:userid/profile",
"/user/:userid/inbox/:messageid"
]
}
### Simulating lag in responses
To add the same lag to all responses, set simulated-lag to a number.
{
"simulated-lag": 1000
}
If you want a random lag in responses, like in a real-world scenario, set
simulated-lag-min and simulated-lag-max instead of simulated-lag. If
simulated-lag is set, it will take precedence over simulated-lag-min and -max.
#### Changing the simulated lag based on the path
For more fine-grained control over lag in responses, specify an object for
simulated-lag, as in the following example:
```
{
"simulated-lag": {
"default": 500,
"paths": [
{
"match": "^/users$",
"lag": 1000
},
{
"match": "^/users/.*",
"lag": 2000
},
{
"match": "no-lag",
"lag": 0
}
]
}
}
```
Each "match" value is turned into a regular expression (using `new RegExp`) and
matched against the request path (which excludes the query string). The first
match found in the "paths" array is the one used, so be careful with the order.
### Variables
Variables that you define in your config.json can be used in files that have the \_get/\_post/... extension. As well you can use them in your templates.
Nested variables support: #{name_#{lang}} will resolve to #{name_de} for #{lang} = 'de' (if given as GET or POST parameter for example).
Following variables are available by default:
- `#{HOST}` -> Requested hostname (and port) of the request. For example ```localhost:3000``` or ```127.0.0.1```
- `#{QUERY_STRING}` -> Complete query string of the request. For example ```foo=bar``` or ```a=b&c=d```
Example to use variables. item_get.json:
{ "user_name": "#{name}", "image": "http://#{HOST}/img.jpg"}
This will return:
{ "user_name": "#{user_name", "image": "http://localhost/img.jpg"}
## GET query and POST body fields as Variables
Any field given in GET or POST can be used like other variables.
Example: GET /search?q=test
Will provide you with a usable ```#{q}``` in your json file.
## Header fields as variables
Any header can be used as a variable. For example the header Accept-Language can be accessed via ```#{HEADER_ACCEPT_LANGUAGE}```.
### Routes
The routes defined in the config.json will get mapped to one corresponding file in which the given name will be available as a variable.
With the above config.json a call to GET /user/1234 would get mapped to the file: /user/userid_get.json. Inside that file one could write:
{ "id": #{userid} }
If this is the file, the result would be ```{ "userid": 1234 }```
## Templates
If you have items that are used over and over again, you can make templates for them and reuse the same template.
For that create a folder ```_templates``` and in it place for example a file object.json:
{ "name": "my object" }
Then you can refer this template out of another file like items_get.json:
[ "{{object}}", "{{object}}", "{{object}}", "{{object}}" ]
This will return a array with four times the object from the template.
### Parameters
You can even use parameters. For example you have a template Object.json:
{
"name": "Item #{_1}",
"image": "#{server}/img/img_#{_2}.jpg",
"active": #{_3}
}
And then a api object called items_get.json:
[
"{{Object(1,one,true)}}",
"{{Object(2,two,false)}}",
"{{Object(3,three,true)}}"
]
You will receive the following response:
[
{
"name":"Item 1",
"image":"http://server.com/img/img_one.jpg",
"active":true
},
{
"name":"Item 2",
"image":"http://server.com/img/img_two.jpg",
"active":false
},
{
"name":"Item 3",
"image":"http://server.com/img/img_three.jpg",
"active":true
}
]
## Response headers
You can specify the status code for the response with @status and add headers with @header. The following example is for doing a redirect response.
< @status 301
< @header Location: http://www.cyberagent.co.jp
Will respond with:
HTTP/1.1 301 Moved Permanently
x-powered-by: Express
location: http://www.cyberagent.co.jp
content-type: text/html; charset=utf-8
content-length: 0
date: Tue, 12 Mar 2013 08:21:39 GMT
connection: close
## Documentation
easymock automatically documents the API it represents. This documentation can be extended by adding additional information like description, input info and output info to the json file. This is an example on how to do that for example in test_post.json:
# This is some documentation
# This call creates an object
> @param name
> @param description (optional)
> @body {
> @body "name": "Nobody"
> @body }
< @status 200
< @header Content-Type: application/json
{
"id": 1234,
"name": "your name",
"description": "your description"
}
Explanation:
- ```#``` Is general information about the call.
- ```>``` About the request to the API.
- ```<``` About the response from the API.
- Everything afterwards is the response body.
To add some general information in the documentation, add a file ```_documentation/index.md```. That one will be shown at the top of the documented calls.
## Logging
All requests get logged and can be inspected. You can do so at http://localhost:3000/_logs/.
## CORS and JSONP
Can be enabled by setting either "jsonp" or "cors" or both to true in the config.json.
## Errors
Easymock can return errors defined in the documentation. the config.json set "error-rate": 0.5, to have a 50% error rate. So one out of 2 calls in average will return an error.
To specify an error, first add a error json file in \_errors. For example "\_errors/not\_authenticated.json":
< @status 401
{
"error": "Authentication required"
}
In the mock file add an error like the following (example user.json):
< @error sample
< @error sample2
< @error sample3 0.5
If there are multiple errors like above, it will randomly select one. By default it uses the ```error-rate``` specified in the config.json. A specific error rate for each error can be set by adding the error rate as shown above.
The name after @error indicates the file name. "@error sample" will serve "\_errors/sample.json".
### General errors
For errors that can occur on any call, set up the config.json as follows:
{
"error-rate": 1,
"errors" : ["general"]
}
Or to have specific error rates on each general error:
{
"error-rate": 0,
"errors" : [
{
"name": "general",
"rate": 0.1
},{
"name": "general2",
"rate": 0.3
}
]
}
## Run tests
make tests
## License
(MIT License)
Copyright (C) 2012 CyberAgent
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.
================================================
FILE: bin/easymock
================================================
#!/usr/bin/env node
var program = require('commander');
program
.version(require('../package').version)
.option('-p, --port [port]', 'Set port. Default is 3000.', 3000)
.option('-d, --path [directory]', 'Default directory where mocks are located.', process.cwd())
.parse(process.argv);
var MockServer = require('../index').MockServer;
var options = {
port: parseInt(program.port),
path: program.path,
requestLogger: function(req) {
console.log(req.method + ' ' + req.path + ' ==> ' + (req.proxied ? 'Proxy' : req.info.file));
}
};
var mock = new MockServer(options);
mock.start();
var serverUrl = 'http://localhost:' + mock.options.port;
console.log('Server running on ' + serverUrl);
console.log('Listening on port ' + mock.options.port + ' and ' + (mock.options.port + 1));
console.log('Documentation at: ' + serverUrl + '/_documentation/');
console.log('Logs at: ' + serverUrl + '/_logs/');
================================================
FILE: index.js
================================================
module.exports = process.env.EASYMOCK_COV
? require('./lib-cov/easymock')
: require('./lib/easymock');
================================================
FILE: lib/access_log.js
================================================
/*global require:true, exports:true */
var sqlite3 = require('sqlite3');
var _ = require('underscore');
function AccessLog(config) {
this.db = new sqlite3.Database(config.access_log || 'access_logs.db');
this.ensureCreation();
}
var extractRequestHeaders = function(req) {
var result = req.method + ' ' + req.url + ' HTTP/' + req.httpVersion + '\n';
result += _.map(_.pairs(req.headers), function(pair) {
return pair[0] + ': ' + pair[1];
}).join('\n');
return result;
};
var extractResponseHeaders = function(res) {
return _.map(_.pairs(res._headers), function(pair) {
return res._headerNames[pair[0]] + ': ' + pair[1];
}).join('\n');
};
AccessLog.prototype.insertDb = function(req, resStatus, resHeaders, resBody) {
if (req.url === '/favicon.ico') { return; }
var requestHeaders = extractRequestHeaders(req);
var requestBody = undefined;
if (req.headers['content-length'] && typeof(req.body) === 'object') {
requestBody = JSON.stringify(req.body, null, 2);
}
if (typeof(resBody) === 'object') {
resBody = JSON.stringify(resBody);
}
this.db.run('INSERT INTO logs ' +
'(client, request_method, request_path, request_headers, request_body, response_status, response_headers, response_body) ' +
'VALUES (?,?,?,?,?,?,?,?)', [ req.connection.remoteAddress, req.method.toUpperCase(), req.url, requestHeaders, requestBody, resStatus, resHeaders, resBody ]);
};
AccessLog.prototype.ensureCreation = function(callback) {
this.db.run('CREATE TABLE IF NOT EXISTS logs (' +
'_id INTEGER PRIMARY KEY AUTOINCREMENT,' +
'time DATETIME DEFAULT CURRENT_TIMESTAMP,' +
'client TEXT,' +
'request_method TEXT,' +
'request_path TEXT,' +
'request_headers TEXT,' +
'request_body TEXT,' +
'response_status INTEGER,' +
'response_headers TEXT,' +
'response_body TEXT' +
')', callback);
};
AccessLog.prototype.insert = function(req, status, body) {
var responseHeaders = extractResponseHeaders(req.res);
this.insertDb(req, status, responseHeaders, body);
};
AccessLog.prototype.insertProxy = function(req) {
this.insertDb(req, 0, 'PROXY', 'PROXY');
};
AccessLog.prototype.getLogs = function(callback) {
this.db.all('SELECT *, strftime("%s", "time") AS timestamp FROM logs ORDER BY _id DESC LIMIT 100', function(err, rows) {
rows = _.map(rows, function(row) {
row.isProxied = function() {
return this.response_status === 0;
};
return row;
});
callback(err, rows);
});
};
AccessLog.prototype.clear = function(callback) {
this.db.run('DELETE FROM logs;', callback);
};
exports.AccessLog = AccessLog;
================================================
FILE: lib/config.json
================================================
{
"simulated-lag": 0
}
================================================
FILE: lib/easymock.js
================================================
/*global require:true, exports:true, __dirname:true, process:true */
var express = require('express');
var bodyParser = require('body-parser');
var typeis = require('type-is'); // pulled in with body-parser
var fs = require('fs');
var url = require('url');
var httpProxy = require('http-proxy');
var _ = require('underscore');
var marked = require('marked');
var AccessLog = require('./access_log').AccessLog;
require('broware');
var TEMPLATE_PATTERN = new RegExp(/"?\{\{([a-zA-Z0-9\-_]+)(\([^()]+\))?\}\}"?/g);
var VARIABLE_PATTERN = new RegExp(/#\{[a-zA-Z0-9\-_]+\}/g);
var PARAM_PATTERN = new RegExp(/#\{_([1-9][0-9]*)\}/g);
exports.version = require('../package').version;
function MockServer(options) {
this.options = options;
this.ensureOptions();
if (this.options.log_enabled) {
this.log = new AccessLog(this.readConfig());
}
}
MockServer.prototype.start = function() {
this.startMock();
this.startProxy();
};
MockServer.prototype.stop = function() {
this.mock_server.close();
this.proxy_server.close();
};
MockServer.prototype.ensureOptions = function() {
if (!this.options) {
this.options = {};
}
if (this.options.log_enabled === undefined) {
this.options.log_enabled = true;
}
this.options.port = this.options.port || 3000;
this.options.path = this.options.path || process.cwd();
if (this.options.path.indexOf('/', this.options.path.length - 1) == -1) {
this.options.path += '/';
}
this.options.config = this.options.config || this.options.path + '/config.json';
// Use default config if none is provided
if (_.isString(this.options.config) && !fs.existsSync(this.options.config)) {
this.options.config = __dirname + '/config.json';
}
};
MockServer.prototype.readConfig = function() {
var now = new Date().getTime();
if (!this.config_last_read || this.config_last_read < now - 2000) {
this.config_last_read = now;
var config;
if (_.isString(this.options.config)) {
config = JSON.parse(fs.readFileSync(this.options.config, 'utf8'));
} else {
config = _.clone(this.options.config);
}
if (config.routes) {
var regexp = /:[a-zA-Z_]*/g;
config.routes = _.map(config.routes, function(route) {
var match;
var params = [];
while (match = regexp.exec(route)) {
params.push(match[0].substr(1));
}
var route2 = {
route: route.replace(regexp, '*'),
matcher: new RegExp('^' + route.replace(regexp, '([^/\?]+)').replace(/([\/\?\*\-])/g, '\\$1') + '$'),
path: route.replace(/:/g, ''),
params: params
};
return route2;
});
}
this.config = config;
}
return this.config;
};
//////////////
// MOCK SERVER
//////////////
MockServer.prototype.startMock = function() {
var app = express();
app.set('mock', this);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
if (this.readConfig().cors) {
app.use(this.allowCrossDomain);
}
app.use(function(req, res, next) {
// If multipart form, ignore rawbody.
// TODO instead just add the parameters and ignore the files
var contentType = req.headers['content-type'] || "";
if (contentType.indexOf('multipart/form-data') == 0) {
req.rawBody = '';
// req.setEncoding('utf8');
req.on('data', function(chunk) { req.rawBody += chunk; });
}
next();
});
app.use(bodyParser.json({
type: function(req) {
return Boolean(typeis(req, 'application/json'))
|| Boolean(typeis(req, 'application/vnd.api+json'));
}
}));
app.locals.moment = require('moment');
app.use('/_documentation', express.static(__dirname + '/static'));
app.use('/_logs', express.static(__dirname + '/static'));
app.get('/_documentation/', this.getApiDocumentation);
app.get('/_logs/', this.getLogs);
app.get('/_documentation.json', this.getApiDocumentationJson);
app.get('/_documentation', this.getApiDocumentationJson);
app.get('*', this.handleAnyRequest);
app.post('*', this.handleAnyRequest);
app.delete('*', this.handleAnyRequest);
app.put('*', this.handleAnyRequest);
app.patch('*', this.handleAnyRequest);
this.mock_server = app.listen(this.options.port + 1);
};
function findMatchingLag(lagconfig, path) {
if (_.isEmpty(lagconfig.paths)) {
return lagconfig.default || 0;
}
for (var i = 0; i < lagconfig.paths.length; i++) {
// Convert the match string to a RegExp object.
var pathobj = lagconfig.paths[i];
if (new RegExp(pathobj.match).test(path)) {
return pathobj.lag || 0;
}
}
return lagconfig.default;
}
MockServer.prototype.generateLag = function(requestPath) {
var config = this.readConfig();
var lag = config['simulated-lag'];
if (typeof(lag) === 'number') {
// Fixed lag.
return lag;
} else if (typeof(lag) === 'object') {
return findMatchingLag(lag, requestPath);
}
var lagMax = config['simulated-lag-max'];
var lagMin = config['simulated-lag-min'];
if(lagMax || lagMin) {
lagMax = lagMax || 40000;
lagMin = lagMin || 0;
var lagRandom = Math.round(Math.random() *(lagMax -lagMin) +lagMin);
return lagRandom;
}
return 0;
}
MockServer.prototype.startProxy = function() {
var self = this;
this.proxy_server = httpProxy.createServer(function (req, res, proxy) {
var reqUrl = url.parse(req.url);
if (self.options.requestLogger) {
self.options.requestLogger({
method: req.method,
path: reqUrl.pathname,
proxied: self.shouldProxy(req) || false,
info: self.getRequestInfo(req)
});
}
if (self.options.log_enabled && self.shouldProxy(req)) {
self.log.insertProxy(req);
}
var buffer = httpProxy.buffer(req);
setTimeout(function () {
if (self.shouldProxy(req)) {
var parsedUrl = url.parse(self.readConfig().proxy.server);
var port = 80;
if (parsedUrl.port) {
port = parsedUrl.port;
} else if (self.readConfig().proxy.port) {
port = self.readConfig().proxy.port;
}
req.headers.host = parsedUrl.hostname;
proxy.proxyRequest(req, res, {
host: parsedUrl.hostname,
port: port,
buffer: buffer
});
} else {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: self.options.port + 1,
buffer: buffer
});
}
}, self.generateLag(reqUrl.pathname));
}).listen(this.options.port);
};
/**
* @param on {string} current url
* @param route {Object} route regexp to match the url against
* @return {?Object}
*
* @description
* Check if the route matches the current url.
*
* Inspired by match in
* visionmedia/express/lib/router/router.js.
* angular-router.js.
*/
function pathRegExp(path, opts) {
var insensitive = opts.caseInsensitiveMatch,
ret = {
originalPath: path,
regexp: path
},
keys = ret.keys = [];
path = path
.replace(/([().])/g, '\\$1')
.replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) {
var optional = option === '?' ? option : null;
var star = option === '*' ? option : null;
keys.push({ name: key, optional: !!optional });
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (star && '(.+?)' || '([^/]+)')
+ (optional || '')
+ ')'
+ (optional || '');
})
.replace(/([\/$\*])/g, '\\$1');
ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
return ret;
}
function switchRouteMatcher(on, route) {
var keys = route.keys,
params = {};
if (!route.regexp) return null;
var m = route.regexp.exec(on);
if (!m) return null;
for (var i = 1, len = m.length; i < len; ++i) {
var key = keys[i - 1];
var val = m[i];
if (key && val) {
params[key.name] = val;
}
}
return params;
}
/**
* Call either with shouldProxy(req) or shouldProxy(path, method).
*/
MockServer.prototype.shouldProxy = function(path, method) {
if (typeof(path) === 'object' && !method) {
// path == req
method = path.method;
path = url.parse(path.url).pathname;
}
method = method.toLowerCase();
// always remove .json
if (path.substr(-5) === '.json') {
path = path.substr(0, path.length - 5);
}
var config = this.readConfig();
if (config.proxy) {
var defaultProxy = config.proxy['default'] || false;
if (config.proxy.calls) {
var entry, router;
for (var prop in config.proxy.calls) {
entry = config.proxy.calls[prop];
router = pathRegExp(prop, { caseInsensitiveMatch : false} );
if (switchRouteMatcher(path, router)) {
if (_.isObject(entry)) {
return _.isBoolean(entry[method]) ? entry[method] : defaultProxy;
}
if (_.isBoolean(entry)) {
return entry;
}
}
}
} else {
return defaultProxy;
}
} else {
return false;
}
};
MockServer.prototype.allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// intercept OPTIONS method
if ('OPTIONS' === req.method) {
res.send(200);
}
else {
next();
}
};
MockServer.prototype.handleAnyRequest = function(req, res){
var mock = res.app.set('mock');
var info = mock.getRequestInfo(req);
info.params = _.extend(info.params||{}, req.query);
info.params = _.extend(info.params||{}, req.body);
info.params = _.extend(info.params||{}, mock.headersToParams(req.headers));
if (!fs.existsSync(info.file)) {
var staticFile = mock.options.path + url.parse(req.url).pathname;
if (fs.existsSync(staticFile)) {
if (mock.options.log_enabled) {
mock.log.insert(req, 200, 'File contents');
}
return res.sendfile(staticFile);
} else {
if (mock.options.log_enabled) {
mock.log.insert(req, 404, '');
}
return res.send(404);
}
}
var data = mock.readFile(info.file, {params: info.params});
var body = '';
var config = mock.readConfig();
var error = undefined;
if (data.response.errors.length !== 0) {
var selectedErrors = [];
var selectRate = Math.random();
for (var i=0; i<data.response.errors.length; i++) {
var e = data.response.errors[i];
if (e.rate > selectRate) {
selectedErrors.push(e);
}
}
if (selectedErrors.length !== 0) {
error = selectedErrors[Math.floor(Math.random() * selectedErrors.length)];
}
}
if (mock.isJson(data.response.body)) {
body = error ? JSON.parse(error.response.body) : JSON.parse(data.response.body);
if (config.jsonp && (req.param('callback') || req.param('jsonp'))) {
var functionName = req.param('callback') || req.param('jsonp');
res.setHeader('Content-Type', 'application/javascript');
body = functionName + '(' + JSON.stringify(body) + ');';
}
}
var statusCode = error ? error.response.status : data.response.status;
res.set(data.response.headers);
if (mock.options.log_enabled) {
mock.log.insert(req, statusCode, body);
}
res.send(statusCode, body);
};
MockServer.prototype.headersToParams = function(headers) {
var params = {};
for (var key in headers) {
if (headers.hasOwnProperty(key)) {
params['HEADER_'+key.replace(/\-/g, '_').toUpperCase()] = headers[key];
}
}
return params;
};
// getRequestInfo(req)
// getRequestInfo(method, path, args)
MockServer.prototype.getRequestInfo = function(arg1, arg2, args) {
var method, pathname;
if (typeof(arg1) === 'object') {
var reqUrl = url.parse(arg1.url);
pathname = reqUrl.pathname;
if (pathname.substr(-5) === '.json') {
pathname = pathname.substr(0, pathname.length - 5);
}
method = arg1.method.toLowerCase();
args = {host:arg1.headers.host, query_string:reqUrl.query};
} else {
method = arg1.toLowerCase();
pathname = arg2;
}
var info = {
file: this.combinePath(this.options.path, pathname),
params: {}
};
if (args && args.host) {
info.params.HOST = args.host;
}
if (args && args.query_string) {
info.params.QUERY_STRING = args.query_string;
}
var config = this.readConfig();
if (config && config.routes) {
for (var i = 0; i < config.routes.length; i++) {
var route = config.routes[i];
var match = route.matcher.exec(pathname);
if (match) {
info.file = this.options.path + route.path;
info.params = info.params || {};
info.route = route;
for (var j = 1; j < match.length; j++) {
var paramName = route.params[j-1];
info.params[paramName] = match[j];
}
break;
}
}
}
// if file request ends with '/' then we check if that file exists
// or if we should fallback to it without '/'
if (info.file.indexOf('/', info.file.length - 1) === -1
|| fs.existsSync(info.file+ '_' + method + '.json')) {
info.file = info.file + '_' + method + '.json';
} else {
info.file = info.file.substr(0, info.file.length - 1) + '_' + method + '.json';
}
return info;
};
MockServer.prototype.combinePath = function(basePath, path) {
if (path && path.charAt(0) == '/') {
return basePath + path.substr(1, path.length);
} else {
return basePath + path
}
}
MockServer.prototype.readFileJson = function(file, options) {
var data = fs.readFileSync(file, 'utf8');
data = this.extendJsonContent(data, options);
return data;
}
MockServer.prototype.extendJsonContent = function(data, options) {
if (!options) { options = {} };
if (!options.params) { options.params = {} };
var self = this;
var config = self.readConfig();
var updatedVariables;
do {
updatedVariables = false;
data = data.replace(VARIABLE_PATTERN, function(match) {
updatedVariables = true;
if (options && options.args) {
var matcher = new RegExp(PARAM_PATTERN).exec(match);
if (matcher !== null) {
var index = parseInt(matcher[1], 10) - 1;
if (index > options.args.length - 1) {
return 'undefined';
}
return options.args[index];
}
}
var varName = match.slice(2,-1);
// replace varName
if (options.params && options.params[varName]) {
return options.params[varName];
}
if (config.variables && config.variables[varName]) {
return config.variables[varName];
}
return varName; // if variable not found, replace #{variable} with "variable"
});
} while (updatedVariables);
data = data.replace(TEMPLATE_PATTERN, function(match) {
var matcher = TEMPLATE_PATTERN.exec(match);
var templateName = matcher[1];
var args = matcher[2];
if (args) {
args = args.slice(1, -1).split(',');
}
var templateFile = self.options.path + '/_templates/' + templateName + '.json';
options = _.clone(options);
options.args = args;
return self.readFile(templateFile, options).response.body;
});
return data;
}
MockServer.prototype.readFile = function(file, options) {
var self = this;
var data = fs.readFileSync(file, 'utf8');
var input = [];
var inputBody = [];
var output = [];
var description = [];
var status = 200;
var headers = {};
var errors = [];
var descriptionInsidePre = false;
data = data.replace(/^(<|>|#) .*$/gm, function(item) {
var firstChar = item.length > 0 ? item.charAt(0) : '?';
if (firstChar === '#') {
if (item.indexOf('<pre>') >= 0) {
descriptionInsidePre = true;
} else if (item.indexOf('</pre>') >= 0) {
descriptionInsidePre = false;
}
description.push(item.substr(2) + (descriptionInsidePre ? '':'<br />'));
} else if (firstChar === '>') {
if (item.indexOf('@body') === 2) {
inputBody.push(item.substr(8));
} else {
input.push(item.substr(2));
}
} else if (firstChar === '<') {
output.push(item.substr(2));
switch(item.substr(2,7)) {
case '@status':
status = parseInt(item.substr(10));
break;
case '@header':
var pos = item.indexOf(':');
var name = item.substr(10, pos-10);
var value = item.substr(pos + 2);
headers[name] = value;
break;
case '@error ':
var items = item.split(' ');
var rate = items.length > 3 ? parseFloat(items[3]) : self.readConfig()['error-rate'];
errors.push({file: '_errors/' + items[2] + '.json', rate: rate});
break;
}
}
return '';
});
if (!options.ignoreErrors) {
// add general errors
var generalErrors = self.readConfig()['errors'];
if (generalErrors && generalErrors.length > 0) {
var generalRate = self.readConfig()['error-rate'];
_.each(generalErrors, function(item) {
var error;
if (typeof(item) === 'object') {
error = { file: "_errors/" + item.name + ".json", rate: item.rate ? item.rate : generalRate };
} else {
error = { file: "_errors/" + item + ".json", rate: generalRate };
}
errors.push(error);
});
}
options.ignoreErrors = true;
errors = _.map(errors, function(error) {
var newError = self.readFile(self.options.path + error.file, options);
newError.name = error.file.substr(error.file.lastIndexOf('/') + 1).replace('.json', '');
newError.rate = error.rate;
delete newError.file;
delete newError.input;
delete newError.inputBody;
delete newError.response.errors;
return newError;
});
options.ignoreErrors = false;
}
data = this.extendJsonContent(data.trim(), options);
return {
file: file,
description: description.join('\n'),
input: input,
inputBody: this.extendJsonContent(inputBody.join('\n'), options),
output: output,
response: {
status: status,
headers: headers,
errors: errors,
body: data
}
};
};
MockServer.prototype.isJson = function(data) {
return data && data.length > 0 && (data[0] === '{' || data[0] === '[');
}
MockServer.prototype.prettifyJson = function(json) {
if (this.isJson(json)) {
try {
return JSON.stringify(JSON.parse(json), null, 2);
} catch(e) {
return "ERROR: " + e + '\n' + json;
}
}
return json;
}
MockServer.prototype.getApiDocumentationJson = function(req, res) {
res.app.set('mock').getApiDocumentationJsonInternal({host:req.headers.host}, function(err, apiDocumentation) {
if (err) { return res.send(400, err); }
res.send(apiDocumentation);
});
}
// TODO refactor this (maybe own class for documentation generation based on a MockServer)
MockServer.prototype.getApiDocumentationJsonInternal = function(args, callback) {
var that = this;
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) { return done(err); }
var i = 0;
(function next() {
var file = list[i++];
if (!file) { return done(null, results); }
file = dir + '/' + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
};
var getCallMethod = function(file) {
if (~file.indexOf('_get.json')) {
return 'GET';
}
if (~file.indexOf('_post.json')) {
return 'POST';
}
if (~file.indexOf('_put.json')) {
return 'PUT';
}
if (~file.indexOf('_delete.json')) {
return 'DELETE';
}
if (~file.indexOf('_patch.json')) {
return 'PATCH';
}
return undefined;
};
var folder = this.options.path;
walk(folder, function(err, results) {
results = _.filter(results, function(file) {
if (!/\.json$/.test(file)) {
return false;
}
if (getCallMethod(file)) {
return true;
}
return false;
});
results = _.map(results, function(file) {
var method = getCallMethod(file);
var path = file.substr(folder.length, file.lastIndexOf('_') - folder.length);
var requestInfo = that.getRequestInfo(method, path, args);
if (requestInfo && requestInfo.route) {
path = requestInfo.route.route;
for (var i = 0; i < requestInfo.route.params.length; i++) {
var key = requestInfo.route.params[i];
path = path.replace('*', ':' + requestInfo.route.params[i]);
requestInfo.params[key] = 1;
}
}
var callInfo = that.readFile(requestInfo.file, {params: requestInfo.params});
return {
method: method,
path: path,
description: callInfo.description,
input: callInfo.input,
inputBody: that.prettifyJson(callInfo.inputBody),
output: callInfo.output,
errors: callInfo.response.errors,
response: that.prettifyJson(callInfo.response.body),
proxy: that.shouldProxy(path, method)
};
});
var getWeightForMethod = function(method) {
var m = method.toLowerCase();
if (m === 'get') {
return 0;
} else if (m === 'post') {
return 1;
} else if (m === 'put') {
return 2;
} else if (m === 'delete') {
return 3;
} else if (m === 'patch') {
return 4;
} else {
return 999;
}
};
results = _.sortBy(results, function(item) { return item.path + '/' + getWeightForMethod(item.method); } );
callback(null, results);
});
};
MockServer.prototype.getApiDocumentation = function(req, res) {
var api, general;
function getDocumentation() {
var mock = res.app.set('mock');
mock.getApiDocumentationJsonInternal({host:req.headers.host}, function(err, apiDocumentation) {
if (err) { return res.send(400, err); }
api = _.map(apiDocumentation, function(item) {
item.classes = item.method.toLowerCase();
return item;
});
getGeneralDocumentation();
});
}
function getGeneralDocumentation() {
var file = res.app.set('mock').options.path + "/_documentation/index.md";
if (fs.existsSync(file)) {
general = fs.readFileSync(file, 'utf8');
}
getDocumentationHtml();
}
function getDocumentationHtml(documentation) {
if (general) {
general = marked(general);
}
res.render('documentation', {title: 'API Documentation', calls: api, general: general});
}
getDocumentation();
};
MockServer.prototype.getLogs = function(req, res) {
var mock = res.app.set('mock');
if (!mock.options.log_enabled) {
return res.send(400, "log_disabled");
}
mock.log.getLogs(function(err, logs) {
if (err) { return res.send(400, err); }
logs = _.map(logs, function(log) {
if (log.response_body &&
log.response_body.length > 0 &&
(log.response_body.charAt(0) === '{' || log.response_body.charAt(0) === '[')) {
log.response_body = JSON.stringify(JSON.parse(log.response_body), null, 2);
}
return log;
});
res.render('logs', {title: 'Access Logs', logs: logs});
});
};
exports.MockServer = MockServer;
================================================
FILE: lib/static/documentation.css
================================================
body {
margin: 5px;
font-family: Helvetica, sans-serif;
}
h1,h2,h3,h4,h5 {
}
ul, li {
margin: 0;
padding: 0;
list-style-type: none;
}
.head, .head label {
cursor: pointer;
}
.head:hover {
background: #cccccc;
}
.head.general {
font-size: 24px;
font-weight: bold;
padding: 5px;
}
.right {
float: right;
}
label.client, label.status {
margin-right: 10px;
}
label.method {
min-width: 80px;
display: inline-block;
text-align: center;
margin-right: 5px;
color: #ffffff;
}
.get label.method {
background: #5DADE2;
}
.post label.method {
background: #239B56;
}
.put label.method {
background: #58D68D;
}
.patch label.method {
background: #186A3B;
}
.delete label.method {
background: #E67E22;
}
label.proxy {
font-size: 10px;
font-style: italic;
color: orange;
margin-left: 10px;
}
.call {
border: 1px solid #aaa;
margin-bottom: 5px;
}
.call .body {
font-size: 12px;
line-height: 18px;
overflow-x: auto;
padding: 3px;
}
.call .in {
margin-bottom: 5px;
}
.error h3 {
font-size: 12px;
font-weight: bold;
margin: 0;
}
================================================
FILE: lib/static/documentation.js
================================================
(function() {
$('.call .body').hide();
$('.call .head').click(function(e) {
$(this).siblings('.body').toggle();
});
})();
================================================
FILE: lib/views/documentation.jade
================================================
extends layout
block head
link(rel='stylesheet',href='documentation.css')
block content
if general
.call
.head.general General
.body
.general!= general
each call in calls
div.call(class=call.classes)
.head
label.method= call.method
label.path= call.path
if call.proxy
label.proxy [proxy]
.body
if call.description
.description!= call.description
if call.input.length > 0
.in
h2 Request
ul
each input in call.input
li= input
if (call.inputBody && call.inputBody.length > 0)
.response
pre
code= call.inputBody
.out
h2 Success Response
ul
each output in call.output
li= output
.response
pre
code= call.response
if (call.errors && call.errors.length > 0)
.errors
h2 Error Responses
each error in call.errors
.error
h3 Error: #{error.name}
if error.description
.description= error.description
.status @status #{error.response.status}
pre
code= error.response.body
script(src='zepto.min.js')
script(src='documentation.js')
script
hljs.initHighlightingOnLoad();
================================================
FILE: lib/views/layout.jade
================================================
doctype 5
html(lang="en")
head
title= title
link(rel='stylesheet',href='//yandex.st/highlightjs/7.3/styles/github.min.css')
script(src='//yandex.st/highlightjs/7.3/highlight.min.js')
block head
body
h1= title
block content
================================================
FILE: lib/views/logs.jade
================================================
extends layout
block head
link(rel='stylesheet',href='documentation.css')
link(src='moment.js')
block content
each log in logs
div.call(class=log.request_method.toLowerCase())
.head
label.method= log.request_method
if !log.isProxied()
label.status= log.response_status
label.path= log.request_path
if log.isProxied()
label.proxy [proxy]
.right
label.client= log.client
label.time= moment(log.time + ' +0000').format('DD.MM.YYYY hh:mm:ss')
.body
.in
h2 Request
pre
code= log.request_headers
if (log.request_body && log.request_body.length > 0)
pre
code= log.request_body
if !log.isProxied()
.out
h2 Response
pre
code= log.response_headers
pre
code= log.response_body
script(src='zepto.min.js')
script(src='documentation.js')
script
hljs.initHighlightingOnLoad();
================================================
FILE: package.json
================================================
{
"name": "easymock",
"description": "Easy to use mock server that supports templates and routes.",
"keywords": [
"server",
"mock",
"routes",
"proxy"
],
"author": "Patrick Boos <mail@pboos.ch>",
"repository": {
"type": "git",
"url": "git://github.com/cyberagent/node-easymock.git"
},
"version": "0.2.29",
"main": "index",
"bin": {
"easymock": "./bin/easymock"
},
"scripts": {
"test": "make tests"
},
"dependencies": {
"body-parser": "^1.18.2",
"broware": "0.1.0",
"commander": "2.1.0",
"express": "^4.16.4",
"http-proxy": "0.10.3",
"jade": "0.27.7",
"marked": "^0.6.1",
"moment": "^2.24.0",
"sqlite3": "^4.0.1",
"underscore": "1.4.2"
},
"devDependencies": {
"chai": "1.1.0",
"coffee-script": "1.3.3",
"mocha": "^6.0.2",
"request": "^2.88.0"
}
}
================================================
FILE: test/cors.test.coffee
================================================
should = require('chai').should()
MockServer = require('../index').MockServer
utils = require('./utils')
request = utils.request
startMock = (withCors) ->
options =
port: utils.TESTING_PORT
log_enabled: false
path: __dirname + '/mock_data/'
if (withCors)
options.config = __dirname + '/mock_data/config_with_cors.json'
m = new MockServer(options)
m.start()
m
describe 'CORS', ->
mock = undefined
describe 'enabled', ->
beforeEach ->
mock = startMock(true)
afterEach ->
mock.stop()
it 'should return CORS headers for any request', (done) ->
request 'get', '/test1', (res) ->
res.statusCode.should.equal 200
res.headers['access-control-allow-origin'].should.equal '*'
res.headers['access-control-allow-methods'].should.equal 'GET,PUT,POST,DELETE,PATCH'
res.headers['access-control-allow-headers'].should.equal 'Content-Type, Authorization'
json = JSON.parse res.body
json.should.have.property 'test'
done()
it 'should return CORS headers and no body for OPTIONS requests', (done) ->
request 'options', '/test1', (res) ->
res.statusCode.should.equal 200
res.headers['access-control-allow-origin'].should.equal '*'
res.headers['access-control-allow-methods'].should.equal 'GET,PUT,POST,DELETE,PATCH'
res.headers['access-control-allow-headers'].should.equal 'Content-Type, Authorization'
done()
describe 'false', ->
beforeEach ->
mock = startMock(false)
afterEach ->
mock.stop()
it 'should return no CORS headers', (done) ->
request 'get', '/test1', (res) ->
res.statusCode.should.equal 200
res.headers.should.not.have.property 'access-control-allow-origin'
json = JSON.parse res.body
json.should.have.property 'test'
done()
it 'should return not respond to OPTIONS requests', (done) ->
request 'options', '/test1', (res) ->
res.statusCode.should.equal 404
done()
================================================
FILE: test/documentation.test.coffee
================================================
should = require('chai').should()
MockServer = require('../index').MockServer
utils = require('./utils')
fs = require('fs')
request = utils.request
describe 'API Documentation', ->
mock = undefined
beforeEach ->
mock = new MockServer({ port: utils.TESTING_PORT, log_enabled: false, path: __dirname + '/mock_data/' })
mock.start()
afterEach ->
mock.stop()
describe 'getApiDocumentationJsonInternal', ->
it 'should return an array of calls', (done) ->
mock.getApiDocumentationJsonInternal 'host', (err, result) ->
result.length.should.exist
result[0].method.should.equal 'GET'
result[0].path.should.exist
done()
it 'should sort the calls by path', (done) ->
mock.getApiDocumentationJsonInternal 'host', (err, result) ->
result[0].path.should.equal '/groups'
done()
it 'should replace the route parameter', (done) ->
mock.getApiDocumentationJsonInternal 'host', (err, result) ->
result[1].path.should.equal '/groups/:groupid'
done()
it 'should return input output documentation', (done) ->
mock.getApiDocumentationJsonInternal 'host', (err, result) ->
result[0].path.should.equal '/groups'
result[0].output.length.should.equal 2
result[0].output[0].should.equal '@status 200'
result[0].output[1].should.equal '@header Content-Type: application/json'
result[7].path.should.equal '/test1'
result[7].input.length.should.equal 1
result[7].input[0].should.equal '@header Content-Type: application/json'
result[7].inputBody.should.equal '{\n "post": true\n}'
result[8].path.should.equal '/test1'
result[8].input.length.should.equal 1
result[8].input[0].should.equal '@header Content-Type: application/json'
result[8].inputBody.should.equal '{\n "patch": true\n}'
done()
it 'should return description', (done) ->
mock.getApiDocumentationJsonInternal 'host', (err, result) ->
result[0].description.should.equal 'Retrieve the groups<br />\nSecond line<br />'
done()
it 'should return proxy (true if call will run proxied)', (done) ->
mock.getApiDocumentationJsonInternal 'host', (err, result) ->
result[4].proxy.should.be.true
done()
describe 'GET /_documentation/', ->
it 'should return the api documentation', (done) ->
request 'get', '/_documentation/', (res) ->
res.statusCode.should.equal 200
done()
================================================
FILE: test/errors.test.coffee
================================================
should = require('chai').should()
MockServer = require('../index').MockServer
utils = require('./utils')
request = utils.request
describe 'Mock Server', ->
mock = undefined
startMock = (configName) ->
mock = new MockServer({
port: utils.TESTING_PORT,
log_enabled: false,
path: __dirname + '/mock_data/',
config: __dirname + '/mock_data/' + configName + '.json'
})
mock.start()
stopMock = ->
mock.stop()
describe 'Call specific error', ->
beforeEach -> startMock('config_with_errors')
afterEach -> stopMock()
it 'GET /with_error.json should return a file specific error', (done) ->
request 'get', '/with_error', (res) ->
res.statusCode.should.equal 401
json = JSON.parse res.body
json.should.have.property 'error'
json.error.should.equal 'Authentication required'
done()
describe 'General error', ->
beforeEach -> startMock('config_with_general_errors')
afterEach -> stopMock()
it 'GET /test1.json should return a general error', (done) ->
request 'get', '/test1', (res) ->
res.statusCode.should.equal 400
json = JSON.parse res.body
json.should.have.property 'error'
json.error.should.equal 'General error'
done()
describe 'General error with own rate', ->
beforeEach -> startMock('config_with_general_errors_own_rates')
afterEach -> stopMock()
it 'GET /test1.json should return a general error', (done) ->
request 'get', '/with_error', (res) ->
res.statusCode.should.equal 400
json = JSON.parse res.body
json.should.have.property 'error'
json.error.should.equal 'General error'
done()
describe 'General error with own rate', ->
beforeEach -> startMock('config_with_error_rate_zero')
afterEach -> stopMock()
it 'GET /test1.json should return a general error', (done) ->
request 'get', '/with_error_rate', (res) ->
res.statusCode.should.equal 401
json = JSON.parse res.body
json.should.have.property 'error'
json.error.should.equal 'Authentication required'
done()
================================================
FILE: test/jsonp.test.coffee
================================================
should = require('chai').should()
MockServer = require('../index').MockServer
utils = require('./utils')
request = utils.request
startMock = (withJsonp) ->
options =
port: utils.TESTING_PORT
log_enabled: false
path: __dirname + '/mock_data/'
if (withJsonp)
options.config = __dirname + '/mock_data/config_with_jsonp.json'
m = new MockServer(options)
m.start()
m
describe 'JSONP', ->
describe 'enabled', ->
mock = undefined
beforeEach ->
mock = startMock(true)
afterEach ->
mock.stop()
it 'should not use jsonp if no jsonp/callback parameter sent', (done) ->
request 'get', '/test1', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'test'
json.test.should.be.true
done()
testJsonpResponse = (res) ->
res.statusCode.should.equal 200
res.body.substr(0,11).should.equal 'myCallback('
res.body.substr(-2).should.equal ');'
json = JSON.parse res.body.substring(11, res.body.length - 2)
json.should.have.property 'test'
it 'should use jsonp if callback parameter sent', (done) ->
request 'get', '/test1?callback=myCallback', (res) ->
testJsonpResponse res
done()
it 'should use jsonp if jsonp parameter sent', (done) ->
request 'get', '/test1?jsonp=myCallback', (res) ->
testJsonpResponse res
done()
describe 'disabled', ->
mock = undefined
beforeEach ->
mock = startMock(false)
afterEach ->
mock.stop()
it 'should not use jsonp even if jsonp/callback parameter sent', (done) ->
request 'get', '/test1?callback=myCallback', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'test'
json.test.should.be.true
done()
================================================
FILE: test/lag.test.coffee
================================================
should = require('chai').should()
MockServer = require('../index').MockServer
utils = require('./utils')
request = utils.request
describe 'Mock Server with lag', ->
mock = undefined
beforeEach ->
mock = new MockServer
port: utils.TESTING_PORT
log_enabled: false
path: __dirname + '/mock_data/'
config: __dirname + '/mock_data/config_with_lag.json'
mock.start()
afterEach ->
mock.stop()
it 'should add lag', (done) ->
start = new Date
request 'get', '/test1', (res) ->
end = new Date
lag = end.getTime() - start.getTime()
lag.should.be.above 100
console.log
done()
describe 'Mock Server with random lag', ->
mock = undefined
beforeEach ->
mock = new MockServer
port: utils.TESTING_PORT
log_enabled: false
path: __dirname + '/mock_data/'
config: __dirname + '/mock_data/config_with_random_lag.json'
mock.start()
afterEach ->
mock.stop()
it 'should add random, variable lag', (done) ->
start = new Date
request 'get', '/test1', (res) ->
end = new Date
lag = end.getTime() - start.getTime()
lag.should.be.above 200
lag.should.be.below 1100
console.log
done()
describe 'Mock Server with lag object (lag on specific paths)', ->
mock = undefined
beforeEach ->
mock = new MockServer
port: utils.TESTING_PORT
log_enabled: false
path: __dirname + '/mock_data/'
config: __dirname + '/mock_data/config_with_lag_object.json'
mock.start()
afterEach ->
mock.stop()
it 'should add the default lag when there are no matches', (done) ->
start = new Date
request 'get', '/test1', (res) ->
end = new Date
lag = end.getTime() - start.getTime()
lag.should.be.above 1000
console.log
done()
it 'should add the lag for the first path matched', (done) ->
start = new Date
request 'get', '/laggy', (res) ->
end = new Date
lag = end.getTime() - start.getTime()
lag.should.be.above 500
lag.should.be.below 800
console.log
done()
describe 'should use regular expressions for matching', ->
it 'and use the lag for the first match found', (done) ->
start = new Date
request 'get', '/lag_is_fun/12345', (res) ->
end = new Date
lag = end.getTime() - start.getTime()
lag.should.be.above 200
lag.should.be.below 1000
console.log
done()
it 'and use the default lag if there are no matches', (done) ->
start = new Date
request 'get', '/lag_is_fun/but_this_wont_match', (res) ->
end = new Date
lag = end.getTime() - start.getTime()
lag.should.be.above 1000
console.log
done()
# Expression has [0-9]+ after the slash, so no content after the slash
# should result in a non-match.
it 'and use the default lag if there are no matches', (done) ->
start = new Date
request 'get', '/lag_is_fun/', (res) ->
end = new Date
lag = end.getTime() - start.getTime()
lag.should.be.above 1000
console.log
done()
================================================
FILE: test/logs.test.coffee
================================================
should = require('chai').should()
MockServer = require('../index').MockServer
utils = require('./utils')
fs = require('fs')
request = utils.request
describe 'Access Logs', ->
mock = undefined
beforeEach (done)->
mock = new MockServer({ port: utils.TESTING_PORT, log_enabled: true, path: __dirname + '/mock_data/' })
mock.start()
mock.log.ensureCreation ->
mock.log.clear(done)
afterEach ->
mock.stop()
describe 'mock.log.getLogs', ->
it 'should return an empty array of logs for no requests', (done) ->
mock.log.getLogs (err, result) ->
result.length.should.exist
result.length.should.equal 0
done()
it 'should return one log for one call', (done) ->
request 'get', '/groups', (res) ->
mock.log.getLogs (err, result) ->
result.length.should.exist
result.length.should.equal 1
result[0].request_method.should.equal 'GET'
result[0].request_path.should.equal '/groups'
result[0].response_status.should.equal 200
result[0].response_body.should.equal '{"name":"groups"}'
done()
it 'should return request_body with requested variables', (done) ->
request 'post', '/groups', {form: {test:true}}, (res) ->
mock.log.getLogs (err, result) ->
result[0].request_body.should.equal 'test=true'
done()
describe 'GET /_logs/', ->
it 'should return the access logs', (done) ->
request 'get', '/_logs/', (res) ->
res.statusCode.should.equal 200
done()
================================================
FILE: test/mock.test.coffee
================================================
should = require('chai').should()
MockServer = require('../index').MockServer
utils = require('./utils')
request = utils.request
describe 'Mock Server', ->
mock = undefined
beforeEach ->
mock = new MockServer({ port: utils.TESTING_PORT, log_enabled: false, path: __dirname + '/mock_data/' })
mock.start()
afterEach ->
mock.stop()
describe 'Static files', ->
it 'GET /test1_get.json should serve test1_get.json', (done) ->
request 'get', '/test1', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'test'
json.test.should.be.true
done()
it 'GET /test2.json should serve test2.json', (done) ->
request 'get', '/test2.json', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'id'
json.id.should.equal '2'
done()
describe 'Mock file', ->
it 'GET /test1 should serve test1_get.json', (done) ->
request 'get', '/test1', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'test'
json.test.should.be.true
done()
it 'GET /test1/ should serve test1_get.json', (done) ->
request 'get', '/test1/', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'test'
json.test.should.be.true
done()
it 'POST /test1 should serve test1_post.json', (done) ->
request 'post', '/test1', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'post'
json.post.should.be.true
done()
it 'PATCH /test1 should serve test1_patch.json', (done) ->
request 'patch', '/test1', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'patch'
json.patch.should.be.true
done()
describe 'Templates', ->
it '{{Object1}} should be replaced with _templates/Object1.json', (done) ->
request 'get', '/with_template', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'object1'
json.object1.should.have.property 'value1'
json.object1.value1.should.equal 'test1'
json.object1.should.have.property 'value2'
json.object1.value2.should.equal 'test2'
done()
describe 'Variables', ->
it '#{server} should be replaced with server variable from config.json', (done) ->
request 'get', '/with_variable', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'image'
json.image.should.equal 'http://server.com/image.jpg'
done()
it '#{_1} should be replaced with template parameter', (done) ->
request 'get', '/with_template_param', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'object'
json.object.should.have.property 'name'
json.object.name.should.equal 'Object 1'
done()
it '#{_1}, #{_2}, #{_3} should all be replaced with template parameter', (done) ->
request 'get', '/with_template_params', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.length 3
json[0].should.have.property('name').and.equal 'Item 1'
json[0].should.have.property('image').and.equal 'http://server.com/img/img_one.jpg'
json[0].should.have.property('active').and.be.true
json[1].should.have.property('name').and.equal 'Item 2'
json[1].should.have.property('image').and.equal 'http://server.com/img/img_two.jpg'
json[1].should.have.property('active').and.be.false
json[2].should.have.property('name').and.equal 'Item 3'
json[2].should.have.property('image').and.equal 'http://server.com/img/img_three.jpg'
json[2].should.have.property('active').and.be.true
done()
it 'POST body parameters should be presented as variables', (done) ->
options = {
form: {name: 'Patrick'}
}
request 'post', '/test1', options, (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property('name').and.equal 'Patrick'
done()
it 'GET body parameters should be presented as variables', (done) ->
request 'get', '/test1?query=help', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property('query').and.equal 'help'
done()
it 'Headers should be presented as variables', (done) ->
options = {
headers: {
'Accept-Language': 'ja'
}
}
request 'get', '/test_headers', options, (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property('language').and.equal 'ja'
done()
it '#{HOST} should be replaced with the current requests host', (done) ->
request 'get', '/with_variable_HOST', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property('path').and.equal 'http://localhost:' + utils.TESTING_PORT + '/path'
done()
it '#{QUERY_STRING} should be replaced with the current request\'s query string', (done) ->
request 'get', '/with_variable_QUERY_STRING?foo=bar', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property('query').and.equal 'foo=bar'
done()
it '#{name_#lang} should be replaced correctly with #lang = de -> #{name_de} => Patrick', (done) ->
request 'get', '/with_variable_within_variable?lang=de', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property('name').and.equal 'Patrick'
done()
describe 'Routes /groups/:id', ->
it '/groups/1 remapped to /groups/id', (done) ->
request 'get', '/groups/1', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.id.should.equal '1234'
json.name.should.equal 'Group'
done()
it '/groups/1 should supply a #{id} variable that gets replaced', (done) ->
request 'get', '/groups/1', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.name2.should.equal 'Group 1'
done()
it '/groups/1/users/2 should supply a #{id} and ${userid} variable that gets replaced', (done) ->
request 'get', '/groups/1/users/2', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.groupid.should.equal '1'
json.userid.should.equal '2'
done()
it '/groups/5/show {{Nested(#{_1}1)}} should get resolved correctly to Nested with _1=51', (done) ->
request 'get', '/groups/5/show', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.length.should.equal 2
json[0].id.should.equal 51
json[0].nested.id.should.equal 51
json[1].id.should.equal 52
json[1].nested.id.should.equal 52
done()
it '/groups/mock_data-1 should supply a #{id} variable that gets replaced', (done) ->
request 'get', '/groups/mock_data-1', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.name2.should.equal 'Group mock_data-1'
done()
it '/groups should not forward to /groups/', (done) ->
request 'get', '/groups', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.name.should.equal 'groups'
done()
describe 'Meta data', ->
it 'should send given @status', (done) ->
request 'get', '/redirect', (res) ->
res.statusCode.should.equal 301
done();
it 'should send given @header', (done) ->
request 'get', '/redirect', (res) ->
res.headers.should.have.property 'location'
res.headers['location'].should.equal 'http://www.cyberagent.co.jp'
done();
describe 'Mock Server create with config object', ->
mock = undefined
beforeEach ->
config = {
variables : {
server: "http://config.server.com"
}
}
mock = new MockServer({ port: utils.TESTING_PORT, log_enabled: false, path: __dirname + '/mock_data/', config: config })
mock.start()
afterEach ->
mock.stop()
it 'should be used config variable', (done) ->
request 'get', '/with_variable', (res) ->
res.statusCode.should.equal 200
json = JSON.parse res.body
json.should.have.property 'image'
json.image.should.equal 'http://config.server.com/image.jpg'
done()
================================================
FILE: test/mock_data/.test1_get.json.test
================================================
================================================
FILE: test/mock_data/_errors/general.json
================================================
< @status 400
{
"error": "General error"
}
================================================
FILE: test/mock_data/_errors/test.json
================================================
< @status 401
{
"error": "Authentication required"
}
================================================
FILE: test/mock_data/_templates/Nested.json
================================================
{
"id": #{_1},
"nested": {{Nested2(#{_1})}}
}
================================================
FILE: test/mock_data/_templates/Nested2.json
================================================
{
"id": #{_1}
}
================================================
FILE: test/mock_data/_templates/Object1.json
================================================
{
"value1": "test1",
"value2": "test2"
}
================================================
FILE: test/mock_data/_templates/ObjectWithParam.json
================================================
{
"name": "Object #{_1}"
}
================================================
FILE: test/mock_data/_templates/ObjectWithParams.json
================================================
{
"name": "Item #{_1}",
"image": "#{server}/img/img_#{_2}.jpg",
"active": #{_3}
}
================================================
FILE: test/mock_data/config.json
================================================
{
"variables" : {
"server": "http://server.com",
"name_de": "Patrick"
},
"routes": [
"/groups/:groupid",
"/groups/:groupid/show",
"/groups/:groupid/users/:userid"
],
"proxy": {
"server": "http://real.com",
"default": false,
"calls": {
"/proxy": true
}
}
}
================================================
FILE: test/mock_data/config_with_cors.json
================================================
{
"cors": true
}
================================================
FILE: test/mock_data/config_with_error_rate_zero.json
================================================
{
"error-rate": 0
}
================================================
FILE: test/mock_data/config_with_errors.json
================================================
{
"error-rate": 1
}
================================================
FILE: test/mock_data/config_with_general_errors.json
================================================
{
"error-rate": 1,
"errors" : ["general"]
}
================================================
FILE: test/mock_data/config_with_general_errors_own_rates.json
================================================
{
"error-rate": 0,
"errors" : [ { "name":"general", "rate": 1 } ]
}
================================================
FILE: test/mock_data/config_with_jsonp.json
================================================
{
"jsonp": true
}
================================================
FILE: test/mock_data/config_with_lag.json
================================================
{
"simulated-lag": 100
}
================================================
FILE: test/mock_data/config_with_lag_object.json
================================================
{
"simulated-lag": {
"default": 1000,
"paths": [
{
"match": "^/dontmatchme$",
"lag": 5000
},
{
"match": "/laggy",
"lag": 500
},
{
"match": "^/laggy",
"lag": 800
},
{
"match": "^/lag_is_fun/[0-9]+$",
"lag": 200
}
]
}
}
================================================
FILE: test/mock_data/config_with_random_lag.json
================================================
{
"simulated-lag-min": 200,
"simulated-lag-max": 1100
}
================================================
FILE: test/mock_data/groups/groupid/show_get.json
================================================
[ {{Nested(#{groupid}1)}}, {{Nested(#{groupid}2)}} ]
================================================
FILE: test/mock_data/groups/groupid/users/userid_get.json
================================================
{
"id": "1234",
"groupid": "#{groupid}",
"userid": "#{userid}"
}
================================================
FILE: test/mock_data/groups/groupid_get.json
================================================
{
"id": "1234",
"name": "Group",
"name2": "Group #{groupid}"
}
================================================
FILE: test/mock_data/groups_get.json
================================================
# Retrieve the groups
# Second line
< @status 200
< @header Content-Type: application/json
{
"name": "groups"
}
================================================
FILE: test/mock_data/proxy_get.json
================================================
{ "proxy": true }
================================================
FILE: test/mock_data/redirect_get.json
================================================
< @status 301
< @header Location: http://www.cyberagent.co.jp
{}
================================================
FILE: test/mock_data/test1_get.json
================================================
{ "test": true, "query": "#{query}" }
================================================
FILE: test/mock_data/test1_patch.json
================================================
> @header Content-Type: application/json
> @body { "patch": true }
< @status 200
{
"patch": true,
"name": "#{name}"
}
================================================
FILE: test/mock_data/test1_post.json
================================================
> @header Content-Type: application/json
> @body { "post": true }
< @status 200
{
"post": true,
"name": "#{name}"
}
================================================
FILE: test/mock_data/test2.json
================================================
{
"id": "2"
}
================================================
FILE: test/mock_data/test_headers_get.json
================================================
{ "language": "#{HEADER_ACCEPT_LANGUAGE}" }
================================================
FILE: test/mock_data/with_error_get.json
================================================
< @status 200
< @header Content-Type: application/json
< @error test
{
"data": "Call successful"
}
================================================
FILE: test/mock_data/with_error_rate_get.json
================================================
< @status 200
< @header Content-Type: application/json
< @error test 1
{
"data": "Call successful"
}
================================================
FILE: test/mock_data/with_template_get.json
================================================
{
"object1": "{{Object1}}"
}
================================================
FILE: test/mock_data/with_template_param_get.json
================================================
{
"object": "{{ObjectWithParam(1)}}"
}
================================================
FILE: test/mock_data/with_template_params_get.json
================================================
[
"{{ObjectWithParams(1,one,true)}}",
"{{ObjectWithParams(2,two,false)}}",
"{{ObjectWithParams(3,three,true)}}"
]
================================================
FILE: test/mock_data/with_variable_HOST_get.json
================================================
{
"path": "http://#{HOST}/path"
}
================================================
FILE: test/mock_data/with_variable_QUERY_STRING_get.json
================================================
{
"query": "#{QUERY_STRING}"
}
================================================
FILE: test/mock_data/with_variable_get.json
================================================
{
"image": "#{server}/image.jpg"
}
================================================
FILE: test/mock_data/with_variable_within_variable_get.json
================================================
{
"name": "#{name_#{lang}}"
}
================================================
FILE: test/utils.coffee
================================================
http = require('http')
_ = require('underscore')
request = require('request')
exports.TESTING_PORT = 12345
exports.request = (method, path, options, fn) ->
if typeof(options) == 'function'
fn = options
options = undefined
options = options || { headers: [] }
options = _.extend({
method: method
, followRedirect: false
, uri: 'http://localhost:' + exports.TESTING_PORT + path
}, options)
req = request(options)
req.on 'response', (res) ->
buf = ''
res.setEncoding('utf8');
res.on 'data', (chunk) ->
buf += chunk
res.on 'end', ->
res.body = buf;
fn(res)
gitextract_gdmbmqx0/
├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── bin/
│ └── easymock
├── index.js
├── lib/
│ ├── access_log.js
│ ├── config.json
│ ├── easymock.js
│ ├── static/
│ │ ├── documentation.css
│ │ └── documentation.js
│ └── views/
│ ├── documentation.jade
│ ├── layout.jade
│ └── logs.jade
├── package.json
└── test/
├── cors.test.coffee
├── documentation.test.coffee
├── errors.test.coffee
├── jsonp.test.coffee
├── lag.test.coffee
├── logs.test.coffee
├── mock.test.coffee
├── mock_data/
│ ├── .test1_get.json.test
│ ├── _errors/
│ │ ├── general.json
│ │ └── test.json
│ ├── _templates/
│ │ ├── Nested.json
│ │ ├── Nested2.json
│ │ ├── Object1.json
│ │ ├── ObjectWithParam.json
│ │ └── ObjectWithParams.json
│ ├── config.json
│ ├── config_with_cors.json
│ ├── config_with_error_rate_zero.json
│ ├── config_with_errors.json
│ ├── config_with_general_errors.json
│ ├── config_with_general_errors_own_rates.json
│ ├── config_with_jsonp.json
│ ├── config_with_lag.json
│ ├── config_with_lag_object.json
│ ├── config_with_random_lag.json
│ ├── groups/
│ │ ├── groupid/
│ │ │ ├── show_get.json
│ │ │ └── users/
│ │ │ └── userid_get.json
│ │ └── groupid_get.json
│ ├── groups_get.json
│ ├── proxy_get.json
│ ├── redirect_get.json
│ ├── test1_get.json
│ ├── test1_patch.json
│ ├── test1_post.json
│ ├── test2.json
│ ├── test_headers_get.json
│ ├── with_error_get.json
│ ├── with_error_rate_get.json
│ ├── with_template_get.json
│ ├── with_template_param_get.json
│ ├── with_template_params_get.json
│ ├── with_variable_HOST_get.json
│ ├── with_variable_QUERY_STRING_get.json
│ ├── with_variable_get.json
│ └── with_variable_within_variable_get.json
└── utils.coffee
SYMBOL INDEX (8 symbols across 2 files)
FILE: lib/access_log.js
function AccessLog (line 5) | function AccessLog(config) {
FILE: lib/easymock.js
function MockServer (line 19) | function MockServer(options) {
function findMatchingLag (line 139) | function findMatchingLag(lagconfig, path) {
function pathRegExp (line 236) | function pathRegExp(path, opts) {
function switchRouteMatcher (line 266) | function switchRouteMatcher(on, route) {
function getDocumentation (line 761) | function getDocumentation() {
function getGeneralDocumentation (line 772) | function getGeneralDocumentation() {
function getDocumentationHtml (line 780) | function getDocumentationHtml(documentation) {
Condensed preview — 62 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (75K chars).
[
{
"path": ".gitignore",
"chars": 69,
"preview": ".DS_Store\n.idea\nnode_modules/\nlib-cov/\ncoverage.html\n\naccess_logs.db\n"
},
{
"path": ".travis.yml",
"chars": 38,
"preview": "language: node_js\nnode_js:\n - \"0.10\"\n"
},
{
"path": "LICENSE",
"chars": 1068,
"preview": "(MIT License)\n\nCopyright (C) 2012 CyberAgent\n\nPermission is hereby granted, free of charge, to any person obtaining a co"
},
{
"path": "Makefile",
"chars": 342,
"preview": "TESTS = $(shell find test -name \"*.test.coffee\")\nREPORTER = dot\n\ntests:\n\t@NODE_ENV=testing ./node_modules/.bin/mocha --c"
},
{
"path": "README.md",
"chars": 9238,
"preview": "# EasyMock Server\n\n## Usage\n\n $ npm install -g easymock\n $ easymock\n\n\n\n## Files\nAll files from the running"
},
{
"path": "bin/easymock",
"chars": 931,
"preview": "#!/usr/bin/env node\n\nvar program = require('commander');\n\nprogram\n .version(require('../package').version)\n .option('-"
},
{
"path": "index.js",
"chars": 106,
"preview": "module.exports = process.env.EASYMOCK_COV\n ? require('./lib-cov/easymock')\n : require('./lib/easymock');"
},
{
"path": "lib/access_log.js",
"chars": 2633,
"preview": "/*global require:true, exports:true */\nvar sqlite3 = require('sqlite3');\nvar _ = require('underscore');\n\nfunction Access"
},
{
"path": "lib/config.json",
"chars": 24,
"preview": "{\n \"simulated-lag\": 0\n}"
},
{
"path": "lib/easymock.js",
"chars": 23626,
"preview": "/*global require:true, exports:true, __dirname:true, process:true */\nvar express = require('express');\nvar bodyParser ="
},
{
"path": "lib/static/documentation.css",
"chars": 1083,
"preview": "body {\n margin: 5px;\n font-family: Helvetica, sans-serif;\n}\nh1,h2,h3,h4,h5 {\n}\nul, li {\n margin: 0;\n padding: 0;\n l"
},
{
"path": "lib/static/documentation.js",
"chars": 123,
"preview": "(function() {\n$('.call .body').hide();\n$('.call .head').click(function(e) {\n $(this).siblings('.body').toggle();\n});\n})"
},
{
"path": "lib/views/documentation.jade",
"chars": 1465,
"preview": "extends layout\n\nblock head\n link(rel='stylesheet',href='documentation.css')\n\nblock content\n if general\n .call\n "
},
{
"path": "lib/views/layout.jade",
"chars": 251,
"preview": "doctype 5\nhtml(lang=\"en\")\n head\n title= title\n link(rel='stylesheet',href='//yandex.st/highlightjs/7.3/styles/git"
},
{
"path": "lib/views/logs.jade",
"chars": 1034,
"preview": "extends layout\n\nblock head\n link(rel='stylesheet',href='documentation.css')\n link(src='moment.js')\n\nblock content\n ea"
},
{
"path": "package.json",
"chars": 867,
"preview": "{\n \"name\": \"easymock\",\n \"description\": \"Easy to use mock server that supports templates and routes.\",\n \"keywords\": [\n"
},
{
"path": "test/cors.test.coffee",
"chars": 2029,
"preview": "should = require('chai').should()\nMockServer = require('../index').MockServer\nutils = require('./utils')\nrequest = utils"
},
{
"path": "test/documentation.test.coffee",
"chars": 2513,
"preview": "should = require('chai').should()\nMockServer = require('../index').MockServer\nutils = require('./utils')\nfs = require('f"
},
{
"path": "test/errors.test.coffee",
"chars": 2169,
"preview": "should = require('chai').should()\nMockServer = require('../index').MockServer\nutils = require('./utils')\nrequest = utils"
},
{
"path": "test/jsonp.test.coffee",
"chars": 1866,
"preview": "should = require('chai').should()\nMockServer = require('../index').MockServer\nutils = require('./utils')\nrequest = utils"
},
{
"path": "test/lag.test.coffee",
"chars": 3152,
"preview": "should = require('chai').should()\nMockServer = require('../index').MockServer\nutils = require('./utils')\nrequest = utils"
},
{
"path": "test/logs.test.coffee",
"chars": 1557,
"preview": "should = require('chai').should()\nMockServer = require('../index').MockServer\nutils = require('./utils')\nfs = require('f"
},
{
"path": "test/mock.test.coffee",
"chars": 8939,
"preview": "should = require('chai').should()\nMockServer = require('../index').MockServer\nutils = require('./utils')\nrequest = utils"
},
{
"path": "test/mock_data/.test1_get.json.test",
"chars": 0,
"preview": ""
},
{
"path": "test/mock_data/_errors/general.json",
"chars": 45,
"preview": "< @status 400\n{\n \"error\": \"General error\"\n}\n"
},
{
"path": "test/mock_data/_errors/test.json",
"chars": 55,
"preview": "< @status 401\n{\n \"error\": \"Authentication required\"\n}\n"
},
{
"path": "test/mock_data/_templates/Nested.json",
"chars": 49,
"preview": "{\n \"id\": #{_1},\n \"nested\": {{Nested2(#{_1})}}\n}"
},
{
"path": "test/mock_data/_templates/Nested2.json",
"chars": 17,
"preview": "{\n \"id\": #{_1}\n}"
},
{
"path": "test/mock_data/_templates/Object1.json",
"chars": 44,
"preview": "{\n \"value1\": \"test1\",\n \"value2\": \"test2\"\n}"
},
{
"path": "test/mock_data/_templates/ObjectWithParam.json",
"chars": 28,
"preview": "{\n \"name\": \"Object #{_1}\"\n}"
},
{
"path": "test/mock_data/_templates/ObjectWithParams.json",
"chars": 87,
"preview": "{\n \"name\": \"Item #{_1}\",\n \"image\": \"#{server}/img/img_#{_2}.jpg\",\n \"active\": #{_3}\n}"
},
{
"path": "test/mock_data/config.json",
"chars": 309,
"preview": "{\n \"variables\" : {\n \"server\": \"http://server.com\",\n \"name_de\": \"Patrick\"\n },\n \"routes\": [\n \"/groups/:groupid"
},
{
"path": "test/mock_data/config_with_cors.json",
"chars": 18,
"preview": "{\n \"cors\": true\n}"
},
{
"path": "test/mock_data/config_with_error_rate_zero.json",
"chars": 22,
"preview": "{\n \"error-rate\": 0\n}\n"
},
{
"path": "test/mock_data/config_with_errors.json",
"chars": 22,
"preview": "{\n \"error-rate\": 1\n}\n"
},
{
"path": "test/mock_data/config_with_general_errors.json",
"chars": 48,
"preview": "{\n \"error-rate\": 1,\n \"errors\" : [\"general\"]\n}\n"
},
{
"path": "test/mock_data/config_with_general_errors_own_rates.json",
"chars": 72,
"preview": "{\n \"error-rate\": 0,\n \"errors\" : [ { \"name\":\"general\", \"rate\": 1 } ]\n}\n"
},
{
"path": "test/mock_data/config_with_jsonp.json",
"chars": 19,
"preview": "{\n \"jsonp\": true\n}"
},
{
"path": "test/mock_data/config_with_lag.json",
"chars": 26,
"preview": "{\n \"simulated-lag\": 100\n}"
},
{
"path": "test/mock_data/config_with_lag_object.json",
"chars": 347,
"preview": "\n{\n \"simulated-lag\": {\n \"default\": 1000,\n \"paths\": [\n {\n \"match\": \"^/dontmatchme$\",\n \"lag\": 50"
},
{
"path": "test/mock_data/config_with_random_lag.json",
"chars": 59,
"preview": "{\n \"simulated-lag-min\": 200,\n \"simulated-lag-max\": 1100\n}"
},
{
"path": "test/mock_data/groups/groupid/show_get.json",
"chars": 52,
"preview": "[ {{Nested(#{groupid}1)}}, {{Nested(#{groupid}2)}} ]"
},
{
"path": "test/mock_data/groups/groupid/users/userid_get.json",
"chars": 70,
"preview": "{\n \"id\": \"1234\",\n \"groupid\": \"#{groupid}\",\n \"userid\": \"#{userid}\"\n}"
},
{
"path": "test/mock_data/groups/groupid_get.json",
"chars": 68,
"preview": "{\n \"id\": \"1234\",\n \"name\": \"Group\",\n \"name2\": \"Group #{groupid}\"\n}"
},
{
"path": "test/mock_data/groups_get.json",
"chars": 114,
"preview": "# Retrieve the groups\n# Second line\n< @status 200\n< @header Content-Type: application/json\n{\n \"name\": \"groups\"\n}\n"
},
{
"path": "test/mock_data/proxy_get.json",
"chars": 17,
"preview": "{ \"proxy\": true }"
},
{
"path": "test/mock_data/redirect_get.json",
"chars": 64,
"preview": "< @status 301\n< @header Location: http://www.cyberagent.co.jp\n{}"
},
{
"path": "test/mock_data/test1_get.json",
"chars": 37,
"preview": "{ \"test\": true, \"query\": \"#{query}\" }"
},
{
"path": "test/mock_data/test1_patch.json",
"chars": 122,
"preview": "> @header Content-Type: application/json\n> @body { \"patch\": true }\n< @status 200\n{\n \"patch\": true,\n \"name\": \"#{name}\"\n"
},
{
"path": "test/mock_data/test1_post.json",
"chars": 120,
"preview": "> @header Content-Type: application/json\n> @body { \"post\": true }\n< @status 200\n{\n \"post\": true,\n \"name\": \"#{name}\"\n}\n"
},
{
"path": "test/mock_data/test2.json",
"chars": 15,
"preview": "{\n \"id\": \"2\"\n}"
},
{
"path": "test/mock_data/test_headers_get.json",
"chars": 43,
"preview": "{ \"language\": \"#{HEADER_ACCEPT_LANGUAGE}\" }"
},
{
"path": "test/mock_data/with_error_get.json",
"chars": 100,
"preview": "< @status 200\n< @header Content-Type: application/json\n< @error test\n\n{\n\t\"data\": \"Call successful\"\n}"
},
{
"path": "test/mock_data/with_error_rate_get.json",
"chars": 102,
"preview": "< @status 200\n< @header Content-Type: application/json\n< @error test 1\n\n{\n\t\"data\": \"Call successful\"\n}"
},
{
"path": "test/mock_data/with_template_get.json",
"chars": 30,
"preview": "{\n \"object1\": \"{{Object1}}\"\n}"
},
{
"path": "test/mock_data/with_template_param_get.json",
"chars": 40,
"preview": "{\n \"object\": \"{{ObjectWithParam(1)}}\"\n}"
},
{
"path": "test/mock_data/with_template_params_get.json",
"chars": 119,
"preview": "[\n \"{{ObjectWithParams(1,one,true)}}\",\n \"{{ObjectWithParams(2,two,false)}}\",\n \"{{ObjectWithParams(3,three,true)}}\"\n]"
},
{
"path": "test/mock_data/with_variable_HOST_get.json",
"chars": 35,
"preview": "{\n \"path\": \"http://#{HOST}/path\"\n}"
},
{
"path": "test/mock_data/with_variable_QUERY_STRING_get.json",
"chars": 33,
"preview": "{\n \"query\": \"#{QUERY_STRING}\"\n}\n"
},
{
"path": "test/mock_data/with_variable_get.json",
"chars": 36,
"preview": "{\n \"image\": \"#{server}/image.jpg\"\n}"
},
{
"path": "test/mock_data/with_variable_within_variable_get.json",
"chars": 31,
"preview": "{\n \"name\": \"#{name_#{lang}}\"\n}"
},
{
"path": "test/utils.coffee",
"chars": 622,
"preview": "http = require('http')\n_ = require('underscore')\nrequest = require('request')\n\nexports.TESTING_PORT = 12345\nexports.requ"
}
]
About this extraction
This page contains the full source code of the CyberAgent/node-easymock GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 62 files (66.7 KB), approximately 18.9k tokens, and a symbol index with 8 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.