<commit_before>
'use strict';

var assert     = require('assert');
var http       = require('http');
var ioStream   = require('../../lib/iostreams')();
var ioStreamS3 = require('../../providers/iostreams-s3');
var _          = require('underscore');
var fs         = require('fs');

ioStream.use(ioStreamS3);

var baseConfig = {
  protocol: 's3:',
  key: process.env.S3_KEY,
  secret: process.env.S3_SECRET,
  bucket: process.env.S3_BUCKET,
  region: 'eu-west-1'
};

describe('iostreams-file', function() {

  describe('getProviderByProtocol', function() {

    it('should return a file instance based on the file: protocol', function() {
      assert.deepEqual(ioStream.getProviderByProtocol('s3:'), ioStreamS3);
    });

  });

  describe('getInputStream', function() {

    it('should provide a stream given a correct config', function(done) {
      ioStream.getInputStream(_.extend(baseConfig, { path: '/webcastio-gravatar.png' }), function(err, stream) {
        assert.ifError(err);
        assert(stream instanceof http.IncomingMessage);
        done();
      });
    });
    it('should provide an error given a file config with no file at path', function(done) {
      ioStream.getInputStream(_.extend(baseConfig, { path: '/non-existent-file.png' }), function(err) {
        assert(err instanceof Error);
        done();
      });
    });
    it('should provide an error given a correct object input');
    it('should provide an error given a file object with no file at path');

  });

  describe('getOutputStream', function() {

    var fileSize, filePath = __dirname + '/../assets/testfile1.flv';

    before(function(done) {
      fs.stat(filePath, function(err, stats) {
        if(err) return done(err);
        fileSize = stats.size;
        done();
      });
    });

    it('should provide a stream given a correct file string', function(done) {

      ioStream.getOutputStream(_.extend(baseConfig, {
        path: '/file-to-be-created.flv',
        'Content-Length': fileSize,
        'Content-Type':   'video/flv',
        'x-amz-acl':      'public-read'
      }), function(err, stream) {
        assert.ifError(err);
        assert(stream instanceof http.OutgoingMessage);

        var fileStream = fs.createReadStream(filePath);

        stream.on('response', function(awsRes) {
          if(awsRes.statusCode !== 200) {
            return done(new Error('Non 200 statuscode'))
          } else {
            return done();
          }
        });

        fileStream.pipe(stream);

      });
    });
    it('should provide an error given a icorrect object input');

  });

});
<commit_msg>Lint Fixes<commit_after>
'use strict';

var assert     = require('assert');
var http       = require('http');
var ioStream   = require('../../lib/iostreams')();
var ioStreamS3 = require('../../providers/iostreams-s3');
var _          = require('underscore');
var fs         = require('fs');

ioStream.use(ioStreamS3);

var baseConfig = {
  protocol: 's3:',
  key: process.env.S3_KEY,
  secret: process.env.S3_SECRET,
  bucket: process.env.S3_BUCKET,
  region: 'eu-west-1'
};

describe('iostreams-file', function() {

  describe('getProviderByProtocol', function() {

    it('should return a file instance based on the file: protocol', function() {
      assert.deepEqual(ioStream.getProviderByProtocol('s3:'), ioStreamS3);
    });

  });

  describe('getInputStream', function() {

    it('should provide a stream given a correct config', function(done) {
      ioStream.getInputStream(_.extend(baseConfig, { path: '/webcastio-gravatar.png' }), function(err, stream) {
        assert.ifError(err);
        assert(stream instanceof http.IncomingMessage);
        done();
      });
    });
    it('should provide an error given a file config with no file at path', function(done) {
      ioStream.getInputStream(_.extend(baseConfig, { path: '/non-existent-file.png' }), function(err) {
        assert(err instanceof Error);
        done();
      });
    });
    it('should provide an error given a correct object input');
    it('should provide an error given a file object with no file at path');

  });

  describe('getOutputStream', function() {

    var fileSize, filePath = __dirname + '/../assets/testfile1.flv';

    before(function(done) {
      fs.stat(filePath, function(err, stats) {
        if(err) {
          return done(err);
        }
        fileSize = stats.size;
        done();
      });
    });

    it('should provide a stream given a correct file string', function(done) {

      ioStream.getOutputStream(_.extend(baseConfig, {
        path: '/file-to-be-created.flv',
        'Content-Length': fileSize,
        'Content-Type':   'video/flv',
        'x-amz-acl':      'public-read'
      }), function(err, stream) {
        assert.ifError(err);
        assert(stream instanceof http.OutgoingMessage);

        var fileStream = fs.createReadStream(filePath);

        stream.on('response', function(awsRes) {
          if(awsRes.statusCode !== 200) {
            return done(new Error('Non 200 statuscode'));
          } else {
            return done();
          }
        });

        fileStream.pipe(stream);

      });
    });
    it('should provide an error given a icorrect object input');

  });

});
<|endoftext|>


<commit_before>// @flow weak

import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from 'material-ui/utils/customPropTypes';

const globalStyleSheet = createStyleSheet('global', theme => {
  const { palette } = theme;
  return {
    '@global': {
      html: {
        // Do the opposite of the docs in order to help catching issues.
        boxSizing: 'border-box',
      },
      '*, *:before, *:after': {
        boxSizing: 'inherit',
        transition: 'none !important',
        animation: 'none !important',
      },
      body: {
        margin: 0,
        background: palette.background.default,
        overflowX: 'hidden',
        WebkitFontSmoothing: 'antialiased',
      },
      a: {
        color: palette.accent.A400,
        textDecoration: 'none',
      },
      'a:hover': {
        textDecoration: 'underline',
      },
    },
  };
});

const styleSheet = createStyleSheet('TestViewer', theme => {
  return {
    root: {
      padding: theme.spacing.unit,
    },
  };
});

export default class TestViewer extends Component {
  static propTypes = {
    children: PropTypes.node,
  };

  static contextTypes = {
    styleManager: customPropTypes.muiRequired,
  };

  componentWillMount() {
    this.context.styleManager.render(globalStyleSheet);
  }

  render() {
    const { children } = this.props;
    const classes = this.context.styleManager.render(styleSheet);
    return (

        {children}

    );
  }
}
<commit_msg>[test] Fix usage of old API<commit_after>// @flow weak

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from 'material-ui/utils/customPropTypes';

const globalStyleSheet = createStyleSheet('global', theme => {
  const { palette } = theme;
  return {
    '@global': {
      html: {
        // Do the opposite of the docs in order to help catching issues.
        boxSizing: 'border-box',
      },
      '*, *:before, *:after': {
        boxSizing: 'inherit',
        transition: 'none !important',
        animation: 'none !important',
      },
      body: {
        margin: 0,
        background: palette.background.default,
        overflowX: 'hidden',
        WebkitFontSmoothing: 'antialiased',
      },
      a: {
        color: palette.accent.A400,
        textDecoration: 'none',
      },
      'a:hover': {
        textDecoration: 'underline',
      },
    },
  };
});

const styleSheet = createStyleSheet('TestViewer', theme => {
  return {
    root: {
      padding: theme.spacing.unit,
    },
  };
});

export default class TestViewer extends Component {
  static propTypes = {
    children: PropTypes.node,
  };

  static contextTypes = {
    styleManager: customPropTypes.muiRequired,
  };

  componentWillMount() {
    this.context.styleManager.render(globalStyleSheet);
  }

  render() {
    const { children } = this.props;
    const classes = this.context.styleManager.render(styleSheet);
    return (

        {children}

    );
  }
}
<|endoftext|>


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

var vm = require('vm');
var fs = require('fs');
var module_code = fs.readFileSync(__dirname + '/../runtime_library/module.js', { encoding: 'utf8' });

function getNewModuleVersion(context){
  vm.runInNewContext(module_code, context);
  return context;
}

describe('Runtime Library module', function(){

  describe('require', function(){

    it('should respond with an error if the identifier is neither a module, nor a javascript or JSON file', function(){
      var __readFileSync = sinon.stub();
      __readFileSync.returns('{"test":[1,2],"a":"b","c":{"d":-1}}');
      var context = {
        __readFileSync: __readFileSync
      };
      var module = getNewModuleVersion(context);

      expect(function(){ module.require('./test.txt'); }).to.throw(/require can only be used to load modules, javascript files, and JSON files/);
    });

    it('should call __readFileSync with the path', function(){

      var __readFileSync = sinon.spy();
      var context = {
        __readFileSync: __readFileSync
      };
      var module = getNewModuleVersion(context);

      var test_module = module.require('module_id');
      expect(__readFileSync).to.have.been.calledOnce;
    });

    it('should eval and extract the module.exports from javascript files', function(){

      var __readFileSync = sinon.stub();
      __readFileSync.returns('module.exports={ global_data: "Hello World!" }');
      var context = {
        __readFileSync: __readFileSync
      };
      var module = getNewModuleVersion(context);

      var test_module = module.require('module_id');
      expect(test_module).to.have.property('global_data', 'Hello World!');
    });

    it('should parse json files', function(){
      var __readFileSync = sinon.stub();
      __readFileSync.returns('{"test":[1,2],"a":"b","c":{"d":-1}}');
      var context = {
        __readFileSync: __readFileSync
      };
      var module = getNewModuleVersion(context);

      var test_module = module.require('test.json');
      expect(test_module).to.deep.equal({
        test: [1, 2],
        a: 'b',
        c: { d: -1 }
      });
    });

    it('should expose a modified version of itself to submodules that translates relative paths to full paths', function(){

      var __readFileSync = sinon.stub();
      __readFileSync.onFirstCall().returns('module.exports = require("sub_module");');
      __readFileSync.onSecondCall().returns('module.exports={ global_data: "Hello World!" }');
      var context = {
        __readFileSync: __readFileSync
      };
      var module = getNewModuleVersion(context);

      var test_module = module.require('top_module');

      expect(test_module).to.have.property('global_data', 'Hello World!');
      expect(__readFileSync.secondCall.args).to.deep.equal([ 'top_module/contract_modules/sub_module' ]);

    });

  });

});
<commit_msg>[TEST] Add more complex require test<commit_after>var chai      = require('chai');
var expect    = chai.expect;
var sinon     = require('sinon');
var sinonChai = require('sinon-chai');
chai.use(sinonChai);

var vm = require('vm');
var fs = require('fs');
var module_code = fs.readFileSync(__dirname + '/../runtime_library/module.js', { encoding: 'utf8' });

function getNewModuleVersion(context){
  vm.runInNewContext(module_code, context);
  return context;
}

describe('Runtime Library module', function(){

  describe('require', function(){

    it('should respond with an error if the identifier is neither a module, nor a javascript or JSON file', function(){
      var context = { __readFileSync: sinon.stub() };
      var module = getNewModuleVersion(context);
      expect(function(){ module.require('./test.txt'); }).to.throw(/require can only be used to load modules, javascript files, and JSON files/);
    });

    it('should call __readFileSync with the module_identifier', function(){
      var context = { __readFileSync: sinon.spy() };
      var module = getNewModuleVersion(context);
      var test_module = module.require('module_id');
      expect(context.__readFileSync).to.have.been.calledOnce;
      expect(context.__readFileSync.firstCall.args).to.deep.equal(['module_id']);
    });

    it('should eval and extract the module.exports from javascript files', function(){
      var context = { __readFileSync: sinon.stub() };
      context.__readFileSync.returns('module.exports={ global_data: "Hello World!" }');
      var module = getNewModuleVersion(context);
      var test_module = module.require('module_id');
      expect(test_module).to.have.property('global_data', 'Hello World!');
    });

    it('should parse json files', function(){
      var context = { __readFileSync: sinon.stub() };
      context.__readFileSync.returns('{"test":[1,2],"a":"b","c":{"d":-1}}');
      var module = getNewModuleVersion(context);

      var test_module = module.require('test.json');
      expect(test_module).to.deep.equal({
        test: [1, 2],
        a: 'b',
        c: { d: -1 }
      });
    });

    it('should expose a modified version of itself to submodules that translates relative paths to full paths', function(){
      var context = { __readFileSync: sinon.stub() };
      context.__readFileSync.onFirstCall().returns('module.exports = require("sub_module");');
      context.__readFileSync.onSecondCall().returns('module.exports={ global_data: "Hello World!" }');
      var module = getNewModuleVersion(context);
      var test_module = module.require('top_module');

      expect(test_module).to.have.property('global_data', 'Hello World!');
      expect(context.__readFileSync.secondCall.args).to.deep.equal([ 'top_module/contract_modules/sub_module' ]);
    });

    it.only('should call __readFileSync with full paths that are normalizeable by the Node.js path module', function(){
      var context = { __readFileSync: sinon.stub(), console: { log: console.log } };
      context.__readFileSync.onFirstCall().returns('require("sub_module");');
      context.__readFileSync.onSecondCall().returns('require("./contract_modules/sub_sub_module/somefile.js");');
      // context.__readFileSync.onThirdCall().returns('module.exports={ global_data: "Hello World!" }');
      var module = getNewModuleVersion(context);
      var test_module = module.require('top_module');

      expect(context.__readFileSync.thirdCall.args).to.deep.equal([ 'top_module/contract_modules/sub_module/contract_modules/sub_sub_module/somefile.js' ]);
    });

  });

});
<|endoftext|>


<commit_before>var carto = require('../../../../src/api/v4');

describe('api/v4/layer', function () {
  var source;
  var style;

  beforeEach(function () {
    source = new carto.source.Dataset('ne_10m_populated_places_simple');
    style = new carto.style.CartoCSS(`#layer {  marker-fill: red; }`);
  });

  describe('constructor', function () {
    it('should build a new Layer params: (source, style)', function () {
      var layer = new carto.layer.Layer(source, style);

      expect(layer.getSource()).toEqual(source);
      expect(layer.getStyle()).toEqual(style);
    });

    it('should assign a unique layer ID string', function () {
      var layer1 = new carto.layer.Layer(source, style);
      var layer2 = new carto.layer.Layer(source, style);

      var id1 = layer1.getId();
      var id2 = layer2.getId();

      expect(id1).toMatch(/L\d+/);
      expect(id2).toMatch(/L\d+/);
      expect(id1).not.toEqual(id2);
    });

    it('should build a new Layer params: (source, style, options)', function () {
      var layer = new carto.layer.Layer(source, style, {
        featureClickColumns: [ 'a', 'b' ],
        featureOverColumns: [ 'c', 'd' ]
      });

      expect(layer.getSource()).toEqual(source);
      expect(layer.getStyle()).toEqual(style);
      expect(layer.getFeatureClickColumns()).toEqual([ 'a', 'b' ]);
      expect(layer.getFeatureOverColumns()).toEqual([ 'c', 'd' ]);
    });
  });

  describe('setSource', function () {
    describe('when the layer has not been instantiated', function () {
      it('should normally add the source', function () {
        var layer = new carto.layer.Layer(source, style);
        var source1 = new carto.source.SQL('SELECT * ne_10m_populated_places_simple LIMIT 10');

        layer.setSource(source1);

        expect(layer.getSource()).toEqual(source1);
      });
    });

    describe('when the layer has been instnatiated', function () {
      describe('when the source has no engine', function () {
        it('should normally add the source', function () { });
      });
      describe('when the source has an engine', function () {
        it('should add the source if the engines are the same', function () { });
        it('should throw an error if the engines are different', function () { });
      });
    });
  });
});
<commit_msg>WIP setSource tests<commit_after>var carto = require('../../../../src/api/v4');

describe('api/v4/layer', function () {
  var source;
  var style;

  beforeEach(function () {
    source = new carto.source.Dataset('ne_10m_populated_places_simple');
    style = new carto.style.CartoCSS(`#layer {  marker-fill: red; }`);
  });

  describe('constructor', function () {
    it('should build a new Layer params: (source, style)', function () {
      var layer = new carto.layer.Layer(source, style);

      expect(layer.getSource()).toEqual(source);
      expect(layer.getStyle()).toEqual(style);
    });

    it('should assign a unique layer ID string', function () {
      var layer1 = new carto.layer.Layer(source, style);
      var layer2 = new carto.layer.Layer(source, style);

      var id1 = layer1.getId();
      var id2 = layer2.getId();

      expect(id1).toMatch(/L\d+/);
      expect(id2).toMatch(/L\d+/);
      expect(id1).not.toEqual(id2);
    });

    it('should build a new Layer params: (source, style, options)', function () {
      var layer = new carto.layer.Layer(source, style, {
        featureClickColumns: [ 'a', 'b' ],
        featureOverColumns: [ 'c', 'd' ]
      });

      expect(layer.getSource()).toEqual(source);
      expect(layer.getStyle()).toEqual(style);
      expect(layer.getFeatureClickColumns()).toEqual([ 'a', 'b' ]);
      expect(layer.getFeatureOverColumns()).toEqual([ 'c', 'd' ]);
    });
  });

  describe('.setSource', function () {
    var layer;
    var newSource;

    beforeEach(function () {
      layer = new carto.layer.Layer(source, style);
      newSource = new carto.source.SQL('SELECT * FROM ne_10m_populated_places_simple LIMIT 10');
    });

    describe("when the layer hasn't been set an engine", function () {
      it('should normally add the source', function () {
        layer.setSource(newSource);

        expect(layer.getSource()).toEqual(newSource);
      });
    });

    describe('when the layer has been set an engine', function () {
      beforeEach(function () {
        layer.$setEngine({ on: function () {}, reload: function () {} });
      });

      describe('when the source has no engine', function () {
        it('should normally add the source', function () {
          layer.setSource(newSource);

          var actualSource = layer.$getInternalModel().get('source');
          var expectedSource = newSource.$getInternalModel();
          expect(actualSource).toEqual(expectedSource);
        });
      });

      describe('when the source has an engine', function () {
        it('should add the source if the engines are the same', function () { });
        it('should throw an error if the engines are different', function () { });
      });
    });
  });
});
<|endoftext|>


<commit_before>describe('navbarDirective', function() {
  describe('ios', function() {
    var element, scope, state, ctrl, timeout, title

    beforeEach(module('bp'))

    beforeEach(module(function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/first')
      $stateProvider.state('first', {
        url: '/first',
        data: {
          up: 'second'
        }
      }).state('second', {
        url: '/second'
      }).state('third', {
        url: '/third',
        data: {
          up: 'first({foo: 1})'
        }
      })

    }))

    beforeEach(inject(function($rootScope, $compile, $state, $timeout) {
      scope = $rootScope.$new()
      state = $state
      timeout = $timeout
      state.transitionTo('first')
      timeout.flush()
      element = $compile('<bp-navbar> <bp-action>Action</bp-action> </bp-navbar>')(scope)
      title = element.find('bp-navbar-title')
      ctrl = element.controller('bpNavbar')
      scope.$apply()
    }))

    describe('controller', function() {
      it('should getTitleFromState', function() {
        var stateTitle = ctrl.getTitleFromState({
          data: {
            title: 'Foo'
          }
        })
        expect(stateTitle).toBe('Foo')
        stateTitle = ctrl.getTitleFromState({
          name: 'Bar'
        })
        expect(stateTitle).toBe('Bar')
        stateTitle = ctrl.getTitleFromState({
          name: 'Buz',
          data: {
            title: 'Baz'
          }
        })
        expect(stateTitle).toBe('Baz')
      })

      it('should convertActionToIcon', function() {
        var $action = angular.element('<bp-action class="bp-button">Yo</bp-action>')
        ctrl.convertActionToIcon($action)
        expect($action.text()).toBe('')
        expect($action.hasClass('bp-button')).toBe(false)
        expect($action.hasClass('bp-icon')).toBe(true)
        expect($action.attr('aria-label')).toBe('Yo')
      })
    })

    describe('element', function() {
      it('should have ARIA role', function() {
        expect(element.attr('role')).toBe('navigation')
        expect(title.attr('role')).toBe('heading')
      })

      it('should apply title', function() {
        expect(title.text()).toBe('First')
      })

      it('should place up button', function() {
        var $up = element.find('.bp-action-up')
        expect($up.text()).toBe('Second')
      })

      it('should apply buttons', function() {
        expect(element.find('bp-action').hasClass('bp-button')).toBe(true)
        expect(element.children().length).toBe(4)
      })

      it('should calculate center', function() {
        angular.element('body').append(element)
        timeout.flush()
        expect(element.children().length).toBe(5)
        var $spacer = element.find('div')
        expect($spacer.attr('style')).toMatch(/width/)
        expect($spacer.attr('style')).toMatch(/flex/)
        expect(element.children().get(2)).toBe($spacer.get(0))
        element.detach()
      })

      it('should allow icons in navbar', inject(function($compile) {
        var element2 = $compile('<bp-navbar bp-navbar-no-up bp-navbar-title> <bp-action class="bp-icon">Action</bp-action> </bp-navbar>')(scope)
        var $icon = element2.find('bp-action')
        expect($icon.hasClass('bp-button')).toBe(false)
        expect($icon.hasClass('bp-icon')).toBe(true)
        expect($icon.attr('aria-label')).toBe('Action')
      }))

      it('should spawn toolbar', inject(function($compile) {
        var element3 = $compile('<bp-navbar> <bp-action>First</bp-action> <bp-action>Second</bp-action> <bp-action>Third</bp-action> </bp-navbar>')(scope)
        expect(element3.next().is('bp-toolbar')).toBe(true)
        expect(element3.next().children().length).toBe(3)
      }))

      it('should remove toolbar on destroy', inject(function($compile) {
        var element4 = angular.element('<bp-navbar> <bp-action>First</bp-action> <bp-action>Second</bp-action> <bp-action>Third</bp-action> </bp-navbar>')
        angular.element('body').append(element4)
        $compile(element4)(scope)
        expect($.contains(document, element4.next().get(0))).toBe(true)
        element4.trigger('$destroy')
        expect($.contains(document, element4.next().get(0))).toBe(false)
      }))

      it('should parse state params from up', inject(function($compile) {
        state.go('third')
        timeout.flush()
        var element5 = $compile(angular.element('<bp-navbar>'))(scope)
        var $up = element5.find('.bp-action-up')

        expect($up.text()).toBe('First')
        expect($up.attr('bp-sref')).toBe('first({foo: 1})')
      }))
    })
  })
  describe('android', function() {
    var compile, element, scope, state, timeout

    beforeEach(module('bp', function(bpConfigProvider) {
      bpConfigProvider.setConfig({
        platform: 'android'
      })
    }))

    beforeEach(module(function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/first')
      $stateProvider.state('first', {
        url: '/first',
        data: {
          up: 'second'
        }
      }).state('second', {
        url: '/second'
      })
    }))

    beforeEach(inject(function($rootScope, $compile, $state, $timeout) {
      compile = $compile
      scope = $rootScope.$new()
      state = $state
      timeout = $timeout
      state.transitionTo('first')
      timeout.flush()
      element = $compile('<bp-navbar> <bp-action>Action</bp-action> </bp-navbar>')(scope)
      scope.$apply()
    }))

    describe('element', function() {
      it('should apply icons', function() {
        var $icons = element.find('.bp-icon')
        expect($icons.length).toBe(2)
        expect($icons.eq(1).attr('aria-label')).toBe('Action')
        expect(element.find('.bp-action-up').length).toBe(1)
        expect(element.children().length).toBe(3)
        expect(element.find('bp-navbar-icon').length).toBe(1)
      })

      it('should handle navbar icons', function() {
        state.transitionTo('second')
        timeout.flush()
        var element2 = compile('<bp-navbar> <bp-action>Action</bp-action> </bp-navbar>')(scope)
        expect(element2.children().length).toBe(3)
        expect(element2.find('bp-navbar-icon').length).toBe(1)
      })

      it('should spawn action overflow', function() {
        var element3 = compile('<bp-navbar> <bp-action>First</bp-action> <bp-action>Second</bp-action> <bp-action>Third</bp-action> </bp-navbar>')(scope)
        expect(element3.children().length).toBe(5)
        expect(element3.find('bp-action-overflow').length).toBe(1)
      })
    })
  })
})
<commit_msg>test(navbar): read up state from url<commit_after>describe('navbarDirective', function() {
  describe('ios', function() {
    var element, scope, state, ctrl, timeout, title

    beforeEach(module('bp'))

    beforeEach(module(function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/first')
      $stateProvider.state('first', {
        url: '/first',
        data: {
          up: 'second'
        }
      }).state('second', {
        url: '/first/second'
      }).state('third', {
        url: '/third',
        data: {
          up: 'first({foo: 1})'
        }
      })

    }))

    beforeEach(inject(function($rootScope, $compile, $state, $timeout) {
      scope = $rootScope.$new()
      state = $state
      timeout = $timeout
      state.transitionTo('first')
      timeout.flush()
      element = $compile('<bp-navbar> <bp-action>Action</bp-action> </bp-navbar>')(scope)
      title = element.find('bp-navbar-title')
      ctrl = element.controller('bpNavbar')
      scope.$apply()
    }))

    describe('controller', function() {
      it('should getTitleFromState', function() {
        var stateTitle = ctrl.getTitleFromState({
          data: {
            title: 'Foo'
          }
        })
        expect(stateTitle).toBe('Foo')
        stateTitle = ctrl.getTitleFromState({
          name: 'Bar'
        })
        expect(stateTitle).toBe('Bar')
        stateTitle = ctrl.getTitleFromState({
          name: 'Buz',
          data: {
            title: 'Baz'
          }
        })
        expect(stateTitle).toBe('Baz')
      })

      it('should convertActionToIcon', function() {
        var $action = angular.element('<bp-action class="bp-button">Yo</bp-action>')
        ctrl.convertActionToIcon($action)
        expect($action.text()).toBe('')
        expect($action.hasClass('bp-button')).toBe(false)
        expect($action.hasClass('bp-icon')).toBe(true)
        expect($action.attr('aria-label')).toBe('Yo')
      })
    })

    describe('element', function() {
      it('should have ARIA role', function() {
        expect(element.attr('role')).toBe('navigation')
        expect(title.attr('role')).toBe('heading')
      })

      it('should apply title', function() {
        expect(title.text()).toBe('First')
      })

      it('should place up button', function() {
        var $up = element.find('.bp-action-up')
        expect($up.text()).toBe('Second')
      })

      it('should apply buttons', function() {
        expect(element.find('bp-action').hasClass('bp-button')).toBe(true)
        expect(element.children().length).toBe(4)
      })

      it('should calculate center', function() {
        angular.element('body').append(element)
        timeout.flush()
        expect(element.children().length).toBe(5)
        var $spacer = element.find('div')
        expect($spacer.attr('style')).toMatch(/width/)
        expect($spacer.attr('style')).toMatch(/flex/)
        expect(element.children().get(2)).toBe($spacer.get(0))
        element.detach()
      })

      it('should allow icons in navbar', inject(function($compile) {
        var element2 = $compile('<bp-navbar bp-navbar-no-up bp-navbar-title> <bp-action class="bp-icon">Action</bp-action> </bp-navbar>')(scope)
        var $icon = element2.find('bp-action')
        expect($icon.hasClass('bp-button')).toBe(false)
        expect($icon.hasClass('bp-icon')).toBe(true)
        expect($icon.attr('aria-label')).toBe('Action')
      }))

      it('should spawn toolbar', inject(function($compile) {
        var element3 = $compile('<bp-navbar> <bp-action>First</bp-action> <bp-action>Second</bp-action> <bp-action>Third</bp-action> </bp-navbar>')(scope)
        expect(element3.next().is('bp-toolbar')).toBe(true)
        expect(element3.next().children().length).toBe(3)
      }))

      it('should remove toolbar on destroy', inject(function($compile) {
        var element4 = angular.element('<bp-navbar> <bp-action>First</bp-action> <bp-action>Second</bp-action> <bp-action>Third</bp-action> </bp-navbar>')
        angular.element('body').append(element4)
        $compile(element4)(scope)
        expect($.contains(document, element4.next().get(0))).toBe(true)
        element4.trigger('$destroy')
        expect($.contains(document, element4.next().get(0))).toBe(false)
      }))

      it('should parse state up (w/ params)', inject(function($compile) {
        state.go('third')
        timeout.flush()
        var element5 = $compile(angular.element('<bp-navbar>'))(scope)
        var $up = element5.find('.bp-action-up')

        expect($up.text()).toBe('First')
        expect($up.attr('bp-sref')).toBe('first({foo: 1})')
        state.go('second')
        timeout.flush()
        var element6 = $compile(angular.element('<bp-navbar>'))(scope)
        $up = element6.find('.bp-action-up')

        expect($up.text()).toBe('First')
        expect($up.attr('bp-sref')).toBe('first')

      }))
    })
  })
  describe('android', function() {
    var compile, element, scope, state, timeout

    beforeEach(module('bp', function(bpConfigProvider) {
      bpConfigProvider.setConfig({
        platform: 'android'
      })
    }))

    beforeEach(module(function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/first')
      $stateProvider.state('first', {
        url: '/first',
        data: {
          up: 'second'
        }
      }).state('second', {
        url: '/second'
      })
    }))

    beforeEach(inject(function($rootScope, $compile, $state, $timeout) {
      compile = $compile
      scope = $rootScope.$new()
      state = $state
      timeout = $timeout
      state.transitionTo('first')
      timeout.flush()
      element = $compile('<bp-navbar> <bp-action>Action</bp-action> </bp-navbar>')(scope)
      scope.$apply()
    }))

    describe('element', function() {
      it('should apply icons', function() {
        var $icons = element.find('.bp-icon')
        expect($icons.length).toBe(2)
        expect($icons.eq(1).attr('aria-label')).toBe('Action')
        expect(element.find('.bp-action-up').length).toBe(1)
        expect(element.children().length).toBe(3)
        expect(element.find('bp-navbar-icon').length).toBe(1)
      })

      it('should handle navbar icons', function() {
        state.transitionTo('second')
        timeout.flush()
        var element2 = compile('<bp-navbar> <bp-action>Action</bp-action> </bp-navbar>')(scope)
        expect(element2.children().length).toBe(3)
        expect(element2.find('bp-navbar-icon').length).toBe(1)
      })

      it('should spawn action overflow', function() {
        var element3 = compile('<bp-navbar> <bp-action>First</bp-action> <bp-action>Second</bp-action> <bp-action>Third</bp-action> </bp-navbar>')(scope)
        expect(element3.children().length).toBe(5)
        expect(element3.find('bp-action-overflow').length).toBe(1)
      })
    })
  })
})
<|endoftext|>


<commit_before>

goog.require('ol.ImageTile');
goog.require('ol.Tile');
goog.require('ol.TileQueue');
goog.require('ol.TileState');
goog.require('ol.source.Image');
goog.require('ol.structs.PriorityQueue');

describe('ol.TileQueue', function() {

  function addRandomPriorityTiles(tq, num) {
    var i, tile, priority;
    for (i = 0; i < num; i++) {
      tile = new ol.Tile();
      priority = Math.floor(Math.random() * 100);
      tq.elements_.push([tile, '', [0, 0]]);
      tq.priorities_.push(priority);
      tq.queuedElements_[tile.getKey()] = true;
    }
  }

  var tileId = 0;
  function createImageTile(opt_tileLoadFunction) {
    ++tileId;
    var tileCoord = [tileId, tileId, tileId];
    var state = 0; // IDLE
    var src = 'data:image/gif;base64,R0lGODlhAQABAPAAAP8AAP///' +
        'yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==#' + tileId;

    var tileLoadFunction = opt_tileLoadFunction ?
      opt_tileLoadFunction : ol.source.Image.defaultImageLoadFunction;
    return new ol.ImageTile(tileCoord, state, src, null, tileLoadFunction);
  }

  describe('#loadMoreTiles()', function() {
    var noop = function() {};

    it('works when tile queues share tiles', function(done) {
      var q1 = new ol.TileQueue(noop, noop);
      var q2 = new ol.TileQueue(noop, noop);

      var numTiles = 20;
      for (var i = 0; i < numTiles; ++i) {
        var tile = createImageTile();
        q1.enqueue([tile]);
        q2.enqueue([tile]);
      }

      // Initially, both have all tiles.
      expect(q1.getCount()).to.equal(numTiles);
      expect(q2.getCount()).to.equal(numTiles);

      var maxLoading = numTiles / 2;

      // and nothing is loading
      expect(q1.getTilesLoading()).to.equal(0);
      expect(q2.getTilesLoading()).to.equal(0);

      // ask both to load
      q1.loadMoreTiles(maxLoading, maxLoading);
      q2.loadMoreTiles(maxLoading, maxLoading);

      // both tiles will be loading the max
      expect(q1.getTilesLoading()).to.equal(maxLoading);
      expect(q2.getTilesLoading()).to.equal(maxLoading);

      // the second queue will be empty now
      expect(q1.getCount()).to.equal(numTiles - maxLoading);
      expect(q2.getCount()).to.equal(0);

      // let all tiles load
      setTimeout(function() {
        expect(q1.getTilesLoading()).to.equal(0);
        expect(q2.getTilesLoading()).to.equal(0);

        // ask both to load, this should clear q1
        q1.loadMoreTiles(maxLoading, maxLoading);
        q2.loadMoreTiles(maxLoading, maxLoading);

        expect(q1.getCount()).to.equal(0);
        expect(q2.getCount()).to.equal(0);

        done();
      }, 20);

    });

    it('calls #tileChangeCallback_ when all wanted tiles are aborted', function() {
      var tileChangeCallback = sinon.spy();
      var queue = new ol.TileQueue(noop, tileChangeCallback);
      var numTiles = 20;
      for (var i = 0; i < numTiles; ++i) {
        var tile = createImageTile();
        tile.state = ol.TileState.ABORT;
        queue.enqueue([tile]);
      }
      var maxLoading = numTiles / 2;
      queue.loadMoreTiles(maxLoading, maxLoading);
      expect(tileChangeCallback.callCount).to.be(1);
    });

  });

  describe('heapify', function() {
    it('does convert an arbitrary array into a heap', function() {

      var tq = new ol.TileQueue(function() {});
      addRandomPriorityTiles(tq, 100);

      tq.heapify_();
    });
  });

  describe('reprioritize', function() {
    it('does reprioritize the array', function() {

      var tq = new ol.TileQueue(function() {});
      addRandomPriorityTiles(tq, 100);

      tq.heapify_();

      // now reprioritize, changing the priority of 50 tiles and removing the
      // rest

      var i = 0;
      tq.priorityFunction_ = function() {
        if ((i++) % 2 === 0) {
          return ol.structs.PriorityQueue.DROP;
        }
        return Math.floor(Math.random() * 100);
      };

      tq.reprioritize();
      expect(tq.elements_.length).to.eql(50);
      expect(tq.priorities_.length).to.eql(50);

    });
  });

  describe('tile change event', function() {
    var noop = function() {};

    it('abort queued tiles', function() {
      var tq = new ol.TileQueue(noop, noop);
      var tile = createImageTile();
      expect(tile.hasListener('change')).to.be(false);

      tq.enqueue([tile]);
      expect(tile.hasListener('change')).to.be(true);

      tile.dispose();
      expect(tile.hasListener('change')).to.be(false);
      expect(tile.getState()).to.eql(5); // ABORT
    });

    it('abort loading tiles', function() {
      var tq = new ol.TileQueue(noop, noop);
      var tile = createImageTile(noop);

      tq.enqueue([tile]);
      tq.loadMoreTiles(Infinity, Infinity);
      expect(tq.getTilesLoading()).to.eql(1);
      expect(tile.getState()).to.eql(1); // LOADING

      tile.dispose();
      expect(tq.getTilesLoading()).to.eql(0);
      expect(tile.hasListener('change')).to.be(false);
      expect(tile.getState()).to.eql(5); // ABORT

    });

  });

});
<commit_msg>Valid and unique URI for images in the tile queue<commit_after>

goog.require('ol.ImageTile');
goog.require('ol.Tile');
goog.require('ol.TileQueue');
goog.require('ol.TileState');
goog.require('ol.source.Image');
goog.require('ol.structs.PriorityQueue');

describe('ol.TileQueue', function() {

  function addRandomPriorityTiles(tq, num) {
    var i, tile, priority;
    for (i = 0; i < num; i++) {
      tile = new ol.Tile();
      priority = Math.floor(Math.random() * 100);
      tq.elements_.push([tile, '', [0, 0]]);
      tq.priorities_.push(priority);
      tq.queuedElements_[tile.getKey()] = true;
    }
  }

  var tileId = 0;
  function createImageTile(opt_tileLoadFunction) {
    ++tileId;
    var tileCoord = [tileId, tileId, tileId];
    var state = 0; // IDLE
    // The tile queue requires a unique URI for each item added.
    // Browsers still load the resource even if they don't understand
    // the charset.  So we create a unique URI by abusing the charset.
    var src = 'data:image/gif;charset=junk-' + tileId +
        ';base64,R0lGODlhAQABAPAAAP8AAP///' +
        'yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';

    var tileLoadFunction = opt_tileLoadFunction ?
      opt_tileLoadFunction : ol.source.Image.defaultImageLoadFunction;
    return new ol.ImageTile(tileCoord, state, src, null, tileLoadFunction);
  }

  describe('#loadMoreTiles()', function() {
    var noop = function() {};

    it('works when tile queues share tiles', function(done) {
      var q1 = new ol.TileQueue(noop, noop);
      var q2 = new ol.TileQueue(noop, noop);

      var numTiles = 20;
      for (var i = 0; i < numTiles; ++i) {
        var tile = createImageTile();
        q1.enqueue([tile]);
        q2.enqueue([tile]);
      }

      // Initially, both have all tiles.
      expect(q1.getCount()).to.equal(numTiles);
      expect(q2.getCount()).to.equal(numTiles);

      var maxLoading = numTiles / 2;

      // and nothing is loading
      expect(q1.getTilesLoading()).to.equal(0);
      expect(q2.getTilesLoading()).to.equal(0);

      // ask both to load
      q1.loadMoreTiles(maxLoading, maxLoading);
      q2.loadMoreTiles(maxLoading, maxLoading);

      // both tiles will be loading the max
      expect(q1.getTilesLoading()).to.equal(maxLoading);
      expect(q2.getTilesLoading()).to.equal(maxLoading);

      // the second queue will be empty now
      expect(q1.getCount()).to.equal(numTiles - maxLoading);
      expect(q2.getCount()).to.equal(0);

      // let all tiles load
      setTimeout(function() {
        expect(q1.getTilesLoading()).to.equal(0);
        expect(q2.getTilesLoading()).to.equal(0);

        // ask both to load, this should clear q1
        q1.loadMoreTiles(maxLoading, maxLoading);
        q2.loadMoreTiles(maxLoading, maxLoading);

        expect(q1.getCount()).to.equal(0);
        expect(q2.getCount()).to.equal(0);

        done();
      }, 20);

    });

    it('calls #tileChangeCallback_ when all wanted tiles are aborted', function() {
      var tileChangeCallback = sinon.spy();
      var queue = new ol.TileQueue(noop, tileChangeCallback);
      var numTiles = 20;
      for (var i = 0; i < numTiles; ++i) {
        var tile = createImageTile();
        tile.state = ol.TileState.ABORT;
        queue.enqueue([tile]);
      }
      var maxLoading = numTiles / 2;
      queue.loadMoreTiles(maxLoading, maxLoading);
      expect(tileChangeCallback.callCount).to.be(1);
    });

  });

  describe('heapify', function() {
    it('does convert an arbitrary array into a heap', function() {

      var tq = new ol.TileQueue(function() {});
      addRandomPriorityTiles(tq, 100);

      tq.heapify_();
    });
  });

  describe('reprioritize', function() {
    it('does reprioritize the array', function() {

      var tq = new ol.TileQueue(function() {});
      addRandomPriorityTiles(tq, 100);

      tq.heapify_();

      // now reprioritize, changing the priority of 50 tiles and removing the
      // rest

      var i = 0;
      tq.priorityFunction_ = function() {
        if ((i++) % 2 === 0) {
          return ol.structs.PriorityQueue.DROP;
        }
        return Math.floor(Math.random() * 100);
      };

      tq.reprioritize();
      expect(tq.elements_.length).to.eql(50);
      expect(tq.priorities_.length).to.eql(50);

    });
  });

  describe('tile change event', function() {
    var noop = function() {};

    it('abort queued tiles', function() {
      var tq = new ol.TileQueue(noop, noop);
      var tile = createImageTile();
      expect(tile.hasListener('change')).to.be(false);

      tq.enqueue([tile]);
      expect(tile.hasListener('change')).to.be(true);

      tile.dispose();
      expect(tile.hasListener('change')).to.be(false);
      expect(tile.getState()).to.eql(5); // ABORT
    });

    it('abort loading tiles', function() {
      var tq = new ol.TileQueue(noop, noop);
      var tile = createImageTile(noop);

      tq.enqueue([tile]);
      tq.loadMoreTiles(Infinity, Infinity);
      expect(tq.getTilesLoading()).to.eql(1);
      expect(tile.getState()).to.eql(1); // LOADING

      tile.dispose();
      expect(tq.getTilesLoading()).to.eql(0);
      expect(tile.hasListener('change')).to.be(false);
      expect(tile.getState()).to.eql(5); // ABORT

    });

  });

});
<|endoftext|>


<commit_before>/*jshint loopfunc: true */

var expect = require('chai').expect;
var exec = require('child_process').exec;
var fs = require('fs');

var mergeCoverageData = function(data) {
  // we have to reconstruct the the _$jscoverage data
  // format as it cannot be stringified to JSON with
  // the additional source property added to arrays
  if (typeof global._$jscoverage === 'undefined') {
    global._$jscoverage = {};
  }
  var jscoverage = global._$jscoverage;
  var sourceArrays = data.sourceArrays;
  var callCounts = data.callCounts;
  for (var filename in sourceArrays) {
    var dest = jscoverage[filename];
    var src = callCounts[filename];
    src.source = sourceArrays[filename];
    if (typeof dest === 'undefined') {
      jscoverage[filename] = src;
    } else {
      src.forEach(function(count, index) {
        if (count !== null) {
          dest[index] += count;
        }
      });
    }
  }
};

var execScenario = function(scenario, callback) {
  var scenarioDir = __dirname + '/../scenarios/' + scenario;
  var child = exec('node ../grunt.js', {cwd: scenarioDir}, function(error, stdout, stderr) {
    // collect coverage data from file if it exists
    // this is because the coverage tool does not
    // really work with child processes so we are
    // giving it a helping hand
    var jscoverageFile = scenarioDir + '/jscoverage.json';
    if (fs.existsSync(jscoverageFile)) {
      mergeCoverageData(JSON.parse(fs.readFileSync(jscoverageFile)));
    }
    callback(error, stdout, stderr);
  });
};

describe('grunt-mocha-test', function() {
  it('should run tests from the supplied files', function(done) {
    execScenario('tests', function(error, stdout, stderr) {
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should run tests from the supplied files with expand option', function(done) {
    execScenario('testsExpand', function(error, stdout, stderr) {
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should report the number of test failures and exit grunt with an error on failed tests', function(done) {
    execScenario('testFailure', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      done();
    });
  });

  it('should cleanly catch asynchronous test failures so that grunt does not exit early', function(done) {
    execScenario('asyncTestFailure', function(error, stdout, stderr) {
      expect(stdout).to.match(/Asynchronous test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      done();
    });
  });

  it('should cleanly catch and log require exceptions thrown synchronously by Mocha so that grunt does not exit early', function(done) {
    execScenario('requireFailure', function(error, stdout, stderr) {
      expect(stdout).to.match(/Cannot find module 'doesNotExist/);
      expect(stdout).to.match(/test.js/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should cleanly catch and log net connect exceptions thrown asynchronously by Mocha so that grunt does not exit early', function(done) {
    execScenario('connectFailure', function(error, stdout, stderr) {
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      done();
    });
  });

  it('should cleanly catch and log exceptions thrown asynchronously by tests that have a before that starts an HTTP server', function(done) {
    execScenario('asyncFailureWithBefore', function(error, stdout, stderr) {
      expect(stdout).to.match(/async tests/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      done();
    });
  });

  it('should support the require option', function(done) {
    execScenario('requireOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the colors option', function(done) {
    execScenario('colorsOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/\u001b\[4mRunning \"mochaTest:all\" \(mochaTest\) task\u001b\[24m\n\n\n  test\n    ◦ should be ok: \n    ✓ should be ok \n\n\n  1 passing/);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the require option with arrays', function(done) {
    execScenario('requireArrayOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the require option with coffee-script', function(done) {
    execScenario('requireCompilersOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test coffee-script/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the clearRequireCacheOption', function(done) {
    execScenario('clearRequireCacheOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/mochaTest:on/);
      expect(stdout).to.match(/mochaTest:off/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).not.to.match(/0 passing/);
      expect(stdout).not.to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the clearRequireCacheOption with the require option', function(done) {
    execScenario('clearRequireCacheAndRequireOptions', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the grep option', function(done) {
    execScenario('grepOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/tests that match grep/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the invert option', function(done) {
    execScenario('invertOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/tests that don't match grep/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the ignoreLeaks option', function(done) {
    execScenario('ignoreLeaksOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      expect(stderr).to.match(/Error: global leak detected: leak/);
      done();
    });
  });

  it('should support the globals option', function(done) {
    execScenario('globalsOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the asyncOnly option', function(done) {
    execScenario('asyncOnlyOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      expect(stderr).to.match(/Error: --async-only option in use without declaring/);
      done();
    });
  });

  it('should support the reporter option', function(done) {
    execScenario('reporterOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/<section class="suite">/);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the ui option', function(done) {
    execScenario('uiOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support using a custom ui option', function(done) {
    execScenario('uiOptionCustom', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the timeout option', function(done) {
    execScenario('timeoutOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      expect(stderr).to.match(/Error: timeout of 500ms exceeded/);
      done();
    });
  });

  it('should support the growl option', function(done) {
    execScenario('growlOption', function(error, stdout, stderr) {
      // TODO: Let's just test that everything completed successfully
      // as there's no way of knowing if growl was actually called for now.
      // A possible option would be to mock the growl binaries in the
      // growlOption scenario directory and have them do something that
      // the test can detect (HTTP server/request?). This would have to
      // be done for each platform though.
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support a destination file to write output', function(done) {
    var destinationFile = __dirname + '/../scenarios/destinationFile/output';

    // first remove the destination file
    if (fs.existsSync(destinationFile)) {
      fs.unlinkSync(destinationFile);
    }

    execScenario('destinationFile', function(error, stdout, stderr) {
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');

      // now read the destination file
      var output = fs.readFileSync(destinationFile, 'utf8');
      expect(output).to.match(/test1/);
      expect(output).to.match(/test2/);
      expect(output).to.match(/2 passing/);

      done();
    });
  });

  it('should support the quiet option', function(done) {
    var destinationFile = __dirname + '/../scenarios/quietOption/output';

    // first remove the destination file
    if (fs.existsSync(destinationFile)) {
      fs.unlinkSync(destinationFile);
    }

    execScenario('quietOption', function(error, stdout, stderr) {
      expect(stdout).to.not.match(/test1/);
      expect(stdout).to.not.match(/test2/);
      expect(stdout).to.not.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');

      // now read the destination file
      var output = fs.readFileSync(destinationFile, 'utf8');
      expect(output).to.match(/test1/);
      expect(output).to.match(/test2/);
      expect(output).to.match(/2 passing/);

      done();
    });
  });

  it('should support the mocha option', function(done) {
    var destinationFile = __dirname + '/../scenarios/mochaOption/output';

    // first remove the destination file
    if (fs.existsSync(destinationFile)) {
      fs.unlinkSync(destinationFile);
    }

    execScenario('mochaOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/Custom Mocha constructor/);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should not run if the src config do not match any files', function(done) {
    execScenario('noFiles', function(error, stdout, stderr) {
      console.log(stdout);
      console.log(stderr);
      expect(stdout).to.match(/No files to check.../);
      expect(stdout).to.match(/Done, without errors./);
      expect(stdout).not.to.match(/0 passing/);
      expect(stderr).to.equal('');
      done();
    });
  });
});
<commit_msg>removing extra logging<commit_after>/*jshint loopfunc: true */

var expect = require('chai').expect;
var exec = require('child_process').exec;
var fs = require('fs');

var mergeCoverageData = function(data) {
  // we have to reconstruct the the _$jscoverage data
  // format as it cannot be stringified to JSON with
  // the additional source property added to arrays
  if (typeof global._$jscoverage === 'undefined') {
    global._$jscoverage = {};
  }
  var jscoverage = global._$jscoverage;
  var sourceArrays = data.sourceArrays;
  var callCounts = data.callCounts;
  for (var filename in sourceArrays) {
    var dest = jscoverage[filename];
    var src = callCounts[filename];
    src.source = sourceArrays[filename];
    if (typeof dest === 'undefined') {
      jscoverage[filename] = src;
    } else {
      src.forEach(function(count, index) {
        if (count !== null) {
          dest[index] += count;
        }
      });
    }
  }
};

var execScenario = function(scenario, callback) {
  var scenarioDir = __dirname + '/../scenarios/' + scenario;
  var child = exec('node ../grunt.js', {cwd: scenarioDir}, function(error, stdout, stderr) {
    // collect coverage data from file if it exists
    // this is because the coverage tool does not
    // really work with child processes so we are
    // giving it a helping hand
    var jscoverageFile = scenarioDir + '/jscoverage.json';
    if (fs.existsSync(jscoverageFile)) {
      mergeCoverageData(JSON.parse(fs.readFileSync(jscoverageFile)));
    }
    callback(error, stdout, stderr);
  });
};

describe('grunt-mocha-test', function() {
  it('should run tests from the supplied files', function(done) {
    execScenario('tests', function(error, stdout, stderr) {
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should run tests from the supplied files with expand option', function(done) {
    execScenario('testsExpand', function(error, stdout, stderr) {
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should report the number of test failures and exit grunt with an error on failed tests', function(done) {
    execScenario('testFailure', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      done();
    });
  });

  it('should cleanly catch asynchronous test failures so that grunt does not exit early', function(done) {
    execScenario('asyncTestFailure', function(error, stdout, stderr) {
      expect(stdout).to.match(/Asynchronous test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      done();
    });
  });

  it('should cleanly catch and log require exceptions thrown synchronously by Mocha so that grunt does not exit early', function(done) {
    execScenario('requireFailure', function(error, stdout, stderr) {
      expect(stdout).to.match(/Cannot find module 'doesNotExist/);
      expect(stdout).to.match(/test.js/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should cleanly catch and log net connect exceptions thrown asynchronously by Mocha so that grunt does not exit early', function(done) {
    execScenario('connectFailure', function(error, stdout, stderr) {
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      done();
    });
  });

  it('should cleanly catch and log exceptions thrown asynchronously by tests that have a before that starts an HTTP server', function(done) {
    execScenario('asyncFailureWithBefore', function(error, stdout, stderr) {
      expect(stdout).to.match(/async tests/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      done();
    });
  });

  it('should support the require option', function(done) {
    execScenario('requireOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the colors option', function(done) {
    execScenario('colorsOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/\u001b\[4mRunning \"mochaTest:all\" \(mochaTest\) task\u001b\[24m\n\n\n  test\n    ◦ should be ok: \n    ✓ should be ok \n\n\n  1 passing/);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the require option with arrays', function(done) {
    execScenario('requireArrayOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the require option with coffee-script', function(done) {
    execScenario('requireCompilersOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test coffee-script/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the clearRequireCacheOption', function(done) {
    execScenario('clearRequireCacheOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/mochaTest:on/);
      expect(stdout).to.match(/mochaTest:off/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).not.to.match(/0 passing/);
      expect(stdout).not.to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the clearRequireCacheOption with the require option', function(done) {
    execScenario('clearRequireCacheAndRequireOptions', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the grep option', function(done) {
    execScenario('grepOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/tests that match grep/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the invert option', function(done) {
    execScenario('invertOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/tests that don't match grep/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the ignoreLeaks option', function(done) {
    execScenario('ignoreLeaksOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      expect(stderr).to.match(/Error: global leak detected: leak/);
      done();
    });
  });

  it('should support the globals option', function(done) {
    execScenario('globalsOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the asyncOnly option', function(done) {
    execScenario('asyncOnlyOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      expect(stderr).to.match(/Error: --async-only option in use without declaring/);
      done();
    });
  });

  it('should support the reporter option', function(done) {
    execScenario('reporterOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/<section class="suite">/);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the ui option', function(done) {
    execScenario('uiOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support using a custom ui option', function(done) {
    execScenario('uiOptionCustom', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/1 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support the timeout option', function(done) {
    execScenario('timeoutOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/test/);
      expect(stdout).to.match(/Aborted due to warnings./);
      expect(stderr).to.match(/1 failing/);
      expect(stderr).to.match(/Error: timeout of 500ms exceeded/);
      done();
    });
  });

  it('should support the growl option', function(done) {
    execScenario('growlOption', function(error, stdout, stderr) {
      // TODO: Let's just test that everything completed successfully
      // as there's no way of knowing if growl was actually called for now.
      // A possible option would be to mock the growl binaries in the
      // growlOption scenario directory and have them do something that
      // the test can detect (HTTP server/request?). This would have to
      // be done for each platform though.
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should support a destination file to write output', function(done) {
    var destinationFile = __dirname + '/../scenarios/destinationFile/output';

    // first remove the destination file
    if (fs.existsSync(destinationFile)) {
      fs.unlinkSync(destinationFile);
    }

    execScenario('destinationFile', function(error, stdout, stderr) {
      expect(stdout).to.match(/test1/);
      expect(stdout).to.match(/test2/);
      expect(stdout).to.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');

      // now read the destination file
      var output = fs.readFileSync(destinationFile, 'utf8');
      expect(output).to.match(/test1/);
      expect(output).to.match(/test2/);
      expect(output).to.match(/2 passing/);

      done();
    });
  });

  it('should support the quiet option', function(done) {
    var destinationFile = __dirname + '/../scenarios/quietOption/output';

    // first remove the destination file
    if (fs.existsSync(destinationFile)) {
      fs.unlinkSync(destinationFile);
    }

    execScenario('quietOption', function(error, stdout, stderr) {
      expect(stdout).to.not.match(/test1/);
      expect(stdout).to.not.match(/test2/);
      expect(stdout).to.not.match(/2 passing/);
      expect(stdout).to.match(/Done, without errors./);
      expect(stderr).to.equal('');

      // now read the destination file
      var output = fs.readFileSync(destinationFile, 'utf8');
      expect(output).to.match(/test1/);
      expect(output).to.match(/test2/);
      expect(output).to.match(/2 passing/);

      done();
    });
  });

  it('should support the mocha option', function(done) {
    var destinationFile = __dirname + '/../scenarios/mochaOption/output';

    // first remove the destination file
    if (fs.existsSync(destinationFile)) {
      fs.unlinkSync(destinationFile);
    }

    execScenario('mochaOption', function(error, stdout, stderr) {
      expect(stdout).to.match(/Custom Mocha constructor/);
      expect(stderr).to.equal('');
      done();
    });
  });

  it('should not run if the src config do not match any files', function(done) {
    execScenario('noFiles', function(error, stdout, stderr) {
      expect(stdout).to.match(/No files to check.../);
      expect(stdout).to.match(/Done, without errors./);
      expect(stdout).not.to.match(/0 passing/);
      expect(stderr).to.equal('');
      done();
    });
  });
});
<|endoftext|>


<commit_before>"use strict";

var Promise = require("bluebird"),
    hotpotato = require("../hotpotato"),
    cluster = require("cluster"),
    common = require("./common");

var expect = require("chai").expect;

var bouncer = hotpotato("test", {
  strategies: ["proxying"]
});

describe("hotpotato proxy strategy", function() {
  before(function() {
    cluster.setupMaster({
      exec: __dirname + "/worker-entrypoint.js"
    });
  });

  beforeEach(function() {
    this.listenPass = common.spawn("pass", true);
    this.echo = common.spawn("echo");

    return Promise.all([
      common.waitForWorker(this.listenPass, true),
      common.waitForWorker(this.echo)
    ]);
  });

  it.only("bounces requests correctly", function() {
    var echo = this.echo;

    bouncer.router(function() {
      return echo.id;
    });

    return common.requestToWorker(this.listenPass, { path: "/passme" })
      .then(function(req) {
        req.end();

        return common.readFully(req);
      })
      .then(function(result) {
        expect(result).to.eql("worker" + echo.id);
      });
  });
});
<commit_msg>It's a test. And it's broken. Noes.<commit_after>"use strict";

var Promise = require("bluebird"),
    hotpotato = require("../hotpotato"),
    cluster = require("cluster"),
    Agent = require("yakaa"),
    common = require("./common");

var expect = require("chai").expect;

var bouncer = hotpotato("test", {
  strategies: ["proxying"]
});

var keepaliveAgent = new Agent({
  keepAlive: true,
  maxIdle: 1,
  maxSockets: 1
});

describe("hotpotato proxy strategy", function() {
  before(function() {
    cluster.setupMaster({
      exec: __dirname + "/worker-entrypoint.js"
    });
  });

  beforeEach(function() {
    this.listenPass = common.spawn("pass", true);
    this.echo = common.spawn("echo");

    return Promise.all([
      common.waitForWorker(this.listenPass, true),
      common.waitForWorker(this.echo)
    ]);
  });

  it.only("bounces requests correctly", function() {
    var echo = this.echo;

    bouncer.router(function() {
      return echo.id;
    });

    return common.requestToWorker(this.listenPass, { path: "/passme" })
      .then(function(req) {
        req.end();

        return common.readFully(req);
      })
      .then(function(result) {
        expect(result).to.eql("worker" + echo.id);
      });
  });

  it.only("bounces connections correctly", function() {
    var self = this;

    bouncer.router(function() {
      return self.echo.id;
    });

    return common.requestToWorker(self.listenPass, { path: "/passconn" })
      .then(function(req) {
        req.end();
        return common.readFully(req);
      })
      .then(function(text) {
        expect(text).to.eql("worker" + self.echo.id);
        return common.requestToWorker(self.listenPass, { path: "/foo"});
      })
      .then(function(req) {
        req.end();
        return common.readFully(req);
      })
      .then(function(text) {
        expect(text).to.eql("worker" + self.echo.id);
      });
  });
});
<|endoftext|>


<commit_before>"use strict";

const expect = require("chai").expect;

const Client = require("../../src/client");

const client = new Client({}, "test", {clientSettings: {highlights: "foo, @all,   sp ace   , 고"}});

describe("Custom highlights", function() {
	it("should NOT highlight", function() {
		const teststrings = [
			"and foos stuff",
			"test foobar",
			"testfoo bar",
			"fooö",
			"wtf@all",
			"foo고",
			"test고",
			"space",
			"sp:ace",
		];

		for (const teststring of teststrings) {
			expect(teststring).to.not.match(client.highlightRegex);
		}
	});

	it("should highlight", function() {
		const teststrings = [
			"Hey foo hello",
			"hey Foo: hi",
			"hey Foo, hi",
			"<foo> testing",
			"foo",
			"hey @all test",
			"testing foo's stuff",
			'"foo"',
			'"@all"',
			"foo!",
			"www.foo.bar",
			"www.bar.foo/page",
			"고",
			"test 고",
			"고!",
			"www.고.com",
			"hey @Foo",
			"hey ~Foo",
			"hey +Foo",
			"hello &foo",
			"@all",
			"@all wtf",
			"wtf @all",
			"@@all",
			"@고",
			"f00 sp ace: bar",
		];

		for (const teststring of teststrings) {
			expect(teststring).to.match(client.highlightRegex);
		}
	});

	it("should trim custom highlights in the compiled regex", function() {
		expect(client.highlightRegex).to.match(/\(\?:foo\|@all\|sp ace\|고\)/);
	});

	it("should NOT compile a regex", function() {
		// test updating the regex and invalid custom hl inputs
		client.config.clientSettings.highlights = ",,";
		client.compileCustomHighlights();
		expect(client.highlightRegex).to.be.null;

		client.config.clientSettings.highlights = "  ";
		client.compileCustomHighlights();
		expect(client.highlightRegex).to.be.null;
	});
});
<commit_msg>Hide user loaded message in tests<commit_after>"use strict";

const expect = require("chai").expect;
const stub = require("sinon").stub;
const log = require("../../src/log");
const Client = require("../../src/client");
const TestUtil = require("../util");

describe("Custom highlights", function() {
	let userLoadedLog = "";
	stub(log, "info").callsFake(TestUtil.sanitizeLog((str) => (userLoadedLog += str)));

	const client = new Client({}, "test", {
		clientSettings: {highlights: "foo, @all,   sp ace   , 고"},
	});

	log.info.restore();
	expect(userLoadedLog).to.equal("User test loaded\n");

	it("should NOT highlight", function() {
		const teststrings = [
			"and foos stuff",
			"test foobar",
			"testfoo bar",
			"fooö",
			"wtf@all",
			"foo고",
			"test고",
			"space",
			"sp:ace",
		];

		for (const teststring of teststrings) {
			expect(teststring).to.not.match(client.highlightRegex);
		}
	});

	it("should highlight", function() {
		const teststrings = [
			"Hey foo hello",
			"hey Foo: hi",
			"hey Foo, hi",
			"<foo> testing",
			"foo",
			"hey @all test",
			"testing foo's stuff",
			'"foo"',
			'"@all"',
			"foo!",
			"www.foo.bar",
			"www.bar.foo/page",
			"고",
			"test 고",
			"고!",
			"www.고.com",
			"hey @Foo",
			"hey ~Foo",
			"hey +Foo",
			"hello &foo",
			"@all",
			"@all wtf",
			"wtf @all",
			"@@all",
			"@고",
			"f00 sp ace: bar",
		];

		for (const teststring of teststrings) {
			expect(teststring).to.match(client.highlightRegex);
		}
	});

	it("should trim custom highlights in the compiled regex", function() {
		expect(client.highlightRegex).to.match(/\(\?:foo\|@all\|sp ace\|고\)/);
	});

	it("should NOT compile a regex", function() {
		// test updating the regex and invalid custom hl inputs
		client.config.clientSettings.highlights = ",,";
		client.compileCustomHighlights();
		expect(client.highlightRegex).to.be.null;

		client.config.clientSettings.highlights = "  ";
		client.compileCustomHighlights();
		expect(client.highlightRegex).to.be.null;
	});
});
<|endoftext|>


<commit_before>/**
 * Context.spec.js
 * (c) 2015~ Summernote Team
 * summernote may be freely distributed under the MIT license./
 */
/* jshint unused: false */
define([
  'chai',
  'spies',
  'helper',
  'jquery',
  'summernote/lite/settings',
  'summernote/base/core/agent',
  'summernote/base/core/dom',
  'summernote/base/Context'
], function (chai, spies, helper, $, settings, agent, dom, Context) {
  'use strict';

  var expect = chai.expect;
  chai.use(spies);

  describe('Context', function () {
    it('should be initialized without calling callback', function () {
      var options = $.extend({}, $.summernote.options);
      options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);

      var spy = chai.spy();
      var $note = $('

hello

');
      $note.on('summernote.change', spy);

      var context = new Context($note, options);
      expect(spy).to.have.not.been.called();

      context.invoke('insertText', 'hello');
      expect(spy).to.have.been.called();
    });
  });
});
<commit_msg>Fixed broken test.<commit_after>/**
 * Context.spec.js
 * (c) 2015~ Summernote Team
 * summernote may be freely distributed under the MIT license./
 */
/* jshint unused: false */
define([
  'chai',
  'spies',
  'helper',
  'jquery',
  'summernote/lite/settings',
  'summernote/base/core/agent',
  'summernote/base/core/dom',
  'summernote/base/Context'
], function (chai, spies, helper, $, settings, agent, dom, Context) {
  'use strict';

  var expect = chai.expect;
  chai.use(spies);

  describe('Context', function () {
    it('should be initialized without calling callback', function () {
      var options = $.extend({}, $.summernote.options);
      options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);

      var spy = chai.spy();
      var $note = $('

hello

');
      $note.on('summernote.change', spy);

      var context = new Context($note, options);
      expect(spy).to.have.not.been.called();

      // [workaround]
      //  - IE8-11 can't create range in headless mode
      if (!agent.isMSIE) {
        context.invoke('insertText', 'hello');
        expect(spy).to.have.been.called();
      }
    });
  });
});
<|endoftext|>


<commit_before>import '../../../src/index';
import create from '../../lib/create';

describe('slot/distribution', () => {
  let slot;
  let host;
  let root;
  let parent;

  beforeEach(() => {
    host = document.createElement('div');
    root = host.attachShadow({ mode: 'closed' });
    parent = create('div');
    slot = create('slot');

    root.appendChild(parent);
    parent.appendChild(slot);
  });

  it('distributes to the inner slot', () => {
    const light = document.createElement('light');
    host.appendChild(light);
    expect(host.childNodes[0]).to.equal(light, 'internal light dom');

    expect(slot.assignedNodes().length).to.equal(1, 'slot');
    expect(slot.assignedNodes()[0]).to.equal(light, 'slot');

    const lightText = document.createTextNode('text');
    host.appendChild(lightText);
    expect(host.childNodes[1]).to.equal(lightText);

    expect(slot.assignedNodes().length).to.equal(2);
    expect(slot.assignedNodes()[0]).to.equal(light, 'slot');
    expect(slot.assignedNodes()[1]).to.equal(lightText);

    const lightComment = document.createComment('text');
    host.appendChild(lightComment);
    expect(host.childNodes[2]).to.equal(lightComment);

    expect(slot.assignedNodes().length).to.equal(2);
    expect(slot.assignedNodes()[0]).to.equal(light, 'slot');
    expect(slot.assignedNodes()[1]).to.equal(lightText);
  });

  it('should remove child elements when distributing a document fragment', () => {
    const div1 = document.createElement('div');
    const div2 = document.createElement('div');

    const frag = document.createDocumentFragment();
    frag.appendChild(div1);
    frag.appendChild(div2);

    host.appendChild(frag);
    expect(frag.childNodes.length).to.equal(0);
  });

  describe('distributes to the slot that is owned by the current shadow root, not slots of descendant shadow roots', () => {
    it('for default slots', () => {
      const host1 = document.createElement('host1');
      const host2 = document.createElement('host2');
      const slot1 = document.createElement('slot');
      const slot2 = document.createElement('slot');
      const test = document.createTextNode('test');

      // Host2 must be set up and then added to host1's shadow root so that
      // host1 tries to slot the test content into host2's slot2 instead of
      // host1's slot1.
      host2.appendChild(slot1);
      host2.attachShadow({ mode: 'open' });
      host2.shadowRoot.appendChild(slot2);

      host1.appendChild(test);
      host1.attachShadow({ mode: 'open' });
      host1.shadowRoot.appendChild(host2);

      expect(slot1.assignedNodes().length).to.equal(1);
      expect(slot1.assignedNodes()[0]).to.equal(test);
      expect(slot2.assignedNodes().length).to.equal(1);
      expect(slot2.assignedNodes()[0]).to.equal(slot1);
    });

    it('for named slots', () => {
      const host1 = document.createElement('host1');
      const host2 = document.createElement('host2');
      const slot1 = document.createElement('slot');
      const slot2 = document.createElement('slot');
      const test = document.createElement('test');

      test.setAttribute('slot', 'test');
      slot1.setAttribute('slot', 'test');

      slot1.setAttribute('name', 'test');
      slot2.setAttribute('name', 'test');

      // Host2 must be set up and then added to host1's shadow root so that
      // host1 tries to slot the test content into host2's slot2 instead of
      // host1's slot1.
      host2.appendChild(slot1);
      host2.attachShadow({ mode: 'open' });
      host2.shadowRoot.appendChild(slot2);

      host1.appendChild(test);
      host1.attachShadow({ mode: 'open' });
      host1.shadowRoot.appendChild(host2);

      expect(slot1.assignedNodes().length).to.equal(1);
      expect(slot1.assignedNodes()[0]).to.equal(test);
      expect(slot2.assignedNodes().length).to.equal(1);
      expect(slot2.assignedNodes()[0]).to.equal(slot1);
    });
  });
});
<commit_msg>test(distribution): add a failing test for an issue with slot names changing<commit_after>import '../../../src/index';
import create from '../../lib/create';

describe('slot/distribution', () => {
  let slot;
  let host;
  let root;
  let parent;

  beforeEach(() => {
    host = document.createElement('div');
    root = host.attachShadow({ mode: 'closed' });
    parent = create('div');
    slot = create('slot');

    root.appendChild(parent);
    parent.appendChild(slot);
  });

  it('distributes to the inner slot', () => {
    const light = document.createElement('light');
    host.appendChild(light);
    expect(host.childNodes[0]).to.equal(light, 'internal light dom');

    expect(slot.assignedNodes().length).to.equal(1, 'slot');
    expect(slot.assignedNodes()[0]).to.equal(light, 'slot');

    const lightText = document.createTextNode('text');
    host.appendChild(lightText);
    expect(host.childNodes[1]).to.equal(lightText);

    expect(slot.assignedNodes().length).to.equal(2);
    expect(slot.assignedNodes()[0]).to.equal(light, 'slot');
    expect(slot.assignedNodes()[1]).to.equal(lightText);

    const lightComment = document.createComment('text');
    host.appendChild(lightComment);
    expect(host.childNodes[2]).to.equal(lightComment);

    expect(slot.assignedNodes().length).to.equal(2);
    expect(slot.assignedNodes()[0]).to.equal(light, 'slot');
    expect(slot.assignedNodes()[1]).to.equal(lightText);
  });

  it('should remove child elements when distributing a document fragment', () => {
    const div1 = document.createElement('div');
    const div2 = document.createElement('div');

    const frag = document.createDocumentFragment();
    frag.appendChild(div1);
    frag.appendChild(div2);

    host.appendChild(frag);
    expect(frag.childNodes.length).to.equal(0);
  });

  it.only('adding a slot name attribute after insertion makes re-slotting occur', () => {
    const light = document.createElement('light');
    host.appendChild(light);
    expect(slot.assignedNodes().length).to.equal(1);

    slot.setAttribute('name', 'foo');
    expect(slot.assignedNodes().length).to.equal(0);
  });

  describe('distributes to the slot that is owned by the current shadow root, not slots of descendant shadow roots', () => {
    it('for default slots', () => {
      const host1 = document.createElement('host1');
      const host2 = document.createElement('host2');
      const slot1 = document.createElement('slot');
      const slot2 = document.createElement('slot');
      const test = document.createTextNode('test');

      // Host2 must be set up and then added to host1's shadow root so that
      // host1 tries to slot the test content into host2's slot2 instead of
      // host1's slot1.
      host2.appendChild(slot1);
      host2.attachShadow({ mode: 'open' });
      host2.shadowRoot.appendChild(slot2);

      host1.appendChild(test);
      host1.attachShadow({ mode: 'open' });
      host1.shadowRoot.appendChild(host2);

      expect(slot1.assignedNodes().length).to.equal(1);
      expect(slot1.assignedNodes()[0]).to.equal(test);
      expect(slot2.assignedNodes().length).to.equal(1);
      expect(slot2.assignedNodes()[0]).to.equal(slot1);
    });

    it('for named slots', () => {
      const host1 = document.createElement('host1');
      const host2 = document.createElement('host2');
      const slot1 = document.createElement('slot');
      const slot2 = document.createElement('slot');
      const test = document.createElement('test');

      test.setAttribute('slot', 'test');
      slot1.setAttribute('slot', 'test');

      slot1.setAttribute('name', 'test');
      slot2.setAttribute('name', 'test');

      // Host2 must be set up and then added to host1's shadow root so that
      // host1 tries to slot the test content into host2's slot2 instead of
      // host1's slot1.
      host2.appendChild(slot1);
      host2.attachShadow({ mode: 'open' });
      host2.shadowRoot.appendChild(slot2);

      host1.appendChild(test);
      host1.attachShadow({ mode: 'open' });
      host1.shadowRoot.appendChild(host2);

      expect(slot1.assignedNodes().length).to.equal(1);
      expect(slot1.assignedNodes()[0]).to.equal(test);
      expect(slot2.assignedNodes().length).to.equal(1);
      expect(slot2.assignedNodes()[0]).to.equal(slot1);
    });
  });
});
<|endoftext|>


<commit_before>window.genUID = function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
};

var IPYTHON_VERSION = '3';

require(["widgets/js/widget", "widgets/js/manager"], function (widget, manager) {
    if (!('DOMWidgetView' in widget)) {

        // we're in IPython2, things moved a bit from 2 --> 3.
        // construct the expected IPython3 widget API
        IPYTHON_VERSION = '2';
        manager = {WidgetManager: widget};
        widget = {DOMWidgetView: IPython.DOMWidgetView}
    }

    var GraphView = widget.DOMWidgetView.extend({
        render: function(){
            var that = this;

            var graphId = window.genUID();
            var loadingId = 'loading-'+graphId;

            var _graph_url = that.model.get('_graph_url');

            // variable plotlyDomain in the case of enterprise
            var url_parts = _graph_url.split('/');
            var plotlyDomain = url_parts[0] + '//' + url_parts[2];

            if(!('plotlyDomains' in window)){
                window.plotlyDomains = {};
            }
            window.plotlyDomains[graphId] = plotlyDomain;

            // Place IFrame in output cell div `$el`
            that.$el.css('width', '100%');
            that.$graph = $(['',
                             ''].join(' '));
            that.$graph.appendTo(that.$el);

            that.$loading = $('
Initializing...
')
                            .appendTo(that.$el);

            // initialize communication with the iframe
            if(!('pingers' in window)){
                window.pingers = {};
            }

            window.pingers[graphId] = setInterval(function() {
                that.graphContentWindow = $('#'+graphId)[0].contentWindow;
                that.graphContentWindow.postMessage({task: 'ping'}, plotlyDomain);
            }, 200);

            // Assign a message listener to the 'message' events
            // from iframe's postMessage protocol.
            // Filter the messages by iframe src so that the right message
            // gets passed to the right widget
            if(!('messageListeners' in window)){
                 window.messageListeners = {};
            }

            window.messageListeners[graphId] = function(e) {
                if(_graph_url.indexOf(e.origin)>-1) {
                    var frame = document.getElementById(graphId);

                    if(frame === null){
                        // frame doesn't exist in the dom anymore, clean up it's old event listener
                        window.removeEventListener('message', window.messageListeners[graphId]);
                        clearInterval(window.pingers[graphId]);
                    } else if(frame.contentWindow === e.source) {
                        // TODO: Stop event propagation, so each frame doesn't listen and filter
                        var frameContentWindow = $('#'+graphId)[0].contentWindow;
                        var message = e.data;

                        if('pong' in message && message.pong) {
                            $('#loading-'+graphId).hide();
                            clearInterval(window.pingers[graphId]);
                            that.send({event: 'pong', graphId: graphId});
                        } else if (message.type==='hover' ||
                                   message.type==='zoom'  ||
                                   message.type==='click' ||
                                   message.type==='unhover') {

                            // click and hover events contain all of the data in the traces,
                            // which can be a very large object and may take a ton of time
                            // to pass to the python backend. Strip out the data, and require
                            // the user to call get_figure if they need trace information
                            if(message.type !== 'zoom') {
                                for(var i in message.points) {
                                    delete message.points[i].data;
                                    delete message.points[i].fullData;
                                }
                            }
                            that.send({event: message.type, message: message, graphId: graphId});
                        }
                    }
                }
            };

            window.removeEventListener('message', window.messageListeners[graphId]);
            window.addEventListener('message', window.messageListeners[graphId]);

        },

        update: function() {
            // Listen for messages from the graph widget in python
            var jmessage = this.model.get('_message');
            var message = JSON.parse(jmessage);

            // check for duplicate messages
            if(!('messageIds' in window)){
                window.messageIds = {};
            }

            if(!(message.uid in window.messageIds)){
                // message hasn't been received yet, do stuff
                window.messageIds[message.uid] = true;

                var plot = $('#'+message.graphId)[0].contentWindow;
                plot.postMessage(message, window.plotlyDomains[message.graphId]);
            }

            return GraphView.__super__.update.apply(this);
        }
    });

    // Register the GraphView with the widget manager.
    manager.WidgetManager.register_widget_view('GraphView', GraphView);

});

//@ sourceURL=graphWidget.js
<commit_msg>Shim bug with setting container div width to 100%.<commit_after>window.genUID = function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
};

var IPYTHON_VERSION = '3';

require(["widgets/js/widget", "widgets/js/manager"], function (widget, manager) {
    if (!('DOMWidgetView' in widget)) {

        // we're in IPython2, things moved a bit from 2 --> 3.
        // construct the expected IPython3 widget API
        IPYTHON_VERSION = '2';
        manager = {WidgetManager: widget};
        widget = {DOMWidgetView: IPython.DOMWidgetView}
    }

    var GraphView = widget.DOMWidgetView.extend({
        render: function(){
            var that = this;

            var graphId = window.genUID();
            var loadingId = 'loading-'+graphId;

            var _graph_url = that.model.get('_graph_url');

            // variable plotlyDomain in the case of enterprise
            var url_parts = _graph_url.split('/');
            var plotlyDomain = url_parts[0] + '//' + url_parts[2];

            if(!('plotlyDomains' in window)){
                window.plotlyDomains = {};
            }
            window.plotlyDomains[graphId] = plotlyDomain;

            // Place IFrame in output cell div `$el`
            that.$el.css('width', '100%');
            that.$graph = $(['',
                             ''].join(' '));
            that.$graph.appendTo(that.$el);

            that.$loading = $('
Initializing...
')
                            .appendTo(that.$el);

            // for some reason the 'width' is being changed in IPython 3.0.0
            // for the containing `div` element. There's a flicker here, but
            // I was unable to fix it otherwise.
            setTimeout(function ()  {
                if (IPYTHON_VERSION === '3') {
                    $('#' + graphId)[0].parentElement.style.width = '100%';
                }
            }, 500);

            // initialize communication with the iframe
            if(!('pingers' in window)){
                window.pingers = {};
            }

            window.pingers[graphId] = setInterval(function() {
                that.graphContentWindow = $('#'+graphId)[0].contentWindow;
                that.graphContentWindow.postMessage({task: 'ping'}, plotlyDomain);
            }, 200);

            // Assign a message listener to the 'message' events
            // from iframe's postMessage protocol.
            // Filter the messages by iframe src so that the right message
            // gets passed to the right widget
            if(!('messageListeners' in window)){
                 window.messageListeners = {};
            }

            window.messageListeners[graphId] = function(e) {
                if(_graph_url.indexOf(e.origin)>-1) {
                    var frame = document.getElementById(graphId);

                    if(frame === null){
                        // frame doesn't exist in the dom anymore, clean up it's old event listener
                        window.removeEventListener('message', window.messageListeners[graphId]);
                        clearInterval(window.pingers[graphId]);
                    } else if(frame.contentWindow === e.source) {
                        // TODO: Stop event propagation, so each frame doesn't listen and filter
                        var frameContentWindow = $('#'+graphId)[0].contentWindow;
                        var message = e.data;

                        if('pong' in message && message.pong) {
                            $('#loading-'+graphId).hide();
                            clearInterval(window.pingers[graphId]);
                            that.send({event: 'pong', graphId: graphId});
                        } else if (message.type==='hover' ||
                                   message.type==='zoom'  ||
                                   message.type==='click' ||
                                   message.type==='unhover') {

                            // click and hover events contain all of the data in the traces,
                            // which can be a very large object and may take a ton of time
                            // to pass to the python backend. Strip out the data, and require
                            // the user to call get_figure if they need trace information
                            if(message.type !== 'zoom') {
                                for(var i in message.points) {
                                    delete message.points[i].data;
                                    delete message.points[i].fullData;
                                }
                            }
                            that.send({event: message.type, message: message, graphId: graphId});
                        }
                    }
                }
            };

            window.removeEventListener('message', window.messageListeners[graphId]);
            window.addEventListener('message', window.messageListeners[graphId]);

        },

        update: function() {
            // Listen for messages from the graph widget in python
            var jmessage = this.model.get('_message');
            var message = JSON.parse(jmessage);

            // check for duplicate messages
            if(!('messageIds' in window)){
                window.messageIds = {};
            }

            if(!(message.uid in window.messageIds)){
                // message hasn't been received yet, do stuff
                window.messageIds[message.uid] = true;

                var plot = $('#'+message.graphId)[0].contentWindow;
                plot.postMessage(message, window.plotlyDomains[message.graphId]);
            }

            return GraphView.__super__.update.apply(this);
        }
    });

    // Register the GraphView with the widget manager.
    manager.WidgetManager.register_widget_view('GraphView', GraphView);

});

//@ sourceURL=graphWidget.js
<|endoftext|>