<commit_before>/*
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

var BASE = 'extensions.reload-on-idle@clear-code.com.';
var prefs = require('lib/prefs').prefs;
var WM = require('lib/WindowManager').WindowManager;

var MINUTE_IN_SECONDS = 60;
var HOUR_IN_MINUTES = 60;
var DAY_IN_HOURS = 24;
var DAY_IN_SECONDS = DAY_IN_HOURS * HOUR_IN_MINUTES * MINUTE_IN_SECONDS;
{
  if (prefs.getDefaultPref(BASE + 'debug') === null)
    prefs.setDefaultPref(BASE + 'debug', false);
  if (prefs.getDefaultPref(BASE + 'filter') === null)
    prefs.setDefaultPref(BASE + 'filter', '.');
  if (prefs.getDefaultPref(BASE + 'idleSeconds') === null)
    prefs.setDefaultPref(BASE + 'idleSeconds', 10 * MINUTE_IN_SECONDS);
}

var timer = Cu.import('resource://gre/modules/Timer.jsm', {});
var { Promise } = Cu.import('resource://gre/modules/Promise.jsm', {});

var reloader = {
  MESSAGE_TYPE: 'reload-on-idle@clear-code.com',
  SCRIPT_URL: 'chrome://reload-on-idle/content/content-utils.js',
  lastTimeout: null,

  onTimeout: function() {
    this.reloadTabs()
      .then((function() {
        var interval = Math.max(1, prefs.getPref(BASE + 'idleSeconds'));
        this.lastTimeout = timer.setTimeout(this.onTimeout.bind(this), interval * 1000);
      }).bind(this))
      .catch(function(error) {
        Cu.reportError(error);
      });
  },

  forEachBrowserWindow: function(aCallback) {
    var browsers = WM.getWindows('navigator:browser');
    browsers.forEach(aCallback, this);
  },

  forEachTab: function(aWindow, aCallback) {
    Array.forEach(aWindow.gBrowser.tabContainer.childNodes, aCallback, this);
  },

  get leaveButtonLabel() {
    delete this.leaveButtonLabel;
    try {
      var label = Cc['@mozilla.org/intl/stringbundle;1']
                    .getService(Ci.nsIStringBundleService)
                    .createBundle('chrome://global/locale/dom/dom.properties')
                    .GetStringFromName('OnBeforeUnloadLeaveButton');
      return this.leaveButtonLabel = label;
    }
    catch(e) {
      return null;
    }
  },

  pushLeaveButton: function(aWindow, aTab) {
    var promptBox = aWindow.gBrowser.getTabModalPromptBox(aTab.linkedBrowser);
    var prompts = promptBox.listPrompts();
    prompts.forEach(function(aPrompt) {
      if (aPrompt.args.promptType != 'confirmEx')
        return;
      if (aPrompt.args.button0Label == this.leaveButtonLabel)
        aPrompt.ui.button0.click();
      else if (aPrompt.args.button1Label == this.leaveButtonLabel)
        aPrompt.ui.button1.click();
    }, this);
  },

  reloadTabs: function() {
    return new Promise((function(resolve, reject) {
      try {
        var filter = new RegExp(prefs.getPref(BASE + 'filter'), 'i');
        this.forEachBrowserWindow(function(aWindow) {
          this.forEachTab(aWindow, function(aTab) {
            if (!filter.test(aTab.linkedBrowser.currentURI.spec) ||
                aTab.getAttribute('pending') == 'true')
              return;

            aTab.linkedBrowser.messageManager.sendAsyncMessage(this.MESSAGE_TYPE, {
              command : 'reload'
            });
            timer.setTimeout(this.pushLeaveButton.bind(this), 0, aWindow, aTab);
          });
        });
        resolve();
      }
      catch(error) {
        reject(error);
      }
    }).bind(this));
  },

  start: function() {
    this.stop();
    this.onTimeout();
  },

  stop: function() {
    if (this.lastTimeout)
      timer.clearTimeout(this.lastTimeout);
    this.lastTimeout = null;
  },

  startup: function() {
    this.forEachBrowserWindow(function(aWindow) {
      this.initBrowserWindow(aWindow);
    });
    this.initBrowserWindow = this.initBrowserWindow.bind(this);
    WM.addHandler(this.initBrowserWindow);
    this.registerIdleObserver();
    prefs.addPrefListener(this);
  },

  shutdown: function() {
    prefs.removePrefListener(this);
    this.unregisterIdleObserver();
    this.stop();
    WM.removeHandler(this.initBrowserWindow);
    this.forEachBrowserWindow(function(aWindow) {
      aWindow.messageManager.broadcastAsyncMessage(this.MESSAGE_TYPE, {
        command : 'shutdown'
      });
      aWindow.messageManager.removeDelayedFrameScript(this.SCRIPT_URL);
    });
  },

  registerIdleObserver: function() {
    var idleSeconds = Math.max(10, prefs.getPref(BASE + 'idleSeconds'));
    idleService.addIdleObserver(this, idleSeconds);
    this.lastIdleSeconds = idleSeconds;
  },

  unregisterIdleObserver: function() {
    idleService.addIdleObserver(this, this.lastIdleSeconds);
  },

  initBrowserWindow: function(aWindow) {
    if (aWindow.document.documentElement.getAttribute('windowtype') == 'navigator:browser')
      aWindow.messageManager.loadFrameScript(this.SCRIPT_URL, true);
  },

  domain: BASE,

  observe: function(aSubject, aTopic, aData) {
    // console.log([aSubject, aTopic, aData]);
    switch (aTopic) {
      case 'idle':
        if (prefs.getPref(BASE + 'debug'))
          console.log('idle: start to reload');
        this.start();
        break;

      case 'active':
        if (prefs.getPref(BASE + 'debug'))
          console.log('active: stop to reload');
        this.stop();
        break;

      case 'nsPref:changed':
        {
          switch (aData.replace(BASE, '')) {
            case 'idleSeconds':
              this.unregisterIdleObserver();
              this.registerIdleObserver();
              break;
          }
        }
        break;
    }
  }
};

var idleService = Cc['@mozilla.org/widget/idleservice;1']
                    .getService(Ci.nsIIdleService);

reloader.startup();

function shutdown() {
  reloader.shutdown();

  timer = Promise = prefs = WM =
    idleService = reloader =
      undefined;
}
<commit_msg>Unregister idle observer correctly<commit_after>/*
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

var BASE = 'extensions.reload-on-idle@clear-code.com.';
var prefs = require('lib/prefs').prefs;
var WM = require('lib/WindowManager').WindowManager;

var MINUTE_IN_SECONDS = 60;
var HOUR_IN_MINUTES = 60;
var DAY_IN_HOURS = 24;
var DAY_IN_SECONDS = DAY_IN_HOURS * HOUR_IN_MINUTES * MINUTE_IN_SECONDS;
{
  if (prefs.getDefaultPref(BASE + 'debug') === null)
    prefs.setDefaultPref(BASE + 'debug', false);
  if (prefs.getDefaultPref(BASE + 'filter') === null)
    prefs.setDefaultPref(BASE + 'filter', '.');
  if (prefs.getDefaultPref(BASE + 'idleSeconds') === null)
    prefs.setDefaultPref(BASE + 'idleSeconds', 10 * MINUTE_IN_SECONDS);
}

var timer = Cu.import('resource://gre/modules/Timer.jsm', {});
var { Promise } = Cu.import('resource://gre/modules/Promise.jsm', {});

var reloader = {
  MESSAGE_TYPE: 'reload-on-idle@clear-code.com',
  SCRIPT_URL: 'chrome://reload-on-idle/content/content-utils.js',
  lastTimeout: null,

  onTimeout: function() {
    this.reloadTabs()
      .then((function() {
        var interval = Math.max(1, prefs.getPref(BASE + 'idleSeconds'));
        this.lastTimeout = timer.setTimeout(this.onTimeout.bind(this), interval * 1000);
      }).bind(this))
      .catch(function(error) {
        Cu.reportError(error);
      });
  },

  forEachBrowserWindow: function(aCallback) {
    var browsers = WM.getWindows('navigator:browser');
    browsers.forEach(aCallback, this);
  },

  forEachTab: function(aWindow, aCallback) {
    Array.forEach(aWindow.gBrowser.tabContainer.childNodes, aCallback, this);
  },

  get leaveButtonLabel() {
    delete this.leaveButtonLabel;
    try {
      var label = Cc['@mozilla.org/intl/stringbundle;1']
                    .getService(Ci.nsIStringBundleService)
                    .createBundle('chrome://global/locale/dom/dom.properties')
                    .GetStringFromName('OnBeforeUnloadLeaveButton');
      return this.leaveButtonLabel = label;
    }
    catch(e) {
      return null;
    }
  },

  pushLeaveButton: function(aWindow, aTab) {
    var promptBox = aWindow.gBrowser.getTabModalPromptBox(aTab.linkedBrowser);
    var prompts = promptBox.listPrompts();
    prompts.forEach(function(aPrompt) {
      if (aPrompt.args.promptType != 'confirmEx')
        return;
      if (aPrompt.args.button0Label == this.leaveButtonLabel)
        aPrompt.ui.button0.click();
      else if (aPrompt.args.button1Label == this.leaveButtonLabel)
        aPrompt.ui.button1.click();
    }, this);
  },

  reloadTabs: function() {
    return new Promise((function(resolve, reject) {
      try {
        var filter = new RegExp(prefs.getPref(BASE + 'filter'), 'i');
        this.forEachBrowserWindow(function(aWindow) {
          this.forEachTab(aWindow, function(aTab) {
            if (!filter.test(aTab.linkedBrowser.currentURI.spec) ||
                aTab.getAttribute('pending') == 'true')
              return;

            aTab.linkedBrowser.messageManager.sendAsyncMessage(this.MESSAGE_TYPE, {
              command : 'reload'
            });
            timer.setTimeout(this.pushLeaveButton.bind(this), 0, aWindow, aTab);
          });
        });
        resolve();
      }
      catch(error) {
        reject(error);
      }
    }).bind(this));
  },

  start: function() {
    this.stop();
    this.onTimeout();
  },

  stop: function() {
    if (this.lastTimeout)
      timer.clearTimeout(this.lastTimeout);
    this.lastTimeout = null;
  },

  startup: function() {
    this.forEachBrowserWindow(function(aWindow) {
      this.initBrowserWindow(aWindow);
    });
    this.initBrowserWindow = this.initBrowserWindow.bind(this);
    WM.addHandler(this.initBrowserWindow);
    this.registerIdleObserver();
    prefs.addPrefListener(this);
  },

  shutdown: function() {
    prefs.removePrefListener(this);
    this.unregisterIdleObserver();
    this.stop();
    WM.removeHandler(this.initBrowserWindow);
    this.forEachBrowserWindow(function(aWindow) {
      aWindow.messageManager.broadcastAsyncMessage(this.MESSAGE_TYPE, {
        command : 'shutdown'
      });
      aWindow.messageManager.removeDelayedFrameScript(this.SCRIPT_URL);
    });
  },

  registerIdleObserver: function() {
    var idleSeconds = Math.max(10, prefs.getPref(BASE + 'idleSeconds'));
    idleService.addIdleObserver(this, idleSeconds);
    this.lastIdleSeconds = idleSeconds;
  },

  unregisterIdleObserver: function() {
    idleService.removeIdleObserver(this, this.lastIdleSeconds);
  },

  initBrowserWindow: function(aWindow) {
    if (aWindow.document.documentElement.getAttribute('windowtype') == 'navigator:browser')
      aWindow.messageManager.loadFrameScript(this.SCRIPT_URL, true);
  },

  domain: BASE,

  observe: function(aSubject, aTopic, aData) {
    // console.log([aSubject, aTopic, aData]);
    switch (aTopic) {
      case 'idle':
        if (prefs.getPref(BASE + 'debug'))
          console.log('idle: start to reload');
        this.start();
        break;

      case 'active':
        if (prefs.getPref(BASE + 'debug'))
          console.log('active: stop to reload');
        this.stop();
        break;

      case 'nsPref:changed':
        {
          switch (aData.replace(BASE, '')) {
            case 'idleSeconds':
              this.unregisterIdleObserver();
              this.registerIdleObserver();
              break;
          }
        }
        break;
    }
  }
};

var idleService = Cc['@mozilla.org/widget/idleservice;1']
                    .getService(Ci.nsIIdleService);

reloader.startup();

function shutdown() {
  reloader.shutdown();

  timer = Promise = prefs = WM =
    idleService = reloader =
      undefined;
}
<|endoftext|>


<commit_before>var express = require('express');
var moment = require('moment');
var rest = require('./rest');

module.exports = (function() {
    'use strict';
    var app = express.Router();

    app.get('/user/:id', getUser);

    function unpackUser(obj) {
        obj.password_hash = "";
        delete obj.lastloggedin;
        delete obj.created;
        obj.contact = "";
        return obj;
    }

    function unpackUserPrivileged(obj) { // only called when user = self
        obj.password_hash = "";
        obj.lastloggedin = moment(obj.lastloggedin);
        obj.created = moment(obj.created);
        return obj;
    }

    function getUser(req, res, next) {
        var id = req.params.id;
        rest.getDetail("user", id, res, next, unpackUser);
    }

    // ===== LOGIN

    app.post('/login', login);
    app.post('/signup', signup);

    function login(req, res, next) {
        var name = req.body.name;
        var hash = req.body.hash;
        rest.client.zscore(["userids", name], function (err, id) {
            if (err) {
                console.log("error while looking up score for user:" + name);
                console.log(err);
            } else {
                if (id == null) {
                    res.json({status: "fail", msg: "wrong pass"});
                } else {
                    rest.client.hgetall("user:" + id, function (err, userData) {
                        if (err) {
                            console.log("error while looking for hash:" + hash);
                            console.log(err);
                        } else {
                            if (userData.password_hash == hash) {
                                console.log("INFO: user "+name+" successfully logged in");
                                res.json({status: "success", obj: unpackUserPrivileged(userData)});
                            } else {
                                console.log("INFO: user "+name+" bad login");
                                console.log(userData.password_hash);
                                console.log(hash)
                                res.json({status: "fail", msg: "wrong pass"});
                            }
                        }
                    });
                }

            }
        });
    }

    function makeUser (name, hash) {
        var d = new Date();
        return {
            name: name,
            password_hash: hash,
            avatar: "",
            created: d.toISOString(),
            lastloggedin: d.toISOString(),
            contact: ""
        };
    }

    function signup(req, res, next) {
        var name = req.body.name;
        var hash = req.body.hash;
        rest.client.sismember(["usernames", name], function(err, userExists) {
            if (err) {
                console.log("error while looking up if username exists:" + name);
                console.log(err);
            } else {
                if (userExists) {
                    console.log("INFO: user "+name+" attempted to sign up, but exists");
                    res.json({status: "fail", msg: "name is already taken"});
                } else {
                    var obj = makeUser(name, hash);
                    rest.client.incr("userID", function (err, nextID) {
                        if (err) {
                            console.log("error while incrementing IDs for user");
                            console.log(err);
                        } else {
                            obj.id = nextID;
                            var hash = "user:" + nextID;
                            rest.client.multi([
                                ["hmset", hash, obj],
                                ["zadd", "userids", nextID, name],
                                ["sadd", "usernames", name],
                                ["sadd", "users", nextID],
                                ["set", hash+":rep:events", 0],
                                ["set", hash+":rep:hushtags", 0],
                                ["set", hash+":rep:locations", 0]
                            ]).exec(function (err) {
                                    if (err) {
                                        console.log("error while inserting data for " + hash);
                                        console.dir(obj);
                                        console.log(err);
                                    } else {
                                        console.log("INFO: user "+name+" signed up");
                                        res.json({status: "success", obj: unpackUserPrivileged(obj)});
                                    }
                                }
                            );
                        }
                    });
                }
            }
        });
    }

    return app;
})();<commit_msg>made login into promise<commit_after>var express = require('express');
var moment = require('moment');
var rest = require('./rest');

module.exports = (function () {
    'use strict';
    var app = express.Router();

    app.get('/user/:id', getUser);

    function unpackUser(obj) {
        obj.password_hash = "";
        delete obj.lastloggedin;
        delete obj.created;
        obj.contact = "";
        return obj;
    }

    function unpackUserPrivileged(obj) { // only called when user = self
        obj.password_hash = "";
        obj.lastloggedin = moment(obj.lastloggedin);
        obj.created = moment(obj.created);
        return obj;
    }

    function getUser(req, res, next) {
        var id = req.params.id;
        rest.getDetail("user", id, res, next, unpackUser);
    }

    // ===== LOGIN

    app.post('/login', login);
    app.post('/signup', signup);

    function login(req, res, next) {
        var name = req.body.name;
        var hash = req.body.hash;
        var p = rest.client.zscoreAsync(["userids", name]).then(function (id) {
            if (id == null) {
                console.log("INFO: user " + name + " bad login - doesn't exist");
                res.json({status: "fail", msg: "wrong pass"});
                return p.cancel();
            } else {
                return rest.client.hgetallAsync("user:" + id);
            }
        }).then(function (userData) {
            if (userData.password_hash == hash) {
                console.log("INFO: user " + name + " successfully logged in");
                res.json({status: "success", obj: unpackUserPrivileged(userData)});
            } else {
                console.log("INFO: user " + name + " bad login");
                res.json({status: "fail", msg: "wrong pass"});
            }
        }).error(function(err) {
            console.log("error while trying to login user:" + name);
            console.log(err);
            res.json({status: "fail", msg: "There was a server problem, please try again in an hour or so."});
        }).cancellable();

    }

    function makeUser(name, hash) {
        var d = new Date();
        return {
            name: name,
            password_hash: hash,
            avatar: "",
            created: d.toISOString(),
            lastloggedin: d.toISOString(),
            contact: ""
        };
    }

    function signup(req, res, next) {
        var name = req.body.name;
        var hash = req.body.hash;
        rest.client.sismember(["usernames", name], function (err, userExists) {
            if (err) {
                console.log("error while looking up if username exists:" + name);
                console.log(err);
            } else {
                if (userExists) {
                    console.log("INFO: user " + name + " attempted to sign up, but exists");
                    res.json({status: "fail", msg: "name is already taken"});
                } else {
                    var obj = makeUser(name, hash);
                    rest.client.incr("userID", function (err, nextID) {
                        if (err) {
                            console.log("error while incrementing IDs for user");
                            console.log(err);
                        } else {
                            obj.id = nextID;
                            var hash = "user:" + nextID;
                            rest.client.multi([
                                ["hmset", hash, obj],
                                ["zadd", "userids", nextID, name],
                                ["sadd", "usernames", name],
                                ["sadd", "users", nextID],
                                ["set", hash + ":rep:events", 0],
                                ["set", hash + ":rep:hushtags", 0],
                                ["set", hash + ":rep:locations", 0]
                            ]).exec(function (err) {
                                    if (err) {
                                        console.log("error while inserting data for " + hash);
                                        console.dir(obj);
                                        console.log(err);
                                    } else {
                                        console.log("INFO: user " + name + " signed up");
                                        res.json({status: "success", obj: unpackUserPrivileged(obj)});
                                    }
                                }
                            );
                        }
                    });
                }
            }
        });
    }

    return app;
})();<|endoftext|>


<commit_before>'use strict';

// var targetApp = 'test-target/some-app';
var targetApp = 'tests/dummy';

var Promise = require("rsvp").Promise;
var EOL = require("os").eol;
var path = require('path');
var fs = require('fs');

var chai = require('chai');

var expect = chai.expect;

var runCommand = require('ember-cli-internal-test-helpers/lib/helpers/run-command');

var TIME_TO_WAIT_FOR_BUILD = 10000;
var TIME_TO_WAIT_FOR_STARTUP = 10000;

var _log = [];

function log(message) {
  _log.push(message);
}

function cleanFakeOpener() {
    try {
      fs.unlinkSync('fake-opener');
    } catch (e) {
      // eslint-disable no-empty
      // don't know how to make without catch efectivelly
    }
}

function getOpenerLaunches() {
    var filePath = path.join(process.cwd(), 'fake-opener');

    try { // if exists
      fs.accessSync(filePath);
    } catch (e) {
      return [];
    }

    var fileContent = fs.readFileSync(filePath, { encoding:  'utf8' });

    var lines = fileContent.split(EOL)
      .map(function(line) { return line.trim(); })
      .filter(function(line) { return !!line; });

    return lines;
}

function runServer(commandOptions) {
  if (!commandOptions.log) {
    commandOptions.log = log;
  }
  commandOptions.killAfterChildSpawnedPromiseResolution = true;

  var openValue;
  if (typeof commandOptions.open !== 'undefined') {
    if (typeof commandOptions.open === 'boolean') {
      openValue = commandOptions.open ? "true" : "false";
    } else {
      openValue = commandOptions.open;
    }
    delete commandOptions.open;
  }

  return new Promise(function(resolve, reject) {
    return runCommand(
      path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'),
      'serve',
      openValue ? ('--open=' + openValue) : '',
      commandOptions
    )
    .then(function() {
      throw new Error('The server should not have exited successfully.');
    })
    .catch(function(err) {
      if (err.testingError) {
        return reject(err.testingError);
      }

      // This error was just caused by us having to kill the program
      return resolve();
    });
  });
}

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

describe('commands/serve', function () {
  before(function() {
    this.timeout(300000);
    process.chdir(targetApp);
    return runCommand('bower', 'install', { log: log })
    .then(() => runCommand('npm', 'uninstall', 'ember-cli-open', { log: log }))
    .then(() => runCommand('npm', 'install', { log: log }))
    .then(() => runCommand('npm', 'install', '--save-dev', path.join('..', '..'), { log: log }));
  });

  after(function() {
    process.chdir(path.join('..', '..'));
  }),

  beforeEach(cleanFakeOpener);

  it('should be launched by default', function() {
    this.timeout(TIME_TO_WAIT_FOR_BUILD + TIME_TO_WAIT_FOR_STARTUP);
    return runServer({
      onChildSpawned: function () {
        return delay(TIME_TO_WAIT_FOR_BUILD).then(function () {
          var launches = getOpenerLaunches();
          expect(launches.length).to.equal(1, "Opener launched 1 time");
        });
      }
    });
  });

  it('should not be launched if open=false', function () {
    this.timeout(TIME_TO_WAIT_FOR_BUILD + TIME_TO_WAIT_FOR_STARTUP);
    return runServer({
      open: false,
      onChildSpawned: function () {
        return delay(TIME_TO_WAIT_FOR_BUILD).then(function () {
          var launches = getOpenerLaunches();
          expect(launches.length).to.equal(0, "Opener not launched");
        });
      }
    });
  });
});

describe('commands/serve with baseURL', function () {
  before(function() {
    this.timeout(300000);
    process.chdir('tests/dummy.with-base-url');
    return runCommand('bower', 'install', { log: log })
    .then(() => runCommand('npm', 'uninstall', 'ember-cli-open', { log: log }))
    .then(() => runCommand('npm', 'install', { log: log }))
    .then(() => runCommand('npm', 'install', '--save-dev', path.join('..', '..'), { log: log }));
  });

  after(function() {
    process.chdir(path.join('..', '..'));
  }),

  beforeEach(cleanFakeOpener);

  it('should be launched by default', function() {
    this.timeout(TIME_TO_WAIT_FOR_BUILD + TIME_TO_WAIT_FOR_STARTUP);
    return runServer({
      onChildSpawned: function () {
        return delay(TIME_TO_WAIT_FOR_BUILD).then(function () {
          var launches = getOpenerLaunches();
          expect(launches.length).to.equal(1, "Opener launched 1 time");
          expect(launches[0]).to.equal('http://localhost:4200/custom-path/', "Opened with baseURL");
        });
      }
    });
  });
});
<commit_msg>update test to be compatible with node@0.12<commit_after>'use strict';

// var targetApp = 'test-target/some-app';
var targetApp = 'tests/dummy';

var Promise = require("rsvp").Promise;
var EOL = require("os").eol;
var path = require('path');
var fs = require('fs');

var chai = require('chai');

var expect = chai.expect;

var runCommand = require('ember-cli-internal-test-helpers/lib/helpers/run-command');

var TIME_TO_WAIT_FOR_BUILD = 10000;
var TIME_TO_WAIT_FOR_STARTUP = 10000;

var _log = [];

function log(message) {
  _log.push(message);
}

function cleanFakeOpener() {
    try {
      fs.unlinkSync('fake-opener');
    } catch (e) {
      // eslint-disable no-empty
      // don't know how to make without catch efectivelly
    }
}

function getOpenerLaunches() {
    var filePath = path.join(process.cwd(), 'fake-opener');

    try { // if exists
      fs.accessSync(filePath);
    } catch (e) {
      return [];
    }

    var fileContent = fs.readFileSync(filePath, { encoding:  'utf8' });

    var lines = fileContent.split(EOL)
      .map(function(line) { return line.trim(); })
      .filter(function(line) { return !!line; });

    return lines;
}

function runServer(commandOptions) {
  if (!commandOptions.log) {
    commandOptions.log = log;
  }
  commandOptions.killAfterChildSpawnedPromiseResolution = true;

  var openValue;
  if (typeof commandOptions.open !== 'undefined') {
    if (typeof commandOptions.open === 'boolean') {
      openValue = commandOptions.open ? "true" : "false";
    } else {
      openValue = commandOptions.open;
    }
    delete commandOptions.open;
  }

  return new Promise(function(resolve, reject) {
    return runCommand(
      path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'),
      'serve',
      openValue ? ('--open=' + openValue) : '',
      commandOptions
    )
    .then(function() {
      throw new Error('The server should not have exited successfully.');
    })
    .catch(function(err) {
      if (err.testingError) {
        return reject(err.testingError);
      }

      // This error was just caused by us having to kill the program
      return resolve();
    });
  });
}

function delay(ms) {
  return new Promise(function(resolve) {
    setTimeout(resolve, ms);
  });
}

describe('commands/serve', function () {
  before(function() {
    this.timeout(300000);
    process.chdir(targetApp);
    return runCommand('bower', 'install', { log: log })
    .then(function() {
      runCommand('npm', 'uninstall', 'ember-cli-open', { log: log });
    })
    .then(function() {
      runCommand('npm', 'install', { log: log });
    })
    .then(function() {
      runCommand('npm', 'install', '--save-dev', path.join('..', '..'), { log: log })
    });
  });

  after(function() {
    process.chdir(path.join('..', '..'));
  }),

  beforeEach(cleanFakeOpener);

  it('should be launched by default', function() {
    this.timeout(TIME_TO_WAIT_FOR_BUILD + TIME_TO_WAIT_FOR_STARTUP);
    return runServer({
      onChildSpawned: function () {
        return delay(TIME_TO_WAIT_FOR_BUILD).then(function () {
          var launches = getOpenerLaunches();
          expect(launches.length).to.equal(1, "Opener launched 1 time");
        });
      }
    });
  });

  it('should not be launched if open=false', function () {
    this.timeout(TIME_TO_WAIT_FOR_BUILD + TIME_TO_WAIT_FOR_STARTUP);
    return runServer({
      open: false,
      onChildSpawned: function () {
        return delay(TIME_TO_WAIT_FOR_BUILD).then(function () {
          var launches = getOpenerLaunches();
          expect(launches.length).to.equal(0, "Opener not launched");
        });
      }
    });
  });
});

describe('commands/serve with baseURL', function () {
  before(function() {
    this.timeout(300000);
    process.chdir('tests/dummy.with-base-url');
    return runCommand('bower', 'install', { log: log })
    .then(function() {
      runCommand('npm', 'uninstall', 'ember-cli-open', { log: log });
    })
    .then(function() {
      runCommand('npm', 'install', { log: log });
    })
    .then(function() {
      runCommand('npm', 'install', '--save-dev', path.join('..', '..'), { log: log })
    });
  });

  after(function() {
    process.chdir(path.join('..', '..'));
  }),

  beforeEach(cleanFakeOpener);

  it('should be launched by default', function() {
    this.timeout(TIME_TO_WAIT_FOR_BUILD + TIME_TO_WAIT_FOR_STARTUP);
    return runServer({
      onChildSpawned: function () {
        return delay(TIME_TO_WAIT_FOR_BUILD).then(function () {
          var launches = getOpenerLaunches();
          expect(launches.length).to.equal(1, "Opener launched 1 time");
          expect(launches[0]).to.equal('http://localhost:4200/custom-path/', "Opened with baseURL");
        });
      }
    });
  });
});
<|endoftext|>


<commit_before>/* globals blanket, module */

const options = {
  modulePrefix: 'ember-remodal',
  filter: '//.*ember-remodal/.*/',
  antifilter: '//.*(tests|template).*/',
  loaderExclusions: [],
  enableCoverage: true,
  cliOptions: {
    reporters: ['json', 'lcov'],
    autostart: true,
    lcovOptions: {
      outputFile: 'lcov.dat',
      excludeMissingFiles: true,

      renamer: function(moduleName) {
        var app = /^ember-remodal/;
        return moduleName.replace(app, 'app') + '.js';
      }
    }
  }
};
if (typeof exports === 'undefined') {
  blanket.options(options);
} else {
  module.exports = options;
}
<commit_msg>fixed file path for code coverage<commit_after>/* globals blanket, module */

const options = {
  modulePrefix: 'ember-remodal',
  filter: '//.*ember-remodal/.*/',
  antifilter: '//.*(tests|template).*/',
  loaderExclusions: [],
  enableCoverage: true,
  cliOptions: {
    reporters: ['json', 'lcov'],
    autostart: true,
    lcovOptions: {
      outputFile: 'lcov.dat',
      excludeMissingFiles: true,

      renamer: function(moduleName) {
        var app = /^ember-remodal/;
        return moduleName.replace(app, 'addon') + '.js';
      }
    }
  }
};
if (typeof exports === 'undefined') {
  blanket.options(options);
} else {
  module.exports = options;
}
<|endoftext|>


<commit_before>(function(root, wax) {
	// Set up Backbone appropriately for the environment. Start with AMD.
	if (typeof define === 'function' && define.amd) {
		define(['mustache'], function(mustache) {
			wax(mustache);
		});

	// Next for Node.js or CommonJS. jQuery may not be needed as a module.
	} else if (typeof exports !== 'undefined') {
		var mustache = require('mustache');
		wax(mustache);

	// Finally, as a browser global.
	} else {
		wax(root.Mustache);
	}
}(this, function Wax(Mustache) {
	Mustache.Formatters = {};

	/*
	 *	This will parse a parameter from a filter:
	 *
	 *      {{ vaue | filter : param1 : param2 : param3 }}
	 */
	Mustache.Context.prototype.parseParam = function parseParam(param) {
		var isString, isInteger, isFloat;
		isString  = /^[\'\"](.*)[\'\"]$/g;
		isInteger = /^[+-]?\d+$/g;
		isFloat   = /^[+-]?\d*\.\d+$/g;
		if (isString.test(param)) {
			return param.replace(isString, '$1');
		}
		if (isInteger.test(param)) {
			return parseInt(param, 10);
		}
		if (isFloat.test(param)) {
			return parseFloat(param);
		}
		return this._lookup(param);
	};

	/*
	 *	This function will resolve one filter# in the mustache expression:
	 *
	 *      {{ value | filter1 | filter2 | ... | filterN }}
	 */
	Mustache.Context.prototype.applyFilter = function applyFilter(expr, fltr) {
		var filterExp, paramsExp, match, filter, params = [expr];
		filterExp = /^\s*([^\:]+)/g;
		paramsExp = /\:\s*([\'][^\']*[\']|[\"][^\"]*[\"]|[^\:]+)\s*/g;
		match = filterExp.exec( fltr);
		filter = match[1].trim();
		while ((match = paramsExp.exec(fltr))) {
			params.push(this.parseParam(match[1].trim()));
		}
		//console.log( filter);
		//console.log( params);
		if (Mustache.Formatters.hasOwnProperty(filter)) {
			fltr = Mustache.Formatters[filter];
			return fltr.apply(fltr, params);
		}
		return expr;
	};

	/*
	 * Keep a copy of the original lookup function of Mustache
	 */
	Mustache.Context.prototype._lookup = Mustache.Context.prototype.lookup;

	/*
	 * Overwrite the Context::lookup method to add filter capabilities
	 */
	Mustache.Context.prototype.lookup =  function parseExpression(name) {
		var i, l, expression, formatters;
		formatters    = name.split("|");
		expression = formatters.shift().trim();
		//console.log(expression);
		expression = this._lookup(expression);
		for (i = 0, l = formatters.length; i < l; ++i) {
			expression = this.applyFilter(expression, formatters[i]);
		}
		return expression;
	};
}));<commit_msg>Fixed AMD when Mustache is loaded with a shim<commit_after>(function(root, wax) {
	// Set up appropriately for the environment. Start with AMD.
	if (typeof define === 'function' && define.amd) {
		define(['mustache'], function(mustache) {
			wax(mustache || root.Mustache);
		});

	// Next for Node.js or CommonJS.
	} else if (typeof exports !== 'undefined') {
		var mustache = require('mustache');
		wax(mustache);

	// Finally, as a browser global.
	} else {
		wax(root.Mustache);
	}
}(this, function Wax(Mustache) {
	Mustache.Formatters = {};

	/*
	 *	This will parse a parameter from a filter:
	 *
	 *      {{ vaue | filter : param1 : param2 : param3 }}
	 */
	Mustache.Context.prototype.parseParam = function parseParam(param) {
		var isString, isInteger, isFloat;
		isString  = /^[\'\"](.*)[\'\"]$/g;
		isInteger = /^[+-]?\d+$/g;
		isFloat   = /^[+-]?\d*\.\d+$/g;
		if (isString.test(param)) {
			return param.replace(isString, '$1');
		}
		if (isInteger.test(param)) {
			return parseInt(param, 10);
		}
		if (isFloat.test(param)) {
			return parseFloat(param);
		}
		return this._lookup(param);
	};

	/*
	 *	This function will resolve one filter# in the mustache expression:
	 *
	 *      {{ value | filter1 | filter2 | ... | filterN }}
	 */
	Mustache.Context.prototype.applyFilter = function applyFilter(expr, fltr) {
		var filterExp, paramsExp, match, filter, params = [expr];
		filterExp = /^\s*([^\:]+)/g;
		paramsExp = /\:\s*([\'][^\']*[\']|[\"][^\"]*[\"]|[^\:]+)\s*/g;
		match = filterExp.exec( fltr);
		filter = match[1].trim();
		while ((match = paramsExp.exec(fltr))) {
			params.push(this.parseParam(match[1].trim()));
		}
		//console.log( filter);
		//console.log( params);
		if (Mustache.Formatters.hasOwnProperty(filter)) {
			fltr = Mustache.Formatters[filter];
			return fltr.apply(fltr, params);
		}
		return expr;
	};

	/*
	 * Keep a copy of the original lookup function of Mustache
	 */
	Mustache.Context.prototype._lookup = Mustache.Context.prototype.lookup;

	/*
	 * Overwrite the Context::lookup method to add filter capabilities
	 */
	Mustache.Context.prototype.lookup =  function parseExpression(name) {
		var i, l, expression, formatters;
		formatters    = name.split("|");
		expression = formatters.shift().trim();
		//console.log(expression);
		expression = this._lookup(expression);
		for (i = 0, l = formatters.length; i < l; ++i) {
			expression = this.applyFilter(expression, formatters[i]);
		}
		return expression;
	};
}));
<|endoftext|>


<commit_before>/*
 * jquery.simulate - simulate browser mouse and keyboard events
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 */

;(function( $ ) {

$.fn.extend({
	simulate: function( type, options ) {
		return this.each(function() {
			var opt = $.extend( {}, $.simulate.defaults, options );
			new $.simulate( this, type, opt );
		});
	}
});

$.simulate = function( el, type, options ) {
	this.target = el;
	this.options = options;

	if ( type === "drag" ) {
		this[ type ].apply( this, [ this.target, options ] );
	} else if ( type === "focus" || type === "blur" ) {
		this[ type ]();
	} else {
		this.simulateEvent( el, type, options );
	}
};

$.extend( $.simulate.prototype, {
	simulateEvent: function( el, type, options ) {
		var evt = this.createEvent( type, options );
		this.dispatchEvent( el, type, evt, options );
		return evt;
	},
	createEvent: function( type, options ) {
		if ( /^mouse(over|out|down|up|move)|(dbl)?click$/.test( type ) ) {
			return this.mouseEvent( type, options );
		} else if ( /^key(up|down|press)$/.test( type ) ) {
			return this.keyboardEvent( type, options );
		}
	},
	mouseEvent: function( type, options ) {
		var evt;
		var e = $.extend({
			bubbles: true,
			cancelable: (type !== "mousemove"),
			view: window,
			detail: 0,
			screenX: 0,
			screenY: 0,
			clientX: 0,
			clientY: 0,
			ctrlKey: false,
			altKey: false,
			shiftKey: false,
			metaKey: false,
			button: 0,
			relatedTarget: undefined
		}, options );

		var relatedTarget = $( e.relatedTarget )[0];

		if ( $.isFunction( document.createEvent ) ) {
			evt = document.createEvent( "MouseEvents" );
			evt.initMouseEvent( type, e.bubbles, e.cancelable, e.view, e.detail,
				e.screenX, e.screenY, e.clientX, e.clientY,
				e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
				e.button, e.relatedTarget || document.body.parentNode );
		} else if ( document.createEventObject ) {
			evt = document.createEventObject();
			$.extend( evt, e );
			evt.button = { 0:1, 1:4, 2:2 }[evt.button] || evt.button;
		}
		return evt;
	},
	keyboardEvent: function( type, options ) {
		var evt;

		var e = $.extend({
			bubbles: true,
			cancelable: true,
			view: window,
			ctrlKey: false,
			altKey: false,
			shiftKey: false,
			metaKey: false,
			keyCode: 0,
			charCode: 0
		}, options );

		if ( $.isFunction( document.createEvent ) ) {
			try {
				evt = document.createEvent( "KeyEvents" );
				evt.initKeyEvent( type, e.bubbles, e.cancelable, e.view,
					e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
					e.keyCode, e.charCode );
			} catch( err ) {
				evt = document.createEvent( "Events" );
				evt.initEvent( type, e.bubbles, e.cancelable );
				$.extend(evt, {
					view: e.view,
					ctrlKey: e.ctrlKey,
					altKey: e.altKey,
					shiftKey: e.shiftKey,
					metaKey: e.metaKey,
					keyCode: e.keyCode,
					charCode: e.charCode
				});
			}
		} else if ( document.createEventObject ) {
			evt = document.createEventObject();
			$.extend( evt, e );
		}
		if ( $.browser.msie || $.browser.opera ) {
			evt.keyCode = (e.charCode > 0) ? e.charCode : e.keyCode;
			evt.charCode = undefined;
		}
		return evt;
	},

	dispatchEvent: function( el, type, evt ) {
		if ( el.dispatchEvent ) {
			el.dispatchEvent( evt );
		} else if ( el.fireEvent ) {
			el.fireEvent( "on" + type, evt );
		}
		return evt;
	},

	drag: function( el ) {
		var self = this,
			center = this.findCenter(this.target),
			options = this.options,
			x = Math.floor( center.x ),
			y = Math.floor( center.y ),
			dx = options.dx || 0,
			dy = options.dy || 0,
			target = this.target,
			coord = { clientX: x, clientY: y };
		this.simulateEvent( target, "mousedown", coord );
		coord = { clientX: x + 1, clientY: y + 1 };
		this.simulateEvent( document, "mousemove", coord );
		coord = { clientX: x + dx, clientY: y + dy };
		this.simulateEvent( document, "mousemove", coord );
		this.simulateEvent( document, "mousemove", coord );
		this.simulateEvent( target, "mouseup", coord );
		this.simulateEvent( target, "click", coord );
	},
	findCenter: function( el ) {
		var el = $( this.target ),
			o = el.offset(),
			d = $( document );
		return {
			x: o.left + el.outerWidth() / 2 - d.scrollLeft(),
			y: o.top + el.outerHeight() / 2 - d.scrollTop()
		};
	},

	focus: function() {
		var focusinEvent,
			triggered = false,
			element = $( this.target );

		function trigger() {
			triggered = true;
		}

		element.bind( "focus", trigger );
		element[ 0 ].focus();

		if ( !triggered ) {
			focusinEvent = $.Event( "focusin" );
			focusinEvent.preventDefault();
			element.trigger( focusinEvent );
			element.triggerHandler( "focus" );
		}
		element.unbind( "focus", trigger );
	},

	blur: function() {
		var focusoutEvent,
			triggered = false,
			element = $( this.target );

		function trigger() {
			triggered = true;
		}

		element.bind( "blur", trigger );
		element[ 0 ].blur();

		// Some versions of IE don't actually .blur() on an element - so we focus the body
		if ( element[ 0 ].ownerDocument.activeElement === element[ 0 ] ) {
			element[ 0 ].ownerDocument.body.focus();
		}

		if ( !triggered ) {
			focusoutEvent = $.Event( "focusout" );
			focusoutEvent.preventDefault();
			element.trigger( focusoutEvent );
			element.triggerHandler( "blur" );
		}
		element.unbind( "blur", trigger );
	}
});

$.extend( $.simulate, {
	defaults: {
		speed: "sync"
	},
	VK_TAB: 9,
	VK_ENTER: 13,
	VK_ESC: 27,
	VK_PGUP: 33,
	VK_PGDN: 34,
	VK_END: 35,
	VK_HOME: 36,
	VK_LEFT: 37,
	VK_UP: 38,
	VK_RIGHT: 39,
	VK_DOWN: 40
});

})( jQuery );
<commit_msg>Tests (Simulate): Make the blur event async to deal with IE's native blur being async.<commit_after>/*
 * jquery.simulate - simulate browser mouse and keyboard events
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 */

;(function( $ ) {

$.fn.extend({
	simulate: function( type, options ) {
		return this.each(function() {
			var opt = $.extend( {}, $.simulate.defaults, options );
			new $.simulate( this, type, opt );
		});
	}
});

$.simulate = function( el, type, options ) {
	this.target = el;
	this.options = options;

	if ( type === "drag" ) {
		this[ type ].apply( this, [ this.target, options ] );
	} else if ( type === "focus" || type === "blur" ) {
		this[ type ]();
	} else {
		this.simulateEvent( el, type, options );
	}
};

$.extend( $.simulate.prototype, {
	simulateEvent: function( el, type, options ) {
		var evt = this.createEvent( type, options );
		this.dispatchEvent( el, type, evt, options );
		return evt;
	},
	createEvent: function( type, options ) {
		if ( /^mouse(over|out|down|up|move)|(dbl)?click$/.test( type ) ) {
			return this.mouseEvent( type, options );
		} else if ( /^key(up|down|press)$/.test( type ) ) {
			return this.keyboardEvent( type, options );
		}
	},
	mouseEvent: function( type, options ) {
		var evt;
		var e = $.extend({
			bubbles: true,
			cancelable: (type !== "mousemove"),
			view: window,
			detail: 0,
			screenX: 0,
			screenY: 0,
			clientX: 0,
			clientY: 0,
			ctrlKey: false,
			altKey: false,
			shiftKey: false,
			metaKey: false,
			button: 0,
			relatedTarget: undefined
		}, options );

		var relatedTarget = $( e.relatedTarget )[0];

		if ( $.isFunction( document.createEvent ) ) {
			evt = document.createEvent( "MouseEvents" );
			evt.initMouseEvent( type, e.bubbles, e.cancelable, e.view, e.detail,
				e.screenX, e.screenY, e.clientX, e.clientY,
				e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
				e.button, e.relatedTarget || document.body.parentNode );
		} else if ( document.createEventObject ) {
			evt = document.createEventObject();
			$.extend( evt, e );
			evt.button = { 0:1, 1:4, 2:2 }[evt.button] || evt.button;
		}
		return evt;
	},
	keyboardEvent: function( type, options ) {
		var evt;

		var e = $.extend({
			bubbles: true,
			cancelable: true,
			view: window,
			ctrlKey: false,
			altKey: false,
			shiftKey: false,
			metaKey: false,
			keyCode: 0,
			charCode: 0
		}, options );

		if ( $.isFunction( document.createEvent ) ) {
			try {
				evt = document.createEvent( "KeyEvents" );
				evt.initKeyEvent( type, e.bubbles, e.cancelable, e.view,
					e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
					e.keyCode, e.charCode );
			} catch( err ) {
				evt = document.createEvent( "Events" );
				evt.initEvent( type, e.bubbles, e.cancelable );
				$.extend(evt, {
					view: e.view,
					ctrlKey: e.ctrlKey,
					altKey: e.altKey,
					shiftKey: e.shiftKey,
					metaKey: e.metaKey,
					keyCode: e.keyCode,
					charCode: e.charCode
				});
			}
		} else if ( document.createEventObject ) {
			evt = document.createEventObject();
			$.extend( evt, e );
		}
		if ( $.browser.msie || $.browser.opera ) {
			evt.keyCode = (e.charCode > 0) ? e.charCode : e.keyCode;
			evt.charCode = undefined;
		}
		return evt;
	},

	dispatchEvent: function( el, type, evt ) {
		if ( el.dispatchEvent ) {
			el.dispatchEvent( evt );
		} else if ( el.fireEvent ) {
			el.fireEvent( "on" + type, evt );
		}
		return evt;
	},

	drag: function( el ) {
		var self = this,
			center = this.findCenter(this.target),
			options = this.options,
			x = Math.floor( center.x ),
			y = Math.floor( center.y ),
			dx = options.dx || 0,
			dy = options.dy || 0,
			target = this.target,
			coord = { clientX: x, clientY: y };
		this.simulateEvent( target, "mousedown", coord );
		coord = { clientX: x + 1, clientY: y + 1 };
		this.simulateEvent( document, "mousemove", coord );
		coord = { clientX: x + dx, clientY: y + dy };
		this.simulateEvent( document, "mousemove", coord );
		this.simulateEvent( document, "mousemove", coord );
		this.simulateEvent( target, "mouseup", coord );
		this.simulateEvent( target, "click", coord );
	},
	findCenter: function( el ) {
		var el = $( this.target ),
			o = el.offset(),
			d = $( document );
		return {
			x: o.left + el.outerWidth() / 2 - d.scrollLeft(),
			y: o.top + el.outerHeight() / 2 - d.scrollTop()
		};
	},

	focus: function() {
		var focusinEvent,
			triggered = false,
			element = $( this.target );

		function trigger() {
			triggered = true;
		}

		element.bind( "focus", trigger );
		element[ 0 ].focus();

		if ( !triggered ) {
			focusinEvent = $.Event( "focusin" );
			focusinEvent.preventDefault();
			element.trigger( focusinEvent );
			element.triggerHandler( "focus" );
		}
		element.unbind( "focus", trigger );
	},

	blur: function() {
		var focusoutEvent,
			triggered = false,
			element = $( this.target );

		function trigger() {
			triggered = true;
		}

		element.bind( "blur", trigger );
		element[ 0 ].blur();

		// blur events are async in IE
		setTimeout(function() {
			// IE won't let the blur occur if the window is inactive
			if ( element[ 0 ].ownerDocument.activeElement === element[ 0 ] ) {
				element[ 0 ].ownerDocument.body.focus();
			}

			// Firefox won't trigger events if the window is inactive
			// IE doesn't trigger events if we had to manually focus the body
			if ( !triggered ) {
				focusoutEvent = $.Event( "focusout" );
				focusoutEvent.preventDefault();
				element.trigger( focusoutEvent );
				element.triggerHandler( "blur" );
			}
			element.unbind( "blur", trigger );
		}, 1 );
	}
});

$.extend( $.simulate, {
	defaults: {
		speed: "sync"
	},
	VK_TAB: 9,
	VK_ENTER: 13,
	VK_ESC: 27,
	VK_PGUP: 33,
	VK_PGDN: 34,
	VK_END: 35,
	VK_HOME: 36,
	VK_LEFT: 37,
	VK_UP: 38,
	VK_RIGHT: 39,
	VK_DOWN: 40
});

})( jQuery );
<|endoftext|>


<commit_before>
beforeEach(function() {

	jasmine.addMatchers({
		toEqualMoment: function() {
			return {
				compare: function(actual, expected) {
					var actualStr = $.fullCalendar.moment.parseZone(actual).format();
					var expectedStr = $.fullCalendar.moment.parseZone(expected).format();
					var result = {
						pass: actualStr === expectedStr
					};
					if (!result.pass) {
						result.message = 'Moment ' + actualStr + ' does not equal ' + expectedStr;
					}
					return result;
				}
			};
		},
		toEqualNow: function() {
			return {
				compare: function(actual) {
					var actualMoment = $.fullCalendar.moment.parseZone(actual);
					var result = {
						pass: Math.abs(actualMoment - new Date()) < 1000 // within a second of current datetime
					};
					if (!result.pass) {
						result.message = 'Moment ' + actualMoment.format() + ' is not close enough to now';
					}
					return result;
				}
			};
		},
		toEqualDuration: function() {
			return {
				compare: function(actual, expected) {
					var actualStr = serializeDuration(moment.duration(actual));
					var expectedStr = serializeDuration(moment.duration(expected));
					var result = {
						pass: actualStr === expectedStr
					};
					if (!result.pass) {
						result.message = 'Duration ' + actualStr + ' does not equal ' + expectedStr;
					}
					return result;
				}
			};
		}
	});

	function serializeDuration(duration) {
		return Math.floor(duration.asDays()) + '.' +
			pad(duration.hours(), 2) + ':' +
			pad(duration.minutes(), 2) + ':' +
			pad(duration.seconds(), 2) + '.' +
			pad(duration.milliseconds(), 3);
	}

	function pad(n, width) {
		n = n + '';
		return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
	}

});
<commit_msg>moment-2.8 compatibility, automated tests, suppress warnings<commit_after>
beforeEach(function() {

	// don't show warnings about deprecated methods like `moment.lang`, etc.
	// at some point we'll require moment version above 2.8.
	// until then, it's too annoying to support two versions.
	// (not the best place for this)
	moment.suppressDeprecationWarnings = true;

	jasmine.addMatchers({
		toEqualMoment: function() {
			return {
				compare: function(actual, expected) {
					var actualStr = $.fullCalendar.moment.parseZone(actual).format();
					var expectedStr = $.fullCalendar.moment.parseZone(expected).format();
					var result = {
						pass: actualStr === expectedStr
					};
					if (!result.pass) {
						result.message = 'Moment ' + actualStr + ' does not equal ' + expectedStr;
					}
					return result;
				}
			};
		},
		toEqualNow: function() {
			return {
				compare: function(actual) {
					var actualMoment = $.fullCalendar.moment.parseZone(actual);
					var result = {
						pass: Math.abs(actualMoment - new Date()) < 1000 // within a second of current datetime
					};
					if (!result.pass) {
						result.message = 'Moment ' + actualMoment.format() + ' is not close enough to now';
					}
					return result;
				}
			};
		},
		toEqualDuration: function() {
			return {
				compare: function(actual, expected) {
					var actualStr = serializeDuration(moment.duration(actual));
					var expectedStr = serializeDuration(moment.duration(expected));
					var result = {
						pass: actualStr === expectedStr
					};
					if (!result.pass) {
						result.message = 'Duration ' + actualStr + ' does not equal ' + expectedStr;
					}
					return result;
				}
			};
		}
	});

	function serializeDuration(duration) {
		return Math.floor(duration.asDays()) + '.' +
			pad(duration.hours(), 2) + ':' +
			pad(duration.minutes(), 2) + ':' +
			pad(duration.seconds(), 2) + '.' +
			pad(duration.milliseconds(), 3);
	}

	function pad(n, width) {
		n = n + '';
		return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
	}

});
<|endoftext|>


<commit_before>import glob from 'glob';
import React from 'react';
import { render } from 'enzyme';
import { renderToJson } from 'enzyme-to-json';
import renderer from 'react-test-renderer';
import MockDate from 'mockdate';

export function webDemoTest(component, options = {}) {
  const files = glob.sync(`./components/${component}/demo/*.md`);

  files.forEach((file) => {
    let testMethod = options.skip === true ? test.skip : test;
    if (Array.isArray(options.skip) && options.skip.some(c => file.includes(c))) {
      testMethod = test.skip;
    }
    testMethod(`renders ${file} correctly`, () => {
      // https://github.com/boblauer/MockDate#api
      MockDate.set('11/22/2016', new Date().getTimezoneOffset());
      const demo = require(`../.${file}`); // eslint-disable-line global-require, import/no-dynamic-require
      const wrapper = render(demo);
      expect(renderToJson(wrapper)).toMatchSnapshot();
      MockDate.reset();
    });
  });
}

export function rnDemoTest(component, options = {}) {
  const files = glob.sync(`./components/${component}/demo/*.tsx`);

  files.forEach((file) => {
    let testMethod = options.skip === true ? test.skip : test;
    if (Array.isArray(options.skip) && options.skip.some(c => file.includes(c))) {
      testMethod = test.skip;
    }

    testMethod(`renders ${file} correctly`, () => {
      let Demo = require(`../.${file}`); // eslint-disable-line global-require, import/no-dynamic-require
      Demo = Demo.default || Demo;
      const tree = renderer.create(<Demo />).toJSON();
      expect(tree).toMatchSnapshot();
    });
  });
}
<commit_msg>fix: test<commit_after>import glob from 'glob';
import React from 'react';
import { render } from 'enzyme';
import { renderToJson } from 'enzyme-to-json';
import renderer from 'react-test-renderer';
import MockDate from 'mockdate';

export function webDemoTest(component, options = {}) {
  const files = glob.sync(`./components/${component}/demo/*.md`);

  files.forEach((file) => {
    let testMethod = options.skip === true ? test.skip : test;
    if (Array.isArray(options.skip) && options.skip.some(c => file.includes(c))) {
      testMethod = test.skip;
    }
    testMethod(`renders ${file} correctly`, () => {
      // https://github.com/boblauer/MockDate#api
      MockDate.set('11/22/2016', -480);
      const demo = require(`../.${file}`); // eslint-disable-line global-require, import/no-dynamic-require
      const wrapper = render(demo);
      expect(renderToJson(wrapper)).toMatchSnapshot();
      MockDate.reset();
    });
  });
}

export function rnDemoTest(component, options = {}) {
  const files = glob.sync(`./components/${component}/demo/*.tsx`);

  files.forEach((file) => {
    let testMethod = options.skip === true ? test.skip : test;
    if (Array.isArray(options.skip) && options.skip.some(c => file.includes(c))) {
      testMethod = test.skip;
    }

    testMethod(`renders ${file} correctly`, () => {
      let Demo = require(`../.${file}`); // eslint-disable-line global-require, import/no-dynamic-require
      Demo = Demo.default || Demo;
      const tree = renderer.create(<Demo />).toJSON();
      expect(tree).toMatchSnapshot();
    });
  });
}
<|endoftext|>


<commit_before>
/* Get transfer key */
function get_transferkey(cid, apicode, callback) {
	var undefined,
	    https = require('https'),
		transferkey = '',
	    options = {
			host: 'www.trustpoint.fi',
			port: 443,
			path: '/API/requirekey.php',
			method: 'POST',
			headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			},
	    req = https.request(options, function(res) { // Handles response
			console.log("statusCode: ", res.statusCode);
			console.log("headers: ", res.headers);
			res.on('data', function(d) {
				transferkey += d;
			});
			res.on('end', function() {
				callback(undefined, transferkey);
			});
		});

	req.end('cid='+encodeURIComponent(cid)+'&apicode='+encodeURIComponent(apicode));

	req.on('error', function(e) {
		callback("Getting transferkey failed: " + e);
	});
}

/* Insert invoice */
function insert_invoice(cid, apicode, callback) {
	get_transferkey(config.cid, config.apicode, function(err, transferkey) {
		if(err) throw new Error("Error: " + err);
		console.log("received transferkey: " + transferkey + "\n");

	});
}

// Main
(function() {
	var config = require('./config.js');

})();
<commit_msg>Updated<commit_after>
/* Foreach every element in array, object or the element itself if neither */
function foreach(values) {

    if(!values) return do_single();
    if(typeof values != 'object') return do_single();
    if(values instanceof Array) return do_array();
    return do_obj();

    function do_single() {
        return {'do': function(f) { f(values);}};
    }

    function do_array() {
        var i=0, length=values.length;
        return {'do': function(f) { for(; i<length; ++i) f(values[i], i); }};
    }

    function do_obj() {
        var i;
        return {'do': function(f) { for(i in values) if(values.hasOwnProperty(i)) f(values[i], i); }};
    }
}

/* Constructor */
function Trustpoint(cid, apicode) {
	if(!(this instanceof arguments.callee)) return new (arguments.callee)(args);
	var undefined, trust = this;
	trust.cid = cid;
	trust.apicode = apicode;
	trust.transferkey = undefined;
}

/* Get transfer key */
Trustpoint.prototype.requirekey = function(cid, apicode, callback) {
	var trust = this;

	// Use cached transferkey if it exists
	if(trust.transferkey) {
		callback(undefined, trust.transferkey);
		return trust;
	}

	// Get fresh transferkey from Trustpoint
	var undefined,
	    https = require('https'),
		transferkey = '',
	    options = {
			host: 'www.trustpoint.fi',
			port: 443,
			path: '/API/requirekey.php',
			method: 'POST',
			headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			},
	    req = https.request(options, function(res) { // Handles response
			console.log("statusCode: ", res.statusCode);
			console.log("headers: ", res.headers);
			res.on('data', function(d) {
				transferkey += d;
			});
			res.on('end', function() {
				trust.transferkey = transferkey;
				callback(undefined, transferkey);
			});
		});

	req.end('cid='+encodeURIComponent(cid)+'&apicode='+encodeURIComponent(apicode));

	req.on('error', function(e) {
		callback("Getting transferkey failed: " + e);
	});
}

/* Commit transfer */
Trustpoint.prototype.committransfer = function(callback) {
	var trust = this;
	trust.requirekey(trust.cid, trust.apicode, function(err, transferkey) {
		if(err) throw new Error("Error: " + err);
		console.log("transferkey: " + transferkey + "\n");

		var undefined,
		    https = require('https'),
			results = '',
		    options = {
				host: 'www.trustpoint.fi',
				port: 443,
				path: '/API/committransfer.php',
				method: 'POST',
				headers: {'Content-Type': 'application/xml'}
				},
		    req = https.request(options, function(res) { // Handles response
				console.log("statusCode: ", res.statusCode);
				console.log("headers: ", res.headers);
				res.on('data', function(d) {
					results += d;
				});
				res.on('end', function() {
					callback(undefined, transferkey);
				});
			});

		req.end('');

		req.on('error', function(e) {
			callback("Getting transferkey failed: " + e);
		});
	});
	return trust;
}

/* Get XML message from a JSON string */
Trustpoint._xml_req = function(args) {

	var _dataset_date_keywords = ['billdate', 'paydate', 'noticedate'];
	var _dataset_keywords = ['custnum', 'billnum', 'billcode', 'name', 'address', 'postcode', 'city', 'customaddress', 'customertype', 'jobtype', 'govid', 'amount', 'operator'];

	var _required_dataset_keys = ['name', 'address', 'postcode', 'city', 'customertype', 'jobtype', 'amount'];

	/* Escape string for XML */
	function escape_xml (str) {
	    return (""+str).replace(/&/g, "&")
	               .replace(/"/g, """)
	               .replace(/"/g, """)
	               .replace(/</g, "<")
	               .replace(/>/g, ">")
	               .replace(/'/g, "'");
	}

	var trust = this,
	    args = args || {},
	    transferkey = args.transferkey,
	    operator = args.operator,
	    dataset = args.dataset || [],
	    xml = '';

	if(!transferkey) throw new Error("No transferkey!");

	xml += '<datastream>\n';
	xml += ' <transferkey>'+escape_xml(transferkey)+'</transferkey>\n';
	if(debug) xml += ' <debug>true</debug>\n';
	if(operator) xml += ' <operator>'+escape_xml(operator)+'</operator>\n';
	foreach(operator.dataset).do(function(data) {
		xml += ' <dataset>\n';
		foreach(_dataset_keywords).do(function(key) {
			if(dataset[key]) xml += '  <'+key+'>'+escape_xml(dataset[key])+'</'+key+'>\n';
		});
		foreach(_dataset_date_keywords).do(function(key) {
			function format(value) {
				function format_date(date) {
					function d(n) { return (((""+n).length <= 1) ? "0" : "") + n; }
					return date.getFullYear() + "-" + d(date.getMonth()+1) + "-" + d(date.getDate());
				}
				if(value instanceof Date) return format_date(value);
				if((""+value).match(/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$/)) {
					return ""+value;
				}
				throw new Error("date value invalid: " + value);
			}
			if(!dataset[key]) return;
			xml += '  <'+key+'>'+escape_xml(format(dataset[key]))+'</'+key+'>\n';
		});
		xml += ' </dataset>\n';
	});
	xml += '</datastream>';
	return xml;
}

// Main
(function() {
	var config = require('./config.js');
	var trust = new Trustpoint(config.cid, config.apicode);
	console.log(trust._xml_req({
		'transferkey':'test',
		'debug':true,
		'operator':12345,
		'dataset':[
			{
				'custnum':227,
				'billnum':1224,
				'billcode':'2270012240',
				'name':'Teemu Testi',
				'address':'Testikatu 74',
				'postcode':13101,
				'city':'Hämeenlinna',
				'customertype':1,
				'jobtype':2,
				'govid':'12345678-9',
				'billdate':'2009-11-01',
				'paydate':'2009-11-15',
				'noticedate':'2009-11-29',
				'amount':1250.50,
			}
		]});
})();
<|endoftext|>


<commit_before>/*globals initTestDB: false, emit: true, generateAdapterUrl: false */
/*globals PERSIST_DATABASES: false, initDBPair: false, utils: true, putAfter: false */
/*globals ajax: true, LevelPouch: true, makeDocs: false */

"use strict";

var adapter = 'local-1';
var qunit = module;

// if we are running under node.js, set things up
// a little differently, and only test the leveldb adapter
if (typeof module !== undefined && module.exports) {
  Pouch = require('../src/pouch.js');
  LevelPouch = require('../src/adapters/pouch.leveldb.js');
  utils = require('./test.utils.js');

  for (var k in utils) {
    global[k] = global[k] || utils[k];
  }
  qunit = QUnit.module;
}

qunit('compaction: ' + adapter, {
  setup : function () {
    this.name = generateAdapterUrl(adapter);
  },
  teardown: function() {
    if (!PERSIST_DATABASES) {
      Pouch.destroy(this.name);
    }
  }
});

asyncTest('Simple compation test', function() {
  initTestDB(this.name, function(err, db) {
    var doc = {_id: "foo", value: "bar"};

    db.post(doc, function(err, res) {
      var rev1 = res.rev;
      doc._rev = rev1;
      doc.value = "baz";
      db.post(doc, function(err, res) {
        var rev2 = res.rev;
        db.compact(function(){
          ok(true, "compaction finished");
          db.get("foo", {rev: rev1}, function(err, doc){
            ok(err.status === 404 && err.error === "not_found", "compacted document is missing");
            db.get("foo", {rev: rev2}, function(err, doc){
              ok(!err, "newest revision does not get compacted");
              start();
            });
          });
        });
      });
    });
  });
});

// docs will be inserted one after another
// starting from root
var insertBranch = function(db, docs, callback) {
  function insert(i) {
    var prev = i > 0 ? docs[i-1]._rev : null;
    putAfter(db, docs[i], prev, function() {
      if (i < docs.length - 1) {
        insert(i+1);
      } else {
        callback();
      }
    });
  }
  insert(0);
};

var checkBranch = function(db, docs, callback) {
  function check(i) {
    var doc = docs[i];
    db.get(doc._id, {rev: doc._rev}, function(err, doc) {
      if (i < docs.length - 1) {
        ok(err.status === 404, "compacted!");
        check(i+1);
      } else {
        ok(!err, "not compacted!");
        callback();
      }
    });
  }
  check(0);
};

var checkTree = function(db, tree, callback) {
  function check(i) {
    checkBranch(db, tree[i], function() {
      if (i < tree.length - 1) {
        check(i + 1);
      } else {
        callback();
      }
    });
  }
  check(0);
};

var putTree = function(db, tree, callback) {
  function insert(i) {
    var branch = tree[i];
    insertBranch(db, branch, function() {
      if (i < tree.length - 1) {
        insert(i+1);
      } else {
        callback();
      }
    });
  }
  insert(0);
};

var exampleTree = [
  [
    {_id: "foo", _rev: "1-a", value: "foo a"},
    {_id: "foo", _rev: "2-b", value: "foo b"},
    {_id: "foo", _rev: "3-c", value: "foo c"}
  ],
  [
    {_id: "foo", _rev: "1-a", value: "foo a"},
    {_id: "foo", _rev: "2-d", value: "foo d"},
    {_id: "foo", _rev: "3-e", value: "foo e"},
    {_id: "foo", _rev: "4-f", value: "foo f"}
  ],
  [
    {_id: "foo", _rev: "1-a", value: "foo a"},
    {_id: "foo", _rev: "2-g", value: "foo g"},
    {_id: "foo", _rev: "3-h", value: "foo h"},
    {_id: "foo", _rev: "4-i", value: "foo i"},
    {_id: "foo", _rev: "5-j", _deleted: true, value: "foo j"}
  ]
];

var exampleTree2 = [
  [
    {_id: "bar", _rev: "1-m", value: "bar m"},
    {_id: "bar", _rev: "2-n", value: "bar n"},
    {_id: "bar", _rev: "3-o", _deleted: true, value: "foo o"}
  ],
  [
    {_id: "bar", _rev: "2-n", value: "bar n"},
    {_id: "bar", _rev: "3-p", value: "bar p"},
    {_id: "bar", _rev: "4-r", value: "bar r"},
    {_id: "bar", _rev: "5-s", value: "bar s"}
  ],
  [
    {_id: "bar", _rev: "3-p", value: "bar p"},
    {_id: "bar", _rev: "4-t", value: "bar t"},
    {_id: "bar", _rev: "5-u", value: "bar u"}
  ]
];

asyncTest('Compact more complicated tree', function() {
  initTestDB(this.name, function(err, db) {
    putTree(db, exampleTree, function() {
      db.compact(function() {
        checkTree(db, exampleTree, function() {
          ok(1, "checks finished");
          start();
        });
      });
    });
  });
});

asyncTest('Compact two times more complicated tree', function() {
  initTestDB(this.name, function(err, db) {
    putTree(db, exampleTree, function() {
      db.compact(function() {
        db.compact(function() {
          checkTree(db, exampleTree, function() {
            ok(1, "checks finished");
            start();
          });
        });
      });
    });
  });
});

asyncTest('Compact database with at least two documents', function() {
  initTestDB(this.name, function(err, db) {
    putTree(db, exampleTree, function() {
      putTree(db, exampleTree2, function() {
        db.compact(function() {
          checkTree(db, exampleTree, function() {
            checkTree(db, exampleTree2, function() {
              ok(1, "checks finished");
              start();
            });
          });
        });
      });
    });
  });
});
<commit_msg>(#114) - new compaction tests<commit_after>/*globals initTestDB: false, emit: true, generateAdapterUrl: false */
/*globals PERSIST_DATABASES: false, initDBPair: false, utils: true, putAfter: false */
/*globals ajax: true, LevelPouch: true, makeDocs: false */

"use strict";

var adapter = 'local-1';
var qunit = module;

// if we are running under node.js, set things up
// a little differently, and only test the leveldb adapter
if (typeof module !== undefined && module.exports) {
  Pouch = require('../src/pouch.js');
  LevelPouch = require('../src/adapters/pouch.leveldb.js');
  utils = require('./test.utils.js');

  for (var k in utils) {
    global[k] = global[k] || utils[k];
  }
  qunit = QUnit.module;
}

qunit('compaction: ' + adapter, {
  setup : function () {
    this.name = generateAdapterUrl(adapter);
  },
  teardown: function() {
    if (!PERSIST_DATABASES) {
      Pouch.destroy(this.name);
    }
  }
});

asyncTest('Compation document with no revisions to remove', function() {
  initTestDB(this.name, function(err, db) {
    var doc = {_id: "foo", value: "bar"};
    db.put(doc, function(err, res) {
      db.compact(function(){
        ok(true, "compaction finished");
        db.get("foo", function(err, doc) {
          ok(!err, "document not deleted");
          start();
        });
      });
    });
  });
});

asyncTest('Simple compation test', function() {
  initTestDB(this.name, function(err, db) {
    var doc = {_id: "foo", value: "bar"};

    db.post(doc, function(err, res) {
      var rev1 = res.rev;
      doc._rev = rev1;
      doc.value = "baz";
      db.post(doc, function(err, res) {
        var rev2 = res.rev;
        db.compact(function(){
          ok(true, "compaction finished");
          db.get("foo", {rev: rev1}, function(err, doc){
            ok(err.status === 404 && err.error === "not_found", "compacted document is missing");
            db.get("foo", {rev: rev2}, function(err, doc){
              ok(!err, "newest revision does not get compacted");
              start();
            });
          });
        });
      });
    });
  });
});

// docs will be inserted one after another
// starting from root
var insertBranch = function(db, docs, callback) {
  function insert(i) {
    var prev = i > 0 ? docs[i-1]._rev : null;
    putAfter(db, docs[i], prev, function() {
      if (i < docs.length - 1) {
        insert(i+1);
      } else {
        callback();
      }
    });
  }
  insert(0);
};

var checkBranch = function(db, docs, callback) {
  function check(i) {
    var doc = docs[i];
    db.get(doc._id, {rev: doc._rev}, function(err, doc) {
      if (i < docs.length - 1) {
        ok(err.status === 404, "compacted!");
        check(i+1);
      } else {
        ok(!err, "not compacted!");
        callback();
      }
    });
  }
  check(0);
};

var checkTree = function(db, tree, callback) {
  function check(i) {
    checkBranch(db, tree[i], function() {
      if (i < tree.length - 1) {
        check(i + 1);
      } else {
        callback();
      }
    });
  }
  check(0);
};

var putTree = function(db, tree, callback) {
  function insert(i) {
    var branch = tree[i];
    insertBranch(db, branch, function() {
      if (i < tree.length - 1) {
        insert(i+1);
      } else {
        callback();
      }
    });
  }
  insert(0);
};

var exampleTree = [
  [
    {_id: "foo", _rev: "1-a", value: "foo a"},
    {_id: "foo", _rev: "2-b", value: "foo b"},
    {_id: "foo", _rev: "3-c", value: "foo c"}
  ],
  [
    {_id: "foo", _rev: "1-a", value: "foo a"},
    {_id: "foo", _rev: "2-d", value: "foo d"},
    {_id: "foo", _rev: "3-e", value: "foo e"},
    {_id: "foo", _rev: "4-f", value: "foo f"}
  ],
  [
    {_id: "foo", _rev: "1-a", value: "foo a"},
    {_id: "foo", _rev: "2-g", value: "foo g"},
    {_id: "foo", _rev: "3-h", value: "foo h"},
    {_id: "foo", _rev: "4-i", value: "foo i"},
    {_id: "foo", _rev: "5-j", _deleted: true, value: "foo j"}
  ]
];

var exampleTree2 = [
  [
    {_id: "bar", _rev: "1-m", value: "bar m"},
    {_id: "bar", _rev: "2-n", value: "bar n"},
    {_id: "bar", _rev: "3-o", _deleted: true, value: "foo o"}
  ],
  [
    {_id: "bar", _rev: "2-n", value: "bar n"},
    {_id: "bar", _rev: "3-p", value: "bar p"},
    {_id: "bar", _rev: "4-r", value: "bar r"},
    {_id: "bar", _rev: "5-s", value: "bar s"}
  ],
  [
    {_id: "bar", _rev: "3-p", value: "bar p"},
    {_id: "bar", _rev: "4-t", value: "bar t"},
    {_id: "bar", _rev: "5-u", value: "bar u"}
  ]
];

asyncTest('Compact more complicated tree', function() {
  initTestDB(this.name, function(err, db) {
    putTree(db, exampleTree, function() {
      db.compact(function() {
        checkTree(db, exampleTree, function() {
          ok(1, "checks finished");
          start();
        });
      });
    });
  });
});

asyncTest('Compact two times more complicated tree', function() {
  initTestDB(this.name, function(err, db) {
    putTree(db, exampleTree, function() {
      db.compact(function() {
        db.compact(function() {
          checkTree(db, exampleTree, function() {
            ok(1, "checks finished");
            start();
          });
        });
      });
    });
  });
});

asyncTest('Compact database with at least two documents', function() {
  initTestDB(this.name, function(err, db) {
    putTree(db, exampleTree, function() {
      putTree(db, exampleTree2, function() {
        db.compact(function() {
          checkTree(db, exampleTree, function() {
            checkTree(db, exampleTree2, function() {
              ok(1, "checks finished");
              start();
            });
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>"use strict";

const fs = require("fs");
const extname = require("path").extname;
const prettier = require("../");
const types = require("../src/ast-types");
const parser = require("../src/parser");
const massageAST = require('../src/clean-ast.js').massageAST;

const RUN_AST_TESTS = process.env["AST_COMPARE"];
const VERIFY_ALL_PARSERS = process.env["VERIFY_ALL_PARSERS"] || false;
const ALL_PARSERS = process.env["ALL_PARSERS"]
  ? JSON.parse(process.env["ALL_PARSERS"])
  : ["flow", "babylon", "typescript"];

function run_spec(dirname, options, additionalParsers) {
  fs.readdirSync(dirname).forEach(filename => {
    const extension = extname(filename);
    if (/^\.[jt]sx?$/.test(extension) && filename !== "jsfmt.spec.js") {
      const path = dirname + "/" + filename;
      const mergedOptions = mergeDefaultOptions(options || {});

      if (!RUN_AST_TESTS) {
        const source = read(path).replace(/\r\n/g, "\n");
        const output = prettyprint(source, path, mergedOptions);
        test(`${mergedOptions.parser} - ${parser.parser}-verify`, () => {
          expect(raw(source + "~".repeat(80) + "\n" + output)).toMatchSnapshot(
            filename
          );
        });

        getParsersToVerify(
          mergedOptions.parser,
          additionalParsers || []
        ).forEach(parserName => {
          test(`${filename} - ${parserName}-verify`, () => {
            const verifyOptions = Object.assign(mergedOptions, {
              parser: parserName
            });
            const verifyOutput = prettyprint(source, path, verifyOptions);
            expect(output).toEqual(verifyOutput);
          });
        });
      }

      if (RUN_AST_TESTS) {
        const source = read(dirname + "/" + filename);
        const ast = parse(source, mergedOptions);
        const astMassaged = massageAST(ast);
        let ppastMassaged;
        let pperr = null;
        try {
          const ppast = parse(prettyprint(source, path, mergedOptions), mergedOptions)
          ppastMassaged = massageAST(ppast);
        } catch (e) {
          pperr = e.stack;
        }

        test(path + " parse", () => {
          expect(pperr).toBe(null);
          expect(ppastMassaged).toBeDefined();
          if (!ast.errors || ast.errors.length === 0) {
            expect(astMassaged).toEqual(ppastMassaged);
          }
        });
      }
    }
  });
}
global.run_spec = run_spec;

function stripLocation(ast) {
  if (Array.isArray(ast)) {
    return ast.map(e => stripLocation(e));
  }
  if (typeof ast === "object") {
    const newObj = {};
    for (var key in ast) {
      if (
        key === "loc" || key === "range" || key === "raw" || key === "comments"
      ) {
        continue;
      }
      newObj[key] = stripLocation(ast[key]);
    }
    return newObj;
  }
  return ast;
}

function parse(string, opts) {
  return stripLocation(parser.parse(string, opts));
}

function prettyprint(src, filename, options) {
  return prettier.format(
    src,
    Object.assign(
      {
        filename
      },
      options
    )
  );
}

function read(filename) {
  return fs.readFileSync(filename, "utf8");
}

/**
 * Wraps a string in a marker object that is used by `./raw-serializer.js` to
 * directly print that string in a snapshot without escaping all double quotes.
 * Backticks will still be escaped.
 */
function raw(string) {
  if (typeof string !== "string") {
    throw new Error("Raw snapshots have to be strings.");
  }
  return { [Symbol.for("raw")]: string };
}

function mergeDefaultOptions(parserConfig) {
  return Object.assign(
    {
      parser: "flow",
      printWidth: 80
    },
    parserConfig
  );
}

function getParsersToVerify(parser, additionalParsers) {
  if (VERIFY_ALL_PARSERS) {
    return ALL_PARSERS.splice(ALL_PARSERS.indexOf(parser), 1);
  }
  return additionalParsers;
}
<commit_msg>Also run normal tests when AST_COMPARE=1 (#1561)<commit_after>"use strict";

const fs = require("fs");
const extname = require("path").extname;
const prettier = require("../");
const types = require("../src/ast-types");
const parser = require("../src/parser");
const massageAST = require('../src/clean-ast.js').massageAST;

const RUN_AST_TESTS = process.env["AST_COMPARE"];
const VERIFY_ALL_PARSERS = process.env["VERIFY_ALL_PARSERS"] || false;
const ALL_PARSERS = process.env["ALL_PARSERS"]
  ? JSON.parse(process.env["ALL_PARSERS"])
  : ["flow", "babylon", "typescript"];

function run_spec(dirname, options, additionalParsers) {
  fs.readdirSync(dirname).forEach(filename => {
    const extension = extname(filename);
    if (/^\.[jt]sx?$/.test(extension) && filename !== "jsfmt.spec.js") {
      const path = dirname + "/" + filename;
      const mergedOptions = mergeDefaultOptions(options || {});

      const source = read(path).replace(/\r\n/g, "\n");
      const output = prettyprint(source, path, mergedOptions);
      test(`${mergedOptions.parser} - ${parser.parser}-verify`, () => {
        expect(raw(source + "~".repeat(80) + "\n" + output)).toMatchSnapshot(
          filename
        );
      });

      getParsersToVerify(
        mergedOptions.parser,
        additionalParsers || []
      ).forEach(parserName => {
        test(`${filename} - ${parserName}-verify`, () => {
          const verifyOptions = Object.assign(mergedOptions, {
            parser: parserName
          });
          const verifyOutput = prettyprint(source, path, verifyOptions);
          expect(output).toEqual(verifyOutput);
        });
      });

      if (RUN_AST_TESTS) {
        const source = read(dirname + "/" + filename);
        const ast = parse(source, mergedOptions);
        const astMassaged = massageAST(ast);
        let ppastMassaged;
        let pperr = null;
        try {
          const ppast = parse(prettyprint(source, path, mergedOptions), mergedOptions)
          ppastMassaged = massageAST(ppast);
        } catch (e) {
          pperr = e.stack;
        }

        test(path + " parse", () => {
          expect(pperr).toBe(null);
          expect(ppastMassaged).toBeDefined();
          if (!ast.errors || ast.errors.length === 0) {
            expect(astMassaged).toEqual(ppastMassaged);
          }
        });
      }
    }
  });
}
global.run_spec = run_spec;

function stripLocation(ast) {
  if (Array.isArray(ast)) {
    return ast.map(e => stripLocation(e));
  }
  if (typeof ast === "object") {
    const newObj = {};
    for (var key in ast) {
      if (
        key === "loc" || key === "range" || key === "raw" || key === "comments"
      ) {
        continue;
      }
      newObj[key] = stripLocation(ast[key]);
    }
    return newObj;
  }
  return ast;
}

function parse(string, opts) {
  return stripLocation(parser.parse(string, opts));
}

function prettyprint(src, filename, options) {
  return prettier.format(
    src,
    Object.assign(
      {
        filename
      },
      options
    )
  );
}

function read(filename) {
  return fs.readFileSync(filename, "utf8");
}

/**
 * Wraps a string in a marker object that is used by `./raw-serializer.js` to
 * directly print that string in a snapshot without escaping all double quotes.
 * Backticks will still be escaped.
 */
function raw(string) {
  if (typeof string !== "string") {
    throw new Error("Raw snapshots have to be strings.");
  }
  return { [Symbol.for("raw")]: string };
}

function mergeDefaultOptions(parserConfig) {
  return Object.assign(
    {
      parser: "flow",
      printWidth: 80
    },
    parserConfig
  );
}

function getParsersToVerify(parser, additionalParsers) {
  if (VERIFY_ALL_PARSERS) {
    return ALL_PARSERS.splice(ALL_PARSERS.indexOf(parser), 1);
  }
  return additionalParsers;
}
<|endoftext|>


<commit_before>const {updated} = require(`../lib/updated`);
const wrapHandler = require(`../lib/wrap-handler`);
const {list} = require(`../util/package`);

module.exports = {
  command: `list`,
  desc: `List packages`,
  builder: {
    fortests: {
      default: false,
      description: `list packages that should be tested in CI`,
      type: `boolean`
    },
    forpipeline: {
      default: false,
      description: `list packages that should be tested in a pipeline gating job`,
      type: `boolean`
    }
  },
  handler: wrapHandler(async ({fortests, forpipeline}) => {
    let packages;
    if (fortests) {
      const changed = await updated({});
      if (changed.includes(`tooling`)) {
        packages = await list();
      }
      else {
        packages = await updated({dependents: true});
      }
    }
    else {
      packages = await list();
    }

    if (forpipeline || fortests) {
      if (packages.includes(`legacy`)) {
        packages = packages.filter((p) => p !== `legacy`);
        packages.push(`legacy-node`);
        packages.push(`legacy-browser`);
      }

      packages = packages
        .filter((p) => !p.includes(`bin-`))
        .filter((p) => !p.includes(`test-helper-`))
        .filter((p) => !p.includes(`eslint-config`))
        .filter((p) => !p.includes(`xunit-with-logs`));
    }

    for (const pkg of packages) {
      console.info(pkg);
    }
  })
};
<commit_msg>fix(tooling): make sure legacy tests run in pipeline<commit_after>const {updated} = require(`../lib/updated`);
const wrapHandler = require(`../lib/wrap-handler`);
const {list} = require(`../util/package`);

module.exports = {
  command: `list`,
  desc: `List packages`,
  builder: {
    fortests: {
      default: false,
      description: `list packages that should be tested in CI`,
      type: `boolean`
    },
    forpipeline: {
      default: false,
      description: `list packages that should be tested in a pipeline gating job`,
      type: `boolean`
    }
  },
  handler: wrapHandler(async ({fortests, forpipeline}) => {
    let packages;
    if (fortests) {
      const changed = await updated({});
      if (changed.includes(`tooling`)) {
        packages = await list();
        packages.push(`legacy`);
      }
      else {
        packages = await updated({dependents: true});
      }
    }
    else {
      packages = await list();
    }

    if (forpipeline || fortests) {
      if (packages.includes(`legacy`)) {
        packages = packages.filter((p) => p !== `legacy`);
        packages.push(`legacy-node`);
        packages.push(`legacy-browser`);
      }

      packages = packages
        .filter((p) => !p.includes(`bin-`))
        .filter((p) => !p.includes(`test-helper-`))
        .filter((p) => !p.includes(`eslint-config`))
        .filter((p) => !p.includes(`xunit-with-logs`));
    }

    for (const pkg of packages) {
      console.info(pkg);
    }
  })
};
<|endoftext|>


<commit_before>(function() {
  "use strict";

  var board = {
    "name": "The Big Bang Theory",
    "categories": [{
      "name": "To Do",
      "tasks": [{
        "name": "Chinese takeway night",
        "users": [],
        "comments": []
      }, {
        "name": "Laundry",
        "users": [0, 4],
        "comments": []
      }, {
        "name": "Convince Bernadette to move in with Howard's mum",
        "users": [],
        "comments": []
      }, {
        "name": "Find girlfriend for Raj",
        "users": [],
        "comments": [{
          "user": 3,
          "content": "I am never lucky guys!!",
          "date": Date.now() - 60 * 24 * 60 * 60 * 1000
        }]
      }, {
        "name": "Solve the singularity",
        "users": [0],
        "comments": []
      }]
    }, {
      "name": "Underway",
      "tasks": [{
        "name": "Visit the comic book store 7pm",
        "users": [1, 3, 0],
        "comments": [{
          "user": 1,
          "content": "I'm so excited about this!",
          "date": Date.now() - 3 * 60 * 60 * 1000
        }, {
          "user": 3,
          "content": "Yeah, the new X-men is out!",
          "date": Date.now() - 2 * 60 * 60 * 1000
        }]
      }, {
        "name": "Date night",
        "users": [4, 2],
        "comments": []
      }]
    }, {
      "name": "Finished",
      "tasks": [{
        "name": "Star War movie marathon",
        "users": [2, 1, 0, 3],
        "comments": [{
          "user": 4,
          "content": "..."
        }]
      }]
    }],
    "members": [],
    "admins": []
  };

  module.exports = board;
})();
<commit_msg>fix age of post in the board-import data<commit_after>(function() {
  "use strict";

  var board = {
    "name": "The Big Bang Theory",
    "categories": [{
      "name": "To Do",
      "tasks": [{
        "name": "Chinese takeway night",
        "users": [],
        "comments": []
      }, {
        "name": "Laundry",
        "users": [0, 4],
        "comments": []
      }, {
        "name": "Convince Bernadette to move in with Howard's mum",
        "users": [],
        "comments": []
      }, {
        "name": "Find girlfriend for Raj",
        "users": [],
        "comments": [{
          "user": 3,
          "content": "I am never lucky guys!!",
          "date": Date.now() - 60 * 24 * 60 * 60 * 1000
        }]
      }, {
        "name": "Solve the singularity",
        "users": [0],
        "comments": []
      }]
    }, {
      "name": "Underway",
      "tasks": [{
        "name": "Visit the comic book store 7pm",
        "users": [1, 3, 0],
        "comments": [{
          "user": 1,
          "content": "I'm so excited about this!",
          "date": Date.now() - 3 * 60 * 60 * 1000
        }, {
          "user": 3,
          "content": "Yeah, the new X-men is out!",
          "date": Date.now() - 2 * 60 * 60 * 1000
        }]
      }, {
        "name": "Date night",
        "users": [4, 2],
        "comments": []
      }]
    }, {
      "name": "Finished",
      "tasks": [{
        "name": "Star War movie marathon",
        "users": [2, 1, 0, 3],
        "comments": [{
          "user": 4,
          "content": "...",
          "date": Date.now() - 50 * 60 * 1000
        }]
      }]
    }],
    "members": [],
    "admins": []
  };

  module.exports = board;
})();<|endoftext|>


<commit_before>module( "jump_navigation", {
  setup: function() {
    $('body')
      .append('')
      .append('')
      .append('');
    var $fancy = $('.fancy');
    $fancy.fancybox();
    $fancy.on('click', function() {
      setTimeout( function() {
        $('.fancybox-wrap').hide();
        $('.fancybox-overlay').hide();
      }, 100);
    }).first().trigger('click');

  },
  teardown: function() {
    $('.fancy').remove();
    F.close();
  }
});

/*
*
*= JUMPTO
*
*/

test( "jumpto accepts index, direction, and router as parameters", function() {

  var directionParam = 'right',
    indexParam = 1,
    routerParam = 'jumpto',
    jumptoSpy = this.spy(F, 'jumpto'),
    current = {
      index: 1,
      direction: { next: 'left', prev: 'right' },
      loop: true,
      group: [
        { href: "img/cat.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-2.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-3.jpeg", isDom: true, title: "", type: "image" }
      ]
    };
  $.extend(F, { current: current });

  F.jumpto(indexParam, directionParam, routerParam);
  ok(jumptoSpy.called, "F.jumpto was called");
  ok(jumptoSpy.calledWithExactly(indexParam, directionParam, routerParam), "F.jumpto called with proper parameters");

  expect(2);
  delete F.current;

});

test( "jumpto returns if current is null", function() {
  var directionParam = 'right',
    jumptoSpy = this.spy(F, 'jumpto'),
    cancelSpy = this.spy(F, 'cancel'),
    startSpy = this.spy(F, '_start'),
    bigIndex = 10000;

  $.extend(F, { current: null });

  F.jumpto(directionParam);

  ok(jumptoSpy.firstCall, "F.jumpto was called first");
  ok(jumptoSpy.calledOnce, "F.jumpto was called once");
  equal(jumptoSpy.returnValues[0], undefined, "F.jumpto returned no values");
  ok(jumptoSpy.lastCall, "F.jumpto was called last");
  equal(cancelSpy.callCount, 0, "F.cancel was not called");
  equal(startSpy.callCount, 0, "F._start() was not called");

  expect(6);
  delete F.current;
});

test( "jumpto does not call F.cancel if current is null", function() {
  var directionParam = 'right',
    jumptoSpy = this.spy(F, 'jumpto'),
    cancelSpy = this.spy(F, 'cancel'),
    bigIndex = 10000;

  $.extend(F, { current: null });

  F.jumpto(directionParam);

  ok(jumptoSpy.firstCall, "F.jumpto was called first");
  equal(cancelSpy.callCount, 0, "F.cancel was not called");
  ok(jumptoSpy.lastCall, "F.jumpto was called last");

  expect(3);
  delete F.current;
});

test( "jumpto does not call F._start if current is null", function() {
  var directionParam = 'right',
    jumptoSpy = this.spy(F, 'jumpto'),
    startSpy = this.spy(F, '_start'),
    bigIndex = 10000;

  $.extend(F, { current: null });

  F.jumpto(directionParam);

  ok(jumptoSpy.firstCall, "F.jumpto was called first");
  equal(startSpy.callCount, 0, "F._start was not called");
  ok(jumptoSpy.lastCall, "F.jumpto was called last");

  expect(3);
  delete F.current;
});

test("if current.group at position index is not undefined, F.cancel() and F._start() are called", function() {
  var directionParam = 'right',
    cancelSpy = this.spy(F, 'cancel'),
    startSpy = this.spy(F, '_start'),
    current = {
      index: 1,
      direction: { next: 'left', prev: 'right' },
      loop: true,
      group: [
        { href: "img/cat.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-2.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-3.jpeg", isDom: true, title: "", type: "image" }
      ]
    };
  $.extend(F, { current: current });

  F.jumpto(directionParam);
  ok(cancelSpy.called, "F.cancel was called");
  ok(startSpy.called, "F._start() was called");

  expect(2);
  delete F.current;
});

// ensure order of functons is maintained
test("if current.group at position index is not undefined, F.cancel() is called, and then F._start() is called", function() {
  var directionParam = 'right',
    cancelSpy = this.spy(F, 'cancel'),
    startSpy = this.spy(F, '_start'),
    current = {
      index: 1,
      direction: { next: 'left', prev: 'right' },
      loop: true,
      group: [
        { href: "img/cat.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-2.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-3.jpeg", isDom: true, title: "", type: "image" }
      ]
    };
  $.extend(F, { current: current });

  F.jumpto(directionParam);
  ok(cancelSpy.called, "F.cancel was called");
  ok(startSpy.called, "F._start was called");
  ok(cancelSpy.calledBefore(startSpy), "F.cancel was called before F.start");

  expect(3);
  delete F.current;
});

test("if current.group at position index is undefined, F.cancel() and F._start() are not called", function() {

  var directionParam = 'right',
    cancelSpy = this.spy(F, 'cancel'),
    startSpy = this.spy(F, '_start'),
    bigIndex = 10000,
    current = {
      index: bigIndex, // pass in an impossible index
      direction: { next: 'left', prev: 'right' },
      loop: false, // ensure index stays as the param we passed in
      group: [
        { href: "img/cat.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-2.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-3.jpeg", isDom: true, title: "", type: "image" }
      ]
    },
    stubIndexCalc = this.stub(window, 'getScalar', function(arg) {
      // ensure we maintain unaltered bigIndex
      return arg;
    });
  $.extend(F, { current: current });

  F.jumpto(directionParam);

  ok(typeof(current.group[ bigIndex ]) === 'undefined', "current.group at position index is undefined");
  equal(cancelSpy.callCount, 0, "F.cancel was not called");
  equal(startSpy.callCount, 0, "F._start() was not called");

  expect(3);
  delete F.current;
});<commit_msg>commenting jumpto nav tests<commit_after>module( "jump_navigation", {
  setup: function() {
    $('body')
      .append('')
      .append('')
      .append('');
    var $fancy = $('.fancy');
    $fancy.fancybox();
    $fancy.on('click', function() {
      setTimeout( function() {
        $('.fancybox-wrap').hide();
        $('.fancybox-overlay').hide();
      }, 100);
    }).first().trigger('click');

  },
  teardown: function() {
    $('.fancy').remove();
    F.close();
  }
});

/*
*
*= JUMPTO
*
*/

// jumpto allows the user to pass in index, direction, and router, with
// direction and router being optional parameters.
test( "jumpto accepts index, direction, and router as parameters", function() {

  var directionParam = 'right',
    indexParam = 1,
    routerParam = 'jumpto',
    jumptoSpy = this.spy(F, 'jumpto'),
    current = {
      index: 1,
      direction: { next: 'left', prev: 'right' },
      loop: true,
      group: [
        { href: "img/cat.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-2.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-3.jpeg", isDom: true, title: "", type: "image" }
      ]
    };
  $.extend(F, { current: current });

  F.jumpto(indexParam, directionParam, routerParam);
  ok(jumptoSpy.called, "F.jumpto was called");
  ok(jumptoSpy.calledWithExactly(indexParam, directionParam, routerParam), "F.jumpto called with proper parameters");

  expect(2);
  delete F.current;

});

// Jumpto relies on the current fancybox object (ie. F.current).
// If it isn't present, the function should exit, ie. it should
// be the first and last function called. It should also
// not return any values.
test( "jumpto returns if current is null", function() {
  var directionParam = 'right',
    jumptoSpy = this.spy(F, 'jumpto'),
    cancelSpy = this.spy(F, 'cancel'),
    startSpy = this.spy(F, '_start'),
    bigIndex = 10000;

  $.extend(F, { current: null });

  F.jumpto(directionParam);

  ok(jumptoSpy.firstCall, "F.jumpto was called first");
  ok(jumptoSpy.calledOnce, "F.jumpto was called once");
  equal(jumptoSpy.returnValues[0], undefined, "F.jumpto returned no values");
  ok(jumptoSpy.lastCall, "F.jumpto was called last");
  equal(cancelSpy.callCount, 0, "F.cancel was not called");
  equal(startSpy.callCount, 0, "F._start() was not called");

  expect(6);
  delete F.current;
});

// Jumpto relies on the current fancybox object (ie. F.current).
// If it isn't present, the function should exit, ie. it should
// be the first and last function called, and it should not call
// the cancel function referenced within.
test( "jumpto does not call F.cancel if current is null", function() {
  var directionParam = 'right',
    jumptoSpy = this.spy(F, 'jumpto'),
    cancelSpy = this.spy(F, 'cancel'),
    bigIndex = 10000;

  $.extend(F, { current: null });

  F.jumpto(directionParam);

  ok(jumptoSpy.firstCall, "F.jumpto was called first");
  equal(cancelSpy.callCount, 0, "F.cancel was not called");
  ok(jumptoSpy.lastCall, "F.jumpto was called last");

  expect(3);
  delete F.current;
});

// Jumpto relies on the current fancybox object (ie. F.current).
// If it isn't present, the function should exit, ie. it should
// be the first and last function called, and it should not call
// the _start function referenced within.
test( "jumpto does not call F._start if current is null", function() {
  var directionParam = 'right',
    jumptoSpy = this.spy(F, 'jumpto'),
    startSpy = this.spy(F, '_start'),
    bigIndex = 10000;

  $.extend(F, { current: null });

  F.jumpto(directionParam);

  ok(jumptoSpy.firstCall, "F.jumpto was called first");
  equal(startSpy.callCount, 0, "F._start was not called");
  ok(jumptoSpy.lastCall, "F.jumpto was called last");

  expect(3);
  delete F.current;
});

// Jumpto relies on the current fancybox object (ie. F.current).
// If it is present, the function should call the functions referenced
// within, ie. cancel and _start.
test("if current.group at position index is not undefined, F.cancel() and F._start() are called", function() {
  var directionParam = 'right',
    cancelSpy = this.spy(F, 'cancel'),
    startSpy = this.spy(F, '_start'),
    current = {
      index: 1,
      direction: { next: 'left', prev: 'right' },
      loop: true,
      group: [
        { href: "img/cat.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-2.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-3.jpeg", isDom: true, title: "", type: "image" }
      ]
    };
  $.extend(F, { current: current });

  F.jumpto(directionParam);
  ok(cancelSpy.called, "F.cancel was called");
  ok(startSpy.called, "F._start() was called");

  expect(2);
  delete F.current;
});

// Ensure order of functions called within jumpto is maintained.
test("if current.group at position index is not undefined, F.cancel() is called, and then F._start() is called", function() {
  var directionParam = 'right',
    cancelSpy = this.spy(F, 'cancel'),
    startSpy = this.spy(F, '_start'),
    current = {
      index: 1,
      direction: { next: 'left', prev: 'right' },
      loop: true,
      group: [
        { href: "img/cat.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-2.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-3.jpeg", isDom: true, title: "", type: "image" }
      ]
    };
  $.extend(F, { current: current });

  F.jumpto(directionParam);
  ok(cancelSpy.called, "F.cancel was called");
  ok(startSpy.called, "F._start was called");
  ok(cancelSpy.calledBefore(startSpy), "F.cancel was called before F.start");

  expect(3);
  delete F.current;
});

// Jumpto needs to be able to advance to the proper gallery element.
// This element should exist within the current fancybox element's group
// array at its respective index. If it's not, the function should exit.
test("if current.group at position index is undefined, F.cancel() and F._start() are not called", function() {

  var directionParam = 'right',
    cancelSpy = this.spy(F, 'cancel'),
    startSpy = this.spy(F, '_start'),
    bigIndex = 10000,
    current = {
      index: bigIndex, // pass in an impossible index
      direction: { next: 'left', prev: 'right' },
      loop: false, // ensure index stays as the param we passed in
      group: [
        { href: "img/cat.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-2.jpeg", isDom: true, title: "", type: "image" },
        { href: "img/cat-3.jpeg", isDom: true, title: "", type: "image" }
      ]
    },
    stubIndexCalc = this.stub(window, 'getScalar', function(arg) {
      // ensure we maintain unaltered bigIndex
      return arg;
    });
  $.extend(F, { current: current });

  F.jumpto(directionParam);

  ok(typeof(current.group[ bigIndex ]) === 'undefined', "current.group at position index is undefined");
  equal(cancelSpy.callCount, 0, "F.cancel was not called");
  equal(startSpy.callCount, 0, "F._start() was not called");

  expect(3);
  delete F.current;
});<|endoftext|>