<commit_before>/*
 * grunt-init-amber
 * https://amber-lang.net/
 *
 * Copyright (c) 2013 Manfred Kroehnert, contributors
 * Licensed under the MIT license.
 */

'use strict';

// Basic template description.
exports.description = 'Create a web application based on Amber Smalltalk.';

// Template-specific notes to be displayed before question prompts.
exports.notes = ' _Project title_ should be a human-readable title.';

// Template-specific notes to be displayed after question prompts.
exports.after = 'You should now install project dependencies with _bower install_.' +
  ' Afterwards, start the development server with _./bower_components/amber/bin/amber serve_.' +
  ' Your application is then accessible via _http://localhost:4000/_';

// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';

// The actual init template.
exports.template = function(grunt, init, done) {

  init.process({type: 'amber'}, [
    // Prompt for these values.
    init.prompt('name', 'AmberApplication'),
    init.prompt('title'),
    init.prompt('description', 'Amber Application.'),
    {
      name: 'namespace',
      message: 'The namespace used to store your Amber Packages.',
    },
    {
      name: 'amber_version',
      default: '>= 0.12.4',
      message: 'The version of Amber to use. Must be >= 0.12.4',
    },
    init.prompt('version'),
    init.prompt('repository'),
    init.prompt('homepage'),
    init.prompt('bugs'),
    init.prompt('licenses', 'MIT'),
    init.prompt('author_name'),
    init.prompt('author_email'),
    init.prompt('author_url')
  ], function(err, props) {
    // Files to copy (and process).
    var files = init.filesToCopy(props);

    // Add properly-named license files.
    init.addLicenseFiles(files, props.licenses);

    // Actually copy (and process) files.
    init.copyAndProcess(files, props, {noProcess: 'libs/**'});

    // Clean up non-npm props.
    var namespace = props.namespace;
    delete props.namespace;
    var amberVersion = props.amber_version;
    delete props.amber_version;

    // Add '~' at the beginning if version is without operation (starts with number)
    if (amberVersion.match(/^\d/)) {
      amberVersion = '~' + amberVersion;
    }

    // A few additional properties.
    props.keywords = ['Amber', 'Smalltalk'];
    props.devDependencies = {
      "grunt": "~0.4.0",
      "amber-dev": "0.0.3"
    };
    props.node_version = '>= 0.8.0';

    // Generate package.json file, used by npm and grunt.
    init.writePackageJSON('package.json', props);

    // generate bower.json file
    grunt.file.write('bower.json', JSON.stringify({

        "name": props.name,
        "description": props.description,
        "version": props.version,
        "authors": [
            {
                "name": props.author_name,
                "email": props.author_email
            }
        ],
        "homepage": props.homepage,
        "main": props.main,
        "keywords": props.keywords,
        "license": props.licenses,
        "private": false,
        "dependencies": {
            "amber": amberVersion
        }
    }, null, 4));

    // All done!
    done();
  });

};
<commit_msg>Variable namespace was unused, removed it.<commit_after>/*
 * grunt-init-amber
 * https://amber-lang.net/
 *
 * Copyright (c) 2013 Manfred Kroehnert, contributors
 * Licensed under the MIT license.
 */

'use strict';

// Basic template description.
exports.description = 'Create a web application based on Amber Smalltalk.';

// Template-specific notes to be displayed before question prompts.
exports.notes = ' _Project title_ should be a human-readable title.';

// Template-specific notes to be displayed after question prompts.
exports.after = 'You should now install project dependencies with _bower install_.' +
  ' Afterwards, start the development server with _./bower_components/amber/bin/amber serve_.' +
  ' Your application is then accessible via _http://localhost:4000/_';

// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';

// The actual init template.
exports.template = function(grunt, init, done) {

  init.process({type: 'amber'}, [
    // Prompt for these values.
    init.prompt('name', 'AmberApplication'),
    init.prompt('title'),
    init.prompt('description', 'Amber Application.'),
    {
      name: 'namespace',
      message: 'The namespace used to store your Amber Packages.',
    },
    {
      name: 'amber_version',
      default: '>= 0.12.4',
      message: 'The version of Amber to use. Must be >= 0.12.4',
    },
    init.prompt('version'),
    init.prompt('repository'),
    init.prompt('homepage'),
    init.prompt('bugs'),
    init.prompt('licenses', 'MIT'),
    init.prompt('author_name'),
    init.prompt('author_email'),
    init.prompt('author_url')
  ], function(err, props) {
    // Files to copy (and process).
    var files = init.filesToCopy(props);

    // Add properly-named license files.
    init.addLicenseFiles(files, props.licenses);

    // Actually copy (and process) files.
    init.copyAndProcess(files, props, {noProcess: 'libs/**'});

    // Clean up non-npm props.
    delete props.namespace;
    var amberVersion = props.amber_version;
    delete props.amber_version;

    // Add '~' at the beginning if version is without operation (starts with number)
    if (amberVersion.match(/^\d/)) {
      amberVersion = '~' + amberVersion;
    }

    // A few additional properties.
    props.keywords = ['Amber', 'Smalltalk'];
    props.devDependencies = {
      "grunt": "~0.4.0",
      "amber-dev": "0.0.3"
    };
    props.node_version = '>= 0.8.0';

    // Generate package.json file, used by npm and grunt.
    init.writePackageJSON('package.json', props);

    // generate bower.json file
    grunt.file.write('bower.json', JSON.stringify({

        "name": props.name,
        "description": props.description,
        "version": props.version,
        "authors": [
            {
                "name": props.author_name,
                "email": props.author_email
            }
        ],
        "homepage": props.homepage,
        "main": props.main,
        "keywords": props.keywords,
        "license": props.licenses,
        "private": false,
        "dependencies": {
            "amber": amberVersion
        }
    }, null, 4));

    // All done!
    done();
  });

};
<|endoftext|>


<commit_before>/**
 * Created by arming on 6/15/16.
 */
'use strict'
const ValueException = require('./exceptions').ValueException
const TypeException = require('./exceptions').TypeException
const Mapping = require('./mapping').Mapping
const Output = require('./output').Output
const Parameter = require('./parameter').Parameter
const WKResource = require('./resource').WKResource
const path = require('path')
const yaml = require('js-yaml')

/** @module Core */

function _handleDuplicateKey (key) {
  console.log('Duplicate key ' + key)
  throw new ValueException('duplicate key "%s" detected' % key)
}

function _add (d, values) {
  if (Array.isArray(values)) {
    values.forEach((v) => {
      if (v.WKName in d) {
        _handleDuplicateKey(v.WKName)
      }
      d[v.WKName] = v
    })
  } else {
    if (values.WKName in d) {
      _handleDuplicateKey(values.WKName)
    }
    d[values.WKName] = values
  }
  return values
}

function _remove (d, values) {
  if (Array.isArray(values)) {
    values.forEach((v) => {
      delete d[v.WKName]
    })
  } else {
    delete d[values.WKName]
  }
  return values
}

function _populateFromExisting(newTemplate, existingTemplate) {
  for (let param in existingTemplate.Parameters) {
    let newParam = new Parameter(param, existingTemplate.Parameters[param])
    newTemplate.add(newParam)
  }
  for (let output in existingTemplate.Outputs) {
    let newOutput = new Output(output, existingTemplate.Outputs[output])
    newTemplate.add(newOutput)
  }
  for (let mapping in existingTemplate.Mappings) {
    let newMapping = new Mapping(mapping, existingTemplate.Mappings[mapping])
    newTemplate.add(newMapping)
  }
  for (let resource in existingTemplate.Resources) {
    let typeSplit = existingTemplate.Resources[resource].Type.split('::')
    let resourceGroupName = typeSplit[1]
    let resourceGroup
    let resourceName = typeSplit[2]
    if (typeSplit[0] === 'Custom') {
      resourceGroup = require(path.join(__dirname, 'resources', 'cloudformation'))
      resourceName = 'CustomResource'
    } else {
      resourceGroup = require(path.join(__dirname, 'resources', resourceGroupName.toLowerCase()))
      if (resourceGroupName === 'Lambda' && resourceName === 'Function') {
        resourceName = 'LambdaFunction'
      }
    }
    let temp = Object.create(resourceGroup[resourceName].prototype)
    let newResource = Reflect.construct(resourceGroup[resourceName], [resource, existingTemplate.Resources[resource].Properties])
    newTemplate.add(newResource)
  }
}

/**
 * @memberof module:Core
 */
function Template (template) {
  this.Description = ''
  this.Metadata = {}
  this.Conditions = {}
  this.Mappings = {}
  this.Outputs = {}
  this.Parameters = {}
  this.Resources = {}
  this.AWSTemplateFormatVersion = '2010-09-09'
  if (template) {
    _populateFromExisting(this, template)
  }
}

/**
 * Add an element to the Template
 * @param element
 */
Template.prototype.add = function (element) {
  if (element instanceof Parameter) {
    _add(this.Parameters, element)
  } else if (element instanceof WKResource) {
    _add(this.Resources, element)
  } else if (element instanceof Output) {
    _add(this.Outputs, element)
  } else if (element instanceof Mapping) {
    _add(this.Mappings, element)
  } else {
    throw new TypeException(element + ' is not a valid type and cannot be added to the template.')
  }
}

/**
 * Remove an element from the Template
 * @param element
 */
Template.prototype.remove = function (element) {
  if (element instanceof Parameter) {
    _remove(this.Parameters, element)
  } else if (element instanceof WKResource) {
    _remove(this.Resources, element)
  } else if (element instanceof Output) {
    _remove(this.Outputs, element)
  } else if (element instanceof Mapping) {
    _remove(this.Mappings, element)
  } else {
    throw new TypeException(element + ' is not a valid type and cannot be added to the template.')
  }
}

/**
 * Set the metadata value of the template
 * @param metadata
 */
Template.prototype.setMetadata = function (metadata) {
  this.Metadata = metadata
}

/**
 * Set the version value of the template
 * @param version
 */
Template.prototype.setVersion = function (version) {
  this.Version = version
}

/**
 * Add a description to the template
 * @param description
 */
Template.prototype.setDescription = function (description) {
  this.Description = description
}

/**
 * Add a condition to the template
 * @param name
 * @param condition
 */
Template.prototype.addCondition = function (name, condition) {
  this.Conditions[name] = condition
}

/**
 * Remove a condition from the template
 * @param name
 * @param condition
 */
Template.prototype.removeCondition = function (name, condition) {
  delete this.Conditions[name]
}

/**
 *
 * @param callback
 */
Template.prototype.toJsonAsync = function (callback) {
  if (callback) {
    let result = this.toJson()
    if (result.Errors) {
      callback(result.Errors, result.Template)
    } else {
      callback(null, result.Template)
    }
  } else {
    return new Promise((resolve, reject) => {
      process.nextTick(() => {
        let result = this.toJson()
        if (result.Errors) {
          reject({ Errors: result.Errors, Template: result.Template })
        } else {
          resolve(result.Template)
        }
      })
    })
  }
}

/**
 * Returns a CloudFormation JSON template string
 * @returns {Object}
 */
Template.prototype.toJson = function () {
  let j = JSON.parse(JSON.stringify(this))
  let errors = []
  for (let param in this.Parameters) {
    try {
      j.Parameters[param] = this.Parameters[param].toJson()
    } catch (e) {
      errors.push(e.message)
    }
  }
  for (let resource in this.Resources) {
    let result = this.Resources[resource].toJson()
    if (result.errors) {
      result.errors.forEach((e) => {
        errors.push(e)
      })
    }
    j.Resources[resource] = result.json
  }
  for (let output in this.Outputs) {
    try {
      j.Outputs[output] = this.Outputs[output].toJson()
    } catch (e) {
      errors.push(e.message)
    }
  }
  for (let map in this.Mappings) {
    if (this.Mappings[map] instanceof Mapping) {
      try {
        j.Mappings[map] = this.Mappings[map].toJson()
      } catch (e) {
        errors.push(e.message)
      }
    } else {
      j.Mappings[map] = this.Mappings[map]
    }
  }
  if (Object.keys(j.Metadata).length === 0) {
    delete j.Metadata
  }
  if (Object.keys(j.Conditions).length === 0) {
    delete j.Conditions
  }
  if (Object.keys(j.Mappings).length === 0) {
    delete j.Mappings
  }
  if (Object.keys(j.Outputs).length === 0) {
    delete j.Outputs
  }
  if (Object.keys(j.Parameters).length === 0) {
    delete j.Parameters
  }
  if (j.Description === '') {
    delete j.Description
  }
  if (errors.length === 0) {
    errors = null
  }
  return {
    Errors: errors,
    Template: JSON.stringify(j, null, 2)
  }
}

Template.prototype.toYaml = function () {
  let jsonResult = this.toJson()
  return { Errors: jsonResult.errors, Template: yaml.safeDump(JSON.parse(jsonResult.Template)) }
}

module.exports = {
  Template: Template
}
<commit_msg>Fixed all outstanding unit tests.<commit_after>/**
 * Created by arming on 6/15/16.
 */
'use strict'
const ValueException = require('./exceptions').ValueException
const TypeException = require('./exceptions').TypeException
const Mapping = require('./mapping').Mapping
const Output = require('./output').Output
const Parameter = require('./parameter').Parameter
const WKResource = require('./resource').WKResource
const path = require('path')
const yaml = require('js-yaml')
const Service = require('./service')

/** @module Core */

function _handleDuplicateKey (key) {
  console.log('Duplicate key ' + key)
  throw new ValueException('duplicate key "%s" detected' % key)
}

function _add (d, values) {
  if (Array.isArray(values)) {
    values.forEach((v) => {
      if (v.WKName in d) {
        _handleDuplicateKey(v.WKName)
      }
      d[v.WKName] = v
    })
  } else {
    if (values.WKName in d) {
      _handleDuplicateKey(values.WKName)
    }
    d[values.WKName] = values
  }
  return values
}

function _remove (d, values) {
  if (Array.isArray(values)) {
    values.forEach((v) => {
      delete d[v.WKName]
    })
  } else {
    delete d[values.WKName]
  }
  return values
}

function _populateFromExisting(newTemplate, existingTemplate) {
  for (let param in existingTemplate.Parameters) {
    let newParam = new Parameter(param, existingTemplate.Parameters[param])
    newTemplate.add(newParam)
  }
  for (let output in existingTemplate.Outputs) {
    let newOutput = new Output(output, existingTemplate.Outputs[output])
    newTemplate.add(newOutput)
  }
  for (let mapping in existingTemplate.Mappings) {
    let newMapping = new Mapping(mapping, existingTemplate.Mappings[mapping])
    newTemplate.add(newMapping)
  }
  for (let resource in existingTemplate.Resources) {
    let typeSplit = existingTemplate.Resources[resource].Type.split('::')
    let resourceGroupName = typeSplit[1]
    let resourceGroup = null
    let resourceName = typeSplit[2]
    if (typeSplit[0] === 'Custom') {
      resourceGroup = require(path.join(__dirname, 'resources', 'cloudformation'))
      resourceName = 'CustomResource'
    } else {
      resourceGroup = require(path.join(__dirname, 'resources', resourceGroupName.toLowerCase()))
      /* if (resourceGroupName === 'Lambda' && resourceName === 'Function') {
        resourceName = 'LambdaFunction'
      } */
    }
    // let temp = Object.create(resourceGroup[resourceName].prototype)
    let serviceClient = Service(resourceGroupName)
    let newResource = new serviceClient[resourceName](resource, existingTemplate.Resources[resource].Properties)
    // let newResource = Reflect.construct(resourceGroup[resourceName], [resource, existingTemplate.Resources[resource].Properties])
    newTemplate.add(newResource)
  }
}

/**
 * @memberof module:Core
 */
function Template (template) {
  this.Description = ''
  this.Metadata = {}
  this.Conditions = {}
  this.Mappings = {}
  this.Outputs = {}
  this.Parameters = {}
  this.Resources = {}
  this.AWSTemplateFormatVersion = '2010-09-09'
  if (template) {
    _populateFromExisting(this, template)
  }
}

/**
 * Add an element to the Template
 * @param element
 */
Template.prototype.add = function (element) {
  if (element instanceof Parameter) {
    _add(this.Parameters, element)
  } else if (element instanceof WKResource) {
    _add(this.Resources, element)
  } else if (element instanceof Output) {
    _add(this.Outputs, element)
  } else if (element instanceof Mapping) {
    _add(this.Mappings, element)
  } else {
    throw new TypeException(element + ' is not a valid type and cannot be added to the template.')
  }
}

/**
 * Remove an element from the Template
 * @param element
 */
Template.prototype.remove = function (element) {
  if (element instanceof Parameter) {
    _remove(this.Parameters, element)
  } else if (element instanceof WKResource) {
    _remove(this.Resources, element)
  } else if (element instanceof Output) {
    _remove(this.Outputs, element)
  } else if (element instanceof Mapping) {
    _remove(this.Mappings, element)
  } else {
    throw new TypeException(element + ' is not a valid type and cannot be added to the template.')
  }
}

/**
 * Set the metadata value of the template
 * @param metadata
 */
Template.prototype.setMetadata = function (metadata) {
  this.Metadata = metadata
}

/**
 * Set the version value of the template
 * @param version
 */
Template.prototype.setVersion = function (version) {
  this.Version = version
}

/**
 * Add a description to the template
 * @param description
 */
Template.prototype.setDescription = function (description) {
  this.Description = description
}

/**
 * Add a condition to the template
 * @param name
 * @param condition
 */
Template.prototype.addCondition = function (name, condition) {
  this.Conditions[name] = condition
}

/**
 * Remove a condition from the template
 * @param name
 * @param condition
 */
Template.prototype.removeCondition = function (name, condition) {
  delete this.Conditions[name]
}

/**
 *
 * @param callback
 */
Template.prototype.toJsonAsync = function (callback) {
  if (callback) {
    let result = this.toJson()
    if (result.Errors) {
      callback(result.Errors, result.Template)
    } else {
      callback(null, result.Template)
    }
  } else {
    return new Promise((resolve, reject) => {
      process.nextTick(() => {
        let result = this.toJson()
        if (result.Errors) {
          reject({ Errors: result.Errors, Template: result.Template })
        } else {
          resolve(result.Template)
        }
      })
    })
  }
}

/**
 * Returns a CloudFormation JSON template string
 * @returns {Object}
 */
Template.prototype.toJson = function () {
  let j = JSON.parse(JSON.stringify(this))
  let errors = []
  for (let param in this.Parameters) {
    try {
      j.Parameters[param] = this.Parameters[param].toJson()
    } catch (e) {
      errors.push(e.message)
    }
  }
  for (let resource in this.Resources) {
    let result = this.Resources[resource].toJson()
    if (result.errors) {
      result.errors.forEach((e) => {
        errors.push(e)
      })
    }
    j.Resources[resource] = result.json
  }
  for (let output in this.Outputs) {
    try {
      j.Outputs[output] = this.Outputs[output].toJson()
    } catch (e) {
      errors.push(e.message)
    }
  }
  for (let map in this.Mappings) {
    if (this.Mappings[map] instanceof Mapping) {
      try {
        j.Mappings[map] = this.Mappings[map].toJson()
      } catch (e) {
        errors.push(e.message)
      }
    } else {
      j.Mappings[map] = this.Mappings[map]
    }
  }
  if (Object.keys(j.Metadata).length === 0) {
    delete j.Metadata
  }
  if (Object.keys(j.Conditions).length === 0) {
    delete j.Conditions
  }
  if (Object.keys(j.Mappings).length === 0) {
    delete j.Mappings
  }
  if (Object.keys(j.Outputs).length === 0) {
    delete j.Outputs
  }
  if (Object.keys(j.Parameters).length === 0) {
    delete j.Parameters
  }
  if (j.Description === '') {
    delete j.Description
  }
  if (errors.length === 0) {
    errors = null
  }
  return {
    Errors: errors,
    Template: JSON.stringify(j, null, 2)
  }
}

Template.prototype.toYaml = function () {
  let jsonResult = this.toJson()
  return { Errors: jsonResult.errors, Template: yaml.safeDump(JSON.parse(jsonResult.Template)) }
}

module.exports = {
  Template: Template
}
<|endoftext|>


<commit_before>function Tileset(options) {
  options = options || {}
  this.width = options.width || 128;
  this.height = options.height || 256;
  this.tileWidth = options.tileWidth || 8;
  this.tileHeight = options.tileHeight || 16;
  this.name = options.name || "tileset.png";

  this.setup = function (loader, resources) {
    var baseTexture = resources[this.name].texture.baseTexture;
    baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST;
    this.tiles = {}
    var x = 0, y = 0;
    var numTiles =
	(this.width / this.tileWidth) *	(this.height / this.tileHeight);
    for (var i = 0; i < numTiles; i++) {
      var frame = new PIXI.Rectangle(x, y, this.tileWidth, this.tileHeight);
      this.tiles[i] = new PIXI.Texture(baseTexture, frame);
      x += this.tileWidth;
      if (x >= this.width) {
	x = 0;
	y += this.tileHeight;
      }
    }

    if (typeof this.loaded === "function") {
      this.loaded();
    }
  }

  PIXI.loader.add(this.name, this.name).load(this.setup.bind(this));
}

function Terminal(options) {
  const FG_COLOR_DEFAULT = 0xffffff;
  const BG_COLOR_DEFAULT = 0x000000;

  options = options || {}
  this.scrWidth = options.scrWidth || 640;
  this.scrHeight = options.scrHeight || 480;
  this.width = options.width || 80;
  this.height = options.height || 30;
  this.tileset = options.tileset || new Tileset();

  this.renderer =
    new PIXI.autoDetectRenderer(this.scrWidth, this.scrHeight,
				{antialiasing: false,
				 resolution: window.devicePixelRatio});
  this.view = this.renderer.view;
  this.view.className = "terminal";

  this.stage = new PIXI.Container();

  var setup = function () {
    // background layer (for text background colors)
    this.background = new PIXI.Graphics();
    this.background.beginFill(BG_COLOR_DEFAULT);
    this.background.drawRect(0, 0, this.scrWidth, this.scrHeight);
    this.stage.addChild(this.background);

    // text layer
    this.sprites = [];
    this.chars = [];
    this.spriteWidth = this.scrWidth / this.width;
    this.spriteHeight = this.scrHeight / this.height;
    for (var x = 0; x < this.width; x++) {
      var spriteCol = [];
      var charCol = [];
      for (var y = 0; y < this.height; y++) {
	var sprite = new PIXI.Sprite(this.tileset.tiles[0]);
	sprite.position.x = x * this.spriteWidth;
	sprite.position.y = y * this.spriteHeight;
	sprite.width = this.spriteWidth;
	sprite.height = this.spriteHeight;
	spriteCol.push(sprite);
	charCol.push({value: 0, fg: FG_COLOR_DEFAULT, bg: BG_COLOR_DEFAULT});
	this.stage.addChild(sprite);
      }
      this.sprites.push(spriteCol);
      this.chars.push(charCol);
    }

    // foreground graphics layer
    this.foreground = new PIXI.Graphics();
    this.stage.addChild(this.foreground);

    this.animate();

    if (typeof this.ready === "function") {
      this.ready();
    }
  }
  this.tileset.loaded = setup.bind(this);

  this.animate = function () {
    requestAnimationFrame(this.animate.bind(this));

    if (typeof this.update === "function") {
      this.update();
    }

    this.renderer.render(this.stage);
  }

  //
  // --- text methods ----
  //
  this.putChar = function(x, y, c, fg, bg) {
    if (typeof fg === "undefined") { fg = FG_COLOR_DEFAULT };
    if (typeof bg === "undefined") { bg = BG_COLOR_DEFAULT };
    var value = (typeof c == "string") ? c.charCodeAt(0) : c;
    this.chars[x][y] = {value: value, fg: fg, bg: bg};
    this.sprites[x][y].texture = this.tileset.tiles[value];
    this.sprites[x][y].tint = fg;
    // bg
    this.background.beginFill(bg);
    this.background.drawRect(this.sprites[x][y].position.x,
			     this.sprites[x][y].position.y,
			     this.spriteWidth, this.spriteHeight);
    this.background.endFill();
  }

  this.getChar = function(x, y) {
    return this.chars[x][y].value;
  }
  this.getCharFG = function(x, y) {
    return this.chars[x][y].fg;
  }
  this.getCharBG = function(x, y) {
    return this.chars[x][y].bg;
  }
  this.getCharAttribs = function(x, y) {
    return this.chars[x][y];
  }

  this.putString = function(x, y, str, fg, bg) {
    var curX = x, curY = y;
    for (var i = 0; i < str.length; i++) {
      var c = str.charAt(i);
      if (c == "\n") {
	curX = x;
	curY++;
      } else {
        this.putChar(curX++, curY, c, fg, bg)
      }
    }
  }

  this.clearText = function(bg) {
    for (var x = 0; x < this.width; x++) {
      for (var y = 0; y < this.height; y++) {
	terminal.putChar(x, y, 0, null, bg);
      }
    }
  }

  this.clearDraw = function() {
    this.foreground.clear();
  }

  this.clear = function(bg) {
    this.clearText(bg);
    this.clearDraw();
  }

  //
  // --- drawing methods ----
  //
  this.drawPixel = function(x, y, col) {
    if (typeof col === "undefined") { col = FG_COLOR_DEFAULT };
    this.foreground.beginFill(col);
    this.foreground.drawRect(x, y, 1, 1);
    this.foreground.endFill();
  }

  this.drawHorizLine = function(x0, x1, y, col) {
    for (var x = Math.min(x0, x1); x <= Math.max(x0, x1); x++) {
      this.drawPixel(x, y, col);
    }
  }

  this.drawVertLine = function(x, y0, y1, col) {
    for (var y = Math.min(y0, y1); y <= Math.max(y0, y1); y++) {
      this.drawPixel(x, y, col);
    }
  }

  // Bresenham's algorithm
  this.drawLine = function(x0, y0, x1, y1, col) {
    if (x0 > x1) {
      var tmp = x1; x1 = x0; x0 = tmp;
      tmp = y1; y1 = y0; y0 = tmp;
    }
    if (Math.abs(x0 - x1) < 1) {  // vertical line
      this.drawVertLine(x0, y0, y1, col);
    } else {
      var deltax = x1 - x0;
      var deltay = y1 - y0;
      var error = 0;
      var deltaerr = Math.abs(deltay / deltax);
      var y = y0;
      for (var x = x0; x <= x1; x++) {
	this.drawPixel(x, y, col);
	error += deltaerr;
	while (error >= 0.5) {
	  this.drawPixel(x, y);
	  y += Math.sign(y1 - y0, col);
	  error -= 1.0;
	}
      }
    }
  }

  this.drawRect = function(x0, y0, x1, y1, col) {
    this.drawHorizLine(x0, x1, y0, col);
    this.drawHorizLine(x0, x1, y1, col);
    this.drawVertLine(x0, Math.min(y0, y1) + 1, Math.max(y0, y1) - 1, col);
    this.drawVertLine(x1, Math.min(y0, y1) + 1, Math.max(y0, y1) - 1, col);
  }

  this.fillRect = function(x0, y0, x1, y1, col) {
    for (var y = Math.min(y0, y1); y <= Math.max(y0, y1); y++) {
      this.drawHorizLine(x0, x1, y, col);
    }
  }

  // algorithm: https://web.archive.org/web/20120225095359/ ...
  // http://homepage.smc.edu/kennedy_john/belipse.pdf
  this._plot4 = function (cx, cy, x, y, col) {
    this.drawPixel(cx + x, cy + y, col);
    this.drawPixel(cx - x, cy + y, col);
    this.drawPixel(cx - x, cy - y, col);
    this.drawPixel(cx + x, cy - y, col);
  }

  this.drawEllipse = function(cx, cy, xradius, yradius, col) {
    var twoASquare = 2 * xradius * xradius;
    var twoBSquare = 2 * yradius * yradius;
    // 1st set
    var x = xradius, y = 0;
    var xchange = yradius * yradius * (1 - 2 * xradius);
    var ychange = xradius * xradius;
    var ellipseError = 0;
    var stoppingX = twoBSquare * xradius;
    var stoppingY = 0;
    while (stoppingX >= stoppingY) {
      this._plot4(cx, cy, x, y, col);
      y++;
      stoppingY += twoASquare;
      ellipseError += ychange;
      ychange += twoASquare;
      if ((2 * ellipseError + xchange) > 0) {
	x--;
	stoppingX -= twoBSquare;
	ellipseError += xchange;
	xchange += twoBSquare;
      }
    }
    // 2nd set
    x = 0;
    y = yradius;
    xchange = yradius * yradius;
    ychange = xradius * xradius * (1 - 2 * yradius);
    ellipseError = 0;
    stoppingX = 0;
    stoppingY = twoASquare * yradius;
    while (stoppingX <= stoppingY) {
      this._plot4(cx, cy, x, y, col);
      x++;
      stoppingX += twoBSquare;
      ellipseError += xchange;
      xchange += twoBSquare;
      if ((2 * ellipseError + ychange) > 0) {
	y--;
	stoppingY -= twoASquare;
	ellipseError += ychange;
	ychange += twoASquare;
      }
    }
  }

  this.fillEllipse = function(cx, cy, xradius, yradius, col) {
    for (var x = cx - xradius; x <= cx + xradius; x++) {
      for (var y = cy - yradius; y <= cy + yradius; y++) {
	if ((x-cx)*(x-cx)/(xradius*xradius)+
	    (y-cy)*(y-cy)/(yradius*yradius) <= 1) {
    	  this.drawPixel(x, y);
	}
      }
    }
  }
}
<commit_msg>putChar now uses old fg and bg as default<commit_after>function Tileset(options) {
  options = options || {}
  this.width = options.width || 128;
  this.height = options.height || 256;
  this.tileWidth = options.tileWidth || 8;
  this.tileHeight = options.tileHeight || 16;
  this.name = options.name || "tileset.png";

  this.setup = function (loader, resources) {
    var baseTexture = resources[this.name].texture.baseTexture;
    baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST;
    this.tiles = {}
    var x = 0, y = 0;
    var numTiles =
	(this.width / this.tileWidth) *	(this.height / this.tileHeight);
    for (var i = 0; i < numTiles; i++) {
      var frame = new PIXI.Rectangle(x, y, this.tileWidth, this.tileHeight);
      this.tiles[i] = new PIXI.Texture(baseTexture, frame);
      x += this.tileWidth;
      if (x >= this.width) {
	x = 0;
	y += this.tileHeight;
      }
    }

    if (typeof this.loaded === "function") {
      this.loaded();
    }
  }

  PIXI.loader.add(this.name, this.name).load(this.setup.bind(this));
}

function Terminal(options) {
  const FG_COLOR_DEFAULT = 0xffffff;
  const BG_COLOR_DEFAULT = 0x000000;

  options = options || {}
  this.scrWidth = options.scrWidth || 640;
  this.scrHeight = options.scrHeight || 480;
  this.width = options.width || 80;
  this.height = options.height || 30;
  this.tileset = options.tileset || new Tileset();

  this.renderer =
    new PIXI.autoDetectRenderer(this.scrWidth, this.scrHeight,
				{antialiasing: false,
				 resolution: window.devicePixelRatio});
  this.view = this.renderer.view;
  this.view.className = "terminal";

  this.stage = new PIXI.Container();

  var setup = function () {
    // background layer (for text background colors)
    this.background = new PIXI.Graphics();
    this.background.beginFill(BG_COLOR_DEFAULT);
    this.background.drawRect(0, 0, this.scrWidth, this.scrHeight);
    this.stage.addChild(this.background);

    // text layer
    this.sprites = [];
    this.chars = [];
    this.spriteWidth = this.scrWidth / this.width;
    this.spriteHeight = this.scrHeight / this.height;
    for (var x = 0; x < this.width; x++) {
      var spriteCol = [];
      var charCol = [];
      for (var y = 0; y < this.height; y++) {
	var sprite = new PIXI.Sprite(this.tileset.tiles[0]);
	sprite.position.x = x * this.spriteWidth;
	sprite.position.y = y * this.spriteHeight;
	sprite.width = this.spriteWidth;
	sprite.height = this.spriteHeight;
	spriteCol.push(sprite);
	charCol.push({value: 0, fg: FG_COLOR_DEFAULT, bg: BG_COLOR_DEFAULT});
	this.stage.addChild(sprite);
      }
      this.sprites.push(spriteCol);
      this.chars.push(charCol);
    }

    // foreground graphics layer
    this.foreground = new PIXI.Graphics();
    this.stage.addChild(this.foreground);

    this.animate();

    if (typeof this.ready === "function") {
      this.ready();
    }
  }
  this.tileset.loaded = setup.bind(this);

  this.animate = function () {
    requestAnimationFrame(this.animate.bind(this));

    if (typeof this.update === "function") {
      this.update();
    }

    this.renderer.render(this.stage);
  }

  //
  // --- text methods ----
  //
  this.putChar = function(x, y, c, fg, bg) {
    if (typeof fg === "undefined") { fg = this.getCharFG(x, y) };
    var value = (typeof c == "string") ? c.charCodeAt(0) : c;
    this.chars[x][y] = {value: value, fg: fg, bg: bg};
    this.sprites[x][y].texture = this.tileset.tiles[value];
    this.sprites[x][y].tint = fg;
    if (typeof bg !== "undefined") {
      // bg
      this.background.beginFill(bg);
      this.background.drawRect(this.sprites[x][y].position.x,
			       this.sprites[x][y].position.y,
			       this.spriteWidth, this.spriteHeight);
      this.background.endFill();
    }
  }

  this.getChar = function(x, y) {
    return this.chars[x][y].value;
  }
  this.getCharFG = function(x, y) {
    return this.chars[x][y].fg;
  }
  this.getCharBG = function(x, y) {
    return this.chars[x][y].bg;
  }
  this.getCharAttribs = function(x, y) {
    return this.chars[x][y];
  }

  this.putString = function(x, y, str, fg, bg) {
    var curX = x, curY = y;
    for (var i = 0; i < str.length; i++) {
      var c = str.charAt(i);
      if (c == "\n") {
	curX = x;
	curY++;
      } else {
        this.putChar(curX++, curY, c, fg, bg)
      }
    }
  }

  this.clearText = function(bg) {
    for (var x = 0; x < this.width; x++) {
      for (var y = 0; y < this.height; y++) {
	terminal.putChar(x, y, 0, null, bg);
      }
    }
  }

  this.clearDraw = function() {
    this.foreground.clear();
  }

  this.clear = function(bg) {
    this.clearText(bg);
    this.clearDraw();
  }

  //
  // --- drawing methods ----
  //
  this.drawPixel = function(x, y, col) {
    if (typeof col === "undefined") { col = FG_COLOR_DEFAULT };
    this.foreground.beginFill(col);
    this.foreground.drawRect(x, y, 1, 1);
    this.foreground.endFill();
  }

  this.drawHorizLine = function(x0, x1, y, col) {
    for (var x = Math.min(x0, x1); x <= Math.max(x0, x1); x++) {
      this.drawPixel(x, y, col);
    }
  }

  this.drawVertLine = function(x, y0, y1, col) {
    for (var y = Math.min(y0, y1); y <= Math.max(y0, y1); y++) {
      this.drawPixel(x, y, col);
    }
  }

  // Bresenham's algorithm
  this.drawLine = function(x0, y0, x1, y1, col) {
    if (x0 > x1) {
      var tmp = x1; x1 = x0; x0 = tmp;
      tmp = y1; y1 = y0; y0 = tmp;
    }
    if (Math.abs(x0 - x1) < 1) {  // vertical line
      this.drawVertLine(x0, y0, y1, col);
    } else {
      var deltax = x1 - x0;
      var deltay = y1 - y0;
      var error = 0;
      var deltaerr = Math.abs(deltay / deltax);
      var y = y0;
      for (var x = x0; x <= x1; x++) {
	this.drawPixel(x, y, col);
	error += deltaerr;
	while (error >= 0.5) {
	  this.drawPixel(x, y);
	  y += Math.sign(y1 - y0, col);
	  error -= 1.0;
	}
      }
    }
  }

  this.drawRect = function(x0, y0, x1, y1, col) {
    this.drawHorizLine(x0, x1, y0, col);
    this.drawHorizLine(x0, x1, y1, col);
    this.drawVertLine(x0, Math.min(y0, y1) + 1, Math.max(y0, y1) - 1, col);
    this.drawVertLine(x1, Math.min(y0, y1) + 1, Math.max(y0, y1) - 1, col);
  }

  this.fillRect = function(x0, y0, x1, y1, col) {
    for (var y = Math.min(y0, y1); y <= Math.max(y0, y1); y++) {
      this.drawHorizLine(x0, x1, y, col);
    }
  }

  // algorithm: https://web.archive.org/web/20120225095359/ ...
  // http://homepage.smc.edu/kennedy_john/belipse.pdf
  this._plot4 = function (cx, cy, x, y, col) {
    this.drawPixel(cx + x, cy + y, col);
    this.drawPixel(cx - x, cy + y, col);
    this.drawPixel(cx - x, cy - y, col);
    this.drawPixel(cx + x, cy - y, col);
  }

  this.drawEllipse = function(cx, cy, xradius, yradius, col) {
    var twoASquare = 2 * xradius * xradius;
    var twoBSquare = 2 * yradius * yradius;
    // 1st set
    var x = xradius, y = 0;
    var xchange = yradius * yradius * (1 - 2 * xradius);
    var ychange = xradius * xradius;
    var ellipseError = 0;
    var stoppingX = twoBSquare * xradius;
    var stoppingY = 0;
    while (stoppingX >= stoppingY) {
      this._plot4(cx, cy, x, y, col);
      y++;
      stoppingY += twoASquare;
      ellipseError += ychange;
      ychange += twoASquare;
      if ((2 * ellipseError + xchange) > 0) {
	x--;
	stoppingX -= twoBSquare;
	ellipseError += xchange;
	xchange += twoBSquare;
      }
    }
    // 2nd set
    x = 0;
    y = yradius;
    xchange = yradius * yradius;
    ychange = xradius * xradius * (1 - 2 * yradius);
    ellipseError = 0;
    stoppingX = 0;
    stoppingY = twoASquare * yradius;
    while (stoppingX <= stoppingY) {
      this._plot4(cx, cy, x, y, col);
      x++;
      stoppingX += twoBSquare;
      ellipseError += xchange;
      xchange += twoBSquare;
      if ((2 * ellipseError + ychange) > 0) {
	y--;
	stoppingY -= twoASquare;
	ellipseError += ychange;
	ychange += twoASquare;
      }
    }
  }

  this.fillEllipse = function(cx, cy, xradius, yradius, col) {
    for (var x = cx - xradius; x <= cx + xradius; x++) {
      for (var y = cy - yradius; y <= cy + yradius; y++) {
	if ((x-cx)*(x-cx)/(xradius*xradius)+
	    (y-cy)*(y-cy)/(yradius*yradius) <= 1) {
    	  this.drawPixel(x, y);
	}
      }
    }
  }
}
<|endoftext|>


<commit_before>require('./errorcodes');
require('./errormessages');
<commit_msg>Included peer-send test in all tests<commit_after>require('./errorcodes');
require('./errormessages');

require('./peer-send');
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

var testName = 'Bob Jr';
var testWork = 'Test Work';
var testEmail = 'bob@example.com';
var testWebsite = 'http://www.example.com';
var testLicenses = [
  'CC-BY-4.0',
  'CC-BY-SA-4.0',
  'CC-BY-ND-4.0',
  'CC-BY-NC-4.0',
  'CC-BY-NC-SA-4.0',
  'CC-NY-NC-ND-4.0'
];

var testOutput = 'LICENSE';

describe('generator-license-cc:app', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        work: testWork,
        email: testEmail,
        website: testWebsite,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file', function () {
    assert.file([
      'LICENSE'
    ]);
  });

  it('does not create package.json file', function () {
    assert.noFile('package.json');
  });
});

<commit_msg>travis-ci<commit_after>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

var testName = 'Bob Jr';
var testWork = 'Test Work';
var testEmail = 'bob@example.com';
var testWebsite = 'http://www.example.com';
var testLicenses = [
  'CC-BY-4.0',
  'CC-BY-SA-4.0',
  'CC-BY-ND-4.0',
  'CC-BY-NC-4.0',
  'CC-BY-NC-SA-4.0',
  'CC-NY-NC-ND-4.0'
];

var testOutput = 'LICENSE';

describe('generator-license-cc:app', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        work: testWork,
        email: testEmail,
        website: testWebsite,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file', function () {
    assert.file([
      'LICENSE'
    ]);
  });

  it('does not create package.json file', function () {
    assert.noFile('package.json');
  });
});
<|endoftext|>


<commit_before>var request = require('supertest');
var app = require('../index.js');

describe('GET / in development env', function() {
  it('should return 200 OK', function(done) {
    request(app)
      .get('/')
      .expect(200, done);
  });
});

describe('GET /about in development env', function() {
  it('should return 404 Page Not Found', function(done) {
    request(app)
      .get('/about')
      .expect(404, done);
  });
});

app.set('env', 'production');

describe('GET / in production env', function() {
  it('should return 200 OK', function(done) {
    request(app)
      .get('/')
      .expect(200, done);
  });
});

describe('GET /about in production env', function() {
  it('should return 404 Page Not Found', function(done) {
    request(app)
      .get('/about')
      .expect(404, done);
  });
});
<commit_msg>Revert back tests<commit_after>var request = require('supertest');
var app = require('../index.js');

describe('GET /', function() {
  it('should return 200 OK', function(done) {
    request(app)
      .get('/')
      .expect(200, done);
  });
});

describe('GET /about', function() {
  it('should return 404 Page Not Found', function(done) {
    request(app)
      .get('/about')
      .expect(404, done);
  });
});
<|endoftext|>


<commit_before>var test = require("tape"),
    fs = require("fs"),
    path = require("path"),
    mfs = require("more-fs"),
    exec = require("child_process").exec;

function initFixture(){
    mfs.rmdir("test/fixture");
    mfs.write("test/fixture/clive1.txt");
    mfs.write("test/fixture/clive2.txt");
    mfs.write("test/fixture/file3.txt");
}
function _test(){
    initFixture();
    return test.apply(test, arguments);
}

test("cli: no args", function(t){
    initFixture();
    t.plan(2);
    exec("./bin/cli.js", function(err, stdout, stderr){
        t.ok(/Usage:/.test(stdout), "usage is there");
        if (err) {
            t.error(err);
        } else {
            t.pass("ran ok. ")
        }
    });
});

test("cli: simple replace", function(t){
    initFixture();
    t.plan(6);
    exec("./bin/cli.js -f clive -r hater test/fixture/*", function(err, stdout, stderr){
        if (err) {
            t.error(err);
        } else {
            t.pass("ran ok. ")
        }

        t.notOk(fs.existsSync(path.join("test", "fixture", "clive1.txt")), "file doesn't exist");
        t.notOk(fs.existsSync(path.join("test", "fixture", "clive2.txt")), "file doesn't exist");
        t.ok(fs.existsSync(path.join("test", "fixture", "hater1.txt")), "file exists");
        t.ok(fs.existsSync(path.join("test", "fixture", "hater2.txt")), "file exists");
        t.ok(fs.existsSync(path.join("test", "fixture", "file3.txt")), "file exists");
    });
});
<commit_msg>win friendly exec<commit_after>var test = require("tape"),
    fs = require("fs"),
    path = require("path"),
    mfs = require("more-fs"),
    exec = require("child_process").exec;

function initFixture(){
    mfs.rmdir("test/fixture");
    mfs.write("test/fixture/clive1.txt");
    mfs.write("test/fixture/clive2.txt");
    mfs.write("test/fixture/file3.txt");
}
function _test(){
    initFixture();
    return test.apply(test, arguments);
}

test("cli: no args", function(t){
    initFixture();
    t.plan(2);
    exec("node bin/cli.js", function(err, stdout, stderr){
        t.ok(/Usage:/.test(stdout), "usage is there");
        if (err) {
            t.error(err);
        } else {
            t.pass("ran ok. ")
        }
    });
});

test("cli: simple replace", function(t){
    initFixture();
    t.plan(6);
    exec("node bin/cli.js -f clive -r hater test/fixture/*", function(err, stdout, stderr){
        if (err) {
            t.error(err);
        } else {
            t.pass("ran ok. ")
        }

        t.notOk(fs.existsSync(path.join("test", "fixture", "clive1.txt")), "file doesn't exist");
        t.notOk(fs.existsSync(path.join("test", "fixture", "clive2.txt")), "file doesn't exist");
        t.ok(fs.existsSync(path.join("test", "fixture", "hater1.txt")), "file exists");
        t.ok(fs.existsSync(path.join("test", "fixture", "hater2.txt")), "file exists");
        t.ok(fs.existsSync(path.join("test", "fixture", "file3.txt")), "file exists");
    });
});
<|endoftext|>


<commit_before>var cp     = require('child_process');
var expect = require('expect.js');

module.exports = function () {
    describe('CLI', function () {
        it('should error if task file does not exist', function (done) {
            cp.exec('node bin/automaton something-that-will-never-exist', function (err, stdout, stderr) {
                expect(stderr).to.match(/could not find/i);
            }).on('exit', function (code) {
                expect(code).to.equal(1);
                done();
            });
        });

        it('should exit with an appropriate code if a task fails', function (done) {
            cp.exec('node bin/automaton test/helpers/tasks/dummy-mandatory', function (err, stdout) {
                expect(stdout).to.match(/mandatory/);
            }).on('exit', function (code) {
                expect(code).to.equal(1);

                cp.exec('node bin/automaton test/helpers/tasks/dummy-mandatory --mandatory=foo')
                  .on('exit', function (code) {
                    expect(code).to.equal(0);
                    done();
                });
            });
        });
    });
};<commit_msg>Increase timeout of CLI tests to let the update notifier do the job.<commit_after>var cp     = require('child_process');
var expect = require('expect.js');

module.exports = function () {
    describe('CLI', function () {
        this.timeout(10000); // Increase the timeout to let the update-notifier do it's job

        it('should error if task file does not exist', function (done) {
            cp.exec('node bin/automaton something-that-will-never-exist', function (err, stdout, stderr) {
                expect(stderr).to.match(/could not find/i);
            }).on('exit', function (code) {
                expect(code).to.equal(1);
                done();
            });
        });

        it('should exit with an appropriate code if a task fails', function (done) {
            cp.exec('node bin/automaton test/helpers/tasks/dummy-mandatory', function (err, stdout) {
                expect(stdout).to.match(/mandatory/);
            }).on('exit', function (code) {
                expect(code).to.equal(1);

                cp.exec('node bin/automaton test/helpers/tasks/dummy-mandatory --mandatory=foo')
                  .on('exit', function (code) {
                    expect(code).to.equal(0);
                    done();
                });
            });
        });
    });
};<|endoftext|>


<commit_before>gt.module('End 2 end tests');

var path = require('path');
var xplain = path.join(__dirname, '../index.js');
var examples = path.join(__dirname, '../examples');

gt.async('basic', 1, function () {
    var js = path.join(examples, 'basic/*.js');
    var docs = path.join(examples, 'basic/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'basic api');
}, 4000);

gt.async('submodules', 1, function () {
    var js = path.join(examples, 'submodules/*.js');
    var docs = path.join(examples, 'submodules/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'submodules');
}, 4000);

gt.async('add', 1, function () {
    var js = path.join(examples, 'add/*.js');
    var docs = path.join(examples, 'add/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'add');
}, 4000);

gt.async('qunit', 1, function () {
    var js = path.join(examples, 'qunit/*.js');
    var docs = path.join(examples, 'qunit/docs');
    gt.exec('node', [xplain, '--input', js, '--output', docs], 0, 'qunit');
}, 4000);

gt.async('lodash', 1, function () {
    var js = path.join(examples, 'lodash/*.js');
    var docs = path.join(examples, 'lodash/docs');
    gt.exec('node', [xplain, '--input', js, '--output', docs, '--title', 'lodash example'], 0, 'lodash');
}, 4000);

gt.async('anonymous', 1, function () {
    var js = path.join(examples, 'anonymous/*.js');
    var docs = path.join(examples, 'anonymous/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'anonymous');
}, 4000);

gt.async('immediate', 1, function () {
    var js = path.join(examples, 'immediate/*.js');
    var docs = path.join(examples, 'immediate/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'immediate');
}, 4000);

gt.async('unnamed', 1, function () {
    var js = path.join(examples, 'unnamed/*.js');
    var docs = path.join(examples, 'unnamed/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'unnamed');
}, 4000);

gt.async('deprecated', 1, function () {
    var js = path.join(examples, 'deprecated/*.js');
    var docs = path.join(examples, 'deprecated/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'deprecated');
}, 4000);

gt.async('sort', 1, function () {
    var js = path.join(examples, 'sort/*.js');
    var docs = path.join(examples, 'sort/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'sort');
}, 2000);

gt.async('long', 1, function () {
    var js = path.join(examples, 'long/test.js');
    var docs = path.join(examples, 'long/docs');
    gt.exec('node', [xplain, '--input', js, '--output', docs], 0, 'long');
}, 2000);

gt.async('jasmine', 1, function () {
    var js = path.join(examples, 'jasmine/spec.js');
    var docs = path.join(examples, 'jasmine/docs');
    gt.exec('node', [xplain, '-f', 'jasmine', '--input', js, '--output', docs], 0, 'jasmine');
}, 2000);

gt.async('external', 1, function () {
    var js = path.join(examples, 'external/test.js');
    var docs = path.join(examples, 'external/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'external');
}, 2000);

gt.async('underscore', 1, function () {
    var js = path.join(examples, 'underscore/test.js');
    var docs = path.join(examples, 'underscore/docs');
    gt.exec('node', [xplain, '--input', js, '--output', docs, '--title', 'underscore'], 0, 'underscore');
}, 2000);<commit_msg>fixed e2e example unit test<commit_after>gt.module('End 2 end tests');

var path = require('path');
var xplain = path.join(__dirname, '../index.js');
var examples = path.join(__dirname, '../examples');

gt.async('basic', 1, function () {
    var js = path.join(examples, 'basic/*.js');
    var docs = path.join(examples, 'basic/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'basic api');
}, 4000);

gt.async('submodules', 1, function () {
    var js = path.join(examples, 'submodules/*.js');
    var docs = path.join(examples, 'submodules/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'submodules');
}, 4000);

gt.async('add', 1, function () {
    var js = path.join(examples, 'add/*.js');
    var docs = path.join(examples, 'add/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'add');
}, 4000);

gt.async('qunit', 1, function () {
    var js = path.join(examples, 'qunit/*.js');
    var docs = path.join(examples, 'qunit/docs');
    gt.exec('node', [xplain, '--input', js, '--output', docs], 0, 'qunit');
}, 4000);

gt.async('lodash', 1, function () {
    var js = path.join(examples, 'lodash/*.js');
    var docs = path.join(examples, 'lodash/docs');
    gt.exec('node', [xplain, '--input', js, '--output', docs, '--title', 'lodash example'], 0, 'lodash');
}, 4000);

gt.async('anonymous', 1, function () {
    var js = path.join(examples, 'anonymous/*.js');
    var docs = path.join(examples, 'anonymous/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'anonymous');
}, 4000);

gt.async('immediate', 1, function () {
    var js = path.join(examples, 'immediate/*.js');
    var docs = path.join(examples, 'immediate/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'immediate');
}, 4000);

gt.async('unnamed', 1, function () {
    var js = path.join(examples, 'unnamed/*.js');
    var docs = path.join(examples, 'unnamed/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'unnamed');
}, 4000);

gt.async('deprecated', 1, function () {
    var js = path.join(examples, 'deprecated/*.js');
    var docs = path.join(examples, 'deprecated/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'deprecated');
}, 4000);

gt.async('sort', 1, function () {
    var js = path.join(examples, 'sort/*.js');
    var docs = path.join(examples, 'sort/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'sort');
}, 2000);

gt.async('long', 1, function () {
    var js = path.join(examples, 'long/test.js');
    var docs = path.join(examples, 'long/docs');
    gt.exec('node', [xplain, '--input', js, '--output', docs], 0, 'long');
}, 2000);

gt.async('jasmine', 1, function () {
    var js = path.join(examples, 'jasmine/spec.js');
    var docs = path.join(examples, 'jasmine/docs');
    gt.exec('node', [xplain, '-f', 'jasmine', '--input', js, '--output', docs], 0, 'jasmine');
}, 2000);

gt.async('external', 1, function () {
    var js = path.join(examples, 'external/test.js');
    var docs = path.join(examples, 'external/docs');
    gt.exec('node', [xplain, '-f', 'gt', '--input', js, '--output', docs], 0, 'external');
}, 2000);

gt.async('underscore', 1, function () {
    var js = path.join(examples, 'underscore/*.js');
    var docs = path.join(examples, 'underscore/docs');
    gt.exec('node', [xplain, '--input', js, '--output', docs, '--title', 'underscore'], 0, 'underscore');
}, 2000);<|endoftext|>


<commit_before>var path = require('path')
var HOME = path.join(__dirname, 'home')
process.env.HOME = HOME

var should = require('should')
  , gcr = require('../')
  , rimraf = require('rimraf')
  , sinon = require('sinon')

describe('gcr', function() {
  var server, port
  before(function(done) {
    rimraf.sync(__dirname + '/home/.config/gcr.json')
    rimraf.sync(__dirname + '/home/builds')
    server = require('./fixtures/server')
    server.listen(0, function(err) {
      if (err) return done(err)
      port = server.address().port
      done()
    })
  })

  it('should be an EventEmitter', function() {
    gcr.should.be.instanceOf(require('events').EventEmitter)
  })

  it('should have property root', function() {
    should.exist(gcr.root)
    gcr.root.should.equal(path.join(HOME, '.config'))
  })

  it('should have property loaded', function() {
    gcr.loaded.should.be.false
  })

  it('should have property version', function() {
    gcr.version.should.equal(require('../package').version)
  })

  it('should have property help', function() {
    gcr.should.have.property('help')
  })

  it('should have property key', function() {
    var kp = path.join(HOME, '.ssh', 'gcr.pub')
    gcr.key.should.equal(kp)
  })

  it('should have property utils', function() {
    should.exist(gcr.utils)
  })

  it('should allow loading', function(done) {
    gcr.loaded.should.be.false
    gcr.load({
      url: 'http://127.0.0.1:' + port
    , token: 'biscuits'
    , buildDir: '/tmp/gcr-builds'
    , npm: true
    , strictSSL: false
    , timeout: 5000
    , loglevel: 'silent'
    }, function(err) {
      if (err) return done(err)
      gcr.loaded.should.be.true
      done()
    })
  })

  it('should allow passing just a callback to load', function(done) {
    gcr.load(done)
  })

  it('gcr.config should exist after loading', function() {
    gcr.should.have.property('config')
  })

  describe('build', function() {
    var Build = require('../lib/build')
    var build

    it('should allow construction', function() {
      build = Build({
        commands: ['npm test']
      , timeout: 5000
      , project_id: 1
      , repo_url: 'git://github.com/evanlucas/gcr-test.git'
      , ref: 'origin/master'
      , allow_git_fetch: true
      , before_sha: 'blah'
      , ref_name: 'master'
      , id: 1
      })

      build.should.be.instanceOf(require('events').EventEmitter)
      build.should.have.property('git', gcr.config.get('git'))
      build.should.have.property('buildDir', gcr.config.get('buildDir'))
      build.should.have.property('opts')
      build.should.have.property('output')
      build.should.have.property('projectDir')
      build.projectDir.should.equal('/tmp/gcr-builds/project-1')
      build.should.have.property('state', 'waiting')
    })

    it('should run with clone', function(done) {
      this.timeout(10000)
      var sandbox = sinon.sandbox.create()
      sandbox.stub(build, 'update', function(cb) {
        cb && cb()
      })
      var count = 0
      function next() {
        count++
        if (count === 2) done()
      }
      build.on('done', function(success) {
        success.should.be.true
        sandbox.restore()
        done()
      })
      build.run()
      build.state.should.equal('running')
    })

    it('should run with fetch', function(done) {
      var build2 = Build({
        commands: ['npm test']
      , timeout: 5000
      , project_id: 2
      , repo_url: 'git://github.com/evanlucas/gcr-test.git'
      , ref: 'origin/master'
      , allow_git_fetch: false
      , before_sha: 'blah'
      , ref_name: 'master'
      , id: 2
      })
      this.timeout(10000)
      var sandbox = sinon.sandbox.create()
      sandbox.stub(gcr.client, 'updateBuild', function(id, s, o, cb) {
        cb && cb()
      })
      var count = 0
      function next() {
        count++
        if (count === 2) done()
      }
      build2.on('done', function(success) {
        success.should.be.true
        sandbox.restore()
        done()
      })
      build2.run()
      build2.state.should.equal('running')
    })
  })

  describe('client', function() {
    it('should be accessible via gcr.client', function() {
      should.exist(gcr.client)
    })

    it('apuUrl() should return gcr.config.get(\'url\')', function() {
      gcr.client.apiUrl().should.equal(gcr.config.get('url'))
    })

    describe('updateBuild', function() {
      it('should return null, true on success', function(done) {
        gcr.client.updateBuild(1, 'running', 'blah', function(err, out) {
          if (err) return done(err)
          out.should.be.true
          done()
        })
      })

      it('should return null, false on error', function(done) {
        gcr.client.updateBuild(1, 'running', 'blah2', function(err, out) {
          if (err) return done(err)
          out.should.be.false
          done()
        })
      })
    })

    describe('registerRunner', function() {
      it('should return null, token on success', function(done) {
        gcr.client.registerRunner(1, 'biscuits', function(err, out) {
          if (err) return done(err)
          should.exist(out)
          done()
        })
      })

      it('should return err on error', function(done) {
        gcr.client.registerRunner(1, 'blah', function(err, out) {
          should.exist(err)
          err.should.match(/Invalid response/)
          done()
        })
      })
    })

    describe('getBuild', function() {
      it('should return null, object on success', function(done) {
        gcr.config.set('token', 'biscuits')
        gcr.client.getBuild(done)
      })

      it('should return err on 403', function(done) {
        gcr.config.set('token', 'blah')
        gcr.client.getBuild(function(err, out) {
          should.exist(err)
          err.should.match(/Unable to get builds/)
          done()
        })
      })

      it('should return undefined on anything else', function(done) {
        gcr.config.set('token', 'baaaaa')
        gcr.client.getBuild(function(err, out) {
          if (err) return done(err)
          should.not.exist(out)
          done()
        })
      })
    })
  })

  describe('runner', function() {

  })

  describe('utils', function() {

  })
})
<commit_msg>Add a few tests for runner<commit_after>var path = require('path')
var HOME = path.join(__dirname, 'home')
process.env.HOME = HOME

var should = require('should')
  , gcr = require('../')
  , rimraf = require('rimraf')
  , sinon = require('sinon')

describe('gcr', function() {
  var server, port
  before(function(done) {
    rimraf.sync(__dirname + '/home/.config/gcr.json')
    rimraf.sync(__dirname + '/home/builds')
    server = require('./fixtures/server')
    server.listen(0, function(err) {
      if (err) return done(err)
      port = server.address().port
      done()
    })
  })

  it('should be an EventEmitter', function() {
    gcr.should.be.instanceOf(require('events').EventEmitter)
  })

  it('should have property root', function() {
    should.exist(gcr.root)
    gcr.root.should.equal(path.join(HOME, '.config'))
  })

  it('should have property loaded', function() {
    gcr.loaded.should.be.false
  })

  it('should have property version', function() {
    gcr.version.should.equal(require('../package').version)
  })

  it('should have property help', function() {
    gcr.should.have.property('help')
  })

  it('should have property key', function() {
    var kp = path.join(HOME, '.ssh', 'gcr.pub')
    gcr.key.should.equal(kp)
  })

  it('should have property utils', function() {
    should.exist(gcr.utils)
  })

  it('should allow loading', function(done) {
    gcr.loaded.should.be.false
    gcr.load({
      url: 'http://127.0.0.1:' + port
    , token: 'biscuits'
    , buildDir: '/tmp/gcr-builds'
    , npm: true
    , strictSSL: false
    , timeout: 5000
    , loglevel: 'silent'
    }, function(err) {
      if (err) return done(err)
      gcr.loaded.should.be.true
      done()
    })
  })

  it('should allow passing just a callback to load', function(done) {
    gcr.load(done)
  })

  it('gcr.config should exist after loading', function() {
    gcr.should.have.property('config')
  })

  describe('build', function() {
    var Build = require('../lib/build')
    var build

    it('should allow construction', function() {
      build = Build({
        commands: ['npm test']
      , timeout: 5000
      , project_id: 1
      , repo_url: 'git://github.com/evanlucas/gcr-test.git'
      , ref: 'origin/master'
      , allow_git_fetch: true
      , before_sha: 'blah'
      , ref_name: 'master'
      , id: 1
      })

      build.should.be.instanceOf(require('events').EventEmitter)
      build.should.have.property('git', gcr.config.get('git'))
      build.should.have.property('buildDir', gcr.config.get('buildDir'))
      build.should.have.property('opts')
      build.should.have.property('output')
      build.should.have.property('projectDir')
      build.projectDir.should.equal('/tmp/gcr-builds/project-1')
      build.should.have.property('state', 'waiting')
    })

    it('should run with clone', function(done) {
      this.timeout(10000)
      var sandbox = sinon.sandbox.create()
      sandbox.stub(build, 'update', function(cb) {
        cb && cb()
      })
      var count = 0
      function next() {
        count++
        if (count === 2) done()
      }
      build.on('done', function(success) {
        success.should.be.true
        sandbox.restore()
        done()
      })
      build.run()
      build.state.should.equal('running')
    })

    it('should run with fetch', function(done) {
      var build2 = Build({
        commands: ['npm test']
      , timeout: 5000
      , project_id: 2
      , repo_url: 'git://github.com/evanlucas/gcr-test.git'
      , ref: 'origin/master'
      , allow_git_fetch: false
      , before_sha: 'blah'
      , ref_name: 'master'
      , id: 2
      })
      this.timeout(10000)
      var sandbox = sinon.sandbox.create()
      sandbox.stub(gcr.client, 'updateBuild', function(id, s, o, cb) {
        cb && cb()
      })
      var count = 0
      function next() {
        count++
        if (count === 2) done()
      }
      build2.on('done', function(success) {
        success.should.be.true
        sandbox.restore()
        done()
      })
      build2.run()
      build2.state.should.equal('running')
    })
  })

  describe('client', function() {
    it('should be accessible via gcr.client', function() {
      should.exist(gcr.client)
    })

    it('apuUrl() should return gcr.config.get(\'url\')', function() {
      gcr.client.apiUrl().should.equal(gcr.config.get('url'))
    })

    describe('updateBuild', function() {
      it('should return null, true on success', function(done) {
        gcr.client.updateBuild(1, 'running', 'blah', function(err, out) {
          if (err) return done(err)
          out.should.be.true
          done()
        })
      })

      it('should return null, false on error', function(done) {
        gcr.client.updateBuild(1, 'running', 'blah2', function(err, out) {
          if (err) return done(err)
          out.should.be.false
          done()
        })
      })
    })

    describe('registerRunner', function() {
      it('should return null, token on success', function(done) {
        gcr.client.registerRunner(1, 'biscuits', function(err, out) {
          if (err) return done(err)
          should.exist(out)
          done()
        })
      })

      it('should return err on error', function(done) {
        gcr.client.registerRunner(1, 'blah', function(err, out) {
          should.exist(err)
          err.should.match(/Invalid response/)
          done()
        })
      })
    })

    describe('getBuild', function() {
      it('should return null, object on success', function(done) {
        gcr.config.set('token', 'biscuits')
        gcr.client.getBuild(done)
      })

      it('should return err on 403', function(done) {
        gcr.config.set('token', 'blah')
        gcr.client.getBuild(function(err, out) {
          should.exist(err)
          err.should.match(/Unable to get builds/)
          done()
        })
      })

      it('should return undefined on anything else', function(done) {
        gcr.config.set('token', 'baaaaa')
        gcr.client.getBuild(function(err, out) {
          if (err) return done(err)
          should.not.exist(out)
          done()
        })
      })
    })
  })

  describe('runner', function() {
    it('should have properties', function() {
      gcr.runner.should.have.property('builds')
      gcr.runner.should.have.property('queue')
      gcr.runner.should.have.property('interval')
    })

    describe('projectIsRunning', function() {
      it('should return true if a build exists', function() {
        gcr.runner.builds = { 1: 1 }
        gcr.runner.projectIsRunning(1).should.be.true
      })

      it('should return false if a build does not exist', function() {
        gcr.runner.builds = {}
        gcr.runner.projectIsRunning(1).should.be.false
      })
    })
  })

  describe('utils', function() {

  })
})
<|endoftext|>


<commit_before>

var cc =require('..')
var INI = require('ini')
var assert = require('assert')

function test(obj) {

  var _json, _ini
  var json = cc.parse (_json = JSON.stringify(obj))
  var ini = cc.parse (_ini = INI.stringify(obj))

  assert.deepEqual(json, ini)
}

test({hello: true})

<commit_msg>relax test<commit_after>

var cc =require('..')
var INI = require('ini')
var assert = require('assert')

function test(obj) {

  var _json, _ini
  var json = cc.parse (_json = JSON.stringify(obj))
  var ini = cc.parse (_ini = INI.stringify(obj))
console.log(_ini, _json)
  assert.deepEqual(json, ini)
}

test({hello: 'true'})

<|endoftext|>


<commit_before>var app, chai, expect, generate, request, rootUrl, request;

// Imports
// =============================================================================

chai = require( 'chai' );
request = require( 'supertest' );
expect = chai.expect;

generate = require( './generator' );

// Set up globals
// =============================================================================

rootUrl = 'http://localhost:8080/api';

// Before and After hooks
// =============================================================================

// PULL THE LEVER!
// =============================================================================

describe( 'Rat Endpoints', function () {
  describe( 'POST /api/rats', function () {
    var rat;

    // Create a rat object
    rat = generate.randomRat();

    it( 'should create a new rat', function ( done ) {

      request
      .post( rootUrl + '/rats' )
      .send( rat )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        // Make sure the POST succeeded
        expect( response.status ).to.equal( 201 );

        // Make sure there are no errors
        expect( response.body ).to.not.have.property( 'errors' );

        // Make sure our response is correctly constructed
        expect( response.body.data ).to.be.an( 'object' );

        // Check all of the properties on the returned object
        expect( response.body.data.CMDRname ).to.equal( rat.CMDRname );
        expect( response.body.data.gamertag ).to.equal( rat.gamertag );
        expect( response.body.data.drilled ).to.equal( rat.drilled );
        expect( response.body.data.nickname ).to.equal( rat.nickname );

        done();
      });
    });
  });

  describe( 'GET /api/rats', function () {

    it( 'should return a list of rats', function ( done ) {
      request
      .get( rootUrl + '/rats' )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        // Make sure the GET succeeded
        expect( response.status ).to.equal( 200 );

        // Make sure there are no errors
        expect( response.body ).to.not.have.property( 'errors' );

        // Make sure our response is correctly constructed
        expect( response.body.data ).to.be.an( 'array' );

        done( error );
      });
    });
  });

  describe( 'GET /api/rats/:id', function () {

    var rat;

    // Create a rat object
    rat = generate.randomRat();

    // Create a new rat to test against
    before( function ( done ) {
      request
      .post( rootUrl + '/rats' )
      .send( rat )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        rat.id = response.body.data.id;

        done();
      });
    });

    it( 'should return a rat', function ( done ) {
      request
      .get( rootUrl + '/rats/' + rat.id )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        // Make sure the request succeeded
        expect( response.status ).to.equal( 200 );

        // Make sure there are no errors
        expect( response.body ).to.not.have.property( 'errors' );

        // Make sure our response is correctly constructed
        expect( response.body.data ).to.be.an( 'object' );

        // Make sure our response has the right data
        expect( response.body.data.id ).to.equal( rat.id );

        done();
      });
    });
  });

  describe( 'PUT /api/rats/:id', function () {
    var rat;

    // Create a new rat to test against
    before( function ( done ) {
      request
      .post( rootUrl + '/rats' )
      .send( generate.randomRat() )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        rat = response.body.data;

        done();
      });
    });

    it( 'should update a rat', function ( done ) {
      request
      .put( rootUrl + '/rats/' + rat.id )
      .send({
        nickname: 'Edited Test Client ' + ( Date.now() - parseInt( ( Math.random() * Math.random() ) * 1000000 ) ).toString( 36 )
      })
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        // Make sure the POST succeeded
        expect( response.status ).to.equal( 200 );

        done();
      });
    });
  });
});
<commit_msg>Remove pointless /api/ suffix in urls<commit_after>var app, chai, expect, generate, request, rootUrl, request;

// Imports
// =============================================================================

chai = require( 'chai' );
request = require( 'supertest' );
expect = chai.expect;

generate = require( './generator' );

// Set up globals
// =============================================================================

rootUrl = 'http://localhost:8080';

// Before and After hooks
// =============================================================================

// PULL THE LEVER!
// =============================================================================

describe( 'Rat Endpoints', function () {
  describe( 'POST /api/rats', function () {
    var rat;

    // Create a rat object
    rat = generate.randomRat();

    it( 'should create a new rat', function ( done ) {

      request
      .post( rootUrl + '/rats' )
      .send( rat )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        // Make sure the POST succeeded
        expect( response.status ).to.equal( 201 );

        // Make sure there are no errors
        expect( response.body ).to.not.have.property( 'errors' );

        // Make sure our response is correctly constructed
        expect( response.body.data ).to.be.an( 'object' );

        // Check all of the properties on the returned object
        expect( response.body.data.CMDRname ).to.equal( rat.CMDRname );
        expect( response.body.data.gamertag ).to.equal( rat.gamertag );
        expect( response.body.data.drilled ).to.equal( rat.drilled );
        expect( response.body.data.nickname ).to.equal( rat.nickname );

        done();
      });
    });
  });

  describe( 'GET /api/rats', function () {

    it( 'should return a list of rats', function ( done ) {
      request
      .get( rootUrl + '/rats' )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        // Make sure the GET succeeded
        expect( response.status ).to.equal( 200 );

        // Make sure there are no errors
        expect( response.body ).to.not.have.property( 'errors' );

        // Make sure our response is correctly constructed
        expect( response.body.data ).to.be.an( 'array' );

        done( error );
      });
    });
  });

  describe( 'GET /api/rats/:id', function () {

    var rat;

    // Create a rat object
    rat = generate.randomRat();

    // Create a new rat to test against
    before( function ( done ) {
      request
      .post( rootUrl + '/rats' )
      .send( rat )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        rat.id = response.body.data.id;

        done();
      });
    });

    it( 'should return a rat', function ( done ) {
      request
      .get( rootUrl + '/rats/' + rat.id )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        // Make sure the request succeeded
        expect( response.status ).to.equal( 200 );

        // Make sure there are no errors
        expect( response.body ).to.not.have.property( 'errors' );

        // Make sure our response is correctly constructed
        expect( response.body.data ).to.be.an( 'object' );

        // Make sure our response has the right data
        expect( response.body.data.id ).to.equal( rat.id );

        done();
      });
    });
  });

  describe( 'PUT /api/rats/:id', function () {
    var rat;

    // Create a new rat to test against
    before( function ( done ) {
      request
      .post( rootUrl + '/rats' )
      .send( generate.randomRat() )
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        rat = response.body.data;

        done();
      });
    });

    it( 'should update a rat', function ( done ) {
      request
      .put( rootUrl + '/rats/' + rat.id )
      .send({
        nickname: 'Edited Test Client ' + ( Date.now() - parseInt( ( Math.random() * Math.random() ) * 1000000 ) ).toString( 36 )
      })
      .end( function ( error, response ) {
        if ( error ) {
          return done( error );
        }

        // Make sure the POST succeeded
        expect( response.status ).to.equal( 200 );

        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var ok = require("./lint").ok;

var files = new (require('node-static').Server)();

var server = require('http').createServer(function (req, res) {
  req.addListener('end', function () {
    files.serve(req, res, function (err/*, result */) {
      if (err) {
        console.error(err);
        process.exit(1);
      }
    });
  }).resume();
}).addListener('error', function (err) {
  throw err;
}).listen(3000,(async () => {
  const puppeteer = require('puppeteer');
  const browser = await puppeteer.launch({args: ["--no-sandbox", "--disable-setuid-sandbox"]})
  const page = await browser.newPage()
  page.on('console', msg => console.log("console:", msg.text()))
  page.on('dialog', async dialog => {
    console.log(dialog.message())
    await dialog.dismiss()
  })
  page.evaluateOnNewDocument(() => window.automatedTests = true)
  await page.goto('http://localhost:3000/test/index.html#' + (process.argv[2] || ""))
  while(1) {
    if (await page.evaluate(() => window.done)) break
    await sleep(200)
  }
  let [failed, errors] = await page.evaluate(() => [window.failed, window.errored])
  for (let error of errors) console.log(error)
  console.log(await page.evaluate(() => document.getElementById('output').innerText + "\n" +
                                          document.getElementById('status').innerText))
  process.exit(failed > 0 || errors.length ? 1 : 0)
  await browser.close()
})())

function sleep(n) { return new Promise(acc => setTimeout(acc, n)) }
<commit_msg>Fix failing the test when the linter finds an issue<commit_after>#!/usr/bin/env node

var lint = require("./lint");

var files = new (require('node-static').Server)();

var server = require('http').createServer(function (req, res) {
  req.addListener('end', function () {
    files.serve(req, res, function (err/*, result */) {
      if (err) {
        console.error(err);
        process.exit(1);
      }
    });
  }).resume();
}).addListener('error', function (err) {
  throw err;
}).listen(3000,(async () => {
  const puppeteer = require('puppeteer');
  const browser = await puppeteer.launch({args: ["--no-sandbox", "--disable-setuid-sandbox"]})
  const page = await browser.newPage()
  page.on('console', msg => console.log("console:", msg.text()))
  page.on('dialog', async dialog => {
    console.log(dialog.message())
    await dialog.dismiss()
  })
  page.evaluateOnNewDocument(() => window.automatedTests = true)
  await page.goto('http://localhost:3000/test/index.html#' + (process.argv[2] || ""))
  while(1) {
    if (await page.evaluate(() => window.done)) break
    await sleep(200)
  }
  let [failed, errors] = await page.evaluate(() => [window.failed, window.errored])
  for (let error of errors) console.log(error)
  console.log(await page.evaluate(() => document.getElementById('output').innerText + "\n" +
                                          document.getElementById('status').innerText))
  process.exit(failed > 0 || errors.length || !lint.ok ? 1 : 0)
  await browser.close()
})())

function sleep(n) { return new Promise(acc => setTimeout(acc, n)) }
<|endoftext|>