<commit_before>describe("Easey", function() {
    function Receiver() { }
    Receiver.prototype.receive = function() { };

    var map, sink;

    beforeEach(function() {
        sink = new Receiver();
        var map_div = document.createElement('div');
        map = new MM.Map(map_div, new MM.TemplatedLayer('http://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png'));
    });

    it('assigns the map var correctly', function() {
        var ease = easey();
        ease.map(map);
        expect(ease.map()).toEqual(map);
    });

    it('automatically sets to and from', function() {
        var ease = easey();
        ease.map(map);
        expect(ease.from()).toEqual(map.coordinate);
        expect(ease.to()).toEqual(map.coordinate);
    });

    it('zooms the to coordinate with zoom()', function() {
        var ease = easey();
        ease.map(map);
        ease.zoom(10);
        expect(ease.to().zoom).toEqual(10);
    });

    it('correctly interpolates between two coordinates', function() {
        easey().map(map)
        .from(new MM.Coordinate(0, 10, 0))
        .to(new MM.Coordinate(0, 0, 0))
        .easing('linear')
        .t(0.5);

        expect(map.coordinate.column).toEqual(5);
        expect(map.coordinate.row).toEqual(0);
        expect(map.coordinate.zoom).toEqual(0);
    });

    it('predicts the future correctly', function() {
        var ease = easey();
        ease.map(map).from(new MM.Coordinate(0, 10, 0))
        .to(new MM.Coordinate(0, 0, 0));
        var future = ease.future(10);
        expect(future.length).toEqual(10);
        expect(future[0].column).toEqual(10);
        expect(future[9].column).toEqual(0);
    });

    it('moves the map quickly', function() {
        var ease = easey();
        ease.map(map).from(new MM.Coordinate(0, 10, 0))
        .to(new MM.Coordinate(0, 0, 0));
        runs(function() {
            ease.run(10);
        });
        waits(200);
        runs(function() {
            expect(map.coordinate.column).toEqual(0);
            expect(map.coordinate.row).toEqual(0);
            expect(map.coordinate.zoom).toEqual(0);
        });
    });

    it('calls a callback after finishing an ease', function() {
        var ease = easey();
        ease.map(map).from(new MM.Coordinate(0, 10, 0))
        .to(new MM.Coordinate(0, 0, 0));
        spyOn(sink, 'receive');
        runs(function() {
            ease.run(10, sink.receive);
        });
        waits(200);
        runs(function() {
            expect(sink.receive).toHaveBeenCalledWith(map);
        });
    });

    it('ends up at the correct coord after an optimal zoom/pan', function() {
        map.setSize(new MM.Point(10, 10));
        var ease = easey();
        ease.map(map).from(new MM.Coordinate(2, 2, 2))
        .to(new MM.Coordinate(1, 1, 1));
        runs(function() {
            ease.optimal(20);
        });
        waits(200);
        runs(function() {
            expect(map.coordinate.column).toEqual(1);
            expect(map.coordinate.row).toEqual(1);
            expect(map.coordinate.zoom).toEqual(1);
        });
    });
});
<commit_msg>Revert test to aibram's code<commit_after>describe("Easey", function() {
    function Receiver() { }
    Receiver.prototype.receive = function() { };

    var map, sink;

    beforeEach(function() {
        sink = new Receiver();
        var map_div = document.createElement('div');
        map = new MM.Map(map_div, new MM.TemplatedLayer('http://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png'));
    });

    it('assigns the map var correctly', function() {
        var ease = easey();
        ease.map(map);
        expect(ease.map()).toEqual(map);
    });

    it('automatically sets to', function() {
        var ease = easey();
        ease.map(map);
        expect(ease.to()).toEqual(map.coordinate);
    });

    it('zooms the to coordinate with zoom()', function() {
        var ease = easey();
        ease.map(map);
        ease.zoom(10);
        expect(ease.to().zoom).toEqual(10);
    });

    it('correctly interpolates between two coordinates', function() {
        easey().map(map)
        .from(new MM.Coordinate(0, 10, 0))
        .to(new MM.Coordinate(0, 0, 0))
        .easing('linear')
        .t(0.5);

        expect(map.coordinate.column).toEqual(5);
        expect(map.coordinate.row).toEqual(0);
        expect(map.coordinate.zoom).toEqual(0);
    });

    it('predicts the future correctly', function() {
        var ease = easey();
        ease.map(map).from(new MM.Coordinate(0, 10, 0))
        .to(new MM.Coordinate(0, 0, 0));
        var future = ease.future(10);
        expect(future.length).toEqual(10);
        expect(future[0].column).toEqual(10);
        expect(future[9].column).toEqual(0);
    });

    it('moves the map quickly', function() {
        var ease = easey();
        ease.map(map).from(new MM.Coordinate(0, 10, 0))
        .to(new MM.Coordinate(0, 0, 0));
        runs(function() {
            ease.run(10);
        });
        waits(200);
        runs(function() {
            expect(map.coordinate.column).toEqual(0);
            expect(map.coordinate.row).toEqual(0);
            expect(map.coordinate.zoom).toEqual(0);
        });
    });

    it('calls a callback after finishing an ease', function() {
        var ease = easey();
        ease.map(map).from(new MM.Coordinate(0, 10, 0))
        .to(new MM.Coordinate(0, 0, 0));
        spyOn(sink, 'receive');
        runs(function() {
            ease.run(10, sink.receive);
        });
        waits(200);
        runs(function() {
            expect(sink.receive).toHaveBeenCalledWith(map);
        });
    });

    it('ends up at the correct coord after an optimal zoom/pan', function() {
        map.setSize(new MM.Point(10, 10));
        var ease = easey();
        ease.map(map).from(new MM.Coordinate(2, 2, 2))
        .to(new MM.Coordinate(1, 1, 1));
        runs(function() {
            ease.optimal(20);
        });
        waits(200);
        runs(function() {
            expect(map.coordinate.column).toEqual(1);
            expect(map.coordinate.row).toEqual(1);
            expect(map.coordinate.zoom).toEqual(1);
        });
    });

    it('resets from after a run', function() {
        var ease = easey();
        ease.map(map).from(new MM.Coordinate(0, 10, 0))
        .to(new MM.Coordinate(0, 0, 0)).run(1);
        waits(50);
        runs(function() {
            expect(ease.from()).toEqual(undefined);
        });
    });
});
<|endoftext|>


<commit_before>/*eslint quotes: ["off"]*/

import { expect } from "chai";
import Bundler from "../../src/index";
import jsPlugin from "bit-loader-js";
import splitBundle from "bit-bundler-splitter";

describe("Bundler test suite", function() {
  var act, bundler, config;

  beforeEach(function() {
    act = () => bundler = new Bundler(config);
  });

  describe("When creating a bundler with no configuration", function() {
    beforeEach(function() {
      config = null;
      act();
    });

    it("then the bundler is an instance of Bundler", function() {
      expect(bundler).to.be.an.instanceof(Bundler);
    });

    describe("and bundling a modules with a couple dependencies", function() {
      var result;

      beforeEach(function() {
        return bundler.bundle("test/sample/X.js").then(function(ctx) {
          result = ctx;
        });
      });

      it("then result does not contain the dependencies", function() {
        expect(trimResult(result.bundle.result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){/*eslint no-console: ["off"]*/var Y = require("./Y");function X() {  console.log("Say X");  this._y = new Y();}module.exports = new X();},{}]},{},[1])`);
      });
    });
  });

  describe("When creating a bundler with the JS plugin", function() {
    beforeEach(function() {
      config = {
        loader: {
          plugins: jsPlugin()
        }
      };
      act();
    });

    it("then the bundler is an instance of Bundler", function() {
      expect(bundler).to.be.an.instanceof(Bundler);
    });

    describe("and bundling a module with a couple of dependencies", function() {
      var result;

      beforeEach(function() {
        return bundler.bundle("test/sample/X.js").then(function(ctx) {
          result = ctx;
        });
      });

      it("then result contains the dependencies", function() {
        expect(trimResult(result.bundle.result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){/*eslint no-console: ["off"]*/var Y = require("./Y");function X() {  console.log("Say X");  this._y = new Y();}module.exports = new X();},{"./Y":2}],2:[function(require,module,exports){/*eslint no-console: ["off"]*/var z = require("./z");function Y() {  console.log("Say Y");  z.potatoes();}module.exports = Y;},{"./z":3}],3:[function(require,module,exports){/*eslint no-console: ["off"]*/module.exports = {  roast: "this",  potatoes: function() {    console.log("Say potatoes");  }};},{}]},{},[1])`);
      });
    });
  });

  describe("When creating a bundler with the JS plugin and spitting bundles", function() {
    beforeEach(function() {
      config = {
        loader: {
          plugins: jsPlugin()
        },
        bundler: {
          plugins: [
            splitBundle("dest/Y.js", { match: { fileName: "Y.js" }}),
            splitBundle("dest/Z.js", { match: { fileName: "z.js" } })
          ]
        }
      };
      act();
    });

    it("then the bundler is an instance of Bundler", function() {
      expect(bundler).to.be.an.instanceof(Bundler);
    });

    describe("and bundling a module with a couple of dependencies", function() {
      var result;

      beforeEach(function() {
        return bundler.bundle("test/sample/X.js").then(function(ctx) {
          result = ctx;
        });
      });

      it("then the result has one root module", function() {
        expect(result.modules).to.have.lengthOf(1);
      });

      it("then the result root module is X.js", function() {
        expect(result.modules[0].fileName).to.be.equal("X.js");
      });

      it("then result contains the dependencies", function() {
        expect(trimResult(result.bundle.result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){/*eslint no-console: ["off"]*/var Y = require("./Y");function X() {  console.log("Say X");  this._y = new Y();}module.exports = new X();},{"./Y":2}]},{},[1])`);
      });

      it("then splitter created a part for 'dest/Y.js'", function() {
        expect(result.parts).to.have.property("dest/Y.js");
      });

      it("then splitter created a part for 'dest/Y.js' with the correct bundle result", function() {
        expect(trimResult(result.parts["dest/Y.js"].result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module \'"+o+"\'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({2:[function(require,module,exports){/*eslint no-console: ["off"]*/var z = require("./z");function Y() {  console.log("Say Y");  z.potatoes();}module.exports = Y;},{"./z":3}],3:[function(require,module,exports){/*eslint no-console: ["off"]*/module.exports = {  roast: "this",  potatoes: function() {    console.log("Say potatoes");  }};},{}]},{},[2])`);
      });

      it("then splitter created a part for 'dest/Z.js'", function() {
        expect(result.parts).to.have.property("dest/Z.js");
      });

      it("then splitter created a part for 'dest/Z.js' with the correct bundle result", function() {
        expect(trimResult(result.parts["dest/Z.js"].result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({3:[function(require,module,exports){/*eslint no-console: ["off"]*/module.exports = {  roast: "this",  potatoes: function() {    console.log("Say potatoes");  }};},{}]},{},[3])`);
      });
    });
  });
});

function trimResult(data) {
  return data
    .replace(/\n/g, "")
    .replace(/\/\/# sourceMappingURL=.*/, "");
}
<commit_msg>Changed where test data is written to<commit_after>/*eslint quotes: ["off"]*/

import { expect } from "chai";
import Bundler from "../../src/index";
import jsPlugin from "bit-loader-js";
import splitBundle from "bit-bundler-splitter";

describe("Bundler test suite", function() {
  var act, bundler, config;

  beforeEach(function() {
    act = () => bundler = new Bundler(config);
  });

  describe("When creating a bundler with no configuration", function() {
    beforeEach(function() {
      config = null;
      act();
    });

    it("then the bundler is an instance of Bundler", function() {
      expect(bundler).to.be.an.instanceof(Bundler);
    });

    describe("and bundling a modules with a couple dependencies", function() {
      var result;

      beforeEach(function() {
        return bundler.bundle("test/sample/X.js").then(function(ctx) {
          result = ctx;
        });
      });

      it("then result does not contain the dependencies", function() {
        expect(trimResult(result.bundle.result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){/*eslint no-console: ["off"]*/var Y = require("./Y");function X() {  console.log("Say X");  this._y = new Y();}module.exports = new X();},{}]},{},[1])`);
      });
    });
  });

  describe("When creating a bundler with the JS plugin", function() {
    beforeEach(function() {
      config = {
        loader: {
          plugins: jsPlugin()
        }
      };
      act();
    });

    it("then the bundler is an instance of Bundler", function() {
      expect(bundler).to.be.an.instanceof(Bundler);
    });

    describe("and bundling a module with a couple of dependencies", function() {
      var result;

      beforeEach(function() {
        return bundler.bundle("test/sample/X.js").then(function(ctx) {
          result = ctx;
        });
      });

      it("then result contains the dependencies", function() {
        expect(trimResult(result.bundle.result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){/*eslint no-console: ["off"]*/var Y = require("./Y");function X() {  console.log("Say X");  this._y = new Y();}module.exports = new X();},{"./Y":2}],2:[function(require,module,exports){/*eslint no-console: ["off"]*/var z = require("./z");function Y() {  console.log("Say Y");  z.potatoes();}module.exports = Y;},{"./z":3}],3:[function(require,module,exports){/*eslint no-console: ["off"]*/module.exports = {  roast: "this",  potatoes: function() {    console.log("Say potatoes");  }};},{}]},{},[1])`);
      });
    });
  });

  describe("When creating a bundler with the JS plugin and spitting bundles", function() {
    beforeEach(function() {
      config = {
        loader: {
          plugins: jsPlugin()
        },
        bundler: {
          plugins: [
            splitBundle("test/dest/Y.js", { match: { fileName: "Y.js" }}),
            splitBundle("test/dest/Z.js", { match: { fileName: "z.js" } })
          ]
        }
      };
      act();
    });

    it("then the bundler is an instance of Bundler", function() {
      expect(bundler).to.be.an.instanceof(Bundler);
    });

    describe("and bundling a module with a couple of dependencies", function() {
      var result;

      beforeEach(function() {
        return bundler.bundle("test/sample/X.js").then(function(ctx) {
          result = ctx;
        });
      });

      it("then the result has one root module", function() {
        expect(result.modules).to.have.lengthOf(1);
      });

      it("then the result root module is X.js", function() {
        expect(result.modules[0].fileName).to.be.equal("X.js");
      });

      it("then result contains the dependencies", function() {
        expect(trimResult(result.bundle.result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){/*eslint no-console: ["off"]*/var Y = require("./Y");function X() {  console.log("Say X");  this._y = new Y();}module.exports = new X();},{"./Y":2}]},{},[1])`);
      });

      it("then splitter created a part for 'test/dest/Y.js'", function() {
        expect(result.parts).to.have.property("test/dest/Y.js");
      });

      it("then splitter created a part for 'test/dest/Y.js' with the correct bundle result", function() {
        expect(trimResult(result.parts["test/dest/Y.js"].result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module \'"+o+"\'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({2:[function(require,module,exports){/*eslint no-console: ["off"]*/var z = require("./z");function Y() {  console.log("Say Y");  z.potatoes();}module.exports = Y;},{"./z":3}],3:[function(require,module,exports){/*eslint no-console: ["off"]*/module.exports = {  roast: "this",  potatoes: function() {    console.log("Say potatoes");  }};},{}]},{},[2])`);
      });

      it("then splitter created a part for 'test/dest/Z.js'", function() {
        expect(result.parts).to.have.property("test/dest/Z.js");
      });

      it("then splitter created a part for 'test/dest/Z.js' with the correct bundle result", function() {
        expect(trimResult(result.parts["test/dest/Z.js"].result)).to.be.equal(`require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({3:[function(require,module,exports){/*eslint no-console: ["off"]*/module.exports = {  roast: "this",  potatoes: function() {    console.log("Say potatoes");  }};},{}]},{},[3])`);
      });
    });
  });
});

function trimResult(data) {
  return data
    .replace(/\n/g, "")
    .replace(/\/\/# sourceMappingURL=.*/, "");
}
<|endoftext|>


<commit_before>/*global jasmine, describe, xdescribe, it, expect, spyOn, beforeEach */
define(['real/View', 'nbd/Class', 'jquery'], function(View, Class, $) {
  'use strict';

  describe('View', function() {

    var instance;

    beforeEach(function() {
      instance = new View();
    });

    it('is a Class constructor', function() {
      expect( View ).toEqual(jasmine.any(Function));
      expect( View.inherits( Class ) ).toBe(true);
    });

    describe('.templateData()', function() {
      it('returns an object', function() {
        expect( instance.templateData() ).toEqual(jasmine.any(Object));
      });
    });

    describe('.render()', function() {
      it('uses templateData when given no data', function() {
        spyOn( instance, 'templateData' );

        instance.render();

        expect( instance.templateData ).toHaveBeenCalled();
      });

      it('uses data when given', function() {
        var data = { rand: Math.random() };

        spyOn( instance, 'template' ).andCallThrough();
        spyOn( instance, 'templateData' );

        instance.render(data);

        expect( instance.templateData ).not.toHaveBeenCalled();
        expect( instance.template ).toHaveBeenCalledWith(data);
      });

      it('calls rendered() if any', function() {
        instance.rendered = function() {
          expect(this).toBe(instance);
        };
        spyOn( instance, 'rendered' ).andCallThrough();
        instance.render();
        expect( instance.rendered ).toHaveBeenCalled();
      });

      it('fires prerender event', function() {
        var prerender = jasmine.createSpy('prerender')
        .andCallFake(function() {
          expect( instance.template ).not.toHaveBeenCalled();
        });
        spyOn( instance, 'template' ).andCallThrough();

        instance.on('prerender', prerender);
        instance.render();

        expect( prerender ).toHaveBeenCalled();
      });

      it('fires postrender event', function() {
        var postrender = jasmine.createSpy('postrender')
        .andCallFake(function() {
          expect( instance.template ).toHaveBeenCalled();
        });
        spyOn( instance, 'template' ).andCallThrough();

        instance.on('postrender', postrender);
        instance.render();

        expect( postrender ).toHaveBeenCalledWith( instance.$view );
      });
    });

    describe('.destroy()', function() {
      it('destroys itself', function() {
        var instance = new View();

        instance.template = function() {
          return $('
').appendTo(document.body);
        };

        instance.render();
        instance.destroy();
        expect( $('#mytest').length ).toBe(0);
        expect( instance.$view ).toBe(null);
      });
    });
  });

  return View;
});
<commit_msg>View tests: test view replacing<commit_after>/*global jasmine, describe, xdescribe, it, expect, spyOn, beforeEach */
define(['real/View', 'nbd/Class', 'jquery'], function(View, Class, $) {
  'use strict';

  describe('View', function() {

    var instance;

    beforeEach(function() {
      instance = new View();
    });

    it('is a Class constructor', function() {
      expect( View ).toEqual(jasmine.any(Function));
      expect( View.inherits( Class ) ).toBe(true);
    });

    describe('.templateData()', function() {
      it('returns an object', function() {
        expect( instance.templateData() ).toEqual(jasmine.any(Object));
      });
    });

    describe('.render()', function() {
      it('uses templateData when given no data', function() {
        spyOn( instance, 'templateData' );

        instance.render();

        expect( instance.templateData ).toHaveBeenCalled();
      });

      it('uses data when given', function() {
        var data = { rand: Math.random() };

        spyOn( instance, 'template' ).andCallThrough();
        spyOn( instance, 'templateData' );

        instance.render(data);

        expect( instance.templateData ).not.toHaveBeenCalled();
        expect( instance.template ).toHaveBeenCalledWith(data);
      });

      it('replaces view if existing', function() {
        var replace = jasmine.createSpy('replaceWith');
        spyOn( instance, 'template' ).andCallFake(function() {
          return { length:1, replaceWith : replace, "1":null };
        });

        instance.render();
        expect(replace).not.toHaveBeenCalled();
        expect(instance.template).toHaveBeenCalled();

        instance.render();
        expect(replace).toHaveBeenCalled();
      });

      it('calls rendered() if any', function() {
        instance.rendered = function() {
          expect(this).toBe(instance);
        };
        spyOn( instance, 'rendered' ).andCallThrough();
        instance.render();
        expect( instance.rendered ).toHaveBeenCalled();
      });

      it('fires prerender event', function() {
        var prerender = jasmine.createSpy('prerender')
        .andCallFake(function() {
          expect( instance.template ).not.toHaveBeenCalled();
        });
        spyOn( instance, 'template' ).andCallThrough();

        instance.on('prerender', prerender);
        instance.render();

        expect( prerender ).toHaveBeenCalled();
      });

      it('fires postrender event', function() {
        var postrender = jasmine.createSpy('postrender')
        .andCallFake(function() {
          expect( instance.template ).toHaveBeenCalled();
        });
        spyOn( instance, 'template' ).andCallThrough();

        instance.on('postrender', postrender);
        instance.render();

        expect( postrender ).toHaveBeenCalledWith( instance.$view );
      });
    });

    describe('.destroy()', function() {
      it('destroys itself', function() {
        var instance = new View();

        instance.template = function() {
          return $('
').appendTo(document.body);
        };

        instance.render();
        instance.destroy();
        expect( $('#mytest').length ).toBe(0);
        expect( instance.$view ).toBe(null);
      });
    });
  });

  return View;
});
<|endoftext|>


<commit_before>// Definition of browsers to test remotely

module.exports = function remote (rev) {
    return [{
        browserName: 'safari',
        version: '6.0',
        platform: 'OS X 10.8',
        build: rev,
        name: 'Safari Mountain Lion ' + rev
    },{
        browserName: 'safari',
        version: '7.0',
        platform: 'OS X 10.9',
        build: rev,
        name: 'Safari Mavericks ' + rev
    },{
        browserName: 'safari',
        version: '8.0',
        platform: 'OS X 10.10',
        build: rev,
        name: 'Safari Yosemite ' + rev
    },{
        browserName: 'safari',
        version: '9.0',
        platform: 'OS X 10.11',
        build: rev,
        name: 'Safari El Capitan ' + rev
    },{
        browserName: 'chrome',
        version: '46.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Chrome Windows 10 46.0 ' + rev
    },{
        browserName: 'chrome',
        version: '45.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Chrome Windows 10 45.0 ' + rev
    },{
        browserName: 'chrome',
        version: '44.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Chrome Windows 10 44.0 ' + rev
    },{
        browserName: 'chrome',
        version: '43.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Chrome Windows 10 43.0 ' + rev
    },{
        browserName: 'firefox',
        version: '41.0',
        platform: 'Linux',
        build: rev,
        name: 'Firefox Linux 41.0 ' + rev
    },{
        browserName: 'firefox',
        version: '40.0',
        platform: 'Linux',
        build: rev,
        name: 'Firefox Linux 40.0 ' + rev
    },{
        browserName: 'firefox',
        version: '39.0',
        platform: 'Linux',
        build: rev,
        name: 'Firefox Linux 39.0 ' + rev
    },{
        browserName: 'firefox',
        version: '38.0',
        platform: 'Linux',
        build: rev,
        name: 'Firefox Linux 38.0 ' + rev
    },{
        browserName: 'internet explorer',
        version: '9.0',
        platform: 'Windows 7',
        build: rev,
        name: 'Internet Explorer 9.0 ' + rev,
    },{
        browserName: 'opera',
        version: '12.15',
        platform: 'Linux',
        build: rev,
        name: 'Opera 12.15 ' + rev,
    },{
        browserName: 'internet explorer',
        version: '10.0',
        platform: 'Windows 8',
        build: rev,
        name: 'Internet Explorer 10.0 ' + rev
    },{
        browserName: 'internet explorer',
        version: '11.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Internet Explorer 11.0 ' + rev
    },{
        browserName: 'iphone',
        platform: 'OS X 10.10',
        version: '9.1',
        deviceName: 'iPhone Simulator',
        deviceOrientation: 'portrait',
        build: rev,
        name: 'iOS 9.1 ' + rev
/*  },{
        browserName: 'android',
        platform: 'Linux',
        version: '5.1',
        deviceName: 'Android Emulator',
        deviceOrientation: 'portrait',
        build: rev,
        name: 'Android 5.1 ' + rev
    },{
        browserName: 'microsoftedge',
        version: '20.10240',
        platform: 'Windows 10',
        build: rev,
        name: 'MS Edge 20.10240 ' + rev
*/  }];
};
<commit_msg>Test iOS 8.4. Don't test Android for the moment.<commit_after>// Definition of browsers to test remotely

module.exports = function remote (rev) {
    return [{
        browserName: 'safari',
        version: '6.0',
        platform: 'OS X 10.8',
        build: rev,
        name: 'Safari Mountain Lion ' + rev
    },{
        browserName: 'safari',
        version: '7.0',
        platform: 'OS X 10.9',
        build: rev,
        name: 'Safari Mavericks ' + rev
    },{
        browserName: 'safari',
        version: '8.0',
        platform: 'OS X 10.10',
        build: rev,
        name: 'Safari Yosemite ' + rev
    },{
        browserName: 'safari',
        version: '9.0',
        platform: 'OS X 10.11',
        build: rev,
        name: 'Safari El Capitan ' + rev
    },{
        browserName: 'chrome',
        version: '46.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Chrome Windows 10 46.0 ' + rev
    },{
        browserName: 'chrome',
        version: '45.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Chrome Windows 10 45.0 ' + rev
    },{
        browserName: 'chrome',
        version: '44.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Chrome Windows 10 44.0 ' + rev
    },{
        browserName: 'chrome',
        version: '43.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Chrome Windows 10 43.0 ' + rev
    },{
        browserName: 'firefox',
        version: '41.0',
        platform: 'Linux',
        build: rev,
        name: 'Firefox Linux 41.0 ' + rev
    },{
        browserName: 'firefox',
        version: '40.0',
        platform: 'Linux',
        build: rev,
        name: 'Firefox Linux 40.0 ' + rev
    },{
        browserName: 'firefox',
        version: '39.0',
        platform: 'Linux',
        build: rev,
        name: 'Firefox Linux 39.0 ' + rev
    },{
        browserName: 'firefox',
        version: '38.0',
        platform: 'Linux',
        build: rev,
        name: 'Firefox Linux 38.0 ' + rev
    },{
        browserName: 'internet explorer',
        version: '9.0',
        platform: 'Windows 7',
        build: rev,
        name: 'Internet Explorer 9.0 ' + rev,
    },{
        browserName: 'opera',
        version: '12.15',
        platform: 'Linux',
        build: rev,
        name: 'Opera 12.15 ' + rev,
    },{
        browserName: 'internet explorer',
        version: '10.0',
        platform: 'Windows 8',
        build: rev,
        name: 'Internet Explorer 10.0 ' + rev
    },{
        browserName: 'internet explorer',
        version: '11.0',
        platform: 'Windows 10',
        build: rev,
        name: 'Internet Explorer 11.0 ' + rev
    },{
        browserName: 'iphone',
        platform: 'OS X 10.10',
        version: '9.1',
        deviceName: 'iPhone Simulator',
        deviceOrientation: 'portrait',
        build: rev,
        name: 'iOS 9.1 ' + rev
    },{
        browserName: 'iphone',
        platform: 'OS X 10.10',
        version: '8.4',
        deviceName: 'iPhone Simulator',
        deviceOrientation: 'portrait',
        build: rev,
        name: 'iOS 8.4 ' + rev
/*  },{
        browserName: 'microsoftedge',
        version: '20.10240',
        platform: 'Windows 10',
        build: rev,
        name: 'MS Edge 20.10240 ' + rev
*/  }];
};
<|endoftext|>


<commit_before>var assert = require("assert")
var fs = require('fs');
var HPACK = require('../lib/hpack').HPACK;

function convertForTest(headers) {
    var i, n, entry, converted = {};
    for (i = 0; i < headers.length; i++) {
        if (headers[i] instanceof Array) {
            converted[headers[i][0]] = headers[i][1];
        } else {
            converted[Object.keys(headers[i])[0]] = headers[i][Object.keys(headers[i])[0]];
        }
    }
    return converted;
};

describe('HPACK', function () {
    var nStory = 31;
    var reference = 'nghttp2';
    var testcaseDir = 'test/hpack-test-case/';

    describe('#decode()', function () {
        var i, j, impl, story, decoded, nCase;

        beforeEach(function () {
            impl = new HPACK();
        });

        for (i = 0; i <= nStory; i++) {
            (function () {
                var storyNumber = i;
                it('should decode wire data as same as reference implementation on the story ' + storyNumber, function () {
                    story = JSON.parse(fs.readFileSync(testcaseDir + reference + '/story_' + (parseInt(storyNumber / 10) ? '' : '0') + '' + storyNumber + '.json'));
                    nCase = story.cases.length;
                    for (j = 0; j < nCase; j++) {
                        decoded = impl.decode(new Buffer(story.cases[j].wire, 'hex'));
                        assert.deepEqual(convertForTest(decoded), convertForTest(story.cases[j].headers), 'Story ' + storyNumber + ' seq ' + j);
                    }
                });
            })();
        }
    });

    describe('#encode()', function () {
        it('should encode raw-data, and the encoded data shoud be decodable.');
    });
});
<commit_msg>add tests for encode()<commit_after>var assert = require("assert")
var fs = require('fs');
var HPACK = require('../lib/hpack').HPACK;

function convertForInput(headers) {
    var i, n, entry, converted = [];
    for (i = 0; i < headers.length; i++) {
        converted.push([Object.keys(headers[i])[0], headers[i][Object.keys(headers[i])[0]]]);
    }
    return converted;
};

function convertForCompare(headers) {
    var i, n, entry, converted = {};
    for (i = 0; i < headers.length; i++) {
        if (headers[i] instanceof Array) {
            converted[headers[i][0]] = headers[i][1];
        } else {
            converted[Object.keys(headers[i])[0]] = headers[i][Object.keys(headers[i])[0]];
        }
    }
    return converted;
};

describe('HPACK', function () {
    var nStory = 31;
    var reference = 'nghttp2';
    var testcaseDir = 'test/hpack-test-case/';

    describe('#decode()', function () {
        var i, j, impl, story, decoded, nCase;

        beforeEach(function () {
            impl = new HPACK();
        });

        for (i = 0; i <= nStory; i++) {
            (function () {
                var storyNumber = i;
                it('should decode wire data as same as reference implementation on the story ' + storyNumber, function () {
                    story = JSON.parse(fs.readFileSync(testcaseDir + reference + '/story_' + (parseInt(storyNumber / 10) ? '' : '0') + '' + storyNumber + '.json'));
                    nCase = story.cases.length;
                    for (j = 0; j < nCase; j++) {
                        decoded = impl.decode(new Buffer(story.cases[j].wire, 'hex'));
                        assert.deepEqual(convertForCompare(decoded), convertForCompare(story.cases[j].headers), 'Story ' + storyNumber + ' seq ' + j);
                    }
                });
            })();
        }
    });

    describe('#encode()', function () {
        var i, j, impl, story, decoded, nCase, wire;

        beforeEach(function () {
            impl = new HPACK();
        });

        for (i = 0; i <= nStory; i++) {
            (function () {
                var storyNumber = i;
                it('should encode raw-data, and the encoded data shoud be decodable, on the story ' + storyNumber, function () {
                    story = JSON.parse(fs.readFileSync(testcaseDir + 'raw-data/story_' + (parseInt(storyNumber / 10) ? '' : '0') + '' + storyNumber + '.json'));
                    nCase = story.cases.length;
                    for (j = 0; j < nCase; j++) {
                        wire = impl.encode(convertForInput(story.cases[j].headers));
                        decoded = impl.decode(wire);
                        assert.deepEqual(convertForCompare(decoded), convertForCompare(story.cases[j].headers), 'Story ' + storyNumber + ' seq ' + j);
                    }
                });
            })();
        }
    });
});
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var nodemock = require('nodemock');
var net = require('net');
var msgpack = require('msgpack');
var http = require('http');
var Deferred = require('jsdeferred').Deferred;
var client = require('socket.io-client');
var express = require('express');

var socketIoDefaultCommandsModule =
  exports.socketIoDefaultCommandsModule =
    require('../lib/frontend/default-commands/socket.io');
var model = require('../lib/model');
var FluentReceiver = require('../lib/backend/receiver').FluentReceiver;
var Connection = require('../lib/backend/connection').Connection;

var testSendPort = exports.testSendPort = 3333;
var testReceivePort = exports.testReceivePort = 3334;
var testServerPort = exports.testServerPort = 3335;

function connectTo(port) {
  var deferred = new Deferred();
  var clientSocket = new net.Socket();
  clientSocket.on('error', function(error){
    clientSocket.destroy();
    deferred.fail(error);
  });
  clientSocket.connect(port, 'localhost', function(){
    deferred.call(clientSocket);
  });
  return deferred;
}
exports.connectTo = connectTo;
Deferred.register('connectTo', connectTo);

function sendPacketTo(packet, port) {
  var clientSocket;
  return connectTo(port)
    .next(function(newSocket) {
      clientSocket = newSocket;
      var packedPacket = msgpack.pack(packet);
      clientSocket.write(new Buffer(packedPacket));
    })
    .wait(0.01)
    .next(function() {
      clientSocket.destroy();
      clientSocket = undefined;
    })
    .error(function(error) {
      if (clientSocket) {
        clientSocket.destroy();
        clientSocket = undefined;
      }
      throw error;
    });
}
exports.sendPacketTo = sendPacketTo;
Deferred.register('sendPacketTo', sendPacketTo);

function setupServer(handlerOrServer) {
  var deferred = new Deferred();
  var server;
  if ('close' in handlerOrServer) { // it is a server
    server = handlerOrServer;
  } else { // it is a handler
    server = http.createServer(handlerOrServer);
  }
  server.listen(testServerPort, function() {
    deferred.call(server);
  });
  return deferred;
}
exports.setupServer = setupServer;

function sendRequest(method, path, postData, headers) {
  var deferred = new Deferred();

  var options = {
        host: 'localhost',
        port: testServerPort,
        path: path,
        method: method,
        headers: {}
      };

  if (headers) {
    for (var header in headers) {
      if (headers.hasOwnProperty(header))
        options.headers[header] = headers[header];
    }
  }

  Deferred.next(function() {
    var request = http.request(options, function(response) {
          var body = '';
          response.on('data', function(data) {
            body += data;
          });
          response.on('end', function() {
            deferred.call({
              statusCode: response.statusCode,
              body: body
            });
          });
        });
    request.on('error', function(error) {
      deferred.fail(error);
    });

    if (postData) request.write(postData);
    request.end();
  });

  return deferred;
}

function get(path, headers) {
  return sendRequest('GET', path, null, headers);
}
exports.get = get;
Deferred.register('get', function() { return get.apply(this, arguments); });

function post(path, body, headers) {
  return sendRequest('POST', path, body, headers);
}
exports.post = post;
Deferred.register('post', function() { return post.apply(this, arguments); });

function createClientSocket() {
  var deferred = new Deferred();
  var host = 'http://localhost:' + testServerPort;
  var options = { 'force new connection': true };
  var socket = client.connect(host, options);
  socket.on('connect', function() {
    deferred.call(socket);
  });
  return deferred;
}
exports.createClientSocket = createClientSocket;
Deferred.register('createClientSocket', createClientSocket);

function createClientSockets(count) {
  var sockets = [];
  return Deferred.next(function loop() {
    if (sockets.length < count) {
      return createClientSocket()
               .next(function(newSocket) {
                 sockets.push(newSocket);
               })
               .next(loop);
    } else {
      return sockets;
    }
  });
}
exports.createClientSockets = createClientSockets;
Deferred.register('createClientSockets', createClientSockets);

function createStubbedBackendConnection() {
  return {
    emitMessage: function(type, message, callback, options) {
      this.emitMessageCalledArguments.push({
        type:     type,
        message:  message,
        callback: callback,
        options:  options
      });
    },
    emitMessageCalledArguments: [],

    emit: function() {},
    on: function() {},
    removeListener: function() {},
    removeAllListeners: function() {},
    close: function() {}
  };
}
exports.createStubbedBackendConnection = createStubbedBackendConnection;

function setupApplication() {
  var application = express();
  var server;
  var backend;
  return setupServer(application)
    .next(function(newServer) {
      server = newServer;
    })
    .createBackend()
    .next(function(newBackend) {
      backend = newBackend;
      var connection = new Connection({
        tag:      'test',
        hostName: 'localhost',
        port:     testSendPort,
        receivePort: testReceivePort,
        maxRetyrCount: 3,
        retryDelay: 1
      });
      return {
        backend:     backend,
        server:      server,
        application: application,
        connection:  connection
      };
    });
}
exports.setupApplication = setupApplication;
Deferred.register('setupApplication', setupApplication);

function teardownApplication(params) {
  params = params || {};
  if (params.backend) {
    params.backend.close();
    params.backend = undefined;
  }
  if (params.connection) {
    params.connection.close();
    params.connection = undefined;
  }
  if (params.server) {
    params.server.close();
    params.server = undefined;
  }
}
exports.teardownApplication = teardownApplication;
Deferred.register('teardownApplication', teardownApplication);

function readyToDestroyMockedConnection(connection, clientCount) {
  connection = connection
    .mock('removeListener')
      .takes('error', function() {});
  if (clientCount)
    connection = connection.times(clientCount);
  return connection;
}
exports.readyToDestroyMockedConnection = readyToDestroyMockedConnection;

function createBackend() {
  var deferred = new Deferred();
  var backend = new FluentReceiver(testSendPort);
  backend.received = [];
  backend.on('receive', function(data) {
    backend.received.push(data);
  });
  backend.listen(function() {
    return deferred.call(backend);
  });
  backend.getMessages = function() {
    return this.received.map(function(packet) {
      return packet[2];
    });
  };
  backend.getEvents = function() {
    return this.getMessages().map(function(envelope) {
      return envelope.type;
    });
  };
  backend.getBodies = function() {
    return this.getMessages().map(function(envelope) {
      return envelope.body;
    });
  };
  backend.assertReceived = function(expectedMessages) {
    assert.deepEqual(this.getMessages().map(function(message) {
                       return { type: message.type,
                                body: message.body };
                     }),
                     expectedMessages);
  };
  backend.sendMessage = function(type, body) {
    var response = createEnvelope(type, body);
    return sendPacketTo(createPacket(response), testReceivePort)
  };
  backend.sendResponse = function(request, type, body) {
    var response = createReplyEnvelope(request, type, body);
    return sendPacketTo(createPacket(response), testReceivePort)
  };
  return deferred;
}
exports.createBackend = createBackend;
Deferred.register('createBackend', createBackend);

function createEnvelope(type, body) {
  var now = new Date();
  var envelope = {
    id:         now.getTime(),
    date:       now.toISOString(),
    replyTo:    'localhost:' + testReceivePort,
    statusCode: 200,
    type:       type,
    body:       body
  };
  return envelope;
}
exports.createEnvelope = createEnvelope;

function createExpectedEnvelope(type, body) {
  var envelope = createEnvelope(type, body);
  envelope.id = TypeOf('string');
  envelope.date = InstanceOf(Date);
  return envelope;
}
exports.createExpectedEnvelope = createExpectedEnvelope;

function createReplyEnvelope(message, type, body) {
  var response = createEnvelope(type, body);
  response.inReplyTo = message.id;
  return response;
}
exports.createReplyEnvelope = createReplyEnvelope;

function createPacket(message, tag) {
  tag = tag || 'test.message';
  return [tag, Date.now(), message];
}
exports.createPacket = createPacket;

function TypeOf(typeString) {
  if (!(this instanceof TypeOf))
    return new TypeOf(typeString);

  this.typeString = typeString;
  if (typeString == 'date') {
    return new InstanceOf(Date);
  }
}
exports.TypeOf = TypeOf;

function InstanceOf(constructor) {
  if (!(this instanceof InstanceOf))
    return new InstanceOf(constructor);

  this.constructorFunction = constructor;
}
exports.InstanceOf = InstanceOf;

function assertEnvelopeEqual(actual, expected) {
  var vs = JSON.stringify(actual) + ' vs ' + JSON.stringify(expected);
  Object.keys(expected).forEach(function(key) {
    var actualValue = actual[key];
    var expectedValue = expected[key];
    if (expectedValue instanceof InstanceOf) {
      if (typeof actualValue == 'string') {
        // Try fo parse the value and create new instance.
        // If this process is failed, it can be an invalid value.
        actualValue = new expectedValue.constructorFunction(actualValue);
      }
      assert.instanceOf(actualValue,
                        expectedValue.constructorFunction,
                        key + ' / ' + vs);
    } else if (expectedValue instanceof TypeOf) {
      assert.typeOf(typeof actualValue,
                    expectedValue.typeString,
                    key + ' / ' + vs);
    } else {
      assert.deepEqual(actualValue, expectedValue, key + ' / ' + vs);
    }
  });
}
assert.envelopeEqual = assertEnvelopeEqual;

function sortKeys(original) {
  if (!original || typeof original != 'object')
    return original;

  if (Array.isArray(original))
    return original.map(sortKeys);

  var sorted = {};
  Object.keys(original).sort().forEach(function(key) {
    sorted[key] = sortKeys(original[key]);
  });
  return sorted;
}

// assert.deepEqual fails when the order of hash keys are different,
// even if they are "eaual" as JSON objects.
function assertEqualJSON(actual, expected) {
  this.deepEqual(sortKeys(actual), sortKeys(expected));
}
assert.equalJSON = assertEqualJSON;

exports.outputAll = {
  startTime:   true,
  elapsedTime: true,
  count:       true,
  attributes:  true,
  recodes:     true
};
<commit_msg>test: Remove obsolete codes<commit_after>var assert = require('chai').assert;
var nodemock = require('nodemock');
var net = require('net');
var msgpack = require('msgpack');
var http = require('http');
var Deferred = require('jsdeferred').Deferred;
var client = require('socket.io-client');
var express = require('express');

var FluentReceiver = require('../lib/backend/receiver').FluentReceiver;
var Connection = require('../lib/backend/connection').Connection;

var testSendPort = exports.testSendPort = 3333;
var testReceivePort = exports.testReceivePort = 3334;
var testServerPort = exports.testServerPort = 3335;

function connectTo(port) {
  var deferred = new Deferred();
  var clientSocket = new net.Socket();
  clientSocket.on('error', function(error){
    clientSocket.destroy();
    deferred.fail(error);
  });
  clientSocket.connect(port, 'localhost', function(){
    deferred.call(clientSocket);
  });
  return deferred;
}
exports.connectTo = connectTo;
Deferred.register('connectTo', connectTo);

function sendPacketTo(packet, port) {
  var clientSocket;
  return connectTo(port)
    .next(function(newSocket) {
      clientSocket = newSocket;
      var packedPacket = msgpack.pack(packet);
      clientSocket.write(new Buffer(packedPacket));
    })
    .wait(0.01)
    .next(function() {
      clientSocket.destroy();
      clientSocket = undefined;
    })
    .error(function(error) {
      if (clientSocket) {
        clientSocket.destroy();
        clientSocket = undefined;
      }
      throw error;
    });
}
exports.sendPacketTo = sendPacketTo;
Deferred.register('sendPacketTo', sendPacketTo);

function setupServer(handlerOrServer) {
  var deferred = new Deferred();
  var server;
  if ('close' in handlerOrServer) { // it is a server
    server = handlerOrServer;
  } else { // it is a handler
    server = http.createServer(handlerOrServer);
  }
  server.listen(testServerPort, function() {
    deferred.call(server);
  });
  return deferred;
}
exports.setupServer = setupServer;

function sendRequest(method, path, postData, headers) {
  var deferred = new Deferred();

  var options = {
        host: 'localhost',
        port: testServerPort,
        path: path,
        method: method,
        headers: {}
      };

  if (headers) {
    for (var header in headers) {
      if (headers.hasOwnProperty(header))
        options.headers[header] = headers[header];
    }
  }

  Deferred.next(function() {
    var request = http.request(options, function(response) {
          var body = '';
          response.on('data', function(data) {
            body += data;
          });
          response.on('end', function() {
            deferred.call({
              statusCode: response.statusCode,
              body: body
            });
          });
        });
    request.on('error', function(error) {
      deferred.fail(error);
    });

    if (postData) request.write(postData);
    request.end();
  });

  return deferred;
}

function get(path, headers) {
  return sendRequest('GET', path, null, headers);
}
exports.get = get;
Deferred.register('get', function() { return get.apply(this, arguments); });

function post(path, body, headers) {
  return sendRequest('POST', path, body, headers);
}
exports.post = post;
Deferred.register('post', function() { return post.apply(this, arguments); });

function createClientSocket() {
  var deferred = new Deferred();
  var host = 'http://localhost:' + testServerPort;
  var options = { 'force new connection': true };
  var socket = client.connect(host, options);
  socket.on('connect', function() {
    deferred.call(socket);
  });
  return deferred;
}
exports.createClientSocket = createClientSocket;
Deferred.register('createClientSocket', createClientSocket);

function createClientSockets(count) {
  var sockets = [];
  return Deferred.next(function loop() {
    if (sockets.length < count) {
      return createClientSocket()
               .next(function(newSocket) {
                 sockets.push(newSocket);
               })
               .next(loop);
    } else {
      return sockets;
    }
  });
}
exports.createClientSockets = createClientSockets;
Deferred.register('createClientSockets', createClientSockets);

function createStubbedBackendConnection() {
  return {
    emitMessage: function(type, message, callback, options) {
      this.emitMessageCalledArguments.push({
        type:     type,
        message:  message,
        callback: callback,
        options:  options
      });
    },
    emitMessageCalledArguments: [],

    emit: function() {},
    on: function() {},
    removeListener: function() {},
    removeAllListeners: function() {},
    close: function() {}
  };
}
exports.createStubbedBackendConnection = createStubbedBackendConnection;

function setupApplication() {
  var application = express();
  var server;
  var backend;
  return setupServer(application)
    .next(function(newServer) {
      server = newServer;
    })
    .createBackend()
    .next(function(newBackend) {
      backend = newBackend;
      var connection = new Connection({
        tag:      'test',
        hostName: 'localhost',
        port:     testSendPort,
        receivePort: testReceivePort,
        maxRetyrCount: 3,
        retryDelay: 1
      });
      return {
        backend:     backend,
        server:      server,
        application: application,
        connection:  connection
      };
    });
}
exports.setupApplication = setupApplication;
Deferred.register('setupApplication', setupApplication);

function teardownApplication(params) {
  params = params || {};
  if (params.backend) {
    params.backend.close();
    params.backend = undefined;
  }
  if (params.connection) {
    params.connection.close();
    params.connection = undefined;
  }
  if (params.server) {
    params.server.close();
    params.server = undefined;
  }
}
exports.teardownApplication = teardownApplication;
Deferred.register('teardownApplication', teardownApplication);

function readyToDestroyMockedConnection(connection, clientCount) {
  connection = connection
    .mock('removeListener')
      .takes('error', function() {});
  if (clientCount)
    connection = connection.times(clientCount);
  return connection;
}
exports.readyToDestroyMockedConnection = readyToDestroyMockedConnection;

function createBackend() {
  var deferred = new Deferred();
  var backend = new FluentReceiver(testSendPort);
  backend.received = [];
  backend.on('receive', function(data) {
    backend.received.push(data);
  });
  backend.listen(function() {
    return deferred.call(backend);
  });
  backend.getMessages = function() {
    return this.received.map(function(packet) {
      return packet[2];
    });
  };
  backend.getEvents = function() {
    return this.getMessages().map(function(envelope) {
      return envelope.type;
    });
  };
  backend.getBodies = function() {
    return this.getMessages().map(function(envelope) {
      return envelope.body;
    });
  };
  backend.assertReceived = function(expectedMessages) {
    assert.deepEqual(this.getMessages().map(function(message) {
                       return { type: message.type,
                                body: message.body };
                     }),
                     expectedMessages);
  };
  backend.sendMessage = function(type, body) {
    var response = createEnvelope(type, body);
    return sendPacketTo(createPacket(response), testReceivePort)
  };
  backend.sendResponse = function(request, type, body) {
    var response = createReplyEnvelope(request, type, body);
    return sendPacketTo(createPacket(response), testReceivePort)
  };
  return deferred;
}
exports.createBackend = createBackend;
Deferred.register('createBackend', createBackend);

function createEnvelope(type, body) {
  var now = new Date();
  var envelope = {
    id:         now.getTime(),
    date:       now.toISOString(),
    replyTo:    'localhost:' + testReceivePort,
    statusCode: 200,
    type:       type,
    body:       body
  };
  return envelope;
}
exports.createEnvelope = createEnvelope;

function createExpectedEnvelope(type, body) {
  var envelope = createEnvelope(type, body);
  envelope.id = TypeOf('string');
  envelope.date = InstanceOf(Date);
  return envelope;
}
exports.createExpectedEnvelope = createExpectedEnvelope;

function createReplyEnvelope(message, type, body) {
  var response = createEnvelope(type, body);
  response.inReplyTo = message.id;
  return response;
}
exports.createReplyEnvelope = createReplyEnvelope;

function createPacket(message, tag) {
  tag = tag || 'test.message';
  return [tag, Date.now(), message];
}
exports.createPacket = createPacket;

function TypeOf(typeString) {
  if (!(this instanceof TypeOf))
    return new TypeOf(typeString);

  this.typeString = typeString;
  if (typeString == 'date') {
    return new InstanceOf(Date);
  }
}
exports.TypeOf = TypeOf;

function InstanceOf(constructor) {
  if (!(this instanceof InstanceOf))
    return new InstanceOf(constructor);

  this.constructorFunction = constructor;
}
exports.InstanceOf = InstanceOf;

function assertEnvelopeEqual(actual, expected) {
  var vs = JSON.stringify(actual) + ' vs ' + JSON.stringify(expected);
  Object.keys(expected).forEach(function(key) {
    var actualValue = actual[key];
    var expectedValue = expected[key];
    if (expectedValue instanceof InstanceOf) {
      if (typeof actualValue == 'string') {
        // Try fo parse the value and create new instance.
        // If this process is failed, it can be an invalid value.
        actualValue = new expectedValue.constructorFunction(actualValue);
      }
      assert.instanceOf(actualValue,
                        expectedValue.constructorFunction,
                        key + ' / ' + vs);
    } else if (expectedValue instanceof TypeOf) {
      assert.typeOf(typeof actualValue,
                    expectedValue.typeString,
                    key + ' / ' + vs);
    } else {
      assert.deepEqual(actualValue, expectedValue, key + ' / ' + vs);
    }
  });
}
assert.envelopeEqual = assertEnvelopeEqual;

function sortKeys(original) {
  if (!original || typeof original != 'object')
    return original;

  if (Array.isArray(original))
    return original.map(sortKeys);

  var sorted = {};
  Object.keys(original).sort().forEach(function(key) {
    sorted[key] = sortKeys(original[key]);
  });
  return sorted;
}

// assert.deepEqual fails when the order of hash keys are different,
// even if they are "eaual" as JSON objects.
function assertEqualJSON(actual, expected) {
  this.deepEqual(sortKeys(actual), sortKeys(expected));
}
assert.equalJSON = assertEqualJSON;

exports.outputAll = {
  startTime:   true,
  elapsedTime: true,
  count:       true,
  attributes:  true,
  recodes:     true
};
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        cb && cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.sql.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            cb && cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        cb && cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            cb && cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            cb && cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test SQLite', function() {
    before('Test SQLite: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            config.native.dbtype   = 'sqlite';

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

    it('Test SQLite: Check if adapter started', function (done) {
        this.timeout(5000);
        checkConnectionOfAdapter(function () {
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    objects.getObject('system.adapter.sql.0.memRss', function (err, obj) {
                        obj.common.history = {
                            'sql.0': {
                                enabled:      true,
                                changesOnly:  false,
                                debounce:     0,
                                retention:    31536000
                            }
                        };
                        objects.setObject('system.adapter.sql.0.memRss', obj, function (err) {
                            // wait till adapter receives the new settings
                            setTimeout(function () {
                                done();
                            }, 3000);
                        });
                });
            });
        });
    });
    after('Test SQLite: Write values into DB', function (done) {
        this.timeout(25000);
        var now = new Date().getTime();

        states.setState('system.adapter.sql.0.memRss', {val: 1, ts: now - 2000}, function (err) {
            states.setState('system.adapter.sql.0.memRss', {val: 2, ts: now - 1000}, function (err) {
                states.setState('system.adapter.sql.0.memRss', {val: 3, ts: now}, function (err) {
                    setTimeout(function () {
                        sendTo('sql.0', 'query', 'SELECT id FROM datapoints WHERE name="system.adapter.sql.0.memRss"', function (result) {
                            sendTo('sql.0', 'query', 'SELECT * FROM ts_number WHERE id=' + result.result[0].id, function (result) {
                                console.log(JSON.stringify(result.result, null, 2));
                                expect(result.result.length).to.be.at.least(3);
                                var found = 0;
                                for (var i = 0; i < result.result.length; i++) {
                                    if (result.result[i].val >= 1 && result.result[i].val <= 3) found ++;
                                }
                                expect(found).to.be.equal(3);
                                done();
                            });
                        });
                    }, 4000);
                });
            });
        });
    });

    after('Test SQLite: Stop js-controller', function (done) {
        this.timeout(6000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});<commit_msg>try to get more infos on failing sqlite test<commit_after>var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        cb && cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.sql.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            cb && cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        cb && cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            cb && cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            cb && cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test SQLite', function() {
    before('Test SQLite: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            config.native.dbtype   = 'sqlite';

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

    it('Test SQLite: Check if adapter started', function (done) {
        this.timeout(5000);
        checkConnectionOfAdapter(function () {
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    objects.getObject('system.adapter.sql.0.memRss', function (err, obj) {
                        obj.common.history = {
                            'sql.0': {
                                enabled:      true,
                                changesOnly:  false,
                                debounce:     0,
                                retention:    31536000
                            }
                        };
                        objects.setObject('system.adapter.sql.0.memRss', obj, function (err) {
                            // wait till adapter receives the new settings
                            setTimeout(function () {
                                done();
                            }, 3000);
                        });
                });
            });
        });
    });
    after('Test SQLite: Write values into DB', function (done) {
        this.timeout(25000);
        var now = new Date().getTime();

        states.setState('system.adapter.sql.0.memRss', {val: 1, ts: now - 2000}, function (err) {
            if (err) {
                console.log(err);
            }
            states.setState('system.adapter.sql.0.memRss', {val: 2, ts: now - 1000}, function (err) {
                if (err) {
                    console.log(err);
                }
                states.setState('system.adapter.sql.0.memRss', {val: 3, ts: now}, function (err) {
                    if (err) {
                        console.log(err);
                    }
                    setTimeout(function () {
                        sendTo('sql.0', 'query', 'SELECT id FROM datapoints WHERE name="system.adapter.sql.0.memRss"', function (result) {
                            sendTo('sql.0', 'query', 'SELECT * FROM ts_number WHERE id=' + result.result[0].id, function (result) {
                                console.log(JSON.stringify(result.result, null, 2));
                                expect(result.result.length).to.be.at.least(3);
                                var found = 0;
                                for (var i = 0; i < result.result.length; i++) {
                                    if (result.result[i].val >= 1 && result.result[i].val <= 3) found ++;
                                }
                                expect(found).to.be.equal(3);
                                done();
                            });
                        });
                    }, 4000);
                });
            });
        });
    });

    after('Test SQLite: Stop js-controller', function (done) {
        this.timeout(6000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<|endoftext|>


<commit_before>/*jslint node: true, indent: 4 */
'use strict';
var async = require('async');
var discourse,
    conf;

exports.description = 'Issue Likes to all posts in a thread';

exports.configuration = {
    enabled: false,
    follow: false,
    binge: false,
    bingeHour: 23,
    bingeMinute: 30,
    topic: 1000
};

exports.name = 'AutoLikes';

exports.priority = 0;

exports.version = '1.13.0';

function format(str, dict) {
    for (var name in dict) {
        str = str.replace(new RegExp('%' + name + '%', 'g'), dict[name]);
    }
    return str;
}

function binge(callback) {
        if (typeof conf.topic === 'number') {
        binge(conf.topic, callback);
    } else {
        async.each(conf.topic, function(topic, next){
            return innerBinge(topic, next);
        }, callback);
    }
}

function innerBinge(topic, callback){
    var msg = 'Liking /t/%TOPIC%/%POST% by @%USER%';
    discourse.getAllPosts(topic, function (posts, next) {
        var likeables = posts.filter(function (x) {
            var action = x.actions_summary.filter(function (y) {
                return y.id === 2;
            });
            return action && action[0].can_act;
        });
        async.each(likeables, function (post, flow) {
            discourse.log(format(msg, {
                'TOPIC': post.topic_id,
                'POST': post.post_number,
                'USER': post.username
            }));
            discourse.postAction('like', post.id, function (err, resp) {
                flow(err || resp.statusCode === 429);
            });
        }, next);
    }, function () {
        callback();
    });
}

function scheduleBinges() {
    async.forever(function (cb) {
        var now = new Date(),
            utc = new Date(),
            hours,
            minutes;
        utc.setUTCHours(conf.bingeHour);
        utc.setUTCMinutes(conf.bingeMinute);
        utc.setUTCSeconds(0);
        utc.setMilliseconds(0);
        now = now.getTime();
        utc = utc.getTime();
        if (now > utc) {
            // add a day if scheduling after 23:40 UTC
            utc += 24 * 60 * 60 * 1000;
        }
        minutes = Math.ceil(((utc - now) / 1000) / 60);
        hours = Math.floor(minutes / 60);
        minutes = minutes % 60;
        discourse.log('Like Binge scheduled for ' + hours + 'h' +
            minutes + 'm from now');
        setTimeout(function () {
            binge(cb);
        }, utc - now);
    });
}

exports.onMessage = function onMessage(message, post, callback) {
    if (message.data && message.data.type === 'created') {
        if (post) {
            discourse.log('Liking Post /t/' + post.topic_id +
                '/' + post.post_number + ' by @' + post.username);
        } else {
            discourse.log('Liking Post #' + message.data.id);
        }
        discourse.postAction('like', message.data.id, callback);
    } else {
        callback();
    }
};

exports.registerListeners = function registerListeners(callback) {
    if (conf.enabled && conf.follow) {
        if (typeof conf.topic === 'number') {
            callback(null, ['/topic/' + conf.topic]);
        } else {
            callback(null, conf.topic.map(function (v) {
                return '/topic/' + v;
            }));
        }
    } else {
        callback();
    }
};

exports.begin = function begin(browser, config) {
    conf = config.modules[exports.name];
    discourse = browser;
    if (conf.enabled && conf.binge) {
        scheduleBinges();
    }
};
<commit_msg>Accalia name things right.....<commit_after>/*jslint node: true, indent: 4 */
'use strict';
var async = require('async');
var discourse,
    conf;

exports.description = 'Issue Likes to all posts in a thread';

exports.configuration = {
    enabled: false,
    follow: false,
    binge: false,
    bingeHour: 23,
    bingeMinute: 30,
    topic: 1000
};

exports.name = 'AutoLikes';

exports.priority = 0;

exports.version = '1.13.0';

function format(str, dict) {
    for (var name in dict) {
        str = str.replace(new RegExp('%' + name + '%', 'g'), dict[name]);
    }
    return str;
}

function binge(callback) {
        if (typeof conf.topic === 'number') {
        innerBinge(conf.topic, callback);
    } else {
        async.each(conf.topic, function(topic, next){
            return innerBinge(topic, next);
        }, callback);
    }
}

function innerBinge(topic, callback){
    var msg = 'Liking /t/%TOPIC%/%POST% by @%USER%';
    discourse.getAllPosts(topic, function (posts, next) {
        var likeables = posts.filter(function (x) {
            var action = x.actions_summary.filter(function (y) {
                return y.id === 2;
            });
            return action && action[0].can_act;
        });
        async.each(likeables, function (post, flow) {
            discourse.log(format(msg, {
                'TOPIC': post.topic_id,
                'POST': post.post_number,
                'USER': post.username
            }));
            discourse.postAction('like', post.id, function (err, resp) {
                flow(err || resp.statusCode === 429);
            });
        }, next);
    }, function () {
        callback();
    });
}

function scheduleBinges() {
    async.forever(function (cb) {
        var now = new Date(),
            utc = new Date(),
            hours,
            minutes;
        utc.setUTCHours(conf.bingeHour);
        utc.setUTCMinutes(conf.bingeMinute);
        utc.setUTCSeconds(0);
        utc.setMilliseconds(0);
        now = now.getTime();
        utc = utc.getTime();
        if (now > utc) {
            // add a day if scheduling after 23:40 UTC
            utc += 24 * 60 * 60 * 1000;
        }
        minutes = Math.ceil(((utc - now) / 1000) / 60);
        hours = Math.floor(minutes / 60);
        minutes = minutes % 60;
        discourse.log('Like Binge scheduled for ' + hours + 'h' +
            minutes + 'm from now');
        setTimeout(function () {
            binge(cb);
        }, utc - now);
    });
}

exports.onMessage = function onMessage(message, post, callback) {
    if (message.data && message.data.type === 'created') {
        if (post) {
            discourse.log('Liking Post /t/' + post.topic_id +
                '/' + post.post_number + ' by @' + post.username);
        } else {
            discourse.log('Liking Post #' + message.data.id);
        }
        discourse.postAction('like', message.data.id, callback);
    } else {
        callback();
    }
};

exports.registerListeners = function registerListeners(callback) {
    if (conf.enabled && conf.follow) {
        if (typeof conf.topic === 'number') {
            callback(null, ['/topic/' + conf.topic]);
        } else {
            callback(null, conf.topic.map(function (v) {
                return '/topic/' + v;
            }));
        }
    } else {
        callback();
    }
};

exports.begin = function begin(browser, config) {
    conf = config.modules[exports.name];
    discourse = browser;
    if (conf.enabled && conf.binge) {
        scheduleBinges();
    }
};
<|endoftext|>


<commit_before>/*jslint node: true, indent: 4 */
(function () {
    'use strict';
    var async = require('async'),
        m_browser,
        m_config,
        likesList = [];

    function getPage(thread_id, start_post, callback) {
        m_browser.getContent('t/' + thread_id + '/' + start_post + '.json', function (err, req, contents) {
            if (err || req.statusCode >= 400) {
                console.error('Topic ' + thread_id + ' could not be loaded.');
                callback(-1);
                return;
            }
            if (req.statusCode >= 300) {
                console.log('Topic ' + thread_id + ' is private or not exist');
                callback(-1);
                return;
            }
            if (typeof contents !== 'object') {
                callback(0);
                return;
            }
            var posts = contents.post_stream.posts,
                likeables = posts.filter(function (x) {
                    var action = x.actions_summary.filter(function (y) {
                        return y.id === 2;
                    });
                    return action && action[0].can_act;
                });
            likeables.forEach(function (x) {
                var data = {
                    form: {
                        'id': x.id,
                        'post_action_type_id': 2,
                        'flag_topic': false
                    },
                    post_number: x.post_number,
                    post_id: x.id,
                    username: x.username
                };
                likesList.push(data);
            });
            callback(posts[posts.length - 1].post_number);
        });
    }

    function fillList(thread_id) {
        var start_post = 0;
        async.forever(function (cb) {
            if (likesList.length >= 1000) {
                // if likeslist is longer than limit wait an hour and check again
                setTimeout(cb, 60 * 60 * 1000);
                return;
            }
            getPage(thread_id, start_post, function (last_post) {
                if (last_post < 0) {
                    console.error(exports.name + ' encountered a fatal error. Stopping.');
                    cb(true);
                    return;
                }
                console.log('Processed ' + last_post + ' posts for likeable posts.');
                var got_results = last_post > start_post;
                start_post = last_post + 1;
                // delay a quarter second on post get, delay 5 minutes on no new posts
                setTimeout(cb, got_results ? 250 : 5 * 60 * 1000);
            });
        });
    }

    function likeBinge(callback) {
        async.forever(function (cb) {
            if (likesList.length === 0) {
                setTimeout(cb, 100);
                return;
            }
            var like = likesList.shift();
            console.log('Liking Post ' + like.post_number + '(#' + like.post_id + ') By `' + like.username + '`');
            m_browser.postMessage('post_actions', like.form, function (err, resp) {
                if (err || resp.statusCode < 300) {
                    setTimeout(cb, 100);
                } else {
                    console.log('Send Error ' + resp.statusCode);
                    likesList.unshift(like);
                    cb(true);
                }
            });

        }, function () {
            callback();
        });
    }

    function scheduleBinges() {
        async.forever(function (cb) {
            var now = new Date(),
                utc = new Date(),
                hours,
                minutes;
            utc.setUTCHours(m_config.likeBingeHour || 23);
            utc.setUTCMinutes(m_config.likeBingeMinute || 40);
            utc.setUTCSeconds(0);
            utc.setMilliseconds(0);
            now = now.getTime();
            utc = utc.getTime();
            if (now > utc) {
                utc += 24 * 60 * 60 * 1000; // add a day if scheduling after 23:40 UTC
            }
            minutes = Math.ceil(((utc - now) / 1000) / 60);
            hours = Math.floor(minutes / 60);
            minutes = minutes % 60;
            console.log('Like Binge scheduled for ' + hours + 'h' + minutes + 'm from now');
            setTimeout(function () {
                likeBinge(cb);
            }, utc - now);
        });
    }
    exports.name = 'AutoLike 1.0.1';
    exports.begin = function begin(browser, config) {
        m_browser = browser;
        m_config = config;

        if (config.likeBinge) {
            fillList(config.likeBingeTopic);
            scheduleBinges();
        }
    };
}());<commit_msg>add condition to liker that ignoresposts that got on the list twice for some crazy reason<commit_after>/*jslint node: true, indent: 4 */
(function () {
    'use strict';
    var async = require('async'),
        m_browser,
        m_config,
        likesList = [];

    function getPage(thread_id, start_post, callback) {
        m_browser.getContent('t/' + thread_id + '/' + start_post + '.json', function (err, req, contents) {
            if (err || req.statusCode >= 400) {
                console.error('Topic ' + thread_id + ' could not be loaded.');
                callback(-1);
                return;
            }
            if (req.statusCode >= 300) {
                console.log('Topic ' + thread_id + ' is private or not exist');
                callback(-1);
                return;
            }
            if (typeof contents !== 'object') {
                callback(0);
                return;
            }
            var posts = contents.post_stream.posts,
                likeables = posts.filter(function (x) {
                    var action = x.actions_summary.filter(function (y) {
                        return y.id === 2;
                    });
                    return action && action[0].can_act;
                });
            likeables.forEach(function (x) {
                var data = {
                    form: {
                        'id': x.id,
                        'post_action_type_id': 2,
                        'flag_topic': false
                    },
                    post_number: x.post_number,
                    post_id: x.id,
                    username: x.username
                };
                likesList.push(data);
            });
            callback(posts[posts.length - 1].post_number);
        });
    }

    function fillList(thread_id) {
        var start_post = 0;
        async.forever(function (cb) {
            if (likesList.length >= 1000) {
                // if likeslist is longer than limit wait an hour and check again
                setTimeout(cb, 60 * 60 * 1000);
                return;
            }
            getPage(thread_id, start_post, function (last_post) {
                if (last_post < 0) {
                    console.error(exports.name + ' encountered a fatal error. Stopping.');
                    cb(true);
                    return;
                }
                console.log('Processed ' + last_post + ' posts for likeable posts.');
                var got_results = last_post > start_post;
                start_post = last_post + 1;
                // delay a quarter second on post get, delay 5 minutes on no new posts
                setTimeout(cb, got_results ? 250 : 5 * 60 * 1000);
            });
        });
    }

    function likeBinge(callback) {
        async.forever(function (cb) {
            if (likesList.length === 0) {
                setTimeout(cb, 100);
                return;
            }
            var like = likesList.shift();
            console.log('Liking Post ' + like.post_number + '(#' + like.post_id + ') By `' + like.username + '`');
            m_browser.postMessage('post_actions', like.form, function (err, resp) {
                if (err || (resp.statusCode < 300 && resp.statusCode != 403)) { // Ignore error 403, that means duplicate like or post deleted
                    setTimeout(cb, 100);
                } else {
                    console.log('Send Error ' + resp.statusCode);
                    likesList.unshift(like);
                    cb(true);
                }
            });

        }, function () {
            callback();
        });
    }

    function scheduleBinges() {
        async.forever(function (cb) {
            var now = new Date(),
                utc = new Date(),
                hours,
                minutes;
            utc.setUTCHours(m_config.likeBingeHour || 23);
            utc.setUTCMinutes(m_config.likeBingeMinute || 40);
            utc.setUTCSeconds(0);
            utc.setMilliseconds(0);
            now = now.getTime();
            utc = utc.getTime();
            if (now > utc) {
                utc += 24 * 60 * 60 * 1000; // add a day if scheduling after 23:40 UTC
            }
            minutes = Math.ceil(((utc - now) / 1000) / 60);
            hours = Math.floor(minutes / 60);
            minutes = minutes % 60;
            console.log('Like Binge scheduled for ' + hours + 'h' + minutes + 'm from now');
            setTimeout(function () {
                likeBinge(cb);
            }, utc - now);
        });
    }
    exports.name = 'AutoLike 1.0.1';
    exports.begin = function begin(browser, config) {
        m_browser = browser;
        m_config = config;

        if (config.likeBinge) {
            fillList(config.likeBingeTopic);
            scheduleBinges();
        }
    };
}());<|endoftext|>