<commit_before>/*global kontext: true, describe: true, it: true, expect: true*/
describe('Kontext Provider Text', function() {
	'use strict';

	var provider = kontext.provider('text');

	it('text provider exists', function() {
		expect(typeof provider).toBe('function');
	});

	it('finds all placeholders', function() {
		var main = document.createElement('main'),
			collect = [];

		main.appendChild(document.createTextNode('hello {greet}'));
		main.appendChild(document.createElement('div'))
			.appendChild(document.createTextNode('a {foo:fool} walks into a {bar:trap}.'))
		main.appendChild(document.createTextNode('goodbye {target}!'));

		provider(kontext.defaults(), main, function(target, options) {
			expect(target.nodeType).toBe(3);

			expect('text' in options).toBe(true);
			expect(typeof options.text).toBe('object');
			expect('target' in options.text).toBe(true);
			expect('initial' in options.text).toBe(true);

			if (options.text.target === 'foo') {
				expect(options.text.initial).toBe('fool');
			}
			else if (options.text.target === 'bar') {
				expect(options.text.initial).toBe('trap');
			}
			else {
				expect(options.text.initial).toBe('');
			}

			collect.push(options.text.target);
		});

		expect(collect.length).toBe(4);
		expect(collect.indexOf('greet') >= 0).toBe(true);
		expect(collect.indexOf('foo') >= 0).toBe(true);
		expect(collect.indexOf('bar') >= 0).toBe(true);
		expect(collect.indexOf('target') >= 0).toBe(true);
	});
});
<commit_msg>okay codacy, you're right... Missing semicolon.<commit_after>/*global kontext: true, describe: true, it: true, expect: true*/
describe('Kontext Provider Text', function() {
	'use strict';

	var provider = kontext.provider('text');

	it('text provider exists', function() {
		expect(typeof provider).toBe('function');
	});

	it('finds all placeholders', function() {
		var main = document.createElement('main'),
			collect = [];

		main.appendChild(document.createTextNode('hello {greet}'));
		main.appendChild(document.createElement('div'))
			.appendChild(document.createTextNode('a {foo:fool} walks into a {bar:trap}.'));
		main.appendChild(document.createTextNode('goodbye {target}!'));

		provider(kontext.defaults(), main, function(target, options) {
			expect(target.nodeType).toBe(3);

			expect('text' in options).toBe(true);
			expect(typeof options.text).toBe('object');
			expect('target' in options.text).toBe(true);
			expect('initial' in options.text).toBe(true);

			if (options.text.target === 'foo') {
				expect(options.text.initial).toBe('fool');
			}
			else if (options.text.target === 'bar') {
				expect(options.text.initial).toBe('trap');
			}
			else {
				expect(options.text.initial).toBe('');
			}

			collect.push(options.text.target);
		});

		expect(collect.length).toBe(4);
		expect(collect.indexOf('greet') >= 0).toBe(true);
		expect(collect.indexOf('foo') >= 0).toBe(true);
		expect(collect.indexOf('bar') >= 0).toBe(true);
		expect(collect.indexOf('target') >= 0).toBe(true);
	});
});
<|endoftext|>


<commit_before>"use strict";

/* jshint camelcase: false */
/* jshint expr: true */
var chai      = require('chai')
  , Sequelize = require('../../index')
  , Promise   = Sequelize.Promise
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , dialect   = Support.getTestDialect()
  , datetime  = require('chai-datetime');

chai.use(datetime);
chai.config.includeStack = true;

describe(Support.getTestDialectTeaser("Model"), function () {
  describe('attributes', function () {
    describe('field', function () {
      beforeEach(function () {
        var queryInterface = this.sequelize.getQueryInterface();

        this.User = this.sequelize.define('user', {
          id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true,
            autoIncrement: true,
            field: 'userId'
          },
          name: {
            type: DataTypes.STRING,
            field: 'full_name'
          }
        }, {
          tableName: 'users',
          timestamps: false
        });

        this.Task = this.sequelize.define('task', {
          id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true,
            autoIncrement: true,
            field: 'taskId'
          },
          title: {
            type: DataTypes.STRING,
            field: 'name'
          }
        }, {
          tableName: 'tasks',
          timestamps: false
        });

        this.Comment = this.sequelize.define('comment', {
          id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true,
            autoIncrement: true,
            field: 'commentId'
          },
          text: {
            type: DataTypes.STRING,
            field: 'comment_text'
          },
		  notes: {
			type: DataTypes.STRING,
			field: 'notes'
		  }
        }, {
          tableName: 'comments',
          timestamps: false
        });

        this.User.hasMany(this.Task, {
          foreignKey: 'user_id'
        });
        this.Task.belongsTo(this.User, {
          foreignKey: 'user_id'
        });
        this.Task.hasMany(this.Comment, {
          foreignKey: 'task_id'
        });
        this.Comment.belongsTo(this.Task, {
          foreignKey: 'task_id'
        });

        return Promise.all([
          queryInterface.createTable('users', {
            userId: {
              type: DataTypes.INTEGER,
              allowNull: false,
              primaryKey: true,
              autoIncrement: true
            },
            full_name: {
              type: DataTypes.STRING
            }
          }),
          queryInterface.createTable('tasks', {
            taskId: {
              type: DataTypes.INTEGER,
              allowNull: false,
              primaryKey: true,
              autoIncrement: true
            },
            user_id: {
              type: DataTypes.INTEGER
            },
            name: {
              type: DataTypes.STRING
            }
          }),
          queryInterface.createTable('comments', {
            commentId: {
              type: DataTypes.INTEGER,
              allowNull: false,
              primaryKey: true,
              autoIncrement: true
            },
            task_id: {
              type: DataTypes.INTEGER
            },
            comment_text: {
              type: DataTypes.STRING
            },
			notes: {
			  type: DataTypes.STRING
			}
          })
        ]);
      });

      it('should create, fetch and update with alternative field names from a simple model', function () {
        var self = this;

        return this.User.create({
          name: 'Foobar'
        }).then(function () {
          return self.User.find({
            limit: 1
          });
        }).then(function (user) {
          expect(user.get('name')).to.equal('Foobar');
          return user.updateAttributes({
            name: 'Barfoo'
          });
        }).then(function () {
          return self.User.find({
            limit: 1
          });
        }).then(function (user) {
          expect(user.get('name')).to.equal('Barfoo');
        });
      });

      it('should make the aliased auto incremented primary key available after create', function () {
        var self = this;
        return this.User.create({
          name: 'Barfoo'
        }).then(function (user) {
          expect(user.get('id')).to.be.ok;
        });
      });

      it('should work with where on includes for find', function () {
        var self = this;

        return this.User.create({
          name: 'Barfoo'
        }).then(function (user) {
          return user.createTask({
            title: 'DatDo'
          });
        }).then(function (task) {
          return task.createComment({
            text: 'Comment'
          });
        }).then(function () {
          return self.Task.find({
            include: [
              {model: self.Comment},
              {model: self.User}
            ],
            where: {title: 'DatDo'}
          });
        }).then(function (task) {
          expect(task.get('title')).to.equal('DatDo');
          expect(task.get('comments')[0].get('text')).to.equal('Comment');
          expect(task.get('user')).to.be.ok;
        });
      });

      it('should work with where on includes for findAll', function () {
        var self = this;

        return this.User.create({
          name: 'Foobar'
        }).then(function (user) {
          return user.createTask({
            title: 'DoDat'
          });
        }).then(function (task) {
          return task.createComment({
            text: 'Comment'
          });
        }).then(function () {
          return self.User.findAll({
            include: [
              {model: self.Task, where: {title: 'DoDat'}, include: [
                {model: self.Comment}
              ]}
            ]
          });
        }).then(function (users) {
          users.forEach(function (user) {
            expect(user.get('name')).to.be.ok;
            expect(user.get('tasks')[0].get('title')).to.equal('DoDat');
            expect(user.get('tasks')[0].get('comments')).to.be.ok;
          });
        });
      });

      it('should work with a simple where', function () {
        var self = this;

        return this.User.create({
          name: 'Foobar'
        }).then(function () {
          return self.User.find({
            where: {
              name: 'Foobar'
            }
          });
        }).then(function (user) {
          expect(user).to.be.ok;
        });
      });

      it('should work with bulkCreate and findAll', function () {
        var self = this;
        return this.User.bulkCreate([{
          name: 'Abc',
        }, {
          name: 'Bcd'
        }, {
          name: 'Cde'
        }]).then(function () {
          return self.User.findAll();
        }).then(function (users) {
          users.forEach(function (user) {
            expect(['Abc', 'Bcd', 'Cde'].indexOf(user.get('name')) !== -1).to.be.true;
          });
        });
      });

    it('should support renaming of sequelize method fields', function () {
      var User = this.sequelize.define('user', {
        someProperty: Sequelize.VIRTUAL // Since we specify the AS part as a part of the literal string, not with sequelize syntax, we have to tell sequelize about the field
      });

      return this.sequelize.sync({ force: true }).then(function () {
        return User.create({});
      }).then(function () {
        return User.findAll({
          attributes: [
            Sequelize.literal('EXISTS(SELECT 1) AS "someProperty"'),
            [Sequelize.literal('EXISTS(SELECT 1)'), 'someProperty2']
          ]
        });
      }).then(function (users) {
        expect(users[0].get('someProperty')).to.be.ok;
        expect(users[0].get('someProperty2')).to.be.ok;
      });
    });

	  it('field names that are the same as property names should create, update, and read correctly', function () {
        var self = this;

        return this.Comment.create({
          notes: 'Foobar'
        }).then(function () {
          return self.Comment.find({
            limit: 1
          });
        }).then(function (comment) {
          expect(comment.get('notes')).to.equal('Foobar');
          return comment.updateAttributes({
            notes: 'Barfoo'
          });
        }).then(function () {
          return self.Comment.find({
            limit: 1
          });
        }).then(function (comment) {
          expect(comment.get('notes')).to.equal('Barfoo');
        });
      });

    });

    describe('types', function () {
      describe('VIRTUAL', function () {
        beforeEach(function () {
          this.User = this.sequelize.define('user', {
            storage: Sequelize.STRING,
            field1: {
              type: Sequelize.VIRTUAL,
              set: function (val) {
                this.setDataValue('storage', val);
                this.setDataValue('field1', val);
              },
              get: function () {
                return this.getDataValue('field1');
              }
            },
            field2: {
              type: Sequelize.VIRTUAL,
              get: function () {
                return 42;
              }
            },
            virtualWithDefault: {
              type: Sequelize.VIRTUAL,
              defaultValue: 'cake'
            }
          }, { timestamps: false });

          this.Task = this.sequelize.define('task', {});
          this.Project = this.sequelize.define('project', {});

          this.Task.belongsTo(this.User);
          this.Project.hasMany(this.User);
          this.User.hasMany(this.Project);

          this.sqlAssert = function(sql) {
            expect(sql.indexOf('field1')).to.equal(-1);
            expect(sql.indexOf('field2')).to.equal(-1);
          };

          return this.sequelize.sync({ force: true });
        });

        it('should not be ignored in dataValues get', function () {
          var user = this.User.build({
            field1: 'field1_value',
            field2: 'field2_value'
          });

          expect(user.get()).to.deep.equal({ storage: 'field1_value', field1: 'field1_value', virtualWithDefault: 'cake', field2: 42, id: null });
        });

        it('should be ignored in table creation', function () {
          return this.sequelize.getQueryInterface().describeTable(this.User.tableName).then(function (fields) {
            expect(Object.keys(fields).length).to.equal(2);
          });
        });

        it('should be ignored in find, findAll and includes', function () {
          return Promise.all([
            this.User.find().on('sql', this.sqlAssert),
            this.User.findAll().on('sql', this.sqlAssert),
            this.Task.findAll({
              include: [
                this.User
              ]
            }).on('sql', this.sqlAssert),
            this.Project.findAll({
              include: [
                this.User
              ]
            }).on('sql', this.sqlAssert)
          ]);
        });

        it("should allow me to store selected values", function () {
          var Post = this.sequelize.define('Post', {
              text: Sequelize.TEXT,
              someBoolean: {
                type: Sequelize.VIRTUAL
              }
            });

          return this.sequelize.sync({ force: true}).then(function () {
            return Post.bulkCreate([{ text: 'text1' },{ text: 'text2' }]);
          }).then(function () {
            return Post.find({ attributes: ['id','text',Sequelize.literal('EXISTS(SELECT 1) AS "someBoolean"')] });
          }).then(function (post) {
            expect(post.get('someBoolean')).to.be.ok;
            expect(post.get().someBoolean).to.be.ok;
          });
        });

        it('should be ignored in create and updateAttributes', function () {
          return this.User.create({
            field1: 'something'
          }).then(function (user) {
            // We already verified that the virtual is not added to the table definition, so if this succeeds, were good

            expect(user.virtualWithDefault).to.equal('cake');
            expect(user.storage).to.equal('something');
            return user.updateAttributes({
              field1: 'something else'
            });
          }).then(function (user) {
            expect(user.virtualWithDefault).to.equal('cake');
            expect(user.storage).to.equal('something else');
          });
        });

        it('should be ignored in bulkCreate and and bulkUpdate', function () {
          var self = this;
          return this.User.bulkCreate([{
            field1: 'something'
          }]).on('sql', this.sqlAssert).then(function () {
            return self.User.findAll();
          }).then(function (users) {
            expect(users[0].storage).to.equal('something');
          });
        });
      });
    });
  });
});<commit_msg>Fix test 'should support renaming of sequelize method fields'<commit_after>"use strict";

/* jshint camelcase: false */
/* jshint expr: true */
var chai      = require('chai')
  , Sequelize = require('../../index')
  , Promise   = Sequelize.Promise
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , dialect   = Support.getTestDialect()
  , datetime  = require('chai-datetime');

chai.use(datetime);
chai.config.includeStack = true;

describe(Support.getTestDialectTeaser("Model"), function () {
  describe('attributes', function () {
    describe('field', function () {
      beforeEach(function () {
        var queryInterface = this.sequelize.getQueryInterface();

        this.User = this.sequelize.define('user', {
          id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true,
            autoIncrement: true,
            field: 'userId'
          },
          name: {
            type: DataTypes.STRING,
            field: 'full_name'
          }
        }, {
          tableName: 'users',
          timestamps: false
        });

        this.Task = this.sequelize.define('task', {
          id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true,
            autoIncrement: true,
            field: 'taskId'
          },
          title: {
            type: DataTypes.STRING,
            field: 'name'
          }
        }, {
          tableName: 'tasks',
          timestamps: false
        });

        this.Comment = this.sequelize.define('comment', {
          id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true,
            autoIncrement: true,
            field: 'commentId'
          },
          text: {
            type: DataTypes.STRING,
            field: 'comment_text'
          },
		  notes: {
			type: DataTypes.STRING,
			field: 'notes'
		  }
        }, {
          tableName: 'comments',
          timestamps: false
        });

        this.User.hasMany(this.Task, {
          foreignKey: 'user_id'
        });
        this.Task.belongsTo(this.User, {
          foreignKey: 'user_id'
        });
        this.Task.hasMany(this.Comment, {
          foreignKey: 'task_id'
        });
        this.Comment.belongsTo(this.Task, {
          foreignKey: 'task_id'
        });

        return Promise.all([
          queryInterface.createTable('users', {
            userId: {
              type: DataTypes.INTEGER,
              allowNull: false,
              primaryKey: true,
              autoIncrement: true
            },
            full_name: {
              type: DataTypes.STRING
            }
          }),
          queryInterface.createTable('tasks', {
            taskId: {
              type: DataTypes.INTEGER,
              allowNull: false,
              primaryKey: true,
              autoIncrement: true
            },
            user_id: {
              type: DataTypes.INTEGER
            },
            name: {
              type: DataTypes.STRING
            }
          }),
          queryInterface.createTable('comments', {
            commentId: {
              type: DataTypes.INTEGER,
              allowNull: false,
              primaryKey: true,
              autoIncrement: true
            },
            task_id: {
              type: DataTypes.INTEGER
            },
            comment_text: {
              type: DataTypes.STRING
            },
			notes: {
			  type: DataTypes.STRING
			}
          })
        ]);
      });

      it('should create, fetch and update with alternative field names from a simple model', function () {
        var self = this;

        return this.User.create({
          name: 'Foobar'
        }).then(function () {
          return self.User.find({
            limit: 1
          });
        }).then(function (user) {
          expect(user.get('name')).to.equal('Foobar');
          return user.updateAttributes({
            name: 'Barfoo'
          });
        }).then(function () {
          return self.User.find({
            limit: 1
          });
        }).then(function (user) {
          expect(user.get('name')).to.equal('Barfoo');
        });
      });

      it('should make the aliased auto incremented primary key available after create', function () {
        var self = this;
        return this.User.create({
          name: 'Barfoo'
        }).then(function (user) {
          expect(user.get('id')).to.be.ok;
        });
      });

      it('should work with where on includes for find', function () {
        var self = this;

        return this.User.create({
          name: 'Barfoo'
        }).then(function (user) {
          return user.createTask({
            title: 'DatDo'
          });
        }).then(function (task) {
          return task.createComment({
            text: 'Comment'
          });
        }).then(function () {
          return self.Task.find({
            include: [
              {model: self.Comment},
              {model: self.User}
            ],
            where: {title: 'DatDo'}
          });
        }).then(function (task) {
          expect(task.get('title')).to.equal('DatDo');
          expect(task.get('comments')[0].get('text')).to.equal('Comment');
          expect(task.get('user')).to.be.ok;
        });
      });

      it('should work with where on includes for findAll', function () {
        var self = this;

        return this.User.create({
          name: 'Foobar'
        }).then(function (user) {
          return user.createTask({
            title: 'DoDat'
          });
        }).then(function (task) {
          return task.createComment({
            text: 'Comment'
          });
        }).then(function () {
          return self.User.findAll({
            include: [
              {model: self.Task, where: {title: 'DoDat'}, include: [
                {model: self.Comment}
              ]}
            ]
          });
        }).then(function (users) {
          users.forEach(function (user) {
            expect(user.get('name')).to.be.ok;
            expect(user.get('tasks')[0].get('title')).to.equal('DoDat');
            expect(user.get('tasks')[0].get('comments')).to.be.ok;
          });
        });
      });

      it('should work with a simple where', function () {
        var self = this;

        return this.User.create({
          name: 'Foobar'
        }).then(function () {
          return self.User.find({
            where: {
              name: 'Foobar'
            }
          });
        }).then(function (user) {
          expect(user).to.be.ok;
        });
      });

      it('should work with bulkCreate and findAll', function () {
        var self = this;
        return this.User.bulkCreate([{
          name: 'Abc',
        }, {
          name: 'Bcd'
        }, {
          name: 'Cde'
        }]).then(function () {
          return self.User.findAll();
        }).then(function (users) {
          users.forEach(function (user) {
            expect(['Abc', 'Bcd', 'Cde'].indexOf(user.get('name')) !== -1).to.be.true;
          });
        });
      });

      it('should support renaming of sequelize method fields', function () {
        var Test = this.sequelize.define('test', {
          someProperty: Sequelize.VIRTUAL // Since we specify the AS part as a part of the literal string, not with sequelize syntax, we have to tell sequelize about the field
        });

        return this.sequelize.sync({ force: true }).then(function () {
          return Test.create({});
        }).then(function () {
          return Test.findAll({
            attributes: [
              Sequelize.literal('EXISTS(SELECT 1) AS "someProperty"'),
              [Sequelize.literal('EXISTS(SELECT 1)'), 'someProperty2']
            ]
          });
        }).then(function (tests) {
          expect(tests[0].get('someProperty')).to.be.ok;
          expect(tests[0].get('someProperty2')).to.be.ok;
        });
      });

      it('field names that are the same as property names should create, update, and read correctly', function () {
        var self = this;

        return this.Comment.create({
          notes: 'Foobar'
        }).then(function () {
          return self.Comment.find({
            limit: 1
          });
        }).then(function (comment) {
          expect(comment.get('notes')).to.equal('Foobar');
          return comment.updateAttributes({
            notes: 'Barfoo'
          });
        }).then(function () {
          return self.Comment.find({
            limit: 1
          });
        }).then(function (comment) {
          expect(comment.get('notes')).to.equal('Barfoo');
        });
      });

    });

    describe('types', function () {
      describe('VIRTUAL', function () {
        beforeEach(function () {
          this.User = this.sequelize.define('user', {
            storage: Sequelize.STRING,
            field1: {
              type: Sequelize.VIRTUAL,
              set: function (val) {
                this.setDataValue('storage', val);
                this.setDataValue('field1', val);
              },
              get: function () {
                return this.getDataValue('field1');
              }
            },
            field2: {
              type: Sequelize.VIRTUAL,
              get: function () {
                return 42;
              }
            },
            virtualWithDefault: {
              type: Sequelize.VIRTUAL,
              defaultValue: 'cake'
            }
          }, { timestamps: false });

          this.Task = this.sequelize.define('task', {});
          this.Project = this.sequelize.define('project', {});

          this.Task.belongsTo(this.User);
          this.Project.hasMany(this.User);
          this.User.hasMany(this.Project);

          this.sqlAssert = function(sql) {
            expect(sql.indexOf('field1')).to.equal(-1);
            expect(sql.indexOf('field2')).to.equal(-1);
          };

          return this.sequelize.sync({ force: true });
        });

        it('should not be ignored in dataValues get', function () {
          var user = this.User.build({
            field1: 'field1_value',
            field2: 'field2_value'
          });

          expect(user.get()).to.deep.equal({ storage: 'field1_value', field1: 'field1_value', virtualWithDefault: 'cake', field2: 42, id: null });
        });

        it('should be ignored in table creation', function () {
          return this.sequelize.getQueryInterface().describeTable(this.User.tableName).then(function (fields) {
            expect(Object.keys(fields).length).to.equal(2);
          });
        });

        it('should be ignored in find, findAll and includes', function () {
          return Promise.all([
            this.User.find().on('sql', this.sqlAssert),
            this.User.findAll().on('sql', this.sqlAssert),
            this.Task.findAll({
              include: [
                this.User
              ]
            }).on('sql', this.sqlAssert),
            this.Project.findAll({
              include: [
                this.User
              ]
            }).on('sql', this.sqlAssert)
          ]);
        });

        it("should allow me to store selected values", function () {
          var Post = this.sequelize.define('Post', {
              text: Sequelize.TEXT,
              someBoolean: {
                type: Sequelize.VIRTUAL
              }
            });

          return this.sequelize.sync({ force: true}).then(function () {
            return Post.bulkCreate([{ text: 'text1' },{ text: 'text2' }]);
          }).then(function () {
            return Post.find({ attributes: ['id','text',Sequelize.literal('EXISTS(SELECT 1) AS "someBoolean"')] });
          }).then(function (post) {
            expect(post.get('someBoolean')).to.be.ok;
            expect(post.get().someBoolean).to.be.ok;
          });
        });

        it('should be ignored in create and updateAttributes', function () {
          return this.User.create({
            field1: 'something'
          }).then(function (user) {
            // We already verified that the virtual is not added to the table definition, so if this succeeds, were good

            expect(user.virtualWithDefault).to.equal('cake');
            expect(user.storage).to.equal('something');
            return user.updateAttributes({
              field1: 'something else'
            });
          }).then(function (user) {
            expect(user.virtualWithDefault).to.equal('cake');
            expect(user.storage).to.equal('something else');
          });
        });

        it('should be ignored in bulkCreate and and bulkUpdate', function () {
          var self = this;
          return this.User.bulkCreate([{
            field1: 'something'
          }]).on('sql', this.sqlAssert).then(function () {
            return self.User.findAll();
          }).then(function (users) {
            expect(users[0].storage).to.equal('something');
          });
        });
      });
    });
  });
});<|endoftext|>


<commit_before>var moment = require('moment');
var mongo_driver = require('../drivers/playlists/mongo-driver')
var should = require('should');
var mbc = require('mbc-common');

describe('PlaylistMongoDriver', function(){
    var self = this;

    before(function(done) {
        // setup mongo driver
        var conf = {
            db: {
                dbName: 'mediatestdb',
                dbHost: 'localhost',
                dbPort: 27017
            }
        };
        self.driver = new mongo_driver(conf);
        self.db = mbc.db(conf.db);
        self.driver.start();
        self.from = moment(new Date());
        self.to = moment((self.from.unix() + 120 * 60) * 1000); // add 2hs

        var playlist = {
            "_id": 1,
            "models" : [
                {
                    "file" : "./videos/SMPTE_Color_Bars_01.mp4",
                    "durationraw" : "00:30:00",
                    "fps" : 25,
                    "_id" : 1
                },
                {
                    "file" : "./videos/SMPTE_Color_Bars_02.mp4",
                    "durationraw" : "00:30:00",
                    "fps" : 25,
                    "_id" : 2
                },
                {
                    "file" : "./videos/SMPTE_Color_Bars_03.mp4",
                    "durationraw" : "00:30:00",
                    "fps" : 25,
                    "_id" : 3
                },
            ],
        }

        var schedule = {
            "title" : "long 2",
            "list" : 1,
            "start" : 1365588000,
            "end" : 1365596786,
            "allDay" : false,
            "event" : null,
            "_id" : 1365625760578
        };

        self.collections = {
            lists: self.db.collection('lists'),
            scheds: self.db.collection('scheds'),
        };

        self.collections.lists.save(playlist, function(err, list) {
            self.collections.scheds.save(schedule, function(err, sched){
                done();
            });
        });
    });

    after(function(done) {
        //
        if(self.collections) {
            for( var col in self.collections) {
                self.collections[col].drop();
            }
        }
        done();
    });

    describe('#setWindow()', function() {
        beforeEach(function(){
            self.driver.window = undefined;
        });
        it('should exist', function() {
            self.driver.should.have.property('setWindow');
            self.driver.setWindow.should.be.a('function');
        });
        it('should accept two parameters and save them in window = {from, to}', function() {
            self.driver.setWindow(self.from, self.to);
            var window = self.driver.window;
            window.should.have.property('from');
            window.should.have.property('to');
        });
        it('should accept an object', function() {
            self.driver.setWindow({from: self.from, to: self.to})
            var window = self.driver.window;
            window.should.have.property('from');
            window.should.have.property('to');
        });
        it('should accept only a "to" object and assume "from" is now', function() {
            self.driver.setWindow({to: self.to});
            self.driver.window.should.have.property('from');
        });
        it('should accept dates and transform them to moments', function() {
            self.driver.setWindow(new Date(), new Date());
            moment.isMoment(self.driver.window.from).should.be.ok;
            moment.isMoment(self.driver.window.to).should.be.ok;
        });
    });

    describe('#subscriptions', function() {
        before(function() {
            self.pubsub = mbc.pubsub();
        });

        var message = {
            backend: 'schedbackend',
            model: {
                start: moment(new Date()).unix(),
                end: moment(new Date()).add(5*60*1000).unix(),
                _id: 1,
                list: 1,
                name: 'a playlist',
            },
        };
        this.timeout(10000);
        it('should respond to create messages',function(done){
            // set window from now to 10 minutes
            message.method = 'create';
            self.driver.setWindow(new Date(), moment(new Date()).add(10 * 60 * 1000));
            self.driver.registerNewPlaylistListener(function(playlist) {
                playlist.id.should.be.eql(message.model._id);
                playlist.name.should.be.eql(message.model.name);
                moment(playlist.startDate).valueOf().should.eql(message.model.start * 1000);
                done();
            });
            self.pubsub.publish(message);
        });
        it('should respond to update messages', function(done) {
            message.method = 'update';
            self.driver.registerUpdatePlaylistListener(function(playlist) {
                done();
            });
            self.pubsub.publish(message);
        });
        it('should respond to remove messages', function(done) {
            message.method = 'delete';
            self.driver.registerRemovePlaylistListener(function(id) {
                id.should.be.eql(message.model._id);
                done();
            });
            self.pubsub.publish(message);
        });
    });
});
<commit_msg>populate db from data file<commit_after>var moment = require('moment');
var mongo_driver = require('../drivers/playlists/mongo-driver');
var should = require('should');
var mbc = require('mbc-common');
var _ = require('underscore');

describe('PlaylistMongoDriver', function(){
    var self = this;

    before(function(done) {
        // setup mongo driver
        var conf = {
            db: {
                dbName: 'mediatestdb',
                dbHost: 'localhost',
                dbPort: 27017
            }
        };
        self.driver = new mongo_driver(conf);
        self.db = mbc.db(conf.db);
        self.driver.start();
        self.from = moment(new Date());
        self.to = moment((self.from.unix() + 120 * 60) * 1000); // add 2hs

        var db_data = require('./playlists/db-data');
        var lists = db_data.lists;
        var scheds = db_data.scheds;

        self.collections = {
            lists: self.db.collection('lists'),
            scheds: self.db.collection('scheds'),
        };

        var ready = _.after(lists.length + scheds.length, function(){ done() });

        self.lists = [];
        self.scheds = [];

        lists.forEach(function(playlist) {
            self.lists.push(playlist._id);
            playlist._id = self.db.ObjectID(playlist._id);
            self.collections.lists.save(playlist, function(err, list) {
                ready();
            });
        });
        scheds.forEach(function(schedule) {
            self.scheds.push(schedule._id);
            self.collections.scheds.save(schedule, function(err, sched){
                ready();
            });
        });
    });

    after(function(done) {
        //
        if(self.collections) {
            for( var col in self.collections) {
                self.collections[col].drop();
            }
        }
        done();
    });

    describe('#setWindow()', function() {
        beforeEach(function(){
            self.driver.window = undefined;
        });
        it('should exist', function() {
            self.driver.should.have.property('setWindow');
            self.driver.setWindow.should.be.a('function');
        });
        it('should accept two parameters and save them in window = {from, to}', function() {
            self.driver.setWindow(self.from, self.to);
            var window = self.driver.window;
            window.should.have.property('from');
            window.should.have.property('to');
        });
        it('should accept an object', function() {
            self.driver.setWindow({from: self.from, to: self.to})
            var window = self.driver.window;
            window.should.have.property('from');
            window.should.have.property('to');
        });
        it('should accept only a "to" object and assume "from" is now', function() {
            self.driver.setWindow({to: self.to});
            self.driver.window.should.have.property('from');
        });
        it('should accept dates and transform them to moments', function() {
            self.driver.setWindow(new Date(), new Date());
            moment.isMoment(self.driver.window.from).should.be.ok;
            moment.isMoment(self.driver.window.to).should.be.ok;
        });
    });

    describe('#subscriptions', function() {
        before(function() {
            self.pubsub = mbc.pubsub();

            self.message = {
                backend: 'schedbackend',
                model: {
                    start: moment(new Date()).unix(),
                    end: moment(new Date()).add(5*60*1000).unix(),
                    _id: self.scheds[0],
                    list: self.lists[0],
                    name: 'a playlist',
                },
            };
        });

        this.timeout(10000);
        it('should respond to create messages',function(done){
            // set window from now to 10 minutes
            var message = self.message;
            message.method = 'create';
            self.driver.setWindow(new Date(), moment(new Date()).add(10 * 60 * 1000));
            self.driver.registerNewPlaylistListener(function(playlist) {
                playlist.id.should.be.eql(message.model._id);
                playlist.name.should.be.eql(message.model.name);
                moment(playlist.startDate).valueOf().should.eql(message.model.start * 1000);
                done();
            });
            self.pubsub.publish(message);
        });
        it('should respond to update messages', function(done) {
            var message = self.message;
            message.method = 'update';
            self.driver.registerUpdatePlaylistListener(function(playlist) {
                done();
            });
            self.pubsub.publish(message);
        });
        it('should respond to remove messages', function(done) {
            var message = self.message;
            message.method = 'delete';
            self.driver.registerRemovePlaylistListener(function(id) {
                id.should.be.eql(message.model._id);
                done();
            });
            self.pubsub.publish(message);
        });
    });
});
<|endoftext|>


<commit_before>'use strict';
require('../helpers');
const assert  = require('assert');
const Ironium = require('../..');

describe('Processing', ()=> {

  const errorCallbackQueue   = Ironium.queue('error-callback');
  const errorPromiseQueue    = Ironium.queue('error-promise');
  const errorGeneratorQueue  = Ironium.queue('error-generator');

  function untilSuccessful() {
    return Ironium.runOnce()
      .catch(function() {
        return untilSuccessful();
      });
  }

  describe('with callback error', ()=> {

    // First two runs should fail, runs ends at 3
    let runs = 0;
    before(()=> {
      errorCallbackQueue.eachJob((job, callback)=> {
        runs++;
        if (runs > 2)
          callback();
        else
          callback(new Error('fail'));
      });
    });

    before(()=> errorCallbackQueue.queueJob('job'));
    before(untilSuccessful);

    it('should repeat until processed', ()=> {
      assert.equal(runs, 3);
    });

  });

  describe('with rejected promise', ()=> {

    // First two runs should fail, runs ends at 3
    let runs = 0;
    before(()=> {
      errorPromiseQueue.eachJob(()=> {
        runs++;
        if (runs > 2)
          return Promise.resolve();
        else
          return Promise.reject(new Error('fail'));
      });
    });

    before(()=> errorPromiseQueue.queueJob('job'));
    before(untilSuccessful);

    it('should repeat until processed', ()=> {
      assert.equal(runs, 3);
    });

  });

  describe('with generator error', ()=> {

    // First two runs should fail, runs ends at 3
    let runs = 0;
    before(()=> {
      errorGeneratorQueue.eachJob(function*() {
        runs++;
        switch (runs) {
          case 1: {
              throw new Error('fail');
            }
          case 2: {
              yield Promise.reject(Error('fail'));
              break;
            }
        }
      });
    });

    before(()=> errorGeneratorQueue.queueJob('job'));
    before(untilSuccessful);

    it('should repeat until processed', ()=> {
      assert.equal(runs, 3);
    });

  });

});

<commit_msg>Cleanup error_test.js<commit_after>'use strict';
require('../helpers');
const assert  = require('assert');
const Ironium = require('../..');

describe('Running a job', function() {

  const errorCallbackQueue   = Ironium.queue('error-callback');
  const errorPromiseQueue    = Ironium.queue('error-promise');
  const errorGeneratorQueue  = Ironium.queue('error-generator');

  function untilSuccessful() {
    return Ironium.runOnce()
      .catch(function() {
        return untilSuccessful();
      });
  }

  describe('with callback error (twice)', function() {

    // First two runs should fail, runs ends at 3
    let runs = 0;

    function countAndFailJob(job, callback) {
      runs++;
      if (runs > 2)
        callback();
      else
        callback(new Error('fail'));
    }

    before(Ironium.purgeQueues);
    before(function() {
      errorCallbackQueue.eachJob(countAndFailJob);
      return errorCallbackQueue.queueJob('job');
    });
    before(untilSuccessful);

    it('should run three times until successful', function() {
      assert.equal(runs, 3);
    });

  });

  describe('with rejected promise (twice)', function() {

    // First two runs should fail, runs ends at 3
    let runs = 0;

    function countAndFailJob() {
      runs++;
      if (runs > 2)
        return Promise.resolve();
      else
        return Promise.reject(new Error('fail'));
    }

    before(Ironium.purgeQueues);
    before(function() {
      errorCallbackQueue.eachJob(countAndFailJob);
      return errorCallbackQueue.queueJob('job');
    });
    before(untilSuccessful);

    it('should run three times until successful', function() {
      assert.equal(runs, 3);
    });

  });

  describe('with generator error (twice)', function() {

    // First two runs should fail, runs ends at 3
    let runs = 0;

    function* countAndFailJob() {
      runs++;
      switch (runs) {
        case 1: {
          throw new Error('fail');
        }
        case 2: {
          yield Promise.reject(Error('fail'));
          break;
        }
        default: {
          break;
        }
      }
    }

    before(Ironium.purgeQueues);
    before(function() {
      errorCallbackQueue.eachJob(countAndFailJob);
      return errorCallbackQueue.queueJob('job');
    });
    before(untilSuccessful);

    it('should run three times until successful', function() {
      assert.equal(runs, 3);
    });

  });

});

<|endoftext|>


<commit_before>var assert = require("assert");
var {Client, request, post, get, put, del} = require('ringo/httpclient');
var {Server} = require('ringo/httpserver');
var {Request} = require('ringo/webapp/request');
var {Response} = require('ringo/webapp/response');

var server;
var host = "127.0.0.1";
var port = "8282";
var baseUri = "http://" + host + ":" + port + "/";

require('ringo/logging').setConfig(getResource('./httpclient_log4j.properties'));

/**
 * tests overwrite getResponse() to control the response they expect back
 */
var getResponse;

/**
 * setUp pre every test
 */
exports.setUp = function() {
    var handleRequest = function(env) {
        var req = new Request(env);
        req.charset = config.charset || 'utf8';
        req.pathInfo = decodeURI(req.pathInfo);
        return getResponse(req, env);
    };

    var config = {
       host: host,
       port: port
    };

    server = new Server(config);
    server.getDefaultContext().serveApplication(handleRequest);
    server.start();
    // test used to hang without this, but seems no longer the case
    // java.lang.Thread.currentThread().sleep(1000);
};

/**
 * tearDown after each test
 */
exports.tearDown = function() {
    server.stop();
    server.destroy();
    server = null;
};

/**
 * test that callbacks get called at all; all other
 * tests rely on that.
 */
exports.testCallbacksGetCalled = function() {
   getResponse = function(req) {
      return new Response('');
   };

   var successCalled, completeCalled, errorCalled;
   var exchange = request({
      url: baseUri,
      success: function() {
         successCalled = true;
      },
      complete: function() {
         completeCalled = true;
      },
      error: function() {
         errorCalled = true;
      }
   });
   assert.isTrue(successCalled);
   assert.isTrue(completeCalled);
   assert.isUndefined(errorCalled);
};

/**
 * test basic get
 */
exports.testBasic = function() {
   getResponse = function(req) {
      return new Response('
This is the Response Text
');
   };

   var errorCalled, myData;
   var exchange = request({
      url: baseUri,
      success: function(data, status, contentType, exchange) {
         myData = data;
      },
      error: function() {
         errorCalled = true;
      }
   });
   assert.isUndefined(errorCalled);
   assert.strictEqual(myData, '
This is the Response Text
');
};

/**
 * convinience wrappers
 */
exports.testConvenience = function() {
    getResponse = function(req) {
        if (req.params.foo) {
            return new Response (req.method + ' with param');
        }
        return new Response(req.method);
    };
    var x = post(baseUri);
    assert.strictEqual(200, x.status);
    assert.strictEqual('POST', x.content);

    x = post(baseUri, {foo: 'bar'});
    assert.strictEqual(200, x.status);
    assert.strictEqual('POST with param', x.content);

    x = get(baseUri, {foo: 'bar'});
    assert.strictEqual(200, x.status);
    assert.strictEqual('GET with param', x.content);

    x = del(baseUri);
    assert.strictEqual(200, x.status);
    assert.strictEqual('DELETE', x.content);

    x = put(baseUri);
    assert.strictEqual(200, x.status);
    assert.strictEqual('PUT', x.content);
};

/**
 * GET, POST params
 */
exports.testParams = function() {
    getResponse = function(req) {
        return new Response(JSON.stringify(req.params));
    };
    var data = {
        a: "fääßß",
        b: "fööööbääzz",
        c: "08083",
        d: "0x0004"
    };
    var getExchange = request({
        url: baseUri,
        method: 'GET',
        data: data
    });
    assert.strictEqual(200, getExchange.status);
    var receivedData = JSON.parse(getExchange.content);
    assert.deepEqual(data, receivedData);

    var postExchange = request({
        url: baseUri,
        method: 'POST',
        data: data
    });
    assert.strictEqual(200, postExchange.status);
    receivedData = JSON.parse(postExchange.content);
    assert.deepEqual(data, receivedData);
};

/**
 * Callbacks
 */
exports.testCallbacks = function() {
    getResponse = function(req) {
        if (req.pathInfo == '/notfound') {
            return Response.notFound('error');
        } else if (req.pathInfo == '/success') {
            var res = new Response('success');
            res.contentType = 'text/json';
            return res;
        } else if (req.pathInfo == '/redirect') {
            return {
                status: 302,
                headers: {Location: '/redirectlocation'},
                body: ["Found: " + '/redirectlocation']
            };
        } else if (req.pathInfo == '/redirectlocation') {
            return new Response('redirect success');
        }
    };
    var myStatus, successCalled, errorCalled, myMessage, myContentType, myData;
    // success shouldn't get called
    var getErrorExchange = request({
        url: baseUri + 'notfound',
        method: 'GET',
        complete: function(data, status, contentType, exchange) {
            myStatus = status;
        },
        success: function() {
            successCalled = true
        },
        error: function(message, status, exchange) {
            myMessage = message;
        }
    });
    assert.isUndefined(successCalled);
    assert.strictEqual(myStatus, 404);
    assert.strictEqual(getErrorExchange.status, 404);
    assert.strictEqual(myMessage, "Not Found");

    var getSuccessExchange = request({
        url: baseUri + 'success',
        method: 'GET',
        complete: function(data, status, contentType, exchange) {
            myStatus = status;
        },
        success: function(data, status, contentType, exchange) {
            myContentType = contentType;
        },
        error: function() {
            errorCalled = true;
        }
    });
    assert.strictEqual('text/json; charset=utf-8', myContentType);
    assert.strictEqual(200, myStatus);
    assert.isUndefined(errorCalled);

    var getRedirectExchange = request({
        url: baseUri + 'redirect',
        method: 'GET',
        complete: function(data, status, contentType, exchange) {
            myStatus = status;
            myData = data;
        },
        error: function(message) {
            errorCalled = true;
        }
    });
    assert.strictEqual(200, myStatus);
    assert.strictEqual('redirect success', myData);
    assert.isUndefined(errorCalled);
};

/**
 * Cookie set and read
 */
exports.testCookie = function() {
    var COOKIE_NAME = 'testcookie'
    var COOKIE_VALUE = 'cookie value with s p   a c es';

    getResponse = function(req) {
        // set cookie
        var res = new Response('cookie set');
        res.setCookie(COOKIE_NAME, req.params.cookievalue, 5);
        return res;
    };

    // receive cookie
    var myStatus, myExchange, errorCalled;
    request({
        url: baseUri,
        method: 'GET',
        data: {'cookievalue': COOKIE_VALUE},
        complete: function(data, status, contentType, exchange) {
            myStatus = status;
        },
        success: function(data, status, contentType, exchange) {
            myExchange = exchange;
        },
        error: function() {
            errorCalled = true;
        }
    });
    assert.isUndefined(errorCalled);
    assert.strictEqual(200, myStatus);
    assert.strictEqual(COOKIE_VALUE, myExchange.cookies[COOKIE_NAME].value);
};

/**
 * send stream and get the same stream back
 */
exports.testStreamRequest = function() {

    getResponse = function(req, env) {
        if (req.isPost) {
            var input;
            return {
                    status: 200,
                    headers: {
                        'Content-Type': 'image/png'
                    },
                    body: {
                        forEach: function(fn) {
                            var read, bufsize = 8192;
                            var buffer = new ByteArray(bufsize);
                            input = env.input;
                            while ((read = input.readInto(buffer)) > -1) {
                                buffer.length = read;
                                fn(buffer);
                                buffer.length = bufsize;
                            }
                        },
                        close: function() {
                            if (input) {
                                input.close();
                            }
                        }
                    }
                };

        }
    };

    var resource = getResource('./upload_test.png');
    var ByteArray = require('binary').ByteArray;
    var inputStream = resource.getInputStream();
    // small <1k file, just read it all in
    var size = resource.getLength();
    var inputByteArray = new ByteArray(size);
    inputStream.read(inputByteArray, 0, size);
    var sendInputStream = resource.getInputStream();
    var myExchange, myContentType, errorCalled;
    request({
        url: baseUri,
        method: 'POST',
        data: sendInputStream,
        error: function() {
            errorCalled = true;
        },
        complete: function(data, status, contentType, exchange) {
            myExchange = exchange;
            myContentType = contentType;
        }
    });
    assert.isUndefined(errorCalled);
    assert.isNotNull(myExchange);
    assert.strictEqual (inputByteArray.length, myExchange.contentBytes.length);
    assert.deepEqual (inputByteArray.toArray(), myExchange.contentBytes.toArray());
    assert.strictEqual('image/png', myContentType);
};
<commit_msg>Simple test to confirm env.servlet is set.<commit_after>var assert = require("assert");
var {Client, request, post, get, put, del} = require('ringo/httpclient');
var {Server} = require('ringo/httpserver');
var {Request} = require('ringo/webapp/request');
var {Response} = require('ringo/webapp/response');

var server;
var host = "127.0.0.1";
var port = "8282";
var baseUri = "http://" + host + ":" + port + "/";

require('ringo/logging').setConfig(getResource('./httpclient_log4j.properties'));

/**
 * tests overwrite getResponse() to control the response they expect back
 */
var getResponse;

/**
 * setUp pre every test
 */
exports.setUp = function() {
    var handleRequest = function(env) {
        var req = new Request(env);
        req.charset = config.charset || 'utf8';
        req.pathInfo = decodeURI(req.pathInfo);
        return getResponse(req, env);
    };

    var config = {
       host: host,
       port: port
    };

    server = new Server(config);
    server.getDefaultContext().serveApplication(handleRequest);
    server.start();
    // test used to hang without this, but seems no longer the case
    // java.lang.Thread.currentThread().sleep(1000);
};

/**
 * tearDown after each test
 */
exports.tearDown = function() {
    server.stop();
    server.destroy();
    server = null;
};

/**
 * test that callbacks get called at all; all other
 * tests rely on that.
 */
exports.testCallbacksGetCalled = function() {
   getResponse = function(req) {
      return new Response('');
   };

   var successCalled, completeCalled, errorCalled;
   var exchange = request({
      url: baseUri,
      success: function() {
         successCalled = true;
      },
      complete: function() {
         completeCalled = true;
      },
      error: function() {
         errorCalled = true;
      }
   });
   assert.isTrue(successCalled);
   assert.isTrue(completeCalled);
   assert.isUndefined(errorCalled);
};

/**
 * test basic get
 */
exports.testBasic = function() {
   getResponse = function(req) {
      return new Response('
This is the Response Text
');
   };

   var errorCalled, myData;
   var exchange = request({
      url: baseUri,
      success: function(data, status, contentType, exchange) {
         myData = data;
      },
      error: function() {
         errorCalled = true;
      }
   });
   assert.isUndefined(errorCalled);
   assert.strictEqual(myData, '
This is the Response Text
');
};

/**
 * test servlet on request env (this is not httpclient specific, but uses same setUp tearDown)
 */
exports.testServlet = function() {

    var servlet;
    getResponse = function(req) {
        servlet = req.env.servlet;
        return new Response("servlet set");
    };

    var errorCalled, myData;
    var exchange = request({
        url: baseUri,
        success: function(data, status, contentType, exchange) {
            myData = data;
        },
        error: function() {
            errorCalled = true;
        }
    });
    assert.isUndefined(errorCalled);
    assert.strictEqual(myData, "servlet set");
    assert.ok(servlet instanceof javax.servlet.http.HttpServlet, "servlet instance");
};

/**
 * convinience wrappers
 */
exports.testConvenience = function() {
    getResponse = function(req) {
        if (req.params.foo) {
            return new Response (req.method + ' with param');
        }
        return new Response(req.method);
    };
    var x = post(baseUri);
    assert.strictEqual(200, x.status);
    assert.strictEqual('POST', x.content);

    x = post(baseUri, {foo: 'bar'});
    assert.strictEqual(200, x.status);
    assert.strictEqual('POST with param', x.content);

    x = get(baseUri, {foo: 'bar'});
    assert.strictEqual(200, x.status);
    assert.strictEqual('GET with param', x.content);

    x = del(baseUri);
    assert.strictEqual(200, x.status);
    assert.strictEqual('DELETE', x.content);

    x = put(baseUri);
    assert.strictEqual(200, x.status);
    assert.strictEqual('PUT', x.content);
};

/**
 * GET, POST params
 */
exports.testParams = function() {
    getResponse = function(req) {
        return new Response(JSON.stringify(req.params));
    };
    var data = {
        a: "fääßß",
        b: "fööööbääzz",
        c: "08083",
        d: "0x0004"
    };
    var getExchange = request({
        url: baseUri,
        method: 'GET',
        data: data
    });
    assert.strictEqual(200, getExchange.status);
    var receivedData = JSON.parse(getExchange.content);
    assert.deepEqual(data, receivedData);

    var postExchange = request({
        url: baseUri,
        method: 'POST',
        data: data
    });
    assert.strictEqual(200, postExchange.status);
    receivedData = JSON.parse(postExchange.content);
    assert.deepEqual(data, receivedData);
};

/**
 * Callbacks
 */
exports.testCallbacks = function() {
    getResponse = function(req) {
        if (req.pathInfo == '/notfound') {
            return Response.notFound('error');
        } else if (req.pathInfo == '/success') {
            var res = new Response('success');
            res.contentType = 'text/json';
            return res;
        } else if (req.pathInfo == '/redirect') {
            return {
                status: 302,
                headers: {Location: '/redirectlocation'},
                body: ["Found: " + '/redirectlocation']
            };
        } else if (req.pathInfo == '/redirectlocation') {
            return new Response('redirect success');
        }
    };
    var myStatus, successCalled, errorCalled, myMessage, myContentType, myData;
    // success shouldn't get called
    var getErrorExchange = request({
        url: baseUri + 'notfound',
        method: 'GET',
        complete: function(data, status, contentType, exchange) {
            myStatus = status;
        },
        success: function() {
            successCalled = true
        },
        error: function(message, status, exchange) {
            myMessage = message;
        }
    });
    assert.isUndefined(successCalled);
    assert.strictEqual(myStatus, 404);
    assert.strictEqual(getErrorExchange.status, 404);
    assert.strictEqual(myMessage, "Not Found");

    var getSuccessExchange = request({
        url: baseUri + 'success',
        method: 'GET',
        complete: function(data, status, contentType, exchange) {
            myStatus = status;
        },
        success: function(data, status, contentType, exchange) {
            myContentType = contentType;
        },
        error: function() {
            errorCalled = true;
        }
    });
    assert.strictEqual('text/json; charset=utf-8', myContentType);
    assert.strictEqual(200, myStatus);
    assert.isUndefined(errorCalled);

    var getRedirectExchange = request({
        url: baseUri + 'redirect',
        method: 'GET',
        complete: function(data, status, contentType, exchange) {
            myStatus = status;
            myData = data;
        },
        error: function(message) {
            errorCalled = true;
        }
    });
    assert.strictEqual(200, myStatus);
    assert.strictEqual('redirect success', myData);
    assert.isUndefined(errorCalled);
};

/**
 * Cookie set and read
 */
exports.testCookie = function() {
    var COOKIE_NAME = 'testcookie'
    var COOKIE_VALUE = 'cookie value with s p   a c es';

    getResponse = function(req) {
        // set cookie
        var res = new Response('cookie set');
        res.setCookie(COOKIE_NAME, req.params.cookievalue, 5);
        return res;
    };

    // receive cookie
    var myStatus, myExchange, errorCalled;
    request({
        url: baseUri,
        method: 'GET',
        data: {'cookievalue': COOKIE_VALUE},
        complete: function(data, status, contentType, exchange) {
            myStatus = status;
        },
        success: function(data, status, contentType, exchange) {
            myExchange = exchange;
        },
        error: function() {
            errorCalled = true;
        }
    });
    assert.isUndefined(errorCalled);
    assert.strictEqual(200, myStatus);
    assert.strictEqual(COOKIE_VALUE, myExchange.cookies[COOKIE_NAME].value);
};

/**
 * send stream and get the same stream back
 */
exports.testStreamRequest = function() {

    getResponse = function(req, env) {
        if (req.isPost) {
            var input;
            return {
                    status: 200,
                    headers: {
                        'Content-Type': 'image/png'
                    },
                    body: {
                        forEach: function(fn) {
                            var read, bufsize = 8192;
                            var buffer = new ByteArray(bufsize);
                            input = env.input;
                            while ((read = input.readInto(buffer)) > -1) {
                                buffer.length = read;
                                fn(buffer);
                                buffer.length = bufsize;
                            }
                        },
                        close: function() {
                            if (input) {
                                input.close();
                            }
                        }
                    }
                };

        }
    };

    var resource = getResource('./upload_test.png');
    var ByteArray = require('binary').ByteArray;
    var inputStream = resource.getInputStream();
    // small <1k file, just read it all in
    var size = resource.getLength();
    var inputByteArray = new ByteArray(size);
    inputStream.read(inputByteArray, 0, size);
    var sendInputStream = resource.getInputStream();
    var myExchange, myContentType, errorCalled;
    request({
        url: baseUri,
        method: 'POST',
        data: sendInputStream,
        error: function() {
            errorCalled = true;
        },
        complete: function(data, status, contentType, exchange) {
            myExchange = exchange;
            myContentType = contentType;
        }
    });
    assert.isUndefined(errorCalled);
    assert.isNotNull(myExchange);
    assert.strictEqual (inputByteArray.length, myExchange.contentBytes.length);
    assert.deepEqual (inputByteArray.toArray(), myExchange.contentBytes.toArray());
    assert.strictEqual('image/png', myContentType);
};

// start the test runner if we're called directly from command line
if (require.main == module.id) {
    system.exit(require("test").run(exports));
}
<|endoftext|>


<commit_before>/*jslint onevar: false, eqeqeq: false, browser: true*/
/*globals window sinon buster*/
/**
 * @author Christian Johansen (christian@cjohansen.no)
 * @license BSD
 *
 * Copyright (c) 2011-2012 Christian Johansen
 */
"use strict";

buster.testCase("sinon.EventTarget", {
    setUp: function () {
        this.target = sinon.extend({}, sinon.EventTarget);
    },

    "notifies event listener": function () {
        var listener = sinon.spy();
        this.target.addEventListener("dummy", listener);

        var event = new sinon.Event("dummy");
        this.target.dispatchEvent(event);

        assert(listener.calledOnce);
        assert(listener.calledWith(event));
    },

    "notifies event listener with target as this": function () {
        var listener = sinon.spy();
        this.target.addEventListener("dummy", listener);

        var event = new sinon.Event("dummy");
        this.target.dispatchEvent(event);

        assert(listener.calledOn(this.target));
    },

    "notifies all event listeners": function () {
        var listeners = [sinon.spy(), sinon.spy()];
        this.target.addEventListener("dummy", listeners[0]);
        this.target.addEventListener("dummy", listeners[1]);

        var event = new sinon.Event("dummy");
        this.target.dispatchEvent(event);

        assert(listeners[0].calledOnce);
        assert(listeners[0].calledOnce);
    },

    "notifies event listener of type listener": function () {
        var listener = { handleEvent: sinon.spy() };
        this.target.addEventListener("dummy", listener);

        this.target.dispatchEvent(new sinon.Event("dummy"));

        assert(listener.handleEvent.calledOnce);
    },

    "does not notify listeners of other events": function () {
        var listeners = [sinon.spy(), sinon.spy()];
        this.target.addEventListener("dummy", listeners[0]);
        this.target.addEventListener("other", listeners[1]);

        this.target.dispatchEvent(new sinon.Event("dummy"));

        assert.isFalse(listeners[1].called);
    },

    "does not notify unregistered listeners": function () {
        var listener = sinon.spy();
        this.target.addEventListener("dummy", listener);
        this.target.removeEventListener("dummy", listener);

        this.target.dispatchEvent(new sinon.Event("dummy"));

        assert.isFalse(listener.called);
    },

    "notifies existing listeners after removing one": function () {
        var listeners = [sinon.spy(), sinon.spy(), sinon.spy()];
        this.target.addEventListener("dummy", listeners[0]);
        this.target.addEventListener("dummy", listeners[1]);
        this.target.addEventListener("dummy", listeners[2]);
        this.target.removeEventListener("dummy", listeners[1]);

        this.target.dispatchEvent(new sinon.Event("dummy"));

        assert(listeners[0].calledOnce);
        assert(listeners[2].calledOnce);
    },

    "returns false when event.preventDefault is not called": function () {
        this.target.addEventListener("dummy", sinon.spy());

        var event = new sinon.Event("dummy");
        var result = this.target.dispatchEvent(event);

        assert.isFalse(result);
    },

    "returns true when event.preventDefault is called": function () {
        this.target.addEventListener("dummy", function (e) {
            e.preventDefault();
        });

        var result = this.target.dispatchEvent(new sinon.Event("dummy"));

        assert.isTrue(result);
    }
});
<commit_msg>Added tests for new fake events ProgressEvent and CustomEvents in event.js.<commit_after>/*jslint onevar: false, eqeqeq: false, browser: true*/
/*globals window sinon buster*/
/**
 * @author Christian Johansen (christian@cjohansen.no)
 * @license BSD
 *
 * Copyright (c) 2011-2012 Christian Johansen
 */
"use strict";

buster.testCase("sinon.EventTarget", {
    setUp: function () {
        this.target = sinon.extend({}, sinon.EventTarget);
    },

    "notifies event listener": function () {
        var listener = sinon.spy();
        this.target.addEventListener("dummy", listener);

        var event = new sinon.Event("dummy");
        this.target.dispatchEvent(event);

        assert(listener.calledOnce);
        assert(listener.calledWith(event));
    },

    "notifies event listener with target as this": function () {
        var listener = sinon.spy();
        this.target.addEventListener("dummy", listener);

        var event = new sinon.Event("dummy");
        this.target.dispatchEvent(event);

        assert(listener.calledOn(this.target));
    },

    "notifies all event listeners": function () {
        var listeners = [sinon.spy(), sinon.spy()];
        this.target.addEventListener("dummy", listeners[0]);
        this.target.addEventListener("dummy", listeners[1]);

        var event = new sinon.Event("dummy");
        this.target.dispatchEvent(event);

        assert(listeners[0].calledOnce);
        assert(listeners[0].calledOnce);
    },

    "notifies event listener of type listener": function () {
        var listener = { handleEvent: sinon.spy() };
        this.target.addEventListener("dummy", listener);

        this.target.dispatchEvent(new sinon.Event("dummy"));

        assert(listener.handleEvent.calledOnce);
    },

    "does not notify listeners of other events": function () {
        var listeners = [sinon.spy(), sinon.spy()];
        this.target.addEventListener("dummy", listeners[0]);
        this.target.addEventListener("other", listeners[1]);

        this.target.dispatchEvent(new sinon.Event("dummy"));

        assert.isFalse(listeners[1].called);
    },

    "does not notify unregistered listeners": function () {
        var listener = sinon.spy();
        this.target.addEventListener("dummy", listener);
        this.target.removeEventListener("dummy", listener);

        this.target.dispatchEvent(new sinon.Event("dummy"));

        assert.isFalse(listener.called);
    },

    "notifies existing listeners after removing one": function () {
        var listeners = [sinon.spy(), sinon.spy(), sinon.spy()];
        this.target.addEventListener("dummy", listeners[0]);
        this.target.addEventListener("dummy", listeners[1]);
        this.target.addEventListener("dummy", listeners[2]);
        this.target.removeEventListener("dummy", listeners[1]);

        this.target.dispatchEvent(new sinon.Event("dummy"));

        assert(listeners[0].calledOnce);
        assert(listeners[2].calledOnce);
    },

    "returns false when event.preventDefault is not called": function () {
        this.target.addEventListener("dummy", sinon.spy());

        var event = new sinon.Event("dummy");
        var result = this.target.dispatchEvent(event);

        assert.isFalse(result);
    },

    "returns true when event.preventDefault is called": function () {
        this.target.addEventListener("dummy", function (e) {
            e.preventDefault();
        });

        var result = this.target.dispatchEvent(new sinon.Event("dummy"));

        assert.isTrue(result);
    },

    "notifies ProgressEvent listener with progress data ": function () {
      var listener = sinon.spy();
      this.target.addEventListener("dummyProgress", listener);

      var progressEvent = new sinon.ProgressEvent("dummyProgress", {loaded: 50, total: 120});
      this.target.dispatchEvent(progressEvent);

      assert(listener.calledOnce);
      assert(listener.calledWith(progressEvent));
    },

    "notifies CustomEvent listener with custom data": function () {
      var listener = sinon.spy();
      this.target.addEventListener("dummyCustom", listener);

      var customEvent = new sinon.CustomEvent("dummyCustom", {"detail": "hola"});
      this.target.dispatchEvent(customEvent);

      assert(listener.calledOnce);
      assert(listener.calledWith(customEvent));
    }

});
<|endoftext|>


<commit_before>'use strict';

describe('Controller: MainCtrl', function () {

  // load the controller's module
  beforeEach(module('tamadroidApp'));

  var MainCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });
});
<commit_msg>fake test<commit_after>'use strict';

describe('Controller: MainCtrl', function () {

  // load the controller's module
  beforeEach(module('tamadroidApp'));

  var MainCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings).toBe(void 0);
  });
});
<|endoftext|>


<commit_before>define([
  'trait/attachDom',
  'nbd/Model'
], function(attachDom, Model) {
  'use strict';

  describe('trait/attachDom', function() {
    var model;

    beforeEach(function() {
      model = new Model();
      spyOn(model, 'get').and.callThrough();
      spyOn(model, 'set').and.callThrough();
      spyOn(model, 'trigger').and.callThrough();
    });

    afterEach(function() {
      model.destroy();
    });

    describe('attachCheckbox', function() {
      var $context;

      beforeEach(function() {
        $context = affix('div input[type="checkbox"][value="bar"] input[type="checkbox"][value="baz"]');
      });

      it('sets model with piped dom values', function(done) {
        attachDom.attachCheckbox.call(model, 'foo', $context);
        $context.find('input:first').click();

        setTimeout(function() {
          expect(model.set).toHaveBeenCalledWith('foo', 'bar');
          $context.find('input:last').click();

          setTimeout(function() {
            expect(model.set).toHaveBeenCalledWith('foo', 'bar|baz');
            done();
          }, 100);
        }, 100);
      });

      it('changes based on model', function(done) {
        attachDom.attachCheckbox.call(model, 'foo', $context);
        model.trigger('foo', 'baz');
        setTimeout(function() {
          expect($context.find('input:first')[0].checked).toBe(false);
          expect($context.find('input:last')[0].checked).toBe(true);
          done();
        }, 100);
      });
    });

    describe('attachRadio', function() {
      var $context;

      beforeEach(function() {
        $context = affix('div input[type="radio"][name="foo"][value="bar"] input[type="radio"][name="foo"][value="baz"]');
      });

      it('sets model to dom values', function(done) {
        attachDom.attachRadio.call(model, 'foo', $context);
        $context.find('input:first').click();

        setTimeout(function() {
          expect(model.set).toHaveBeenCalledWith('foo', 'bar');
          $context.find('input:last').click();

          setTimeout(function() {
            expect(model.set).toHaveBeenCalledWith('foo', 'baz');
            done();
          }, 100);
        }, 100);
      });

      it('changes based on model', function(done) {
        attachDom.attachRadio.call(model, 'foo', $context);
        model.trigger('foo', 'baz');

        setTimeout(function() {
          expect($context.find('input:first')[0].checked).toBe(false);
          expect($context.find('input:last')[0].checked).toBe(true);
          done();
        }, 100);
      });
    });

    describe('attachSelect', function() {
      var $context;

      beforeEach(function() {
        $context = affix('select option[value="bar"]');
        $context.affix('option[value="baz"]');
      });

      it('sets model with dom values', function(done) {
        attachDom.attachSelect.call(model, 'foo', $context);
        $context.find('option:first').prop('selected', true).change();

        setTimeout(function() {
          expect(model.set).toHaveBeenCalledWith('foo', 'bar');
          $context.find('option:last').prop('selected', true).change();

          setTimeout(function() {
            expect(model.set).toHaveBeenCalledWith('foo', 'baz');
            done();
          }, 100);
        }, 100);
      });

      it('changes based on model', function(done) {
        attachDom.attachSelect.call(model, 'foo', $context);
        model.trigger('foo', 'baz');

        setTimeout(function() {
          expect($context.val()).toBe('baz');
          done();
        }, 100);
      });
    });

    describe('attachText', function() {
      var $context;

      beforeEach(function() {
        $context = affix('input[type="text"]');
      });

      it('sets model with dom values', function(done) {
        attachDom.attachText.call(model, 'foo', $context);
        $context.val('bar').change();

        setTimeout(function() {
          expect(model.set).toHaveBeenCalledWith('foo', 'bar');
          done();
        }, 100);
      });

      it('changes based on model', function(done) {
        attachDom.attachText.call(model, 'foo', $context);
        model.set('foo', 'baz');

        setTimeout(function() {
          expect($context.val()).toBe('baz');
          done();
        }, 100);
      });
    });
  });
});
<commit_msg>attachDom: updated jasmine tests<commit_after>define([
  'trait/attachDom',
  'nbd/Model'
], function(attachDom, Model) {
  'use strict';

  describe('trait/attachDom', function() {
    var model;

    beforeEach(function() {
      model = Model.extend().mixin(attachDom)();
      spyOn(model, 'get').and.callThrough();
      spyOn(model, 'set').and.callThrough();
    });

    afterEach(function() {
      model.destroy();
    });

    describe('attachCheckbox', function() {
      var $context;

      beforeEach(function() {
        $context = affix('div input[type="checkbox"][value="bar"] input[type="checkbox"][value="baz"]');
      });

      it('sets model with piped dom values', function(done) {
        model.attachCheckbox('foo', $context);
        $context.find('input:first').click();

        setTimeout(function() {
          expect(model.set).toHaveBeenCalledWith('foo', 'bar');
          $context.find('input:last').click();

          setTimeout(function() {
            expect(model.set).toHaveBeenCalledWith('foo', 'bar|baz');
            done();
          }, 100);
        }, 100);
      });

      it('changes based on model', function(done) {
        model.attachCheckbox('foo', $context);
        model.trigger('foo', 'baz');
        setTimeout(function() {
          expect($context.find('input:first')[0].checked).toBe(false);
          expect($context.find('input:last')[0].checked).toBe(true);
          done();
        }, 100);
      });
    });

    describe('attachRadio', function() {
      var $context;

      beforeEach(function() {
        $context = affix('div input[type="radio"][name="foo"][value="bar"] input[type="radio"][name="foo"][value="baz"]');
      });

      it('sets model to dom values', function(done) {
        model.attachRadio('foo', $context);
        $context.find('input:first').click();

        setTimeout(function() {
          expect(model.set).toHaveBeenCalledWith('foo', 'bar');
          $context.find('input:last').click();

          setTimeout(function() {
            expect(model.set).toHaveBeenCalledWith('foo', 'baz');
            done();
          }, 100);
        }, 100);
      });

      it('changes based on model', function(done) {
        model.attachRadio('foo', $context);
        model.trigger('foo', 'baz');

        setTimeout(function() {
          expect($context.find('input:first')[0].checked).toBe(false);
          expect($context.find('input:last')[0].checked).toBe(true);
          done();
        }, 100);
      });
    });

    describe('attachSelect', function() {
      var $context;

      beforeEach(function() {
        $context = affix('select option[value="bar"]');
        $context.affix('option[value="baz"]');
      });

      it('sets model with dom values', function(done) {
        model.attachSelect('foo', $context);
        $context.find('option:first').prop('selected', true).change();

        setTimeout(function() {
          expect(model.set).toHaveBeenCalledWith('foo', 'bar');
          $context.find('option:last').prop('selected', true).change();

          setTimeout(function() {
            expect(model.set).toHaveBeenCalledWith('foo', 'baz');
            done();
          }, 100);
        }, 100);
      });

      it('changes based on model', function(done) {
        model.attachSelect('foo', $context);
        model.trigger('foo', 'baz');

        setTimeout(function() {
          expect($context.val()).toBe('baz');
          done();
        }, 100);
      });
    });

    describe('attachText', function() {
      var $context;

      beforeEach(function() {
        $context = affix('input[type="text"]');
      });

      it('sets model with dom values', function(done) {
        model.attachText('foo', $context);
        $context.val('bar').change();

        setTimeout(function() {
          expect(model.set).toHaveBeenCalledWith('foo', 'bar');
          done();
        }, 100);
      });

      it('changes based on model', function(done) {
        model.attachText('foo', $context);
        model.set('foo', 'baz');

        setTimeout(function() {
          expect($context.val()).toBe('baz');
          done();
        }, 100);
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var grunt = require('grunt');
var path = require('path');
var fs = require('fs');
var http = require('http');
var helper = require('./helper');

var fixtures = helper.fixtures;

function cleanUp() {
  helper.cleanUp([
    'livereload/node_modules',
  ]);
}

// Helper for requesting the live reload server
function request(port, done) {
  var data = '';
  var req = http.request({
    hostname: 'localhost',
    port: port,
  }, function(res) {
    res.setEncoding('utf8');
    res.on('data', function(chunk) {
      data += chunk;
    });
    res.on('end', function() {
      done(data);
    });
  });
  req.end();
}

exports.livereload = {
  setUp: function(done) {
    cleanUp();
    fs.symlinkSync(path.join(__dirname, '../../node_modules'), path.join(fixtures, 'livereload', 'node_modules'));
    done();
  },
  tearDown: function(done) {
    cleanUp();
    done();
  },
  basic: function(test) {
    test.expect(4);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:basic', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(35729, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('I ran before livereload.') !== -1, 'task should have ran before live reload.');
      test.ok(result.indexOf('Live reload server started on port: 35729') !== -1, 'live reload server should have been started on port 35729.');
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  customport: function(test) {
    test.expect(4);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:customport', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(8675, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('I ran before livereload.') !== -1, 'task should have ran before live reload.');
      test.ok(result.indexOf('Live reload server started on port: 8675') !== -1, 'live reload server should have been started on port 35729.');
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  differentfiles: function(test) {
    test.expect(3);
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:differentfiles', '-v'], {cwd: cwd});
    assertWatch([function() {
      grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      setTimeout(function () {
        grunt.file.write(path.join(cwd, 'lib', 'two.js'), 'var two = true;');
      }, 500);
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      test.ok(result.indexOf('Live reloading lib/two.js...') !== -1, 'live reload should have triggered on lib/two.js');
      test.ok(! /Live reloading (lib\/one\.js, lib\/two.js|lib\/two.js, lib\/one.js)\.\.\./.test(result), 'live reload should have cleared js file that was already reloaded');
      test.done();
    });
  },
  multiplefiles: function(test) {
    test.expect(4);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:multiplefiles', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(9876, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
        grunt.file.write(path.join(cwd, 'lib', 'two.js'), 'var two = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('I ran before livereload.') !== -1, 'task should have ran before live reload.');
      test.ok(result.indexOf('Live reload server started on port: 9876') !== -1, 'live reload server should have been started on port 9876.');
      test.ok(/Live reloading (lib\/one\.js, lib\/two.js|lib\/two.js, lib\/one.js)\.\.\./.test(result), 'live reload should have triggered on lib/one.js and lib/two.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  nospawn: function(test) {
    test.expect(4);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:nospawn', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(1337, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('I ran before livereload.') !== -1, 'task should have ran before live reload.');
      test.ok(result.indexOf('Live reload server started on port: 1337') !== -1, 'live reload server should have been started on port 1337.');
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  notasks: function(test) {
    test.expect(3);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:notasks', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(35729, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('Live reload server started on port: 35729') !== -1, 'live reload server should have been started on port 35729.');
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  onlytriggeron: function(test) {
    test.expect(2);
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(35729, function(data) {
        grunt.file.write(path.join(cwd, 'sass', 'one.scss'), '#one {}');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('Live reloading sass/one.scss') === -1, 'Should not trigger live reload on non livereload targets.');
      test.ok(result.indexOf('Live reloading css/one.css') !== -1, 'Should trigger live reload when other tasks trigger livereload targets.');
      test.done();
    });
  },
};
<commit_msg>nitpicky clean up<commit_after>'use strict';

var grunt = require('grunt');
var path = require('path');
var fs = require('fs');
var http = require('http');
var helper = require('./helper');

var fixtures = helper.fixtures;

function cleanUp() {
  helper.cleanUp([
    'livereload/node_modules',
  ]);
}

// Helper for requesting the live reload server
function request(port, done) {
  var data = '';
  var req = http.request({
    hostname: 'localhost',
    port: port,
  }, function(res) {
    res.setEncoding('utf8');
    res.on('data', function(chunk) {
      data += chunk;
    });
    res.on('end', function() {
      done(data);
    });
  });
  req.end();
}

exports.livereload = {
  setUp: function(done) {
    cleanUp();
    fs.symlinkSync(path.join(__dirname, '../../node_modules'), path.join(fixtures, 'livereload', 'node_modules'));
    done();
  },
  tearDown: function(done) {
    cleanUp();
    done();
  },
  basic: function(test) {
    test.expect(4);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:basic', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(35729, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('I ran before livereload.') !== -1, 'task should have ran before live reload.');
      test.ok(result.indexOf('Live reload server started on port: 35729') !== -1, 'live reload server should have been started on port 35729.');
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  customport: function(test) {
    test.expect(4);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:customport', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(8675, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('I ran before livereload.') !== -1, 'task should have ran before live reload.');
      test.ok(result.indexOf('Live reload server started on port: 8675') !== -1, 'live reload server should have been started on port 35729.');
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  differentfiles: function(test) {
    test.expect(3);
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:differentfiles', '-v'], {cwd: cwd});
    assertWatch([function() {
      grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      setTimeout(function () {
        grunt.file.write(path.join(cwd, 'lib', 'two.js'), 'var two = true;');
      }, 500);
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      test.ok(result.indexOf('Live reloading lib/two.js...') !== -1, 'live reload should have triggered on lib/two.js');
      test.ok(!/Live reloading (lib\/one\.js, lib\/two.js|lib\/two.js, lib\/one.js)\.\.\./.test(result), 'live reload should have cleared js file that was already reloaded');
      test.done();
    });
  },
  multiplefiles: function(test) {
    test.expect(4);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:multiplefiles', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(9876, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
        grunt.file.write(path.join(cwd, 'lib', 'two.js'), 'var two = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('I ran before livereload.') !== -1, 'task should have ran before live reload.');
      test.ok(result.indexOf('Live reload server started on port: 9876') !== -1, 'live reload server should have been started on port 9876.');
      test.ok(/Live reloading (lib\/one\.js, lib\/two.js|lib\/two.js, lib\/one.js)\.\.\./.test(result), 'live reload should have triggered on lib/one.js and lib/two.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  nospawn: function(test) {
    test.expect(4);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:nospawn', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(1337, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('I ran before livereload.') !== -1, 'task should have ran before live reload.');
      test.ok(result.indexOf('Live reload server started on port: 1337') !== -1, 'live reload server should have been started on port 1337.');
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  notasks: function(test) {
    test.expect(3);
    var resultData = '';
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch:notasks', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(35729, function(data) {
        resultData += data;
        grunt.file.write(path.join(cwd, 'lib', 'one.js'), 'var one = true;');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('Live reload server started on port: 35729') !== -1, 'live reload server should have been started on port 35729.');
      test.ok(result.indexOf('Live reloading lib/one.js...') !== -1, 'live reload should have triggered on lib/one.js');
      resultData = JSON.parse(resultData);
      test.equal(resultData.tinylr, 'Welcome', 'tinylr server should have welcomed you.');
      test.done();
    });
  },
  onlytriggeron: function(test) {
    test.expect(2);
    var cwd = path.resolve(fixtures, 'livereload');
    var assertWatch = helper.assertTask(['watch', '-v'], {cwd: cwd});
    assertWatch([function() {
      request(35729, function(data) {
        grunt.file.write(path.join(cwd, 'sass', 'one.scss'), '#one {}');
      });
    }], function(result) {
      result = helper.unixify(result);
      helper.verboseLog(result);
      test.ok(result.indexOf('Live reloading sass/one.scss') === -1, 'Should not trigger live reload on non livereload targets.');
      test.ok(result.indexOf('Live reloading css/one.css') !== -1, 'Should trigger live reload when other tasks trigger livereload targets.');
      test.done();
    });
  },
};
<|endoftext|>