<commit_before>const path = require('path');
const stripColorCodes = require('stripcolorcodes');
const reporters = require('../lib/reporters');
const checkstyleReporter = require('../lib/reporters/checkstyle');
const jsonReporter = require('../lib/reporters/json');
const customReporter = require('./support/custom_reporter');
const expectedResults = require('./support/expected_results');

exports.reporters = {
  defaultReporter: {
    'when given empty result': (test) => {
      const result = [];
      const reporter = reporters.defaultReporter;
      const expected = '';
      const actual = reporter(result);

      test.equal(actual, expected, 'Should return empty String for empty result');
      test.done();
    },
    'when given non-empty result': (test) => {
      const invalidHtml = path.join('test', 'invalid.html');
      const result = expectedResults.invalid;
      const reporter = reporters.defaultReporter;
      const expected = [
        `${invalidHtml} [L1:C16] Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”.`,
        `${invalidHtml} [L9:C96] Attribute “unknownattr” not allowed on element “img” at this point.`,
        `${invalidHtml} [L9:C96] An “img” element must have an “alt” attribute, except under certain conditions. For details, consult guidance on providing text alternatives for images.`,
        `${invalidHtml} [L11:C19] The “clear” attribute on the “br” element is obsolete. Use CSS instead.`
      ].join('\n');
      const actual = stripColorCodes(reporter(result));

      test.equal(actual, expected, 'Should report errors as a String');
      test.done();
    }
  },
  selectReporter: {
    'when no reporter is specified': (test) => {
      const options = {};
      const reporter = reporters.selectReporter(options);

      test.equal(reporter, reporters.defaultReporter, 'Should return default reporter');
      test.done();
    },
    'when checkstyle reporter is specified': (test) => {
      const options = {
        reporter: 'checkstyle'
      };
      const reporter = reporters.selectReporter(options);

      test.equal(reporter, checkstyleReporter, 'Should return checkstyle reporter');
      test.done();
    },
    'when json reporter is specified': (test) => {
      const options = {
        reporter: 'json'
      };
      const reporter = reporters.selectReporter(options);

      test.equal(reporter, jsonReporter, 'Should return json reporter');
      test.done();
    },
    'when valid custom reporter is specified': (test) => {
      const options = {
        reporter: 'test/support/custom_reporter.js'
      };
      const reporter = reporters.selectReporter(options);

      test.equal(reporter, customReporter, 'Should return custom reporter');
      test.done();
    },
    'when invalid custom reporter is specified': (test) => {
      const options = {
        reporter: 'does/not/exist.js'
      };

      test.throws(
        () => {
          reporters.selectReporter(options);
        },
        Error, 'Should throw an error'
      );
      test.done();
    }
  }
};
<commit_msg>Add one more test.<commit_after>const path = require('path');
const stripColorCodes = require('stripcolorcodes');
const reporters = require('../lib/reporters');
const checkstyleReporter = require('../lib/reporters/checkstyle');
const jsonReporter = require('../lib/reporters/json');
const junitReporter = require('../lib/reporters/junit');
const customReporter = require('./support/custom_reporter');
const expectedResults = require('./support/expected_results');

exports.reporters = {
  defaultReporter: {
    'when given empty result': (test) => {
      const result = [];
      const reporter = reporters.defaultReporter;
      const expected = '';
      const actual = reporter(result);

      test.equal(actual, expected, 'Should return empty String for empty result');
      test.done();
    },
    'when given non-empty result': (test) => {
      const invalidHtml = path.join('test', 'invalid.html');
      const result = expectedResults.invalid;
      const reporter = reporters.defaultReporter;
      const expected = [
        `${invalidHtml} [L1:C16] Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”.`,
        `${invalidHtml} [L9:C96] Attribute “unknownattr” not allowed on element “img” at this point.`,
        `${invalidHtml} [L9:C96] An “img” element must have an “alt” attribute, except under certain conditions. For details, consult guidance on providing text alternatives for images.`,
        `${invalidHtml} [L11:C19] The “clear” attribute on the “br” element is obsolete. Use CSS instead.`
      ].join('\n');
      const actual = stripColorCodes(reporter(result));

      test.equal(actual, expected, 'Should report errors as a String');
      test.done();
    }
  },
  selectReporter: {
    'when no reporter is specified': (test) => {
      const options = {};
      const reporter = reporters.selectReporter(options);

      test.equal(reporter, reporters.defaultReporter, 'Should return default reporter');
      test.done();
    },
    'when checkstyle reporter is specified': (test) => {
      const options = {
        reporter: 'checkstyle'
      };
      const reporter = reporters.selectReporter(options);

      test.equal(reporter, checkstyleReporter, 'Should return checkstyle reporter');
      test.done();
    },
    'when json reporter is specified': (test) => {
      const options = {
        reporter: 'json'
      };
      const reporter = reporters.selectReporter(options);

      test.equal(reporter, jsonReporter, 'Should return json reporter');
      test.done();
    },
    'when junit reporter is specified': (test) => {
      const options = {
        reporter: 'junit'
      };
      const reporter = reporters.selectReporter(options);

      test.equal(reporter, junitReporter, 'Should return junit reporter');
      test.done();
    },
    'when valid custom reporter is specified': (test) => {
      const options = {
        reporter: 'test/support/custom_reporter.js'
      };
      const reporter = reporters.selectReporter(options);

      test.equal(reporter, customReporter, 'Should return custom reporter');
      test.done();
    },
    'when invalid custom reporter is specified': (test) => {
      const options = {
        reporter: 'does/not/exist.js'
      };

      test.throws(
        () => {
          reporters.selectReporter(options);
        },
        Error, 'Should throw an error'
      );
      test.done();
    }
  }
};
<|endoftext|>


<commit_before>var webdriverio = require('webdriverio'),
    client = webdriverio.remote({
        desiredCapabilities: {
            browserName: 'chrome',
            version: '56',
            platform: 'WIN7',
            'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
            name: 'Compodoc test',
            'public': true,
            build: process.env.TRAVIS_BUILD_NUMBER
        },
        host: 'ondemand.saucelabs.com',
        port: 80,
        user: process.env.SAUCE_USERNAME,
        key: process.env.SAUCE_ACCESS_KEY,
        logLevel: 'verbose'
    }).init();

client
    .url('http://127.0.0.1:8383')
    .getTitle(function(err, title) {
        console.log(title);
    })
    .end();

/*
client = webdriverio.remote({
    desiredCapabilities: {
        browserName: 'firefox',
        version: '50',
        platform: 'XP',
        name: 'Compodoc test',
        'public': true
    },
    host: 'ondemand.saucelabs.com',
    port: 80,
    user: process.env.SAUCE_USERNAME,
    key: process.env.SAUCE_ACCESS_KEY,
    logLevel: 'verbose'
}).init()

client
    .url('http://google.com')
    .setValue('*[name="q"]', 'webdriverio')
    .click('*[name="btnG"]')
    .pause(1000)
    .getTitle(function(err, title) {
        console.log(title);
    })
    .end();
*/
<commit_msg>fix(test): real test<commit_after>var webdriverio = require('webdriverio'),
    expect = rquire('chai').expect:

describe('Compodoc page', function() {
    return it('should get the title', function(done) {

        var client = webdriverio.remote({
                desiredCapabilities: {
                    browserName: 'chrome',
                    version: '56',
                    platform: 'WIN7',
                    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
                    name: 'Compodoc test',
                    'public': true,
                    build: process.env.TRAVIS_BUILD_NUMBER
                },
                host: 'ondemand.saucelabs.com',
                port: 80,
                user: process.env.SAUCE_USERNAME,
                key: process.env.SAUCE_ACCESS_KEY,
                logLevel: 'verbose'
            }).init();

        return client
            .url('http://127.0.0.1:8383')
            .getTitle(function(err, title) {
                console.log(title);
                expect(title).to.equal('compodoc documentation');
                return done();
            })
            .end();
    });
});

/*
client = webdriverio.remote({
    desiredCapabilities: {
        browserName: 'firefox',
        version: '50',
        platform: 'XP',
        name: 'Compodoc test',
        'public': true
    },
    host: 'ondemand.saucelabs.com',
    port: 80,
    user: process.env.SAUCE_USERNAME,
    key: process.env.SAUCE_ACCESS_KEY,
    logLevel: 'verbose'
}).init()

client
    .url('http://google.com')
    .setValue('*[name="q"]', 'webdriverio')
    .click('*[name="btnG"]')
    .pause(1000)
    .getTitle(function(err, title) {
        console.log(title);
    })
    .end();
*/
<|endoftext|>


<commit_before>import React from 'react'
import mocha from 'mocha'
import fetch from 'whatwg-fetch'
import fetchMock from 'fetch-mock'
// import { shallow, mount } from 'enzyme'
import filmsScrubber from '../App/Scrubbers/filmsScrubber'
import peopleNeedPlanets from '../App/Scrubbers/peopleNeedPlanets'
import peopleScrubber from '../App/Scrubbers/peopleScrubber'
import planetScrubber from '../App/Scrubbers/planetScrubber'
import speciesOrdered from '../App/Scrubbers/speciesOrdered'
import speciesScrubber from '../App/Scrubbers/speciesScrubber'
import vehicleScrubber from '../App/Scrubbers/vehicleScrubber'

//stubbed data
import films from '../App/Data/films.json'
import planets1 from '../App/Data/Planets/Planets1.json'
import planets2 from '../App/Data/Planets/Planets2.json'
import planets3 from '../App/Data/Planets/Planets3.json'
import planets4 from '../App/Data/Planets/Planets4.json'
import planets5 from '../App/Data/Planets/Planets5.json'
import planets6 from '../App/Data/Planets/Planets6.json'
import planets7 from '../App/Data/Planets/Planets7.json'
import people1 from '../App/Data/People/People1.json'
import people2 from '../App/Data/People/People2.json'
import people3 from '../App/Data/People/People3.json'
import people4 from '../App/Data/People/People4.json'
import people5 from '../App/Data/People/People5.json'
import people6 from '../App/Data/People/People6.json'
import people7 from '../App/Data/People/People7.json'
import people8 from '../App/Data/People/People8.json'
import people9 from '../App/Data/People/People9.json'
import species1 from '../App/Data/Species/Species1.json'
import species2 from '../App/Data/Species/Species2.json'
import species3 from '../App/Data/Species/Species3.json'
import species4 from '../App/Data/Species/Species4.json'
import vehicles1 from '../App/Data/Vehicles/Vehicles1.json'
import vehicles2 from '../App/Data/Vehicles/Vehicles2.json'
import vehicles3 from '../App/Data/Vehicles/Vehicles3.json'
import vehicles4 from '../App/Data/Vehicles/Vehicles4.json'

describe('Time to scrub some data', () => {

  afterEach(() => {
    fetchMock.restore()
  })

function resolveAfter2Seconds () {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, 2000);
  });
}

  it('filmsScrubber should grab scroll text for seven films', async () => {
    fetchMock.get('http://swapi.co/api/films/?page=1', {
      status: 200,
      body: films
    })
    let filmArray = filmsScrubber();

    await resolveAfter2Seconds();
    filmArray.then((array) => {
      expect(array.length).toEqual(7);
    })

  })

  it('planetScrubber make 7 api calls and return an array of length 67', async () => {
    fetchMock.get('http://swapi.co/api/films/?page=1', { status: 200, body: planets1 });
    fetchMock.get('http://swapi.co/api/films/?page=2', { status: 200, body: planets2 });
    fetchMock.get('http://swapi.co/api/films/?page=3', { status: 200, body: planets3 });
    fetchMock.get('http://swapi.co/api/films/?page=4', { status: 200, body: planets4 });
    fetchMock.get('http://swapi.co/api/films/?page=5', { status: 200, body: planets5 });
    fetchMock.get('http://swapi.co/api/films/?page=6', { status: 200, body: planets6 });
    fetchMock.get('http://swapi.co/api/films/?page=7', { status: 200, body: planets7 });

    let planetArray = planetScrubber();

    await resolveAfter2Seconds();
    planetArray.then((array) => {
      expect(array.length).toEqual(67);
    })
  })

  it('peopleScrubber makes 9 api calls and return an array of length', async () => {
    fetchMock.get('http://swapi.co/api/people/?page=1', { status: 200, body: people1 });
    fetchMock.get('http://swapi.co/api/people/?page=2', { status: 200, body: people2 });
    fetchMock.get('http://swapi.co/api/people/?page=3', { status: 200, body: people3 });
    fetchMock.get('http://swapi.co/api/people/?page=4', { status: 200, body: people4 });
    fetchMock.get('http://swapi.co/api/people/?page=5', { status: 200, body: people5 });
    fetchMock.get('http://swapi.co/api/people/?page=6', { status: 200, body: people6 });
    fetchMock.get('http://swapi.co/api/people/?page=7', { status: 200, body: people7 });
    fetchMock.get('http://swapi.co/api/people/?page=8', { status: 200, body: people8 });
    fetchMock.get('http://swapi.co/api/people/?page=9', { status: 200, body: people9 });

    let peopleArray = peopleScrubber();

    await resolveAfter2Seconds();
    peopleArray.then((array) => {
      expect(array.length).toEqual(42);
    })
  })

  it('speciesScrubber makes 9 api calls and return an array of length', async () => {
    fetchMock.get('http://swapi.co/api/species/?page=1', { status: 200, body: species1 });
    fetchMock.get('http://swapi.co/api/species/?page=2', { status: 200, body: species2 });
    fetchMock.get('http://swapi.co/api/species/?page=3', { status: 200, body: species3 });
    fetchMock.get('http://swapi.co/api/species/?page=4', { status: 200, body: species4 });

    let speciesArray = speciesScrubber();

    await resolveAfter2Seconds();
    speciesArray.then((array) => {
      expect(array.length).toEqual(42);
    })
  })

  it('vehicleScrubber makes 9 api calls and return an array of length', async () => {
    fetchMock.get('http://swapi.co/api/vehicles/?page=1', { status: 200, body: vehicles1 });
    fetchMock.get('http://swapi.co/api/vehicles/?page=2', { status: 200, body: vehicles2 });
    fetchMock.get('http://swapi.co/api/vehicles/?page=3', { status: 200, body: vehicles3 });
    fetchMock.get('http://swapi.co/api/vehicles/?page=4', { status: 200, body: vehicles4 });

    let vehicleArray = vehicleScrubber();

    await resolveAfter2Seconds();
    vehicleArray.then((array) => {
      expect(array.length).toEqual(42);
    })
  })

})
<commit_msg>corrected tests urls<commit_after>import React from 'react'
import mocha from 'mocha'
import fetch from 'whatwg-fetch'
import fetchMock from 'fetch-mock'
// import { shallow, mount } from 'enzyme'
import filmsScrubber from '../App/Scrubbers/filmsScrubber'
import peopleNeedPlanets from '../App/Scrubbers/peopleNeedPlanets'
import peopleScrubber from '../App/Scrubbers/peopleScrubber'
import planetScrubber from '../App/Scrubbers/planetScrubber'
import speciesOrdered from '../App/Scrubbers/speciesOrdered'
import speciesScrubber from '../App/Scrubbers/speciesScrubber'
import vehicleScrubber from '../App/Scrubbers/vehicleScrubber'

//stubbed data
import films from '../App/Data/films.json'
import planets1 from '../App/Data/Planets/Planets1.json'
import planets2 from '../App/Data/Planets/Planets2.json'
import planets3 from '../App/Data/Planets/Planets3.json'
import planets4 from '../App/Data/Planets/Planets4.json'
import planets5 from '../App/Data/Planets/Planets5.json'
import planets6 from '../App/Data/Planets/Planets6.json'
import planets7 from '../App/Data/Planets/Planets7.json'
import people1 from '../App/Data/People/People1.json'
import people2 from '../App/Data/People/People2.json'
import people3 from '../App/Data/People/People3.json'
import people4 from '../App/Data/People/People4.json'
import people5 from '../App/Data/People/People5.json'
import people6 from '../App/Data/People/People6.json'
import people7 from '../App/Data/People/People7.json'
import people8 from '../App/Data/People/People8.json'
import people9 from '../App/Data/People/People9.json'
import species1 from '../App/Data/Species/Species1.json'
import species2 from '../App/Data/Species/Species2.json'
import species3 from '../App/Data/Species/Species3.json'
import species4 from '../App/Data/Species/Species4.json'
import vehicles1 from '../App/Data/Vehicles/Vehicles1.json'
import vehicles2 from '../App/Data/Vehicles/Vehicles2.json'
import vehicles3 from '../App/Data/Vehicles/Vehicles3.json'
import vehicles4 from '../App/Data/Vehicles/Vehicles4.json'

describe('Time to scrub some data', () => {

  afterEach(() => {
    fetchMock.restore()
  })

function resolveAfter2Seconds () {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, 2000);
  });
}

  it('filmsScrubber should grab scroll text for seven films', async () => {
    fetchMock.get('http://swapi.co/api/films/?page=1', {
      status: 200,
      body: films
    })
    let filmArray = filmsScrubber();

    await resolveAfter2Seconds();
    filmArray.then((array) => {
      expect(array.length).toEqual(7);
    })

  })

  it('planetScrubber make 7 api calls and return an array of length 67', async () => {
    fetchMock.get('http://swapi.co/api/planets/?page=1', { status: 200, body: planets1 });
    fetchMock.get('http://swapi.co/api/planets/?page=2', { status: 200, body: planets2 });
    fetchMock.get('http://swapi.co/api/planets/?page=3', { status: 200, body: planets3 });
    fetchMock.get('http://swapi.co/api/planets/?page=4', { status: 200, body: planets4 });
    fetchMock.get('http://swapi.co/api/planets/?page=5', { status: 200, body: planets5 });
    fetchMock.get('http://swapi.co/api/planets/?page=6', { status: 200, body: planets6 });
    fetchMock.get('http://swapi.co/api/planets/?page=7', { status: 200, body: planets7 });

    let planetArray = planetScrubber();

    await resolveAfter2Seconds();
    planetArray.then((array) => {
      console.log('planets test', array.length)
      expect(array.length).toEqual(67);
    })
  })

  it('peopleScrubber makes 9 api calls and return an array of length', async () => {
    fetchMock.get('http://swapi.co/api/people/?page=1', { status: 200, body: people1 });
    fetchMock.get('http://swapi.co/api/people/?page=2', { status: 200, body: people2 });
    fetchMock.get('http://swapi.co/api/people/?page=3', { status: 200, body: people3 });
    fetchMock.get('http://swapi.co/api/people/?page=4', { status: 200, body: people4 });
    fetchMock.get('http://swapi.co/api/people/?page=5', { status: 200, body: people5 });
    fetchMock.get('http://swapi.co/api/people/?page=6', { status: 200, body: people6 });
    fetchMock.get('http://swapi.co/api/people/?page=7', { status: 200, body: people7 });
    fetchMock.get('http://swapi.co/api/people/?page=8', { status: 200, body: people8 });
    fetchMock.get('http://swapi.co/api/people/?page=9', { status: 200, body: people9 });

    let peopleArray = peopleScrubber();

    await resolveAfter2Seconds();
    peopleArray.then((array) => {
      expect(array.length).toEqual(87);
    })
  })

  it('speciesScrubber makes 4 api calls and return an array of length', async () => {
    fetchMock.get('http://swapi.co/api/species/?page=1', { status: 200, body: species1 });
    fetchMock.get('http://swapi.co/api/species/?page=2', { status: 200, body: species2 });
    fetchMock.get('http://swapi.co/api/species/?page=3', { status: 200, body: species3 });
    fetchMock.get('http://swapi.co/api/species/?page=4', { status: 200, body: species4 });

    let speciesArray = speciesScrubber();

    await resolveAfter2Seconds();
    speciesArray.then((array) => {
      expect(array.length).toEqual(37);
    })
  })

  it('vehicleScrubber makes 4 api calls and return an array of length', async () => {
    fetchMock.get('http://swapi.co/api/vehicles/?page=1', { status: 200, body: vehicles1 });
    fetchMock.get('http://swapi.co/api/vehicles/?page=2', { status: 200, body: vehicles2 });
    fetchMock.get('http://swapi.co/api/vehicles/?page=3', { status: 200, body: vehicles3 });
    fetchMock.get('http://swapi.co/api/vehicles/?page=4', { status: 200, body: vehicles4 });

    let vehicleArray = vehicleScrubber();

    await resolveAfter2Seconds();
    vehicleArray.then((array) => {
      expect(array.length).toEqual(39);
    })
  })

})
<|endoftext|>


<commit_before>describe('small-ide', function() {
  it("should have a config object", function() {
    expect(config).toBeDefined(undefined);
    expect(config.indentation).toBeDefined(undefined);
    expect(config.indentation).toEqual(jasmine.any(Number));
  })

  describe('Canvas', function() {
    it("canvas and draw should be defined", function() {
      expect(canvas).toBeDefined(undefined);
      expect(draw).toBeDefined(undefined);
    });
  });

  describe("Console", function() {
    it("log should be defined", function() {
      expect(log).toBeDefined(undefined);
      expect(out).toBeDefined(undefined);
      expect(out.clear).toBeDefined(undefined);
    })

    // beforeEach(function() {
    //   timerCallback = jasmine.createSpy('timerCallback');
    //   jasmine.Clock.useMock();
    // });

    afterEach(function() {
      out.clear();
    });

    it("should display string", function() {
      var string = "string", expected = "" + string + "
";
      log(string);
      expect(out.innerHTML).toEqual(expected);
    });

    it("should display number", function(done) {
      var number = 123, expected = '' + number + "
"
      log(number);
      setTimeout(function() {
        expect(out.innerHTML).toEqual(expected);
        done();
      }, 700);
    });

    it("should display object", function(done) {
      var obj = { foo: "bar", num:123, list: [1,2,3] },
        expected = '' + JSON.stringify(obj) + "
"
      log(obj);
      setTimeout(function() {
        expect(out.innerHTML).toEqual(expected);
        done();
      }, 700);
    });

    it("should display arrays", function(done) {
      var arr = [1,2,3], expected = '' + JSON.stringify(arr) + "
"
      log(arr);
      setTimeout(function() {
        expect(out.innerHTML).toEqual(expected);
        done();
      }, 700);
    });

    it("should scroll to the bottom if there is more elements logged that it can display", function(done) {
      var expected = '0
1
2
3
4
5
6
7
8
9
10
';
      for(var i = 0; log(i), i < 10; ++i);
      var scrollTop = out.scrollHeight - out.clientHeight;
      expect(out.scrollTop).toBe(scrollTop);
      // assert than the console contains what we expect
      setTimeout(function() {
        expect(out.innerHTML).toBe(expected);
        done();
      }, 700);
    })

    it("unless the user scrolls the console content", function(){
      var expected = '0
1
2
3
4
5
6
7
8
9
10
extra line
';
      var scrollTop = 20;
      for(var i = 0; log(i), i < 10; ++i);
      out.scrollTop = scrollTop;
      log("extra line");
      expect(out.scrollTop).toBe(scrollTop);
      // assert than the console contains what we expect
      setTimeout(function() {
        expect(out.innerHTML).toBe(expected);
        done();
      }, 700);
    });

  });

  describe("Editor", function() {
    it("canvas and draw should be defined", function() {
      expect(ta).toBeDefined(undefined);
    })
  });

});<commit_msg>added extra test for multiple strings to log<commit_after>describe('small-ide', function() {
  it("should have a config object", function() {
    expect(config).toBeDefined(undefined);
    expect(config.indentation).toBeDefined(undefined);
    expect(config.indentation).toEqual(jasmine.any(Number));
  })

  describe('Canvas', function() {
    it("canvas and draw should be defined", function() {
      expect(canvas).toBeDefined(undefined);
      expect(draw).toBeDefined(undefined);
    });
  });

  describe("Console", function() {
    var formatDelay = 600; // check source if this is altered

    it("log should be defined", function() {
      expect(log).toBeDefined(undefined);
      expect(out).toBeDefined(undefined);
      expect(out.clear).toBeDefined(undefined);
    })

    // beforeEach(function() {
    //   timerCallback = jasmine.createSpy('timerCallback');
    //   jasmine.Clock.useMock();
    // });

    afterEach(function() {
      out.clear();
    });

    it("should display string(s)", function() {
      var string = "string", expected = "" + string + "
";
      log(string);
      expect(out.innerHTML).toEqual(expected);
      expected += "" + string + "" + string + "
";
      log(string, string);
      expect(out.innerHTML).toEqual(expected);
    });

    it("should display number", function(done) {
      var number = 123, expected = '' + number + "
"
      log(number);
      setTimeout(function() {
        expect(out.innerHTML).toEqual(expected);
        done();
      }, formatDelay);
    });

    it("should display object", function(done) {
      var obj = { foo: "bar", num:123, list: [1,2,3] },
        expected = '' + JSON.stringify(obj) + "
"
      log(obj);
      setTimeout(function() {
        expect(out.innerHTML).toEqual(expected);
        done();
      }, formatDelay);
    });

    it("should display arrays", function(done) {
      var arr = [1,2,3], expected = '' + JSON.stringify(arr) + "
"
      log(arr);
      setTimeout(function() {
        expect(out.innerHTML).toEqual(expected);
        done();
      }, formatDelay);
    });

    it("should scroll to the bottom if there is more elements logged that it can display", function(done) {
      var expected = '0
1
2
3
4
5
6
7
8
9
10
';
      for(var i = 0; log(i), i < 10; ++i);
      var scrollTop = out.scrollHeight - out.clientHeight;
      expect(out.scrollTop).toBe(scrollTop);
      // assert than the console contains what we expect
      setTimeout(function() {
        expect(out.innerHTML).toBe(expected);
        done();
      }, formatDelay);
    })

    it("unless the user scrolls the console content", function(){
      var expected = '0
1
2
3
4
5
6
7
8
9
10
extra line
';
      var scrollTop = 20;
      for(var i = 0; log(i), i < 10; ++i);
      out.scrollTop = scrollTop;
      log("extra line");
      expect(out.scrollTop).toBe(scrollTop);
      // assert than the console contains what we expect
      setTimeout(function() {
        expect(out.innerHTML).toBe(expected);
        done();
      }, formatDelay);
    });

  });

  describe("Editor", function() {
    it("canvas and draw should be defined", function() {
      expect(ta).toBeDefined(undefined);
    })
  });

});<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

var fs = require('fs');
var https = require('https');
var program = require('commander');
var git = require('simple-git')();
var child_process = require('child_process');
var path = require('path');

var tempFolder = 'test_data';
var testRepoUrl = 'https://github.com/Microsoft/vscode-smoketest-express';
var testRepoLocalDir = path.join(process.cwd(), `${tempFolder}/vscode-smoketest-express`);
var keybindingsUrl = 'https://raw.githubusercontent.com/Microsoft/vscode-docs/master/scripts/keybindings';

program
	.option('-l, --latest <file path>', 'path to the latest VS Code to test')
	.option('-s, --stable [file path]', 'path to the stable VS Code to be used in data migration tests');

program.on('--help', () => {
	console.log('  Examples:');
	console.log('');
	console.log('    $ npm test -- --latest path/to/binary');
	console.log('    $ npm test -- -l path/to/binary');
	console.log('');
	console.log('    $ npm test -- --latest path/to/latest/binary --stable path/to/stable/binary');
	console.log('    $ npm test -- -l path/to/latest/binary -s path/to/stable/binary');
	console.log('');
});
program.parse(process.argv);

if (!program.latest) {
	console.error('You must specify the binary to run the smoke test against');
	process.exit(1);
}
if (!binaryExists(program.latest) || (program.stable && !binaryExists(program.stable))) {
	console.error('The file path to electron binary does not exist or permissions do not allow to execute it. Please check the path provided.');
	process.exit(1);
}

// Setting up environment variables
process.env.VSCODE_LATEST_PATH = program.latest;
if (program.stable) process.env.VSCODE_STABLE_PATH = program.stable;
process.env.SMOKETEST_REPO = testRepoLocalDir;
if (program.stable && program.stable.toLowerCase().startsWith('insiders')) process.env.VSCODE_EDITION = 'insiders';

// Setting up 'vscode-smoketest-express' project
var os = process.platform;
if (os === 'darwin') os = 'osx';
else if (os === 'win32') os = 'win';
var promises = [];

try {
	promises.push(getKeybindings(`${keybindingsUrl}/doc.keybindings.${os}.json`, `${tempFolder}/keybindings.json`));
	promises.push(cleanOrClone(testRepoUrl, testRepoLocalDir));

	Promise.all(promises).then(() => { execute('npm install', testRepoLocalDir).then(() => runTests()); });
} catch (e) {
	throw new Error('Error caught running the smoke test: ' + e);
}

function runTests() {
	console.log('Running tests...')
	const spawn = require('child_process').spawn;
	var proc = spawn(process.execPath, [
		'src/mocha-runner.js'
	]);
	proc.stdout.on('data', data => {
		console.log(data.toString());
	});
	proc.stderr.on('data', data => {
		var date = new Date().toLocaleString();
		fs.appendFile(`${tempFolder}/errors.log`, `${date}: ${data.toString()}`, (err) => {
			if (err) throw new Error(`Could not write stderr to errors.log with the following error: ${err}`);
		});
	});
	proc.on('exit', (code) => {
		process.exit(code);
	});
}

function cleanOrClone(repo, dir) {
	console.log('Cleaning or cloning test project repository...');
	return new Promise((res, rej) => {
		if (!folderExists(dir)) {
			git.clone(repo, dir, () => {
				console.log('Test repository successfully cloned.');
				res();
			});
		} else {
			git.cwd(dir);
			git.fetch((err) => {
				if (err) rej(err);
				resetAndClean();
			});
		}

		var resetAndClean = () => {
			git.reset(['FETCH_HEAD', '--hard'], (err) => {
				if (err) rej(err);

				git.clean('f', ['-d'], (err) => {
					if (err) rej(err);
					console.log('Test project was successfully reset to initial state.');
					res();
				});
			});
		}
	});
}

function execute(cmd, dir) {
	return new Promise((res, rej) => {
		console.log(`Running ${cmd}...`);
		child_process.exec(cmd, { cwd: dir, stdio: [0, 1, 2] }, (error, stdout, stderr) => {
			if (error) rej(error);
			if (stderr) console.error(stderr);
			console.log(stdout);
			res();
		});
	});
}

function getKeybindings(url, location) {
	console.log(`Fetching keybindings from ${url}...`);
	return new Promise((resolve, reject) => {
		https.get(url, (res) => {
			if (res.statusCode != 200) {
				reject(`Failed to obtain key bindings with response code: ${res.statusCode}`);
			}

			var buffer = [];
			res.on('data', (chunk) => buffer.push(chunk));
			res.on('end', () => {
				fs.writeFile(location, Buffer.concat(buffer), 'utf8', () => {
					console.log('Keybindings were successfully fetched.');
					resolve();
				});
			});
		}).on('error', (e) => {
			reject(`Failed to obtain key bindings with an error: ${e}`);
		});
	});
}

function folderExists(folder) {
	try {
		fs.accessSync(folder, 'rw');
		return true;
	} catch (e) {
		return false;
	}
}

function binaryExists(filePath) {
	try {
		fs.accessSync(filePath, 'x');
		return true;
	} catch (e) {
		return false;
	}
}<commit_msg>Resolves #27922<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

var fs = require('fs');
var https = require('https');
var program = require('commander');
var git = require('simple-git')();
var child_process = require('child_process');
var path = require('path');

var tempFolder = 'test_data';
var testRepoUrl = 'https://github.com/Microsoft/vscode-smoketest-express';
var testRepoLocalDir = path.join(process.cwd(), `${tempFolder}/vscode-smoketest-express`);
var keybindingsUrl = 'https://raw.githubusercontent.com/Microsoft/vscode-docs/master/scripts/keybindings';

program
	.option('-l, --latest <file path>', 'path to the latest VS Code to test')
	.option('-s, --stable [file path]', 'path to the stable VS Code to be used in data migration tests');

program.on('--help', () => {
	console.log('  Examples:');
	console.log('');
	console.log('    $ npm test -- --latest path/to/binary');
	console.log('    $ npm test -- -l path/to/binary');
	console.log('');
	console.log('    $ npm test -- --latest path/to/latest/binary --stable path/to/stable/binary');
	console.log('    $ npm test -- -l path/to/latest/binary -s path/to/stable/binary');
	console.log('');
});
program.parse(process.argv);

if (!program.latest) {
	fail('You must specify the binary to run the smoke test against');
}
if (!binaryExists(program.latest) || (program.stable && !binaryExists(program.stable))) {
	fail('The file path to electron binary does not exist or permissions do not allow to execute it. Please check the path provided.');
}
if (parseInt(process.version.substr(1)) < 6) {
	fail('Please update your Node version to greater than 6 to run the smoke test.');
}

// Setting up environment variables
process.env.VSCODE_LATEST_PATH = program.latest;
if (program.stable) process.env.VSCODE_STABLE_PATH = program.stable;
process.env.SMOKETEST_REPO = testRepoLocalDir;
if (program.stable && program.stable.toLowerCase().startsWith('insiders')) process.env.VSCODE_EDITION = 'insiders';

// Setting up 'vscode-smoketest-express' project
var os = process.platform;
if (os === 'darwin') os = 'osx';
else if (os === 'win32') os = 'win';
var promises = [];

try {
	promises.push(getKeybindings(`${keybindingsUrl}/doc.keybindings.${os}.json`, `${tempFolder}/keybindings.json`));
	promises.push(cleanOrClone(testRepoUrl, testRepoLocalDir));

	Promise.all(promises).then(() => { execute('npm install', testRepoLocalDir).then(() => runTests()); });
} catch (e) {
	throw new Error('Error caught running the smoke test: ' + e);
}

function fail(errorMessage) {
	console.error(errorMessage);
	process.exit(1);
}

function runTests() {
	console.log('Running tests...')
	const spawn = require('child_process').spawn;
	var proc = spawn(process.execPath, [
		'src/mocha-runner.js'
	]);
	proc.stdout.on('data', data => {
		console.log(data.toString());
	});
	proc.stderr.on('data', data => {
		var date = new Date().toLocaleString();
		fs.appendFile(`${tempFolder}/errors.log`, `${date}: ${data.toString()}`, (err) => {
			if (err) throw new Error(`Could not write stderr to errors.log with the following error: ${err}`);
		});
	});
	proc.on('exit', (code) => {
		process.exit(code);
	});
}

function cleanOrClone(repo, dir) {
	console.log('Cleaning or cloning test project repository...');
	return new Promise((res, rej) => {
		if (!folderExists(dir)) {
			git.clone(repo, dir, () => {
				console.log('Test repository successfully cloned.');
				res();
			});
		} else {
			git.cwd(dir);
			git.fetch((err) => {
				if (err) rej(err);
				resetAndClean();
			});
		}

		var resetAndClean = () => {
			git.reset(['FETCH_HEAD', '--hard'], (err) => {
				if (err) rej(err);

				git.clean('f', ['-d'], (err) => {
					if (err) rej(err);
					console.log('Test project was successfully reset to initial state.');
					res();
				});
			});
		}
	});
}

function execute(cmd, dir) {
	return new Promise((res, rej) => {
		console.log(`Running ${cmd}...`);
		child_process.exec(cmd, { cwd: dir, stdio: [0, 1, 2] }, (error, stdout, stderr) => {
			if (error) rej(error);
			if (stderr) console.error(stderr);
			console.log(stdout);
			res();
		});
	});
}

function getKeybindings(url, location) {
	console.log(`Fetching keybindings from ${url}...`);
	return new Promise((resolve, reject) => {
		https.get(url, (res) => {
			if (res.statusCode != 200) {
				reject(`Failed to obtain key bindings with response code: ${res.statusCode}`);
			}

			var buffer = [];
			res.on('data', (chunk) => buffer.push(chunk));
			res.on('end', () => {
				fs.writeFile(location, Buffer.concat(buffer), 'utf8', () => {
					console.log('Keybindings were successfully fetched.');
					resolve();
				});
			});
		}).on('error', (e) => {
			reject(`Failed to obtain key bindings with an error: ${e}`);
		});
	});
}

function folderExists(folder) {
	try {
		fs.accessSync(folder, 'rw');
		return true;
	} catch (e) {
		return false;
	}
}

function binaryExists(filePath) {
	try {
		fs.accessSync(filePath, 'x');
		return true;
	} catch (e) {
		return false;
	}
}<|endoftext|>


<commit_before>/*global define:true, describe:true , it:true , expect:true,
beforeEach:true, sinon:true, spyOn:true , expect:true */
/* jshint strict: false */
define(['go2o', 'jquery'], function(Go2o, $) {

    describe('just checking', function() {

        it('Go2o should be loaded', function() {
            expect(Go2o).toBeTruthy();
            var go2o = new Go2o();
            expect(go2o).toBeTruthy();
        });

        it('Go2o should initialize', function() {
            var go2o = new Go2o();
            var output   = go2o.init();
            var expected = 'This is just a stub!';
            expect(output).toEqual(expected);
        });

    });

});<commit_msg>SPEC: Adding initial tests.<commit_after>/*global define:true, describe:true , it:true , expect:true,
beforeEach:true, sinon:true, spyOn:true , expect:true */
/* jshint strict: false */
define(function(require) {
    var Go2o = require('go2o');

    describe('Go2o helpers', function() {

        it('should be accessible through the helpers namespace', function() {
            expect(Go2o.helpers).toBeTruthy();
        });
        it('should have a different helper methods', function() {
            var helpers = ['diff', 'extend', 'Parser'];
            expect(Go2o.helpers).toHaveProperties('diff', 'extend', 'Parser');
        });
    });

    describe('Go2o diff helper', function() {
        it('should have a diff helper', function() {
            var diff = Go2o.helpers.diff,
                src = {
                    foo: 'foo',
                    bar: 'bar'
                },
                tgt = {
                    foo: 'foo',
                    baz: 'baz'
                },
                exp = ['bar'];
            expect(diff).toBeTruthy();
            expect(diff(src, tgt)).toMatchObject(exp);
        });

        it('diff helper should handle undefined target argument', function() {
            var diff = Go2o.helpers.diff,
                src = {
                    foo: 'foo',
                    baz: 'baz'
                },
                tgt = null,
                exp = [];
            expect(diff).toBeTruthy();
            expect(diff(src, tgt)).toMatchObject(exp);
        });

        it('diff helper should handle undefined source argument', function() {
            var diff = Go2o.helpers.diff,
                src = null,
                tgt = {
                    foo: 'foo',
                    baz: 'baz'
                },
                exp = ['foo', 'baz'];
            expect(diff).toBeTruthy();
            expect(diff(src, tgt)).toMatchObject(exp);
        });
    });

    describe('extend helper', function() {
        it('should handle no arguments by returning a new object', function() {
            var extend = Go2o.helpers.extend;
            expect(extend()).toMatchObject({});
        });

        it('extend the target object with the properties of objects passed as arguments', function() {
            var source = {},
                target = {
                    foo: 'foo',
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target)).toMatchObject(output);
        });

        it('extend the target object with the properties of multiple objects passed as arguments', function() {
            var source = {},
                target = {
                    foo: 'foo'
                },
                target2 = {
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target, target2)).toMatchObject(output);
        });

        it('target objects should override source properties', function() {
            var source = {
                foo: 'fiz',
                bar: 'biz'
            },
                target = {
                    foo: 'foo',
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target)).toMatchObject(output);
        });

        it('multiple target objects should override source properties', function() {
            var source = {
                foo: 'fiz',
                bar: 'biz'
            },
                target = {
                    foo: 'foo',
                    bar: 'bir'
                },
                target2 = {
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target, target2)).toMatchObject(output);
        });
    });

    describe('Object helper should', function() {
        it('have a flatten method', function() {
            expect(Go2o.helpers.Parser.flatten).toBeTruthy();
            expect(Go2o.helpers.Parser.flatten).toBeOfType('function');
        });

        it('have a flatten unflatten', function() {
            expect(Go2o.helpers.Parser.unflatten).toBeTruthy();
            expect(Go2o.helpers.Parser.unflatten).toBeOfType('function');
        });

        it('have a flatten glob', function() {
            expect(Go2o.helpers.Parser.glob).toBeTruthy();
            expect(Go2o.helpers.Parser.glob).toBeOfType('function');
        });
    });

});<|endoftext|>


<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*
 * Copyright (c) 2014, Yahoo! Inc. All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 *
 * Library which supports opening , closing  and listing open sessions
 */

var fs = require("fs");
var util = require("util");
var log4js = require("log4js");
var WdSession = require("../lib/session/wdsession");
var wd = require("../lib/util/wd-wrapper");
var CapabilityManager = require("../lib/util/capabilitymanager");
var logger = log4js.getLogger("selLib");

/**
 *
 * @param config
 * @constructor
 */
function SelLib(config) {
    this.config = config;
    this.hub = new WdSession(config);
}

/**
 *  Build webdriver object based on properties set in webdriverConfObj
 * @param webdriverConfObj
 * @returns webdriver object
 */
SelLib.prototype.buildWebDriver = function(webdriverConfObj) {

    var webdriver;

    if (webdriverConfObj) {

        webdriver = new wd.Builder().
            usingServer(webdriverConfObj.seleniumHost).
            usingSession(webdriverConfObj.sessionId).
            withCapabilities(webdriverConfObj.capabilities).
            build();
    }

    return webdriver;
};

/**
 * Lists the open sessions
 * @param arrSessions
 * @param cb
 */
SelLib.prototype.listSessions = function (arrSessions, cb) {

    if (!arrSessions) {
        logger.info('No sessions found');
        cb();
    }

    if (arrSessions.length > 0) {

        var sessionId = arrSessions[0],
            self = this,
            webdriver,
            webdriverConfObj = {};

        arrSessions.shift();

        // Build webdriver object
        webdriverConfObj.seleniumHost = self.config.seleniumHost;
        webdriverConfObj.sessionId = sessionId;
        webdriver = self.buildWebDriver(webdriverConfObj);

        webdriver.getCapabilities().then(function(sessionCaps) {

            if (sessionCaps) {
                console.log('\n');
                console.log(sessionCaps.toJSON());
            }
            self.listSessions(arrSessions, cb);

        }, function(err) {
            logger.error('Error while listing sessions:' + err);
            self.listSessions(arrSessions, cb);
        });

    } else {
        cb();
    }

};

/**
 * Help !!
 */
SelLib.prototype.listHelp = function () {
    console.info("\nCommandline Options :" + "\n" +
        "--list : Lists all selenium browser sessions" + "\n" +
        "--open=<browser1[, browser2]> : Comma seperated list of browsers to launch" + "\n" +
        "--open=<browser> : browser to choose from capabilities.json" + " --capabilities= path to capabilities.json" + "\n" +
        "--close : Close all selenium controller browser sessions" + "\n\n" +
        "Examples:\n" +
        "Open Firefox and Chrome browser instances:\n" +
        "arrow_selenium --open=firefox,chrome\n"  +
        "Open Firefox with given capabilities:\n" +
        "arrow_selenium --open=firefox --capabilities=./cap.json\n"
        );
};

/**
 *
 * @param capabilities
 * @param browserName
 * @returns capability object based on pass capabilities and browser
 */
SelLib.prototype.getCapabilityObject = function(capabilities, browserName) {

    var caps,
        cm;

    // If user has passed capabilities
    if (capabilities) {
        caps = {
            "platform": "ANY",
            "javascriptEnabled": true,
            "seleniumProtocol": "WebDriver"
        };
        caps.browserName = browserName;

        if (!caps.browserName) {
            logger.error("No Browser is specified");
            process.exit(1);
        }

        cm = new CapabilityManager();
        capabilities = cm.getCapability(capabilities, caps.browserName);

        if (capabilities === null) {
            logger.error("No related capability for " + caps.browserName + " in " + capabilities);
            process.exit(1);
        }
    } else {
        // default capabilities
        capabilities = {
            "browserName": browserName,
            "version": "",
            "platform": "ANY",
            "javascriptEnabled": true
        };
    }
    logger.info('Capabilities::' + JSON.stringify(capabilities));
    return capabilities;

};

/**
 *
 * @param browserList - Browsers to open
 * @param openBrowserList - Already open browsers
 * @param capabilities - capabilities object
 * @param cb
 */
SelLib.prototype.openBrowsers = function(browserList, openBrowserList, capabilities, cb) {

    var webdriver,
        browserToOpen,
        self = this,
        webdriverConfObj = {};

    if (browserList && browserList.length > 0) {

        browserToOpen = browserList[0];

        browserList.shift();

        if (openBrowserList.indexOf(browserToOpen) !== -1) {
            logger.info('Browser ' + browserToOpen + ' is already open');
            self.openBrowsers(browserList, openBrowserList, capabilities, cb);
        } else {
            logger.info('Opening browser..' + browserToOpen);

            capabilities = self.getCapabilityObject(capabilities, browserToOpen);

            // Build webdriver object
            webdriverConfObj.seleniumHost = self.config.seleniumHost;
            webdriverConfObj.capabilities = capabilities;
            webdriver = self.buildWebDriver(webdriverConfObj);

            webdriver.getCapabilities().then(function(sessionCaps) {
                console.log(sessionCaps);

                openBrowserList.push(browserToOpen);
                logger.info('Session created for the browser ' + browserToOpen);
                // Open another browser, if asked for
                self.openBrowsers(browserList, openBrowserList, capabilities, cb);

            }, function(err) {
                logger.error('Error encountered while opening browser ' + browserToOpen +  ' - Error :'  + err);
                // Open another browser, if asked for
                self.openBrowsers(browserList, openBrowserList, capabilities, cb);
            });

        }

    } else {
        cb();
    }

};

/**
 * Get browser name for the webdriver object
 * @param webdriver
 * @param cb
 */
SelLib.prototype.getBrowserName = function(webdriver, cb) {

    if (webdriver) {

        webdriver.getCapabilities().then(function(val) {

            if (val) {
                var browserName = val.get("browserName");
                cb(browserName);
            }

        }, function(err) {
            logger.error('Error in getBrowserName getting browser name :' + err);
            cb();
        });
    } else {
        cb();
    }

};

/**
 *
 * @param arrSessions - Already open sessions
 * @param openBrowserList - List of open browsers
 * @param cb
 */
SelLib.prototype.getListOfOpenBrowsers = function(arrSessions, openBrowserList, cb) {

    var
        webdriver,
        self = this,
        sessionId;

    if (arrSessions.length === 0) {
        cb(openBrowserList);
    } else {

        sessionId = arrSessions[0];
        arrSessions.shift();

        webdriver = new wd.Builder().
            usingServer(self.config.seleniumHost).
            usingSession(sessionId).
            build();

        self.getBrowserName(webdriver, function(browserName) {
            if (browserName) {
                openBrowserList.push(browserName);
            }
            self.getListOfOpenBrowsers(arrSessions, openBrowserList, cb);
        });
    }
};

/**
 *
 * @param arrSessions
 * @param cb
 */
SelLib.prototype.closeBrowsers = function (arrSessions, cb) {

    var
        sessionId,
        self = this,
        webdriver;

    if (arrSessions) {

        if (arrSessions.length === 0) {
            cb();
        } else {

            sessionId = arrSessions[0];
            arrSessions.shift();

            webdriver  = new wd.Builder().
                usingServer(self.config["seleniumHost"]).
                usingSession(sessionId).
                build();
            logger.info("Killing Session ID :" + sessionId);

            webdriver.quit().then(function() {
                self.closeBrowsers(arrSessions, cb);
            }, function(err) {
                logger.info("Error in Killing Session ID :" + sessionId + " , error :" + err);
                self.closeBrowsers(arrSessions, cb);
            });

        }

    }

};

/**
 *
 * @param browsers - comma separated list of arguments to --open e.g firefox,chrome
 * @param capabilities
 */
SelLib.prototype.open = function (browsers, capabilities, cb) {

    var self = this;

    self.hub.getSessions(function (error, arrSessions) {

        if (error) {
            logger.info('Error:' + error);
            if (cb) {
                cb(error);
            }
        } else {
            var browserList = browsers.split(","),
                openBrowserList = [];

            if (arrSessions) {
                logger.info("Found " + arrSessions.length + " browsers.");
            }
            self.getListOfOpenBrowsers(arrSessions, openBrowserList, function(openBrowserList) {

                self.openBrowsers(browserList, openBrowserList, capabilities, function() {
                    logger.info('Done opening all browsers...' + browsers.split(","));

                    if (cb) {
                        cb();
                    }
                });

            });

        }

    }, true);

};

/**
 * Close all open browsers
 */
SelLib.prototype.close = function (cb) {
    var self = this;
    self.hub.getSessions(function (error, arrSessions) {

        if (error) {
            logger.info(error);
        } else if (arrSessions && arrSessions.length > 0) {

            logger.info("Found " + arrSessions.length + " browsers.");
            self.closeBrowsers(arrSessions, function() {
                logger.info('Closed all open browsers on host ' + self.config.seleniumHost);
                if (cb) {
                    cb();
                }
            });
        }
    });

};

/**
 * List all open sessions
 */
SelLib.prototype.list = function () {

    var self = this;
    self.hub.getSessions(function (error, arrSessions) {
        if (error) {
            logger.info(error);
        } else {
            self.listSessions(arrSessions, function() {
                logger.info('Listed all sessions');
            });
        }
    }, false);

};

module.exports = SelLib;<commit_msg>Fixing capabilities for each browser, using buildWebdriver() for all calls<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*
 * Copyright (c) 2014, Yahoo! Inc. All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 *
 * Library which supports opening , closing  and listing open sessions
 */

var fs = require("fs");
var util = require("util");
var log4js = require("log4js");
var WdSession = require("../lib/session/wdsession");
var wd = require("../lib/util/wd-wrapper");
var CapabilityManager = require("../lib/util/capabilitymanager");
var logger = log4js.getLogger("selLib");

/**
 *
 * @param config
 * @constructor
 */
function SelLib(config) {
    this.config = config;
    this.hub = new WdSession(config);
}

/**
 *  Build webdriver object based on properties set in webdriverConfObj
 * @param webdriverConfObj
 * @returns webdriver object
 */
SelLib.prototype.buildWebDriver = function(webdriverConfObj) {

    var webdriver;

    if (webdriverConfObj) {

        webdriver = new wd.Builder().
            usingServer(webdriverConfObj.seleniumHost).
            usingSession(webdriverConfObj.sessionId).
            withCapabilities(webdriverConfObj.capabilities).
            build();
    }

    return webdriver;
};

/**
 * Lists the open sessions
 * @param arrSessions
 * @param cb
 */
SelLib.prototype.listSessions = function (arrSessions, cb) {

    if (!arrSessions) {
        logger.info('No sessions found');
        cb();
    }

    if (arrSessions.length > 0) {

        var sessionId = arrSessions[0],
            self = this,
            webdriver,
            webdriverConfObj = {};

        arrSessions.shift();

        // Build webdriver object
        webdriverConfObj.seleniumHost = self.config.seleniumHost;
        webdriverConfObj.sessionId = sessionId;
        webdriver = self.buildWebDriver(webdriverConfObj);

        webdriver.getCapabilities().then(function(sessionCaps) {

            if (sessionCaps) {
                console.log('\n');
                console.log(sessionCaps.toJSON());
            }
            self.listSessions(arrSessions, cb);

        }, function(err) {
            logger.error('Error while listing sessions:' + err);
            self.listSessions(arrSessions, cb);
        });

    } else {
        cb();
    }

};

/**
 * Help !!
 */
SelLib.prototype.listHelp = function () {
    console.info("\nCommandline Options :" + "\n" +
        "--list : Lists all selenium browser sessions" + "\n" +
        "--open=<browser1[, browser2]> : Comma seperated list of browsers to launch" + "\n" +
        "--open=<browser> : browser to choose from capabilities.json" + " --capabilities= path to capabilities.json" + "\n" +
        "--close : Close all selenium controller browser sessions" + "\n\n" +
        "Examples:\n" +
        "Open Firefox and Chrome browser instances:\n" +
        "arrow_selenium --open=firefox,chrome\n"  +
        "Open Firefox with given capabilities:\n" +
        "arrow_selenium --open=firefox --capabilities=./cap.json\n"
        );
};

/**
 *
 * @param capabilities
 * @param browserName
 * @returns capability object based on pass capabilities and browser
 */
SelLib.prototype.getCapabilityObject = function(capabilities, browserName) {

    var caps,
        cm;

    // If user has passed capabilities
    if (capabilities) {
        caps = {
            "platform": "ANY",
            "javascriptEnabled": true,
            "seleniumProtocol": "WebDriver"
        };
        caps.browserName = browserName;

        if (!caps.browserName) {
            logger.error("No Browser is specified");
            process.exit(1);
        }

        cm = new CapabilityManager();
        capabilities = cm.getCapability(capabilities, caps.browserName);

        if (capabilities === null) {
            logger.error("No related capability for " + caps.browserName + " in " + capabilities);
            process.exit(1);
        }
    } else {
        // default capabilities
        capabilities = {
            "browserName": browserName,
            "version": "",
            "platform": "ANY",
            "javascriptEnabled": true
        };
    }
    return capabilities;

};

/**
 *
 * @param browserList - Browsers to open
 * @param openBrowserList - Already open browsers
 * @param capabilities - capabilities object
 * @param cb
 */
SelLib.prototype.openBrowsers = function(browserList, openBrowserList, capabilities, cb) {

    var webdriver,
        browserToOpen,
        self = this,
        webdriverConfObj = {},
        caps;

    if (browserList && browserList.length > 0) {

        browserToOpen = browserList[0];

        browserList.shift();

        if (openBrowserList.indexOf(browserToOpen) !== -1) {
            logger.info('Browser ' + browserToOpen + ' is already open');
            self.openBrowsers(browserList, openBrowserList, capabilities, cb);
        } else {
            logger.info('Opening browser..' + browserToOpen);
//            logger.info('capabilities..' + JSON.stringify(capabilities));

            caps = self.getCapabilityObject(capabilities, browserToOpen);
            logger.info('Capabilities::' + JSON.stringify(caps));

            // Build webdriver object
            webdriverConfObj.seleniumHost = self.config.seleniumHost;
            webdriverConfObj.capabilities = caps;
            webdriver = self.buildWebDriver(webdriverConfObj);

            webdriver.getCapabilities().then(function(sessionCaps) {
                console.log(sessionCaps);

                openBrowserList.push(browserToOpen);
                logger.info('Session created for the browser ' + browserToOpen);
                // Open another browser, if asked for
                self.openBrowsers(browserList, openBrowserList, capabilities, cb);

            }, function(err) {
                logger.error('Error encountered while opening browser ' + browserToOpen +  ' - Error :'  + err);
                // Open another browser, if asked for
                self.openBrowsers(browserList, openBrowserList, capabilities, cb);
            });

        }

    } else {
        cb();
    }

};

/**
 * Get browser name for the webdriver object
 * @param webdriver
 * @param cb
 */
SelLib.prototype.getBrowserName = function(webdriver, cb) {

    if (webdriver) {

        webdriver.getCapabilities().then(function(val) {

            if (val) {
                var browserName = val.get("browserName");
                cb(browserName);
            }

        }, function(err) {
            logger.error('Error in getBrowserName getting browser name :' + err);
            cb();
        });
    } else {
        cb();
    }

};

/**
 *
 * @param arrSessions - Already open sessions
 * @param openBrowserList - List of open browsers
 * @param cb
 */
SelLib.prototype.getListOfOpenBrowsers = function(arrSessions, openBrowserList, cb) {

    var
        webdriver,
        self = this,
        sessionId,
        webdriverConfObj = {};

    if (arrSessions.length === 0) {
        cb(openBrowserList);
    } else {

        sessionId = arrSessions[0];
        arrSessions.shift();

        // Build webdriver object
        webdriverConfObj.seleniumHost = self.config.seleniumHost;
        webdriverConfObj.sessionId = sessionId;
        webdriver = self.buildWebDriver(webdriverConfObj);

        self.getBrowserName(webdriver, function(browserName) {
            if (browserName) {
                openBrowserList.push(browserName);
            }
            self.getListOfOpenBrowsers(arrSessions, openBrowserList, cb);
        });
    }
};

/**
 *
 * @param arrSessions
 * @param cb
 */
SelLib.prototype.closeBrowsers = function (arrSessions, cb) {

    var
        sessionId,
        self = this,
        webdriver,
        webdriverConfObj = {};

    if (arrSessions) {

        if (arrSessions.length === 0) {
            cb();
        } else {

            sessionId = arrSessions[0];
            arrSessions.shift();

            // Build webdriver object
            webdriverConfObj.seleniumHost = self.config.seleniumHost;
            webdriverConfObj.sessionId = sessionId;
            webdriver = self.buildWebDriver(webdriverConfObj);

            logger.info("Killing Session ID :" + sessionId);

            webdriver.quit().then(function() {
                self.closeBrowsers(arrSessions, cb);
            }, function(err) {
                logger.info("Error in Killing Session ID :" + sessionId + " , error :" + err);
                self.closeBrowsers(arrSessions, cb);
            });

        }

    }

};

/**
 *
 * @param browsers - comma separated list of arguments to --open e.g firefox,chrome
 * @param capabilities - passed by the user
 */
SelLib.prototype.open = function (browsers, capabilities, cb) {

    var self = this;

    self.hub.getSessions(function (error, arrSessions) {

        if (error) {
            logger.info('Error:' + error);
            if (cb) {
                cb(error);
            }
        } else {
            var browserList = browsers.split(","),
                openBrowserList = [];

            if (arrSessions) {
                logger.info("Found " + arrSessions.length + " browsers.");
            }
            self.getListOfOpenBrowsers(arrSessions, openBrowserList, function(openBrowserList) {

                self.openBrowsers(browserList, openBrowserList, capabilities, function() {
                    logger.info('Done opening all browsers...' + browsers.split(","));

                    if (cb) {
                        cb();
                    }
                });

            });

        }

    }, true);

};

/**
 * Close all open browsers
 */
SelLib.prototype.close = function (cb) {
    var self = this;
    self.hub.getSessions(function (error, arrSessions) {

        if (error) {
            logger.info(error);
        } else if (arrSessions && arrSessions.length > 0) {

            logger.info("Found " + arrSessions.length + " browsers.");
            self.closeBrowsers(arrSessions, function() {
                logger.info('Closed all open browsers on host ' + self.config.seleniumHost);
                if (cb) {
                    cb();
                }
            });
        }
    });

};

/**
 * List all open sessions
 */
SelLib.prototype.list = function () {

    var self = this;
    self.hub.getSessions(function (error, arrSessions) {
        if (error) {
            logger.info(error);
        } else {
            self.listSessions(arrSessions, function() {
                logger.info('Listed all sessions');
            });
        }
    }, false);

};

module.exports = SelLib;<|endoftext|>


<commit_before>import response from 'alexa-response';
import { alexaEars, facebookEars } from './listener';
import { getTopBoards, getProductsByCategory } from './service';
import { SYSTEM, BOARDS, CLIPS, IDENTITY } from './nlp';

alexaEars.on('message_received', function(bot, message) {
  if (message.alexa.session.application.applicationId !== process.env.ALEXA_APPID) {
    bot.reply(message,
      response
        .fail(`Invalid applicationId: ${message.alexa.session.application.applicationId}`)
        .shouldEndSession(true)
    );
  }
});

facebookEars.hears(SYSTEM.LAUNCH.intents, ['message_received'], function(bot, message) {
  bot.reply(message, SYSTEM.LAUNCH.responses.greeting);
  message.utu.event("Session Launch");
});

alexaEars.hears(SYSTEM.LAUNCH.intents, ['message_received'], function(bot, message) {
  bot.reply(message,
    response
      .say(SYSTEM.LAUNCH.responses.greeting)
      .reprompt(SYSTEM.HELP.responses.help)
      .shouldEndSession(false)
  );
  message.utu.event("Session Launch");
});

alexaEars.hears(SYSTEM.START.intents, ['message_received'], function(bot, message) {
  bot.reply(message, SYSTEM.START.responses.greeting);
  message.utu.event("Session Start");
});

alexaEars.hears(SYSTEM.START.intents, ['message_received'], function(bot, message) {
  bot.reply(message,
    response
      .say(SYSTEM.START.responses.greeting)
      .reprompt(SYSTEM.HELP.responses.help)
      .shouldEndSession(false)
  );
  message.utu.event("Session Start");
});

facebookEars.hears(BOARDS.TOP_BOARDS.intents, ['message_received'], function(bot, message) {
  getTopBoards()
    .then((url) => {
      bot.reply(message, `you asked for all top boards ${url}`);
    });
    message.utu.event("Top Boards");
});

alexaEars.hears(BOARDS.TOP_BOARDS.intents, ['message_received'], function(bot, message) {
  getTopBoards()
    .then((url) => {
      bot.reply(message,
        response
          .say(`you asked for all top boards ${url}`)
          .shouldEndSession(false)
      );
    });
    message.utu.event("Top Boards");
});

facebookEars.hears(CLIPS.LIST_CATEGORIES.intents, ['message_received'], function(bot, message) {
  bot.reply(message, `Categories are as follows ${CLIPS.slotTypes.CATEGORIES.toString()}`);
  message.utu.event("Clip Categories");
});

alexaEars.hears(CLIPS.LIST_CATEGORIES.intents, ['message_received'], function(bot, message) {
  bot.reply(message,
    response
      .say(`Categories are as follows ${CLIPS.slotTypes.CATEGORIES.toString()}`)
      .reprompt('Please say, show then a category name for example show gifts')
      .shouldEndSession(false)
  );
  message.utu.event("Clip Categories");
});

facebookEars.hears(CLIPS.CLIP_CATEGORIES.intents, ['message_received'], function(bot, message) {
  const category = message.match[1];
  if (category) {
    if (CLIPS.slotTypes.CATEGORIES.indexOf(category) > 0) {
      getProductsByCategory(category)
        .then((res) => {
          bot.reply(message, `Heard you want clips for the ${category}. ${res.url}`);
        });
      message.utu.event("Clip by Category", {
        values: {
          "Category": category,
        }
      });
    } else {
      bot.reply(message, `Sorry, but ${category} is not a category.  Please try again.`);
      message.utu.event("Error - Clip Category");
    }
  } else {
    bot.reply(message, "Sorry, I didn't catach a category.  Can you repeat it please?");
    message.utu.event("Error - Clip Category");
  }
});

alexaEars.hears(CLIPS.CLIP_CATEGORIES.intents, ['message_received'], function(bot, message) {
  const category = message.alexa.getSlotValue('CATEGORY');
  if (category) {
    if (CLIPS.slotTypes.CATEGORIES.indexOf(category) > 0) {
      getProductsByCategory(category)
        .then((res) => {
          bot.reply(message,
            response
              .say(`Heard you want clips for the ${category}. ${res.url}`)
              .shouldEndSession(false)
          );
        });
      message.utu.event("Clip by Category", {
        values: {
          "Category": category,
        }
      });
    } else {
      bot.reply(message,
        response
          .ask(`Sorry, but ${category} is not a category.  Please try again.`)
          .reprompt(SYSTEM.HELP.responses.help)
          .shouldEndSession(false)
      );
      message.utu.event("Error - Clip Category");
    }
  } else {
    bot.reply(message,
      response
        .ask("Sorry, I didn't catach a category.  Can you repeat it please?")
        .shouldEndSession(false)
    );
    message.utu.event("Error - Clip Category");
  }
});

facebookEars.hears(IDENTITY.LOGIN.intents, ['message_received'], (bot, message) => {
  const email = message.match[1];
  if (email) {
    bot.reply(message, IDENTITY.LOGIN.responses.update);
    message.utu.event("Login");
    message.utu.user({
      values: {
        email: email,
      }
    });
  } else {
    bot.reply(message, "Sorry, I didn't catach an email.  Can you repeat it please?");
    message.utu.event("Error - Login");
  }
});

alexaEars.hears(IDENTITY.LOGIN.intents, ['message_received'], function(bot, message) {
  const email = message.alexa.getSlotValue('EMAIL');
  if (email) {
    bot.reply(message,
      response
        .say(IDENTITY.LOGIN.responses.update)
        .shouldEndSession(false)
    );
    message.utu.event("Login");
    message.utu.user({
      values: {
        email: email,
      }
    });
  } else {
    bot.reply(message,
      response
        .ask("Sorry, I didn't catach an email.  Can you repeat it please?")
        .shouldEndSession(false)
    );
    message.utu.event("Error - Login");
  }
});

facebookEars.hears(SYSTEM.HELP.intents, ['message_received'], (bot, message) => {
  bot.reply(message, SYSTEM.HELP.responses.intro);
  message.utu.event("Help");
});

alexaEars.hears(SYSTEM.HELP.intents, ['message_received'], (bot, message) => {
  bot.reply(message,
    response
      .say(SYSTEM.HELP.responses.intro)
      .say(SYSTEM.HELP.responses.help)
      .shouldEndSession(false)
  );
  message.utu.event("Help");
});

facebookEars.hears(SYSTEM.STOP.intents, ['message_received'], (bot, message) => {
  bot.reply(message, SYSTEM.STOP.responses.goodbye);
  message.utu.event("Goodbye");
});

alexaEars.hears(SYSTEM.STOP.intents, ['message_received'], (bot, message) => {
  bot.reply(message,
    response
      .say(SYSTEM.STOP.responses.goodbye)
      .shouldEndSession(true)
  );
  message.utu.event("Goodbye");
});
<commit_msg>intent order<commit_after>import response from 'alexa-response';
import { alexaEars, facebookEars } from './listener';
import { getTopBoards, getProductsByCategory } from './service';
import { SYSTEM, BOARDS, CLIPS, IDENTITY } from './nlp';

alexaEars.on('message_received', function(bot, message) {
  if (message.alexa.session.application.applicationId !== process.env.ALEXA_APPID) {
    bot.reply(message,
      response
        .fail(`Invalid applicationId: ${message.alexa.session.application.applicationId}`)
        .shouldEndSession(true)
    );
  }
});

facebookEars.hears(SYSTEM.LAUNCH.intents, ['message_received'], function(bot, message) {
  bot.reply(message, SYSTEM.LAUNCH.responses.greeting);
  message.utu.event("Session Launch");
});

alexaEars.hears(SYSTEM.LAUNCH.intents, ['message_received'], function(bot, message) {
  bot.reply(message,
    response
      .say(SYSTEM.LAUNCH.responses.greeting)
      .reprompt(SYSTEM.HELP.responses.help)
      .shouldEndSession(false)
  );
  message.utu.event("Session Launch");
});

alexaEars.hears(SYSTEM.START.intents, ['message_received'], function(bot, message) {
  bot.reply(message, SYSTEM.START.responses.greeting);
  message.utu.event("Session Start");
});

alexaEars.hears(SYSTEM.START.intents, ['message_received'], function(bot, message) {
  bot.reply(message,
    response
      .say(SYSTEM.START.responses.greeting)
      .reprompt(SYSTEM.HELP.responses.help)
      .shouldEndSession(false)
  );
  message.utu.event("Session Start");
});

facebookEars.hears(BOARDS.TOP_BOARDS.intents, ['message_received'], function(bot, message) {
  getTopBoards()
    .then((url) => {
      bot.reply(message, `you asked for all top boards ${url}`);
    });
    message.utu.event("Top Boards");
});

alexaEars.hears(BOARDS.TOP_BOARDS.intents, ['message_received'], function(bot, message) {
  getTopBoards()
    .then((url) => {
      bot.reply(message,
        response
          .say(`you asked for all top boards ${url}`)
          .shouldEndSession(false)
      );
    });
    message.utu.event("Top Boards");
});

facebookEars.hears(CLIPS.LIST_CATEGORIES.intents, ['message_received'], function(bot, message) {
  bot.reply(message, `Categories are as follows ${CLIPS.slotTypes.CATEGORIES.toString()}`);
  message.utu.event("Clip Categories");
});

alexaEars.hears(CLIPS.LIST_CATEGORIES.intents, ['message_received'], function(bot, message) {
  bot.reply(message,
    response
      .say(`Categories are as follows ${CLIPS.slotTypes.CATEGORIES.toString()}`)
      .reprompt('Please say, show then a category name for example show gifts')
      .shouldEndSession(false)
  );
  message.utu.event("Clip Categories");
});

facebookEars.hears(CLIPS.CLIP_CATEGORIES.intents, ['message_received'], function(bot, message) {
  const category = message.match[1];
  if (category) {
    if (CLIPS.slotTypes.CATEGORIES.indexOf(category) > 0) {
      getProductsByCategory(category)
        .then((res) => {
          bot.reply(message, `Heard you want clips for the ${category}. ${res.url}`);
        });
      message.utu.event("Clip by Category", {
        values: {
          "Category": category,
        }
      });
    } else {
      bot.reply(message, `Sorry, but ${category} is not a category.  Please try again.`);
      message.utu.event("Error - Clip Category");
    }
  } else {
    bot.reply(message, "Sorry, I didn't catach a category.  Can you repeat it please?");
    message.utu.event("Error - Clip Category");
  }
});

alexaEars.hears(CLIPS.CLIP_CATEGORIES.intents, ['message_received'], function(bot, message) {
  const category = message.alexa.getSlotValue('CATEGORY');
  if (category) {
    if (CLIPS.slotTypes.CATEGORIES.indexOf(category) > 0) {
      getProductsByCategory(category)
        .then((res) => {
          bot.reply(message,
            response
              .say(`Heard you want clips for the ${category}. ${res.url}`)
              .shouldEndSession(false)
          );
        });
      message.utu.event("Clip by Category", {
        values: {
          "Category": category,
        }
      });
    } else {
      bot.reply(message,
        response
          .ask(`Sorry, but ${category} is not a category.  Please try again.`)
          .reprompt(SYSTEM.HELP.responses.help)
          .shouldEndSession(false)
      );
      message.utu.event("Error - Clip Category");
    }
  } else {
    bot.reply(message,
      response
        .ask("Sorry, I didn't catach a category.  Can you repeat it please?")
        .shouldEndSession(false)
    );
    message.utu.event("Error - Clip Category");
  }
});

facebookEars.hears(IDENTITY.LOGIN.intents, ['message_received'], (bot, message) => {
  console.log("message: ", message.match);
  const email = message.match[1];
  console.log("email: ", email);
  if (email) {
    message.utu.event("Login");
    bot.reply(message, IDENTITY.LOGIN.responses.update);
    message.utu.user({
      values: {
        email: email,
      }
    });
  } else {
    message.utu.event("Error - Login");
    bot.reply(message, "Sorry, I didn't catach an email.  Can you repeat it please?");
  }
});

alexaEars.hears(IDENTITY.LOGIN.intents, ['message_received'], function(bot, message) {
  const email = message.alexa.getSlotValue('EMAIL');
  if (email) {
    bot.reply(message,
      response
        .say(IDENTITY.LOGIN.responses.update)
        .shouldEndSession(false)
    );
    message.utu.event("Login");
    message.utu.user({
      values: {
        email: email,
      }
    });
  } else {
    bot.reply(message,
      response
        .ask("Sorry, I didn't catach an email.  Can you repeat it please?")
        .shouldEndSession(false)
    );
    message.utu.event("Error - Login");
  }
});

facebookEars.hears(SYSTEM.HELP.intents, ['message_received'], (bot, message) => {
  bot.reply(message, SYSTEM.HELP.responses.intro);
  message.utu.event("Help");
});

alexaEars.hears(SYSTEM.HELP.intents, ['message_received'], (bot, message) => {
  bot.reply(message,
    response
      .say(SYSTEM.HELP.responses.intro)
      .say(SYSTEM.HELP.responses.help)
      .shouldEndSession(false)
  );
  message.utu.event("Help");
});

facebookEars.hears(SYSTEM.STOP.intents, ['message_received'], (bot, message) => {
  bot.reply(message, SYSTEM.STOP.responses.goodbye);
  message.utu.event("Goodbye");
});

alexaEars.hears(SYSTEM.STOP.intents, ['message_received'], (bot, message) => {
  bot.reply(message,
    response
      .say(SYSTEM.STOP.responses.goodbye)
      .shouldEndSession(true)
  );
  message.utu.event("Goodbye");
});
<|endoftext|>


<commit_before>var webpack = require('webpack');

module.exports = {
  entry: {
    index: './components/index',
    Toggle: ['./components/Toggle'],
    Group: ['./components/Group'],
    Slider: ['./components/Slider'],
    AutoComplete: ['./components/AutoComplete'],
    Count: ['./components/Count'],
    InputRange: ['./components/InputRange']
  },
  output: {
    path: './dist',
    filename: '[name].js',
    libraryTarget: 'umd'
  },

  externals: {
    react: 'React',
    classnames: 'classNames',
    'react-dom': 'ReactDOM',
    'fuse.js': 'Fuse',
    'deep-copy': 'deepCopy'
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel'
      }
    ]
  },
  plugins: [
    new webpack.optimize.DedupePlugin()
  ]
};
<commit_msg>chore(webpack): fix external names<commit_after>var webpack = require('webpack');

module.exports = {
  entry: {
    index: './components/index',
    Toggle: ['./components/Toggle'],
    Group: ['./components/Group'],
    Slider: ['./components/Slider'],
    AutoComplete: ['./components/AutoComplete'],
    Count: ['./components/Count'],
    InputRange: ['./components/InputRange']
  },
  output: {
    path: './dist',
    filename: '[name].js',
    libraryTarget: 'umd'
  },

  externals: ['react', 'react-dom', 'deep-copy', 'fuse.js', 'classnames'],

  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel'
      }
    ]
  },
  plugins: [
    new webpack.optimize.DedupePlugin()
  ]
};
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SassLintPlugin = require('sasslint-webpack-plugin');

const basePlugins = [
  new webpack.DefinePlugin({
    __DEV__: process.env.NODE_ENV !== 'production',
    __PRODUCTION__: process.env.NODE_ENV === 'production',
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
  }),
  new webpack.optimize.CommonsChunkPlugin('vendor', '[name].[hash].bundle.js'),
  new HtmlWebpackPlugin({
    template: './src/index.html',
    inject: 'body',
    minify: false,
  }),
  new SassLintPlugin({
    glob: 'src/**/*.s?(a|c)ss',
  }),
];

const devPlugins = [];

const prodPlugins = [
  new webpack.optimize.UglifyJsPlugin({
    mangle: false,
    compress: {
      warnings: false,
    },
  }),
];

const plugins = basePlugins
  .concat(process.env.NODE_ENV === 'production' ? prodPlugins : [])
  .concat(process.env.NODE_ENV === 'development' ? devPlugins : []);

module.exports = {
  entry: {
    app: './src/index',
    vendor: [
      'es5-shim',
      'es6-shim',
      'es6-promise',
      'react',
      'react-dom',
      'react-router',
    ],
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].[hash].js',
    sourceMapFilename: '[name].[hash].js.map',
    chunkFilename: '[id].chunk.js',
  },

  devtool: 'source-map',

  devServer: {
    host: 'localhost',
    port: 8080,
  },

  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
      },
    ],
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.s?(a|c)ss$/,
        exclude: /node_modules/,
        loader: 'style-loader!css-loader!postcss-loader!sass-loader',
      },
    ],
  },

  plugins: plugins,

  resolve: {
    extensions: ['', '.js', '.jsx'],
  },

  postcss: function postcssInit() {
    return [
      require('postcss-cssnext'),
    ];
  },
};
<commit_msg>cleaned up webpack config<commit_after>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SassLintPlugin = require('sasslint-webpack-plugin');

const basePlugins = [
  new webpack.DefinePlugin({
    __DEV__: process.env.NODE_ENV !== 'production',
    __PRODUCTION__: process.env.NODE_ENV === 'production',
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
  }),
  new webpack.optimize.CommonsChunkPlugin('vendor', '[name].[hash].bundle.js'),
  new HtmlWebpackPlugin({
    template: './src/index.html',
    inject: 'body',
    minify: false,
  }),
  new SassLintPlugin({
    glob: 'src/**/*.scss',
  }),
];

const devPlugins = [];

const prodPlugins = [
  new webpack.optimize.UglifyJsPlugin({
    mangle: false,
    compress: {
      warnings: false,
    },
  }),
];

const plugins = basePlugins
  .concat(process.env.NODE_ENV === 'production' ? prodPlugins : [])
  .concat(process.env.NODE_ENV === 'development' ? devPlugins : []);

module.exports = {
  entry: {
    app: './src/index',
    vendor: [
      'es5-shim',
      'es6-shim',
      'es6-promise',
      'react',
      'react-dom',
      'react-router',
    ],
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].[hash].js',
    sourceMapFilename: '[name].[hash].js.map',
    chunkFilename: '[id].chunk.js',
  },

  devtool: 'source-map',

  devServer: {
    host: 'localhost',
    port: 8080,
  },

  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'eslint',
      },
    ],
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loader: 'style!css!postcss!sass',
      },
    ],
  },

  plugins: plugins,

  resolve: {
    extensions: ['', '.js', '.jsx'],
  },

  postcss: function postcssInit() {
    return [
      require('postcss-cssnext'),
    ];
  },
};
<|endoftext|>


<commit_before>const
    custom_config = require('./webpack/config'),
    config        = custom_config || {},
    indexJSFile   = require('./webpack/index')(config),
    _v            = config.vars;

config.devtool = null;

config.entry = [
  // 'webpack-hot-middleware/client', //handled in NODE_ENV switch statement below
  './src/js/app.js',
];

config.output = {
  path: __dirname + "/app",
  filename: 'bundle.js',
  publicPath: '/'
};

config.resolve = {
  extensions: ['', '.js', '.jsx'],
  alias: {
    request: 'browser-request'
  }
};

config.module = {

  preLoaders: [
    {
      test: /\.jsx$|\.js$/,
      loaders: [ 'eslint' ],
      include: _v.path.join(__dirname, 'src'),
      exclude: /(node_modules|vendor|bower_components)/
    }
  ],
  loaders: [
    // Javascript
    {
      test: /\.jsx$|\.js$/,
      include: _v.path.join(__dirname, 'src'),
      loaders: ['react-hot','babel'],
    },

      //TEMPLATE (PUG)
    {
      test: /\.pug$/,
      exclude: /(node_modules|bower_components)/,
      loader: "pug-loader"
    },

      //FILES
    {
      test: /\.(jpg|jpeg|png|gif|tif|svg|woff|woff2|eot|ttf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      loader: 'url'
    }

  ],
  postLoaders: [
      { //delays coverage til after tests are run, fixing transpiled source coverage error
        test: /\.js$/,
        exclude: /(tests|node_modules|bower_components)\//,
        loader: 'istanbul-instrumenter'
      }
  ]
};

config.postcss = [ _v.autoprefixer({ browsers: ['last 2 versions'] }) ];

//*****************************************************************
//*****************************PLUGINS*****************************
//*****************************************************************

let plugins = [
  new _v.webpack.EnvironmentPlugin([
    "NODE_ENV"
  ]),
  new _v.ProgressBarPlugin({
    format: 'webpack [:bar] ' + _v.chalk.green.bold(':percent') + ' (:elapsed seconds)',
    clear: true
  }),
  new _v.HtmlWebpackPlugin(indexJSFile),
  new _v.Visualizer({
    filename: './stats.html'
  })
];

console.log('_v.NODE_ENV: ', _v.NODE_ENV);

switch (_v.NODE_ENV) {
  case "production": {
    config.devtool  = null;

    config.entry = {
      riko: './src/js/app.js',
    };

    config.module.loaders.push({
          test: /\.scss$/,
          loader: _v.ExtractTextPlugin.extract(
              "style",
              "css!postcss!sass"),
        },
        // CSS
        {
          test: /\.css$/,
          include: _v.path.join(__dirname, 'src'),
          loader: _v.ExtractTextPlugin.extract("style", "css!postcss")
        }
    );

    plugins = plugins.concat([
      new _v.webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new _v.webpack.optimize.DedupePlugin(),
      new _v.webpack.optimize.OccurenceOrderPlugin(),
      new _v.webpack.optimize.UglifyJsPlugin({mangle: false, sourcemap: false, compress: {warnings: false} }),
      new _v.webpack.optimize.CommonsChunkPlugin(config.moduleName, config.js_main_name),
      new _v.ExtractTextPlugin("styles.min.css", {allChunks: true})
    ]);
    break;
  }
  case "development": {
    //update entry
    config.entry.unshift('webpack-hot-middleware/client');

    config.devtool = '#eval-source-map';

    config.eslint = {
      failOnError: false,
      failOnWarning: false
    };

    config.debug = true;

    config.module.loaders.push(
        // SASS
        {
          test: /\.scss$/,
          loaders: [
            'style',
            'css-loader?sourceMap',
            "postcss",
            "sass?sourceMap",
          ],
        },

        // CSS
        {
          test: /\.css$/,
          include: _v.path.join(__dirname, 'src'),
          loaders: ["style", "css?sourceMap!postcss"],

        });

    plugins = plugins.concat([
      new _v.webpack.optimize.OccurenceOrderPlugin(),
      new _v.webpack.HotModuleReplacementPlugin(),
      new _v.BrowserSyncPlugin(
          {
            proxy: 'http://localhost:' + config.EXPRESS_PORT,
          },
          {
            reload: false //Allows hot module reloading to take care of this. (preserves state)
          }),
      new _v.StyleLintPlugin({
        configFile: '.stylelintrc.yaml',
        files: ['**/*.s?(a|c)ss','!node_modules/'],
        failOnError: false,
      })
    ]);
    break;
  }
  default: {
    break;
  }
}

config.plugins = plugins;

module.exports = config;<commit_msg>clean up<commit_after>const
    custom_config = require('./webpack/config'),
    config        = custom_config || {},
    indexJSFile   = require('./webpack/index')(config),
    _v            = config.vars;

config.devtool = null;

config.entry = [
  // 'webpack-hot-middleware/client', //handled in NODE_ENV switch statement below
  './src/js/app.js',
];

config.output = {
  path: __dirname + "/app",
  filename: 'bundle.js',
  publicPath: '/'
};

config.resolve = {
  extensions: ['', '.js', '.jsx'],
  alias: {
    request: 'browser-request'
  }
};

config.module = {

  preLoaders: [
    {
      test: /\.jsx$|\.js$/,
      loaders: [ 'eslint' ],
      include: _v.path.join(__dirname, 'src'),
      exclude: /(node_modules|vendor|bower_components)/
    }
  ],
  loaders: [
    // Javascript
    {
      test: /\.jsx$|\.js$/,
      include: _v.path.join(__dirname, 'src'),
      loaders: ['react-hot','babel'],
    },

      //TEMPLATE (PUG)
    {
      test: /\.pug$/,
      exclude: /(node_modules|bower_components)/,
      loader: "pug-loader"
    },

      //FILES
    {
      test: /\.(jpg|jpeg|png|gif|tif|svg|woff|woff2|eot|ttf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      loader: 'url'
    }

  ],
  postLoaders: [
      { //delays coverage til after tests are run, fixing transpiled source coverage error
        test: /\.js$/,
        exclude: /(tests|node_modules|bower_components)\//,
        loader: 'istanbul-instrumenter'
      }
  ]
};

config.postcss = [ _v.autoprefixer({ browsers: ['last 2 versions'] }) ];

//*****************************************************************
//*****************************PLUGINS*****************************
//*****************************************************************

let plugins = [
  new _v.webpack.EnvironmentPlugin([
    "NODE_ENV"
  ]),
  new _v.ProgressBarPlugin({
    format: 'webpack [:bar] ' + _v.chalk.green.bold(':percent') + ' (:elapsed seconds)',
    clear: true
  }),
  new _v.HtmlWebpackPlugin(indexJSFile),
  new _v.Visualizer({
    filename: './stats.html'
  })
];

console.log('_v.NODE_ENV: ', _v.NODE_ENV);

switch (_v.NODE_ENV) {
  case "production": {
    config.devtool  = null;

    config.entry = {
      riko: './src/js/app.js',
    };

    config.module.loaders.push({
          test: /\.scss$/,
          loader: _v.ExtractTextPlugin.extract("style", "css!postcss!sass"),
        },
        // CSS
        {
          test: /\.css$/,
          include: _v.path.join(__dirname, 'src'),
          loader: _v.ExtractTextPlugin.extract("style", "css!postcss")
        }
    );

    plugins = plugins.concat([
      new _v.webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new _v.webpack.optimize.DedupePlugin(),
      new _v.webpack.optimize.OccurenceOrderPlugin(),
      new _v.webpack.optimize.UglifyJsPlugin({mangle: false, sourcemap: false, compress: {warnings: false} }),
      new _v.webpack.optimize.CommonsChunkPlugin(config.moduleName, config.js_main_name),
      new _v.ExtractTextPlugin("styles.min.css", {allChunks: true})
    ]);
    break;
  }
  case "development": {
    //update entry
    config.entry.unshift('webpack-hot-middleware/client');

    config.devtool = '#eval-source-map';

    config.eslint = {
      failOnError: false,
      failOnWarning: false
    };

    config.debug = true;

    config.module.loaders.push(
        // SASS
        {
          test: /\.scss$/,
          loaders: ['style', 'css-loader?sourceMap', "postcss", "sass?sourceMap",],
        },

        // CSS
        {
          test: /\.css$/,
          include: _v.path.join(__dirname, 'src'),
          loaders: ["style", "css?sourceMap!postcss"],

        });

    plugins = plugins.concat([
      new _v.webpack.optimize.OccurenceOrderPlugin(),
      new _v.webpack.HotModuleReplacementPlugin(),
      new _v.BrowserSyncPlugin(
          {
            proxy: 'http://localhost:' + config.EXPRESS_PORT,
          },
          {
            reload: false //Allows hot module reloading to take care of this. (preserves state)
          }),
      new _v.StyleLintPlugin({
        configFile: '.stylelintrc.yaml',
        files: ['**/*.s?(a|c)ss','!node_modules/'],
        failOnError: false,
      })
    ]);
    break;
  }
  default: {
    break;
  }
}

config.plugins = plugins;

module.exports = config;<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var autoprefixer = require('autoprefixer');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTestWatch = ENV === 'test-watch';
var isTest = ENV === 'test' || isTestWatch;
// var isProd = ENV === 'build'; not using it right now //

module.exports = function makeWebpackConfig() {

	var config = {};

	config.devtool = isTest ? 'inline-source-map' : 'eval-source-map';

	if (!isTest) {
		config.entry = isTest ? {} : {
			'polyfills': './src/polyfills.ts',
			'vendor': './src/vendor.ts',
			'app': './src/main.ts'
		};
	}

	config.output = isTest ? {} : {
		path: root('dist'),
		publicPath: 'http://localhost:8080/',
		filename: 'js/[name].js',
		chunkFilename: '[id].chunk.js'
	};

	config.resolve = {
		extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html']
	};

	var atlOptions = '';

	if (isTest && !isTestWatch) {
		// awesome-typescript-loader needs to output inlineSourceMap for code coverage to work with source maps.
		atlOptions = 'inlineSourceMap=true&sourceMap=false';
	}

	config.module = {
		rules: [
			{
				test: /\.ts$/,
				loaders: ['awesome-typescript-loader?' + atlOptions, 'angular2-template-loader'],
				exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
			},
			{
				test: /\.ts$/,
				enforce: 'pre',
				loader: 'tslint-loader'
			},
			{
				test: /\.(png|jpe?g|gif|svg|otf|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
				loader: 'file-loader?name=fonts/[name].[hash].[ext]?'
			},
			{
				test: /\.(png|jpe?g|gif|svg)$/,
				loader: 'file-loader?name=img/[name].[hash].[ext]?'
			},
			{
				test: /app\.module\.scss$/,
				loader: ExtractTextPlugin.extract({
					use: ['css-loader', 'postcss-loader', 'sass-loader']
				})
			},
			{
				test: /\.html$/,
				use: 'raw-loader',
				exclude: [root('src/index.html')]
			},
			{
				test: /\.json$/, loader: 'json-loader'
			}
		]
	};

	if (!isTest || !isTestWatch) {
		// tslint support
		config.module.rules.push({
			test: /\.ts$/,
			enforce: 'pre',
			loader: 'tslint-loader'
		});
	}

	config.plugins = [
		new webpack.DefinePlugin({
			'process.env': { ENV: JSON.stringify(ENV) }
		}),
		new webpack.ContextReplacementPlugin(
			/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
			root('./src')
		),
		new webpack.LoaderOptionsPlugin({
			tslint: {
				emitErrors: false,
				failOnHint: false
			}
		})
	];

	if (!isTest) {
		config.plugins.push(
			new webpack.optimize.CommonsChunkPlugin({
				name: ['vendor', 'polyfills']
			}),
			new HtmlWebpackPlugin({
				template: 'src/index.html',
				chunksSortMode: 'dependency'
			}),
			new ExtractTextPlugin({ filename: 'css/[name].[hash].css' })
		);
	}

	config.devServer = {
		historyApiFallback: true,
		quiet: true,
		stats: 'minimal', // none (or false), errors-only, minimal, normal (or true) and verbose
		proxy: {
			"/api": {
				target: "http://localhost:3000", // to be changed by the good api url
				pathRewrite: {"^/api" : ""}
			}
		}
	};

	return config;
}();

// Helper functions
function root(args) {
	args = Array.prototype.slice.call(arguments, 0);
	return path.join.apply(path, [__dirname].concat(args));
}<commit_msg>webpack: Change config for sass files<commit_after>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var autoprefixer = require('autoprefixer');

const extractCSS = new ExtractTextPlugin({ filename: 'css/[name].[hash].css' });

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTestWatch = ENV === 'test-watch';
var isTest = ENV === 'test' || isTestWatch;
// var isProd = ENV === 'build'; not using it right now //

module.exports = function makeWebpackConfig() {

	var config = {};

	config.devtool = isTest ? 'inline-source-map' : 'eval-source-map';

	if (!isTest) {
		config.entry = isTest ? {} : {
			'polyfills': './src/polyfills.ts',
			'vendor': './src/vendor.ts',
			'app': './src/main.ts'
		};
	}

	config.output = isTest ? {} : {
		path: root('dist'),
		publicPath: 'http://localhost:8080/',
		filename: 'js/[name].js',
		chunkFilename: '[id].chunk.js'
	};

	config.resolve = {
		extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html']
	};

	var atlOptions = '';

	if (isTest && !isTestWatch) {
		// awesome-typescript-loader needs to output inlineSourceMap for code coverage to work with source maps.
		atlOptions = 'inlineSourceMap=true&sourceMap=false';
	}

	config.module = {
		rules: [
			{
				test: /\.ts$/,
				loaders: ['awesome-typescript-loader?' + atlOptions, 'angular2-template-loader'],
				exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
			},
			{
				test: /\.ts$/,
				enforce: 'pre',
				loader: 'tslint-loader'
			},
			{
				test: /\.(png|jpe?g|gif|svg|otf|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
				loader: 'file-loader?name=fonts/[name].[hash].[ext]?'
			},
			{
				test: /\.(png|jpe?g|gif|svg)$/,
				loader: 'file-loader?name=img/[name].[hash].[ext]?'
			},
			{
				test: /app\.module\.scss$/,
				loader: extractCSS.extract({
					fallback: 'style-loader',
					use: ['css-loader', 'postcss-loader', 'sass-loader']
				})
			},
			{
				test: /\.(scss|sass)$/,
				exclude: /app\.module\.scss$/,
				loader: 'raw-loader!postcss-loader!sass-loader'
			},
			{
				test: /\.html$/,
				use: 'raw-loader',
				exclude: [root('src/index.html')]
			},
			{
				test: /\.json$/, loader: 'json-loader'
			}
		]
	};

	if (!isTest || !isTestWatch) {
		// tslint support
		config.module.rules.push({
			test: /\.ts$/,
			enforce: 'pre',
			loader: 'tslint-loader'
		});
	}

	config.plugins = [
		new webpack.DefinePlugin({
			'process.env': { ENV: JSON.stringify(ENV) }
		}),
		new webpack.ContextReplacementPlugin(
			/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
			root('./src')
		),
		new webpack.LoaderOptionsPlugin({
			tslint: {
				emitErrors: false,
				failOnHint: false
			}
		})
	];

	if (!isTest) {
		config.plugins.push(
			new webpack.optimize.CommonsChunkPlugin({
				name: ['vendor', 'polyfills']
			}),
			new HtmlWebpackPlugin({
				template: 'src/index.html',
				chunksSortMode: 'dependency'
			}),
			extractCSS
		);
	}

	config.devServer = {
		historyApiFallback: true,
		quiet: true,
		stats: 'minimal', // none (or false), errors-only, minimal, normal (or true) and verbose
		proxy: {
			"/api": {
				target: "http://localhost:3000", // to be changed by the good api url
				pathRewrite: {"^/api" : ""}
			}
		}
	};

	return config;
}();

// Helper functions
function root(args) {
	args = Array.prototype.slice.call(arguments, 0);
	return path.join.apply(path, [__dirname].concat(args));
}<|endoftext|>