<commit_before>var mailgun = require('mailgun-js')
const _ = require('lodash')

class MailService {
  constructor (mailgunConfig, fromEmail, toEmail) {
    this.mailer = mailgun(mailgunConfig)
    this.fromEmail = fromEmail
    this.toEmail = toEmail
  }

  sendRsvpEmail(rsvp, callback) {
    callback = callback || function () {}

    let names = _.join(_.map(rsvp.guests, guest => guest.name), ', ')

    let body = ''
    rsvp.guests.forEach(guest => {
      body += `${guest.name}\n`
      body += `Coming: ${guest.coming ? 'yes' : 'no'}\n`
      body += `Using Shuttle: ${guest.shuttle ? 'yes' : 'no'}\n`
      body += `Dietary Restrictions: ${guest.diet}\n\n`
    })
    body += 'Songs:\n'
    rsvp.songs.forEach(song => {
      body += `- ${song}\n`
    })
    body += `\nComments:\n${rsvp.comments}`

    let mailOptions = {
      from: this.fromEmail,
      to: this.toEmail,
      subject: `RSVP: ${names}`,
      text: body
    }

    // this.mailer.messages().send(mailOptions, (err) => {
    //     if(err){
    //         console.log('Failed to send rsvp notification ' + err + ' ' + JSON.stringify(rsvp));
    //         return callback(err)
    //     }
    //     console.log('Rsvp notification sent for ' + names)
    //     callback()
    // })
  }
}

module.exports = MailService
<commit_msg>turn emails back on<commit_after>var mailgun = require('mailgun-js')
const _ = require('lodash')

class MailService {
  constructor (mailgunConfig, fromEmail, toEmail) {
    this.mailer = mailgun(mailgunConfig)
    this.fromEmail = fromEmail
    this.toEmail = toEmail
  }

  sendRsvpEmail(rsvp, callback) {
    callback = callback || function () {}

    let names = _.join(_.map(rsvp.guests, guest => guest.name), ', ')

    let body = ''
    rsvp.guests.forEach(guest => {
      body += `${guest.name}\n`
      body += `Coming: ${guest.coming ? 'yes' : 'no'}\n`
      body += `Using Shuttle: ${guest.shuttle ? 'yes' : 'no'}\n`
      body += `Dietary Restrictions: ${guest.diet}\n\n`
    })
    body += 'Songs:\n'
    rsvp.songs.forEach(song => {
      body += `- ${song}\n`
    })
    body += `\nComments:\n${rsvp.comments}`

    let mailOptions = {
      from: this.fromEmail,
      to: this.toEmail,
      subject: `RSVP: ${names}`,
      text: body
    }

    this.mailer.messages().send(mailOptions, (err) => {
        if(err){
            console.log('Failed to send rsvp notification ' + err + ' ' + JSON.stringify(rsvp));
            return callback(err)
        }
        console.log('Rsvp notification sent for ' + names)
        callback()
    })
  }
}

module.exports = MailService
<|endoftext|>


<commit_before>import should from 'should/as-function';
import Promise from 'bluebird';
import _ from 'lodash';
import Syncano from '../../src/syncano';
import {ValidationError} from '../../src/errors';
import {suffix, credentials, createCleaner, hex} from './utils';

describe('GCMDevice', function() {
  this.timeout(15000);

  const cleaner = createCleaner();
  let connection = null;
  let Model = null;
  let Instance = null;
  const instanceName = suffix.get('GCMDevice');
  const registrationId = hex.getRandom(64);
  const deviceLabel = suffix.get('gcm');
  const devId = '10000000001';
  const data = {
    instanceName,
    registration_id: registrationId,
    label: deviceLabel,
    device_id: devId
  }

  before(function() {
    connection = Syncano(credentials.getCredentials());
    Instance = connection.Instance;
    Model = connection.GCMDevice;

    return Instance.please().create({name: instanceName});
  });

  beforeEach(function() {
    data.registration_id = hex.getRandom(64);
  })

  after(function() {
    return Instance.please().delete({name: instanceName});
  });

  afterEach(function() {
    return cleaner.clean();
  });

  it('should be validated', function() {
    should(Model().save()).be.rejectedWith(ValidationError);
  });

  it('should require "instanceName"', function() {
    should(Model({registration_id: registrationId}).save()).be.rejectedWith(/instanceName/);
  });

  it('should require "registration_id"', function() {
    should(Model({instanceName}).save()).be.rejectedWith(/registration_id/);
  });

  it('should validate "registration_id"', function() {
    should(Model({label: deviceLabel, instanceName, user: data.user, registration_id: 1337}).save()).be.rejectedWith(/registration_id/);
  });

  it('should validate "device_id"', function() {
    should(Model({label: deviceLabel, instanceName, user: data.user, registration_id: registrationId, device_id: 1337}).save()).be.rejectedWith(/device_id/);
  });

  it('should validate "user"', function() {
    should(Model({label: deviceLabel, instanceName, user: 'user', registration_id: registrationId, device_id: devId}).save()).be.rejectedWith(/user/);
  });

  it('should validate "metadata"', function() {
    should(Model({label: deviceLabel, instanceName, user: data.user, registration_id: registrationId, device_id: devId, metadata: 'metadata'}).save()).be.rejectedWith(/metadata/);
  });

  it('should validate "is_active"', function() {
    should(Model({label: deviceLabel, instanceName, user: data.user, registration_id: registrationId, device_id: devId , is_active: 'no'}).save()).be.rejectedWith(/is_active/);
  });

  it('should be able to save via model instance', function() {
    return Model(data).save()
      .then(cleaner.mark)
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(object).have.property('links').which.is.Object();
        should(object).have.property('metadata').which.is.Object();
        should(object).have.property('created_at').which.is.Date();
        should(object).have.property('updated_at').which.is.Date();
      });
  });

  it('should be able to delete via model instance', function() {
    return Model(data).save()
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(object).have.property('links').which.is.Object();
        should(object).have.property('metadata').which.is.Object();
        should(object).have.property('created_at').which.is.Date();
        should(object).have.property('updated_at').which.is.Date();

        return object.delete();
      });
  });

  describe('#please()', function() {

    it('should be able to list Models', function() {
      return Model.please().list(data).then((objects) => {
        should(objects).be.an.Array();
      });
    });

    it('should be able to create a Model', function() {
      return Model.please().create(data)
      .then(cleaner.mark)
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(object).have.property('links').which.is.Object();
        should(object).have.property('metadata').which.is.Object();
        should(object).have.property('created_at').which.is.Date();
        should(object).have.property('updated_at').which.is.Date();
      });
    });

    it('should be able to bulk create an objects', function() {
      const objects = [
        Model(data),
        Model(_.assign({}, data, {registration_id: `${registrationId}1`}))
      ];

      return Model.please().bulkCreate(objects)
        .then(cleaner.mark)
        .then((result) => {
          should(result).be.an.Array().with.length(2);
        });
    });

    it('should be able to get a Model', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then((object) => {
          should(object).be.a.Object();
          should(object).have.property('label').which.is.String().equal(data.label);
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
          should(object).have.property('links').which.is.Object();
          should(object).have.property('metadata').which.is.Object();
          should(object).have.property('created_at').which.is.Date();
          should(object).have.property('updated_at').which.is.Date();

          return object;
        })
        .then(() => {
          return Model
            .please()
            .get(data)
            .request();
        })
        .then(([object, response]) => {
          should(response).be.an.Object();
          should(object).be.a.Object();
          should(object).have.property('label').which.is.String().equal(data.label);
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
          should(object).have.property('links').which.is.Object();
          should(object).have.property('metadata').which.is.Object();
          should(object).have.property('created_at').which.is.Date();
          should(object).have.property('updated_at').which.is.Date();
        });
    });

    it('should be able to get or create a Model (CREATE)', function() {
      return Model.please().getOrCreate(data, {label: 'test2'})
      .then(cleaner.mark)
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal('test2');
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(object).have.property('links').which.is.Object();
        should(object).have.property('metadata').which.is.Object();
        should(object).have.property('created_at').which.is.Date();
        should(object).have.property('updated_at').which.is.Date();
      });
    });

    it('should be able to get or create an object (GET)', function() {
      return Model.please().create(data)
      .then(cleaner.mark)
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);

        return Model.please().getOrCreate(data, {label: 'newTest'});
      })
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
      });
    });

    it('should be able to update a Model', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then((gcm) => {
          should(gcm).be.an.Object();
          should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
          should(gcm).have.property('label').which.is.String().equal(data.label);
          should(gcm).have.property('registration_id').which.is.String().equal(data.registration_id);

        return Model.please().update({registration_id: data.registration_id, instanceName}, {label: 'new label'});
      })
      .then((gcm) => {
        should(gcm).be.an.Object();
        should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
        should(gcm).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(gcm.label).which.is.String().equal('new label');
      });
    });

    it('should be able to update or create a Model (UPDATE)', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then((gcm) => {
          should(gcm).be.an.Object();
          should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
          should(gcm).have.property('label').which.is.String().equal(data.label);
          should(gcm).have.property('registration_id').which.is.String().equal(data.registration_id);

        return Model.please().updateOrCreate(data, {label: 'new label'});
      })
      .then((gcm) => {
        should(gcm).be.an.Object();
        should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
        should(gcm).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(gcm.label).which.is.String().equal('new label');
      });
    });

    it('should be able to update or create a Model (CREATE)', function() {
      let properties = {registration_id: registrationId, instanceName};
      let object = {label: 'new label'};
      let defaults = {
          label: 'label',
          registration_id: registrationId
      };

      return Model.please().updateOrCreate(properties, object, defaults)
        .then(cleaner.mark)
        .then((gcm) => {
          should(gcm).be.an.Object();
          should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
          should(gcm).have.property('registration_id').which.is.String().equal(defaults.registration_id);
          should(gcm.label).which.is.String().equal(defaults.label);
        });
      });

    it('should be able to get first Model (SUCCESS)', function() {
      const ids = [
        `${registrationId}1`,
        `${registrationId}2`
      ];

      return Promise
        .mapSeries(ids, (id) => Model.please().create(_.assign({}, data, {registration_id: id})))
        .then(cleaner.mark)
        .then(() => {
          return Model.please().first(data);
        })
        .then((object) => {
          should(object).be.an.Object();
        });
    });

    it('should be able to change page size', function() {
      const ids = [
        `${registrationId}1`,
        `${registrationId}2`
      ];

      return Promise
        .mapSeries(ids, (id) => Model.please().create(_.assign({}, data, {registration_id: id})))
        .then(cleaner.mark)
        .then((objects) => {
          should(objects).be.an.Array().with.length(2);
          return Model.please(data).pageSize(1);
        })
        .then((objects) => {
          should(objects).be.an.Array().with.length(1);
        });
    });

    it('should be able to change ordering', function() {
      const ids = [
        `${registrationId}1`,
        `${registrationId}2`
      ];
      let asc = null;

      return Promise
        .mapSeries(ids, (id) => Model.please().create(_.assign({}, data, {registration_id: id})))
        .then(cleaner.mark)
        .then((objects) => {
          should(objects).be.an.Array().with.length(2);
          return Model.please(data).ordering('asc');
        })
        .then((objects) => {
          should(objects).be.an.Array().with.length(2);
          asc = objects;
          return Model.please(data).ordering('desc');
        }).then((desc) => {
          const ascIds = _.map(asc, 'registration_id');
          const descIds = _.map(desc, 'registration_id');
          descIds.reverse();

          should(desc).be.an.Array().with.length(2);

          _.forEach(ascIds, (ascId, index) => {
            should(ascId).be.equal(descIds[index]);
          });
        });
    });

    it('should be able to get raw data', function() {
      return Model.please().list(data).raw().then((response) => {
        should(response).be.a.Object();
        should(response).have.property('objects').which.is.Array();
        should(response).have.property('next').which.is.null();
        should(response).have.property('prev').which.is.null();
      });
    });

    it('should be able to send message directly from device', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then(() => {
          return connection.GCMConfig.please().update({instanceName}, {
            development_api_key: suffix.get('key')
          })
        })
        .then(() => {
          return Model.please().sendMessage({registration_id: data.registration_id, instanceName}, {environment: 'development'});
        })
        .then((object) => {
          should(object).be.a.Object();
          should(object).have.property('id').which.is.Number();
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('status').which.is.String();
          should(object).have.property('created_at').which.is.Date();
          should(object).have.property('updated_at').which.is.Date();
          should(object).have.property('links').which.is.Object();
          should(object).have.property('result').which.is.Object();
          should(object).have.property('content').which.is.Object();
          should(object.content).have.property('environment').which.is.String();
          should(object.content).have.property('registration_ids').which.is.Array();
        });
    });

    it('should be able to send messages directly from device', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then(() => {
          return connection.GCMConfig.please().update({instanceName}, {
            development_api_key: suffix.get('key')
          })
        })
        .then(() => {
          return Model.please().sendMessages({instanceName}, {environment: 'development', registration_ids: [data.registration_id]});
        })
    });

  });

});
<commit_msg>[LIB-792] Return request from test case<commit_after>import should from 'should/as-function';
import Promise from 'bluebird';
import _ from 'lodash';
import Syncano from '../../src/syncano';
import {ValidationError} from '../../src/errors';
import {suffix, credentials, createCleaner, hex} from './utils';

describe('GCMDevice', function() {
  this.timeout(15000);

  const cleaner = createCleaner();
  let connection = null;
  let Model = null;
  let Instance = null;
  const instanceName = suffix.get('GCMDevice');
  const registrationId = hex.getRandom(64);
  const deviceLabel = suffix.get('gcm');
  const devId = '10000000001';
  const data = {
    instanceName,
    registration_id: registrationId,
    label: deviceLabel,
    device_id: devId
  }

  before(function() {
    connection = Syncano(credentials.getCredentials());
    Instance = connection.Instance;
    Model = connection.GCMDevice;

    return Instance.please().create({name: instanceName});
  });

  beforeEach(function() {
    data.registration_id = hex.getRandom(64);
  })

  after(function() {
    return Instance.please().delete({name: instanceName});
  });

  afterEach(function() {
    return cleaner.clean();
  });

  it('should be validated', function() {
    should(Model().save()).be.rejectedWith(ValidationError);
  });

  it('should require "instanceName"', function() {
    should(Model({registration_id: registrationId}).save()).be.rejectedWith(/instanceName/);
  });

  it('should require "registration_id"', function() {
    should(Model({instanceName}).save()).be.rejectedWith(/registration_id/);
  });

  it('should validate "registration_id"', function() {
    should(Model({label: deviceLabel, instanceName, user: data.user, registration_id: 1337}).save()).be.rejectedWith(/registration_id/);
  });

  it('should validate "device_id"', function() {
    should(Model({label: deviceLabel, instanceName, user: data.user, registration_id: registrationId, device_id: 1337}).save()).be.rejectedWith(/device_id/);
  });

  it('should validate "user"', function() {
    should(Model({label: deviceLabel, instanceName, user: 'user', registration_id: registrationId, device_id: devId}).save()).be.rejectedWith(/user/);
  });

  it('should validate "metadata"', function() {
    should(Model({label: deviceLabel, instanceName, user: data.user, registration_id: registrationId, device_id: devId, metadata: 'metadata'}).save()).be.rejectedWith(/metadata/);
  });

  it('should validate "is_active"', function() {
    should(Model({label: deviceLabel, instanceName, user: data.user, registration_id: registrationId, device_id: devId , is_active: 'no'}).save()).be.rejectedWith(/is_active/);
  });

  it('should be able to save via model instance', function() {
    return Model(data).save()
      .then(cleaner.mark)
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(object).have.property('links').which.is.Object();
        should(object).have.property('metadata').which.is.Object();
        should(object).have.property('created_at').which.is.Date();
        should(object).have.property('updated_at').which.is.Date();
      });
  });

  it('should be able to delete via model instance', function() {
    return Model(data).save()
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(object).have.property('links').which.is.Object();
        should(object).have.property('metadata').which.is.Object();
        should(object).have.property('created_at').which.is.Date();
        should(object).have.property('updated_at').which.is.Date();

        return object.delete();
      });
  });

  describe('#please()', function() {

    it('should be able to list Models', function() {
      return Model.please().list(data).then((objects) => {
        should(objects).be.an.Array();
      });
    });

    it('should be able to create a Model', function() {
      return Model.please().create(data)
      .then(cleaner.mark)
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(object).have.property('links').which.is.Object();
        should(object).have.property('metadata').which.is.Object();
        should(object).have.property('created_at').which.is.Date();
        should(object).have.property('updated_at').which.is.Date();
      });
    });

    it('should be able to bulk create an objects', function() {
      const objects = [
        Model(data),
        Model(_.assign({}, data, {registration_id: `${registrationId}1`}))
      ];

      return Model.please().bulkCreate(objects)
        .then(cleaner.mark)
        .then((result) => {
          should(result).be.an.Array().with.length(2);
        });
    });

    it('should be able to get a Model', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then((object) => {
          should(object).be.a.Object();
          should(object).have.property('label').which.is.String().equal(data.label);
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
          should(object).have.property('links').which.is.Object();
          should(object).have.property('metadata').which.is.Object();
          should(object).have.property('created_at').which.is.Date();
          should(object).have.property('updated_at').which.is.Date();

          return object;
        })
        .then(() => {
          return Model
            .please()
            .get(data)
            .request();
        })
        .then(([object, response]) => {
          should(response).be.an.Object();
          should(object).be.a.Object();
          should(object).have.property('label').which.is.String().equal(data.label);
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
          should(object).have.property('links').which.is.Object();
          should(object).have.property('metadata').which.is.Object();
          should(object).have.property('created_at').which.is.Date();
          should(object).have.property('updated_at').which.is.Date();
        });
    });

    it('should be able to get or create a Model (CREATE)', function() {
      return Model.please().getOrCreate(data, {label: 'test2'})
      .then(cleaner.mark)
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal('test2');
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(object).have.property('links').which.is.Object();
        should(object).have.property('metadata').which.is.Object();
        should(object).have.property('created_at').which.is.Date();
        should(object).have.property('updated_at').which.is.Date();
      });
    });

    it('should be able to get or create an object (GET)', function() {
      return Model.please().create(data)
      .then(cleaner.mark)
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);

        return Model.please().getOrCreate(data, {label: 'newTest'});
      })
      .then((object) => {
        should(object).be.a.Object();
        should(object).have.property('label').which.is.String().equal(data.label);
        should(object).have.property('instanceName').which.is.String().equal(instanceName);
        should(object).have.property('registration_id').which.is.String().equal(data.registration_id);
      });
    });

    it('should be able to update a Model', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then((gcm) => {
          should(gcm).be.an.Object();
          should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
          should(gcm).have.property('label').which.is.String().equal(data.label);
          should(gcm).have.property('registration_id').which.is.String().equal(data.registration_id);

        return Model.please().update({registration_id: data.registration_id, instanceName}, {label: 'new label'});
      })
      .then((gcm) => {
        should(gcm).be.an.Object();
        should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
        should(gcm).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(gcm.label).which.is.String().equal('new label');
      });
    });

    it('should be able to update or create a Model (UPDATE)', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then((gcm) => {
          should(gcm).be.an.Object();
          should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
          should(gcm).have.property('label').which.is.String().equal(data.label);
          should(gcm).have.property('registration_id').which.is.String().equal(data.registration_id);

        return Model.please().updateOrCreate(data, {label: 'new label'});
      })
      .then((gcm) => {
        should(gcm).be.an.Object();
        should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
        should(gcm).have.property('registration_id').which.is.String().equal(data.registration_id);
        should(gcm.label).which.is.String().equal('new label');
      });
    });

    it('should be able to update or create a Model (CREATE)', function() {
      let properties = {registration_id: registrationId, instanceName};
      let object = {label: 'new label'};
      let defaults = {
          label: 'label',
          registration_id: registrationId
      };

      return Model.please().updateOrCreate(properties, object, defaults)
        .then(cleaner.mark)
        .then((gcm) => {
          should(gcm).be.an.Object();
          should(gcm).have.property('instanceName').which.is.String().equal(instanceName);
          should(gcm).have.property('registration_id').which.is.String().equal(defaults.registration_id);
          should(gcm.label).which.is.String().equal(defaults.label);
        });
      });

    it('should be able to get first Model (SUCCESS)', function() {
      const ids = [
        `${registrationId}1`,
        `${registrationId}2`
      ];

      return Promise
        .mapSeries(ids, (id) => Model.please().create(_.assign({}, data, {registration_id: id})))
        .then(cleaner.mark)
        .then(() => {
          return Model.please().first(data);
        })
        .then((object) => {
          should(object).be.an.Object();
        });
    });

    it('should be able to change page size', function() {
      const ids = [
        `${registrationId}1`,
        `${registrationId}2`
      ];

      return Promise
        .mapSeries(ids, (id) => Model.please().create(_.assign({}, data, {registration_id: id})))
        .then(cleaner.mark)
        .then((objects) => {
          should(objects).be.an.Array().with.length(2);
          return Model.please(data).pageSize(1);
        })
        .then((objects) => {
          should(objects).be.an.Array().with.length(1);
        });
    });

    it('should be able to change ordering', function() {
      const ids = [
        `${registrationId}1`,
        `${registrationId}2`
      ];
      let asc = null;

      return Promise
        .mapSeries(ids, (id) => Model.please().create(_.assign({}, data, {registration_id: id})))
        .then(cleaner.mark)
        .then((objects) => {
          should(objects).be.an.Array().with.length(2);
          return Model.please(data).ordering('asc');
        })
        .then((objects) => {
          should(objects).be.an.Array().with.length(2);
          asc = objects;
          return Model.please(data).ordering('desc');
        }).then((desc) => {
          const ascIds = _.map(asc, 'registration_id');
          const descIds = _.map(desc, 'registration_id');
          descIds.reverse();

          should(desc).be.an.Array().with.length(2);

          _.forEach(ascIds, (ascId, index) => {
            should(ascId).be.equal(descIds[index]);
          });
        });
    });

    it('should be able to get raw data', function() {
      return Model.please().list(data).raw().then((response) => {
        should(response).be.a.Object();
        should(response).have.property('objects').which.is.Array();
        should(response).have.property('next').which.is.null();
        should(response).have.property('prev').which.is.null();
      });
    });

    it('should be able to send message directly from device', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then(() => {
          return connection.GCMConfig.please().update({instanceName}, {
            development_api_key: suffix.get('key')
          })
        })
        .then(() => {
          return Model.please().sendMessage({registration_id: data.registration_id, instanceName}, {environment: 'development'});
        })
        .then((object) => {
          should(object).be.a.Object();
          should(object).have.property('id').which.is.Number();
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('status').which.is.String();
          should(object).have.property('created_at').which.is.Date();
          should(object).have.property('updated_at').which.is.Date();
          should(object).have.property('links').which.is.Object();
          should(object).have.property('result').which.is.Object();
          should(object).have.property('content').which.is.Object();
          should(object.content).have.property('environment').which.is.String();
          should(object.content).have.property('registration_ids').which.is.Array();
        });
    });

    it('should be able to send messages directly from device', function() {
      return Model.please().create(data)
        .then(cleaner.mark)
        .then(() => {
          return connection.GCMConfig.please().update({instanceName}, {
            development_api_key: suffix.get('key')
          })
        })
        .then(() => {
          return Model.please().sendMessages({instanceName}, {environment: 'development', registration_ids: [data.registration_id]}).request();
        })
    });

  });

});
<|endoftext|>


<commit_before>/* Copyright (c) 2012 Top Hat Monocle, http://tophatmonocle.com/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/

(function($) {
    $.fn.barReporter = function(options) {
        options = $.extend({}, $.fn.barReporter.defaults, options);

        //add appropriate type css to barReport
        if( options["type"] == "multi" ) {
            $(this).removeClass("brStacked").addClass("brMulti");
        } else if( options["type"] == "stacked" ) {
            $(this).removeClass("brMulti").addClass("brStacked");
        }

        //determine graph scale
        var data_scale = $.fn.barReporter.calculate_scale(options);
        var pct_scale = $.fn.barReporter.calculate_pct_scale(options);
        var scale = options.scale || data_scale;

        //determine if non row-specfic values have been changed since last rendering
        //data must be removed, as modifying it is not indicative of change in other options
        var comp_options = $.extend({}, options, {"scale": scale, "data":false});
        var options_modified = $.fn.barReporter.is_modified( this, comp_options );

        //Remove any rows that no longer exist
        if( $(this).find(".brRow").length >= options.data.length ) {
            $(this).find(".brRow").each(function(index) {
                if( index > options.data.length - 1 ) {
                    $(this).remove();
                }
            });
        }

        //get or create the overall report container
        $.fn.barReporter.get_or_create_report_container( this );
        var report_el = $(this).children("#brReportContainer");

        //Get or add legend container if we are in a stacked bar
        if( options.legends.length && (options.type == "stacked") ) {
            var legend_container_el = $(this).children("#brLegendContainer");
        } else {
            $(this).children("#brLegendContainer").remove();
        }

        //loop through rows and render them
        for( var row_index in options.data ) {
            var row_data = options.data[row_index];

            //get or create row
            var row_el = $.fn.barReporter.get_or_create_row(report_el, row_index);

            //only redraw rows if data has been modified
            if( !options_modified && !$.fn.barReporter.is_modified( row_el, row_data ) ) {
                continue;
            }

            var data = $.isArray( row_data[0] ) ? row_data[0] : [ row_data[0] ];
            var label = row_data[1];

            //Remove any bars that no longer exist
            if( row_el.find(".brBar").length >= data.length ) {
                row_el.find(".brBar").each(function(row_index) {
                    if( row_index > data.length - 1 ) {
                        $(this).remove();
                    }
                });
            }

            //Update bar data
            for( var bar_index in data ) {
                var color = options.colors[bar_index] || options.colors[0];
                var el = $.fn.barReporter.get_or_create_bar( row_el, bar_index, color );

                var value = data[bar_index];
                var width = value / scale * 100;
                if( width > 100 ) { width = 100; }
                $(el).css("width", width + "%");
                $(el).text(value);

                //if value > 0, add a brNonZero class
                if( value > 0 ) {
                    $(el).addClass("brNonZero");
                } else {
                    $(el).removeClass("brNonZero");
                }

                //only show inline legends for multi bars
                if( options.legends.length ) {

                    //create a bar report in the legend container if it has been defined; otherwise,
                    //create in the row
                    var legend_parent_el = legend_container_el || row_el.find(".brLegends");
                    var legend_el = $.fn.barReporter.get_or_create_legend( legend_parent_el, bar_index, color );

                    //format legend text
                    legend = options.legends[bar_index].toString();
                    if( legend.length > 23 ) { legend = legend.substr(0, 20) + "..."; }
                    legend = legend.replace(/\s/g, " ");

                    //add legend
                    legend_el.find("em").html(legend);
                }
            }

            //Update label
            label = $.fn.barReporter.format_label( label, options.num_no_wrap_chars );
            $(row_el).find(".brLabel").html( label );

            //Render percent value for row
            if( options.show_percent ) {

                //calculate total pct for all row data based on data_scale
                var total_pct = 0;
                $(data).each( function(row_index, value) {
                    total_pct += value / pct_scale * 100;
                });
                total_pct = Math.round(total_pct);

                //render value
                $(row_el).find(".brPct").html( total_pct + "%" );
            } else {
                //render nothing
                $(row_el).find(".brPct").html( false );
            }

        }
    };
    //
    //determines if the row's data has changed, requiring a redraw
    $.fn.barReporter.is_modified = function( row_el, row_data ) {
        var old_data = $(row_el).data("rowData");
        var new_data = JSON.stringify(row_data);

        if( new_data == old_data ) {
            return false;
        } else {
            $(row_el).data("rowData", new_data);
            return true;
        }
    }

    $.fn.barReporter.format_label = function( str, num_no_wrap_chars ) {
        //use default num_no_wrap_chars if no value provided
        if( !num_no_wrap_chars ) {
            num_no_wrap_chars = $.fn.barReporter.defaults.num_no_wrap_chars;
        }

        return str.substr(0,num_no_wrap_chars).replace(/\s/g, " ") + str.substr( num_no_wrap_chars );
    }

    //find the bar element or initialize & add to container
    $.fn.barReporter.get_or_create_row = function(parent, id) {
        var el = $(parent).children("#brRow" + id);

        if( !el.length ) {
            el = $("
" +
                "

" +
                "

" +
                "

" +
                "

");
            $(parent).append( el );
        }
        return el;
    }

    //find or add a new bar
    $.fn.barReporter.get_or_create_bar = function(parent, index, color) {
        var el = $(parent).find(".brBars > #brBar" + index);

        if( !el.length ) {
            el = $("

");
            $(parent).find(".brBars").append( el );
        }
        return el;
    }

    //find or add a bar legend
    $.fn.barReporter.get_or_create_legend = function(parent, index, color) {
        var el = $(parent).find("#brLegend" + index);

        if( !el.length ) {
            el = $("

");
            $(parent).append( el );
        }
        return el;
    }

    //find or create the container that holds the report and legend
    $.fn.barReporter.get_or_create_report_container = function(parent) {
        var el = $(parent).children("#brReportContainer");

        if( !el.length ) {
            el = $("

");
            $(parent).append( el );
        }
        return el;
    }

    //calculates the scale to present items out of
    $.fn.barReporter.calculate_scale = function(options) {
        var scale = 0;

        for( var index in options.data ) {
            var data = options.data[index][0];
            var total = 0;

            //if row does not have array of data, row's total is simply the value
            if( !$.isArray(data) ) {
                total = data;

            //if row has array of data, row is either sum of values or highest value (depends on report type)
            } else {
                $(data).each(function(i,value) {
                    if( options.type == "stacked" ) {
                        total += value;
                    } else if( (options.type == "multi") && (value > total) ) {
                        total = value;
                    }
                });
            }

            if( total > scale ) {
                scale = total;
            }
        }

        return scale;
    }

    //calculate the value to scale percent with
    //this should be equal to the sum of all values
    $.fn.barReporter.calculate_pct_scale = function(options) {
        var total = 0;

        for( var index in options.data ) {
            var data = options.data[index][0];
            if( !$.isArray(data) ) { data = [data]; }
            $(data).each(function(i,value) { total += value; });
        }

        return total;
    }

    $.fn.barReporter.defaults = {
        "data": [],
        "type": "multi",
        "scale": undefined,
        "num_no_wrap_chars": 20,
        "show_percent": true,
        "colors": ["#6FBF4D", "#5b9e3e", "#356022", "#242424"],
        "legends": []
    }

})(jQuery);
<commit_msg>Fixed issue with undefined labels<commit_after>/* Copyright (c) 2012 Top Hat Monocle, http://tophatmonocle.com/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/

(function($) {
    $.fn.barReporter = function(options) {
        options = $.extend({}, $.fn.barReporter.defaults, options);

        //add appropriate type css to barReport
        if( options["type"] == "multi" ) {
            $(this).removeClass("brStacked").addClass("brMulti");
        } else if( options["type"] == "stacked" ) {
            $(this).removeClass("brMulti").addClass("brStacked");
        }

        //determine graph scale
        var data_scale = $.fn.barReporter.calculate_scale(options);
        var pct_scale = $.fn.barReporter.calculate_pct_scale(options);
        var scale = options.scale || data_scale;

        //determine if non row-specfic values have been changed since last rendering
        //data must be removed, as modifying it is not indicative of change in other options
        var comp_options = $.extend({}, options, {"scale": scale, "data":false});
        var options_modified = $.fn.barReporter.is_modified( this, comp_options );

        //Remove any rows that no longer exist
        if( $(this).find(".brRow").length >= options.data.length ) {
            $(this).find(".brRow").each(function(index) {
                if( index > options.data.length - 1 ) {
                    $(this).remove();
                }
            });
        }

        //get or create the overall report container
        $.fn.barReporter.get_or_create_report_container( this );
        var report_el = $(this).children("#brReportContainer");

        //Get or add legend container if we are in a stacked bar
        if( options.legends.length && (options.type == "stacked") ) {
            var legend_container_el = $(this).children("#brLegendContainer");
        } else {
            $(this).children("#brLegendContainer").remove();
        }

        //loop through rows and render them
        for( var row_index in options.data ) {
            var row_data = options.data[row_index];

            //get or create row
            var row_el = $.fn.barReporter.get_or_create_row(report_el, row_index);

            //only redraw rows if data has been modified
            if( !options_modified && !$.fn.barReporter.is_modified( row_el, row_data ) ) {
                continue;
            }

            var data = $.isArray( row_data[0] ) ? row_data[0] : [ row_data[0] ];
            var label = row_data[1];

            //Remove any bars that no longer exist
            if( row_el.find(".brBar").length >= data.length ) {
                row_el.find(".brBar").each(function(row_index) {
                    if( row_index > data.length - 1 ) {
                        $(this).remove();
                    }
                });
            }

            //Update bar data
            for( var bar_index in data ) {
                var color = options.colors[bar_index] || options.colors[0];
                var el = $.fn.barReporter.get_or_create_bar( row_el, bar_index, color );

                var value = data[bar_index];
                var width = value / scale * 100;
                if( width > 100 ) { width = 100; }
                $(el).css("width", width + "%");
                $(el).text(value);

                //if value > 0, add a brNonZero class
                if( value > 0 ) {
                    $(el).addClass("brNonZero");
                } else {
                    $(el).removeClass("brNonZero");
                }

                //only show inline legends for multi bars
                if( options.legends.length ) {

                    //create a bar report in the legend container if it has been defined; otherwise,
                    //create in the row
                    var legend_parent_el = legend_container_el || row_el.find(".brLegends");
                    var legend_el = $.fn.barReporter.get_or_create_legend( legend_parent_el, bar_index, color );

                    //format legend text
                    legend = options.legends[bar_index] || "";
                    legend = legend.toString();
                    if( legend.length > 23 ) { legend = legend.substr(0, 20) + "..."; }
                    legend = legend.replace(/\s/g, " ");

                    //add legend
                    legend_el.find("em").html(legend);
                }
            }

            //Update label
            label = $.fn.barReporter.format_label( label, options.num_no_wrap_chars );
            $(row_el).find(".brLabel").html( label );

            //Render percent value for row
            if( options.show_percent ) {

                //calculate total pct for all row data based on data_scale
                var total_pct = 0;
                $(data).each( function(row_index, value) {
                    total_pct += value / pct_scale * 100;
                });
                total_pct = Math.round(total_pct);

                //render value
                $(row_el).find(".brPct").html( total_pct + "%" );
            } else {
                //render nothing
                $(row_el).find(".brPct").html( false );
            }

        }
    };
    //
    //determines if the row's data has changed, requiring a redraw
    $.fn.barReporter.is_modified = function( row_el, row_data ) {
        var old_data = $(row_el).data("rowData");
        var new_data = JSON.stringify(row_data);

        if( new_data == old_data ) {
            return false;
        } else {
            $(row_el).data("rowData", new_data);
            return true;
        }
    }

    $.fn.barReporter.format_label = function( str, num_no_wrap_chars ) {
        //use default num_no_wrap_chars if no value provided
        if( !num_no_wrap_chars ) {
            num_no_wrap_chars = $.fn.barReporter.defaults.num_no_wrap_chars;
        }

        return str.substr(0,num_no_wrap_chars).replace(/\s/g, " ") + str.substr( num_no_wrap_chars );
    }

    //find the bar element or initialize & add to container
    $.fn.barReporter.get_or_create_row = function(parent, id) {
        var el = $(parent).children("#brRow" + id);

        if( !el.length ) {
            el = $("
" +
                "

" +
                "

" +
                "

" +
                "

");
            $(parent).append( el );
        }
        return el;
    }

    //find or add a new bar
    $.fn.barReporter.get_or_create_bar = function(parent, index, color) {
        var el = $(parent).find(".brBars > #brBar" + index);

        if( !el.length ) {
            el = $("

");
            $(parent).find(".brBars").append( el );
        }
        return el;
    }

    //find or add a bar legend
    $.fn.barReporter.get_or_create_legend = function(parent, index, color) {
        var el = $(parent).find("#brLegend" + index);

        if( !el.length ) {
            el = $("

");
            $(parent).append( el );
        }
        return el;
    }

    //find or create the container that holds the report and legend
    $.fn.barReporter.get_or_create_report_container = function(parent) {
        var el = $(parent).children("#brReportContainer");

        if( !el.length ) {
            el = $("

");
            $(parent).append( el );
        }
        return el;
    }

    //calculates the scale to present items out of
    $.fn.barReporter.calculate_scale = function(options) {
        var scale = 0;

        for( var index in options.data ) {
            var data = options.data[index][0];
            var total = 0;

            //if row does not have array of data, row's total is simply the value
            if( !$.isArray(data) ) {
                total = data;

            //if row has array of data, row is either sum of values or highest value (depends on report type)
            } else {
                $(data).each(function(i,value) {
                    if( options.type == "stacked" ) {
                        total += value;
                    } else if( (options.type == "multi") && (value > total) ) {
                        total = value;
                    }
                });
            }

            if( total > scale ) {
                scale = total;
            }
        }

        return scale;
    }

    //calculate the value to scale percent with
    //this should be equal to the sum of all values
    $.fn.barReporter.calculate_pct_scale = function(options) {
        var total = 0;

        for( var index in options.data ) {
            var data = options.data[index][0];
            if( !$.isArray(data) ) { data = [data]; }
            $(data).each(function(i,value) { total += value; });
        }

        return total;
    }

    $.fn.barReporter.defaults = {
        "data": [],
        "type": "multi",
        "scale": undefined,
        "num_no_wrap_chars": 20,
        "show_percent": true,
        "colors": ["#6FBF4D", "#5b9e3e", "#356022", "#242424"],
        "legends": []
    }

})(jQuery);
<|endoftext|>


<commit_before>/*
===============================================================================

    Multiple caches, based on Cache.

===============================================================================
*/

function Texture( url ) {
    if ( !(this instanceof Texture) ) return new Texture();

    this.url = url;
    this._texture = null;
}

Texture.prototype.load = function () {
    if ( this._texture === null ) {
        this._texture = THREE.ImageUtils.loadTexture( this.url );
    }
    return this._texture ;
}

Texture.prototype.unload = function () {
    if ( this._texture !== null ) {
        delete this._texture;
    }
    this._texture = null;
}

/*
---------------------------------------------------------------------------
DOA
---------------------------------------------------------------------------
*/
DOA.Textures = new Cache();  // Texture files, loaded into RAM
DOA.Materials = new Cache(); // Materials, based on texture and loaded into GPU memory
DOA.Models = new Cache();    // Models, imported from Blender
DOA.Sounds = new Cache();    // Game sounds

/*
---------------------------------------------------------------------------
Textures
    There are 3 different kinds of texture:
    1. GLobal textures, that is used constantly, like users HUD.
    2. Level textures, that will be used on the game level.
    3. Other textures, that may be loaded in the future.
    And 2 types of material:
    1. Already loaded into GPU memory and used ( based on 1 and 2 textures );
    2. Other materials, that may be loaded in the future.
    Textures are loaded into RAM, Materials are loaded into GPU memory.
---------------------------------------------------------------------------
*/

// PRELOADED

DOA.Textures.add( 'default',      new Texture( 'base/data/textures/default.png' ) ).load();

DOA.Textures.add( 'hud_crossdot', new Texture( 'base/data/textures/crosshairs/crossdot.png' ) ).load();

// REGISTERED
DOA.Textures.add( 'hud_dot',      new Texture( 'base/data/textures/crosshairs/dot.png' ) );
DOA.Textures.add( 'hud_circle',   new Texture( 'base/data/textures/crosshairs/circle.png' ) );
DOA.Textures.add( 'hud_cross',    new Texture( 'base/data/textures/crosshairs/cross.png' ) );
DOA.Textures.add( 'hud_bigcross', new Texture( 'base/data/textures/crosshairs/bigcross.png' ) );
<commit_msg>Update Textures cache preload<commit_after>/*
===============================================================================

    Multiple caches, based on Cache.

===============================================================================
*/

function Texture( url ) {
    if ( !(this instanceof Texture) ) return new Texture();

    this.url = url;
    this._texture = null;
}

Texture.prototype.load = function () {
    if ( this._texture === null ) {
        this._texture = THREE.ImageUtils.loadTexture( this.url );
    }
    return this._texture ;
}

Texture.prototype.unload = function () {
    if ( this._texture !== null ) {
        delete this._texture;
    }
    this._texture = null;
}

/*
---------------------------------------------------------------------------
DOA
---------------------------------------------------------------------------
*/
DOA.Textures  = new Cache(); // Texture files, loaded into RAM
DOA.Materials = new Cache(); // Materials, based on texture and loaded into GPU memory
DOA.Models    = new Cache(); // Models, imported from Blender
DOA.Sounds    = new Cache(); // Game sounds

/*
---------------------------------------------------------------------------
Textures
    There are 3 different kinds of texture:
    1. GLobal textures, that is used constantly, like users HUD.
    2. Level textures, that will be used on the game level.
    3. Other textures, that may be loaded in the future.
    And 2 types of material:
    1. Already loaded into GPU memory and used ( based on 1 and 2 textures );
    2. Other materials, that may be loaded in the future.
    Textures are loaded into RAM, Materials are loaded into GPU memory.
---------------------------------------------------------------------------
*/

// PRELOADED
DOA.Textures.add( 'default',      new Texture( 'base/data/textures/default.png' ) ).load();

// Crosshairs
DOA.Textures.add( 'hud_crossdot', new Texture( 'base/data/textures/crosshairs/crossdot.png' ), 'crosshair' ).load();
DOA.Textures.add( 'hud_dot',      new Texture( 'base/data/textures/crosshairs/dot.png' ),      'crosshair' );
DOA.Textures.add( 'hud_circle',   new Texture( 'base/data/textures/crosshairs/circle.png' ),   'crosshair' );
DOA.Textures.add( 'hud_cross',    new Texture( 'base/data/textures/crosshairs/cross.png' ),    'crosshair' );
DOA.Textures.add( 'hud_bigcross', new Texture( 'base/data/textures/crosshairs/bigcross.png' ), 'crosshair' );

// HUD
DOA.Textures.add( 'hud_health',   new Texture( 'base/data/textures/interface/health.png' ), 'hud' ).load();
DOA.Textures.add( 'hud_armor',    new Texture( 'base/data/textures/interface/armor.png' ),  'hud' ).load();
<|endoftext|>


<commit_before>define(['$',
        'atum/interpret'],
function($,
        interpret){

    var a = $.Id('a');
    var b = $.Id('b');
    var c = $.Id('c');

    return {
        'module': "Try",
        'tests': [
            ["No throw",
            function(){
                var root = $.Program(
                    $.Try(
                        $.Block(
                            $.Expression($.Number(10))),
                        null,
                        $.Block()));

                var result = interpret.interpret(root);
                assert.equal(result.type, 'number');
                assert.equal(result.value, 10);
            }],
            ["Simple Throw",
            function(){
                var root = $.Program(
                    $.Assign(b, $.Number(0)),
                    $.Try(
                        $.Block(
                            $.Expression($.PostIncrement(b)),
                            $.Throw($.Number(10))),
                    $.Catch(a,
                        $.Block(
                            $.Expression($.Add(a, b))))));

                var result = interpret.interpret(root);
                assert.equal(result.type, 'number');
                assert.equal(result.value, 11);
            }],

        ]
    };
});
<commit_msg>Added basic tests for finally only try<commit_after>define(['$',
        'atum/interpret'],
function($,
        interpret){

    var a = $.Id('a');
    var b = $.Id('b');
    var c = $.Id('c');

    return {
        'module': "Try",
        'tests': [
            ["No throw",
            function(){
                var root = $.Program(
                    $.Try(
                        $.Block(
                            $.Expression($.Number(10))),
                        null,
                        $.Block()));

                var result = interpret.interpret(root);
                assert.equal(result.type, 'number');
                assert.equal(result.value, 10);
            }],
            ["Simple Throw",
            function(){
                var root = $.Program(
                    $.Assign(b, $.Number(0)),
                    $.Try(
                        $.Block(
                            $.Expression($.PostIncrement(b)),
                            $.Throw($.Number(10))),
                        $.Catch(a,
                            $.Block(
                                $.Expression($.Add(a, b))))));

                var result = interpret.interpret(root);
                assert.equal(result.type, 'number');
                assert.equal(result.value, 11);
            }],
            ["Throw finally no catch",
            function(){
                var root = $.Program(
                    $.Assign(b, $.Number(1)),
                    $.Try(
                        $.Block(
                            $.Try(
                                $.Block(
                                    $.Expression($.PostIncrement(b)),
                                    $.Throw($.Number(10)),
                                    $.Expression($.PostIncrement(b))),
                                null,
                                $.Block(
                                    $.Expression($.Assign(b, $.Mul(b, b)))))),
                        $.Catch(a, $.Block())),
                    $.Expression(b));

                var result = interpret.interpret(root);
                assert.equal(result.type, 'number');
                assert.equal(result.value, 4);
            }],
            ["No throw finally no catch",
            function(){
                var root = $.Program(
                    $.Assign(b, $.Number(1)),
                    $.Try(
                        $.Block(
                            $.Try(
                                $.Block(
                                    $.Expression($.PostIncrement(b))),
                                null,
                                $.Block(
                                    $.Expression($.Assign(b, $.Mul(b, b)))))),
                        $.Catch(a, $.Block())),
                    $.Expression(b));

                var result = interpret.interpret(root);
                assert.equal(result.type, 'number');
                assert.equal(result.value, 2);
            }],

        ]
    };
});
<|endoftext|>


<commit_before>'use strict';

module.exports = {

  types: [
    {value: 'feat',     name: 'feat:     A new feature'},
    {value: 'fix',      name: 'fix:      A bug fix'},
    {value: 'docs',     name: 'docs:     Documentation only changes'},
    {value: 'style',    name: 'style:    Changes that do not affect the meaning of the code\n            (white-space, formatting, missing semi-colons, etc)'},
    {value: 'refactor', name: 'refactor: A code change that neither fixes a bug nor adds a feature'},
    {value: 'perf',     name: 'perf:     A code change that improves performance'},
    {value: 'test',     name: 'test:     Adding missing tests'},
    {value: 'chore',    name: 'chore:    Changes to the build process or auxiliary tools\n            and libraries such as documentation generation'},
    {value: 'revert',   name: 'revert:   Revert to a commit'},
    {value: 'WIP',      name: 'WIP:      Work in progress'}
  ],

  scopes: [
    {name: 'Button'},
    {name: 'Card'},
    {name: 'Checkbox'},
    {name: 'Copy'},
    {name: 'Datepicker'},
    {name: 'DateRange'},
    {name: 'Input'},
    {name: 'Link'},
    {name: 'LoadingOverlay'},
    {name: 'LoginForm'},
    {name: 'Menu'},
    {name: 'Navigation'},
    {name: 'Paginator'},
    {name: 'RadioGroup'},
    {name: 'Search'},
    {name: 'Select'},
    {name: 'Services'},
    {name: 'SCSS'},
    {name: 'Spacing'},
    {name: 'Table'},
    {name: 'Toggle'},
    {name: 'Tooltip'},
    {name: 'Utilities'},
    {name: 'ValidationMessages'},
    // INJECT: Add commitizen scope
    // NB! The above line is required for our yeoman generator and should not be changed.

    {name: 'Demo'},
    {name: 'Packages'},
    {name: 'CI'},
  ],

  // it needs to match the value for field type. Eg.: 'fix'
  /*
  scopeOverrides: {
    fix: [
      {name: 'merge'},
      {name: 'style'},
      {name: 'e2eTest'},
      {name: 'unitTest'}
    ]
  },
  */

  allowCustomScopes: true,
  allowBreakingChanges: ['feat', 'fix']

};
<commit_msg>chore(CI): Allow refactor to be breaking change<commit_after>'use strict';

module.exports = {

  types: [
    {value: 'feat',     name: 'feat:     A new feature'},
    {value: 'fix',      name: 'fix:      A bug fix'},
    {value: 'docs',     name: 'docs:     Documentation only changes'},
    {value: 'style',    name: 'style:    Changes that do not affect the meaning of the code\n            (white-space, formatting, missing semi-colons, etc)'},
    {value: 'refactor', name: 'refactor: A code change that neither fixes a bug nor adds a feature'},
    {value: 'perf',     name: 'perf:     A code change that improves performance'},
    {value: 'test',     name: 'test:     Adding missing tests'},
    {value: 'chore',    name: 'chore:    Changes to the build process or auxiliary tools\n            and libraries such as documentation generation'},
    {value: 'revert',   name: 'revert:   Revert to a commit'},
    {value: 'WIP',      name: 'WIP:      Work in progress'}
  ],

  scopes: [
    {name: 'Button'},
    {name: 'Card'},
    {name: 'Checkbox'},
    {name: 'Copy'},
    {name: 'Datepicker'},
    {name: 'DateRange'},
    {name: 'Input'},
    {name: 'Link'},
    {name: 'LoadingOverlay'},
    {name: 'LoginForm'},
    {name: 'Menu'},
    {name: 'Navigation'},
    {name: 'Paginator'},
    {name: 'RadioGroup'},
    {name: 'Search'},
    {name: 'Select'},
    {name: 'Services'},
    {name: 'SCSS'},
    {name: 'Spacing'},
    {name: 'Table'},
    {name: 'Toggle'},
    {name: 'Tooltip'},
    {name: 'Utilities'},
    {name: 'ValidationMessages'},
    // INJECT: Add commitizen scope
    // NB! The above line is required for our yeoman generator and should not be changed.

    {name: 'Demo'},
    {name: 'Packages'},
    {name: 'CI'},
  ],

  // it needs to match the value for field type. Eg.: 'fix'
  /*
  scopeOverrides: {
    fix: [
      {name: 'merge'},
      {name: 'style'},
      {name: 'e2eTest'},
      {name: 'unitTest'}
    ]
  },
  */

  allowCustomScopes: true,
  allowBreakingChanges: ['feat', 'fix', 'refactor']

};
<|endoftext|>


<commit_before>var test = require('tap').test;
var torrents = require('../');
var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var parseTorrent = require('parse-torrent');
var tracker = require('bittorrent-tracker');
var server = new tracker.Server();

var torrent = parseTorrent(fs.readFileSync(path.join(__dirname, 'data', 'test.torrent')));
var tmpPath = path.join(__dirname, '..', 'torrents');
rimraf.sync(tmpPath);

var fixture = torrents(torrent, {
	dht: false,
	path: path.join(__dirname, 'data')
});
fixture.listen(6882);

server.on('error', function () {
});

test('seed should connect to the tracker', function (t) {
	t.plan(3);

	server.on('listening', t.ok.bind(t, true, 'tracker should be listening'));
	server.once('start', function (addr) {
		t.equal(addr, '127.0.0.1:6882');
	});
	server.listen(12345);

	fixture.on('ready', t.ok.bind(t, true, 'should be ready'));
});

test('peer should connect to the swarm using .torrent file', function (t) {
	t.plan(4);
	var engine = torrents(torrent, { dht: false, tmp: tmpPath });
	engine.on('ready', function () {
		t.ok(true, 'should be ready');
		engine.destroy(function() {
			engine.remove(t.ok.bind(t, true, 'should be destroyed'));
		});
	});
	server.once('start', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
	});
	server.once('stop', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
	});
});

test('peer should connect to the swarm using magnet link', function (t) {
	t.plan(4);
	var engine = torrents('magnet:?xt=urn:btih:1cb9681dccbe6ef86ac797ab93840a4f0c4ccae8' +
		'&tr=http%3A%2F%2F127.0.0.1%3A12345%2Fannounce', { dht: false, tmp: tmpPath });
	engine.on('ready', function () {
		t.ok(true, 'should be ready');
		engine.destroy(function() {
			engine.remove(t.ok.bind(t, true, 'should be destroyed'));
		});
	});
	server.once('start', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
		engine.connect('127.0.0.1:6882'); // TODO: it's a workaround
	});
	server.once('stop', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
	});
});

test('peer should connect to the swarm using magnet link and trackers', function (t) {
	t.plan(4);
	var engine = torrents('magnet:?xt=urn:btih:1cb9681dccbe6ef86ac797ab93840a4f0c4ccae8',
		{ dht: false, tmp: tmpPath, trackers: ['http://127.0.0.1:12345/announce'] });
	engine.on('ready', function () {
		t.ok(true, 'should be ready');
		engine.destroy(function() {
			engine.remove(t.ok.bind(t, true, 'should be destroyed'));
		});
	});
	server.once('start', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
		engine.connect('127.0.0.1:6882'); // TODO: it's a workaround
	});
	server.once('stop', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
	});
});

test('cleanup', function (t) {
	t.plan(2);
	fixture.destroy(t.ok.bind(t, true, 'should be destroyed'));
	server.close(t.ok.bind(t, true, 'tracker should be closed'));
});<commit_msg>added tests for alternate trackers<commit_after>var test = require('tap').test;
var torrents = require('../');
var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var parseTorrent = require('parse-torrent');
var tracker = require('bittorrent-tracker');
var server = new tracker.Server();

var torrent = parseTorrent(fs.readFileSync(path.join(__dirname, 'data', 'test.torrent')));
var tmpPath = path.join(__dirname, '..', 'torrents', 'test');
rimraf.sync(tmpPath);

var fixture = torrents(torrent, {
	dht: false,
	path: path.join(__dirname, 'data')
});
fixture.listen(6882);

server.on('error', function () {
});

test('seed should connect to the tracker', function (t) {
	t.plan(3);

	server.once('listening', t.ok.bind(t, true, 'tracker should be listening'));
	server.once('start', function (addr) {
		t.equal(addr, '127.0.0.1:6882');
	});
	server.listen(12345);

	fixture.once('ready', t.ok.bind(t, true, 'should be ready'));
});

test('peer should connect to the swarm using .torrent file', function (t) {
	t.plan(4);
	var engine = torrents(torrent, { dht: false });
	engine.once('ready', function () {
		t.ok(true, 'should be ready');
		engine.destroy(function() {
			engine.remove(t.ok.bind(t, true, 'should be destroyed'));
		});
	});
	server.once('start', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
	});
	server.once('stop', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
	});
});

test('peer should connect to the swarm using magnet link', function (t) {
	t.plan(4);
	var engine = torrents('magnet:?xt=urn:btih:1cb9681dccbe6ef86ac797ab93840a4f0c4ccae8' +
		'&tr=http%3A%2F%2F127.0.0.1%3A12345%2Fannounce', { dht: false, tmp: tmpPath });
	engine.once('ready', function () {
		t.ok(true, 'should be ready');
		engine.destroy(function() {
			engine.remove(t.ok.bind(t, true, 'should be destroyed'));
		});
	});
	server.once('start', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
		engine.connect('127.0.0.1:6882'); // TODO: it's a workaround
	});
	server.once('stop', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
	});
});

test('peer should connect to the swarm using magnet link and trackers', function (t) {
	t.plan(4);
	var engine = torrents('magnet:?xt=urn:btih:1cb9681dccbe6ef86ac797ab93840a4f0c4ccae8',
		{ dht: false, tmp: tmpPath, trackers: ['http://127.0.0.1:12345/announce'] });
	engine.once('ready', function () {
		t.ok(true, 'should be ready');
		engine.destroy(function() {
			engine.remove(t.ok.bind(t, true, 'should be destroyed'));
		});
	});
	server.once('start', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
		engine.connect('127.0.0.1:6882'); // TODO: it's a workaround
	});
	server.once('stop', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
	});
});

test('peer should connect to an alternate tracker', function (t) {
	t.plan(5);
	var server = new tracker.Server();
	server.once('listening', t.ok.bind(t, true, 'tracker should be listening'));
	server.once('start', function (addr) {
		t.equal(addr, '127.0.0.1:6881');
	});
	server.listen(54321);

	var engine = torrents(torrent, { dht: false, trackers: ['http://127.0.0.1:54321/announce'] });
	engine.once('ready', function () {
		t.ok(true, 'should be ready');
		engine.destroy(t.ok.bind(t, true, 'should be destroyed'));
		server.close(t.ok.bind(t, true, 'tracker should be closed'));
	});
});

test('cleanup', function (t) {
	t.plan(2);
	fixture.destroy(t.ok.bind(t, true, 'should be destroyed'));
	server.close(t.ok.bind(t, true, 'tracker should be closed'));
});<|endoftext|>


<commit_before>"use strict";

const helpers = require("../helpers.js");
const path = require("path");

describe("tray", function() {
  var workingDir;
  let app;

  helpers.setupTest(this);

  beforeEach(function() {
    workingDir = helpers.getTempDir();
    let saversDir = path.join(workingDir, "savers");
    let saverJSONFile = helpers.addSaver(saversDir, "saver");

    helpers.specifyConfig(workingDir, "config");
    helpers.setConfigValue(workingDir, "sourceRepo", "foo/bar");
    helpers.setConfigValue(workingDir, "sourceUpdatedAt", new Date(0));
    helpers.setConfigValue(workingDir, "saver", saverJSONFile);

    app = helpers.application(workingDir);
    return app.start().
      then(() => helpers.waitUntilBooted(app, true));
  });

  afterEach(function() {
    return helpers.stopApp(app);
  });

  describe("run now", function() {
    before(function() {
      if ( process.platform === "win32" ) {
        console.log("skipping on win32")
        this.skip();
      }
    });

    it("opens screensaver", function() {
      return helpers.waitForWindow(app, "test shim").
        then(() => app.client.click("button.RunNow")).
        then(() => helpers.waitForWindow(app, "screensaver"));
    });
  });

  describe("preferences", function() {
    it("opens prefs window", function() {
      return helpers.waitForWindow(app, "test shim").
        then(() => app.client.click("button.Preferences")).
        then(() => helpers.waitForWindow(app, "Before Dawn: Preferences") );
    });
  });

  describe("about", function() {
    it("opens about window", function() {
      return helpers.waitForWindow(app, "test shim").
        then(() => app.client.click("button.AboutBeforeDawn")).
        then(() => helpers.waitForWindow(app, "Before Dawn: About!") );
    });
  });

  describe("enable/disable", function() {
    it("toggles app status", function() {
      return helpers.waitForWindow(app, "test shim").
        then(() => app.client.waitUntilTextExists("body", "idle")).
        then(() => app.client.click("button.Disable")).
        then(() => {
          helpers.sleep(1000);
        }).
        then(() => app.client.waitUntilTextExists("body", "paused")).
        then(() => app.client.click("button.Enable")).
        then(() => {
          helpers.sleep(1000);
        }).
        then(() => app.client.waitUntilTextExists("body", "idle"));
    });
  });
});
<commit_msg>Skip test on windows<commit_after>"use strict";

const helpers = require("../helpers.js");
const path = require("path");

describe("tray", function() {
  var workingDir;
  let app;

  helpers.setupTest(this);

  beforeEach(function() {
    workingDir = helpers.getTempDir();
    let saversDir = path.join(workingDir, "savers");
    let saverJSONFile = helpers.addSaver(saversDir, "saver");

    helpers.specifyConfig(workingDir, "config");
    helpers.setConfigValue(workingDir, "sourceRepo", "foo/bar");
    helpers.setConfigValue(workingDir, "sourceUpdatedAt", new Date(0));
    helpers.setConfigValue(workingDir, "saver", saverJSONFile);

    app = helpers.application(workingDir);
    return app.start().
      then(() => helpers.waitUntilBooted(app, true));
  });

  afterEach(function() {
    return helpers.stopApp(app);
  });

  describe("run now", function() {
    before(function() {
      if ( process.platform === "win32" ) {
        // eslint-disable-next-line no-console
        console.log("skipping on win32");
        this.skip();
      }
    });

    it("opens screensaver", function() {
      return helpers.waitForWindow(app, "test shim").
        then(() => app.client.click("button.RunNow")).
        then(() => helpers.waitForWindow(app, "screensaver"));
    });
  });

  describe("preferences", function() {
    it("opens prefs window", function() {
      return helpers.waitForWindow(app, "test shim").
        then(() => app.client.click("button.Preferences")).
        then(() => helpers.waitForWindow(app, "Before Dawn: Preferences") );
    });
  });

  describe("about", function() {
    it("opens about window", function() {
      return helpers.waitForWindow(app, "test shim").
        then(() => app.client.click("button.AboutBeforeDawn")).
        then(() => helpers.waitForWindow(app, "Before Dawn: About!") );
    });
  });

  describe("enable/disable", function() {
    before(function() {
      if ( process.platform === "win32" ) {
        // eslint-disable-next-line no-console
        console.log("skipping on win32");
        this.skip();
      }
    });

    it("toggles app status", function() {
      return helpers.waitForWindow(app, "test shim").
        then(() => app.client.waitUntilTextExists("body", "idle")).
        then(() => app.client.click("button.Disable")).
        then(() => {
          helpers.sleep(1000);
        }).
        then(() => app.client.waitUntilTextExists("body", "paused")).
        then(() => app.client.click("button.Enable")).
        then(() => {
          helpers.sleep(1000);
        }).
        then(() => app.client.waitUntilTextExists("body", "idle"));
    });
  });
});
<|endoftext|>


<commit_before>$(document).ready(function() {

  module("Utility functions (uniqueId, template)");

  test("utility: noConflict", function() {
    var underscore = _.noConflict();
    ok(underscore.isUndefined(_), "The '_' variable has been returned to its previous state.");
    var intersection = underscore.intersect([-1, 0, 1, 2], [1, 2, 3, 4]);
    equals(intersection.join(', '), '1, 2', 'but the intersection function still works');
    window._ = underscore;
  });

  test("utility: identity", function() {
    var moe = {name : 'moe'};
    equals(_.identity(moe), moe, 'moe is the same as his identity');
  });

  test('utility: breakLoop', function() {
    var result = null;
    _([1,2,3,4,5,6]).each(function(num) {
      result = num;
      if (num == 3) _.breakLoop();
    });
    equals(result, 3, 'broke out of a loop');
  });

  test("utility: uniqueId", function() {
    var ids = [], i = 0;
    while(i++ < 100) ids.push(_.uniqueId());
    equals(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids');
  });

  test("utility: functions", function() {
    var expected = ["all", "any", "bind", "bindAll", "breakLoop", "clone", "compact", "compose",
    "defer", "delay", "detect", "each", "every", "extend", "filter", "first",
    "flatten", "foldl", "foldr", "forEach", "functions", "identity", "include",
    "indexOf", "inject", "intersect", "invoke", "isArray", "isElement", "isEmpty", "isEqual",
    "isFunction", "isNumber", "isString", "isUndefined", "keys", "last", "lastIndexOf", "map", "max",
    "methods", "min", "pluck", "reduce", "reduceRight", "reject", "select",
    "size", "some", "sortBy", "sortedIndex", "template", "toArray", "uniq",
    "uniqueId", "values", "without", "wrap", "zip"];
    ok(_(expected).isEqual(_.methods()), 'provides a sorted list of functions');
  });

  test("utility: template", function() {
    var basicTemplate = _.template("<%= thing %> is gettin' on my noives!");
    var result = basicTemplate({thing : 'This'});
    equals(result, "This is gettin' on my noives!", 'can do basic attribute interpolation');
    var fancyTemplate = _.template("<% for (key in people) { %>
<%= people[key] %>
<% } %>");
    result = fancyTemplate({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
    equals(result, "
Moe

Larry

Curly
", 'can run arbitrary javascript in templates');
  });

});
<commit_msg>Correct the test for functions() to account for the new functions and aliases.<commit_after>$(document).ready(function() {

  module("Utility functions (uniqueId, template)");

  test("utility: noConflict", function() {
    var underscore = _.noConflict();
    ok(underscore.isUndefined(_), "The '_' variable has been returned to its previous state.");
    var intersection = underscore.intersect([-1, 0, 1, 2], [1, 2, 3, 4]);
    equals(intersection.join(', '), '1, 2', 'but the intersection function still works');
    window._ = underscore;
  });

  test("utility: identity", function() {
    var moe = {name : 'moe'};
    equals(_.identity(moe), moe, 'moe is the same as his identity');
  });

  test('utility: breakLoop', function() {
    var result = null;
    _([1,2,3,4,5,6]).each(function(num) {
      result = num;
      if (num == 3) _.breakLoop();
    });
    equals(result, 3, 'broke out of a loop');
  });

  test("utility: uniqueId", function() {
    var ids = [], i = 0;
    while(i++ < 100) ids.push(_.uniqueId());
    equals(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids');
  });

  test("utility: functions", function() {
    var expected = ["all", "any", "bind", "bindAll", "breakLoop", "clone", "compact",
    "compose","defer", "delay", "detect", "each", "every", "extend", "filter", "first",
    "flatten", "foldl", "foldr", "forEach", "functions", "head", "identity", "include",
    "indexOf", "init", "inject", "intersect", "invoke", "isArray", "isElement", "isEmpty", "isEqual",
    "isFunction", "isNumber", "isString", "isUndefined", "keys", "last", "lastIndexOf", "map", "max",
    "methods", "min", "pluck", "reduce", "reduceRight", "reject", "reverse", "select",
    "size", "some", "sortBy", "sortedIndex", "tail", "template", "toArray", "uniq",
    "uniqueId", "values", "without", "wrap", "zip"];
    ok(_(expected).isEqual(_.methods()), 'provides a sorted list of functions');
  });

  test("utility: template", function() {
    var basicTemplate = _.template("<%= thing %> is gettin' on my noives!");
    var result = basicTemplate({thing : 'This'});
    equals(result, "This is gettin' on my noives!", 'can do basic attribute interpolation');
    var fancyTemplate = _.template("<% for (key in people) { %>
<%= people[key] %>
<% } %>");
    result = fancyTemplate({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
    equals(result, "
Moe

Larry

Curly
", 'can run arbitrary javascript in templates');
  });

});
<|endoftext|>


<commit_before>var $ = require("../lib/keigai.js").util;

exports["clone"] = {
	setUp: function (done) {
		this.array = [true, false, true];
		done();
	},
	test: function (test) {
		var dest;

		test.expect(3);
		test.equal((dest = $.clone(this.array)).length, this.array.length, "Should be an identical Array");
		test.equal(dest.push(false), 4, "Should be `4`");
		test.equal(this.array.length, 3, "Should be `3`");
		test.done();
	}
};

exports["coerce"] = {
	setUp: function (done) {
		this.number    = "1234";
		this.boolean   = "true";
		this.json      = "{\"test\": true}";
		this.undefined = "undefined";
		this.null      = "null";
		done();
	},
	test: function (test) {
		test.expect(5);
		test.equal($.coerce(this.number), 1234, "Should be `1234`");
		test.equal($.coerce(this.boolean), true, "Should be `true`");
		test.equal($.coerce(this.json) instanceof Object, true, "Should be an Object");
		test.equal($.coerce(this.undefined), undefined, "Should be `undefined`");
		test.equal($.coerce(this.null), null, "Should be `null`");
		test.done();
	}
};

exports["extend"] = {
	setUp: function (done) {
		this.obj = {method: function () { void 0; }};
		this.ext = {};
		done();
	},
	test: function (test) {
		test.expect(1);
		test.equal(this.ext = $.extend(this.obj), this.ext, "Should be `this.ext`");
		test.done();
	}
};<commit_msg>Adding a unit test for `util.equal()`<commit_after>var $ = require("../lib/keigai.js").util;

exports["clone"] = {
	setUp: function (done) {
		this.array = [true, false, true];
		done();
	},
	test: function (test) {
		var dest;

		test.expect(3);
		test.equal((dest = $.clone(this.array)).length, this.array.length, "Should be an identical Array");
		test.equal(dest.push(false), 4, "Should be `4`");
		test.equal(this.array.length, 3, "Should be `3`");
		test.done();
	}
};

exports["coerce"] = {
	setUp: function (done) {
		this.number    = "1234";
		this.boolean   = "true";
		this.json      = "{\"test\": true}";
		this.undefined = "undefined";
		this.null      = "null";
		done();
	},
	test: function (test) {
		test.expect(5);
		test.equal($.coerce(this.number), 1234, "Should be `1234`");
		test.equal($.coerce(this.boolean), true, "Should be `true`");
		test.equal($.coerce(this.json) instanceof Object, true, "Should be an Object");
		test.equal($.coerce(this.undefined), undefined, "Should be `undefined`");
		test.equal($.coerce(this.null), null, "Should be `null`");
		test.done();
	}
};

exports["equal"] = {
	setUp: function (done) {
		this.a = {a: true, b: false};
		this.b = {a: true, b: false};
		this.c = {a: true, b: true};
		done();
	},
	test: function (test) {
		test.expect(3);
		test.equal($.equal(this.a, this.b), true, "Should be `true`");
		test.equal($.equal(this.a, this.c), false, "Should be `false`");
		test.equal($.equal(this.b, this.c), false, "Should be `false`");
		test.done();
	}
};

exports["extend"] = {
	setUp: function (done) {
		this.obj = {method: function () { void 0; }};
		this.ext = {};
		done();
	},
	test: function (test) {
		test.expect(1);
		test.equal(this.ext = $.extend(this.obj), this.ext, "Should be `this.ext`");
		test.done();
	}
};<|endoftext|>


<commit_before>/*
 * (C) Copyright 2013-2014 Kurento (http://kurento.org/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/**
 * {@link HttpEndpoint} test suite.
 *
 *

 * Methods tested:
 *

 *
{@link HttpEndpoint#getUrl()}
 *

 *

 * Events tested:
 *

 *
{@link HttpEndpoint#addMediaSessionStartListener(MediaEventListener)}
 *

 * {@link HttpEndpoint#addMediaSessionTerminatedListener(MediaEventListener)}
 *

 *
 *
 * @author Jesús Leganés Combarro "piranna" (piranna@gmail.com)
 * @version 1.0.0
 *
 */

if (typeof QUnit == 'undefined') {
  QUnit = require('qunit-cli');
  QUnit.load();

  kurentoClient = require('..');

  require('./_common');
  require('./_proxy');
};

if (QUnit.config.prefix == undefined)
  QUnit.config.prefix = '';

QUnit.module(QUnit.config.prefix + 'waiting', lifecycle);

function getOnError(done) {
  return function onerror(error) {
    QUnit.pushFailure(error.message || error, error.stack);

    done();
  };
}

/**
 * Waiting 10 minutes and ask again for an object
 */
QUnit.test('Waiting 10 minutes and ask again for an object', function (assert) {
  var self = this;

  QUnit.config.testTimeout = 660000;
  QUnit.expect(2);

  var done = assert.async()
  var onerror = getOnError(done)

  var client = this.kurento
  var pipeline = this.pipeline
  var sessionId = client.sessionId;

  setTimeout(function () {
    client.getMediaobjectById(pipeline.id, function (error, pipeline_) {

      QUnit.equal(error, null)

      if (error) return onerror(error);

      QUnit.equal(pipeline.id, pipeline_.id);

      console.log("Pipeline:", pipeline.id, " pipeline_:",
        pipeline_.id)

      QUnit.config.testTimeout = 30000 * Timeout.factor;

      done();
    })
  }, 600000);

});
<commit_msg>[test] Reduce test time<commit_after>/*
 * (C) Copyright 2013-2014 Kurento (http://kurento.org/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/**
 * {@link HttpEndpoint} test suite.
 *
 *

 * Methods tested:
 *

 *
{@link HttpEndpoint#getUrl()}
 *

 *

 * Events tested:
 *

 *
{@link HttpEndpoint#addMediaSessionStartListener(MediaEventListener)}
 *

 * {@link HttpEndpoint#addMediaSessionTerminatedListener(MediaEventListener)}
 *

 *
 *
 * @author Jesús Leganés Combarro "piranna" (piranna@gmail.com)
 * @version 1.0.0
 *
 */

if (typeof QUnit == 'undefined') {
  QUnit = require('qunit-cli');
  QUnit.load();

  kurentoClient = require('..');

  require('./_common');
  require('./_proxy');
};

if (QUnit.config.prefix == undefined)
  QUnit.config.prefix = '';

QUnit.module(QUnit.config.prefix + 'waiting', lifecycle);

function getOnError(done) {
  return function onerror(error) {
    QUnit.pushFailure(error.message || error, error.stack);

    done();
  };
}

/**
 * Waiting 2 minutes and ask again for an object
 */
QUnit.test('Waiting 2 minutes and ask again for an object', function (assert) {
  var self = this;

  QUnit.config.testTimeout = 132000;
  QUnit.expect(2);

  var done = assert.async()
  var onerror = getOnError(done)

  var client = this.kurento
  var pipeline = this.pipeline

  setTimeout(function () {
    client.getMediaobjectById(pipeline.id, function (error, pipeline_) {

      QUnit.equal(error, null)

      if (error) return onerror(error);

      QUnit.equal(pipeline.id, pipeline_.id);

      console.log("Pipeline:", pipeline.id, " pipeline_:",
        pipeline_.id)

      QUnit.config.testTimeout = 6000 * Timeout.factor;

      done();
    })
  }, 120000);

});
<|endoftext|>


<commit_before>/*global require*/
require(["gtfs-exchange"], function (Agencies) {
	"use strict";
	var agencyListUrl = "proxy.ashx?http://www.gtfs-data-exchange.com/api/agencies";

	function isInWA(val) {
		return val && val.country === "United States" && val.state === "Washington";
	}

	function createAgencyTable(/**Object[]*/ agencies) {
		var table, propNames, i, l, row, cell;
		if (agencies && agencies.length) {
			table = document.createElement("table");
			table.createTBody();
			// Get agency property names.
			propNames = Object.getOwnPropertyNames(agencies[0]);

			for (i = 0, l = agencies.length; i < l; i++) {
				row = table.insertRow(i);
				for (var j = 0, jl = propNames.length; j < jl; j += 1) {
					cell = row.insertCell(j);
					cell.textContent = String(agencies[i][propNames[j]]);
				}
			}

			table.createTHead();
			row = table.insertRow(0);
			for (i = 0, l = propNames.length; i < l; i += 1) {
				cell = row.insertCell(i);
				cell.textContent = propNames[i];
			}
		}

		return table;

	}

	function handleAgencyList(/**{string}*/ json) {
		var agencies, agencyResponse = Agencies.parseAgencyResponse(json);

		/** Use with Array.filter() filter out non-WA agencies.
		*/

		if (agencyResponse.data) {
			agencies = agencyResponse.data;
			agencies = agencies.filter(isInWA);
			document.body.appendChild(createAgencyTable(agencies));
		}
	}

	function sendRequestForAgencyList() {
		var xhr = new XMLHttpRequest();
		xhr.open("GET", agencyListUrl, true);
		xhr.onload = function () {
			if (xhr.readyState === 4) {
				if (xhr.status === 200) {
					handleAgencyList(xhr.responseText);
				} else {
					console.error(xhr.statusText);
				}
			}
		};
		xhr.onerror = function (e) {
			console.error(e);
		};
		xhr.send();
	}

	sendRequestForAgencyList();
});<commit_msg>Loops now use Array.forEach.<commit_after>/*global require*/
require(["gtfs-exchange"], function (Agencies) {
	"use strict";
	var agencyListUrl = "proxy.ashx?http://www.gtfs-data-exchange.com/api/agencies";

	function isInWA(val) {
		return val && val.country === "United States" && val.state === "Washington";
	}

	function createAgencyTable(/**Object[]*/ agencies) {
		var table, propNames, insertCell, row;

		if (agencies && agencies.length) {
			table = document.createElement("table");
			table.createTBody();
			// Get agency property names.
			propNames = Object.getOwnPropertyNames(agencies[0]);

			/** Inserts a cell into a row.
			 * @this {Object} Properties are row and agency.
			*/
			insertCell = function (propName, j) {
				var cell = this.row.insertCell(j);
				cell.textContent = String(this.agency[propName]);
			};

			// Add rows for each agency.
			agencies.forEach(function (agency, i) {
				var row = table.insertRow(i);
				propNames.forEach(insertCell, { row: row, agency: agency });
			});

			// Add the header
			table.createTHead();
			row = table.insertRow(0);

			propNames.forEach(function (propName, i) {
				var cell = row.insertCell(i);
				cell.textContent = propName;
			});
		}

		return table;

	}

	function handleAgencyList(/**{string}*/ json) {
		var agencies, agencyResponse = Agencies.parseAgencyResponse(json);

		/** Use with Array.filter() filter out non-WA agencies.
		*/

		if (agencyResponse.data) {
			agencies = agencyResponse.data;
			agencies = agencies.filter(isInWA);
			document.body.appendChild(createAgencyTable(agencies));
		}
	}

	function sendRequestForAgencyList() {
		var xhr = new XMLHttpRequest();
		xhr.open("GET", agencyListUrl, true);
		xhr.onload = function () {
			if (xhr.readyState === 4) {
				if (xhr.status === 200) {
					handleAgencyList(xhr.responseText);
				} else {
					console.error(xhr.statusText);
				}
			}
		};
		xhr.onerror = function (e) {
			console.error(e);
		};
		xhr.send();
	}

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