<commit_before>'use strict';

const fs = require('fs');
const http = require('http');
const path = require('path');

const env = require('../../modules/environment');

describe('browser/index.html', function desc() {
  this.timeout(30000);

  const config = {
    version: 1,
    teams: [{
      name: 'example_1',
      url: env.mattermostURL + '1'
    }, {
      name: 'example_2',
      url: env.mattermostURL + '2'
    }]
  };

  const serverPort = 8181;

  before(() => {
    function serverCallback(req, res) {
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      res.end(fs.readFileSync(path.resolve(env.sourceRootDir, 'test/modules/test.html'), 'utf-8'));
    }
    this.server = http.createServer(serverCallback).listen(serverPort, '127.0.0.1');
  });

  beforeEach(() => {
    fs.writeFileSync(env.configFilePath, JSON.stringify(config));
    this.app = env.getSpectronApp();
    return this.app.start();
  });

  afterEach(() => {
    if (this.app && this.app.isRunning()) {
      return this.app.stop();
    }
    return true;
  });

  after((done) => {
    this.server.close(done);
  });

  it('should NOT show tabs when there is one team', () => {
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      url: env.mattermostURL
    }));
    return this.app.restart().then(() => {
      return this.app.client.waitUntilWindowLoaded().
        isExisting('#tabBar').then((existing) => {
          existing.should.be.false;
        });
    });
  });

  it('should set src of webview from config file', () => {
    return this.app.client.waitUntilWindowLoaded().
      getAttribute('#mattermostView0', 'src').then((src) => {
        src.should.equal(config.teams[0].url);
      }).
      getAttribute('#mattermostView1', 'src').then((src) => {
        src.should.equal(config.teams[1].url);
      }).
      isExisting('#mattermostView2').then((existing) => {
        existing.should.be.false;
      });
  });

  it('should set name of tab from config file', () => {
    return this.app.client.waitUntilWindowLoaded().
      getText('#teamTabItem0').then((text) => {
        text.should.equal(config.teams[0].name);
      }).
      getText('#teamTabItem1').then((text) => {
        text.should.equal(config.teams[1].name);
      });
  });

  it('should show only the selected team', () => {
    return this.app.client.waitUntilWindowLoaded().
      isVisible('#mattermostView0').then((visible) => {
        visible.should.be.true;
      }).
      isVisible('#mattermostView1').then((visible) => {
        visible.should.be.false;
      }).
      click('#teamTabItem1').
      waitForVisible('#mattermostView1', 2000).
      isVisible('#mattermostView0').then((visible) => {
        visible.should.be.false;
      });
  });

  it('should show error when using incorrect URL', () => {
    this.timeout(30000);
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      version: 1,
      teams: [{
        name: 'error_1',
        url: 'http://false'
      }]
    }));
    return this.app.restart().then(() => {
      return this.app.client.waitUntilWindowLoaded().
        waitForVisible('#mattermostView0-fail', 20000);
    });
  });

  it('should set window title by using webview\'s one', () => {
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      version: 1,
      teams: [{
        name: 'title_test',
        url: `http://localhost:${serverPort}`
      }]
    }));
    return this.app.restart().then(() => {
      return this.app.client.waitUntilWindowLoaded().pause(2000);
    }).then(() => {
      return this.app.browserWindow.getTitle();
    }).then((title) => {
      title.should.equal('Mattermost Desktop testing html');
    });
  });

  // Skip because it's very unstable in CI
  it.skip('should update window title when the activated tab\'s title is updated', () => {
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      version: 1,
      teams: [{
        name: 'title_test_0',
        url: `http://localhost:${serverPort}`
      }, {
        name: 'title_test_1',
        url: `http://localhost:${serverPort}`
      }]
    }));
    return this.app.restart().then(() => {
      return this.app.client.waitUntilWindowLoaded().pause(500);
    }).then(() => {
      // Note: Indices of webview are correct.
      // Somehow they are swapped.
      return this.app.client.
        windowByIndex(2).
        execute(() => {
          document.title = 'Title 0';
        }).
        windowByIndex(0).
        pause(500).
        browserWindow.getTitle().then((title) => {
          title.should.equal('Title 0');
        }).
        windowByIndex(1).
        execute(() => {
          document.title = 'Title 1';
        }).
        windowByIndex(0).
        pause(500).
        browserWindow.getTitle().then((title) => {
          title.should.equal('Title 0');
        });
    });
  });

  // Skip because it's very unstable in CI
  it.skip('should update window title when a tab is selected', () => {
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      version: 1,
      teams: [{
        name: 'title_test_0',
        url: `http://localhost:${serverPort}`
      }, {
        name: 'title_test_1',
        url: `http://localhost:${serverPort}`
      }]
    }));
    return this.app.restart().then(() => {
      // Note: Indices of webview are correct.
      // Somehow they are swapped.
      return this.app.client.
        waitUntilWindowLoaded().
        pause(500).
        windowByIndex(2).
        execute(() => {
          document.title = 'Title 0';
        }).
        windowByIndex(1).
        execute(() => {
          document.title = 'Title 1';
        }).
        windowByIndex(0).
        pause(500).
        browserWindow.getTitle().then((title) => {
          title.should.equal('Title 0');
        }).
        click('#teamTabItem1').
        pause(500).
        browserWindow.getTitle().then((title) => {
          title.should.equal('Title 1');
        });
    });
  });

  it('should open the new server prompt after clicking the add button', () => {
    // See settings_test for specs that cover the actual prompt
    return this.app.client.waitUntilWindowLoaded().
      click('#addServerButton').
      pause(500).
      isExisting('#newServerModal').then((existing) => {
        existing.should.be.true;
      });
  });
});
<commit_msg>Wait unselected team disappears in test<commit_after>'use strict';

const fs = require('fs');
const http = require('http');
const path = require('path');

const env = require('../../modules/environment');

describe('browser/index.html', function desc() {
  this.timeout(30000);

  const config = {
    version: 1,
    teams: [{
      name: 'example_1',
      url: env.mattermostURL + '1'
    }, {
      name: 'example_2',
      url: env.mattermostURL + '2'
    }]
  };

  const serverPort = 8181;

  before(() => {
    function serverCallback(req, res) {
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      res.end(fs.readFileSync(path.resolve(env.sourceRootDir, 'test/modules/test.html'), 'utf-8'));
    }
    this.server = http.createServer(serverCallback).listen(serverPort, '127.0.0.1');
  });

  beforeEach(() => {
    fs.writeFileSync(env.configFilePath, JSON.stringify(config));
    this.app = env.getSpectronApp();
    return this.app.start();
  });

  afterEach(() => {
    if (this.app && this.app.isRunning()) {
      return this.app.stop();
    }
    return true;
  });

  after((done) => {
    this.server.close(done);
  });

  it('should NOT show tabs when there is one team', () => {
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      url: env.mattermostURL
    }));
    return this.app.restart().then(() => {
      return this.app.client.waitUntilWindowLoaded().
        isExisting('#tabBar').then((existing) => {
          existing.should.be.false;
        });
    });
  });

  it('should set src of webview from config file', () => {
    return this.app.client.waitUntilWindowLoaded().
      getAttribute('#mattermostView0', 'src').then((src) => {
        src.should.equal(config.teams[0].url);
      }).
      getAttribute('#mattermostView1', 'src').then((src) => {
        src.should.equal(config.teams[1].url);
      }).
      isExisting('#mattermostView2').then((existing) => {
        existing.should.be.false;
      });
  });

  it('should set name of tab from config file', () => {
    return this.app.client.waitUntilWindowLoaded().
      getText('#teamTabItem0').then((text) => {
        text.should.equal(config.teams[0].name);
      }).
      getText('#teamTabItem1').then((text) => {
        text.should.equal(config.teams[1].name);
      });
  });

  it('should show only the selected team', () => {
    return this.app.client.waitUntilWindowLoaded().
      waitForVisible('#mattermostView0', 2000).
      waitForVisible('#mattermostView1', 2000, true).
      click('#teamTabItem1').
      waitForVisible('#mattermostView1', 2000).
      waitForVisible('#mattermostView0', 2000, true);
  });

  it('should show error when using incorrect URL', () => {
    this.timeout(30000);
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      version: 1,
      teams: [{
        name: 'error_1',
        url: 'http://false'
      }]
    }));
    return this.app.restart().then(() => {
      return this.app.client.waitUntilWindowLoaded().
        waitForVisible('#mattermostView0-fail', 20000);
    });
  });

  it('should set window title by using webview\'s one', () => {
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      version: 1,
      teams: [{
        name: 'title_test',
        url: `http://localhost:${serverPort}`
      }]
    }));
    return this.app.restart().then(() => {
      return this.app.client.waitUntilWindowLoaded().pause(2000);
    }).then(() => {
      return this.app.browserWindow.getTitle();
    }).then((title) => {
      title.should.equal('Mattermost Desktop testing html');
    });
  });

  // Skip because it's very unstable in CI
  it.skip('should update window title when the activated tab\'s title is updated', () => {
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      version: 1,
      teams: [{
        name: 'title_test_0',
        url: `http://localhost:${serverPort}`
      }, {
        name: 'title_test_1',
        url: `http://localhost:${serverPort}`
      }]
    }));
    return this.app.restart().then(() => {
      return this.app.client.waitUntilWindowLoaded().pause(500);
    }).then(() => {
      // Note: Indices of webview are correct.
      // Somehow they are swapped.
      return this.app.client.
        windowByIndex(2).
        execute(() => {
          document.title = 'Title 0';
        }).
        windowByIndex(0).
        pause(500).
        browserWindow.getTitle().then((title) => {
          title.should.equal('Title 0');
        }).
        windowByIndex(1).
        execute(() => {
          document.title = 'Title 1';
        }).
        windowByIndex(0).
        pause(500).
        browserWindow.getTitle().then((title) => {
          title.should.equal('Title 0');
        });
    });
  });

  // Skip because it's very unstable in CI
  it.skip('should update window title when a tab is selected', () => {
    fs.writeFileSync(env.configFilePath, JSON.stringify({
      version: 1,
      teams: [{
        name: 'title_test_0',
        url: `http://localhost:${serverPort}`
      }, {
        name: 'title_test_1',
        url: `http://localhost:${serverPort}`
      }]
    }));
    return this.app.restart().then(() => {
      // Note: Indices of webview are correct.
      // Somehow they are swapped.
      return this.app.client.
        waitUntilWindowLoaded().
        pause(500).
        windowByIndex(2).
        execute(() => {
          document.title = 'Title 0';
        }).
        windowByIndex(1).
        execute(() => {
          document.title = 'Title 1';
        }).
        windowByIndex(0).
        pause(500).
        browserWindow.getTitle().then((title) => {
          title.should.equal('Title 0');
        }).
        click('#teamTabItem1').
        pause(500).
        browserWindow.getTitle().then((title) => {
          title.should.equal('Title 1');
        });
    });
  });

  it('should open the new server prompt after clicking the add button', () => {
    // See settings_test for specs that cover the actual prompt
    return this.app.client.waitUntilWindowLoaded().
      click('#addServerButton').
      pause(500).
      isExisting('#newServerModal').then((existing) => {
        existing.should.be.true;
      });
  });
});
<|endoftext|>


<commit_before>
/**
 * WPCOM module
 */

var WPCOM = require('../');
var Site = require('../lib/site');
var assert = require('assert');

/**
 * Testing data
 */

var fixture = require('./fixture');

describe('wpcom.site.category', function() {
  // Create `wpcom` and `site` global instances
  var wpcom = WPCOM(fixture.site.token);
  var site = wpcom.site(fixture.site.url);

  // global var to store category added
  var testing_category;

  // Create a new_category before to start tests
  var new_category;
  before(function(done){
    site.category()
    .add(fixture.category, function(err, category) {
      if (err) throw err;

      new_category = category;
      done();
    });
  });

  after(function(done){
    site.category(new_category.slug)
    .delete(function(err, category) {
      if (err) throw err;

      done();
    });
  });

  describe('wpcom.site.category.get()', function(){

    it('should get added category', function(done){
      site.category(new_category.slug)
      .get(function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.ok(data instanceof Object, 'data is not an object');
        assert.equal(new_category.slug, data.slug);
        assert.equal(new_category.name, data.name);
        done();
      });
    });
  });

  describe('wpcom.site.category.add()', function(){

    it('should add a new category', function(done){
      var category = site.category();

      fixture.category.name += '-added';
      category.add(fixture.category, function(err, data){
        if (err) throw err;

        // checking some data date
        assert.ok(data);
        assert.ok(data instanceof Object, 'data is not an object');

        // store added catogory
        testing_category = data;

        done();
      });
    });
  });

  describe('wpcom.site.category.update()', function(){

    it('should edit the new added category', function(done){
      var category = site.category(testing_category.slug);
      var edited_name = fixture.category.name + '-edited';

      category.update({ name: edited_name }, function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.equal(edited_name, data.name);

        // update added category
        testing_category = data;

        done();
      });
    });
  });

  describe('wpcom.site.category.delete()', function(){

    it('should delete the new added category', function(done){
      site.category(testing_category.slug)
      .delete(function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.equal('true', data.success);
        assert.equal(testing_category.slug, data.slug);

        done();
      });
    });
  });

});<commit_msg>test: minor comment improvement<commit_after>
/**
 * WPCOM module
 */

var WPCOM = require('../');
var Site = require('../lib/site');
var assert = require('assert');

/**
 * Testing data
 */

var fixture = require('./fixture');

describe('wpcom.site.category', function() {
  // Create `wpcom` and `site` global instances
  var wpcom = WPCOM(fixture.site.token);
  var site = wpcom.site(fixture.site.url);

  // global var to store testing category
  var testing_category;

  // Create a new_category before to start tests
  var new_category;
  before(function(done){
    site.category()
    .add(fixture.category, function(err, category) {
      if (err) throw err;

      new_category = category;
      done();
    });
  });

  after(function(done){
    site.category(new_category.slug)
    .delete(function(err, category) {
      if (err) throw err;

      done();
    });
  });

  describe('wpcom.site.category.get()', function(){

    it('should get added category', function(done){
      site.category(new_category.slug)
      .get(function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.ok(data instanceof Object, 'data is not an object');
        assert.equal(new_category.slug, data.slug);
        assert.equal(new_category.name, data.name);
        done();
      });
    });
  });

  describe('wpcom.site.category.add()', function(){

    it('should add a new category', function(done){
      var category = site.category();

      fixture.category.name += '-added';
      category.add(fixture.category, function(err, data){
        if (err) throw err;

        // checking some data date
        assert.ok(data);
        assert.ok(data instanceof Object, 'data is not an object');

        // store added catogory
        testing_category = data;

        done();
      });
    });
  });

  describe('wpcom.site.category.update()', function(){

    it('should edit the new added category', function(done){
      var category = site.category(testing_category.slug);
      var edited_name = fixture.category.name + '-edited';

      category.update({ name: edited_name }, function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.equal(edited_name, data.name);

        // update added category
        testing_category = data;

        done();
      });
    });
  });

  describe('wpcom.site.category.delete()', function(){

    it('should delete the new added category', function(done){
      site.category(testing_category.slug)
      .delete(function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.equal('true', data.success);
        assert.equal(testing_category.slug, data.slug);

        done();
      });
    });
  });

});<|endoftext|>


<commit_before>import { assert } from '../chai.js';
import * as internal from "../../src/internal.js";
import OpenCloseMixin from "../../src/OpenCloseMixin.js";
import OverlayMixin from "../../src/OverlayMixin.js";
import ReactiveElement from "../../src/ReactiveElement.js";

const Base = OpenCloseMixin(OverlayMixin(ReactiveElement));

class OverlayTest extends Base {
  [internal.render](changed) {
    if (super[internal.render]) {
      super[internal.render](changed);
    }
    this.tabIndex = 0;
  }
}
customElements.define("overlay-test", OverlayTest);

describe("OverlayMixin", function() {
  let container;

  before(() => {
    container = document.getElementById("container");
  });

  afterEach(() => {
    container.innerHTML = "";
  });

  it("sets a default z-index", async () => {
    const fixture = new OverlayTest();
    container.appendChild(fixture);
    await fixture.open();
    // Mocha test runner has element with z-index of 1, so we expect the
    // overlay to get a default z-index of 2.
    assert.equal(fixture.style.zIndex, "2");
  });

  it("sets a default z-index even if component creates a stacking context", async () => {
    // This test is for Safari, where getComputedStyle(element).zIndex returns "0"
    // if the element creates a stacking context.
    const fixture = new OverlayTest();
    fixture.style.position = "fixed"; // Force a stacking context.
    container.appendChild(fixture);
    await fixture.open();
    // Mocha test runner has element with z-index of 1, so we expect the
    // overlay to get a default z-index of 2.
    assert.equal(fixture.style.zIndex, "2");
  });

  it("leaves the z-index alone if one is specified", async () => {
    const fixture = new OverlayTest();
    fixture.style.zIndex = 10;
    container.appendChild(fixture);
    await fixture.open();
    assert.equal(fixture.style.zIndex, "10");
  });

  it("gives overlay focus when opened, restores focus to previous element when closed", async () => {
    const fixture = new OverlayTest();
    container.appendChild(fixture);
    const input = document.createElement("input");
    container.appendChild(input);
    input.focus();
    assert.equal(document.activeElement, input);
    await fixture.open();
    assert.equal(document.activeElement, fixture);
    await fixture.close();
    assert.equal(document.activeElement, input);
  });

  it("appends overlay to body if it not already present, removes it when done", async () => {
    const fixture = new OverlayTest();
    assert.equal(fixture.parentNode, null);
    await fixture.open();
    assert.equal(fixture.parentNode, document.body);
    await fixture.close();
    assert.equal(fixture.parentNode, null);
  });

  it("leaves overlay where it is, if it is already in the DOM", async () => {
    const div = document.createElement("div");
    const fixture = new OverlayTest();
    div.appendChild(fixture);
    container.appendChild(div);
    await fixture.open();
    assert.equal(fixture.parentNode, div);
    await fixture.close();
    assert.equal(fixture.parentNode, div);
  });
});
<commit_msg>Adhere to types as the DOM defines it.<commit_after>import { assert } from '../chai.js';
import * as internal from "../../src/internal.js";
import OpenCloseMixin from "../../src/OpenCloseMixin.js";
import OverlayMixin from "../../src/OverlayMixin.js";
import ReactiveElement from "../../src/ReactiveElement.js";

const Base = OpenCloseMixin(OverlayMixin(ReactiveElement));

class OverlayTest extends Base {
  [internal.render](changed) {
    if (super[internal.render]) {
      super[internal.render](changed);
    }
    this.tabIndex = 0;
  }
}
customElements.define("overlay-test", OverlayTest);

describe("OverlayMixin", function() {
  let container;

  before(() => {
    container = document.getElementById("container");
  });

  afterEach(() => {
    container.innerHTML = "";
  });

  it("sets a default z-index", async () => {
    const fixture = new OverlayTest();
    container.appendChild(fixture);
    await fixture.open();
    // Mocha test runner has element with z-index of 1, so we expect the
    // overlay to get a default z-index of 2.
    assert.equal(fixture.style.zIndex, "2");
  });

  it("sets a default z-index even if component creates a stacking context", async () => {
    // This test is for Safari, where getComputedStyle(element).zIndex returns "0"
    // if the element creates a stacking context.
    const fixture = new OverlayTest();
    fixture.style.position = "fixed"; // Force a stacking context.
    container.appendChild(fixture);
    await fixture.open();
    // Mocha test runner has element with z-index of 1, so we expect the
    // overlay to get a default z-index of 2.
    assert.equal(fixture.style.zIndex, "2");
  });

  it("leaves the z-index alone if one is specified", async () => {
    const fixture = new OverlayTest();
    fixture.style.zIndex = "10";
    container.appendChild(fixture);
    await fixture.open();
    assert.equal(fixture.style.zIndex, "10");
  });

  it("gives overlay focus when opened, restores focus to previous element when closed", async () => {
    const fixture = new OverlayTest();
    container.appendChild(fixture);
    const input = document.createElement("input");
    container.appendChild(input);
    input.focus();
    assert.equal(document.activeElement, input);
    await fixture.open();
    assert.equal(document.activeElement, fixture);
    await fixture.close();
    assert.equal(document.activeElement, input);
  });

  it("appends overlay to body if it not already present, removes it when done", async () => {
    const fixture = new OverlayTest();
    assert.equal(fixture.parentNode, null);
    await fixture.open();
    assert.equal(fixture.parentNode, document.body);
    await fixture.close();
    assert.equal(fixture.parentNode, null);
  });

  it("leaves overlay where it is, if it is already in the DOM", async () => {
    const div = document.createElement("div");
    const fixture = new OverlayTest();
    div.appendChild(fixture);
    container.appendChild(div);
    await fixture.open();
    assert.equal(fixture.parentNode, div);
    await fixture.close();
    assert.equal(fixture.parentNode, div);
  });
});
<|endoftext|>


<commit_before>var TwitterNode = require('../lib').TwitterNode,
         assert = require('assert'),
            sys = require('sys');

process.mixin(GLOBAL, require('ntest'));

describe("json TwitterNode instance")
  before(function() { this.twit = new TwitterNode(); })

  it("accepts JSON in chunks", function() {
    var promise = new process.Promise();
    var result;

    this.twit.addListener('tweet', function(tweet) {
      result = tweet
      promise.emitSuccess()
    })

    this.twit.processTweet("")
    this.twit.processTweet(" ")
    this.twit.processTweet("{")
    this.twit.processTweet('"a":{')
    this.twit.processTweet('"b":1')
    this.twit.processTweet("}\n}\n{\"a\":1}")

    if(!promise.hasFired && promise._blocking) promise.wait()

    assert.ok(result)
    assert.equal(1, result.a.b)
  })

  it("emits tweet with parsed JSON tweet", function() {
    var promise = new process.Promise();
    var result;
    this.twit
      .addListener('tweet', function(tweet) {
        result = tweet
        promise.emitSuccess()
      })
      .addListener('limit', function(tweet) {
        promise.emitError()
      })
      .addListener('delete', function(tweet) {
        promise.emitError()
      })
      .processTweet('{"a":1}')

    if(!promise.hasFired) promise.wait()
    assert.equal(1, result.a)
  })

  it("emits delete with parsed JSON delete command", function() {
    var promise = new process.Promise();
    this.twit
      .addListener('tweet', function(tweet) {
        promise.emitError()
      })
      .addListener('limit', function(tweet) {
        promise.emitError()
      })
      .addListener('delete', function(tweet) {
        result = tweet
        promise.emitSuccess()
      })
      .processTweet('{"delete":{"status":{"id": 1234}}}')

    if(!promise.hasFired) promise.wait()
    assert.equal(1234, result.status.id)
  })

  it("emits limit with parsed JSON limit command", function() {
    var promise = new process.Promise();
    this.twit
      .addListener('tweet', function(tweet) {
        promise.emitError()
      })
      .addListener('delete', function(tweet) {
        promise.emitError()
      })
      .addListener('limit', function(tweet) {
        result = tweet
        promise.emitSuccess()
      })
      .processTweet('{"limit":{"track": 1234}}')

    if(!promise.hasFired) promise.wait()
    assert.equal(1234, result.track)
  })

describe("default TwitterNode instance")
  before(function() { this.twit = new TwitterNode(); })

  it("has default requestUrl()", function() {
    assert.equal("/1/statuses/filter.json", this.twit.requestUrl())
  })

  it("has empty params", function() {
    assert.equal('', this.twit.buildParams())
  })

  it("has default port", function() {
    assert.equal(80, this.twit.port)
  })

  it("has default host", function() {
    assert.equal('stream.twitter.com', this.twit.host)
  })

  it("can add tracking keywords", function() {
    this.twit.track('abc+def')
    this.twit.track('ghi')
    assert.equal('?track=abc%2Bdef%2Cghi', this.twit.buildParams())
  })

  it("can add following users", function() {
    this.twit.follow(123)
    this.twit.follow(456)
    assert.equal('?follow=123%2C456', this.twit.buildParams())
  })

describe("custom TwitterNode instance")
  before(function() {
    this.options = {
      port:81,
      host:'10.0.0.1',
      path: 'abc/',
      action: 'retweet',
      format: 'xml',
      follow: [123,456],
      track: ['abc', 'def'],
      headers: {'a': 'abc'},
      params: {count: 5}
    }
    this.twit = new TwitterNode(this.options);
  })

  it("has default requestUrl()", function() {
    assert.equal("abc/retweet.xml" + this.twit.buildParams(), this.twit.requestUrl())
  })

  it("merges given headers with defaults", function() {
    assert.equal('abc', this.twit.headers.a)
    assert.ok(this.twit.headers['User-Agent'])
  })

  it("has empty params", function() {
    assert.equal('?count=5&track=abc%2Cdef&follow=123%2C456', this.twit.buildParams())
  })

  it("sets port", function() {
    assert.equal(this.options.port, this.twit.port)
  })

  it("sets host", function() {
    assert.equal(this.options.host, this.twit.host)
  })<commit_msg>spacing tweak<commit_after>var TwitterNode = require('../lib').TwitterNode,
         assert = require('assert'),
            sys = require('sys');

process.mixin(GLOBAL, require('ntest'));

describe("json TwitterNode instance")
  before(function() { this.twit = new TwitterNode(); })

  it("accepts JSON in chunks", function() {
    var promise = new process.Promise();
    var result;

    this.twit.addListener('tweet', function(tweet) {
      result = tweet
      promise.emitSuccess()
    })

    this.twit.processTweet("")
    this.twit.processTweet(" ")
    this.twit.processTweet("{")
    this.twit.processTweet('"a":{')
    this.twit.processTweet('"b":1')
    this.twit.processTweet("}\n}\n{\"a\":1}")

    if(!promise.hasFired && promise._blocking) promise.wait()

    assert.ok(result)
    assert.equal(1, result.a.b)
  })

  it("emits tweet with parsed JSON tweet", function() {
    var promise = new process.Promise();
    var result;
    this.twit
      .addListener('tweet', function(tweet) {
        result = tweet
        promise.emitSuccess()
      })
      .addListener('limit', function(tweet) {
        promise.emitError()
      })
      .addListener('delete', function(tweet) {
        promise.emitError()
      })
      .processTweet('{"a":1}')

    if(!promise.hasFired) promise.wait()
    assert.equal(1, result.a)
  })

  it("emits delete with parsed JSON delete command", function() {
    var promise = new process.Promise();
    this.twit
      .addListener('tweet', function(tweet) {
        promise.emitError()
      })
      .addListener('limit', function(tweet) {
        promise.emitError()
      })
      .addListener('delete', function(tweet) {
        result = tweet
        promise.emitSuccess()
      })
      .processTweet('{"delete":{"status":{"id": 1234}}}')

    if(!promise.hasFired) promise.wait()
    assert.equal(1234, result.status.id)
  })

  it("emits limit with parsed JSON limit command", function() {
    var promise = new process.Promise();
    this.twit
      .addListener('tweet', function(tweet) {
        promise.emitError()
      })
      .addListener('delete', function(tweet) {
        promise.emitError()
      })
      .addListener('limit', function(tweet) {
        result = tweet
        promise.emitSuccess()
      })
      .processTweet('{"limit":{"track": 1234}}')

    if(!promise.hasFired) promise.wait()
    assert.equal(1234, result.track)
  })

describe("default TwitterNode instance")
  before(function() { this.twit = new TwitterNode(); })

  it("has default requestUrl()", function() {
    assert.equal("/1/statuses/filter.json", this.twit.requestUrl())
  })

  it("has empty params", function() {
    assert.equal('', this.twit.buildParams())
  })

  it("has default port", function() {
    assert.equal(80, this.twit.port)
  })

  it("has default host", function() {
    assert.equal('stream.twitter.com', this.twit.host)
  })

  it("can add tracking keywords", function() {
    this.twit.track('abc+def')
    this.twit.track('ghi')
    assert.equal('?track=abc%2Bdef%2Cghi', this.twit.buildParams())
  })

  it("can add following users", function() {
    this.twit.follow(123)
    this.twit.follow(456)
    assert.equal('?follow=123%2C456', this.twit.buildParams())
  })

describe("custom TwitterNode instance")
  before(function() {
    this.options = {
      port:    81,
      host:    '10.0.0.1',
      path:    'abc/',
      action:  'retweet',
      format:  'xml',
      follow:  [123,456],
      track:   ['abc', 'def'],
      headers: {'a': 'abc'},
      params:  {count: 5}
    }
    this.twit = new TwitterNode(this.options);
  })

  it("has default requestUrl()", function() {
    assert.equal("abc/retweet.xml" + this.twit.buildParams(), this.twit.requestUrl())
  })

  it("merges given headers with defaults", function() {
    assert.equal('abc', this.twit.headers.a)
    assert.ok(this.twit.headers['User-Agent'])
  })

  it("has empty params", function() {
    assert.equal('?count=5&track=abc%2Cdef&follow=123%2C456', this.twit.buildParams())
  })

  it("sets port", function() {
    assert.equal(this.options.port, this.twit.port)
  })

  it("sets host", function() {
    assert.equal(this.options.host, this.twit.host)
  })<|endoftext|>


<commit_before>if(typeof(define) !== 'function') {
  var define = require('amdefine');
}
define([], function() {

  var suites = [];

  var consoleLog, fakeLogs;

  function FakeRemote(){
    this.connected = true;
    RemoteStorage.eventHandling(this, 'connected', 'disconnected');
  }

  function fakeRequest(path){
    var promise = promising();
    console.log('GET CALLED')
    if(path == '/testing403')
        promise.fulfill(403);
    else
        promise.fulfill(200);
    return promise;
  }
  FakeRemote.prototype = {
    get: fakeRequest,
    put: fakeRequest,
    delete: fakeRequest
  }

  function FakeLocal(){

  }
  FakeLocal.prototype = {
    fireInitial: function(){/*ignore*/}
  }

  function fakeConsoleLog() {
    fakeLogs.push(Array.prototype.slice.call(arguments));
  }

  function replaceConsoleLog() {
    consoleLog = console.log;
    console.log = fakeConsoleLog;
  }

  function restoreConsoleLog() {
    console.log = consoleLog;
    consoleLog = undefined;
  }

  function assertNoConsoleLog(test) {
    test.assert(fakeLogs.length, 0);
  }

  function assertConsoleLog(test) {
    var expected = Array.prototype.slice.call(arguments, 1);
    test.assert(fakeLogs[0], expected);
  }

  suites.push({
    name: "remoteStorage",
    desc: "the RemoteStorage instance",
    setup:  function(env, test) {
      require('./src/remotestorage');
      require('./src/eventhandling');
      require('./lib/promising')
      RemoteStorage.prototype.remote = new FakeRemote();
      //RemoteStorage.prototype.local = new FakeLocal();
      test.done();
    },
    beforeEach: function(env, test) {
      remoteStorage = new RemoteStorage();
      //remoteStorage._emit('ready');
      env.rs = remoteStorage;
      test.done()
    },
    tests: [
      {
        desc: "#get emiting error RemoteStorage.Unauthorized on 403",
        run: function(env, test) {
          var success = false;
          env.rs.on('error', function(e) {
            if(e instanceof RemoteStorage.Unauthorized)
              success = true;
          });
          env.rs.get('/testing403').then(function(status){
            test.assert(success, true);
            test.assert(status, 403);
          });
        }
      },
      {
        desc: "#put emiting error RemoteStorage.Unauthorized on 403",
        run: function(env, test) {
          var success = false;
          env.rs.on('error', function(e) {
            if(e instanceof RemoteStorage.Unauthorized)
              success = true;
          })
          env.rs.put('/testing403').then(function(status){
            test.assert(success, true);
          });
        }
      },
      {
        desc: "#delete emiting error RemoteStorage.Unauthorized on 403",
        run: function(env, test) {
          var success = false;
          env.rs.on('error', function(e) {
            if(e instanceof RemoteStorage.Unauthorized)
              success = true;
          })
          env.rs.delete('/testing403').then(function(status){
            test.assert(success, true);
          });
        }
      },
      {
        desc: "#get #put #delete not emmitting Error when getting 200",
        run: function(env, test) {
          var success = true;
          env.rs.on('error', function(e) {
            success = false
          })
          env.rs.get('/testing200').then(function() {
            test.assert(success, true);
          });
          env.rs.put('/testing200').then(function() {
            test.assert(success, true);
          });
          env.rs.delete('/testing200').then(function() {
            test.assert(success, true);
          });
        }
      }
    ]
  });

  suites.push({
    name: "RemoteStorage",
    desc: "The global RemoteStorage namespace",
    setup: function(env, test) {
      require('./src/remotestorage');
      test.done();
    },

    beforeEach: function(env, test) {
      fakeLogs = [];
      test.done();
    },

    tests: [

      {
        desc: "exports the global RemoteStorage function",
        run: function(env, test) {
          test.assertType(global.RemoteStorage, 'function');
        }
      },

      {
        desc: "#log doesn't call console.log by default",
        run: function(env, test) {
          replaceConsoleLog();
          try {
            RemoteStorage.log('message');
            assertNoConsoleLog(test);
          } catch(e) {
            restoreConsoleLog();
            throw e;
          }
          restoreConsoleLog();
        }
      },

      {
        desc: "#log calls console.log, when _log is true",
        run: function(env, test) {
          replaceConsoleLog();
          try {
            RemoteStorage._log = true;
            RemoteStorage.log('foo', 'bar', 'baz');
            assertConsoleLog(test, 'foo', 'bar', 'baz');
          } catch(e) {
            restoreConsoleLog();
            RemoteStorage._log = false;
            throw e;
          }
          restoreConsoleLog();
        }
      }
    ]
  });

  return suites;

});
<commit_msg>fixing tests for remotestorage instance<commit_after>if(typeof(define) !== 'function') {
  var define = require('amdefine');
}
define([], function() {

  var suites = [];

  var consoleLog, fakeLogs;

  function FakeRemote(){
    this.connected = true;
    RemoteStorage.eventHandling(this, 'connected', 'disconnected');
  }

  function fakeRequest(path){
    var promise = promising();
    console.log('GET CALLED')
    if(path == '/testing403')
        promise.fulfill(403);
    else
        promise.fulfill(200);
    return promise;
  }
  FakeRemote.prototype = {
    get: fakeRequest,
    put: fakeRequest,
    delete: fakeRequest
  }

  function FakeLocal(){

  }
  FakeLocal.prototype = {
    fireInitial: function(){/*ignore*/}
  }

  function fakeConsoleLog() {
    fakeLogs.push(Array.prototype.slice.call(arguments));
  }

  function replaceConsoleLog() {
    consoleLog = console.log;
    console.log = fakeConsoleLog;
  }

  function restoreConsoleLog() {
    console.log = consoleLog;
    consoleLog = undefined;
  }

  function assertNoConsoleLog(test) {
    test.assert(fakeLogs.length, 0);
  }

  function assertConsoleLog(test) {
    var expected = Array.prototype.slice.call(arguments, 1);
    test.assert(fakeLogs[0], expected);
  }

  suites.push({
    name: "remoteStorage",
    desc: "the RemoteStorage instance",
    setup:  function(env, test) {
      require('./src/remotestorage');
      require('./src/eventhandling');
      require('./lib/promising')
      if(global.rs_eventhandling) {
        RemoteStorage.eventHandling = global.rs_eventhandling;
      } else {
        global.rs_eventhandling = RemoteStorage.eventHandling;
      }

      RemoteStorage.prototype.remote = new FakeRemote();
      //RemoteStorage.prototype.local = new FakeLocal();
      test.done();
    },
    beforeEach: function(env, test) {
      remoteStorage = new RemoteStorage();
      //remoteStorage._emit('ready');
      env.rs = remoteStorage;
      test.done()
    },
    tests: [
      {
        desc: "#get emiting error RemoteStorage.Unauthorized on 403",
        run: function(env, test) {
          var success = false;
          env.rs.on('error', function(e) {
            if(e instanceof RemoteStorage.Unauthorized)
              success = true;
          });
          env.rs.get('/testing403').then(function(status){
            test.assertAnd(status, 403);
            test.assertAnd(success, true);
            test.done();
          });
        }
      },
      {
        desc: "#put emiting error RemoteStorage.Unauthorized on 403",
        run: function(env, test) {
          var success = false;
          env.rs.on('error', function(e) {
            if(e instanceof RemoteStorage.Unauthorized)
              success = true;
          })
          env.rs.put('/testing403').then(function(status){
            test.assert(success, true);
          });
        }
      },
      {
        desc: "#delete emiting error RemoteStorage.Unauthorized on 403",
        run: function(env, test) {
          var success = false;
          env.rs.on('error', function(e) {
            if(e instanceof RemoteStorage.Unauthorized)
              success = true;
          })
          env.rs.delete('/testing403').then(function(status){
            test.assert(success, true);
          });
        }
      },
      {
        desc: "#get #put #delete not emmitting Error when getting 200",
        run: function(env, test) {
          var success = true;
          var c = 0;
          function test_done(){
            c+=1
            if(c==3)
              test.done();
          }
          env.rs.on('error', function(e) {
            success = false
          })
          env.rs.get('/testing200').then(function() {
            test.assertAnd(success, true);
            test_done();
          });
          env.rs.put('/testing200').then(function() {
            test.assertAnd(success, true);
            test_done();
          });
          env.rs.delete('/testing200').then(function() {
            test.assertAnd(success, true);
            test_done()
          });
        }
      }
    ]
  });

  suites.push({
    name: "RemoteStorage",
    desc: "The global RemoteStorage namespace",
    setup: function(env, test) {
      require('./src/remotestorage');
      test.done();
    },

    beforeEach: function(env, test) {
      fakeLogs = [];
      test.done();
    },

    tests: [

      {
        desc: "exports the global RemoteStorage function",
        run: function(env, test) {
          test.assertType(global.RemoteStorage, 'function');
        }
      },

      {
        desc: "#log doesn't call console.log by default",
        run: function(env, test) {
          replaceConsoleLog();
          try {
            RemoteStorage.log('message');
            assertNoConsoleLog(test);
          } catch(e) {
            restoreConsoleLog();
            throw e;
          }
          restoreConsoleLog();
        }
      },

      {
        desc: "#log calls console.log, when _log is true",
        run: function(env, test) {
          replaceConsoleLog();
          try {
            RemoteStorage._log = true;
            RemoteStorage.log('foo', 'bar', 'baz');
            assertConsoleLog(test, 'foo', 'bar', 'baz');
          } catch(e) {
            restoreConsoleLog();
            RemoteStorage._log = false;
            throw e;
          }
          restoreConsoleLog();
        }
      }
    ]
  });

  return suites;

});
<|endoftext|>


<commit_before>/* global describe, it */

var expect = require('expect.js'),
    sdk = require('postman-collection'),
    runtimeVersion = require('../../package').version,
    requesterUtil = require('../../lib/requester/util');

describe('requester util', function () {
    describe('.getRequestOptions', function () {
        it('should use http as the default protocol', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                header: [{
                    key: 'alpha',
                    value: 'foo'
                }],
                body: {
                    mode: 'raw',
                    raw: '{"alpha": "foo"}'
                }
            });

            expect(requesterUtil.getRequestOptions(request)).to.eql({
                headers: {
                    alpha: 'foo',
                    'User-Agent': 'PostmanRuntime/' + runtimeVersion,
                    'Content-Type': 'text/plain',
                    Accept: '*/*',
                    Host: 'postman-echo.com'
                },
                body: '{"alpha": "foo"}',
                url: 'http://postman-echo.com/post',
                method: 'POST',
                jar: true,
                timeout: undefined,
                gzip: true,
                useQuerystring: true,
                strictSSL: undefined,
                followRedirect: undefined,
                followAllRedirects: undefined,
                encoding: null,
                agentOptions: {keepAlive: undefined}
            });
        });

        it('should use https where applicable', function () {
            var request = new sdk.Request({
                url: 'https://postman-echo.com',
                method: 'GET',
                header: [{
                    key: 'alpha',
                    value: 'foo'
                }]
            });

            expect(requesterUtil.getRequestOptions(request)).to.eql({
                headers: {
                    alpha: 'foo',
                    'User-Agent': 'PostmanRuntime/6.2.2',
                    Accept: '*/*',
                    Host: 'postman-echo.com'
                },
                url: 'https://postman-echo.com',
                method: 'GET',
                jar: true,
                timeout: undefined,
                gzip: true,
                useQuerystring: true,
                strictSSL: undefined,
                followRedirect: undefined,
                followAllRedirects: undefined,
                encoding: null,
                agentOptions: {keepAlive: undefined}
            });
        });
    });

    describe('.ensureHeaderExists', function () {
        it('should not mutate the header if it already exists', function () {
            var headers = {alpha: 'foo', beta: 'bar'};

            requesterUtil.ensureHeaderExists(headers, 'alpha');
            expect(headers).to.eql({alpha: 'foo', beta: 'bar'});
        });

        it('should correctly set a missing header', function () {
            var headers = {alpha: 'foo', beta: 'bar'};

            requesterUtil.ensureHeaderExists(headers, 'gamma', 'baz');
            expect(headers).to.eql({alpha: 'foo', beta: 'bar', gamma: 'baz'});
        });
    });

    describe('.getRequestHeaders', function () {
        it('should handle invalid input correctly', function () {
            var result = requesterUtil.getRequestHeaders({});
            expect(result).to.be(undefined);
        });

        it('should correctly fetch request headers from a sdk Request instance', function () {
            var request = new sdk.Request({
                    url: 'postman-echo.com',
                    method: 'GET',
                    header: [
                        {key: 'alpha', value: 'foo'},
                        {key: 'beta', value: 'bar', disabled: true},
                        {key: 'gamma', value: 'baz'},
                        {key: 'alpha', value: 'next'},
                        {key: 'alpha', value: 'other'}
                    ]
                }),
                headers = requesterUtil.getRequestHeaders(request);

            expect(headers).to.eql({
                alpha: ['foo', 'next', 'other'],
                gamma: 'baz'
            });
        });
    });

    describe('.getRequestBody', function () {
        it('should correctly handle empty bodies', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {mode: 'formdata'}
            });

            expect(requesterUtil.getRequestBody(request)).to.be(undefined);
        });

        it('should correctly handle missing bodies', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST'
            });

            expect(requesterUtil.getRequestBody(request)).to.be(undefined);
        });

        it('should correctly handle missing request methods', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                header: [{
                    key: 'alpha',
                    value: 'foo'
                }],
                body: {
                    mode: 'formdata',
                    formdata: [{
                        key: 'foo',
                        value: 'bar'
                    }]
                }
            });

            delete request.method;
            expect(requesterUtil.getRequestBody(request, {})).to.eql({
                formData: {foo: 'bar'}
            });
        });

        it('should not bail out on GET requests for sendBodyWithGetRequests', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/get',
                body: {
                    mode: 'formdata',
                    formdata: [{
                        key: 'foo',
                        value: 'bar'
                    }]
                }
            });

            expect(requesterUtil.getRequestBody(request, {sendBodyWithGetRequests: true})).to.eql({
                formData: {foo: 'bar'}
            });
        });

        it('should handle raw request bodies correctly ', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'raw',
                    raw: '{"beta":"bar"}'
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.eql({
                body: '{"beta":"bar"}'
            });
        });

        it('should handle urlencoded request bodies correctly', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'urlencoded',
                    urlencoded: [
                        {key: 'alpha', value: 'foo', type: 'text'},
                        {key: 'beta', value: 'bar', type: 'text'},
                        {key: 'gamma', value: 'baz', type: 'text', disabled: true},
                        {key: 'alpha', value: 'other', type: 'text'},
                        {key: 'alpha', value: 'next', type: 'text'}
                    ]
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.eql({
                form: {alpha: ['foo', 'other', 'next'], beta: 'bar'}
            });
        });

        it('should handle form data request bodies correctly', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'formdata',
                    formdata: [
                        {key: 'alpha', value: 'foo', type: 'text'},
                        {key: 'beta', value: 'bar', type: 'text'},
                        {key: 'gamma', value: 'baz', type: 'text', disabled: true},
                        {key: 'alpha', value: 'other', type: 'text'},
                        {key: 'alpha', value: 'next', type: 'text'}
                    ]
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.eql({
                formData: {alpha: ['foo', 'other', 'next'], beta: 'bar'}
            });
        });

        it('should handle file based request bodies correctly', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'file',
                    file: {src: 'random.txt'}
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.have.property('body');
        });

        it('should handle arbitrary request bodies correctly', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'random',
                    random: 'An arbitrary request body format'
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.be(undefined);
        });
    });

    describe('.jsonifyResponse', function () {
        it('should handle falsy input correctly', function () {
            expect(requesterUtil.jsonifyResponse()).to.be(undefined);
        });
    });

    describe('.arrayPairsToObject', function () {
        it('should bail out for non-arrays', function () {
            var result = requesterUtil.arrayPairsToObject('random');
            expect(result).to.be(undefined);
        });

        it('should correctly convert an array of pairs to an object', function () {
            var obj = requesterUtil.arrayPairsToObject(['a', 'b', 'c', 'd']);
            expect(obj).to.eql({a: 'b', c: 'd'});
        });

        it('should correctly handle multi valued keys', function () {
            var obj = requesterUtil.arrayPairsToObject(['a', 'b', 'c', 'd', 'a', 'e']);
            expect(obj).to.eql({a: ['b', 'e'], c: 'd'});
        });
    });
});
<commit_msg>bug(test): Fixed broken requester util unit test :bug:<commit_after>/* global describe, it */

var expect = require('expect.js'),
    sdk = require('postman-collection'),
    runtimeVersion = require('../../package').version,
    requesterUtil = require('../../lib/requester/util');

describe('requester util', function () {
    describe('.getRequestOptions', function () {
        it('should use http as the default protocol', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                header: [{
                    key: 'alpha',
                    value: 'foo'
                }],
                body: {
                    mode: 'raw',
                    raw: '{"alpha": "foo"}'
                }
            });

            expect(requesterUtil.getRequestOptions(request)).to.eql({
                headers: {
                    alpha: 'foo',
                    'User-Agent': 'PostmanRuntime/' + runtimeVersion,
                    'Content-Type': 'text/plain',
                    Accept: '*/*',
                    Host: 'postman-echo.com'
                },
                body: '{"alpha": "foo"}',
                url: 'http://postman-echo.com/post',
                method: 'POST',
                jar: true,
                timeout: undefined,
                gzip: true,
                useQuerystring: true,
                strictSSL: undefined,
                followRedirect: undefined,
                followAllRedirects: undefined,
                encoding: null,
                agentOptions: {keepAlive: undefined}
            });
        });

        it('should use https where applicable', function () {
            var request = new sdk.Request({
                url: 'https://postman-echo.com',
                method: 'GET',
                header: [{
                    key: 'alpha',
                    value: 'foo'
                }]
            });

            expect(requesterUtil.getRequestOptions(request)).to.eql({
                headers: {
                    alpha: 'foo',
                    'User-Agent': 'PostmanRuntime/' + runtimeVersion,
                    Accept: '*/*',
                    Host: 'postman-echo.com'
                },
                url: 'https://postman-echo.com',
                method: 'GET',
                jar: true,
                timeout: undefined,
                gzip: true,
                useQuerystring: true,
                strictSSL: undefined,
                followRedirect: undefined,
                followAllRedirects: undefined,
                encoding: null,
                agentOptions: {keepAlive: undefined}
            });
        });
    });

    describe('.ensureHeaderExists', function () {
        it('should not mutate the header if it already exists', function () {
            var headers = {alpha: 'foo', beta: 'bar'};

            requesterUtil.ensureHeaderExists(headers, 'alpha');
            expect(headers).to.eql({alpha: 'foo', beta: 'bar'});
        });

        it('should correctly set a missing header', function () {
            var headers = {alpha: 'foo', beta: 'bar'};

            requesterUtil.ensureHeaderExists(headers, 'gamma', 'baz');
            expect(headers).to.eql({alpha: 'foo', beta: 'bar', gamma: 'baz'});
        });
    });

    describe('.getRequestHeaders', function () {
        it('should handle invalid input correctly', function () {
            var result = requesterUtil.getRequestHeaders({});
            expect(result).to.be(undefined);
        });

        it('should correctly fetch request headers from a sdk Request instance', function () {
            var request = new sdk.Request({
                    url: 'postman-echo.com',
                    method: 'GET',
                    header: [
                        {key: 'alpha', value: 'foo'},
                        {key: 'beta', value: 'bar', disabled: true},
                        {key: 'gamma', value: 'baz'},
                        {key: 'alpha', value: 'next'},
                        {key: 'alpha', value: 'other'}
                    ]
                }),
                headers = requesterUtil.getRequestHeaders(request);

            expect(headers).to.eql({
                alpha: ['foo', 'next', 'other'],
                gamma: 'baz'
            });
        });
    });

    describe('.getRequestBody', function () {
        it('should correctly handle empty bodies', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {mode: 'formdata'}
            });

            expect(requesterUtil.getRequestBody(request)).to.be(undefined);
        });

        it('should correctly handle missing bodies', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST'
            });

            expect(requesterUtil.getRequestBody(request)).to.be(undefined);
        });

        it('should correctly handle missing request methods', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                header: [{
                    key: 'alpha',
                    value: 'foo'
                }],
                body: {
                    mode: 'formdata',
                    formdata: [{
                        key: 'foo',
                        value: 'bar'
                    }]
                }
            });

            delete request.method;
            expect(requesterUtil.getRequestBody(request, {})).to.eql({
                formData: {foo: 'bar'}
            });
        });

        it('should not bail out on GET requests for sendBodyWithGetRequests', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/get',
                body: {
                    mode: 'formdata',
                    formdata: [{
                        key: 'foo',
                        value: 'bar'
                    }]
                }
            });

            expect(requesterUtil.getRequestBody(request, {sendBodyWithGetRequests: true})).to.eql({
                formData: {foo: 'bar'}
            });
        });

        it('should handle raw request bodies correctly ', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'raw',
                    raw: '{"beta":"bar"}'
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.eql({
                body: '{"beta":"bar"}'
            });
        });

        it('should handle urlencoded request bodies correctly', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'urlencoded',
                    urlencoded: [
                        {key: 'alpha', value: 'foo', type: 'text'},
                        {key: 'beta', value: 'bar', type: 'text'},
                        {key: 'gamma', value: 'baz', type: 'text', disabled: true},
                        {key: 'alpha', value: 'other', type: 'text'},
                        {key: 'alpha', value: 'next', type: 'text'}
                    ]
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.eql({
                form: {alpha: ['foo', 'other', 'next'], beta: 'bar'}
            });
        });

        it('should handle form data request bodies correctly', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'formdata',
                    formdata: [
                        {key: 'alpha', value: 'foo', type: 'text'},
                        {key: 'beta', value: 'bar', type: 'text'},
                        {key: 'gamma', value: 'baz', type: 'text', disabled: true},
                        {key: 'alpha', value: 'other', type: 'text'},
                        {key: 'alpha', value: 'next', type: 'text'}
                    ]
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.eql({
                formData: {alpha: ['foo', 'other', 'next'], beta: 'bar'}
            });
        });

        it('should handle file based request bodies correctly', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'file',
                    file: {src: 'random.txt'}
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.have.property('body');
        });

        it('should handle arbitrary request bodies correctly', function () {
            var request = new sdk.Request({
                url: 'postman-echo.com/post',
                method: 'POST',
                body: {
                    mode: 'random',
                    random: 'An arbitrary request body format'
                }
            });

            expect(requesterUtil.getRequestBody(request)).to.be(undefined);
        });
    });

    describe('.jsonifyResponse', function () {
        it('should handle falsy input correctly', function () {
            expect(requesterUtil.jsonifyResponse()).to.be(undefined);
        });
    });

    describe('.arrayPairsToObject', function () {
        it('should bail out for non-arrays', function () {
            var result = requesterUtil.arrayPairsToObject('random');
            expect(result).to.be(undefined);
        });

        it('should correctly convert an array of pairs to an object', function () {
            var obj = requesterUtil.arrayPairsToObject(['a', 'b', 'c', 'd']);
            expect(obj).to.eql({a: 'b', c: 'd'});
        });

        it('should correctly handle multi valued keys', function () {
            var obj = requesterUtil.arrayPairsToObject(['a', 'b', 'c', 'd', 'a', 'e']);
            expect(obj).to.eql({a: ['b', 'e'], c: 'd'});
        });
    });
});
<|endoftext|>


<commit_before>import { alphabet } from 'app/js/alphabet'

describe('Alphabet', function () {
  describe('Method getNextEntry:', function () {
    it(' Returns b when input is a', function () {
      alphabet.getNextEntry('a').should.equal('b')
    })
    it(' Returns a.b when input is a.a', function () {
      alphabet.getNextEntry('a.a').should.equal('a.b')
    })
    it(' Returns a.aa when input is a.z', function () {
      alphabet.getNextEntry('a.z').should.equal('a.aa')
    })
    it(' Returns ab when input is aa', function () {
      alphabet.getNextEntry('aa').should.equal('ab')
    })
  })
  describe('Method getParentPath:', function () {
    it(' Returns empty when input is undefined', function () {
      alphabet.getParentPath().should.equal('')
    })
    it(' Returns a when input is a.b', function () {
      alphabet.getParentPath('a.b').should.equal('a')
    })
    it(' Returns empty when input is a', function () {
      alphabet.getParentPath('a').should.equal('')
    })
  })
  describe('Method increments:', function () {
    it(' Returns b when incrementing a', function () {
      alphabet.increments('a').should.equal('b')
    })
    it(' Returns aa when incrementing z', function () {
      alphabet.increments('z').should.equal('aa')
    })
    it(' Returns when incrementing aa', function () {
      alphabet.increments('aa').should.equal('ab')
    })
    it(' Returns az when incrementing ay', function () {
      alphabet.increments('ay').should.equal('az')
    })
    it(' Returns ba when incrementing az', function () {
      alphabet.increments('az').should.equal('ba')
    })
    it(' Returns aaaaa when incrementing zzzz', function () {
      alphabet.increments('zzzz').should.equal('aaaaa')
    })
    it(' Returns empty when incrementing null', function () {
      alphabet.increments(null).should.equal('')
    })
    it(' Returns empty when incrementing empty', function () {
      alphabet.increments('').should.equal('')
    })
  })
  describe('Method buildFlatList:', function () {
    it(' Returns empty when input is bad', function () {
      var ret = [{path: 'a'},{path: 'a.a'}]
      var assert = []
      alphabet.buildFlatList('a', ret).should.eql(assert)
    })
    it(' Returns empty when input is good', function () {
      var ret = [{path: 'a.a', parent: 'a'}, {path: 'a.a.a', parent: 'a.a'}]
      var assert = [{account: {parent: 'a', path: 'a.a'}, indent: ''}, {account: {parent: 'a.a', path:'a.a.a'}, indent: '‐‐'}]
      alphabet.buildFlatList('a', ret).should.eql(assert)
    })
  })
})
<commit_msg>Add unit tests to improve the alphabet.js coverage (now is 100%)<commit_after>import { alphabet } from 'app/js/alphabet'

describe('Alphabet', function () {
  describe('Method getNextEntry:', function () {
    it(' Returns b when input is a', function () {
      alphabet.getNextEntry('a').should.equal('b')
    })
    it(' Returns a.b when input is a.a', function () {
      alphabet.getNextEntry('a.a').should.equal('a.b')
    })
    it(' Returns a.aa when input is a.z', function () {
      alphabet.getNextEntry('a.z').should.equal('a.aa')
    })
    it(' Returns ab when input is aa', function () {
      alphabet.getNextEntry('aa').should.equal('ab')
    })
  })
  describe('Method getParentPath:', function () {
    it(' Returns empty when input is undefined', function () {
      alphabet.getParentPath().should.equal('')
    })
    it(' Returns a when input is a.b', function () {
      alphabet.getParentPath('a.b').should.equal('a')
    })
    it(' Returns empty when input is a', function () {
      alphabet.getParentPath('a').should.equal('')
    })
  })
  describe('Method increments:', function () {
    it(' Returns b when incrementing a', function () {
      alphabet.increments('a').should.equal('b')
    })
    it(' Returns aa when incrementing z', function () {
      alphabet.increments('z').should.equal('aa')
    })
    it(' Returns when incrementing aa', function () {
      alphabet.increments('aa').should.equal('ab')
    })
    it(' Returns az when incrementing ay', function () {
      alphabet.increments('ay').should.equal('az')
    })
    it(' Returns ba when incrementing az', function () {
      alphabet.increments('az').should.equal('ba')
    })
    it(' Returns aaaaa when incrementing zzzz', function () {
      alphabet.increments('zzzz').should.equal('aaaaa')
    })
    it(' Returns empty when incrementing null', function () {
      alphabet.increments(null).should.equal('')
    })
    it(' Returns empty when incrementing empty', function () {
      alphabet.increments('').should.equal('')
    })
  })
  describe('Method buildFlatList:', function () {
    it(' Returns empty when input is bad', function () {
      var ret = [{path: 'a'}, {path: 'a.a'}]
      var assert = []
      alphabet.buildFlatList('a', ret).should.eql(assert)
    })
    it(' Returns expected flat list when input is good', function () {
      var ret = [{path: 'a.a', parent: 'a'}, {path: 'a.a.a', parent: 'a.a'}]
      var assert = [{account: {parent: 'a', path: 'a.a'}, indent: ''}, {account: {parent: 'a.a', path: 'a.a.a'}, indent: '‐‐'}]
      alphabet.buildFlatList('a', ret).should.eql(assert)
    })
  })
  describe('Method buildTreeList:', function () {
    it(' Returns empty when input is bad', function () {
      var ret = [{path: 'a'}, {path: 'a.a'}]
      var assert = []
      alphabet.buildTreeList('a', ret).should.eql(assert)
    })
    it(' Returns expected tree list when input is good', function () {
      var ret = [{path: 'a.a', parent: 'a'}, {path: 'a.a.a', parent: 'a.a'}]
      var assert = [{account: {parent: 'a', path: 'a.a'}, children: [{account: {path: 'a.a.a', parent: 'a.a'}, children: []}]}]
      alphabet.buildTreeList('a', ret).should.eql(assert)
    })
  })
})
<|endoftext|>


<commit_before>import Ember from 'ember';
import IntlService from '../../services/intl';
import { runDestroy } from '../helpers/run-append';

export default function (name, callbacks) {
    callbacks = callbacks || {};

    QUnit.module(name, {
        intlBlock: function (templateString, serviceContext, viewContext) {
            var service   = this.service;
            var container = this.container;

            if (typeof serviceContext === 'object') {
                Ember.run(function () {
                    service.setProperties(serviceContext);
                });
            }

            container.injection('formatter', 'intl', 'intl:main');

            // mock the component lookup service since it's invoked prior to
            // looking up a handlebar helper to determine if the helper
            // is a valid component.
            container.register('component-lookup:main', Ember.Object.extend({
                lookupFactory: function () { return false; }
            }));

            return Ember.View.create({
                intl:      service,
                container: container,
                template:  Ember.HTMLBars.compile(templateString),
                context:   viewContext || {}
            });
        },

        setup: function () {
            var self = this;

            Ember.lookup = this.lookup = { Ember: Ember };

            this.container = new Ember.Container();
            this.service = this.getService(this.container);

            if (callbacks.setup) {
                callbacks.setup(this.container);
            }
        },

        teardown: function () {
            runDestroy(this.container);

            if (callbacks.teardown) {
                callbacks.teardown(this.container);
            }
        },

        getService: function (container, serviceContext) {
            serviceContext = serviceContext || {};

            var service;

            if (!container.has('intl:main')) {
                service = IntlService.create(Ember.$.extend({}, {
                    container:     this.container,
                    locales:       ['en'],
                    defaultLocale: 'en'
                }, serviceContext));

                container.register('intl:main', service, {
                    singleton:   true,
                    instantiate: false
                });
            } else {
                service = container.lookup('intl:main');

                Ember.run(function () {
                    service.setProperties(serviceContext);
                });
            }

            return service;
        }
    });
}
<commit_msg>Removing dead code in module-for-intl<commit_after>import Ember from 'ember';
import IntlService from '../../services/intl';
import { runDestroy } from '../helpers/run-append';

export default function (name, callbacks) {
    callbacks = callbacks || {};

    QUnit.module(name, {
        intlBlock: function (templateString, serviceContext, viewContext) {
            var service   = this.service;
            var container = this.container;

            if (typeof serviceContext === 'object') {
                Ember.run(function () {
                    service.setProperties(serviceContext);
                });
            }

            container.injection('formatter', 'intl', 'intl:main');

            // mock the component lookup service since it's invoked prior to
            // looking up a handlebar helper to determine if the helper
            // is a valid component.
            container.register('component-lookup:main', Ember.Object.extend({
                lookupFactory: function () { return false; }
            }));

            return Ember.View.create({
                intl:      service,
                container: container,
                template:  Ember.HTMLBars.compile(templateString),
                context:   viewContext || {}
            });
        },

        setup: function () {
            var self = this;

            Ember.lookup = this.lookup = { Ember: Ember };

            this.container = new Ember.Container();
            this.service = this.getService(this.container);

            if (callbacks.setup) {
                callbacks.setup(this.container);
            }
        },

        teardown: function () {
            runDestroy(this.container);

            if (callbacks.teardown) {
                callbacks.teardown(this.container);
            }
        },

        getService: function () {
            var container = this.container;

            if (!container.has('intl:main')) {
                var service = IntlService.create(Ember.$.extend({}, {
                    container:     this.container,
                    locales:       ['en'],
                    defaultLocale: 'en'
                }));

                container.register('intl:main', service, {
                    singleton:   true,
                    instantiate: false
                });

                return service;
            }

            return container.lookup('intl:main');
        }
    });
}
<|endoftext|>


<commit_before>/*global require*/
require({
    baseUrl : '../../Source'
}, ['Cesium'], function(Cesium) {
    "use strict";
    //A real application should require only the subset of modules that
    //are actually used, instead of requiring the Cesium module, which
    //includes everything.

    var canvas = document.getElementById('glCanvas');
    var ellipsoid = Cesium.Ellipsoid.WGS84; // Used in many Sandbox examples
    var scene = new Cesium.Scene(canvas);
    var primitives = scene.getPrimitives();

    // Bing Maps
    var bing = new Cesium.BingMapsTileProvider({
        server : 'dev.virtualearth.net',
        mapStyle : Cesium.BingMapsStyle.AERIAL,
        // Some versions of Safari support WebGL, but don't correctly implement
        // cross-origin image loading, so we need to load Bing imagery using a proxy.
        proxy : Cesium.FeatureDetection.supportsCrossOriginImagery() ? undefined : new Cesium.DefaultProxy('/proxy/')
    });

    var cb = new Cesium.CentralBody(ellipsoid);
    cb.dayTileProvider = bing;
    cb.nightImageSource = '../../Images/land_ocean_ice_lights_2048.jpg';
    cb.specularMapSource = '../../Images/earthspec1k.jpg';
    if (scene.getContext().getMaximumTextureSize() > 2048) {
        cb.cloudsMapSource = '../../Images/earthcloudmaptrans.jpg';
        cb.bumpMapSource = '../../Images/earthbump1k.jpg';
    }
    cb.showSkyAtmosphere = true;
    cb.showGroundAtmosphere = true;
    primitives.setCentralBody(cb);

    scene.getCamera().frustum.near = 1.0;
    scene.getCamera().getControllers().addCentralBody();

    var transitioner = new Cesium.SceneTransitioner(scene, ellipsoid);

    ///////////////////////////////////////////////////////////////////////////
    // Add examples from the Sandbox here:

    ///////////////////////////////////////////////////////////////////////////

    scene.setAnimation(function() {
        //scene.setSunPosition(scene.getCamera().position);
        scene.setSunPosition(Cesium.SunPosition.compute().position);

        // Add code here to update primitives based on changes to animation time, camera parameters, etc.
    });

    (function tick() {
        scene.render();
        Cesium.requestAnimationFrame(tick);
    }());

    ///////////////////////////////////////////////////////////////////////////
    // Example mouse & keyboard handlers

    var handler = new Cesium.EventHandler(canvas);

    handler.setMouseAction(function(movement) {
        /* ... */
        // Use movement.startX, movement.startY, movement.endX, movement.endY
    }, Cesium.MouseEventType.MOVE);

    function keydownHandler(e) {
        switch (e.keyCode) {
        case "3".charCodeAt(0):  // "3" -> 3D globe
            cb.showSkyAtmosphere = true;
            cb.showGroundAtmosphere = true;
            transitioner.morphTo3D();
            break;
        case "2".charCodeAt(0):  // "2" -> Columbus View
            cb.showSkyAtmosphere = false;
            cb.showGroundAtmosphere = false;
            transitioner.morphToColumbusView();
            break;
        case "1".charCodeAt(0):  // "1" -> 2D map
            cb.showSkyAtmosphere = false;
            cb.showGroundAtmosphere = false;
            transitioner.morphTo2D();
            break;
        default:
            break;
        }
    }
    document.addEventListener('keydown', keydownHandler, false);

    canvas.oncontextmenu = function() {
        return false;
    };

    ///////////////////////////////////////////////////////////////////////////
    // Example resize handler

    window.onresize = function () {
        var width = canvas.clientWidth;
        var height = canvas.clientHeight;

        if (canvas.width === width && canvas.height === height) {
            return;
        }

        canvas.width = width;
        canvas.height = height;

        scene.getContext().setViewport({
            x: 0,
            y: 0,
            width: width,
            height: height
        });

        scene.getCamera().frustum.aspectRatio = width / height;
    };
    window.onresize();
});<commit_msg>Fix Skeleton resize handler to use addEventListener.<commit_after>/*global require*/
require({
    baseUrl : '../../Source'
}, ['Cesium'], function(Cesium) {
    "use strict";
    //A real application should require only the subset of modules that
    //are actually used, instead of requiring the Cesium module, which
    //includes everything.

    var canvas = document.getElementById('glCanvas');
    var ellipsoid = Cesium.Ellipsoid.WGS84; // Used in many Sandbox examples
    var scene = new Cesium.Scene(canvas);
    var primitives = scene.getPrimitives();

    // Bing Maps
    var bing = new Cesium.BingMapsTileProvider({
        server : 'dev.virtualearth.net',
        mapStyle : Cesium.BingMapsStyle.AERIAL,
        // Some versions of Safari support WebGL, but don't correctly implement
        // cross-origin image loading, so we need to load Bing imagery using a proxy.
        proxy : Cesium.FeatureDetection.supportsCrossOriginImagery() ? undefined : new Cesium.DefaultProxy('/proxy/')
    });

    var cb = new Cesium.CentralBody(ellipsoid);
    cb.dayTileProvider = bing;
    cb.nightImageSource = '../../Images/land_ocean_ice_lights_2048.jpg';
    cb.specularMapSource = '../../Images/earthspec1k.jpg';
    if (scene.getContext().getMaximumTextureSize() > 2048) {
        cb.cloudsMapSource = '../../Images/earthcloudmaptrans.jpg';
        cb.bumpMapSource = '../../Images/earthbump1k.jpg';
    }
    cb.showSkyAtmosphere = true;
    cb.showGroundAtmosphere = true;
    primitives.setCentralBody(cb);

    scene.getCamera().frustum.near = 1.0;
    scene.getCamera().getControllers().addCentralBody();

    var transitioner = new Cesium.SceneTransitioner(scene, ellipsoid);

    ///////////////////////////////////////////////////////////////////////////
    // Add examples from the Sandbox here:

    ///////////////////////////////////////////////////////////////////////////

    scene.setAnimation(function() {
        //scene.setSunPosition(scene.getCamera().position);
        scene.setSunPosition(Cesium.SunPosition.compute().position);

        // Add code here to update primitives based on changes to animation time, camera parameters, etc.
    });

    (function tick() {
        scene.render();
        Cesium.requestAnimationFrame(tick);
    }());

    ///////////////////////////////////////////////////////////////////////////
    // Example mouse & keyboard handlers

    var handler = new Cesium.EventHandler(canvas);

    handler.setMouseAction(function(movement) {
        /* ... */
        // Use movement.startX, movement.startY, movement.endX, movement.endY
    }, Cesium.MouseEventType.MOVE);

    function keydownHandler(e) {
        switch (e.keyCode) {
        case "3".charCodeAt(0):  // "3" -> 3D globe
            cb.showSkyAtmosphere = true;
            cb.showGroundAtmosphere = true;
            transitioner.morphTo3D();
            break;
        case "2".charCodeAt(0):  // "2" -> Columbus View
            cb.showSkyAtmosphere = false;
            cb.showGroundAtmosphere = false;
            transitioner.morphToColumbusView();
            break;
        case "1".charCodeAt(0):  // "1" -> 2D map
            cb.showSkyAtmosphere = false;
            cb.showGroundAtmosphere = false;
            transitioner.morphTo2D();
            break;
        default:
            break;
        }
    }
    document.addEventListener('keydown', keydownHandler, false);

    canvas.oncontextmenu = function() {
        return false;
    };

    ///////////////////////////////////////////////////////////////////////////
    // Example resize handler

    var onResize = function () {
        var width = canvas.clientWidth;
        var height = canvas.clientHeight;

        if (canvas.width === width && canvas.height === height) {
            return;
        }

        canvas.width = width;
        canvas.height = height;

        scene.getContext().setViewport({
            x: 0,
            y: 0,
            width: width,
            height: height
        });

        scene.getCamera().frustum.aspectRatio = width / height;
    };
    window.addEventListener('resize', onResize, false);
    onResize();
});<|endoftext|>