<commit_before>var chai = require('chai')
  , sinon = require('sinon')
  , sinonChai = require('sinon-chai')
  , expect = chai.expect;

chai.use(sinonChai);

var ElmCompiler = require('../index')
  , execSync;

describe('ElmCompiler', function (){
  var elmCompiler, baseConfig = {
        paths: {
          public: 'test/public/folder'
        },
        plugins: {
          elmBrunch: {}
        }
      };

  describe('plugin', function () {
    beforeEach(function () {
      elmCompiler = new ElmCompiler(baseConfig);
    });

    it('is an object', function () {
      expect(elmCompiler).to.be.ok;
    });

    it('has a #compile method', function () {
      expect(elmCompiler.compile).to.be.an.instanceof(Function);
    });
  });

  describe('elm config', function () {
    describe('outputFolder', function () {
      describe('when an outputFolder is not specified', function () {
        beforeEach(function () {
          elmCompiler = new ElmCompiler(baseConfig);
        });

        it('defaults to the public js folder', function () {
          expect(elmCompiler.elm_config.outputFolder).to.equal('test/public/folder/js');
        });
      });

      describe('when an outputFolder is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.outputFolder = 'test/output/folder'
          elmCompiler = new ElmCompiler(config);
        });

        it('uses the specified outputFolder', function () {
          expect(elmCompiler.elm_config.outputFolder).to.equal('test/output/folder');
        });
      });
    });

    describe('mainModules', function () {
      describe('when no mainModules are specified', function () {
        beforeEach(function () {
          elmCompiler = new ElmCompiler(baseConfig);
        });

        it('is undefined', function () {
          expect(elmCompiler.elm_config.mainModules).to.be.undefined;
        });
      });

      describe('when one mainModule is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.mainModules = ['Test.elm']
          elmCompiler = new ElmCompiler(config);
        });

        it('provides the specified mainModule', function () {
          expect(elmCompiler.elm_config.mainModules.length).to.equal(1);
          expect(elmCompiler.elm_config.mainModules).to.include('Test.elm');
        });
      });

      describe('when more than one mainModule is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.mainModules = ['Test1.elm', 'Test2.elm']
          elmCompiler = new ElmCompiler(config);
        });

        it('provides the specified mainModule', function () {
          expect(elmCompiler.elm_config.mainModules.length).to.equal(2);
          expect(elmCompiler.elm_config.mainModules).to.include('Test1.elm');
          expect(elmCompiler.elm_config.mainModules).to.include('Test2.elm');
        });
      });
    });

    describe('elmFolder', function () {
      describe('when an elmFolder is not specified', function () {
        beforeEach(function () {
          elmCompiler = new ElmCompiler(baseConfig);
        });

        it('defaults to null', function () {
          expect(elmCompiler.elm_config.elmFolder).to.be.null;
        });
      });

      describe('when an elmFolder is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.elmFolder = 'test/elm/folder'
          elmCompiler = new ElmCompiler(config);
        });

        it('uses the specified elmFolder', function () {
          expect(elmCompiler.elm_config.elmFolder).to.equal('test/elm/folder');
        });
      });
      describe('when an elmFolder has Windows syntax', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.elmFolder = 'test\\elm\\folder'
          elmCompiler = new ElmCompiler(config);
        });

        it('uses the specified elmFolder', function () {
          expect(elmCompiler.elm_config.elmFolder).to.equal('test\\elm\\folder');
        });
      });
    });

    describe('makeParameters', function () {
      describe('when no makeParameters are not specified', function () {
        beforeEach(function () {
          elmCompiler = new ElmCompiler(baseConfig);
        });

        it('defaults to an empty list', function () {
          expect(elmCompiler.elm_config.makeParameters).to.be.empty;
        });
      });

      describe('when some makeParameters are specified', function () {
        var makeParameters = ['--warn'];
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.makeParameters = makeParameters;
          elmCompiler = new ElmCompiler(config);
        });

        it('uses the specified makeParameters', function () {
          expect(elmCompiler.elm_config.makeParameters).to.equal(makeParameters);
        });
      });
    });
  });

  describe('compiling Elm', function () {
    var childProcess = require('child_process')
      , sampleConfig;

    beforeEach(function () {
      execSync = sinon.stub(childProcess, 'execSync');

      sampleConfig = JSON.parse(JSON.stringify(baseConfig));
      sampleConfig.plugins.elmBrunch.outputFolder = 'test/output/folder';
      sampleConfig.plugins.elmBrunch.mainModules = ['Test.elm'];
    });

    afterEach(function () {
      execSync.restore();
    });

    describe('when an elm folder has not been given', function () {
      beforeEach(function () {
        config = JSON.parse(JSON.stringify(sampleConfig));
        elmCompiler = new ElmCompiler(config);
      });

      it('shells out to the `elm make` command with a null cwd', function () {
        var content = '';
        elmCompiler.compile(content, 'File.elm', function(error, data) {
          expect(error).to.not.be.ok;
          expect(data).to.equal('');
        });
        elmCompiler.compile(content, 'File.elm', function(error) {
          expect(error).to.not.be.ok;
        });
        expected = 'elm make --yes --output test/output/folder/test.js Test.elm';
        expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: null});
      });
    });

    describe('when an elm folder has been given', function () {
      beforeEach(function () {
        config = JSON.parse(JSON.stringify(sampleConfig));
        config.plugins.elmBrunch.elmFolder = 'test/elm/folder';
        elmCompiler = new ElmCompiler(config);
      });

      it('shells out to the `elm make` command with the specified elm folder as the cwd', function () {
        var content = '';
        elmCompiler.compile(content, 'File.elm', function(error) {
          expect(error).to.not.be.ok;
        });
        elmCompiler.compile(content, 'File.elm', function(error) {
          expect(error).to.not.be.ok;
        });
        expected = 'elm make --yes --output test/output/folder/test.js Test.elm';
        expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: 'test/elm/folder'});
      });

      it('normalises the brunch file path to the elmFolder path', function () {
        var content = '';
        elmCompiler.compile(content, 'test/elm/folder/Test.elm', function(error) {
          expect(error).to.not.be.ok;
        });
        expected = 'elm make --yes --output test/output/folder/test.js Test.elm';
        expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: 'test/elm/folder'});
      });

    });

    describe('the initial run', function () {
      describe('when main module is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(sampleConfig));
          elmCompiler = new ElmCompiler(config);
        });

        it('should skip non main modules', function () {
          var content = '';
          elmCompiler.compile(content, 'File.elm', function(error, data) {
            expect(error).to.not.be.ok;
            expect(data).to.equal('');
          });
          expected = '';
          expect(childProcess.execSync).to.not.have.been.called;
        });

        it('should compile main modules', function () {
          var content = '';
          elmCompiler.compile(content, 'Test.elm', function(error) {
            expect(error).to.not.be.ok;
          });
          expected = 'elm make --yes --output test/output/folder/test.js Test.elm';
          expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: null});
        });
      });

      describe('when no main module is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(sampleConfig));
          delete config.plugins.elmBrunch.mainModules;
          elmCompiler = new ElmCompiler(config);
        });

        it('should compile all modules', function () {
          var content = '';
          elmCompiler.compile(content, 'Test.elm', function(error) {
            expect(error).to.not.be.ok;
          });
          expected = 'elm make --yes --output test/output/folder/test.js Test.elm';
          expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: null});
        });
      });

      describe('when more than one mainModule is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.outputFolder = 'test/output/folder';
          config.plugins.elmBrunch.mainModules = ['Test1.elm', 'Test2.elm'];
          config.plugins.elmBrunch.outputFile = 'test.js';
          elmCompiler = new ElmCompiler(config);
        });
        it('should compile all modules into a single file', function () {
          var content = '';
          elmCompiler.compile(content, 'Test1.elm', function(error) {
            expect(error).to.not.be.ok;
          });
          expected = 'elm make --yes --output test/output/folder/test.js Test1.elm Test2.elm';
          expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: null});
        });
      });
    });
  });
});
<commit_msg>fix tests for #24 - really have to get the travis build setup<commit_after>var chai = require('chai')
  , sinon = require('sinon')
  , sinonChai = require('sinon-chai')
  , expect = chai.expect;

chai.use(sinonChai);

var ElmCompiler = require('../index')
  , execSync;

describe('ElmCompiler', function (){
  var elmCompiler, baseConfig = {
        paths: {
          public: 'test/public/folder'
        },
        plugins: {
          elmBrunch: {}
        }
      };

  describe('plugin', function () {
    beforeEach(function () {
      elmCompiler = new ElmCompiler(baseConfig);
    });

    it('is an object', function () {
      expect(elmCompiler).to.be.ok;
    });

    it('has a #compile method', function () {
      expect(elmCompiler.compile).to.be.an.instanceof(Function);
    });
  });

  describe('elm config', function () {
    describe('outputFolder', function () {
      describe('when an outputFolder is not specified', function () {
        beforeEach(function () {
          elmCompiler = new ElmCompiler(baseConfig);
        });

        it('defaults to the public js folder', function () {
          expect(elmCompiler.elm_config.outputFolder).to.equal('test/public/folder/js');
        });
      });

      describe('when an outputFolder is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.outputFolder = 'test/output/folder'
          elmCompiler = new ElmCompiler(config);
        });

        it('uses the specified outputFolder', function () {
          expect(elmCompiler.elm_config.outputFolder).to.equal('test/output/folder');
        });
      });
    });

    describe('mainModules', function () {
      describe('when no mainModules are specified', function () {
        beforeEach(function () {
          elmCompiler = new ElmCompiler(baseConfig);
        });

        it('is undefined', function () {
          expect(elmCompiler.elm_config.mainModules).to.be.undefined;
        });
      });

      describe('when one mainModule is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.mainModules = ['Test.elm']
          elmCompiler = new ElmCompiler(config);
        });

        it('provides the specified mainModule', function () {
          expect(elmCompiler.elm_config.mainModules.length).to.equal(1);
          expect(elmCompiler.elm_config.mainModules).to.include('Test.elm');
        });
      });

      describe('when more than one mainModule is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.mainModules = ['Test1.elm', 'Test2.elm']
          elmCompiler = new ElmCompiler(config);
        });

        it('provides the specified mainModule', function () {
          expect(elmCompiler.elm_config.mainModules.length).to.equal(2);
          expect(elmCompiler.elm_config.mainModules).to.include('Test1.elm');
          expect(elmCompiler.elm_config.mainModules).to.include('Test2.elm');
        });
      });
    });

    describe('elmFolder', function () {
      describe('when an elmFolder is not specified', function () {
        beforeEach(function () {
          elmCompiler = new ElmCompiler(baseConfig);
        });

        it('defaults to null', function () {
          expect(elmCompiler.elm_config.elmFolder).to.be.null;
        });
      });

      describe('when an elmFolder is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.elmFolder = 'test/elm/folder'
          elmCompiler = new ElmCompiler(config);
        });

        it('uses the specified elmFolder', function () {
          expect(elmCompiler.elm_config.elmFolder).to.equal('test/elm/folder');
        });
      });
      describe('when an elmFolder has Windows syntax', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.elmFolder = 'test\\elm\\folder'
          elmCompiler = new ElmCompiler(config);
        });

        it('uses the specified elmFolder', function () {
          expect(elmCompiler.elm_config.elmFolder).to.equal('test\\elm\\folder');
        });
      });
    });

    describe('makeParameters', function () {
      describe('when no makeParameters are not specified', function () {
        beforeEach(function () {
          elmCompiler = new ElmCompiler(baseConfig);
        });

        it('defaults to an empty list', function () {
          expect(elmCompiler.elm_config.makeParameters).to.be.empty;
        });
      });

      describe('when some makeParameters are specified', function () {
        var makeParameters = ['--warn'];
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.makeParameters = makeParameters;
          elmCompiler = new ElmCompiler(config);
        });

        it('uses the specified makeParameters', function () {
          expect(elmCompiler.elm_config.makeParameters).to.equal(makeParameters);
        });
      });
    });
  });

  describe('compiling Elm', function () {
    var childProcess = require('child_process')
      , sampleConfig;

    beforeEach(function () {
      execSync = sinon.stub(childProcess, 'execSync');

      sampleConfig = JSON.parse(JSON.stringify(baseConfig));
      sampleConfig.plugins.elmBrunch.outputFolder = 'test/output/folder';
      sampleConfig.plugins.elmBrunch.mainModules = ['Test.elm'];
    });

    afterEach(function () {
      execSync.restore();
    });

    describe('when an elm folder has not been given', function () {
      beforeEach(function () {
        config = JSON.parse(JSON.stringify(sampleConfig));
        elmCompiler = new ElmCompiler(config);
      });

      it('shells out to the `elm-make` command with a null cwd', function () {
        var content = '';
        elmCompiler.compile(content, 'File.elm', function(error, data) {
          expect(error).to.not.be.ok;
          expect(data).to.equal('');
        });
        elmCompiler.compile(content, 'File.elm', function(error) {
          expect(error).to.not.be.ok;
        });
        expected = 'elm-make --yes --output test/output/folder/test.js Test.elm';
        expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: null});
      });
    });

    describe('when an elm folder has been given', function () {
      beforeEach(function () {
        config = JSON.parse(JSON.stringify(sampleConfig));
        config.plugins.elmBrunch.elmFolder = 'test/elm/folder';
        elmCompiler = new ElmCompiler(config);
      });

      it('shells out to the `elm-make` command with the specified elm folder as the cwd', function () {
        var content = '';
        elmCompiler.compile(content, 'File.elm', function(error) {
          expect(error).to.not.be.ok;
        });
        elmCompiler.compile(content, 'File.elm', function(error) {
          expect(error).to.not.be.ok;
        });
        expected = 'elm-make --yes --output test/output/folder/test.js Test.elm';
        expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: 'test/elm/folder'});
      });

      it('normalises the brunch file path to the elmFolder path', function () {
        var content = '';
        elmCompiler.compile(content, 'test/elm/folder/Test.elm', function(error) {
          expect(error).to.not.be.ok;
        });
        expected = 'elm-make --yes --output test/output/folder/test.js Test.elm';
        expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: 'test/elm/folder'});
      });

    });

    describe('the initial run', function () {
      describe('when main module is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(sampleConfig));
          elmCompiler = new ElmCompiler(config);
        });

        it('should skip non main modules', function () {
          var content = '';
          elmCompiler.compile(content, 'File.elm', function(error, data) {
            expect(error).to.not.be.ok;
            expect(data).to.equal('');
          });
          expected = '';
          expect(childProcess.execSync).to.not.have.been.called;
        });

        it('should compile main modules', function () {
          var content = '';
          elmCompiler.compile(content, 'Test.elm', function(error) {
            expect(error).to.not.be.ok;
          });
          expected = 'elm-make --yes --output test/output/folder/test.js Test.elm';
          expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: null});
        });
      });

      describe('when no main module is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(sampleConfig));
          delete config.plugins.elmBrunch.mainModules;
          elmCompiler = new ElmCompiler(config);
        });

        it('should compile all modules', function () {
          var content = '';
          elmCompiler.compile(content, 'Test.elm', function(error) {
            expect(error).to.not.be.ok;
          });
          expected = 'elm-make --yes --output test/output/folder/test.js Test.elm';
          expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: null});
        });
      });

      describe('when more than one mainModule is specified', function () {
        beforeEach(function () {
          config = JSON.parse(JSON.stringify(baseConfig));
          config.plugins.elmBrunch.outputFolder = 'test/output/folder';
          config.plugins.elmBrunch.mainModules = ['Test1.elm', 'Test2.elm'];
          config.plugins.elmBrunch.outputFile = 'test.js';
          elmCompiler = new ElmCompiler(config);
        });
        it('should compile all modules into a single file', function () {
          var content = '';
          elmCompiler.compile(content, 'Test1.elm', function(error) {
            expect(error).to.not.be.ok;
          });
          expected = 'elm-make --yes --output test/output/folder/test.js Test1.elm Test2.elm';
          expect(childProcess.execSync).to.have.been.calledWith(expected, {cwd: null});
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>const bin = require('../bin');
const pkg = bin.common.res('package');
const webpack = bin({ run: 'test' });

/*!
|* This is a karma config file. For more details
|* @see https://www.browserstack.com/screenshots
|* @see https://www.browserstack.com/list-of-browsers-and-platforms?product=automate
|* @see https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md
|* @see http://karma-runner.github.io/0.13/config/configuration-file.html
|* @see http://karma-runner.github.io/0.13/config/browsers.html
|* @see https://github.com/webpack/karma-webpack
`*/
module.exports = (config) => {
	const customLaunchers = {
		bs_mobile_chrome: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '9.3',
			browser: 'chrome',
			browser_version: '5.5.372',
			real_mobile: false,
		},
		bs_mobile_safari_8: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '8.3',
			browser: 'iphone',
			real_mobile: false,
		},
		bs_mobile_safari_9: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '9.1',
			browser: 'iphone',
			real_mobile: false,
		},
		bs_win_chrome: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'chrome',
			browser_version: '47.0',
			flags: ['--no-sandbox'],
		},
		bs_win_firefox: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'firefox',
			browser_version: '43.0',
		},
		bs_win_ie9: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: 'XP',
			browser: 'ie',
			browser_version: '9.0',
		},
		bs_win_ie10: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '8',
			browser: 'ie',
			browser_version: '10.0',
		},
		bs_win_ie11: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'ie',
			browser_version: '11.0',
		},
		bs_mac_chrome: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'chrome',
			browser_version: '47.0',
			flags: ['--no-sandbox'],
		},
		bs_mac_firefox: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'firefox',
			browser_version: '21.0',
		},
		bs_mac_safari: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'safari',
			browser_version: '9.0',
		},
	};

	const settings = {
		webpack,
		customLaunchers,
		logLevel: config.LOG_INFO,
		basePath: '../',
		port: 9876,
		colors: true,
		browsers: ['PhantomJS'],
		frameworks: ['mocha', 'sinon-chai', 'fixture', 'phantomjs-shim'],
		reporters: ['spec', 'coverage'],
		files: [{
			pattern: 'test/fixtures/**/*.fixture.*',
			watched: true,
		}, {
			pattern: 'test/specs/**/*.spec.js',
			watched: true,
		}, {
			pattern: 'source/**/*.js',
			watched: true,
		}],
		preprocessors: {
			'source/**/*.js': ['webpack', 'sourcemap', 'coverage'],
			'test/specs/**/*.spec.js': ['webpack', 'sourcemap'],
			'test/fixtures/**/*.html': ['html2js'],
			'test/fixtures/**/*.json': ['json_fixtures'],
		},
		jsonFixturesPreprocessor: {
			variableName: '__json__',
		},
		webpackServer: {
			noInfo: true,
		},
		browserStack: {
			project: pkg.name,
			username: process.env.BROWSERSTACK_USERNAME,
			accessKey: process.env.BROWSERSTACK_KEY,
			captureTimeout: 120,
			retryLimit: 3,
			timeout: 300,
		},
		client: {
			mocha: {
				reporter: 'html',
			},
		},
		coverageReporter: {
			dir: 'test/coverage',
			reporters: [
				{ type: 'lcovonly', subdir: '.' },
				{ type: 'json', subdir: '.' },
			],
		},
	};

	if (process.env.TRAVIS || process.env.APPVEYOR || process.env.CIRCLECI) {
		settings.browserStack.concurrency = 2;
		settings.browserStack.browserNoActivityTimeout = 240000;
		settings.browserStack.browserDisconnectTimeout = 10000;
		settings.browserStack.browserDisconnectTolerance = 3;
		settings.browserStack.captureTimeout = 240000;
		settings.browserStack.browsers = Object.keys(customLaunchers);
		if (process.env.TRAVIS) {
			settings.browserStack.build = process.env.TRAVIS_BUILD_NUMBER;
			settings.browserStack.name = process.env.TRAVIS_JOB_NUMBER;
		} else if (process.env.APPVEYOR) {
			settings.browserStack.build = process.env.APPVEYOR_BUILD_NUMBER;
			settings.browserStack.name = process.env.APPVEYOR_JOB_NUMBER;
		} else if (process.env.CIRCLECI) {
			settings.browserStack.build = process.env.CIRCLE_BUILD_NUM;
			settings.browserStack.name = process.env.CIRCLE_BUILD_URL;
		}
	}

	config.set(settings);
};
<commit_msg>test: ie8 & edge<commit_after>const bin = require('../bin');
const pkg = bin.common.res('package');
const webpack = bin({ run: 'test' });

/*!
|* This is a karma config file. For more details
|* @see https://www.browserstack.com/screenshots
|* @see https://www.browserstack.com/list-of-browsers-and-platforms?product=automate
|* @see https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md
|* @see http://karma-runner.github.io/0.13/config/configuration-file.html
|* @see http://karma-runner.github.io/0.13/config/browsers.html
|* @see https://github.com/webpack/karma-webpack
`*/
module.exports = (config) => {
	const customLaunchers = {
		bs_mobile_chrome: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '9.3',
			browser: 'chrome',
			browser_version: '5.5.372',
			real_mobile: false,
		},
		bs_mobile_safari_8: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '8.3',
			browser: 'iphone',
			real_mobile: false,
		},
		bs_mobile_safari_9: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '9.1',
			browser: 'iphone',
			real_mobile: false,
		},
		bs_win_chrome: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'chrome',
			browser_version: '47.0',
			flags: ['--no-sandbox'],
		},
		bs_win_firefox: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'firefox',
			browser_version: '43.0',
		},
		bs_win_ie8: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '7',
			browser: 'IE',
			browser_version: '8.0',
		},
		bs_win_ie9: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '7',
			browser: 'IE',
			browser_version: '9.0',
		},
		bs_win_ie10: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '7',
			browser: 'IE',
			browser_version: '10.0',
		},
		bs_win_ie11: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '7',
			browser: 'IE',
			browser_version: '11.0',
		},
		bs_win_edge: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'Edge',
			browser_version: '14.0',
		},
		bs_mac_chrome: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'chrome',
			browser_version: '47.0',
			flags: ['--no-sandbox'],
		},
		bs_mac_firefox: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'firefox',
			browser_version: '21.0',
		},
		bs_mac_safari: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'safari',
			browser_version: '9.0',
		},
	};

	const settings = {
		webpack,
		customLaunchers,
		logLevel: config.LOG_INFO,
		basePath: '../',
		port: 9876,
		colors: true,
		browsers: ['PhantomJS'],
		frameworks: ['mocha', 'sinon-chai', 'fixture', 'phantomjs-shim'],
		reporters: ['spec', 'coverage'],
		files: [{
			pattern: 'test/fixtures/**/*.fixture.*',
			watched: true,
		}, {
			pattern: 'test/specs/**/*.spec.js',
			watched: true,
		}, {
			pattern: 'source/**/*.js',
			watched: true,
		}],
		preprocessors: {
			'source/**/*.js': ['webpack', 'sourcemap', 'coverage'],
			'test/specs/**/*.spec.js': ['webpack', 'sourcemap'],
			'test/fixtures/**/*.html': ['html2js'],
			'test/fixtures/**/*.json': ['json_fixtures'],
		},
		jsonFixturesPreprocessor: {
			variableName: '__json__',
		},
		webpackServer: {
			noInfo: true,
		},
		browserStack: {
			project: pkg.name,
			username: process.env.BROWSERSTACK_USERNAME,
			accessKey: process.env.BROWSERSTACK_KEY,
			captureTimeout: 120,
			retryLimit: 3,
			timeout: 300,
		},
		client: {
			mocha: {
				reporter: 'html',
			},
		},
		coverageReporter: {
			dir: 'test/coverage',
			reporters: [
				{ type: 'lcovonly', subdir: '.' },
				{ type: 'json', subdir: '.' },
			],
		},
	};

	if (process.env.TRAVIS || process.env.APPVEYOR || process.env.CIRCLECI) {
		settings.browserStack.concurrency = 2;
		settings.browserStack.browserNoActivityTimeout = 240000;
		settings.browserStack.browserDisconnectTimeout = 10000;
		settings.browserStack.browserDisconnectTolerance = 3;
		settings.browserStack.captureTimeout = 240000;
		settings.browserStack.browsers = Object.keys(customLaunchers);
		if (process.env.TRAVIS) {
			settings.browserStack.build = process.env.TRAVIS_BUILD_NUMBER;
			settings.browserStack.name = process.env.TRAVIS_JOB_NUMBER;
		} else if (process.env.APPVEYOR) {
			settings.browserStack.build = process.env.APPVEYOR_BUILD_NUMBER;
			settings.browserStack.name = process.env.APPVEYOR_JOB_NUMBER;
		} else if (process.env.CIRCLECI) {
			settings.browserStack.build = process.env.CIRCLE_BUILD_NUM;
			settings.browserStack.name = process.env.CIRCLE_BUILD_URL;
		}
	}

	config.set(settings);
};
<|endoftext|>


<commit_before>module.exports = function(config) {
  'use strict';

  config.set({

    basePath: '../',

    files: [
      'app/bower_components/jquery/dist/jquery.js',
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-animate/angular-animate.js',
      'app/bower_components/angular-cookie/angular-cookie.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/bower_components/angular-sanitize/angular-sanitize.js',
      'app/bower_components/angular-touch/angular-touch.js',
      'app/bower_components/ng-table/dist/ng-table.min.js',
      'app/bower_components/angular-cookies/angular-cookies.js',
      'app/bower_components/angular-base64/angular-base64.js',
      'app/bower_components/ng-table-export/ng-table-export.js',
      'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'app/bower_components/bootstrap/dist/js/bootstrap.js',
      'app/bower_components/bootstrap-switch/dist/js/bootstrap-switch.js',
      'app/bower_components/angular-bootstrap-switch/dist/angular-bootstrap-switch.js',
      'app/bower_components/angular-gettext/dist/angular-gettext.js',
      'app/bower_components/angular-filter/dist/angular-filter.js',
      'app/bower_components/angular-file-saver/dist/angular-file-saver.bundle.js',
      'app/bower_components/bootstrap-ui-datetime-picker/dist/datetime-picker.js',
      'app/bower_components/angular-color-picker/angularjs-color-picker.js',
      'app/bower_components/angular-hamburger-toggle/dist/angular-hamburger-toggle.js',
      'app/bower_components/angular-moment/angular-moment.js',
      'app/bower_components/ng-file-upload/ng-file-upload.js',
      'app/bower_components/ng-lodash/build/ng-lodash.js',
      'app/bower_components/ng-password-strength/dist/scripts/ng-password-strength.js',
      'app/bower_components/angular-messages/angular-messages.js',
      'app/bower_components/angular-sortable-view/src/angular-sortable-view.js',
      'app/bower_components/openolitor-core/dist/scripts/openolitor-core.js',
      'app/scripts/app.js',
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js',
      'app/scripts/**/*.html'
    ],

    preprocessors: {
      'app/scripts/**/*.html': ['ng-html2js']
    },

    ngHtml2JsPreprocessor: {
      stripPrefix: 'app/',
      moduleName: 'templates'
    },

    autoWatch: true,

    frameworks: ['jasmine'],

    browsers: ['PhantomJS'],

    colors: true,

    singleRun: true
  });
};
<commit_msg>angular-css-injector zu karma.conf hinzugefügt. Fix Travis<commit_after>module.exports = function(config) {
  'use strict';

  config.set({

    basePath: '../',

    files: [
      'app/bower_components/jquery/dist/jquery.js',
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-animate/angular-animate.js',
      'app/bower_components/angular-cookie/angular-cookie.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/bower_components/angular-sanitize/angular-sanitize.js',
      'app/bower_components/angular-touch/angular-touch.js',
      'app/bower_components/ng-table/dist/ng-table.min.js',
      'app/bower_components/angular-cookies/angular-cookies.js',
      'app/bower_components/angular-base64/angular-base64.js',
      'app/bower_components/ng-table-export/ng-table-export.js',
      'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'app/bower_components/bootstrap/dist/js/bootstrap.js',
      'app/bower_components/bootstrap-switch/dist/js/bootstrap-switch.js',
      'app/bower_components/angular-bootstrap-switch/dist/angular-bootstrap-switch.js',
      'app/bower_components/angular-gettext/dist/angular-gettext.js',
      'app/bower_components/angular-filter/dist/angular-filter.js',
      'app/bower_components/angular-file-saver/dist/angular-file-saver.bundle.js',
      'app/bower_components/bootstrap-ui-datetime-picker/dist/datetime-picker.js',
      'app/bower_components/angular-color-picker/angularjs-color-picker.js',
      'app/bower_components/angular-hamburger-toggle/dist/angular-hamburger-toggle.js',
      'app/bower_components/angular-moment/angular-moment.js',
      'app/bower_components/ng-file-upload/ng-file-upload.js',
      'app/bower_components/ng-lodash/build/ng-lodash.js',
      'app/bower_components/ng-password-strength/dist/scripts/ng-password-strength.js',
      'app/bower_components/angular-messages/angular-messages.js',
      'app/bower_components/angular-sortable-view/src/angular-sortable-view.js',
      'app/bower_components/angular-css-injector/angular-css-injector.js',
      'app/bower_components/openolitor-core/dist/scripts/openolitor-core.js',
      'app/scripts/app.js',
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js',
      'app/scripts/**/*.html'
    ],

    preprocessors: {
      'app/scripts/**/*.html': ['ng-html2js']
    },

    ngHtml2JsPreprocessor: {
      stripPrefix: 'app/',
      moduleName: 'templates'
    },

    autoWatch: true,

    frameworks: ['jasmine'],

    browsers: ['PhantomJS'],

    colors: true,

    singleRun: true
  });
};
<|endoftext|>


<commit_before>/*eslint no-var:0, object-shorthand:0 */

var coverage = String(process.env.COVERAGE)!=='false',
	sauceLabs = String(process.env.SAUCELABS).match(/^(1|true)$/gi),
	performance = !coverage && !sauceLabs && String(process.env.PERFORMANCE)!=='false',
	webpack = require('webpack');

var sauceLabsLaunchers = {
	sl_chrome: {
		base: 'SauceLabs',
		browserName: 'chrome'
	},
	sl_firefox: {
		base: 'SauceLabs',
		browserName: 'firefox'
	},
	sl_ios_safari: {
		base: 'SauceLabs',
		browserName: 'iphone',
		platform: 'OS X 10.9',
		version: '7.1'
	},
	sl_ie_11: {
		base: 'SauceLabs',
		browserName: 'internet explorer',
		version: '11'
	},
	sl_ie_10: {
		base: 'SauceLabs',
		browserName: 'internet explorer',
		version: '10'
	},
	sl_ie_9: {
		base: 'SauceLabs',
		browserName: 'internet explorer',
		version: '9'
	}
};

module.exports = function(config) {
	config.set({
		browsers: sauceLabs ? Object.keys(sauceLabsLaunchers) : ['PhantomJS'],

		frameworks: ['source-map-support', 'mocha', 'chai-sinon'],

		reporters: ['mocha'].concat(
			coverage ? 'coverage' : [],
			sauceLabs ? 'saucelabs' : []
		),

		coverageReporter: {
			reporters: [
				{
					type: 'text-summary'
				},
				{
					type: 'html',
					dir: __dirname+'/../coverage'
				}
			]
		},

		mochaReporter: {
			showDiff: true
		},

		browserLogOptions: { terminal: true },
		browserConsoleLogOptions: { terminal: true },

		browserNoActivityTimeout: 5 * 60 * 1000,

		// sauceLabs: {
		// 	tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER || ('local'+require('./package.json').version),
		// 	startConnect: false
		// },

		customLaunchers: sauceLabsLaunchers,

		files: [
			{ pattern: '{browser,shared}/**.js', watched: false }
		],

		preprocessors: {
			'**/*': ['webpack', 'sourcemap']
		},

		webpack: {
			devtool: 'inline-source-map',
			module: {
				/* Transpile source and test files */
				preLoaders: [
					{
						test: /\.jsx?$/,
						exclude: /node_modules/,
						loader: 'babel',
						query: {
							loose: 'all',
							blacklist: ['es6.tailCall']
						}
					}
				],
				/* Only Instrument our source files for coverage */
				loaders: [].concat( coverage ? {
					test: /\.jsx?$/,
					loader: 'isparta',
					include: /src/
				} : [])
			},
			resolve: {
				modulesDirectories: [__dirname, 'node_modules']
			},
			plugins: [
				new webpack.DefinePlugin({
					coverage: coverage,
					ENABLE_PERFORMANCE: performance
				})
			]
		},

		webpackMiddleware: {
			noInfo: true
		}
	});
};
<commit_msg>still run tests under phantomjs in addition to saucelabs<commit_after>/*eslint no-var:0, object-shorthand:0 */

var coverage = String(process.env.COVERAGE)!=='false',
	sauceLabs = String(process.env.SAUCELABS).match(/^(1|true)$/gi),
	performance = !coverage && !sauceLabs && String(process.env.PERFORMANCE)!=='false',
	webpack = require('webpack');

var sauceLabsLaunchers = {
	sl_chrome: {
		base: 'SauceLabs',
		browserName: 'chrome'
	},
	sl_firefox: {
		base: 'SauceLabs',
		browserName: 'firefox'
	},
	sl_ios_safari: {
		base: 'SauceLabs',
		browserName: 'iphone',
		platform: 'OS X 10.9',
		version: '7.1'
	},
	sl_ie_11: {
		base: 'SauceLabs',
		browserName: 'internet explorer',
		version: '11'
	},
	sl_ie_10: {
		base: 'SauceLabs',
		browserName: 'internet explorer',
		version: '10'
	},
	sl_ie_9: {
		base: 'SauceLabs',
		browserName: 'internet explorer',
		version: '9'
	}
};

module.exports = function(config) {
	config.set({
		browsers: ['PhantomJS'].concat(sauceLabs ? Object.keys(sauceLabsLaunchers) : []),

		frameworks: ['source-map-support', 'mocha', 'chai-sinon'],

		reporters: ['mocha'].concat(
			coverage ? 'coverage' : [],
			sauceLabs ? 'saucelabs' : []
		),

		coverageReporter: {
			reporters: [
				{
					type: 'text-summary'
				},
				{
					type: 'html',
					dir: __dirname+'/../coverage'
				}
			]
		},

		mochaReporter: {
			showDiff: true
		},

		browserLogOptions: { terminal: true },
		browserConsoleLogOptions: { terminal: true },

		browserNoActivityTimeout: 5 * 60 * 1000,

		// sauceLabs: {
		// 	tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER || ('local'+require('./package.json').version),
		// 	startConnect: false
		// },

		customLaunchers: sauceLabsLaunchers,

		files: [
			{ pattern: '{browser,shared}/**.js', watched: false }
		],

		preprocessors: {
			'**/*': ['webpack', 'sourcemap']
		},

		webpack: {
			devtool: 'inline-source-map',
			module: {
				/* Transpile source and test files */
				preLoaders: [
					{
						test: /\.jsx?$/,
						exclude: /node_modules/,
						loader: 'babel',
						query: {
							loose: 'all',
							blacklist: ['es6.tailCall']
						}
					}
				],
				/* Only Instrument our source files for coverage */
				loaders: [].concat( coverage ? {
					test: /\.jsx?$/,
					loader: 'isparta',
					include: /src/
				} : [])
			},
			resolve: {
				modulesDirectories: [__dirname, 'node_modules']
			},
			plugins: [
				new webpack.DefinePlugin({
					coverage: coverage,
					ENABLE_PERFORMANCE: performance
				})
			]
		},

		webpackMiddleware: {
			noInfo: true
		}
	});
};
<|endoftext|>


<commit_before>module.exports = function(config) {
  var detectBrowsers = {
    enabled: false,
    usePhantomJS: false
  };

  // On Travis CI, we can only run in Firefox and Chrome; so, enforce that.
  if (process.env.TRAVIS) {
    config.browsers = ['Firefox', 'travisChrome'];
  }

  // If no browsers are specified, we enable `karma-detect-browsers`
  // this will detect all browsers that are available for testing
  if (!config.browsers.length) {
    detectBrowsers.enabled = true;
  }

  config.set({
    basePath: '..',
    frameworks: ['qunit', 'detectBrowsers'],
    files: [
      'node_modules/video.js/dist/video-js.css',

      'node_modules/sinon/pkg/sinon.js',
      'node_modules/video.js/dist/video.js',
      'test/dist/bundle.js'
    ],
    customLaunchers: {
      travisChrome: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
    detectBrowsers: detectBrowsers,
    reporters: ['coverage','dots'],
    // Coverage reporter outputs a nicely formated HTML coverage
    // report, as well as an XML report in Clover format for
    // Bamboo to consume
    coverageReporter: {
      dir : 'test/coverage/',
      includeAllSources: true,
      reporters: [
        {type: 'html', subdir: 'report'},
        {type: 'clover', subdir: '.', file: 'report-clover.xml'},
        {type: 'lcov', subdir: '.'}
      ]
    },
    port: 9876,
    colors: true,
    autoWatch: false,
    singleRun: true,
    concurrency: Infinity
  });
};
<commit_msg>apply code coverage to test bundles<commit_after>module.exports = function(config) {
  var detectBrowsers = {
    enabled: false,
    usePhantomJS: false
  };

  // On Travis CI, we can only run in Firefox and Chrome; so, enforce that.
  if (process.env.TRAVIS) {
    config.browsers = ['Firefox', 'travisChrome'];
  }

  // If no browsers are specified, we enable `karma-detect-browsers`
  // this will detect all browsers that are available for testing
  if (!config.browsers.length) {
    detectBrowsers.enabled = true;
  }

  config.set({
    basePath: '..',
    frameworks: ['qunit', 'detectBrowsers'],
    files: [
      'node_modules/video.js/dist/video-js.css',
      'node_modules/sinon/pkg/sinon.js',
      'node_modules/video.js/dist/video.js',
      'test/dist/bundle.js'
    ],
    customLaunchers: {
      travisChrome: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
    detectBrowsers: detectBrowsers,
    preprocessors: {
      'test/dist/**/*.js': ['coverage'],
    },
    reporters: ['coverage','dots'],
    // Coverage reporter outputs a nicely formated HTML coverage
    // report, as well as an XML report in Clover format for
    // Bamboo to consume
    coverageReporter: {
      dir : 'test/coverage/',
      includeAllSources: true,
      reporters: [
        {type: 'html', subdir: 'report'},
        {type: 'clover', subdir: '.', file: 'report-clover.xml'},
        {type: 'lcov', subdir: '.'}
      ]
    },
    port: 9876,
    colors: true,
    autoWatch: false,
    singleRun: true,
    concurrency: Infinity
  });
};
<|endoftext|>


<commit_before>import chai from 'chai';
let assert = chai.assert;
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);

describe('LayerLeaf', () => {
    const {LayerLeaf} = require('../src/styles/layer');

    it('returns an new instanceof', () => {
        let subject = new LayerLeaf({name: 'test', layer: {}});
        assert.instanceOf(subject, LayerLeaf);
        assert.propertyVal(subject, 'name', 'test');
    });

});

describe('LayerTree', () => {
    const {LayerTree} = require('../src/styles/layer');

    it('returns an new instanceof', () => {
        let subject = new LayerTree({name: 'test', layer: {}});
        assert.instanceOf(subject, LayerTree);
        assert.propertyVal(subject, 'name', 'test');
    });
});

describe('.mergeTrees()', () => {
    let subject = [
        [ { group: { a: 0.001 } }, { group: { a: 1, b: 2 } }, { group: { b: 4, c: 3 } }, { group: { d: 4 } } ],
        [ { group: { x: 3.14 } }, { group: { y: 3 } }, { group: { x: 10, z: 1 } }, { group: { w: 2 } } ],
        [ { group: { e: 'y' } }, { group: { f: 'x' } }, { group:{ g: 0.0003 } }, { group: { h: 10 } } ],
        [ { group: { s: 3.14 } }, { group: { t: 2.71828 } }, { group:{ u: 0.0001 } }, { group: { v: 'x' } } ]
    ];

    const {mergeTrees} = require('../src/styles/layer');

    describe('when given an array of arrays to merged', () => {

        it('returns a single object', () => {
            let result = mergeTrees(subject, 'group', {});
            let compare = {
                visible: true,
                a: 1, b: 4, c: 3, d: 4,
                x: 10, y: 3, z: 1, w: 2,
                e: 'y', f: 'x', g: 0.0003, h: 10,
                s: 3.14, t: 2.71828, u: 0.0001, v: 'x'
            };
            assert.deepEqual(result, compare);
        });
    });

    describe('when given a array that is similar to real data', () => {
        const parent = {
            group: {
                "width": 10,
                "order": 1,
                "color": [1, 2, 3],
                "a": "x"
            }
        };

        const subject = [
            [
                parent,
                {
                    group: {
                        "order": 3,
                        "a": "y"
                    }
                }
            ],
            [
                parent,
                {
                    group: {
                        "b": "z",
                        "color": [7, 8, 9]
                    }
                }
            ]
        ];

        it('returns the correct object', () => {
            let result = mergeTrees(subject, 'group');
            let compare = {
                visible: true,
                width: 10,
                order: 3,
                a: 'y',
                b: 'z',
                color: [7, 8, 9]
            };
            assert.deepEqual(result, compare);
        });

    });

    describe('when given layers with ambiguous properties', () => {

        const subject = [
            [ { group: { a: 1, layer_name: 'x' } } ],
            [ { group: { a: 2, layer_name: 'z' } } ],
            [ { group: { a: 3, layer_name: 'y' } } ]
        ];

        it('the lexically sorted highest layer wins', () => {
            let result = mergeTrees(subject, 'group');
            let compare = {
                a: 2,
                visible: true
            };
            assert.deepEqual(result, compare);
        });

    });

});

describe('.parseLayer(layers)', () => {

    const {parseLayers}= require('../src/styles/layer');
    const LayerTree   = require('./fixtures/sample-style');

    describe('when given a raw LayerTree', () => {

        it('returns a LayerTree', () => {
            assert.instanceOf(parseLayers(LayerTree), Object);
        });

        it('returns the correct number of children layers', () => {
            let tree = parseLayers(LayerTree).root;
            let children = 0;

            function walkDown (layer) {
                if (layer.layers) {
                    layer.layers.forEach((r) => {
                        walkDown(r);
                    });
                }
                children++;
            }
            walkDown(tree);

            assert.equal(children, 4);
        });
    });
});

describe('.groupProps()', () => {
    let {groupProps} = require('../src/styles/layer');

    describe('given an object ', () => {
        let subject = {
            draw: { group: { a: 1 } },
            filter: 'I am a filter',
            a: 'b',
            b: 'c'
        };

        it('groups the properties by white listing', () => {
            assert.deepEqual(groupProps(subject),
                [
                    {
                        draw: { group: { a: 1 } },
                        filter: 'I am a filter'
                    },
                    {
                        a: 'b',
                        b: 'c'
                    }
                ]);
        });
    });
});

describe('.calculateDraw()', () => {
    const {calculateDraw} = require('../src/styles/layer');

    let b = {
        calculatedDraw: [
            { group: { a: true } },
            { group: { b: true } }
        ]
    };

    let c = {
        parent: b,
        draw: {
            group: {
                c: true
            }
        }
    };

    it('calculates a layers inherited draw group', () => {
        assert.deepEqual(
            calculateDraw(c),
            [{ group: { a: true } }, { group: { b: true } }, { group: { c: true } }]
        );
    });
});

describe('LayerTree.buildDrawGroups(context)', () => {
    let subject;
    const {parseLayers} = require('../src/styles/layer');
    const {LayerTree}   = require('../src/styles/layer');

    beforeEach(() => {
        subject = parseLayers(
            {
                root: {
                    filter: {
                        kind: 'highway'
                    },
                    draw: {
                        group: {
                            width: 10,
                            color: [1, 2, 3]
                        }
                    },
                    fillA: {
                        filter: {
                            name: 'FDR'
                        },
                        draw: {
                            group: {
                                order: 1,
                                color: [3.14, 3.14, 3.14]
                            }
                        },
                        a: {
                            filter: {
                                name: 'FDR'
                            },
                            draw: {
                                group: {
                                    width: 20,
                                    color: [2.71828, 2.71828, 2.71828]
                                }
                            }
                        }
                    },
                    roads: {
                        filter: {
                            '$zoom': { min: 3}
                        },
                        draw: {
                            group: {
                                width: 10,
                                color: [7, 8, 9]
                            }
                        },
                        fillB: {
                            filter: {
                                id: 10
                             },
                            draw: {
                                group: {
                                    color: [10, 11, 12]
                                }
                            },
                            b: {
                                filter: {
                                    id: 10
                                },
                                draw: {
                                    group: {
                                        color: [1, 2, 3]
                                    }
                                }
                            }

                        },
                    }

                }
            }
        );
    });

    afterEach(() => {
        subject = null;
    });

    describe('when the context matches and we ask to merge the sibling layers', () => {
        let context = {
            feature: {
                properties: {
                    kind: 'highway',
                    name: 'FDR',
                    id: 10
                }
            },
            zoom: 3
        };

        it('returns a single object', () => {
            let layer = subject.root.buildDrawGroups(context);
            assert.equal(Object.keys(layer).length, 1);
            assert.deepEqual(layer.group.color, [1, 2, 3]);
            assert.equal(layer.group.width, 20);
            assert.equal(layer.group.order, 1);
        });
    });

    describe('when the feature is a highway and is named FDR', () => {
        let context = {
            feature: {
                properties: {
                    kind: 'highway',
                    name: 'FDR',
                    id: 10
                }
            },
            zoom: 3
        };

        it('returns the correct number of matching layers', () => {
            let layer = subject.root.buildDrawGroups(context);
            assert.equal(Object.keys(layer).length, 1);
            assert.deepEqual(layer.group.color, [1, 2, 3]);
            assert.equal(layer.group.width, 20);
            assert.equal(layer.group.order, 1);
        });
    });

    describe('when the feature is not a road', () => {
        let context = {
            feature: {
                properties: {
                    kind: 'aeroway'
                }
            }
        };

        it('returns undefined', () => {
            const layer = subject.root.buildDrawGroups(context);
            assert.isUndefined(layer);
        });
    });

    describe('parseLayers', () => {

        it('returns a tree', () => {
            let subject = parseLayers({
                root: {
                    filter: {
                        id: 10
                    },
                    draw: {
                        group: {
                            color: [3.14, 3.14, 3.14]
                        }
                    }
                }
            });
            assert.instanceOf(subject.root, LayerTree);
        });

        describe('when there no draw groups on the parent', () => {
            let subject = parseLayers({
                root: {
                    filter: {
                        name: 'ivan'
                    },
                    a: {
                        filter: {
                            id: 10
                        },
                        draw: {
                            group: {
                                color: [1, 2, 3]
                            }
                        }
                    }
                }
            });
            let context = {
                feature: {
                    properties: {
                        name: 'ivan',
                        id: 10
                    }
                }
            };

            it('returns only the child\'s draw', () => {
                let layer = subject.root.buildDrawGroups(context);
                assert.equal(Object.keys(layer).length, 1);
                assert.deepEqual(layer.group.color, [1, 2, 3]);
            });

        });

    });

});
<commit_msg>tests: update layer test<commit_after>import chai from 'chai';
let assert = chai.assert;
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);

describe('LayerLeaf', () => {
    const {LayerLeaf} = require('../src/styles/layer');

    it('returns an new instanceof', () => {
        let subject = new LayerLeaf({name: 'test', layer: {}});
        assert.instanceOf(subject, LayerLeaf);
        assert.propertyVal(subject, 'name', 'test');
    });

});

describe('LayerTree', () => {
    const {LayerTree} = require('../src/styles/layer');

    it('returns an new instanceof', () => {
        let subject = new LayerTree({name: 'test', layer: {}});
        assert.instanceOf(subject, LayerTree);
        assert.propertyVal(subject, 'name', 'test');
    });
});

describe('.mergeTrees()', () => {
    let subject = [
        [ { group: { a: 0.001 } }, { group: { a: 1, b: 2 } }, { group: { b: 4, c: 3 } }, { group: { d: 4 } } ],
        [ { group: { x: 3.14 } }, { group: { y: 3 } }, { group: { x: 10, z: 1 } }, { group: { w: 2 } } ],
        [ { group: { e: 'y' } }, { group: { f: 'x' } }, { group:{ g: 0.0003 } }, { group: { h: 10 } } ],
        [ { group: { s: 3.14 } }, { group: { t: 2.71828 } }, { group:{ u: 0.0001 } }, { group: { v: 'x' } } ]
    ];

    const {mergeTrees} = require('../src/styles/layer');

    describe('when given an array of arrays to merged', () => {

        it('returns a single object', () => {
            let result = mergeTrees(subject, 'group', {});
            let compare = {
                visible: true,
                a: 1, b: 4, c: 3, d: 4,
                x: 10, y: 3, z: 1, w: 2,
                e: 'y', f: 'x', g: 0.0003, h: 10,
                s: 3.14, t: 2.71828, u: 0.0001, v: 'x'
            };
            assert.deepEqual(result, compare);
        });
    });

    describe('when given a array that is similar to real data', () => {
        const parent = {
            group: {
                "width": 10,
                "order": 1,
                "color": [1, 2, 3],
                "a": "x"
            }
        };

        const subject = [
            [
                parent,
                {
                    group: {
                        "order": 3,
                        "a": "y"
                    }
                }
            ],
            [
                parent,
                {
                    group: {
                        "b": "z",
                        "color": [7, 8, 9]
                    }
                }
            ]
        ];

        it('returns the correct object', () => {
            let result = mergeTrees(subject, 'group');
            let compare = {
                visible: true,
                width: 10,
                order: 3,
                a: 'y',
                b: 'z',
                color: [7, 8, 9]
            };
            assert.deepEqual(result, compare);
        });

    });

    describe('when given layers with ambiguous properties', () => {

        const subject = [
            [ { group: { a: 1, layer_name: 'x' } } ],
            [ { group: { a: 2, layer_name: 'z' } } ],
            [ { group: { a: 3, layer_name: 'y' } } ]
        ];

        it('the lexically sorted highest layer wins', () => {
            let result = mergeTrees(subject, 'group');
            let compare = {
                a: 2,
                visible: true
            };
            assert.deepEqual(result, compare);
        });

    });

});

describe('.parseLayer(layers)', () => {

    const {parseLayers}= require('../src/styles/layer');
    const LayerTree   = require('./fixtures/sample-style');

    describe('when given a raw LayerTree', () => {

        it('returns a LayerTree', () => {
            assert.instanceOf(parseLayers(LayerTree), Object);
        });

        it('returns the correct number of children layers', () => {
            let tree = parseLayers(LayerTree);
            let numChildren = Object.keys(tree.root.children_to_parse).length;
            assert.equal(numChildren, 2);
        });
    });
});

describe('.groupProps()', () => {
    let {groupProps} = require('../src/styles/layer');

    describe('given an object ', () => {
        let subject = {
            draw: { group: { a: 1 } },
            filter: 'I am a filter',
            a: 'b',
            b: 'c'
        };

        it('groups the properties by white listing', () => {
            assert.deepEqual(groupProps(subject),
                [
                    {
                        draw: { group: { a: 1 } },
                        filter: 'I am a filter'
                    },
                    {
                        a: 'b',
                        b: 'c'
                    }
                ]);
        });
    });
});

describe('.calculateDraw()', () => {
    const {calculateDraw} = require('../src/styles/layer');

    let b = {
        calculatedDraw: [
            { group: { a: true } },
            { group: { b: true } }
        ]
    };

    let c = {
        parent: b,
        draw: {
            group: {
                c: true
            }
        }
    };

    it('calculates a layers inherited draw group', () => {
        assert.deepEqual(
            calculateDraw(c),
            [{ group: { a: true } }, { group: { b: true } }, { group: { c: true } }]
        );
    });
});

describe('LayerTree.buildDrawGroups(context)', () => {
    let subject;
    const {parseLayers} = require('../src/styles/layer');
    const {LayerTree}   = require('../src/styles/layer');

    beforeEach(() => {
        subject = parseLayers(
            {
                root: {
                    filter: {
                        kind: 'highway'
                    },
                    draw: {
                        group: {
                            width: 10,
                            color: [1, 2, 3]
                        }
                    },
                    fillA: {
                        filter: {
                            name: 'FDR'
                        },
                        draw: {
                            group: {
                                order: 1,
                                color: [3.14, 3.14, 3.14]
                            }
                        },
                        a: {
                            filter: {
                                name: 'FDR'
                            },
                            draw: {
                                group: {
                                    width: 20,
                                    color: [2.71828, 2.71828, 2.71828]
                                }
                            }
                        }
                    },
                    roads: {
                        filter: {
                            '$zoom': { min: 3}
                        },
                        draw: {
                            group: {
                                width: 10,
                                color: [7, 8, 9]
                            }
                        },
                        fillB: {
                            filter: {
                                id: 10
                             },
                            draw: {
                                group: {
                                    color: [10, 11, 12]
                                }
                            },
                            b: {
                                filter: {
                                    id: 10
                                },
                                draw: {
                                    group: {
                                        color: [1, 2, 3]
                                    }
                                }
                            }

                        },
                    }

                }
            }
        );
    });

    afterEach(() => {
        subject = null;
    });

    describe('when the context matches and we ask to merge the sibling layers', () => {
        let context = {
            feature: {
                properties: {
                    kind: 'highway',
                    name: 'FDR',
                    id: 10
                }
            },
            zoom: 3
        };

        it('returns a single object', () => {
            let layer = subject.root.buildDrawGroups(context);
            assert.equal(Object.keys(layer).length, 1);
            assert.deepEqual(layer.group.color, [1, 2, 3]);
            assert.equal(layer.group.width, 20);
            assert.equal(layer.group.order, 1);
        });
    });

    describe('when the feature is a highway and is named FDR', () => {
        let context = {
            feature: {
                properties: {
                    kind: 'highway',
                    name: 'FDR',
                    id: 10
                }
            },
            zoom: 3
        };

        it('returns the correct number of matching layers', () => {
            let layer = subject.root.buildDrawGroups(context);
            assert.equal(Object.keys(layer).length, 1);
            assert.deepEqual(layer.group.color, [1, 2, 3]);
            assert.equal(layer.group.width, 20);
            assert.equal(layer.group.order, 1);
        });
    });

    describe('when the feature is not a road', () => {
        let context = {
            feature: {
                properties: {
                    kind: 'aeroway'
                }
            }
        };

        it('returns undefined', () => {
            const layer = subject.root.buildDrawGroups(context);
            assert.isUndefined(layer);
        });
    });

    describe('parseLayers', () => {

        it('returns a tree', () => {
            let subject = parseLayers({
                root: {
                    filter: {
                        id: 10
                    },
                    draw: {
                        group: {
                            color: [3.14, 3.14, 3.14]
                        }
                    }
                }
            });
            assert.instanceOf(subject.root, LayerTree);
        });

        describe('when there no draw groups on the parent', () => {
            let subject = parseLayers({
                root: {
                    filter: {
                        name: 'ivan'
                    },
                    a: {
                        filter: {
                            id: 10
                        },
                        draw: {
                            group: {
                                color: [1, 2, 3]
                            }
                        }
                    }
                }
            });
            let context = {
                feature: {
                    properties: {
                        name: 'ivan',
                        id: 10
                    }
                }
            };

            it('returns only the child\'s draw', () => {
                let layer = subject.root.buildDrawGroups(context);
                assert.equal(Object.keys(layer).length, 1);
                assert.deepEqual(layer.group.color, [1, 2, 3]);
            });

        });

    });

});
<|endoftext|>


<commit_before>'use strict';

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

const should = require('should');

describe('Lexer', () => {
  const fixturesPath = path.join(__dirname, 'fixtures/lexer');
  const tests = fs.readdirSync(fixturesPath);
  let lexer;

  beforeEach(() => {
    lexer = require('../tmp/lexer');
  });

  tests.forEach((test) => {
    const testPath = path.join(fixturesPath, test);
    const source = fs.readFileSync(path.join(testPath, 'source.ba'));
    const config = require(path.join(testPath, 'config.js'));
    const itFunction =
      config.only ? it.only :
      config.skip ? it.skip :
      it;

    itFunction(`should handle ${test}`, function () {
      if (config.timeout) {
        this.timeout(config.timeout);
      }

      if (config.type === 'success') {
        let result;

        should(() => {
          result = lexer(source, config.options);
        }).not.throw();

        if (!config.ignoreResult) {
          should(result).be.eql(config.result);
        }

        if (config.inspectResult) {
          console.log(util.inspect(result, { colors: true, depth: null }));
        }
      } else {
        should(() => {
          lexer(source, config.options);
        }).throw(config.error);
      }
    });
  });
});
<commit_msg>Fix typo.<commit_after>'use strict';

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

const should = require('should');

describe('Lexer', () => {
  const fixturesPath = path.join(__dirname, 'fixtures/lexer');
  const tests = fs.readdirSync(fixturesPath);
  let tokenize;

  beforeEach(() => {
    tokenize = require('../tmp/lexer');
  });

  tests.forEach((test) => {
    const testPath = path.join(fixturesPath, test);
    const source = fs.readFileSync(path.join(testPath, 'source.ba'));
    const config = require(path.join(testPath, 'config.js'));
    const itFunction =
      config.only ? it.only :
      config.skip ? it.skip :
      it;

    itFunction(`should handle ${test}`, function () {
      if (config.timeout) {
        this.timeout(config.timeout);
      }

      if (config.type === 'success') {
        let result;

        should(() => {
          result = tokenize(source, config.options);
        }).not.throw();

        if (!config.ignoreResult) {
          should(result).be.eql(config.result);
        }

        if (config.inspectResult) {
          console.log(util.inspect(result, { colors: true, depth: null }));
        }
      } else {
        should(() => {
          tokenize(source, config.options);
        }).throw(config.error);
      }
    });
  });
});
<|endoftext|>


<commit_before>var rewire  = require('rewire'),
    sinon = require('sinon'),
    expect = require('chai').expect,
    Factory = require('../spec_helper').Factory,
    utils = require('../../lib/utils'),
    docker = require('../../lib/docker'),
    Runner = rewire('../../lib/runner');

var MAX_MEMORY         = Runner.__get__('MAX_MEMORY'),
    MAX_EXECUTION_TIME = Runner.__get__('MAX_EXECUTION_TIME');

describe('Runner', function() {
    var sleepCode   = Factory.create('sleepCode'),
        defaultCode = Factory.create('defaultCode');

    it('has a max execution time of 10 seconds', function() {
        expect(MAX_EXECUTION_TIME / 1000).to.equal(10);
    });

    beforeEach(function() {
        runner = new Runner();
    });

    describe('#run()', function() {
        context('when container creation succeed', function(done) {
            beforeEach(function(done) {
                // First we need to manually setup a container.
                return runner._createContainer(defaultCode)
                .then(function(container) {
                    // We stub our container attach to fail.
                    container.attach = sinon.stub().yields(new Error());

                    // We stub our runner client to yield this container.
                    setFakeContainerCreate(null, container);

                    return runner.run(defaultCode);
                })
                .then(function() {
                    done('Run should fail after container creation.');
                })
                .fail(function() {
                    done();
                });
            });

            afterEach(function() {
                revertContainerCreate();
            });

            it('has a container', function() {
                expect(runner.container).not.to.be.null;
            });

            it('creates a container with maxMemory set', function(done) {
                return runner._getContainer('Memory')
                .then(function(info) {
                    expect(info).to.equal(MAX_MEMORY);
                    done();
                });
            });

            it('creates a container with this language image', function(done) {
                var dockerClient = docker.getClient()

                var image = utils.formatImage(dockerClient.repository,
                    defaultCode.language,
                    dockerClient.tag
                );

                return runner._getContainer('Image')
                .then(function(info) {
                    expect(info).to.equal(image);
                    done();
                });
            });

            it('creates a container with this code command', function(done) {
                var cmd = utils.formatCmd(defaultCode.code);

                return runner._getContainer('Cmd')
                .then(function(info) {
                    expect(info).to.deep.equal([cmd]);
                    done();
                });
            });
        });

        context('when container creation failed', function(done) {
            beforeEach(function() {
                error = new Error();

                revert = runner.client.createContainer;

                setFakeContainerCreate(error);
            });

            afterEach(function() {
                revertContainerCreate();
            });

            it('gets an error', function(done) {
                return runner.run(defaultCode)
                .then(function () {
                    done('runner created a container but it should not');
                })
                .fail(function (err) {
                    expect(err).to.equal(error);
                    done();
                });
            });
        });

        ['attach', 'start', 'wait', 'inspect', 'remove'].forEach(
            function (action) {
            context('when docker fail to '+action+' this container', function() {
                beforeEach(function(done) {
                    error = new Error();

                    // First we need to manually setup a container.
                    return runner._createContainer(defaultCode)
                    .then(function(container) {
                        // We stub our container action to fail.
                        container[action] = sinon.stub().yields(error);

                        setFakeContainerCreate(null, container);

                        done();
                    })
                    .fail(function(err) {
                        done(err);
                    });
                });

                afterEach(function() {
                    revertContainerCreate();
                });

                it('gets an error', function(done) {
                    return runner.run(defaultCode)
                    .then(function() {
                        done('container '+action+' did not fail.');
                    })
                    .fail(function (err) {
                        expect(err).to.equal(error);
                        done();
                    });
                });
            });
        });

        // For this context we are testing against a
        // code sample that writes both on stdout and
        // stderr, returns an exit code of 1, with a
        // really short execution time.
        context('when container exits', function() {
            beforeEach(function(done) {
                emited = attachRunnerEvents();

                return runner.run(defaultCode)
                .then(function () {
                    done();
                })
                .fail(function (err) {
                    done(err);
                });
            });

            it('has emited container exit code', function() {
                expect(emited.exitCode).to.equal(defaultCode.exitCode);
            });

            it('has emited appropriate output on stdout', function() {
                expect(emited.output.stdout).to.equal(defaultCode.stdout);
            });

            it('has emited appropriate output on stderr', function() {
                expect(emited.output.stderr).to.equal(defaultCode.stderr);
            });

            it('has removed its container', function(done) {
                emited.container.inspect(function(err, data) {
                    expect(err).not.to.be.null;
                    done();
                });
            });

            it('has no container', function() {
                expect(runner.container).to.be.null;
            });
        });

        // For this context we are using a code sample
        // that should hang more than the test suite
        // default timeout, but runner should automatically
        // timeouts after maxExecutionTime and stop the
        // container, preventing these tests from timeouts.
        context('when execution is too long', function() {
            beforeEach(function() {
                fakeTimeout = 1;
                revert = Runner.__set__('MAX_EXECUTION_TIME', fakeTimeout);

                emited = attachRunnerEvents();
            });

            afterEach(function() {
                revert();
            });

            it('emits a timeout and stops the container', function(done) {
                runner.on('timeout', function(executionTime) {
                    timeout = executionTime;
                });

                return runner.run(defaultCode)
                .then(function () {
                    expect(timeout).to.equal(fakeTimeout);
                    done();
                })
                .fail(function (err) {
                    done(err);
                });
            });
        });
    });

    describe('#stop()', function() {
        context('when idle', function() {
            it('does nothing', function() {
                expect(function() {
                    runner.stop();
                }).not.to.throw(Error);
            });
        });

        // For this context we are using a code example
        // that should hang more than the test suite
        // default timeout, if stop fails, these tests
        // should timeout.
        context('when running', function() {
            beforeEach(function(done) {
                runner.on('start', function() {
                    runner.stop();
                });

                emited = attachRunnerEvents();

                return runner.run(sleepCode)
                .then(function() {
                    done();
                })
                .fail(function(err) {
                    done(err);
                })
            });

            // We must verify that the container doesn't
            // stop because of the code sent as parameter.
            it('stops the container execution', function() {
                expect(emited.output.stderr).to.equal('');
            });

            it("hasn't emited container exit code", function() {
                expect(emited.exitCode).to.be.null;
            });
        });
    });

    function attachRunnerEvents() {
        var emited = {
            output: { stdout: '', stderr: '' },
            exitCode: null,
            timeout: null,
            container: null,
        }

        runner.on('output', function(data) {
            emited.output[data.stream] += data.chunk;
        }).on('status', function(data) {
            emited.exitCode = data;
        }).on('timeout', function(data){
            emited.timeout = data;
        }).on('created', function(data){
            emited.container = data;
        });
        return emited;
    }

    function setFakeContainerCreate(err, container) {
        containerCreate = runner.client.createContainer;

        // We stub our runner client to yield this container.
        runner.client.createContainer = sinon.stub().yields(err, container);
    }

    function revertContainerCreate() {
        if (typeof(containerCreate) == 'undefined') return;

        runner.client.createContainer = containerCreate;
    }
});
<commit_msg>refactor runner tests<commit_after>var rewire  = require('rewire'),
    sinon = require('sinon'),
    expect = require('chai').expect,
    Factory = require('../spec_helper').Factory,
    utils = require('../../lib/utils'),
    docker = require('../../lib/docker'),
    Runner = rewire('../../lib/runner');

var MAX_MEMORY         = Runner.__get__('MAX_MEMORY'),
    MAX_EXECUTION_TIME = Runner.__get__('MAX_EXECUTION_TIME');

describe('Runner', function() {
    var sleepCode   = Factory.create('sleepCode'),
        defaultCode = Factory.create('defaultCode');

    it('has a max execution time of 10 seconds', function() {
        expect(MAX_EXECUTION_TIME / 1000).to.equal(10);
    });

    beforeEach(function() {
        runner = new Runner();
    });

    describe('#run()', function() {
        context('when container creation succeed', function(done) {
            beforeEach(function(done) {
                // First we need to manually setup a container.
                return runner._createContainer(defaultCode)
                .then(function(container) {
                    // We stub our container attach to fail.
                    container.attach = sinon.stub().yields(new Error());

                    // We stub our runner client to yield this container.
                    setFakeContainerCreate(null, container);

                    return runner.run(defaultCode);
                })
                .then(function() {
                    done('Run should fail after container creation.');
                })
                .fail(function() {
                    done();
                });
            });

            afterEach(function() {
                revertContainerCreate();
            });

            it('has a container', function() {
                expect(runner.container).not.to.be.null;
            });

            it('creates a container with maxMemory set', function(done) {
                return runner._getContainer('Memory')
                .then(function(info) {
                    expect(info).to.equal(MAX_MEMORY);
                    done();
                });
            });

            it('creates a container with this language image', function(done) {
                var dockerClient = docker.getClient()

                var image = utils.formatImage(dockerClient.repository,
                    defaultCode.language,
                    dockerClient.tag
                );

                return runner._getContainer('Image')
                .then(function(info) {
                    expect(info).to.equal(image);
                    done();
                });
            });

            it('creates a container with this code command', function(done) {
                var cmd = utils.formatCmd(defaultCode.code);

                return runner._getContainer('Cmd')
                .then(function(info) {
                    expect(info).to.deep.equal([cmd]);
                    done();
                });
            });
        });

        context('when container creation failed', function(done) {
            beforeEach(function() {
                error = new Error();

                revert = runner.client.createContainer;

                setFakeContainerCreate(error);
            });

            afterEach(function() {
                revertContainerCreate();
            });

            expectError();
        });

        ['attach', 'start', 'wait', 'inspect', 'remove'].forEach(
            function (action) {
            context('when docker fail to '+action+' this container', function() {
                beforeEach(function(done) {
                    error = new Error();

                    // First we need to manually setup a container.
                    return runner._createContainer(defaultCode)
                    .then(function(container) {
                        // We stub our container action to fail.
                        container[action] = sinon.stub().yields(error);

                        setFakeContainerCreate(null, container);

                        done();
                    })
                    .fail(function(err) {
                        done(err);
                    });
                });

                afterEach(function() {
                    revertContainerCreate();
                });

                expectError();
            });
        });

        // For this context we are testing against a
        // code sample that writes both on stdout and
        // stderr, returns an exit code of 1, with a
        // really short execution time.
        context('when container exits', function() {
            beforeEach(function(done) {
                emited = attachRunnerEvents();

                run(defaultCode, done);
            });

            it('has emited container exit code', function() {
                expect(emited.exitCode).to.equal(defaultCode.exitCode);
            });

            it('has emited appropriate output on stdout', function() {
                expect(emited.output.stdout).to.equal(defaultCode.stdout);
            });

            it('has emited appropriate output on stderr', function() {
                expect(emited.output.stderr).to.equal(defaultCode.stderr);
            });

            it('has removed its container', function(done) {
                emited.container.inspect(function(err, data) {
                    expect(err).not.to.be.null;
                    done();
                });
            });

            it('has no container', function() {
                expect(runner.container).to.be.null;
            });
        });

        // For this context we are using a code sample
        // that should hang more than the test suite
        // default timeout, but runner should automatically
        // timeouts after maxExecutionTime and stop the
        // container, preventing these tests from timeouts.
        context('when execution is too long', function() {
            beforeEach(function() {
                fakeTimeout = 1;
                revert = Runner.__set__('MAX_EXECUTION_TIME', fakeTimeout);

                emited = attachRunnerEvents();
            });

            afterEach(function() {
                revert();
            });

            it('emits a timeout and stops the container', function(done) {
                runner.on('timeout', function(executionTime) {
                    timeout = executionTime;
                });

                run(sleepCode, function(err) {
                    expect(timeout).to.equal(fakeTimeout);
                    done(err);
                });
            });
        });
    });

    describe('#stop()', function() {
        context('when idle', function() {
            it('does nothing', function() {
                expect(function() {
                    runner.stop();
                }).not.to.throw(Error);
            });
        });

        // For this context we are using a code example
        // that should hang more than the test suite
        // default timeout, if stop fails, these tests
        // should timeout.
        context('when running', function() {
            beforeEach(function(done) {
                runner.on('start', function() {
                    runner.stop();
                });

                emited = attachRunnerEvents();

                run(sleepCode, done);
            });

            // We must verify that the container doesn't
            // stop because of the code sent as parameter.
            it('stops the container execution', function() {
                expect(emited.output.stderr).to.equal('');
            });

            it("hasn't emited container exit code", function() {
                expect(emited.exitCode).to.be.null;
            });
        });
    });

    function attachRunnerEvents() {
        var emited = {
            output: { stdout: '', stderr: '' },
            exitCode: null,
            timeout: null,
            container: null,
        }

        runner.on('output', function(data) {
            emited.output[data.stream] += data.chunk;
        }).on('status', function(data) {
            emited.exitCode = data;
        }).on('timeout', function(data){
            emited.timeout = data;
        }).on('created', function(data){
            emited.container = data;
        });
        return emited;
    }

    function run(example, cb) {
        return runner.run(sleepCode)
        .then(function() {
            cb();
        })
        .fail(function(err) {
            cb(err);
        });
    }

    function expectError() {
        it('gets an error', function(done) {
            run(defaultCode, function(err) {
                expect(err).to.equal(error);
            });
        });
    }

    function setFakeContainerCreate(err, container) {
        containerCreate = runner.client.createContainer;

        // We stub our runner client to yield this container.
        runner.client.createContainer = sinon.stub().yields(err, container);
    }

    function revertContainerCreate() {
        if (typeof(containerCreate) == 'undefined') return;

        runner.client.createContainer = containerCreate;
    }
});
<|endoftext|>