<commit_before>"use strict";

import 'source-map-support/register';
const callbacks = require("../../src/realtime-callbacks");

let wallTime = 1234567890;
jest.useFakeTimers();

describe("realtime-callbacks", function() {
    function tick(millis) {
        wallTime += millis;
        jest.advanceTimersByTime(millis);
    }

    beforeEach(function() {
        callbacks.setNow(() => wallTime);
    });

    afterEach(function() {
        callbacks.setNow();
    });

    describe("setTimeout", function() {
        it("should call the callback after the timeout", function() {
            const callback = jest.fn();
            callbacks.setTimeout(callback, 100);

            expect(callback).not.toHaveBeenCalled();
            tick(100);
            expect(callback).toHaveBeenCalled();
        });

        it("should default to a zero timeout", function() {
            const callback = jest.fn();
            callbacks.setTimeout(callback);

            expect(callback).not.toHaveBeenCalled();
            tick(0);
            expect(callback).toHaveBeenCalled();
        });

        it("should pass any parameters to the callback", function() {
            const callback = jest.fn();
            callbacks.setTimeout(callback, 0, "a", "b", "c");
            tick(0);
            expect(callback).toHaveBeenCalledWith("a", "b", "c");
        });

        it("should set 'this' to the global object", function() {
            let passed = false;
            const callback = function() {
                expect(this).toBe(global); // eslint-disable-line babel/no-invalid-this
                expect(this.console).toBeTruthy(); // eslint-disable-line babel/no-invalid-this
                passed = true;
            };
            callbacks.setTimeout(callback);
            tick(0);
            expect(passed).toBe(true);
        });

        it("should handle timeouts of several seconds", function() {
            const callback = jest.fn();
            callbacks.setTimeout(callback, 2000);

            expect(callback).not.toHaveBeenCalled();
            for (let i = 0; i < 4; i++) {
                tick(500);
            }
            expect(callback).toHaveBeenCalled();
        });

        it("should call multiple callbacks in the right order", function() {
            const callback1 = jest.fn();
            const callback2 = jest.fn();
            const callback3 = jest.fn();
            callbacks.setTimeout(callback2, 200);
            callbacks.setTimeout(callback1, 100);
            callbacks.setTimeout(callback3, 300);

            expect(callback1).not.toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            expect(callback3).not.toHaveBeenCalled();
            tick(100);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            expect(callback3).not.toHaveBeenCalled();
            tick(100);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).toHaveBeenCalled();
            expect(callback3).not.toHaveBeenCalled();
            tick(100);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).toHaveBeenCalled();
            expect(callback3).toHaveBeenCalled();
        });

        it("should treat -ve timeouts the same as a zero timeout", function() {
            const callback1 = jest.fn();
            const callback2 = jest.fn();

            // check that cb1 is called before cb2
            callback1.mockImplementation(function() {
                expect(callback2).not.toHaveBeenCalled();
            });

            callbacks.setTimeout(callback1);
            callbacks.setTimeout(callback2, -100);

            expect(callback1).not.toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            tick(0);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).toHaveBeenCalled();
        });

        it("should not get confused by chained calls", function() {
            const callback2 = jest.fn();
            const callback1 = jest.fn();
            callback1.mockImplementation(function() {
                callbacks.setTimeout(callback2, 0);
                expect(callback2).not.toHaveBeenCalled();
            });

            callbacks.setTimeout(callback1);
            expect(callback1).not.toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            tick(0);
            expect(callback1).toHaveBeenCalled();
            // the fake timer won't actually run callbacks registered during
            // one tick until the next tick.
            tick(1);
            expect(callback2).toHaveBeenCalled();
        });

        it("should be immune to exceptions", function() {
            const callback1 = jest.fn();
            callback1.mockImplementation(function() {
                throw new Error("prepare to die");
            });
            const callback2 = jest.fn();
            callbacks.setTimeout(callback1, 0);
            callbacks.setTimeout(callback2, 0);

            expect(callback1).not.toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            tick(0);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).toHaveBeenCalled();
        });
    });

    describe("cancelTimeout", function() {
        it("should cancel a pending timeout", function() {
            const callback = jest.fn();
            const k = callbacks.setTimeout(callback);
            callbacks.clearTimeout(k);
            tick(0);
            expect(callback).not.toHaveBeenCalled();
        });

        it("should not affect sooner timeouts", function() {
            const callback1 = jest.fn();
            const callback2 = jest.fn();

            callbacks.setTimeout(callback1, 100);
            const k = callbacks.setTimeout(callback2, 200);
            callbacks.clearTimeout(k);

            tick(100);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();

            tick(150);
            expect(callback2).not.toHaveBeenCalled();
        });
    });
});
<commit_msg>tidy up<commit_after>"use strict";

import 'source-map-support/register';
const callbacks = require("../../src/realtime-callbacks");

let wallTime = 1234567890;
jest.useFakeTimers();

describe("realtime-callbacks", function() {
    function tick(millis) {
        wallTime += millis;
        jest.advanceTimersByTime(millis);
    }

    beforeEach(function() {
        callbacks.setNow(() => wallTime);
    });

    afterEach(function() {
        callbacks.setNow();
    });

    describe("setTimeout", function() {
        it("should call the callback after the timeout", function() {
            const callback = jest.fn();
            callbacks.setTimeout(callback, 100);

            expect(callback).not.toHaveBeenCalled();
            tick(100);
            expect(callback).toHaveBeenCalled();
        });

        it("should default to a zero timeout", function() {
            const callback = jest.fn();
            callbacks.setTimeout(callback);

            expect(callback).not.toHaveBeenCalled();
            tick(0);
            expect(callback).toHaveBeenCalled();
        });

        it("should pass any parameters to the callback", function() {
            const callback = jest.fn();
            callbacks.setTimeout(callback, 0, "a", "b", "c");
            tick(0);
            expect(callback).toHaveBeenCalledWith("a", "b", "c");
        });

        it("should set 'this' to the global object", function() {
            let passed = false;
            const callback = function() {
                expect(this).toBe(global); // eslint-disable-line babel/no-invalid-this
                expect(this.console).toBeTruthy(); // eslint-disable-line babel/no-invalid-this
                passed = true;
            };
            callbacks.setTimeout(callback);
            tick(0);
            expect(passed).toBe(true);
        });

        it("should handle timeouts of several seconds", function() {
            const callback = jest.fn();
            callbacks.setTimeout(callback, 2000);

            expect(callback).not.toHaveBeenCalled();
            for (let i = 0; i < 4; i++) {
                tick(500);
            }
            expect(callback).toHaveBeenCalled();
        });

        it("should call multiple callbacks in the right order", function() {
            const callback1 = jest.fn();
            const callback2 = jest.fn();
            const callback3 = jest.fn();
            callbacks.setTimeout(callback2, 200);
            callbacks.setTimeout(callback1, 100);
            callbacks.setTimeout(callback3, 300);

            expect(callback1).not.toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            expect(callback3).not.toHaveBeenCalled();
            tick(100);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            expect(callback3).not.toHaveBeenCalled();
            tick(100);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).toHaveBeenCalled();
            expect(callback3).not.toHaveBeenCalled();
            tick(100);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).toHaveBeenCalled();
            expect(callback3).toHaveBeenCalled();
        });

        it("should treat -ve timeouts the same as a zero timeout", function() {
            const callback1 = jest.fn();
            const callback2 = jest.fn();

            // check that cb1 is called before cb2
            callback1.mockImplementation(function() {
                expect(callback2).not.toHaveBeenCalled();
            });

            callbacks.setTimeout(callback1);
            callbacks.setTimeout(callback2, -100);

            expect(callback1).not.toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            tick(0);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).toHaveBeenCalled();
        });

        it("should not get confused by chained calls", function() {
            const callback2 = jest.fn();
            const callback1 = jest.fn(function() {
                callbacks.setTimeout(callback2, 0);
                expect(callback2).not.toHaveBeenCalled();
            });

            callbacks.setTimeout(callback1);
            expect(callback1).not.toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            tick(0);
            expect(callback1).toHaveBeenCalled();
            // the fake timer won't actually run callbacks registered during
            // one tick until the next tick.
            tick(1);
            expect(callback2).toHaveBeenCalled();
        });

        it("should be immune to exceptions", function() {
            const callback1 = jest.fn(function() {
                throw new Error("prepare to die");
            });
            const callback2 = jest.fn();
            callbacks.setTimeout(callback1, 0);
            callbacks.setTimeout(callback2, 0);

            expect(callback1).not.toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();
            tick(0);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).toHaveBeenCalled();
        });
    });

    describe("cancelTimeout", function() {
        it("should cancel a pending timeout", function() {
            const callback = jest.fn();
            const k = callbacks.setTimeout(callback);
            callbacks.clearTimeout(k);
            tick(0);
            expect(callback).not.toHaveBeenCalled();
        });

        it("should not affect sooner timeouts", function() {
            const callback1 = jest.fn();
            const callback2 = jest.fn();

            callbacks.setTimeout(callback1, 100);
            const k = callbacks.setTimeout(callback2, 200);
            callbacks.clearTimeout(k);

            tick(100);
            expect(callback1).toHaveBeenCalled();
            expect(callback2).not.toHaveBeenCalled();

            tick(150);
            expect(callback2).not.toHaveBeenCalled();
        });
    });
});
<|endoftext|>


<commit_before>import React from 'react'

class NewGame extends React.Component {

  submitGame = (e) => {
    e.preventDefault()
    console.log('Make New Game', e)
    let gameObj = {}
    gameObj.venue = document.getElementById('venue-input').value
    gameObj.date = document.getElementById('date-input').value
    gameObj.time = document.getElementById('time-input').value
    gameObj.gender = document.getElementById('gender-input').value
    gameObj.home_team = document.getElementById('home_team-input').value
    gameObj.away_team = document.getElementById('away_team-input').value
    gameObj.referee_1 = document.getElementById('referee_1-input').value
    gameObj.referee_2 = document.getElementById('referee_2-input').value
    gameObj.timekeeper = document.getElementById('timekeeper-input').value
    gameObj.scorekeeper = document.getElementById('scorekeeper-input').value
    gameObj.owner_id = this.props.userId
    gameObj.home_players = []
    gameObj.away_players = []
    gameObj.events = []
    gameObj.current_score = {home: 0, away: 0}
    gameObj.halftime_score = {home: 0, away: 0}
    gameObj.fulltime_score = {home: 0, away: 0}
    gameObj.status_started = false
    gameObj.status_halftime_completed = false
    gameObj.status_fulltime_completed = false
    gameObj.current_time = 1767

    console.log('gameObj', gameObj)
    this.props.submitGame(gameObj)
    // this.props.history.push('/')
  }

  render () {
    const loggedIn = this.props.loggedIn
    return (

        {loggedIn
          ? <form className='new-game-form'>

                Venue<input className='u-full-width' type='text' name='venue' id='venue-input' />

                date<input className='u-full-width' type='date' name='date' id='date-input' />

                time<input className='u-full-width' type='time' name='time' id='time-input' />

                Gender
                <select type='text' name='gender' id='gender-input' >
                  <option value='male'>Male</option>
                  <option value='female'>Female</option>
                </select>

                Home Team<input className='u-full-width' type='text' name='home_team' id='home_team-input' />

                Away Team<input className='u-full-width' type='text' name='away_team' id='away_team-input' />

                Referee #1<input className='u-full-width' type='text' name='referee_1' id='referee_1-input' />

                Referee #2<input className='u-full-width' type='text' name='referee_2' id='referee_2-input' />

                Timekeeper<input className='u-full-width' type='text' name='timekeeper' id='timekeeper-input' />

                Scorekeeper<input className='u-full-width' type='text' name='scorekeeper' id='scorekeeper-input' />

            <input className='button-primary' type='submit' value='Make New Game' onClick={this.submitGame} />
          </form>
          :

Log In To Make Game

}

    )
  }
}

export default NewGame
<commit_msg>Correct inital time value, add styling class to new game<commit_after>import React from 'react'

class NewGame extends React.Component {

  submitGame = (e) => {
    e.preventDefault()
    console.log('Make New Game', e)
    let gameObj = {}
    gameObj.venue = document.getElementById('venue-input').value
    gameObj.date = document.getElementById('date-input').value
    gameObj.time = document.getElementById('time-input').value
    gameObj.gender = document.getElementById('gender-input').value
    gameObj.home_team = document.getElementById('home_team-input').value
    gameObj.away_team = document.getElementById('away_team-input').value
    gameObj.referee_1 = document.getElementById('referee_1-input').value
    gameObj.referee_2 = document.getElementById('referee_2-input').value
    gameObj.timekeeper = document.getElementById('timekeeper-input').value
    gameObj.scorekeeper = document.getElementById('scorekeeper-input').value
    gameObj.owner_id = this.props.userId
    gameObj.home_players = []
    gameObj.away_players = []
    gameObj.events = []
    gameObj.current_score = {home: 0, away: 0}
    gameObj.halftime_score = {home: 0, away: 0}
    gameObj.fulltime_score = {home: 0, away: 0}
    gameObj.status_started = false
    gameObj.status_halftime_completed = false
    gameObj.status_fulltime_completed = false
    gameObj.current_time = 0

    console.log('gameObj', gameObj)
    this.props.submitGame(gameObj)
    // this.props.history.push('/')
  }

  render () {
    const loggedIn = this.props.loggedIn
    return (

        {loggedIn
          ? <form className='new-game-form'>

                Venue<input className='u-full-width' type='text' name='venue' id='venue-input' />

                date<input className='u-full-width' type='date' name='date' id='date-input' />

                time<input className='u-full-width' type='time' name='time' id='time-input' />

                Gender
                <select type='text' name='gender' id='gender-input' >
                  <option value='male'>Male</option>
                  <option value='female'>Female</option>
                </select>

                Home Team<input className='u-full-width' type='text' name='home_team' id='home_team-input' />

                Away Team<input className='u-full-width' type='text' name='away_team' id='away_team-input' />

                Referee #1<input className='u-full-width' type='text' name='referee_1' id='referee_1-input' />

                Referee #2<input className='u-full-width' type='text' name='referee_2' id='referee_2-input' />

                Timekeeper<input className='u-full-width' type='text' name='timekeeper' id='timekeeper-input' />

                Scorekeeper<input className='u-full-width' type='text' name='scorekeeper' id='scorekeeper-input' />

            <input className='button-primary' type='submit' value='Make New Game' onClick={this.submitGame} />
          </form>
          :

Log In To Make Game

}

    )
  }
}

export default NewGame
<|endoftext|>


<commit_before>var env = process.env
var app = process.app
var log = app.log
var plans = require('plans')
var fs = require('fs')
var spawn = require('lighter-spawn')
var cwd = app.dir + '/android'

var self = exports

self.build = function build (buildDone) {
  var devices = []
  var pkg = 'unknown'
  var xml = cwd + '/AndroidManifest.xml'
  var options = {cwd: cwd, env: env}

  plans
    .all([
      function (done) {
        fs.readFile(xml, 'utf-8', function (err, content) {
          content.replace(/package="([^"]+)"/, function (match, name) {
            pkg = name
          })
          done()
        })
      },
      function (done) {
        spawn('gradle assembleDebug --daemon', options)
          .on('stdout', function (data) {
            data.replace(/Total time: (.+)\s+$/g, function (match, time) {
              log.info('Built APK: ' + time.green + '.')
            })
            done()
          })
      },
      function (done) {
        spawn('adb devices')
          .on('stdout', function (data) {
            data.replace(/\n([\S]+)\s+device\b/g, function (match, device) {
              devices.push(device)
            })
            var n = devices.length
            log.info('Found ' + n + ' Android device' + (n === 1 ? '' : 's') + '.')
            done()
          })
      }
    ])
    .then(function (done) {
      plans.list(devices).each(function (device, done) {
        env.ANDROID_SERIAL = device
        spawn('adb install -rd build/outputs/apk/android-debug.apk', options)
          .on('error', log.error)
          .on('stdout', function () {
            spawn('adb shell am start -a android.intent.action.MAIN -n ' + pkg + '/.MainActivity', options)
              .on('error', log.error)
              .on('stdout', function () {
                spawn('adb shell input keyevent KEYCODE_WAKEUP')
                  .on('error', log.error)
                  .on('stdout', function () {
                    spawn('adb shell input touchscreen swipe 0 1280 1400 1280')
                      .on('error', log.error)
                      .on('stdout', function () {
                        log.info('Installed Android app on ' + device.green + '.')
                        done()
                      })
                  })
              })
          })
      })
    })
}
<commit_msg>Condensed adb install chain<commit_after>var env = process.env
var app = process.app
var log = app.log
var plans = require('plans')
var fs = require('fs')
var spawn = require('lighter-spawn')
var cwd = app.dir + '/android'

var self = exports

self.build = function build (buildDone) {
  var devices = []
  var pkg = 'unknown'
  var xml = cwd + '/AndroidManifest.xml'
  var options = {cwd: cwd, env: env}

  plans
    .all([
      function (done) {
        fs.readFile(xml, 'utf-8', function (err, content) {
          content.replace(/package="([^"]+)"/, function (match, name) {
            pkg = name
          })
          done()
        })
      },
      function (done) {
        spawn('gradle assembleDebug --daemon', options)
          .on('stdout', function (data) {
            data.replace(/Total time: (.+)\s+$/g, function (match, time) {
              log.info('Built APK: ' + time.green + '.')
            })
            done()
          })
      },
      function (done) {
        spawn('adb devices')
          .on('stdout', function (data) {
            data.replace(/\n([\S]+)\s+device\b/g, function (match, device) {
              devices.push(device)
            })
            var n = devices.length
            log.info('Found ' + n + ' Android device' + (n === 1 ? '' : 's') + '.')
            done()
          })
      }
    ])
    .then(function (done) {
      plans.list(devices).each(function (device, done) {
        env.ANDROID_SERIAL = device
        plans
          .each([
            adbFn('install -rd build/outputs/apk/android-debug.apk'),
            adbFn('shell am start -a android.intent.action.MAIN -n ' + pkg + '/.MainActivity'),
            adbFn('shell input keyevent KEYCODE_WAKEUP'),
            adbFn('shell input touchscreen swipe 0 1280 1400 1280')
          ])
          .then(function () {
            log.info('Installed Android app on ' + device.green + '.')
            done()
          })
      })
    })

    function adbFn (args) {
      return function (done) {
        spawn('adb ' + args, options)
          .on('error', log.error)
          .on('stdout', done)
      }
    }
}
<|endoftext|>


<commit_before>import Component from '@ember/component';
import Ember from 'ember';
import { computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';

import InViewportMixin from 'ember-in-viewport';

export default Component.extend(InViewportMixin, {
  auth: service(),
  store: service(),
  externalLinks: service(),
  features: service(),
  flashes: service(),

  tagName: 'header',
  classNames: ['top'],
  landingPage: false,

  user: alias('auth.currentUser'),

  userName: computed('user.{login,name}', function () {
    let login = this.get('user.login');
    let name = this.get('user.name');
    return name || login;
  }),

  showCta: computed('auth.signedIn', 'landingPage', 'features.landingPageCta', function () {
    let signedIn = this.get('auth.signedIn');
    let landingPage = this.get('landingPage');
    let ctaEnabled = this.get('features.landingPageCta');

    return !signedIn && !landingPage && ctaEnabled;
  }),

  didInsertElement() {
    if (Ember.testing) {
      return;
    }

    Ember.setProperties(this, {
      viewportSpy: true
    });
    this._super(...arguments);
    Ember.run.scheduleOnce('afterRender', this, () => {
      Ember.set(this, 'viewportTolerance.top', this.$().height());
    });
  },

  didEnterViewport() {
    this.get('flashes').set('topBarVisible', true);
  },

  didExitViewport() {
    this.get('flashes').set('topBarVisible', false);
  },
});
<commit_msg>Address top bar testing inconsistencies (#1958)<commit_after>import Component from '@ember/component';
import Ember from 'ember';
import { computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';

import InViewportMixin from 'ember-in-viewport';

export default Component.extend(InViewportMixin, {
  auth: service(),
  store: service(),
  externalLinks: service(),
  features: service(),
  flashes: service(),

  tagName: 'header',
  classNames: ['top'],
  landingPage: false,

  user: alias('auth.currentUser'),

  userName: computed('user.{login,name}', function () {
    let login = this.get('user.login');
    let name = this.get('user.name');
    return name || login;
  }),

  showCta: computed('auth.signedIn', 'landingPage', 'features.landingPageCta', function () {
    let signedIn = this.get('auth.signedIn');
    let landingPage = this.get('landingPage');
    let ctaEnabled = this.get('features.landingPageCta');

    return !signedIn && !landingPage && ctaEnabled;
  }),

  didInsertElement() {
    if (Ember.testing) {
      this._super(...arguments);
      return;
    }

    Ember.setProperties(this, {
      viewportSpy: true
    });
    this._super(...arguments);
    Ember.run.scheduleOnce('afterRender', this, () => {
      Ember.set(this, 'viewportTolerance.top', this.$().height());
    });
  },

  didEnterViewport() {
    this.get('flashes').set('topBarVisible', true);
  },

  didExitViewport() {
    this.get('flashes').set('topBarVisible', false);
  },
});
<|endoftext|>


<commit_before>var path = require('path'),
    colors = require('colors'),
    MakePlatform = require('enb/lib/make'),
    makePlatform = new MakePlatform();

/**
 * Запускает таск.
 *
 * @param {String}  task   Название таска.
 * @param {Array}   [args] Аргументы для таска.
 * @param {Object}  [opts]
 * @param {String}  [opts.dir]                  Корень проекта.
 * @param {Boolean} [opts.noCache=false]        Не учитывать кэш при запуске таска.
 * @param {Boolean} [opts.noLog=false]          Не выводить сообщения в консоль в процессе выполнения таска.
 * @param {Boolean} [opts.hideWarnings=false]   Не выводить warning-сообщения в консоль в процессе выполнения таска.
 * @param {Boolean} [opts.graph=false]          Выводить граф сборки.
 * @returns {Promise}
 */
module.exports = function (task, args, opts) {
    var startTime = new Date();

    opts || (opts = {});
    opts.dir || (opts.dir = process.cwd());

    return makePlatform.init(path.resolve(opts.dir))
        .then(function () {
            var logger = makePlatform.getLogger();

            if (opts.noLog) {
                logger.setEnabled(false);
            } else if (opts.hideWarnings) {
                logger.hideWarnings();
            }

            if (opts.cache) {
                makePlatform.loadCache();
            }

            return makePlatform.buildTask(task, args)
                .then(function () {
                    if (opts.graph) {
                        console.log(makePlatform.getBuildGraph().render());
                    }

                    logger.log('build finished - ' + colors.red((new Date() - startTime) + 'ms'));

                    makePlatform.saveCache();
                    makePlatform.destruct();

                    return args;
                });
        })
        .fail(function (err) {
            if (opts.graph) {
                console.log(makePlatform.getBuildGraph().render());
            }

            console.error(err.stack);
            process.exit(1);
        });
};
<commit_msg>Fixed bug with crash if multiple async calls<commit_after>var path = require('path'),
    colors = require('colors'),
    MakePlatform = require('enb/lib/make');

/**
 * Запускает таск.
 *
 * @param {String}  task   Название таска.
 * @param {Array}   [args] Аргументы для таска.
 * @param {Object}  [opts]
 * @param {String}  [opts.dir]                  Корень проекта.
 * @param {Boolean} [opts.noCache=false]        Не учитывать кэш при запуске таска.
 * @param {Boolean} [opts.noLog=false]          Не выводить сообщения в консоль в процессе выполнения таска.
 * @param {Boolean} [opts.hideWarnings=false]   Не выводить warning-сообщения в консоль в процессе выполнения таска.
 * @param {Boolean} [opts.graph=false]          Выводить граф сборки.
 * @returns {Promise}
 */
module.exports = function (task, args, opts) {
    var startTime = new Date(),
        makePlatform = new MakePlatform();

    opts || (opts = {});
    opts.dir || (opts.dir = process.cwd());

    return makePlatform.init(path.resolve(opts.dir))
        .then(function () {
            var logger = makePlatform.getLogger();

            if (opts.noLog) {
                logger.setEnabled(false);
            } else if (opts.hideWarnings) {
                logger.hideWarnings();
            }

            if (opts.cache) {
                makePlatform.loadCache();
            }

            return makePlatform.buildTask(task, args)
                .then(function () {
                    if (opts.graph) {
                        console.log(makePlatform.getBuildGraph().render());
                    }

                    logger.log('build finished - ' + colors.red((new Date() - startTime) + 'ms'));

                    makePlatform.saveCache();
                    makePlatform.destruct();

                    return args;
                });
        })
        .fail(function (err) {
            if (opts.graph) {
                console.log(makePlatform.getBuildGraph().render());
            }

            console.error(err.stack);
            process.exit(1);
        });
};
<|endoftext|>


<commit_before>// polyfill.number.toLocaleString
/*global describe, it, expect*/

describe('number.toLocaleString(locale) polyfill', function() {
    'use strict';

    it('needs to be overridden for phantomjs', function() {
        var num = 123456;
        var locale = 'iq';

        function testLocale() {
            return (num).toLocaleString(locale);
        }

        expect(testLocale).not.toThrow();
    });

    it('returns a string', function() {
        var num = 123456;
        var locale = 'CA';

        expect(typeof (num.toLocaleString(locale))).toBe('string');
    });

    it('returns a string formatted in FR style (1\u00A0234.5) when passed FR', function() {
        var num = 1234.5;
        var locale = 'FR';

        expect(num.toLocaleString(locale)).toEqual('1\u00A0234,5');
    });

    it('returns a string formatted in US style (1,234.5) when passed US', function() {
        var num = 1234.5;
        var locale = 'US';

        expect(num.toLocaleString(locale)).toBe('1,234.5');
    });

    it('returns a string formatted in IT style (1.234,5) when passed IT', function() {
        var num = 1234.5;
        var locale = 'IT';

        expect(num.toLocaleString(locale)).toBe('1.234,5');
    });

    it('returns a formatted string based only on the language code in complex locale codes', function() {
        var num = 1234.5;
        var locale = 'it-US';

        expect(num.toLocaleString(locale)).toBe('1.234,5');
    });

    it('returns a string formatted in KR style (1,234.5) when passed KR', function() {
        var num = 1234.5;
        var locale = 'KR';

        expect(num.toLocaleString(locale)).toBe('1,234.5');
    });

    it('throws when the language tag does not conform to the standard', function() {
        var num = 1234.5;
        var locale = 'i';

        function testLocale() {
            return (num).toLocaleString(locale);
        }

        expect(testLocale).toThrow(new RangeError("Invalid language tag: " + locale));
    });

    it('should support options with minimumFractionDigits', function() {
        var num = 1234;
        var locale = 'it-IT';

        expect(num.toLocaleString(locale, { minimumFractionDigits: 2 })).toBe('1.234,00');
    });

    it('should support options with minimumFractionDigits', function() {
        var num = 1234.0000;
        var locale = 'it-IT';

        expect(num.toLocaleString(locale, { minimumFractionDigits: 4 })).toBe('1.234,0000');
    });

    it('returns a string formatted in US style (1,234.5) by default', function() {
        var num = 1234.5;

        expect(num.toLocaleString()).toBe('1,234.5');
        expect(num.toLocaleString('MX')).toBe('1,234.5');
        expect(num.toLocaleString('AU')).toBe('1,234.5');
    });

    it('returns a string formatted in Hungarian style (1 234,56) by default', function() {
        var num = 1234.56;

        expect(num.toLocaleString('hu')).toBe('1\u00A0234,56');
        expect(num.toLocaleString('hu-HU')).toBe('1\u00A0234,56');
    });

    it('returns currency properly formatted for the locale specified', function() {
        var num = 1234.56;
        var style = "currency";
        var currency = "USD";
        var currencyDisplay = "symbol";

        expect(num.toLocaleString("en-US", {
            style: style,
            currency: currency
        })).toBe("$1,234.56");

        expect(num.toLocaleString("de-DE", {
            style: style,
            currency: currency
        })).toBe("1.234,56 $");

        expect(num.toLocaleString("ko-KR", {
            style: style,
            currency: "krw"
        })).toBe("₩1,234.56");

        expect(num.toLocaleString("ja-JP", {
            style: style,
            currency: "jpy"
        })).toBe("￥1,234.56");

        expect(num.toLocaleString("hu", {
            style: style,
            currency: "huf"
        })).toBe("1\u00A0234,56 HUF");

        expect(num.toLocaleString("hu-HU", {
            style: style,
            currency: "huf"
        })).toBe("1\u00A0234,56 HUF");
    });
});
<commit_msg>Added test case for de-ch<commit_after>// polyfill.number.toLocaleString
/*global describe, it, expect*/

describe('number.toLocaleString(locale) polyfill', function() {
    'use strict';

    it('needs to be overridden for phantomjs', function() {
        var num = 123456;
        var locale = 'iq';

        function testLocale() {
            return (num).toLocaleString(locale);
        }

        expect(testLocale).not.toThrow();
    });

    it('returns a string', function() {
        var num = 123456;
        var locale = 'CA';

        expect(typeof (num.toLocaleString(locale))).toBe('string');
    });

    it('returns a string formatted in FR style (1\u00A0234.5) when passed FR', function() {
        var num = 1234.5;
        var locale = 'FR';

        expect(num.toLocaleString(locale)).toEqual('1\u00A0234,5');
    });

    it('returns a string formatted in US style (1,234.5) when passed US', function() {
        var num = 1234.5;
        var locale = 'US';

        expect(num.toLocaleString(locale)).toBe('1,234.5');
    });

    it('returns a string formatted in IT style (1.234,5) when passed IT', function() {
        var num = 1234.5;
        var locale = 'IT';

        expect(num.toLocaleString(locale)).toBe('1.234,5');
    });

    it("returns a string formatted in de-CH style (1'234.5) when passed de-CH", function() {
        var num = 1234.5;
        var locale = 'de-CH';

        expect(num.toLocaleString(locale)).toBe("1'234.5");
    }

    it('returns a formatted string based only on the language code in complex locale codes', function() {
        var num = 1234.5;
        var locale = 'it-US';

        expect(num.toLocaleString(locale)).toBe('1.234,5');
    });

    it('returns a string formatted in KR style (1,234.5) when passed KR', function() {
        var num = 1234.5;
        var locale = 'KR';

        expect(num.toLocaleString(locale)).toBe('1,234.5');
    });

    it('throws when the language tag does not conform to the standard', function() {
        var num = 1234.5;
        var locale = 'i';

        function testLocale() {
            return (num).toLocaleString(locale);
        }

        expect(testLocale).toThrow(new RangeError("Invalid language tag: " + locale));
    });

    it('should support options with minimumFractionDigits', function() {
        var num = 1234;
        var locale = 'it-IT';

        expect(num.toLocaleString(locale, { minimumFractionDigits: 2 })).toBe('1.234,00');
    });

    it('should support options with minimumFractionDigits', function() {
        var num = 1234.0000;
        var locale = 'it-IT';

        expect(num.toLocaleString(locale, { minimumFractionDigits: 4 })).toBe('1.234,0000');
    });

    it('returns a string formatted in US style (1,234.5) by default', function() {
        var num = 1234.5;

        expect(num.toLocaleString()).toBe('1,234.5');
        expect(num.toLocaleString('MX')).toBe('1,234.5');
        expect(num.toLocaleString('AU')).toBe('1,234.5');
    });

    it('returns a string formatted in Hungarian style (1 234,56) by default', function() {
        var num = 1234.56;

        expect(num.toLocaleString('hu')).toBe('1\u00A0234,56');
        expect(num.toLocaleString('hu-HU')).toBe('1\u00A0234,56');
    });

    it('returns currency properly formatted for the locale specified', function() {
        var num = 1234.56;
        var style = "currency";
        var currency = "USD";
        var currencyDisplay = "symbol";

        expect(num.toLocaleString("en-US", {
            style: style,
            currency: currency
        })).toBe("$1,234.56");

        expect(num.toLocaleString("de-DE", {
            style: style,
            currency: currency
        })).toBe("1.234,56 $");

        expect(num.toLocaleString("ko-KR", {
            style: style,
            currency: "krw"
        })).toBe("₩1,234.56");

        expect(num.toLocaleString("ja-JP", {
            style: style,
            currency: "jpy"
        })).toBe("￥1,234.56");

        expect(num.toLocaleString("hu", {
            style: style,
            currency: "huf"
        })).toBe("1\u00A0234,56 HUF");

        expect(num.toLocaleString("hu-HU", {
            style: style,
            currency: "huf"
        })).toBe("1\u00A0234,56 HUF");
    });
});
<|endoftext|>


<commit_before>/**
 * Created by cgcladera on 21/01/14.
 */
var mongoose        = require('mongoose'),
  Movie             = mongoose.model('Movie'),
  Media             = mongoose.model('Media'),
  ErrorNotification = mongoose.model('ErrorNotification');

exports.query = function(req, res){
  Movie.find(function(err, movies){
    if(err){
      res.send(404);
    }else {
      res.json(movies);
    }

  });
};
exports.get = function(req, res){
  var key = 'id';
  if(req.query.byId && req.query.byId === 'true'){
    key = '_id';
  }
  var query = {};
  query[key] = req.params.movieId;
  console.log(query);
  Movie.findOne(query, function(err, movie){
    if(err){
      return res.send(404);
    }
    if(!movie){
      return res.send(404);
    }
    var m = movie.toObject();
    movie.findMedias(function(err, medias){
      m.medias = medias;
      res.json(m);
    });
  });
};
exports.add = function(req, res){
  //TODO: Check request
  var data = {
    id: req.body.id.toLowerCase(),
    name: req.body.name,
    year: req.body.year,
    imageUrl: req.body.imageUrl,
    genders: req.body.genders.split(','),
    imdbUrl: req.body.imdbUrl,
    filmaffinityUrl: req.body.filmaffinityUrl
  };
  var movie = new Movie(data);
  movie.save(function(err, m){
    if(err){
      res.send(500, err);
    }else {
      res.send(200, m);
    }
  });
};
exports.remove = function(req, res){
  Movie.findOne({id: req.params.movieId}, function(err, movie){
    if(err){
      return res.send(404);
    }
    Media.remove({movie: movie._id}, function(err){
      if(err){
        return res.send(500);
      }
      movie.remove(function(err){
        if(err){
          res.send(500);
        }else {
          res.send(200);
        }
      });
    });
  });
};

exports.update = function(req, res){
  if(typeof req.body.genders === 'string'){
    req.body.genders = req.body.genders.split(',');
  }
  var data = {
    id: req.body.id.toLowerCase(),
    name: req.body.name,
    year: req.body.year,
    imageUrl: req.body.imageUrl,
    genders: req.body.genders,
    imdbUrl: req.body.imdbUrl,
    filmaffinityUrl: req.body.filmaffinityUrl
  };
  Movie.update({_id: req.body._id}, data,{},function(err){
    if(err){
      return res.send(500);
    }
    res.send(200);
  });
};

exports.notificateError = function(req, res){
  Media.findOne({_id: req.body.media}, function(err, media){
    if(err || media === undefined){
      return res.send(400);
    }
    req.body.user = req.user._id;
    var notification = new ErrorNotification(req.body);
    notification.save(function(err, n){
      if(err){
        return res.send(500);
      }
      res.json(n);
    });
  });
};

exports.getMediaErrors = function(req, res){
  ErrorNotification.getAll(function(err, errors){
    if(err){
      return res.send(500);
    }
    res.json(errors);
  });
};<commit_msg>Improves get method of Movies API<commit_after>/**
 * Created by cgcladera on 21/01/14.
 */
var mongoose        = require('mongoose'),
  Movie             = mongoose.model('Movie'),
  Media             = mongoose.model('Media'),
  ErrorNotification = mongoose.model('ErrorNotification');

exports.query = function(req, res){
  Movie.find(function(err, movies){
    if(err){
      return res.send(500);
    }
    res.json(movies);
  });
};
exports.get = function(req, res){
  var key = 'id';
  if(req.query.byId && req.query.byId === 'true'){
    key = '_id';
  }
  var query = {};
  query[key] = req.params.movieId;
  console.log(query);
  Movie.findOne(query, function(err, movie){
    if(err){
      return res.send(404);
    }
    if(!movie){
      return res.send(404);
    }
    var m = movie.toObject();
    movie.findMedias(function(err, medias){
      m.medias = medias;
      res.json(m);
    });
  });
};
exports.add = function(req, res){
  //TODO: Check request
  var data = {
    id: req.body.id.toLowerCase(),
    name: req.body.name,
    year: req.body.year,
    imageUrl: req.body.imageUrl,
    genders: req.body.genders.split(','),
    imdbUrl: req.body.imdbUrl,
    filmaffinityUrl: req.body.filmaffinityUrl
  };
  var movie = new Movie(data);
  movie.save(function(err, m){
    if(err){
      res.send(500, err);
    }else {
      res.send(200, m);
    }
  });
};
exports.remove = function(req, res){
  Movie.findOne({id: req.params.movieId}, function(err, movie){
    if(err){
      return res.send(404);
    }
    Media.remove({movie: movie._id}, function(err){
      if(err){
        return res.send(500);
      }
      movie.remove(function(err){
        if(err){
          res.send(500);
        }else {
          res.send(200);
        }
      });
    });
  });
};

exports.update = function(req, res){
  if(typeof req.body.genders === 'string'){
    req.body.genders = req.body.genders.split(',');
  }
  var data = {
    id: req.body.id.toLowerCase(),
    name: req.body.name,
    year: req.body.year,
    imageUrl: req.body.imageUrl,
    genders: req.body.genders,
    imdbUrl: req.body.imdbUrl,
    filmaffinityUrl: req.body.filmaffinityUrl
  };
  Movie.update({_id: req.body._id}, data,{},function(err){
    if(err){
      return res.send(500);
    }
    res.send(200);
  });
};

exports.notificateError = function(req, res){
  Media.findOne({_id: req.body.media}, function(err, media){
    if(err || media === undefined){
      return res.send(400);
    }
    req.body.user = req.user._id;
    var notification = new ErrorNotification(req.body);
    notification.save(function(err, n){
      if(err){
        return res.send(500);
      }
      res.json(n);
    });
  });
};

exports.getMediaErrors = function(req, res){
  ErrorNotification.getAll(function(err, errors){
    if(err){
      return res.send(500);
    }
    res.json(errors);
  });
};<|endoftext|>


<commit_before>
var http = require('http'),
    fs = require('fs'),
    path = require('path'),
    url = require('url');

exports.Apricot = Apricot;
sys = require('sys');

function Apricot(content,live) {
  var dom = require('jsdom-0.1.2/jsdom/level1/core').dom.level1.core;
  var browser = require('jsdom-0.1.2/jsdom/browser/index').windowAugmentation(dom);

  this.raw = content;

  // TODO, content should be applied to the whole document, not the body.

  browser.document.body.innerHTML = content;
  this.document = browser.document;
  this.window =  browser.window;
  this.matches = [];

  if (live) {
    this.live();
  }

  this.__defineGetter__("toHTML", function(){
    return this.document.body.innerHTML;
  });

  this.__defineGetter__("innerHTML", function(){
    return this.document.body.firstChild.innerHTML;
  });

  this.__defineGetter__("toDOM", function(){
    return this.document.body;
  });
}

Apricot.prototype = {
  find : function(pattern) {
    this.matches = [];
    var m = [];
    var sizzleSandbox = {};
    var sizzle = require("./sizzle").sizzleInit(sizzleSandbox,this.document);
    m = sizzle(pattern);

    for (var i = 0, len = m.length; i < len; ++i) {
      this.matches.push(m[i]);
    }
    return this;
  },

  live: function() {
    var Script = process.binding('evals').Script;
    console.alert = function(m) {
      console.log("Alerting: " + m);
    }

    console.console = {
      log: function(m) {
        console.log("Console: " + m);
      }
    }

    this.window.__defineSetter__("onload", function(e){
      e.call();
    });

    try {
      // Setup the page
      var sandbox = {
        document:this.document,
        window:this.window,
        setTimeout:this.window.setTimeout,
        setInterval:this.window.setInterval,
        alert:console.alert,
        console:console.console
      };

      // Add all script blocks to the scope
      this.find('script').each(function(script){
        if (script.src) {
          var fnLoaderHandle = function(e,d) {
            Script.runInNewContext(d,sandbox);
          }
          fs.readFile(script.src, encoding='utf8', fnLoaderHandle);

        } else {
          Script.runInNewContext(script.innerHTML,sandbox);
        }
      });

      // Call the onload (if it exists)
      this.find("[onload]").each(function(onload){
        var fnName = onload.getAttribute('onload');
        Script.runInNewContext(fnName,sandbox);
      });

    } catch(e){
      sys.puts(sys.inspect(e));
    }

  },

  each : function(fn) {
    for (var i = 0, len = this.matches.length; i < len; ++i) {
      fn.call(this,this.matches[i]);
    }
    return this;
  },

  remove  : function (html) { return this.html('remove', html); },
  inner   : function (html) { return this.html('inner', html); },
  outer   : function (html) { return this.html('outer', html); },
  top     : function (html) { return this.html('top', html); },
  bottom  : function (html) { return this.html('bottom', html); },
  before  : function (html) { return this.html('before', html); },
  after   : function (html) { return this.html('after', html); },

  html    : function(location, html) {
    this._clean(this);

    if (arguments.length == 0) {
      return this[0].innerHTML;
    }
    if (arguments.length == 1 && arguments[0] != 'remove') {
      html = location;
      location = 'inner';
    }

    return this.each(function(el) {
      var parent, list, len, i = 0;

      if (location == "inner") {

        if (typeof html == 'string') {
          el.innerHTML = html;
          list = el.getElementsByTagName('SCRIPT');
          len = list.length;
          for (; i < len; i++) {
            eval(list[i].text);
          }
        } else {
          el.innerHTML = '';
          el.appendChild(html);
        }
      } else if (location == "outer") {
        el.parentNode.replaceChild(this._wrapHelper(html, el), el);
      } else if (location == "top") {
        el.insertBefore(this._wrapHelper(html, el), el.firstChild);
      } else if (location == "bottom") {
        el.insertBefore(this._wrapHelper(html, el), null);
      } else if (location == "before") {
        el.parentNode.insertBefore(this._wrapHelper(html, el.parentNode), el);
      } else if (location == "after") {
        el.parentNode.insertBefore(this._wrapHelper(html, el.parentNode), el.nextSibling);
      } else if (location == "remove") {
        el.parentNode.removeChild(el);
      }
    });
  },

  hasClass: function(className, callback) {

    return (callback === undefined && this.matches.length == 1) ?
    hasClass(this.matches[0], className) :
    this.each(function(el) {
      if (hasClass(el, className)) {
        callback(el);
      }
    });
  },

  removeClass: function(className) {
    if (className === undefined) {
      this.each(function(el) {
        el.className = '';
      });
    } else {
      var re = getClassRegEx(className);
      this.each(function(el) {
        el.className = el.className.replace(re, '');
      });
    }
    return this;
  },

  addClass: function(className) {
    return this.each(function(el) {
      if (hasClass(el, className) === false) {
        el.className = trim(el.className + ' ' + className);
      }
    });
  },

  //
  // Private instance method
  //
  _wrapHelper : function(html, el) {
    return (typeof html === "string") ? this._wrap(html, getTag(el)) : html;
  },

  //
  // Private instance method
  //
  _clean : function(collection) {
    var ns = /\S/;
    collection.each(function(el) {
      var d = el,
      n = d.firstChild,
      ni = -1,
      nx;
      while (n) {
        nx = n.nextSibling;
        if (n.nodeType == 3 && !ns.test(n.nodeValue)) {
          d.removeChild(n);
        } else {
          n.nodeIndex = ++ni;
        }
        n = nx;
      }
    });
  },

  //
  // Private instance method
  //
  _wrap : function(xhtml, tag) {

    var attributes = {},
      re = /^<([A-Z][A-Z0-9]*)([^>]*)>(.*)<\/\1>/i,
      element,
      x,
      a,
      i = 0,
      attr,
      node,
      attrList;

    if (re.test(xhtml)) {
      result = re.exec(xhtml);
      tag = result[1];

      // if the node has any attributes, convert to object
      if (result[2] !== "") {
          attrList = result[2].split(/([A-Z]*\s*=\s*['|"][A-Z0-9:;#\s]*['|"])/i);

          for (; i < attrList.length; i++) {
              attr = attrList[i].replace(/^\s*|\s*$/g, "");
              if (attr !== "" && attr !== " ") {
                  node = attr.split('=');
                  attributes[node[0]] = node[1].replace(/(["']?)/g, '');
              }
          }
      }
      xhtml = result[3];
    }

    if (typeof(tag) === "undefined") {
      element = this.document.createTextNode(xhtml)
    } else {
      element = this.document.createElement(tag);
      for (x in attributes) {
          a = doc.createAttribute(x);
          a.nodeValue = attributes[x];
          element.setAttributeNode(a);
      }
      element.innerHTML = xhtml;
    }
    return element;
  },

  // This is the older version of ON from XUI.
  // TODO: grab the newer one.
  // TODO: add support for dispatchEvent in JSDom Level 2
  on: function(type, fn) {
    return this.each(function(el) {
      if (this.window.addEventListener) {
        el.addEventListener(type, fn, false);
      }
    });
  },

}

//
// Starting point for  data, returns a new Apricot Object
//
Apricot.parse = function (data, callback) {
  try {
    callback(null, new Apricot(data));
  }
  catch (error) {
    callback(error);
  }
}

//
// Starting point for File / HTTP, returns a new Apricot Object
//
Apricot.open = function(file, callback, live) {

  var fnLoaderHandle = function (err, data) {
    if (err) {
      callback(err);
    }
    else {
      try {
        var h = live ? new Apricot(data, true) : new Apricot(data);
        callback(null, h);
      }
      catch (error) {
        callback(error);
      }
    }
  };

  if (file.match(/^https?:\/\//)) {
    var urlInfo = url.parse(file, parseQueryString=false),
    host = http.createClient(((urlInfo.protocol === 'http:') ? 80 : 443), urlInfo.hostname),
    req_url = urlInfo.pathname;

    if (urlInfo.search) {
      req_url += urlInfo.search;
    }
    var request = host.request('GET', req_url, { host: urlInfo.hostname });

    request.addListener('response', function (response) {
      var data = '';
      response.addListener('data', function (chunk) {
        data += chunk;
      });
      response.addListener("end", function() {
        fnLoaderHandle(null, data);
      });
    });
    if (request.end) {
      request.end();
    } else {
      request.close();
    }

  } else {
    fs.readFile(file, encoding='utf8', fnLoaderHandle);
  }
};

//
// Helpers
//

var reClassNameCache = {};

// Via jQuery - used to avoid el.className = ' foo';
// Used for trimming whitespace
var rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;

// Helper for html Method
getTag = function(el) {
  return (el.firstChild === null) ? {'UL':'LI','DL':'DT','TR':'TD'}[el.tagName] || el.tagName : el.firstChild.tagName;
};

getClassRegEx = function(className) {
  var re = reClassNameCache[className];
  if (!re) {
    re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
    reClassNameCache[className] = re;
  }
  return re;
};

hasClass = function(el, className) {
  return getClassRegEx(className).test(el.className);
};

trim = function(text) {
  return (text || "").replace( rtrim, "" );
};

<commit_msg>No need to specify jsdom version number on  because npm handles correct dependency version loading for you.<commit_after>
var http = require('http'),
    fs = require('fs'),
    path = require('path'),
    url = require('url');

exports.Apricot = Apricot;
sys = require('sys');

function Apricot(content,live) {
  var dom = require('jsdom/jsdom/level1/core').dom.level1.core;
  var browser = require('jsdom/jsdom/browser/index').windowAugmentation(dom);

  this.raw = content;

  // TODO, content should be applied to the whole document, not the body.

  browser.document.body.innerHTML = content;
  this.document = browser.document;
  this.window =  browser.window;
  this.matches = [];

  if (live) {
    this.live();
  }

  this.__defineGetter__("toHTML", function(){
    return this.document.body.innerHTML;
  });

  this.__defineGetter__("innerHTML", function(){
    return this.document.body.firstChild.innerHTML;
  });

  this.__defineGetter__("toDOM", function(){
    return this.document.body;
  });
}

Apricot.prototype = {
  find : function(pattern) {
    this.matches = [];
    var m = [];
    var sizzleSandbox = {};
    var sizzle = require("./sizzle").sizzleInit(sizzleSandbox,this.document);
    m = sizzle(pattern);

    for (var i = 0, len = m.length; i < len; ++i) {
      this.matches.push(m[i]);
    }
    return this;
  },

  live: function() {
    var Script = process.binding('evals').Script;
    console.alert = function(m) {
      console.log("Alerting: " + m);
    }

    console.console = {
      log: function(m) {
        console.log("Console: " + m);
      }
    }

    this.window.__defineSetter__("onload", function(e){
      e.call();
    });

    try {
      // Setup the page
      var sandbox = {
        document:this.document,
        window:this.window,
        setTimeout:this.window.setTimeout,
        setInterval:this.window.setInterval,
        alert:console.alert,
        console:console.console
      };

      // Add all script blocks to the scope
      this.find('script').each(function(script){
        if (script.src) {
          var fnLoaderHandle = function(e,d) {
            Script.runInNewContext(d,sandbox);
          }
          fs.readFile(script.src, encoding='utf8', fnLoaderHandle);

        } else {
          Script.runInNewContext(script.innerHTML,sandbox);
        }
      });

      // Call the onload (if it exists)
      this.find("[onload]").each(function(onload){
        var fnName = onload.getAttribute('onload');
        Script.runInNewContext(fnName,sandbox);
      });

    } catch(e){
      sys.puts(sys.inspect(e));
    }

  },

  each : function(fn) {
    for (var i = 0, len = this.matches.length; i < len; ++i) {
      fn.call(this,this.matches[i]);
    }
    return this;
  },

  remove  : function (html) { return this.html('remove', html); },
  inner   : function (html) { return this.html('inner', html); },
  outer   : function (html) { return this.html('outer', html); },
  top     : function (html) { return this.html('top', html); },
  bottom  : function (html) { return this.html('bottom', html); },
  before  : function (html) { return this.html('before', html); },
  after   : function (html) { return this.html('after', html); },

  html    : function(location, html) {
    this._clean(this);

    if (arguments.length == 0) {
      return this[0].innerHTML;
    }
    if (arguments.length == 1 && arguments[0] != 'remove') {
      html = location;
      location = 'inner';
    }

    return this.each(function(el) {
      var parent, list, len, i = 0;

      if (location == "inner") {

        if (typeof html == 'string') {
          el.innerHTML = html;
          list = el.getElementsByTagName('SCRIPT');
          len = list.length;
          for (; i < len; i++) {
            eval(list[i].text);
          }
        } else {
          el.innerHTML = '';
          el.appendChild(html);
        }
      } else if (location == "outer") {
        el.parentNode.replaceChild(this._wrapHelper(html, el), el);
      } else if (location == "top") {
        el.insertBefore(this._wrapHelper(html, el), el.firstChild);
      } else if (location == "bottom") {
        el.insertBefore(this._wrapHelper(html, el), null);
      } else if (location == "before") {
        el.parentNode.insertBefore(this._wrapHelper(html, el.parentNode), el);
      } else if (location == "after") {
        el.parentNode.insertBefore(this._wrapHelper(html, el.parentNode), el.nextSibling);
      } else if (location == "remove") {
        el.parentNode.removeChild(el);
      }
    });
  },

  hasClass: function(className, callback) {

    return (callback === undefined && this.matches.length == 1) ?
    hasClass(this.matches[0], className) :
    this.each(function(el) {
      if (hasClass(el, className)) {
        callback(el);
      }
    });
  },

  removeClass: function(className) {
    if (className === undefined) {
      this.each(function(el) {
        el.className = '';
      });
    } else {
      var re = getClassRegEx(className);
      this.each(function(el) {
        el.className = el.className.replace(re, '');
      });
    }
    return this;
  },

  addClass: function(className) {
    return this.each(function(el) {
      if (hasClass(el, className) === false) {
        el.className = trim(el.className + ' ' + className);
      }
    });
  },

  //
  // Private instance method
  //
  _wrapHelper : function(html, el) {
    return (typeof html === "string") ? this._wrap(html, getTag(el)) : html;
  },

  //
  // Private instance method
  //
  _clean : function(collection) {
    var ns = /\S/;
    collection.each(function(el) {
      var d = el,
      n = d.firstChild,
      ni = -1,
      nx;
      while (n) {
        nx = n.nextSibling;
        if (n.nodeType == 3 && !ns.test(n.nodeValue)) {
          d.removeChild(n);
        } else {
          n.nodeIndex = ++ni;
        }
        n = nx;
      }
    });
  },

  //
  // Private instance method
  //
  _wrap : function(xhtml, tag) {

    var attributes = {},
      re = /^<([A-Z][A-Z0-9]*)([^>]*)>(.*)<\/\1>/i,
      element,
      x,
      a,
      i = 0,
      attr,
      node,
      attrList;

    if (re.test(xhtml)) {
      result = re.exec(xhtml);
      tag = result[1];

      // if the node has any attributes, convert to object
      if (result[2] !== "") {
          attrList = result[2].split(/([A-Z]*\s*=\s*['|"][A-Z0-9:;#\s]*['|"])/i);

          for (; i < attrList.length; i++) {
              attr = attrList[i].replace(/^\s*|\s*$/g, "");
              if (attr !== "" && attr !== " ") {
                  node = attr.split('=');
                  attributes[node[0]] = node[1].replace(/(["']?)/g, '');
              }
          }
      }
      xhtml = result[3];
    }

    if (typeof(tag) === "undefined") {
      element = this.document.createTextNode(xhtml)
    } else {
      element = this.document.createElement(tag);
      for (x in attributes) {
          a = doc.createAttribute(x);
          a.nodeValue = attributes[x];
          element.setAttributeNode(a);
      }
      element.innerHTML = xhtml;
    }
    return element;
  },

  // This is the older version of ON from XUI.
  // TODO: grab the newer one.
  // TODO: add support for dispatchEvent in JSDom Level 2
  on: function(type, fn) {
    return this.each(function(el) {
      if (this.window.addEventListener) {
        el.addEventListener(type, fn, false);
      }
    });
  },

}

//
// Starting point for  data, returns a new Apricot Object
//
Apricot.parse = function (data, callback) {
  try {
    callback(null, new Apricot(data));
  }
  catch (error) {
    callback(error);
  }
}

//
// Starting point for File / HTTP, returns a new Apricot Object
//
Apricot.open = function(file, callback, live) {

  var fnLoaderHandle = function (err, data) {
    if (err) {
      callback(err);
    }
    else {
      try {
        var h = live ? new Apricot(data, true) : new Apricot(data);
        callback(null, h);
      }
      catch (error) {
        callback(error);
      }
    }
  };

  if (file.match(/^https?:\/\//)) {
    var urlInfo = url.parse(file, parseQueryString=false),
    host = http.createClient(((urlInfo.protocol === 'http:') ? 80 : 443), urlInfo.hostname),
    req_url = urlInfo.pathname;

    if (urlInfo.search) {
      req_url += urlInfo.search;
    }
    var request = host.request('GET', req_url, { host: urlInfo.hostname });

    request.addListener('response', function (response) {
      var data = '';
      response.addListener('data', function (chunk) {
        data += chunk;
      });
      response.addListener("end", function() {
        fnLoaderHandle(null, data);
      });
    });
    if (request.end) {
      request.end();
    } else {
      request.close();
    }

  } else {
    fs.readFile(file, encoding='utf8', fnLoaderHandle);
  }
};

//
// Helpers
//

var reClassNameCache = {};

// Via jQuery - used to avoid el.className = ' foo';
// Used for trimming whitespace
var rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;

// Helper for html Method
getTag = function(el) {
  return (el.firstChild === null) ? {'UL':'LI','DL':'DT','TR':'TD'}[el.tagName] || el.tagName : el.firstChild.tagName;
};

getClassRegEx = function(className) {
  var re = reClassNameCache[className];
  if (!re) {
    re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
    reClassNameCache[className] = re;
  }
  return re;
};

hasClass = function(el, className) {
  return getClassRegEx(className).test(el.className);
};

trim = function(text) {
  return (text || "").replace( rtrim, "" );
};

<|endoftext|>


<commit_before>const sortBy = require('lodash/sortBy');

const unflatten = (items, { id = 'id', parentId = 'parentId', mapper = item => item } = {}, parent = null, level = 0) => {
  let children = items
    .filter(item => item[parentId] === parent)
    .map(item => mapper(
      item,
      parent ? items.filter(x => x[id] === parent)[0] : null
    ));

  // Sortieren nach Order-Nummer
  children = sortBy(children, [item => item.order]);

  // Rekursion
  children.forEach((item) => {
    item.children = unflatten(items, { id, parentId, mapper }, item[id], level + 1);
  });

  return children;
};

export default unflatten;
/*let sortBy = require('lodash/sortBy');

const unflatten = (array, options, parentId, level) => {
  if (!options) options = {};
  if (!options.parentId) options.parentId = 'parentId';
  if (!options.id) options.id = 'id';
  let mapper = options.mapper || (item => item);

  parentId = typeof parentId !== 'undefined' ? parentId : null;
  level = typeof level !== 'undefined' ? level : 0;

  let parent = parentId ? array.filter(x => x[options.id] == parentId)[0] : null;
  let children = array.filter(item => item[options.parentId] == parentId).map(item => mapper(item, parent));
  children = sortBy(children, item => item.order);
  children.forEach(item => {
    item.children = unflatten(array, options, item[options.id], level + 1);
  });
  return children;
};

module.exports = unflatten;*/
<commit_msg>unflatten with paths<commit_after>const sortBy = require('lodash/sortBy');

const unflatten = (items, { id = 'id', parentId = 'parentId', setPath, pathProp = 'path', mapper = item => item } = {}, parent = null, level = 0, currentPath = '') => {
  let children = items
    .filter(item => item[parentId] === parent)
    .map(item => mapper(
      item,
      parent ? items.filter(x => x[id] === parent)[0] : null
    ));

  // Sortieren nach Order-Nummer
  children = sortBy(children, [item => item.order]);

  // Rekursion
  children.forEach((item) => {
    if (setPath) item[pathProp] = setPath(currentPath, item);
    item.children = unflatten(items, { id, parentId, mapper, pathProp, setPath }, item[id], level + 1, item[pathProp]);
  });

  return children;
};

export default unflatten;
/*let sortBy = require('lodash/sortBy');

const unflatten = (array, options, parentId, level) => {
  if (!options) options = {};
  if (!options.parentId) options.parentId = 'parentId';
  if (!options.id) options.id = 'id';
  let mapper = options.mapper || (item => item);

  parentId = typeof parentId !== 'undefined' ? parentId : null;
  level = typeof level !== 'undefined' ? level : 0;

  let parent = parentId ? array.filter(x => x[options.id] == parentId)[0] : null;
  let children = array.filter(item => item[options.parentId] == parentId).map(item => mapper(item, parent));
  children = sortBy(children, item => item.order);
  children.forEach(item => {
    item.children = unflatten(array, options, item[options.id], level + 1);
  });
  return children;
};

module.exports = unflatten;*/
<|endoftext|>


<commit_before>import test from 'ava';
import sinon from 'sinon';
import Fetch from '../src/Fetch';

let stubFetch;

const textPromise = Promise.resolve({
  status: 200,
  headers: {
    get: () => 'text/plain',
  },
  text: () => Promise.resolve(),
});

const jsonPromise = Promise.resolve({
  status: 200,
  headers: {
    get: () => 'application/json',
  },
  json: () => Promise.resolve(),
});

test.afterEach(() => {
  if (stubFetch) {
    stubFetch.restore();
  }
});

test('should return a promise', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => '',
    },
    text: () => Promise.resolve(''),
  });

  const result = Fetch.get('/');

  t.is(result instanceof Promise, true);
});

test('should return text when asked', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => 'text/plain',
    },
    text: () => Promise.resolve('Test Mocha'),
  });

  return Fetch.get('/')
    .then(data => t.is(data, 'Test Mocha'));
});

test('should return json when asked', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => 'application/json',
    },
    json: () => Promise.resolve({
      result: 'Test Mocha',
    }),
  });

  return Fetch.get('/')
    .then(data => t.deepEqual(data, {
      result: 'Test Mocha',
    }));
});

test('should return error when 400 or more', (t) => {
  global.fetch = () => Promise.resolve({
    status: 400,
    headers: {
      get: () => 'text/plain',
    },
    text: () => Promise.resolve('Test Mocha Error'),
  });

  return Fetch.get('/')
    .then(() => t.is(false, true))
    .catch((data) => {
      t.is(data.content, 'Test Mocha Error');
      t.is(String(data), 'Test Mocha Error');
    });
});

test('should return jsonError when 400 or more', (t) => {
  global.fetch = () => Promise.resolve({
    status: 500,
    headers: {
      get: () => 'application/json',
    },
    json: () => Promise.resolve({
      error: 'Test Mocha Error',
    }),
  });

  return Fetch.get('/')
    .then(() => t.is(false, true))
    .catch((data) => {
      t.deepEqual(data.content, { error: 'Test Mocha Error' });
      t.is(String(data), '{"error":"Test Mocha Error"}');
    });
});

test('should return error when text fail', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => 'text/plain',
    },
    text: () => Promise.reject(new Error('Mocha Text Error')),
  });

  return Fetch.get('/')
    .then(() => t.is(false, true))
    .catch(data => t.is(String(data), 'Error: Mocha Text Error'));
});

test('should return error when json fail', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => 'application/json',
    },
    json: () => Promise.reject(new Error('Mocha JSON Error')),
  });

  return Fetch.get('/')
    .then(() => t.is(false, true))
    .catch(data => t.is(String(data), 'Error: Mocha JSON Error'));
});

test.serial('should pass header', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').header('custom', 'test').get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        custom: 'test',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass auth', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').auth('token').get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        Authorization: 'token',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass contentType for json', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => jsonPromise);

  return Fetch.url('/').contentJson().get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass contentType for text', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').contentText().get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'text/plain',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass accept for json', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => jsonPromise);

  return Fetch.url('/').acceptJson().get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        Accept: 'application/json',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass accept for text', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').acceptText().get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        Accept: 'text/plain',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass body', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').body('Hello World').post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'text/plain',
      },
      body: 'Hello World',
      method: 'POST',
    }), true));
});

test.serial('should pass json body', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => jsonPromise);

  return Fetch.url('/').body(JSON.stringify({ hello: 'World' })).post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'application/json',
      },
      body: '{"hello":"World"}',
      method: 'POST',
    }), true));
});

test.serial('should not pass body if undefined', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').body().post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'POST',
    }), true));
});

test.serial('should guess json content', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => jsonPromise);

  return Fetch.post('/', JSON.stringify({ hello: 'World' }))
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'application/json',
      },
      body: '{"hello":"World"}',
      method: 'POST',
    }), true));
});

test.serial('should guess text content', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.post('/', '{hello":"World"}')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'text/plain',
      },
      body: '{hello":"World"}',
      method: 'POST',
    }), true));
});

test.serial('should not guess content if already defined', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').contentText().body('{"hello":"World"}').post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'text/plain',
      },
      body: '{"hello":"World"}',
      method: 'POST',
    }), true));
});

test.serial('should not guess content if forbidden', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').body('{"hello":"World"}', false).post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      body: '{"hello":"World"}',
      method: 'POST',
    }), true));
});

test('should use given content handler', (t) => {
  global.fetch = () => Promise.resolve({
    status: 204,
  });

  let result;
  const customContentHandler = content => (result = content);

  return Fetch.url('/').content(customContentHandler).get().then(() => {
    t.deepEqual(result, {
      status: 204,
    });
  });
});

test('should use given error handler', (t) => {
  global.fetch = () => Promise.resolve({
    status: 404,
    reason: 'Failed',
  });

  let result;
  const customErrorHandler = (content) => {
    result = content.reason;

    return Promise.reject();
  };

  return Fetch.url('/').error(customErrorHandler).get()
    .then(() => t.is(false, true))
    .catch(() => t.is(result, 'Failed'));
});

test.serial('should send GET', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.get('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'GET',
    }), true));
});

test.serial('should send POST', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.post('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'POST',
    }), true));
});

test.serial('should send PUT', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.put('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'PUT',
    }), true));
});

test.serial('should send PATCH', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.patch('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'PATCH',
    }), true));
});

test.serial('should send DELETE', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.delete('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'DELETE',
    }), true));
});
<commit_msg>Changing is true to tru for test<commit_after>import test from 'ava';
import sinon from 'sinon';
import Fetch from '../src/Fetch';

let stubFetch;

const textPromise = Promise.resolve({
  status: 200,
  headers: {
    get: () => 'text/plain',
  },
  text: () => Promise.resolve(),
});

const jsonPromise = Promise.resolve({
  status: 200,
  headers: {
    get: () => 'application/json',
  },
  json: () => Promise.resolve(),
});

test.afterEach(() => {
  if (stubFetch) {
    stubFetch.restore();
  }
});

test('should return a promise', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => '',
    },
    text: () => Promise.resolve(''),
  });

  const result = Fetch.get('/');

  t.true(result instanceof Promise);
});

test('should return text when asked', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => 'text/plain',
    },
    text: () => Promise.resolve('Test Mocha'),
  });

  return Fetch.get('/')
    .then(data => t.is(data, 'Test Mocha'));
});

test('should return json when asked', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => 'application/json',
    },
    json: () => Promise.resolve({
      result: 'Test Mocha',
    }),
  });

  return Fetch.get('/')
    .then(data => t.deepEqual(data, {
      result: 'Test Mocha',
    }));
});

test('should return error when 400 or more', (t) => {
  global.fetch = () => Promise.resolve({
    status: 400,
    headers: {
      get: () => 'text/plain',
    },
    text: () => Promise.resolve('Test Mocha Error'),
  });

  return Fetch.get('/')
    .then(() => t.true(false))
    .catch((data) => {
      t.is(data.content, 'Test Mocha Error');
      t.is(String(data), 'Test Mocha Error');
    });
});

test('should return jsonError when 400 or more', (t) => {
  global.fetch = () => Promise.resolve({
    status: 500,
    headers: {
      get: () => 'application/json',
    },
    json: () => Promise.resolve({
      error: 'Test Mocha Error',
    }),
  });

  return Fetch.get('/')
    .then(() => t.true(false))
    .catch((data) => {
      t.deepEqual(data.content, { error: 'Test Mocha Error' });
      t.is(String(data), '{"error":"Test Mocha Error"}');
    });
});

test('should return error when text fail', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => 'text/plain',
    },
    text: () => Promise.reject(new Error('Mocha Text Error')),
  });

  return Fetch.get('/')
    .then(() => t.true(false))
    .catch(data => t.is(String(data), 'Error: Mocha Text Error'));
});

test('should return error when json fail', (t) => {
  global.fetch = () => Promise.resolve({
    status: 200,
    headers: {
      get: () => 'application/json',
    },
    json: () => Promise.reject(new Error('Mocha JSON Error')),
  });

  return Fetch.get('/')
    .then(() => t.true(false))
    .catch(data => t.is(String(data), 'Error: Mocha JSON Error'));
});

test.serial('should pass header', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').header('custom', 'test').get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        custom: 'test',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass auth', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').auth('token').get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        Authorization: 'token',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass contentType for json', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => jsonPromise);

  return Fetch.url('/').contentJson().get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass contentType for text', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').contentText().get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'text/plain',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass accept for json', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => jsonPromise);

  return Fetch.url('/').acceptJson().get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        Accept: 'application/json',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass accept for text', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').acceptText().get()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        Accept: 'text/plain',
      },
      method: 'GET',
    }), true));
});

test.serial('should pass body', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').body('Hello World').post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'text/plain',
      },
      body: 'Hello World',
      method: 'POST',
    }), true));
});

test.serial('should pass json body', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => jsonPromise);

  return Fetch.url('/').body(JSON.stringify({ hello: 'World' })).post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'application/json',
      },
      body: '{"hello":"World"}',
      method: 'POST',
    }), true));
});

test.serial('should not pass body if undefined', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').body().post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'POST',
    }), true));
});

test.serial('should guess json content', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => jsonPromise);

  return Fetch.post('/', JSON.stringify({ hello: 'World' }))
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'application/json',
      },
      body: '{"hello":"World"}',
      method: 'POST',
    }), true));
});

test.serial('should guess text content', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.post('/', '{hello":"World"}')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'text/plain',
      },
      body: '{hello":"World"}',
      method: 'POST',
    }), true));
});

test.serial('should not guess content if already defined', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').contentText().body('{"hello":"World"}').post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {
        'Content-Type': 'text/plain',
      },
      body: '{"hello":"World"}',
      method: 'POST',
    }), true));
});

test.serial('should not guess content if forbidden', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.url('/').body('{"hello":"World"}', false).post()
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      body: '{"hello":"World"}',
      method: 'POST',
    }), true));
});

test('should use given content handler', (t) => {
  global.fetch = () => Promise.resolve({
    status: 204,
  });

  let result;
  const customContentHandler = content => (result = content);

  return Fetch.url('/').content(customContentHandler).get().then(() => {
    t.deepEqual(result, {
      status: 204,
    });
  });
});

test('should use given error handler', (t) => {
  global.fetch = () => Promise.resolve({
    status: 404,
    reason: 'Failed',
  });

  let result;
  const customErrorHandler = (content) => {
    result = content.reason;

    return Promise.reject();
  };

  return Fetch.url('/').error(customErrorHandler).get()
    .then(() => t.true(false))
    .catch(() => t.is(result, 'Failed'));
});

test.serial('should send GET', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.get('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'GET',
    }), true));
});

test.serial('should send POST', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.post('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'POST',
    }), true));
});

test.serial('should send PUT', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.put('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'PUT',
    }), true));
});

test.serial('should send PATCH', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.patch('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'PATCH',
    }), true));
});

test.serial('should send DELETE', (t) => {
  stubFetch = sinon.stub(global, 'fetch').callsFake(() => textPromise);

  return Fetch.delete('/')
    .then(() => t.is(stubFetch.calledWith('/', {
      headers: {},
      method: 'DELETE',
    }), true));
});
<|endoftext|>


<commit_before>"use strict"

/**
 * @type {Chai.Assert}
 */
var assert = require('chai').assert
var xdTesting = require('../../lib/index')
var templates = require('../../lib/templates')
var Flow = require('../../lib/flow/flow')

describe('xdTesting', function() {

    let baseUrl = 'http://localhost:8090/'

    describe('command arguments @large', function () {
        it('are part of a step\'s command name', function () {
            let scenario = {A: templates.devices.chrome()}
            return xdTesting.multiremote(scenario).init()
                .url(baseUrl)
                .click('#button')
                .checkpoint('check')
                .getFlow().then(flow => {
                    let steps = flow.steps()
                    let stepCommandNames = steps.map(step => step.commands)
                        .filter(commands => commands.length > 0)
                    assert.lengthOf(stepCommandNames, 3)
                })
                .end()
        })
    })

    describe('#getFlow @large', function () {
        it('returns the flow object', function () {
            let scenario = {A: templates.devices.chrome()}
            return xdTesting.multiremote(scenario).init()
                .url(baseUrl)
                .click('#button')
                .checkpoint('end')
                .getFlow().then(flow => {
                    assert.instanceOf(flow, Flow)
                    assert.property(flow, 'devices')
                    assert.deepPropertyVal(flow, 'devices.A.deviceId', 'A')
                })
                .end()

        })
    })

    describe('app framework integration', () => {

        beforeEach(() => {
            // Reset config
            xdTesting.baseUrl = null
        })

        it('should load xdTesting.baseUrl after init @large', () => {
            let options = {
                A: templates.devices.chrome()
            }

            xdTesting.baseUrl = 'http://localhost/'

            return xdTesting.multiremote(options).init()
                .getUrl().then(url => assert.equal(url, xdTesting.baseUrl))
                .end()
        })

        describe('for XD-MVC', () => {

            // Define a custom adapter
            xdTesting.appFramework = xdTesting.adapter.xdmvc

            it('app property has devices @medium', () => {
                let options = {
                    A: templates.devices.chrome()
                }

                let devices = xdTesting.multiremote(options)
                let app = devices
                    .app()

                assert.property(app, 'devices')
                assert.isDefined(app.devices)

                return devices.end()
            })

            it('app property should have getEventCounter @medium', () => {
                let options = {
                    A: templates.devices.chrome()
                }

                let devices = xdTesting.multiremote(options)
                let app = devices
                    .app()

                assert.property(app, 'getEventCounter')
                assert.instanceOf(app.getEventCounter, Function)

                return devices.end()
            })

            it('should get the event counter after loading a url @large', () => {
                let options = {
                    A: templates.devices.chrome()
                }
                xdTesting.baseUrl = "http://localhost:8082/gallery.html"
                return xdTesting.multiremote(options).init()
                     //TODO load a XD-MVC app
                    .app().injectEventLogger()
                    .app().getEventCounter().then(counter => {
                        assert.property(counter, 'XDdisconnection')
                        assert.property(counter, 'XDconnection')
                        assert.property(counter, 'XDdevice')
                        assert.property(counter, 'XDroles')
                        assert.property(counter, 'XDsync')
                        assert.property(counter, 'XDserverReady')
                        assert.property(counter, 'XDothersRolesChanged')

                        assert.typeOf(counter['XDdisconnection'], 'number')
                        assert.typeOf(counter['XDconnection'], 'number')
                        assert.typeOf(counter['XDdevice'], 'number')
                        assert.typeOf(counter['XDroles'], 'number')
                        assert.typeOf(counter['XDsync'], 'number')
                        assert.typeOf(counter['XDserverReady'], 'number')
                        assert.typeOf(counter['XDothersRolesChanged'], 'number')
                    })
                    .end()

                    /**
                     * App property?
                     */

                    //// Pair devices via url
                    //.app.pairDevicesViaUrl()
                    // Get event counter
                    //.app.getEventCounter().then(counter => assert.equal(counter.XDconnection == 1))
                // Wait for the next event of a type
                //.app.waitForEvent('XDconnection')
                //// Wait until the event type counter equals a value
                //.app.waitForEventCount('XDconnection', 2)
                //// Custom command
                //.app.addCommand('pairDevicesViaGUI', function() {
                //    return this.click(...)
                //})
            })
        })

    })
})
<commit_msg>Test that it should not load xdTesting.baseUrl if it's not set<commit_after>"use strict"

/**
 * @type {Chai.Assert}
 */
var assert = require('chai').assert
var xdTesting = require('../../lib/index')
var templates = require('../../lib/templates')
var Flow = require('../../lib/flow/flow')

describe('xdTesting', function() {

    let baseUrl = 'http://localhost:8090/'

    describe('command arguments @large', function () {
        it('are part of a step\'s command name', function () {
            let scenario = {A: templates.devices.chrome()}
            return xdTesting.multiremote(scenario).init()
                .url(baseUrl)
                .click('#button')
                .checkpoint('check')
                .getFlow().then(flow => {
                    let steps = flow.steps()
                    let stepCommandNames = steps.map(step => step.commands)
                        .filter(commands => commands.length > 0)
                    assert.lengthOf(stepCommandNames, 3)
                })
                .end()
        })
    })

    describe('#getFlow @large', function () {
        it('returns the flow object', function () {
            let scenario = {A: templates.devices.chrome()}
            return xdTesting.multiremote(scenario).init()
                .url(baseUrl)
                .click('#button')
                .checkpoint('end')
                .getFlow().then(flow => {
                    assert.instanceOf(flow, Flow)
                    assert.property(flow, 'devices')
                    assert.deepPropertyVal(flow, 'devices.A.deviceId', 'A')
                })
                .end()

        })
    })

    describe('app framework integration', () => {

        beforeEach(() => {
            // Reset config
            xdTesting.baseUrl = null
        })

        it('should load xdTesting.baseUrl after init @large', () => {
            let options = {
                A: templates.devices.chrome()
            }

            xdTesting.baseUrl = 'http://localhost/'

            return xdTesting.multiremote(options).init()
                .getUrl().then(url => assert.equal(url, xdTesting.baseUrl))
                .end()
        })

        it('should not load xdTesting.baseUrl if it\'s not set @large', () => {
            let options = {
                A: templates.devices.chrome()
            }

            xdTesting.baseUrl = null

            return xdTesting.multiremote(options).init()
                .getUrl().then(url => assert.equal(url, 'data:,'))
                .end()
        })

        describe('for XD-MVC', () => {

            // Define a custom adapter
            xdTesting.appFramework = xdTesting.adapter.xdmvc

            it('app property has devices @medium', () => {
                let options = {
                    A: templates.devices.chrome()
                }

                let devices = xdTesting.multiremote(options)
                let app = devices
                    .app()

                assert.property(app, 'devices')
                assert.isDefined(app.devices)

                return devices.end()
            })

            it('app property should have getEventCounter @medium', () => {
                let options = {
                    A: templates.devices.chrome()
                }

                let devices = xdTesting.multiremote(options)
                let app = devices
                    .app()

                assert.property(app, 'getEventCounter')
                assert.instanceOf(app.getEventCounter, Function)

                return devices.end()
            })

            it('should get the event counter after loading a url @large', () => {
                let options = {
                    A: templates.devices.chrome()
                }
                xdTesting.baseUrl = "http://localhost:8082/gallery.html"
                return xdTesting.multiremote(options).init()
                     //TODO load a XD-MVC app
                    .app().injectEventLogger()
                    .app().getEventCounter().then(counter => {
                        assert.property(counter, 'XDdisconnection')
                        assert.property(counter, 'XDconnection')
                        assert.property(counter, 'XDdevice')
                        assert.property(counter, 'XDroles')
                        assert.property(counter, 'XDsync')
                        assert.property(counter, 'XDserverReady')
                        assert.property(counter, 'XDothersRolesChanged')

                        assert.typeOf(counter['XDdisconnection'], 'number')
                        assert.typeOf(counter['XDconnection'], 'number')
                        assert.typeOf(counter['XDdevice'], 'number')
                        assert.typeOf(counter['XDroles'], 'number')
                        assert.typeOf(counter['XDsync'], 'number')
                        assert.typeOf(counter['XDserverReady'], 'number')
                        assert.typeOf(counter['XDothersRolesChanged'], 'number')
                    })
                    .end()

                    /**
                     * App property?
                     */

                    //// Pair devices via url
                    //.app.pairDevicesViaUrl()
                    // Get event counter
                    //.app.getEventCounter().then(counter => assert.equal(counter.XDconnection == 1))
                // Wait for the next event of a type
                //.app.waitForEvent('XDconnection')
                //// Wait until the event type counter equals a value
                //.app.waitForEventCount('XDconnection', 2)
                //// Custom command
                //.app.addCommand('pairDevicesViaGUI', function() {
                //    return this.click(...)
                //})
            })
        })

    })
})
<|endoftext|>