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