<commit_before>'use strict'
/* globals describe beforeEach it commands afterEach */

const nock = require('nock')
const cli = require('heroku-cli-util')
const cmd = commands.find((c) => c.topic === 'releases' && c.command === 'info')
const expect = require('unexpected')

let d = new Date(2000, 1, 1)

describe('releases:info', function () {
  beforeEach(() => cli.mockConsole())
  afterEach(() => nock.cleanAll())

  let release = {
    description: 'something changed',
    user: {
      email: 'foo@foo.com'
    },
    created_at: d,
    version: 10
  }

  let v2release = {
    addons: ['addon1', 'addon2'],
    env: {FOO: 'foo', BAR: 'bar'}
  }

  it('shows most recent release info', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases')
      .reply(200, [{version: 10}])
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, release)
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/json')
      .reply(200, v2release)
    return cmd.run({app: 'myapp', flags: {}, args: {}})
      .then(() => expect(cli.stdout, 'to equal', `=== Release v10
Add-ons: addon1
         addon2
By:      foo@foo.com
Change:  something changed
When:    ${d.toISOString()}

=== v10 Config vars
BAR: bar
FOO: foo
`))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })

  it('shows release info by id', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, release)
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/json')
      .reply(200, v2release)
    return cmd.run({app: 'myapp', flags: {}, args: {release: 'v10'}})
      .then(() => expect(cli.stdout, 'to equal', `=== Release v10
Add-ons: addon1
         addon2
By:      foo@foo.com
Change:  something changed
When:    ${d.toISOString()}

=== v10 Config vars
BAR: bar
FOO: foo
`))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })

  it('shows recent release as json', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, release)
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/json')
      .reply(200, v2release)
    return cmd.run({app: 'myapp', flags: {json: true}, args: {release: 'v10'}})
      .then(() => expect(JSON.parse(cli.stdout), 'to satisfy', {version: 10}))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })

  it('shows a failed release info', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases')
      .reply(200, [{version: 10}])
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, {
        description: 'something changed',
        status: 'failure',
        user: { email: 'foo@foo.com' },
        created_at: d,
        version: 10
      })
    return cmd.run({app: 'myapp', flags: {}, args: {}})
      .then(() => expect(cli.stdout, 'to equal', `=== Release v10
By:      foo@foo.com
Change:  something changed (release command failed)
When:    ${d.toISOString()}
`))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })

  it('shows a pending release info', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases')
      .reply(200, [{version: 10}])
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, {
        description: 'something changed',
        status: 'pending',
        user: {email: 'foo@foo.com'},
        version: 10,
        created_at: d
      })
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/json')
      .reply(200, v2release)
    return cmd.run({app: 'myapp', flags: {}, args: {}})
      .then(() => expect(cli.stdout, 'to equal', `=== Release v10
Add-ons: addon1
         addon2
By:      foo@foo.com
Change:  something changed (release command executing)
When:    ${d.toISOString()}

=== v10 Config vars
BAR: bar
FOO: foo
`))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })
})
<commit_msg>test config var shell format<commit_after>'use strict'
/* globals describe beforeEach it commands afterEach */

const nock = require('nock')
const cli = require('heroku-cli-util')
const cmd = commands.find((c) => c.topic === 'releases' && c.command === 'info')
const expect = require('unexpected')

let d = new Date(2000, 1, 1)

describe('releases:info', function () {
  beforeEach(() => cli.mockConsole())
  afterEach(() => nock.cleanAll())

  let release = {
    description: 'something changed',
    user: {
      email: 'foo@foo.com'
    },
    created_at: d,
    version: 10
  }

  let v2release = {
    addons: ['addon1', 'addon2'],
    env: {FOO: 'foo', BAR: 'bar'}
  }

  it('shows most recent release info', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases')
      .reply(200, [{version: 10}])
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, release)
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/json')
      .reply(200, v2release)
    return cmd.run({app: 'myapp', flags: {}, args: {}})
      .then(() => expect(cli.stdout, 'to equal', `=== Release v10
Add-ons: addon1
         addon2
By:      foo@foo.com
Change:  something changed
When:    ${d.toISOString()}

=== v10 Config vars
BAR: bar
FOO: foo
`))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })

  it('shows most recent release info config vars as shell', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases')
      .reply(200, [{version: 10}])
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, release)
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/json')
      .reply(200, v2release)
    return cmd.run({app: 'myapp', flags: {shell: true}, args: {}})
      .then(() => expect(cli.stdout, 'to equal', `=== Release v10
Add-ons: addon1
         addon2
By:      foo@foo.com
Change:  something changed
When:    ${d.toISOString()}

=== v10 Config vars
FOO=foo
BAR=bar
`))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })

  it('shows release info by id', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, release)
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/json')
      .reply(200, v2release)
    return cmd.run({app: 'myapp', flags: {}, args: {release: 'v10'}})
      .then(() => expect(cli.stdout, 'to equal', `=== Release v10
Add-ons: addon1
         addon2
By:      foo@foo.com
Change:  something changed
When:    ${d.toISOString()}

=== v10 Config vars
BAR: bar
FOO: foo
`))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })

  it('shows recent release as json', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, release)
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/json')
      .reply(200, v2release)
    return cmd.run({app: 'myapp', flags: {json: true}, args: {release: 'v10'}})
      .then(() => expect(JSON.parse(cli.stdout), 'to satisfy', {version: 10}))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })

  it('shows a failed release info', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases')
      .reply(200, [{version: 10}])
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, {
        description: 'something changed',
        status: 'failure',
        user: { email: 'foo@foo.com' },
        created_at: d,
        version: 10
      })
    return cmd.run({app: 'myapp', flags: {}, args: {}})
      .then(() => expect(cli.stdout, 'to equal', `=== Release v10
By:      foo@foo.com
Change:  something changed (release command failed)
When:    ${d.toISOString()}
`))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })

  it('shows a pending release info', function () {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp/releases')
      .reply(200, [{version: 10}])
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/vnd.heroku+json; version=3.release_status')
      .reply(200, {
        description: 'something changed',
        status: 'pending',
        user: {email: 'foo@foo.com'},
        version: 10,
        created_at: d
      })
      .get('/apps/myapp/releases/10')
      .matchHeader('accept', 'application/json')
      .reply(200, v2release)
    return cmd.run({app: 'myapp', flags: {}, args: {}})
      .then(() => expect(cli.stdout, 'to equal', `=== Release v10
Add-ons: addon1
         addon2
By:      foo@foo.com
Change:  something changed (release command executing)
When:    ${d.toISOString()}

=== v10 Config vars
BAR: bar
FOO: foo
`))
      .then(() => expect(cli.stderr, 'to be empty'))
      .then(() => api.done())
  })
})
<|endoftext|>


<commit_before>/* global describe, it */

import expect from 'expect'
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import Layout from '../../src/components/Layout'

const renderer = TestUtils.createRenderer()

describe('Layout', () => {
  it('Should add classes equals to props', () => {
    renderer.render(<Layout direction='row' align='center center' margin padding fill wrap />)
    const { type, props: { className } } = renderer.getRenderOutput()
    expect(type).toBe('div')
    expect(className).toContain('layout-row')
    expect(className).toContain('layout-align-center-center')
    expect(className).toContain('layout-margin')
    expect(className).toContain('layout-padding')
    expect(className).toContain('layout-fill')
    expect(className).toContain('layout-wrap')
  })

  it('Should add classes equals to props (direction breakpoints)', () => {
    renderer.render(<Layout direction='row'
      direction-xs='column' direction-gt-xs='row'
      direction-sm='column' direction-gt-sm='row'
      direction-md='column' direction-gt-md='row'
      direction-lg='column' direction-gt-lg='row'
      direction-xl='column' />)
    const { type, props: { className } } = renderer.getRenderOutput()
    expect(type).toBe('div')
    expect(className).toContain('layout-row')
    expect(className).toContain('layout-xs-column')
    expect(className).toContain('layout-gt-xs-row')
    expect(className).toContain('layout-sm-column')
    expect(className).toContain('layout-gt-sm-row')
    expect(className).toContain('layout-md-column')
    expect(className).toContain('layout-gt-md-row')
    expect(className).toContain('layout-lg-column')
    expect(className).toContain('layout-gt-lg-row')
    expect(className).toContain('layout-xl-column')
  })

  it('Should add classes equals to props (align breakpoints)', () => {
    renderer.render(<Layout align='space-around end'
      align-xs='start stretch' align-gt-xs='center end'
      align-sm='start stretch' align-gt-sm='center end'
      align-md='start stretch' align-gt-md='center end'
      align-lg='start stretch' align-gt-lg='center end'
      align-xl='start stretch' />)
    const { type, props: { className } } = renderer.getRenderOutput()
    expect(type).toBe('div')
    expect(className).toContain('layout-align-space-around-end')
    expect(className).toContain('layout-align-xs-start-stretch')
    expect(className).toContain('layout-align-gt-xs-center-end')
    expect(className).toContain('layout-align-sm-start-stretch')
    expect(className).toContain('layout-align-gt-sm-center-end')
    expect(className).toContain('layout-align-md-start-stretch')
    expect(className).toContain('layout-align-gt-md-center-end')
    expect(className).toContain('layout-align-lg-start-stretch')
    expect(className).toContain('layout-align-gt-lg-center-end')
    expect(className).toContain('layout-align-xl-start-stretch')
  })

  it('Should add "layout-row" class if `layout` property is not set', () => {
    renderer.render(<Layout />)
    expect(renderer.getRenderOutput().props.className).toContain('layout-row')
  })

  it('Should add "layout-align-*-stretch" class if `align` property for perpendicular is not set', () => {
    renderer.render(<Layout align='start' />)
    expect(renderer.getRenderOutput().props.className).toContain('layout-align-start-stretch')
  })

  it('Should not replace class', () => {
    renderer.render(<Layout className='foo' direction='column' />)
    const { className } = renderer.getRenderOutput().props
    expect(className).toContain('foo')
    expect(className).toContain('layout-column')
  })

  it('Should support custom tag name', () => {
    renderer.render(<Layout direction='column' align='start stretch' tagName='span' />)

    expect(renderer.getRenderOutput().type).toBe('span')
  })
})
<commit_msg>Updated Layout test.<commit_after>/* global describe, it */

import expect from 'expect'
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import Layout from '../../src/components/Layout'

const renderer = TestUtils.createRenderer()

describe('Layout', () => {
  it('Should add classes equals to props', () => {
    renderer.render(<Layout direction='row' align='center center' margin padding fill wrap />)
    const { type, props: { className } } = renderer.getRenderOutput()
    expect(type).toBe('div')
    expect(className).toContain('layout-row')
    expect(className).toContain('layout-align-center-center')
    expect(className).toContain('layout-margin')
    expect(className).toContain('layout-padding')
    expect(className).toContain('layout-fill')
    expect(className).toContain('layout-wrap')
  })

  it('Should add classes equals to props (direction breakpoints)', () => {
    renderer.render(<Layout direction='row'
      direction-xs='column' direction-gt-xs='row'
      direction-sm='column' direction-gt-sm='row'
      direction-md='column' direction-gt-md='row'
      direction-lg='column' direction-gt-lg='row'
      direction-xl='column' />)
    const { type, props: { className } } = renderer.getRenderOutput()
    expect(type).toBe('div')
    expect(className).toContain('layout-row')
    expect(className).toContain('layout-xs-column')
    expect(className).toContain('layout-gt-xs-row')
    expect(className).toContain('layout-sm-column')
    expect(className).toContain('layout-gt-sm-row')
    expect(className).toContain('layout-md-column')
    expect(className).toContain('layout-gt-md-row')
    expect(className).toContain('layout-lg-column')
    expect(className).toContain('layout-gt-lg-row')
    expect(className).toContain('layout-xl-column')
  })

  it('Should add classes equals to props (align breakpoints)', () => {
    renderer.render(<Layout align='space-around end'
      align-xs='start stretch' align-gt-xs='center end'
      align-sm='start stretch' align-gt-sm='center end'
      align-md='start stretch' align-gt-md='center end'
      align-lg='start stretch' align-gt-lg='center end'
      align-xl='start stretch' />)
    const { type, props: { className } } = renderer.getRenderOutput()
    expect(type).toBe('div')
    expect(className).toContain('layout-align-space-around-end')
    expect(className).toContain('layout-align-xs-start-stretch')
    expect(className).toContain('layout-align-gt-xs-center-end')
    expect(className).toContain('layout-align-sm-start-stretch')
    expect(className).toContain('layout-align-gt-sm-center-end')
    expect(className).toContain('layout-align-md-start-stretch')
    expect(className).toContain('layout-align-gt-md-center-end')
    expect(className).toContain('layout-align-lg-start-stretch')
    expect(className).toContain('layout-align-gt-lg-center-end')
    expect(className).toContain('layout-align-xl-start-stretch')
  })

  it('Should add "layout-row" class if `layout` property is not set', () => {
    renderer.render(<Layout />)
    expect(renderer.getRenderOutput().props.className).toContain('layout-row')
  })

  it('Should add "layout-align-*-stretch" class if `align` property for perpendicular is not set', () => {
    renderer.render(<Layout align='start' />)
    expect(renderer.getRenderOutput().props.className).toContain('layout-align-start-stretch')
  })

  it('Should not replace class', () => {
    renderer.render(<Layout className='foo' direction='column' />)
    const { className } = renderer.getRenderOutput().props
    expect(className).toContain('foo')
    expect(className).toContain('layout-column')
  })

  it('Should preserve inline style', () => {
    let styleToApply = {height: '100%'}
    renderer.render(<Layout direction='column' style={styleToApply} />)
    const { className, style } = renderer.getRenderOutput().props
    expect(className).toContain('layout-column')
    expect(style).toEqual(styleToApply)
  })

  it('Should support custom tag name', () => {
    renderer.render(<Layout direction='column' align='start stretch' tagName='span' />)

    expect(renderer.getRenderOutput().type).toBe('span')
  })
})
<|endoftext|>


<commit_before>/* global describe, it, beforeEach */

import React from 'react'
import { expect } from 'chai'
import { mount } from 'enzyme'
import Submit from '../../src/js/components/submit'

const context = {
  frigForm: {
    layout: 'horizontal',
  },
}

describe('<Submit />', () => {
  it('renders HTML button with value=props.title', () => {
    const wrapper = mount(<Submit title="Save" />, { context })
    const button = wrapper.find('button')
    expect(button.text()).to.equal('Save')
  })

  it('renders HTML button on vertical layout', () => {
    context.frigForm.layout = 'vertical'
    const wrapper = mount(<Submit title="Save" />, { context })
    const submitContainer = wrapper.findWhere((c) => c.hasClass(''))
    expect(submitContainer).to.have.length(1)
  })
})
<commit_msg>As Of Enzyme 2.4.0 hasClass() Needs Class Name<commit_after>/* global describe, it, beforeEach */

import React from 'react'
import { expect } from 'chai'
import { mount } from 'enzyme'
import Submit from '../../src/js/components/submit'

const context = {
  frigForm: {
    layout: 'horizontal',
  },
}

describe('<Submit />', () => {
  it('renders HTML button with value=props.title', () => {
    const wrapper = mount(<Submit title="Save" />, { context })
    const button = wrapper.find('button')
    expect(button.text()).to.equal('Save')
  })

  it('renders HTML button on vertical layout', () => {
    context.frigForm.layout = 'vertical'
    const wrapper = mount(<Submit title="Save" />, { context })
    const submitContainer = wrapper.findWhere(c => c.props().className === '')

    expect(submitContainer).to.have.length(1)
  })
})
<|endoftext|>


<commit_before>'use strict';

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

describe('Deferred Map', function() {
    // shared element locator(s)
    var loadJSAPIButton = element(by.buttonText('Load Esri JSAPI and Map View'));

    beforeAll(function() {
        // refer to conf.js to get the baseUrl that is prepended
        browser.get('/deferred-map.html');
    });

    it('should click on the load JSAPI button, and create a standard map view that is not rotated', function() {
        loadJSAPIButton.click();

        // var mapView = helper.getMapViewElement();
        helper.getMapViewElement().then(function(mapView) {
            expect(mapView.getAttribute('style')).toMatch(/(transform: rotateZ\(0deg\))/);
        });

    });
});
<commit_msg>e2e update for deferred-map test<commit_after>'use strict';

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

describe('Deferred Map', function() {
    // shared element locator(s)
    var loadJSAPIButton = element(by.buttonText('Load Esri JSAPI and MapView'));

    beforeAll(function() {
        // refer to conf.js to get the baseUrl that is prepended
        browser.get('/deferred-map.html');
    });

    it('should click on the load JSAPI button, and create a standard map view that is not rotated', function() {
        loadJSAPIButton.click();

        // var mapView = helper.getMapViewElement();
        helper.getMapViewElement().then(function(mapView) {
            expect(mapView.getAttribute('style')).toMatch(/(transform: rotateZ\(0deg\))/);
        });

    });
});
<|endoftext|>


<commit_before>var stresstest = require('stresstest');
var timeouttest = require('timeouttest');

var win = Ti.UI.createWindow({});

var list = Ti.UI.createView({
  width: Ti.UI.SIZE,
  height: Ti.UI.SIZE,
  layout: 'vertical'
});

win.add(list);

[
  {
    title: 'Execute Stress Test',
    handle: stresstest
  },
  {
    title: 'Timeout test',
    handle: timeouttest
  }
].forEach(function (action) {
  var button = Ti.UI.createButton({
    title: action.title
  });

  var running = false;

  button.addEventListener('click', function () {
    running = true;
    button.enabled = false;
    button.disabled = true;

    action.handle(function (err) {
      running = false;
      button.enabled = true;
      button.disabled = false;

      if (err) {
        throw err;
      }
      else {
        alert('Done');
      }
    });
  });

  list.add(button);
});

win.open();
<commit_msg>Support for a LOT of tests<commit_after>var stresstest = require('stresstest');
var timeouttest = require('timeouttest');

var win = Ti.UI.createWindow({});

var list = Ti.UI.createScrollView({
  width: Ti.UI.SIZE,
  height: Ti.UI.SIZE,
  layout: 'vertical'
});

win.add(list);

[
  {
    title: 'Execute Stress Test',
    handle: stresstest
  },
  {
    title: 'Timeout test',
    handle: timeouttest
  }
].forEach(function (action) {
  var button = Ti.UI.createButton({
    title: action.title
  });

  var running = false;

  button.addEventListener('click', function () {
    running = true;
    button.enabled = false;
    button.disabled = true;

    action.handle(function (err) {
      running = false;
      button.enabled = true;
      button.disabled = false;

      if (err) {
        throw err;
      }
      else {
        alert('Done');
      }
    });
  });

  list.add(button);
});

win.open();
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const { describe, it } = require('../helpers/mocha');
const { expect } = require('../helpers/chai');
const sinon = require('sinon');
const {
  buildTmp,
  processExit,
  fixtureCompare: _fixtureCompare
} = require('git-fixtures');
const { isGitClean } = require('git-diff-apply');
const emberCliUpdate = require('../../src');
const utils = require('boilerplate-update/src/utils');
const {
  assertNoUnstaged,
  assertNoStaged
} = require('../helpers/assertions');
const { initBlueprint } = require('../helpers/blueprint');
const loadSafeBlueprintFile = require('../../src/load-safe-blueprint-file');

const toDefault = require('../../src/args').to.default;

describe(function() {
  this.timeout(30 * 1000);

  let cwd;
  let tmpPath;

  before(function() {
    cwd = process.cwd();
  });

  afterEach(function() {
    sinon.restore();

    process.chdir(cwd);
  });

  async function merge({
    fixturesPath,
    dirty,
    blueprint,
    from,
    to = '3.11.0-beta.1',
    reset,
    compareOnly,
    statsOnly,
    runCodemods,
    codemodsJson,
    listCodemods,
    createCustomDiff,
    commitMessage,
    beforeMerge = () => Promise.resolve(),
    afterMerge = () => Promise.resolve()
  }) {
    tmpPath = await buildTmp({
      fixturesPath,
      commitMessage,
      dirty
    });

    await beforeMerge();

    process.chdir(tmpPath);

    let promise = (async() => {
      let result = await emberCliUpdate({
        blueprint,
        from,
        to,
        reset,
        compareOnly,
        statsOnly,
        runCodemods,
        codemodsJson,
        listCodemods,
        createCustomDiff
      });

      await afterMerge();

      return result;
    })();

    return await processExit({
      promise,
      cwd: tmpPath,
      commitMessage,
      expect
    });
  }

  function fixtureCompare({
    mergeFixtures
  }) {
    let actual = tmpPath;
    let expected = path.join(cwd, mergeFixtures);

    _fixtureCompare({
      expect,
      actual,
      expected
    });
  }

  it('handles dirty', async function() {
    let {
      status,
      stderr
    } = await merge({
      fixturesPath: 'test/fixtures/app/local',
      commitMessage: 'my-app',
      dirty: true
    });

    expect(status).to.equal(`?? a-random-new-file
`);

    expect(stderr).to.contain('You must start with a clean working directory');
    expect(stderr).to.not.contain('UnhandledPromiseRejectionWarning');
  });

  it('handles non-ember-cli app', async function() {
    let promise = merge({
      fixturesPath: 'test/fixtures/package-json/non-ember-cli',
      commitMessage: 'my-app'
    });

    await expect(promise)
      .to.eventually.be.rejectedWith('Ember CLI project type could not be determined');

    expect(await isGitClean({ cwd: tmpPath })).to.be.ok;
  });

  it('handles non-npm dir', async function() {
    let {
      stderr
    } = await merge({
      fixturesPath: 'test/fixtures/package-json/missing',
      commitMessage: 'my-app'
    });

    expect(await isGitClean({ cwd: tmpPath })).to.be.ok;

    expect(stderr).to.contain('No package.json was found in this directory');
  });

  it('handles malformed package.json', async function() {
    let {
      stderr
    } = await merge({
      fixturesPath: 'test/fixtures/package-json/malformed',
      commitMessage: 'my-app'
    });

    expect(await isGitClean({ cwd: tmpPath })).to.be.ok;

    expect(stderr).to.contain('The package.json is malformed');
  });

  it('updates glimmer app', async function() {
    let {
      status
    } = await merge({
      fixturesPath: 'test/fixtures/glimmer/local',
      commitMessage: 'glimmer-app',
      from: '0.5.0',
      to: '0.6.1'
    });

    fixtureCompare({
      mergeFixtures: 'test/fixtures/glimmer/merge/glimmer-app'
    });

    expect(status).to.match(/^M {2}src\/index\.ts$/m);

    assertNoUnstaged(status);
  });

  it('needs --from if glimmer app before 0.6.3', async function() {
    let {
      stderr
    } = await merge({
      fixturesPath: 'test/fixtures/glimmer/local',
      commitMessage: 'glimmer-app',
      to: '0.6.1'
    });

    expect(await isGitClean({ cwd: tmpPath })).to.be.ok;

    expect(stderr).to.contain('version cannot be determined');
  });

  it('resets app', async function() {
    let {
      status
    } = await merge({
      fixturesPath: 'test/fixtures/app/local',
      commitMessage: 'my-app',
      reset: true,
      to: '2.11.1'
      // test the resetting logic of ember-cli-update.json
      // no longer a valid blueprint name
      // blueprint: 'ember-cli',
      // async afterMerge() {
      //   expect(path.join(tmpPath, 'config/ember-cli-update.json')).to.be.a.file()
      //     .and.equal(path.join(cwd, 'test/fixtures/ember-cli-update-json/default/config/ember-cli-update.json'));

      //   await fs.remove(path.join(tmpPath, 'config/ember-cli-update.json'));
      // }
    });

    fixtureCompare({
      mergeFixtures: 'test/fixtures/app/reset/my-app'
    });

    expect(status).to.match(/^ D app\/controllers\/application\.js$/m);

    assertNoStaged(status);
  });

  it('opens compare url', async function() {
    let open = sinon.stub(utils, 'open');

    let {
      result,
      status
    } = await merge({
      fixturesPath: 'test/fixtures/app/local',
      commitMessage: 'my-app',
      compareOnly: true
    });

    assertNoUnstaged(status);

    expect(result, 'don\'t accidentally print anything to the console').to.be.undefined;

    expect(open).to.have.been.calledOnce
      .and.to.have.been.calledWith('https://github.com/ember-cli/ember-new-output/compare/v2.11.1...v3.11.0-beta.1');
  });

  it('resolves semver ranges', async function() {
    let {
      result
    } = await merge({
      fixturesPath: 'test/fixtures/app/local',
      commitMessage: 'my-app',
      from: '1.13',
      to: '^2',
      statsOnly: true
    });

    expect(result).to.equal(`project options: app, welcome
from version: 1.13.15
to version: 2.18.2
output repo: https://github.com/ember-cli/ember-new-output
applicable codemods: `);
  });

  it('shows stats only', async function() {
    let {
      result,
      status
    } = await merge({
      fixturesPath: 'test/fixtures/app/merge',
      commitMessage: 'my-app',
      to: '3.15.0',
      statsOnly: true
    });

    assertNoStaged(status);

    expect(result).to.equal(`project options: app, welcome
from version: 3.11.0-beta.1
to version: 3.15.0
output repo: https://github.com/ember-cli/ember-new-output
applicable codemods: ember-modules-codemod, ember-qunit-codemod, ember-test-helpers-codemod, es5-getter-ember-codemod, notify-property-change, qunit-dom-codemod, deprecate-merge-codemod, deprecate-router-events-codemod, cp-property-codemod, cp-volatile-codemod, cp-property-map-codemod, ember-angle-brackets-codemod`);
  });

  it('lists codemods', async function() {
    let {
      result,
      status
    } = await merge({
      fixturesPath: 'test/fixtures/codemod/local',
      commitMessage: 'my-app',
      listCodemods: true
    });

    assertNoStaged(status);

    // I'm not asserting the entire list because it can be different
    // depending on which node version the tests are running under.
    expect(JSON.parse(result)).to.have.own.property('ember-modules-codemod');
  });

  it('accepts codemods via json string', async function() {
    let {
      result,
      status
    } = await merge({
      fixturesPath: 'test/fixtures/codemod/local',
      commitMessage: 'my-app',
      listCodemods: true,
      codemodsJson: JSON.stringify({
        'test-codemod-json': {
          versions: {
            lodash: '3.0.0'
          },
          projectOptions: ['test-project', 'unused'],
          nodeVersion: '6.0.0',
          commands: []
        }
      })
    });

    assertNoStaged(status);

    expect(JSON.parse(result)).to.have.own.property('test-codemod-json');
  });

  it('can create a personal diff instead of using an output repo - app', async function() {
    this.timeout(5 * 60 * 1000);

    let {
      status
    } = await merge({
      fixturesPath: 'test/fixtures/custom/app/local',
      commitMessage: 'my-custom-app',
      createCustomDiff: true
    });

    fixtureCompare({
      mergeFixtures: 'test/fixtures/custom/app/merge/my-custom-app'
    });

    assertNoUnstaged(status);
  });

  it('can create a personal diff instead of using an output repo - addon', async function() {
    this.timeout(5 * 60 * 1000);

    let {
      status
    } = await merge({
      fixturesPath: 'test/fixtures/custom/addon/local',
      commitMessage: 'my-custom-addon',
      createCustomDiff: true
    });

    fixtureCompare({
      mergeFixtures: 'test/fixtures/custom/addon/merge/my-custom-addon'
    });

    assertNoUnstaged(status);
  });

  describe('blueprints', function() {
    this.timeout(10 * 60 * 1000);

    describe('--blueprint', function() {
      it('throws if missing --from', async function() {
        let promise = merge({
          fixturesPath: 'test/fixtures/app/local',
          commitMessage: 'my-app',
          blueprint: 'test-blueprint'
        });

        await expect(promise).to.eventually.be.rejectedWith('A custom blueprint cannot detect --from. You must supply it.');

        expect(await isGitClean({ cwd: tmpPath })).to.be.ok;
      });

      it('can update a legacy blueprint', async function() {
        let {
          location,
          version: to
        } = (await loadSafeBlueprintFile('test/fixtures/blueprint/app/legacy-app/merge/my-app')).blueprints[0];

        let {
          status
        } = await merge({
          fixturesPath: 'test/fixtures/blueprint/app/legacy-app/local',
          commitMessage: 'my-app',
          blueprint: location,
          to,
          async beforeMerge() {
            await initBlueprint({
              fixturesPath: 'test/fixtures/blueprint/app/legacy',
              resolvedFrom: tmpPath,
              relativeDir: location
            });
          }
        });

        fixtureCompare({
          mergeFixtures: 'test/fixtures/blueprint/app/legacy-app/merge/my-app'
        });

        assertNoUnstaged(status);
      });
    });

    describe('ember-cli-update.json', function() {
      it('can update a remote blueprint', async function() {
        let {
          name,
          version: to
        } = (await loadSafeBlueprintFile('test/fixtures/blueprint/app/remote-app/merge/my-app')).blueprints[0];

        let {
          status
        } = await merge({
          fixturesPath: 'test/fixtures/blueprint/app/remote-app/local',
          commitMessage: 'my-app',
          blueprint: name,
          to
        });

        fixtureCompare({
          mergeFixtures: 'test/fixtures/blueprint/app/remote-app/merge/my-app'
        });

        assertNoUnstaged(status);
      });

      it('can update an npm blueprint', async function() {
        let {
          name
        } = (await loadSafeBlueprintFile('test/fixtures/blueprint/app/npm-app/merge/my-app')).blueprints[0];

        let {
          status
        } = await merge({
          fixturesPath: 'test/fixtures/blueprint/app/npm-app/local',
          commitMessage: 'my-app',
          blueprint: name,
          to: toDefault
        });

        fixtureCompare({
          mergeFixtures: 'test/fixtures/blueprint/app/npm-app/merge/my-app'
        });

        assertNoUnstaged(status);
      });
    });
  });
});
<commit_msg>update codemod list<commit_after>'use strict';

const path = require('path');
const { describe, it } = require('../helpers/mocha');
const { expect } = require('../helpers/chai');
const sinon = require('sinon');
const {
  buildTmp,
  processExit,
  fixtureCompare: _fixtureCompare
} = require('git-fixtures');
const { isGitClean } = require('git-diff-apply');
const emberCliUpdate = require('../../src');
const utils = require('boilerplate-update/src/utils');
const {
  assertNoUnstaged,
  assertNoStaged
} = require('../helpers/assertions');
const { initBlueprint } = require('../helpers/blueprint');
const loadSafeBlueprintFile = require('../../src/load-safe-blueprint-file');

const toDefault = require('../../src/args').to.default;

describe(function() {
  this.timeout(30 * 1000);

  let cwd;
  let tmpPath;

  before(function() {
    cwd = process.cwd();
  });

  afterEach(function() {
    sinon.restore();

    process.chdir(cwd);
  });

  async function merge({
    fixturesPath,
    dirty,
    blueprint,
    from,
    to = '3.11.0-beta.1',
    reset,
    compareOnly,
    statsOnly,
    runCodemods,
    codemodsJson,
    listCodemods,
    createCustomDiff,
    commitMessage,
    beforeMerge = () => Promise.resolve(),
    afterMerge = () => Promise.resolve()
  }) {
    tmpPath = await buildTmp({
      fixturesPath,
      commitMessage,
      dirty
    });

    await beforeMerge();

    process.chdir(tmpPath);

    let promise = (async() => {
      let result = await emberCliUpdate({
        blueprint,
        from,
        to,
        reset,
        compareOnly,
        statsOnly,
        runCodemods,
        codemodsJson,
        listCodemods,
        createCustomDiff
      });

      await afterMerge();

      return result;
    })();

    return await processExit({
      promise,
      cwd: tmpPath,
      commitMessage,
      expect
    });
  }

  function fixtureCompare({
    mergeFixtures
  }) {
    let actual = tmpPath;
    let expected = path.join(cwd, mergeFixtures);

    _fixtureCompare({
      expect,
      actual,
      expected
    });
  }

  it('handles dirty', async function() {
    let {
      status,
      stderr
    } = await merge({
      fixturesPath: 'test/fixtures/app/local',
      commitMessage: 'my-app',
      dirty: true
    });

    expect(status).to.equal(`?? a-random-new-file
`);

    expect(stderr).to.contain('You must start with a clean working directory');
    expect(stderr).to.not.contain('UnhandledPromiseRejectionWarning');
  });

  it('handles non-ember-cli app', async function() {
    let promise = merge({
      fixturesPath: 'test/fixtures/package-json/non-ember-cli',
      commitMessage: 'my-app'
    });

    await expect(promise)
      .to.eventually.be.rejectedWith('Ember CLI project type could not be determined');

    expect(await isGitClean({ cwd: tmpPath })).to.be.ok;
  });

  it('handles non-npm dir', async function() {
    let {
      stderr
    } = await merge({
      fixturesPath: 'test/fixtures/package-json/missing',
      commitMessage: 'my-app'
    });

    expect(await isGitClean({ cwd: tmpPath })).to.be.ok;

    expect(stderr).to.contain('No package.json was found in this directory');
  });

  it('handles malformed package.json', async function() {
    let {
      stderr
    } = await merge({
      fixturesPath: 'test/fixtures/package-json/malformed',
      commitMessage: 'my-app'
    });

    expect(await isGitClean({ cwd: tmpPath })).to.be.ok;

    expect(stderr).to.contain('The package.json is malformed');
  });

  it('updates glimmer app', async function() {
    let {
      status
    } = await merge({
      fixturesPath: 'test/fixtures/glimmer/local',
      commitMessage: 'glimmer-app',
      from: '0.5.0',
      to: '0.6.1'
    });

    fixtureCompare({
      mergeFixtures: 'test/fixtures/glimmer/merge/glimmer-app'
    });

    expect(status).to.match(/^M {2}src\/index\.ts$/m);

    assertNoUnstaged(status);
  });

  it('needs --from if glimmer app before 0.6.3', async function() {
    let {
      stderr
    } = await merge({
      fixturesPath: 'test/fixtures/glimmer/local',
      commitMessage: 'glimmer-app',
      to: '0.6.1'
    });

    expect(await isGitClean({ cwd: tmpPath })).to.be.ok;

    expect(stderr).to.contain('version cannot be determined');
  });

  it('resets app', async function() {
    let {
      status
    } = await merge({
      fixturesPath: 'test/fixtures/app/local',
      commitMessage: 'my-app',
      reset: true,
      to: '2.11.1'
      // test the resetting logic of ember-cli-update.json
      // no longer a valid blueprint name
      // blueprint: 'ember-cli',
      // async afterMerge() {
      //   expect(path.join(tmpPath, 'config/ember-cli-update.json')).to.be.a.file()
      //     .and.equal(path.join(cwd, 'test/fixtures/ember-cli-update-json/default/config/ember-cli-update.json'));

      //   await fs.remove(path.join(tmpPath, 'config/ember-cli-update.json'));
      // }
    });

    fixtureCompare({
      mergeFixtures: 'test/fixtures/app/reset/my-app'
    });

    expect(status).to.match(/^ D app\/controllers\/application\.js$/m);

    assertNoStaged(status);
  });

  it('opens compare url', async function() {
    let open = sinon.stub(utils, 'open');

    let {
      result,
      status
    } = await merge({
      fixturesPath: 'test/fixtures/app/local',
      commitMessage: 'my-app',
      compareOnly: true
    });

    assertNoUnstaged(status);

    expect(result, 'don\'t accidentally print anything to the console').to.be.undefined;

    expect(open).to.have.been.calledOnce
      .and.to.have.been.calledWith('https://github.com/ember-cli/ember-new-output/compare/v2.11.1...v3.11.0-beta.1');
  });

  it('resolves semver ranges', async function() {
    let {
      result
    } = await merge({
      fixturesPath: 'test/fixtures/app/local',
      commitMessage: 'my-app',
      from: '1.13',
      to: '^2',
      statsOnly: true
    });

    expect(result).to.equal(`project options: app, welcome
from version: 1.13.15
to version: 2.18.2
output repo: https://github.com/ember-cli/ember-new-output
applicable codemods: `);
  });

  it('shows stats only', async function() {
    let {
      result,
      status
    } = await merge({
      fixturesPath: 'test/fixtures/app/merge',
      commitMessage: 'my-app',
      to: '3.15.0',
      statsOnly: true
    });

    assertNoStaged(status);

    expect(result).to.equal(`project options: app, welcome
from version: 3.11.0-beta.1
to version: 3.15.0
output repo: https://github.com/ember-cli/ember-new-output
applicable codemods: ember-modules-codemod, ember-qunit-codemod, ember-test-helpers-codemod, es5-getter-ember-codemod, notify-property-change, qunit-dom-codemod, deprecate-merge-codemod, deprecate-router-events-codemod, cp-property-codemod, cp-volatile-codemod, cp-property-map-codemod, ember-angle-brackets-codemod, ember-data-codemod`);
  });

  it('lists codemods', async function() {
    let {
      result,
      status
    } = await merge({
      fixturesPath: 'test/fixtures/codemod/local',
      commitMessage: 'my-app',
      listCodemods: true
    });

    assertNoStaged(status);

    // I'm not asserting the entire list because it can be different
    // depending on which node version the tests are running under.
    expect(JSON.parse(result)).to.have.own.property('ember-modules-codemod');
  });

  it('accepts codemods via json string', async function() {
    let {
      result,
      status
    } = await merge({
      fixturesPath: 'test/fixtures/codemod/local',
      commitMessage: 'my-app',
      listCodemods: true,
      codemodsJson: JSON.stringify({
        'test-codemod-json': {
          versions: {
            lodash: '3.0.0'
          },
          projectOptions: ['test-project', 'unused'],
          nodeVersion: '6.0.0',
          commands: []
        }
      })
    });

    assertNoStaged(status);

    expect(JSON.parse(result)).to.have.own.property('test-codemod-json');
  });

  it('can create a personal diff instead of using an output repo - app', async function() {
    this.timeout(5 * 60 * 1000);

    let {
      status
    } = await merge({
      fixturesPath: 'test/fixtures/custom/app/local',
      commitMessage: 'my-custom-app',
      createCustomDiff: true
    });

    fixtureCompare({
      mergeFixtures: 'test/fixtures/custom/app/merge/my-custom-app'
    });

    assertNoUnstaged(status);
  });

  it('can create a personal diff instead of using an output repo - addon', async function() {
    this.timeout(5 * 60 * 1000);

    let {
      status
    } = await merge({
      fixturesPath: 'test/fixtures/custom/addon/local',
      commitMessage: 'my-custom-addon',
      createCustomDiff: true
    });

    fixtureCompare({
      mergeFixtures: 'test/fixtures/custom/addon/merge/my-custom-addon'
    });

    assertNoUnstaged(status);
  });

  describe('blueprints', function() {
    this.timeout(10 * 60 * 1000);

    describe('--blueprint', function() {
      it('throws if missing --from', async function() {
        let promise = merge({
          fixturesPath: 'test/fixtures/app/local',
          commitMessage: 'my-app',
          blueprint: 'test-blueprint'
        });

        await expect(promise).to.eventually.be.rejectedWith('A custom blueprint cannot detect --from. You must supply it.');

        expect(await isGitClean({ cwd: tmpPath })).to.be.ok;
      });

      it('can update a legacy blueprint', async function() {
        let {
          location,
          version: to
        } = (await loadSafeBlueprintFile('test/fixtures/blueprint/app/legacy-app/merge/my-app')).blueprints[0];

        let {
          status
        } = await merge({
          fixturesPath: 'test/fixtures/blueprint/app/legacy-app/local',
          commitMessage: 'my-app',
          blueprint: location,
          to,
          async beforeMerge() {
            await initBlueprint({
              fixturesPath: 'test/fixtures/blueprint/app/legacy',
              resolvedFrom: tmpPath,
              relativeDir: location
            });
          }
        });

        fixtureCompare({
          mergeFixtures: 'test/fixtures/blueprint/app/legacy-app/merge/my-app'
        });

        assertNoUnstaged(status);
      });
    });

    describe('ember-cli-update.json', function() {
      it('can update a remote blueprint', async function() {
        let {
          name,
          version: to
        } = (await loadSafeBlueprintFile('test/fixtures/blueprint/app/remote-app/merge/my-app')).blueprints[0];

        let {
          status
        } = await merge({
          fixturesPath: 'test/fixtures/blueprint/app/remote-app/local',
          commitMessage: 'my-app',
          blueprint: name,
          to
        });

        fixtureCompare({
          mergeFixtures: 'test/fixtures/blueprint/app/remote-app/merge/my-app'
        });

        assertNoUnstaged(status);
      });

      it('can update an npm blueprint', async function() {
        let {
          name
        } = (await loadSafeBlueprintFile('test/fixtures/blueprint/app/npm-app/merge/my-app')).blueprints[0];

        let {
          status
        } = await merge({
          fixturesPath: 'test/fixtures/blueprint/app/npm-app/local',
          commitMessage: 'my-app',
          blueprint: name,
          to: toDefault
        });

        fixtureCompare({
          mergeFixtures: 'test/fixtures/blueprint/app/npm-app/merge/my-app'
        });

        assertNoUnstaged(status);
      });
    });
  });
});
<|endoftext|>


<commit_before>windmill.jsTest.require('shared.js');

windmillMain.test_timer = new function () {
  this.setup = windmillMain.shared.test_navMain;
  this.test_timerObj = function () {
    var t = new windmill.jsTest.Timer();
    t.start();
    var str = '';
    while (str.length < 10000) {
      str += 'asdf';
    }
    t.finish();
    jum.assertTrue(t.time > 0);
  };
};

<commit_msg>Some browsers take zero amount of time to perform string concat operations.<commit_after>windmill.jsTest.require('shared.js');

windmillMain.test_timer = new function () {
  this.setup = windmillMain.shared.test_navMain;
  this.test_timerObj = function () {
    var t = new windmill.jsTest.Timer();
    t.start();
    var str = '';
    while (str.length < 10000) {
      str += 'asdf';
    }
    t.finish();
    // t.time should be a number -- may actually
    // zero in Safari
    jum.assertTrue(!isNaN(t.time));
  };
};

<|endoftext|>


<commit_before>const Everything = imports.gi.Everything;
if (!('assertEquals' in this)) { /* allow running this test standalone */
    imports.lang.copyPublicProperties(imports.jsUnit, this);
    gjstestRun = function() { return imports.jsUnit.gjstestRun(window); };
}

// We use Gio to have some objects that we know exist
const Gio = imports.gi.Gio;

const INT8_MIN = (-128);
const INT16_MIN = (-32767-1);
const INT32_MIN = (-2147483647-1);
const INT64_MIN = (-9223372036854775807-1);

const INT8_MAX = (127);
const INT16_MAX = (32767);
const INT32_MAX = (2147483647);
const INT64_MAX = (9223372036854775807);

const UINT8_MAX = (255);
const UINT16_MAX = (65535);
const UINT32_MAX = (4294967295);
const UINT64_MAX = (18446744073709551615);

function testLifeUniverseAndEverything() {
    assertEquals(false, Everything.test_boolean(false));
    assertEquals(true, Everything.test_boolean(true));

    assertEquals(42, Everything.test_int8(42));
    assertEquals(-42, Everything.test_int8(-42));

    assertEquals(42, Everything.test_uint8(42));

    assertEquals(42, Everything.test_int16(42));
    assertEquals(-42, Everything.test_int16(-42));

    assertEquals(42, Everything.test_uint16(42));

    assertEquals(42, Everything.test_int32(42));
    assertEquals(-42, Everything.test_int32(-42));

    assertEquals(42, Everything.test_uint32(42));

    assertEquals(42, Everything.test_int64(42));
    assertEquals(-42, Everything.test_int64(-42));

    assertEquals(42, Everything.test_uint64(42));

    assertEquals(42, Everything.test_int(42));
    assertEquals(-42, Everything.test_int(-42));

    assertEquals(42, Everything.test_uint(42));

    assertEquals(42, Everything.test_long(42));
    assertEquals(-42, Everything.test_long(-42));

    assertEquals(42, Everything.test_ulong(42));

    assertEquals(42, Everything.test_ssize(42));
    assertEquals(-42, Everything.test_ssize(-42));

    assertEquals(42, Everything.test_size(42));

    assertEquals(42, Everything.test_float(42));
    assertEquals(-42, Everything.test_float(-42));

    assertEquals(42, Everything.test_double(42));
    assertEquals(-42, Everything.test_double(-42));

    let now = new Date();
    let bounced = Everything.test_timet(now);
    assertEquals(now.getFullYear(), bounced.getFullYear());
    assertEquals(now.getMonth(), bounced.getMonth());
    assertEquals(now.getDay(), bounced.getDay());
    assertEquals(now.getHours(), bounced.getHours());
    assertEquals(now.getSeconds(), bounced.getSeconds());
}

function testLimits() {
    assertEquals(UINT8_MAX, Everything.test_uint8(UINT8_MAX));
    assertEquals(UINT16_MAX, Everything.test_uint16(UINT16_MAX));
    assertEquals(UINT32_MAX, Everything.test_uint32(UINT32_MAX));

    // FAIL: expected 18446744073709552000, got 0
    //assertEquals(UINT64_MAX, Everything.test_uint64(UINT64_MAX));

    assertEquals(INT8_MIN, Everything.test_int8(INT8_MIN));
    assertEquals(INT8_MAX, Everything.test_int8(INT8_MAX));
    assertEquals(INT16_MIN, Everything.test_int16(INT16_MIN));
    assertEquals(INT16_MAX, Everything.test_int16(INT16_MAX));
    assertEquals(INT32_MIN, Everything.test_int32(INT32_MIN));
    assertEquals(INT32_MAX, Everything.test_int32(INT32_MAX));
    assertEquals(INT64_MIN, Everything.test_int64(INT64_MIN));

    // FAIL: expected 9223372036854776000, got -9223372036854776000
    //assertEquals(INT64_MAX, Everything.test_int64(INT64_MAX));
}

function testNoImplicitConversionToUnsigned() {
    assertRaises(function() { return Everything.test_uint8(-42); });
    assertRaises(function() { return Everything.test_uint16(-42); });
    assertRaises(function() { return Everything.test_uint32(-42); });

    assertRaises(function() { return Everything.test_uint64(-42); });

    assertRaises(function() { return Everything.test_uint(-42); });
    assertRaises(function() { return Everything.test_size(-42); });
}

function testBadConstructor() {
    try {
	Gio.AppLaunchContext();
    } catch (e) {
	assert(e.message.indexOf("Constructor called as normal method") >= 0);
    }
}

function testStrv() {
    assertTrue(Everything.test_strv_in(['1', '2', '3']));
    // Second two are deliberately not strings
    assertRaises(function() { Everything.test_strv_in(['1', 2, 3]); });

    // FIXME: Everything.test_strv_out not implemented.
}

function testUtf8() {
    const CONST_STR = "const \u2665 utf8";
    const NONCONST_STR = "nonconst \u2665 utf8";

    assertEquals(CONST_STR, Everything.test_utf8_const_return());
    assertEquals(NONCONST_STR, Everything.test_utf8_nonconst_return());
    Everything.test_utf8_nonconst_in(NONCONST_STR);
    Everything.test_utf8_const_in(CONST_STR);
    assertEquals(NONCONST_STR, Everything.test_utf8_out());
    assertEquals(NONCONST_STR, Everything.test_utf8_inout(CONST_STR));
}

function testFilenameReturn() {
    var filenames = Everything.test_filename_return();
    assertEquals(2, filenames.length);
    assertEquals('\u00e5\u00e4\u00f6', filenames[0]);
    assertEquals('/etc/fstab', filenames[1]);
}

function testStaticMeth() {
    let v = Everything.TestObj.new_from_file("/enoent");
    assertTrue(v instanceof Everything.TestObj);
}

function testClosure() {
    let someCallback = function() {
                           return 42;
                       };

    let i = Everything.test_closure(someCallback);

    assertEquals('callback return value', 42, i);
}

function testClosureOneArg() {
    let someCallback = function(someValue) {
                           return someValue;
                       };

    let i = Everything.test_closure_one_arg(someCallback, 42);

    assertEquals('callback with one arg return value', 42, i);
}

function testIntValueArg() {
    let i = Everything.test_int_value_arg(42);
    assertEquals('Method taking a GValue', 42, i);
}

function testValueReturn() {
    let i = Everything.test_value_return(42);
    assertEquals('Method returning a GValue', 42, i);
}

/* GList types */
function testGListOut() {
    assertEquals("1,2,3", Everything.test_glist_nothing_return().join(','));
    assertEquals("1,2,3", Everything.test_glist_nothing_return2().join(','));
    assertEquals("1,2,3", Everything.test_glist_container_return().join(','));
    assertEquals("1,2,3", Everything.test_glist_everything_return().join(','));
}
function testGListIn() {
    const STR_LIST = ["1", "2", "3" ];
    Everything.test_glist_nothing_in(STR_LIST);
    Everything.test_glist_nothing_in2(STR_LIST);
    //Everything.test_glist_container_in(STR_LIST);
    Everything.test_glist_everything_in(STR_LIST);
}

/* GSList types */
function testGSListOut() {
    assertEquals("1,2,3", Everything.test_gslist_nothing_return().join(','));
    assertEquals("1,2,3", Everything.test_gslist_nothing_return2().join(','));
    assertEquals("1,2,3", Everything.test_gslist_container_return().join(','));
    assertEquals("1,2,3", Everything.test_gslist_everything_return().join(','));
}
function testGSListIn() {
    const STR_LIST = ["1", "2", "3" ];
    Everything.test_gslist_nothing_in(STR_LIST);
    Everything.test_gslist_nothing_in2(STR_LIST);
    //Everything.test_gslist_container_in(STR_LIST);
    Everything.test_gslist_everything_in(STR_LIST);
}

/* Array tests */
function testArrayIn() {
    assertEquals(10, Everything.test_array_int_in(4, [1,2,3,4]));
    assertEquals(10, Everything.test_array_gint8_in(4, [1,2,3,4]));
    assertEquals(10, Everything.test_array_gint16_in(4, [1,2,3,4]));
    assertEquals(10, Everything.test_array_gint32_in(4, [1,2,3,4]));
    // FIXME: arrays of int64 are unimplemented
    //assertEquals(10, Everything.test_array_gint64_in(4, [1,2,3,4]));

    // implicit conversions from strings to int arrays
    assertEquals(10, Everything.test_array_gint8_in(4, "\x01\x02\x03\x04"));
    assertEquals(10, Everything.test_array_gint16_in(4, "\x01\x02\x03\x04"));
    assertEquals(2560, Everything.test_array_gint16_in(4, "\u0100\u0200\u0300\u0400"));
}

function testArrayOut() {
    // FIXME: test_array_int_full_out and test_array_int_none_out unimplemented
}

/* GHash type */
function testGHashOut() {
    const HASH_STR = '({foo:"bar", baz:"bat", qux:"quux"})';
    assertEquals(null, Everything.test_ghash_null_return());
    assertEquals(HASH_STR, Everything.test_ghash_nothing_return().toSource());
    assertEquals(HASH_STR, Everything.test_ghash_nothing_return2().toSource());
    assertEquals(HASH_STR, Everything.test_ghash_container_return().toSource());
    assertEquals(HASH_STR, Everything.test_ghash_everything_return().toSource());
}

function testGHashIn() {
    const STR_HASH = { foo: 'bar', baz: 'bat', qux: 'quux' };
    Everything.test_ghash_null_in(null);
    Everything.test_ghash_nothing_in(STR_HASH);
    Everything.test_ghash_nothing_in2(STR_HASH);
    //Everything.test_ghash_container_in(STR_HASH);
    Everything.test_ghash_everything_in(STR_HASH);
}

function testNestedGHashOut() {
    const HASH_STR = '({wibble:{foo:"bar", baz:"bat", qux:"quux"}})';
    assertEquals(HASH_STR, Everything.test_ghash_nested_everything_return().toSource());
    assertEquals(HASH_STR, Everything.test_ghash_nested_everything_return2().toSource());
}

/* Enums */
function testEnumParam() {
   let e = Everything.test_enum_param(Everything.TestEnum.VALUE1);
   assertEquals('Enum parameter', 'value1', e);
}

function testSignal() {
    let handlerCounter = 0;
    let o = new Everything.TestObj();
    let theObject = null;

    let handlerId = o.connect('test', function(signalObject) {
                                          handlerCounter ++;
                                          theObject = signalObject;
                                          o.disconnect(handlerId);
                                      });

    o.emit('test');
    assertEquals('handler callled', 1, handlerCounter);
    assertEquals('Signal handlers gets called with right object', o, theObject);
    o.emit('test');
    assertEquals('disconnected handler not called', 1, handlerCounter);
}

function testInvalidSignal() {
    let o = new Everything.TestObj();

    assertRaises('connect to invalid signal',
                 function() { o.connect('invalid-signal', function(o) {}); });
    assertRaises('emit invalid signal',
                 function() { o.emit('invalid-signal'); });
}

function testSignalWithStaticScopeArg() {
    let o = new Everything.TestObj();
    let b = new Everything.TestSimpleBoxedA({ some_int: 42,
                                              some_int8: 43,
                                              some_double: 42.5,
                                              some_enum: Everything.TestEnum.VALUE3 });

    o.connect('test-with-static-scope-arg', function(signalObject, signalArg) {
                                                signalArg.some_int = 44;
                                            });

    o.emit('test-with-static-scope-arg', b);
    assertEquals('signal handler was passed arg as reference', 44, b.some_int);
}

gjstestRun();
<commit_msg>temporarily comment out test_ghash_nested_everything_return usage<commit_after>const Everything = imports.gi.Everything;
if (!('assertEquals' in this)) { /* allow running this test standalone */
    imports.lang.copyPublicProperties(imports.jsUnit, this);
    gjstestRun = function() { return imports.jsUnit.gjstestRun(window); };
}

// We use Gio to have some objects that we know exist
const Gio = imports.gi.Gio;

const INT8_MIN = (-128);
const INT16_MIN = (-32767-1);
const INT32_MIN = (-2147483647-1);
const INT64_MIN = (-9223372036854775807-1);

const INT8_MAX = (127);
const INT16_MAX = (32767);
const INT32_MAX = (2147483647);
const INT64_MAX = (9223372036854775807);

const UINT8_MAX = (255);
const UINT16_MAX = (65535);
const UINT32_MAX = (4294967295);
const UINT64_MAX = (18446744073709551615);

function testLifeUniverseAndEverything() {
    assertEquals(false, Everything.test_boolean(false));
    assertEquals(true, Everything.test_boolean(true));

    assertEquals(42, Everything.test_int8(42));
    assertEquals(-42, Everything.test_int8(-42));

    assertEquals(42, Everything.test_uint8(42));

    assertEquals(42, Everything.test_int16(42));
    assertEquals(-42, Everything.test_int16(-42));

    assertEquals(42, Everything.test_uint16(42));

    assertEquals(42, Everything.test_int32(42));
    assertEquals(-42, Everything.test_int32(-42));

    assertEquals(42, Everything.test_uint32(42));

    assertEquals(42, Everything.test_int64(42));
    assertEquals(-42, Everything.test_int64(-42));

    assertEquals(42, Everything.test_uint64(42));

    assertEquals(42, Everything.test_int(42));
    assertEquals(-42, Everything.test_int(-42));

    assertEquals(42, Everything.test_uint(42));

    assertEquals(42, Everything.test_long(42));
    assertEquals(-42, Everything.test_long(-42));

    assertEquals(42, Everything.test_ulong(42));

    assertEquals(42, Everything.test_ssize(42));
    assertEquals(-42, Everything.test_ssize(-42));

    assertEquals(42, Everything.test_size(42));

    assertEquals(42, Everything.test_float(42));
    assertEquals(-42, Everything.test_float(-42));

    assertEquals(42, Everything.test_double(42));
    assertEquals(-42, Everything.test_double(-42));

    let now = new Date();
    let bounced = Everything.test_timet(now);
    assertEquals(now.getFullYear(), bounced.getFullYear());
    assertEquals(now.getMonth(), bounced.getMonth());
    assertEquals(now.getDay(), bounced.getDay());
    assertEquals(now.getHours(), bounced.getHours());
    assertEquals(now.getSeconds(), bounced.getSeconds());
}

function testLimits() {
    assertEquals(UINT8_MAX, Everything.test_uint8(UINT8_MAX));
    assertEquals(UINT16_MAX, Everything.test_uint16(UINT16_MAX));
    assertEquals(UINT32_MAX, Everything.test_uint32(UINT32_MAX));

    // FAIL: expected 18446744073709552000, got 0
    //assertEquals(UINT64_MAX, Everything.test_uint64(UINT64_MAX));

    assertEquals(INT8_MIN, Everything.test_int8(INT8_MIN));
    assertEquals(INT8_MAX, Everything.test_int8(INT8_MAX));
    assertEquals(INT16_MIN, Everything.test_int16(INT16_MIN));
    assertEquals(INT16_MAX, Everything.test_int16(INT16_MAX));
    assertEquals(INT32_MIN, Everything.test_int32(INT32_MIN));
    assertEquals(INT32_MAX, Everything.test_int32(INT32_MAX));
    assertEquals(INT64_MIN, Everything.test_int64(INT64_MIN));

    // FAIL: expected 9223372036854776000, got -9223372036854776000
    //assertEquals(INT64_MAX, Everything.test_int64(INT64_MAX));
}

function testNoImplicitConversionToUnsigned() {
    assertRaises(function() { return Everything.test_uint8(-42); });
    assertRaises(function() { return Everything.test_uint16(-42); });
    assertRaises(function() { return Everything.test_uint32(-42); });

    assertRaises(function() { return Everything.test_uint64(-42); });

    assertRaises(function() { return Everything.test_uint(-42); });
    assertRaises(function() { return Everything.test_size(-42); });
}

function testBadConstructor() {
    try {
	Gio.AppLaunchContext();
    } catch (e) {
	assert(e.message.indexOf("Constructor called as normal method") >= 0);
    }
}

function testStrv() {
    assertTrue(Everything.test_strv_in(['1', '2', '3']));
    // Second two are deliberately not strings
    assertRaises(function() { Everything.test_strv_in(['1', 2, 3]); });

    // FIXME: Everything.test_strv_out not implemented.
}

function testUtf8() {
    const CONST_STR = "const \u2665 utf8";
    const NONCONST_STR = "nonconst \u2665 utf8";

    assertEquals(CONST_STR, Everything.test_utf8_const_return());
    assertEquals(NONCONST_STR, Everything.test_utf8_nonconst_return());
    Everything.test_utf8_nonconst_in(NONCONST_STR);
    Everything.test_utf8_const_in(CONST_STR);
    assertEquals(NONCONST_STR, Everything.test_utf8_out());
    assertEquals(NONCONST_STR, Everything.test_utf8_inout(CONST_STR));
}

function testFilenameReturn() {
    var filenames = Everything.test_filename_return();
    assertEquals(2, filenames.length);
    assertEquals('\u00e5\u00e4\u00f6', filenames[0]);
    assertEquals('/etc/fstab', filenames[1]);
}

function testStaticMeth() {
    let v = Everything.TestObj.new_from_file("/enoent");
    assertTrue(v instanceof Everything.TestObj);
}

function testClosure() {
    let someCallback = function() {
                           return 42;
                       };

    let i = Everything.test_closure(someCallback);

    assertEquals('callback return value', 42, i);
}

function testClosureOneArg() {
    let someCallback = function(someValue) {
                           return someValue;
                       };

    let i = Everything.test_closure_one_arg(someCallback, 42);

    assertEquals('callback with one arg return value', 42, i);
}

function testIntValueArg() {
    let i = Everything.test_int_value_arg(42);
    assertEquals('Method taking a GValue', 42, i);
}

function testValueReturn() {
    let i = Everything.test_value_return(42);
    assertEquals('Method returning a GValue', 42, i);
}

/* GList types */
function testGListOut() {
    assertEquals("1,2,3", Everything.test_glist_nothing_return().join(','));
    assertEquals("1,2,3", Everything.test_glist_nothing_return2().join(','));
    assertEquals("1,2,3", Everything.test_glist_container_return().join(','));
    assertEquals("1,2,3", Everything.test_glist_everything_return().join(','));
}
function testGListIn() {
    const STR_LIST = ["1", "2", "3" ];
    Everything.test_glist_nothing_in(STR_LIST);
    Everything.test_glist_nothing_in2(STR_LIST);
    //Everything.test_glist_container_in(STR_LIST);
    Everything.test_glist_everything_in(STR_LIST);
}

/* GSList types */
function testGSListOut() {
    assertEquals("1,2,3", Everything.test_gslist_nothing_return().join(','));
    assertEquals("1,2,3", Everything.test_gslist_nothing_return2().join(','));
    assertEquals("1,2,3", Everything.test_gslist_container_return().join(','));
    assertEquals("1,2,3", Everything.test_gslist_everything_return().join(','));
}
function testGSListIn() {
    const STR_LIST = ["1", "2", "3" ];
    Everything.test_gslist_nothing_in(STR_LIST);
    Everything.test_gslist_nothing_in2(STR_LIST);
    //Everything.test_gslist_container_in(STR_LIST);
    Everything.test_gslist_everything_in(STR_LIST);
}

/* Array tests */
function testArrayIn() {
    assertEquals(10, Everything.test_array_int_in(4, [1,2,3,4]));
    assertEquals(10, Everything.test_array_gint8_in(4, [1,2,3,4]));
    assertEquals(10, Everything.test_array_gint16_in(4, [1,2,3,4]));
    assertEquals(10, Everything.test_array_gint32_in(4, [1,2,3,4]));
    // FIXME: arrays of int64 are unimplemented
    //assertEquals(10, Everything.test_array_gint64_in(4, [1,2,3,4]));

    // implicit conversions from strings to int arrays
    assertEquals(10, Everything.test_array_gint8_in(4, "\x01\x02\x03\x04"));
    assertEquals(10, Everything.test_array_gint16_in(4, "\x01\x02\x03\x04"));
    assertEquals(2560, Everything.test_array_gint16_in(4, "\u0100\u0200\u0300\u0400"));
}

function testArrayOut() {
    // FIXME: test_array_int_full_out and test_array_int_none_out unimplemented
}

/* GHash type */
function testGHashOut() {
    const HASH_STR = '({foo:"bar", baz:"bat", qux:"quux"})';
    assertEquals(null, Everything.test_ghash_null_return());
    assertEquals(HASH_STR, Everything.test_ghash_nothing_return().toSource());
    assertEquals(HASH_STR, Everything.test_ghash_nothing_return2().toSource());
    assertEquals(HASH_STR, Everything.test_ghash_container_return().toSource());
    assertEquals(HASH_STR, Everything.test_ghash_everything_return().toSource());
}

function testGHashIn() {
    const STR_HASH = { foo: 'bar', baz: 'bat', qux: 'quux' };
    Everything.test_ghash_null_in(null);
    Everything.test_ghash_nothing_in(STR_HASH);
    Everything.test_ghash_nothing_in2(STR_HASH);
    //Everything.test_ghash_container_in(STR_HASH);
    Everything.test_ghash_everything_in(STR_HASH);
}

function testNestedGHashOut() {
    const HASH_STR = '({wibble:{foo:"bar", baz:"bat", qux:"quux"}})';
    // FIXME uncomment this when it's added to everything module
    //assertEquals(HASH_STR, Everything.test_ghash_nested_everything_return().toSource());
    //assertEquals(HASH_STR, Everything.test_ghash_nested_everything_return2().toSource());
}

/* Enums */
function testEnumParam() {
   let e = Everything.test_enum_param(Everything.TestEnum.VALUE1);
   assertEquals('Enum parameter', 'value1', e);
}

function testSignal() {
    let handlerCounter = 0;
    let o = new Everything.TestObj();
    let theObject = null;

    let handlerId = o.connect('test', function(signalObject) {
                                          handlerCounter ++;
                                          theObject = signalObject;
                                          o.disconnect(handlerId);
                                      });

    o.emit('test');
    assertEquals('handler callled', 1, handlerCounter);
    assertEquals('Signal handlers gets called with right object', o, theObject);
    o.emit('test');
    assertEquals('disconnected handler not called', 1, handlerCounter);
}

function testInvalidSignal() {
    let o = new Everything.TestObj();

    assertRaises('connect to invalid signal',
                 function() { o.connect('invalid-signal', function(o) {}); });
    assertRaises('emit invalid signal',
                 function() { o.emit('invalid-signal'); });
}

function testSignalWithStaticScopeArg() {
    let o = new Everything.TestObj();
    let b = new Everything.TestSimpleBoxedA({ some_int: 42,
                                              some_int8: 43,
                                              some_double: 42.5,
                                              some_enum: Everything.TestEnum.VALUE3 });

    o.connect('test-with-static-scope-arg', function(signalObject, signalArg) {
                                                signalArg.some_int = 44;
                                            });

    o.emit('test-with-static-scope-arg', b);
    assertEquals('signal handler was passed arg as reference', 44, b.some_int);
}

gjstestRun();
<|endoftext|>


<commit_before>
// internal libs
import Eventhandler from 'src/libs/eventhandler';

// external libs
import sinon from 'sinon';

describe('Eventhandler Class', () => {

	describe('Eventhandler.prepareEventDomain', () => {

		it('should prepare eventDomain string into event and delegateSelector', () => {

			Eventhandler.prepareEventdomain('click').should.containDeep(['click', null]);
			Eventhandler.prepareEventdomain('dbclick .abc').should.containDeep(['dbclick', '.abc']);
			Eventhandler.prepareEventdomain('mouseup .abc .def').should.containDeep(['mouseup', '.abc .def']);

		});

	});

	// generic functions
	let foo = function foo(){};
	let bar = function bar(){};
	let baz = function baz(){};
	let boo = function boo(){};
	let koo = function koo(){};
	let naz = function naz(){};

	describe('Evenhandler.prototype.getHandlers', () => {

		it('should return callback/s by given event', () => {

			let eventHandler = Eventhandler.create({
				events : {
					"a .foo": foo,
					"a .bar": bar,
					"b .baz": baz,
					"b .boo": boo,
					"c .koo": koo,
					"d"     : naz,
				},
				element: document.createElement("div"),
				bind: {},
			});

			// test
			eventHandler.getHandlers('a').should.have.length(2);
			eventHandler.getHandlers('b').should.have.length(2);
			eventHandler.getHandlers('c').should.have.length(1);
			eventHandler.getHandlers('d').should.have.length(1);
			// negativ test
			let testObject = { f: eventHandler.getHandlers('f') };
			testObject.should.have.propertyByPath('f').eql(null);

		});

	});

	describe('Evenhandler.groupEvents', () => {

		it('should groupby event type', () => {

			let passedObject = {
				"click .foo"  : foo,
				"mouseup .boo": boo,
				"click .bar"  : bar,
				"mouseup .koo": koo,
				"click .baz"  : baz,
				"mousedown"   : naz,
			}

		   /**
			* #### Excepted grouped object ####
			*
			* groupedObject {
			* 	"click" : [
			* 		{ ".foo": function foo(){} },
			* 		{ ".bar": function bar(){} },
			* 	],
			* 	"mouseup": [
			* 		{ ".boo": function foo(){} },
			* 		{ ".koo": function koo(){} },
			* 	],
			* 	"mousedown": [
			* 		{ null:  naz},
			* 		{ null:  laz},
			* 	],
			* }
			**/

			// group events
			let groupedObject = Eventhandler.groupEvents(passedObject);
			// tests click group
			groupedObject.should.have.propertyByPath("click", 0, ".foo").eql(foo);
			groupedObject.should.have.propertyByPath("click", 1, ".bar").eql(bar);
			groupedObject.should.have.propertyByPath("click", 2, ".baz").eql(baz);
			// tests mouseup group
			groupedObject.should.have.propertyByPath("mouseup", 0, ".boo").eql(boo);
			groupedObject.should.have.propertyByPath("mouseup", 1, ".koo").eql(koo);
			// test without delegateSelector
			groupedObject.should.have.propertyByPath("mousedown", 0, null).equal(naz)

		});

	});

	describe('Eventhandler.create() and Eventhandler.prototype.removeEvent', () => {

		let clickFoo = function() {};
		let mouseupBoo = function() {};
		let clickBar = function() { this.someMethod(); };
		let mouseupKoo = function() {};
		let clickBaz = function() {};
		let mouseDown = function() {};

		let element = document.createElement('div');
		let bindObject = {
			someMethod : function(){},
		};

		let clickCallbacks = null;

		beforeEach(() => {

			element = document.createElement("div");
			element.innerHTML = `

Foo

Bar

Baz

Boo

Koo

			`;
			document.body.appendChild(element);

		});

		afterEach(() => {
			document.body.removeChild(element);
		});

		it('should trigger and remove events', () => {

			let eventHandler = Eventhandler.create({
				events : {
					"click .foo"  : clickFoo,
					"click .bar"  : clickBar,
					"click .baz"  : clickBaz,
					"mouseup .boo": mouseupBoo,
					"mouseup .koo": mouseupKoo,
					"mousedown"   : mouseDown,
				},
				element: element,
				bind: bindObject,
			});

			/**
			 * INFO to the test:
			 * except click all other native events can not be easily simulated.
			 * Mouseup, Mousedown was tested manually.
			 */

			// setup tests (spying)
			// test click
			clickCallbacks = eventHandler.getHandlers('click');
			sinon.spy(clickCallbacks[0], ".foo");
			sinon.spy(clickCallbacks[1], ".bar");
			sinon.spy(clickCallbacks[2], ".baz");
			sinon.spy(bindObject, "someMethod");

			// test click event
			element.querySelector('.baz').click();
			clickCallbacks[0][".foo"].callCount.should.eql(0);
			clickCallbacks[1][".bar"].callCount.should.eql(0);
			clickCallbacks[2][".baz"].callCount.should.eql(1);

			element.querySelector('.foo').click();
			clickCallbacks[0][".foo"].callCount.should.eql(1);
			clickCallbacks[1][".bar"].callCount.should.eql(0);
			clickCallbacks[2][".baz"].callCount.should.eql(1);

			element.querySelector('.bar').click();
			clickCallbacks[0][".foo"].callCount.should.eql(1);
			clickCallbacks[1][".bar"].callCount.should.eql(1);
			clickCallbacks[2][".baz"].callCount.should.eql(1);

			// test bind object
			bindObject.someMethod.callCount.should.eql(1);

			// cleanup spyies
			clickCallbacks[0][".foo"].restore();
			clickCallbacks[1][".bar"].restore();
			clickCallbacks[2][".baz"].restore();
			bindObject["someMethod"].restore();

			// test removeEvent
			eventHandler.removeEvent('click .foo');
			eventHandler.getHandlers('click').should.have.length(2);

			eventHandler.removeEvent('mouseup .boo');
			eventHandler.getHandlers('mouseup').should.have.length(1);

			eventHandler.removeEvent('click');
			let clickTestObject = { click: eventHandler.getHandlers('click') };
			clickTestObject.should.have.propertyByPath('click').eql(null);

			eventHandler.removeEvent('mouseup .koo');
			let mouseupTestObject = { mouseup: eventHandler.getHandlers('mouseup') };
			mouseupTestObject.should.have.propertyByPath('mouseup').eql(null);

			eventHandler.removeEvent('mousedown');
			Object.keys(eventHandler.config.events).should.have.length(0);

		});

			// test removeEvent
			eventHandler.removeEvent('click .foo');
			eventHandler.getHandlers('click').should.have.length(2);

			eventHandler.removeEvent('mouseup .boo');
			eventHandler.getHandlers('mouseup').should.have.length(1);

			eventHandler.removeEvent('click');
			let clickTestObject = { click: eventHandler.getHandlers('click') };
			clickTestObject.should.have.propertyByPath('click').eql(null);

			eventHandler.removeEvent('mouseup .koo');
			let mouseupTestObject = { mouseup: eventHandler.getHandlers('mouseup') };
			mouseupTestObject.should.have.propertyByPath('mouseup').eql(null);

			eventHandler.removeEvent('mousedown');
			Object.keys(eventHandler.config.events).should.have.length(0);

		});

	});

});
<commit_msg>Eventhandler.test: added tests for new method "on"<commit_after>
// internal libs
import Eventhandler from 'src/libs/eventhandler';

// external libs
import sinon from 'sinon';

describe('Eventhandler Class', () => {

	describe('Eventhandler.prepareEventDomain', () => {

		it('should prepare eventDomain string into event and delegateSelector', () => {

			Eventhandler.prepareEventdomain('click').should.containDeep(['click', null]);
			Eventhandler.prepareEventdomain('dbclick .abc').should.containDeep(['dbclick', '.abc']);
			Eventhandler.prepareEventdomain('mouseup .abc .def').should.containDeep(['mouseup', '.abc .def']);

		});

	});

	// generic functions
	let foo = function foo(){};
	let bar = function bar(){};
	let baz = function baz(){};
	let boo = function boo(){};
	let koo = function koo(){};
	let naz = function naz(){};

	describe('Evenhandler.prototype.getHandlers', () => {

		it('should return callback/s by given event', () => {

			let eventHandler = Eventhandler.create({
				events : {
					"a .foo": foo,
					"a .bar": bar,
					"b .baz": baz,
					"b .boo": boo,
					"c .koo": koo,
					"d"     : naz,
				},
				element: document.createElement("div"),
				bind: {},
			});

			// test
			eventHandler.getHandlers('a').should.have.length(2);
			eventHandler.getHandlers('b').should.have.length(2);
			eventHandler.getHandlers('c').should.have.length(1);
			eventHandler.getHandlers('d').should.have.length(1);
			// negativ test
			let testObject = { f: eventHandler.getHandlers('f') };
			testObject.should.have.propertyByPath('f').eql(null);

		});

	});

	describe('Evenhandler.groupEvents', () => {

		it('should groupby event type', () => {

			let passedObject = {
				"click .foo"  : foo,
				"mouseup .boo": boo,
				"click .bar"  : bar,
				"mouseup .koo": koo,
				"click .baz"  : baz,
				"mousedown"   : naz,
			}

		   /**
			* #### Excepted grouped object ####
			*
			* groupedObject {
			* 	"click" : [
			* 		{ ".foo": function foo(){} },
			* 		{ ".bar": function bar(){} },
			* 	],
			* 	"mouseup": [
			* 		{ ".boo": function foo(){} },
			* 		{ ".koo": function koo(){} },
			* 	],
			* 	"mousedown": [
			* 		{ null:  naz},
			* 		{ null:  laz},
			* 	],
			* }
			**/

			// group events
			let groupedObject = Eventhandler.groupEvents(passedObject);
			// tests click group
			groupedObject.should.have.propertyByPath("click", 0, ".foo").eql(foo);
			groupedObject.should.have.propertyByPath("click", 1, ".bar").eql(bar);
			groupedObject.should.have.propertyByPath("click", 2, ".baz").eql(baz);
			// tests mouseup group
			groupedObject.should.have.propertyByPath("mouseup", 0, ".boo").eql(boo);
			groupedObject.should.have.propertyByPath("mouseup", 1, ".koo").eql(koo);
			// test without delegateSelector
			groupedObject.should.have.propertyByPath("mousedown", 0, null).equal(naz)

		});

	});

	describe('Eventhandler.create() and Eventhandler.prototype.removeEvent', () => {

		let clickFoo = function() {};
		let mouseupBoo = function() {};
		let clickBar = function() { this.someMethod(); };
		let mouseupKoo = function() {};
		let clickBaz = function() {};
		let mouseDown = function() {};

		let element = document.createElement('div');
		let bindObject = {
			someMethod : function(){},
		};

		let clickCallbacks = null;

		beforeEach(() => {

			element = document.createElement("div");
			element.innerHTML = `

Foo

Bar

Baz

Boo

Koo

			`;
			document.body.appendChild(element);

		});

		afterEach(() => {
			document.body.removeChild(element);
		});

		it('should trigger and remove events', () => {

			let eventHandler = Eventhandler.create({
				events : {
					"click .foo"  : clickFoo,
					"click .bar"  : clickBar,
					"click .baz"  : clickBaz,
					"mouseup .boo": mouseupBoo,
					"mouseup .koo": mouseupKoo,
					"mousedown"   : mouseDown,
				},
				element: element,
				bind: bindObject,
			});

			/**
			 * INFO to the test:
			 * except click all other native events can not be easily simulated.
			 * Mouseup, Mousedown was tested manually.
			 */

			// setup tests (spying)
			// test click
			clickCallbacks = eventHandler.getHandlers('click');
			sinon.spy(clickCallbacks[0], ".foo");
			sinon.spy(clickCallbacks[1], ".bar");
			sinon.spy(clickCallbacks[2], ".baz");
			sinon.spy(bindObject, "someMethod");

			// test click event
			element.querySelector('.baz').click();
			clickCallbacks[0][".foo"].callCount.should.eql(0);
			clickCallbacks[1][".bar"].callCount.should.eql(0);
			clickCallbacks[2][".baz"].callCount.should.eql(1);

			element.querySelector('.foo').click();
			clickCallbacks[0][".foo"].callCount.should.eql(1);
			clickCallbacks[1][".bar"].callCount.should.eql(0);
			clickCallbacks[2][".baz"].callCount.should.eql(1);

			element.querySelector('.bar').click();
			clickCallbacks[0][".foo"].callCount.should.eql(1);
			clickCallbacks[1][".bar"].callCount.should.eql(1);
			clickCallbacks[2][".baz"].callCount.should.eql(1);

			// test bind object
			bindObject.someMethod.callCount.should.eql(1);

			// cleanup spyies
			clickCallbacks[0][".foo"].restore();
			clickCallbacks[1][".bar"].restore();
			clickCallbacks[2][".baz"].restore();
			bindObject["someMethod"].restore();

			// test removeEvent
			eventHandler.removeEvent('click .foo');
			eventHandler.getHandlers('click').should.have.length(2);

			eventHandler.removeEvent('mouseup .boo');
			eventHandler.getHandlers('mouseup').should.have.length(1);

			eventHandler.removeEvent('click');
			let clickTestObject = { click: eventHandler.getHandlers('click') };
			clickTestObject.should.have.propertyByPath('click').eql(null);

			eventHandler.removeEvent('mouseup .koo');
			let mouseupTestObject = { mouseup: eventHandler.getHandlers('mouseup') };
			mouseupTestObject.should.have.propertyByPath('mouseup').eql(null);

			eventHandler.removeEvent('mousedown');
			Object.keys(eventHandler.config.events).should.have.length(0);

		});

		it('should trigger and remove events if registered over on method', () => {

			let eventHandler = Eventhandler.create({ element, bind: bindObject });

			eventHandler.on("click .foo", clickFoo);
			eventHandler.on("click .bar", clickBar);
			eventHandler.on("click .baz", clickBaz);
			eventHandler.on("mouseup .boo", mouseupBoo);
			eventHandler.on("mouseup .koo", mouseupKoo);
			eventHandler.on("mousedown", mouseDown);

			/**
			 * INFO to the test:
			 * except click all other native events can not be easily simulated.
			 * Mouseup, Mousedown was tested manually.
			 */

			// setup tests (spying)
			// test click
			clickCallbacks = eventHandler.getHandlers('click');
			sinon.spy(clickCallbacks[0], ".foo");
			sinon.spy(clickCallbacks[1], ".bar");
			sinon.spy(clickCallbacks[2], ".baz");
			sinon.spy(bindObject, "someMethod");

			// test click event
			element.querySelector('.baz').click();
			clickCallbacks[0][".foo"].callCount.should.eql(0);
			clickCallbacks[1][".bar"].callCount.should.eql(0);
			clickCallbacks[2][".baz"].callCount.should.eql(1);

			element.querySelector('.foo').click();
			clickCallbacks[0][".foo"].callCount.should.eql(1);
			clickCallbacks[1][".bar"].callCount.should.eql(0);
			clickCallbacks[2][".baz"].callCount.should.eql(1);

			element.querySelector('.bar').click();
			clickCallbacks[0][".foo"].callCount.should.eql(1);
			clickCallbacks[1][".bar"].callCount.should.eql(1);
			clickCallbacks[2][".baz"].callCount.should.eql(1);

			// test bind object
			bindObject.someMethod.callCount.should.eql(1);

			// cleanup spyies
			clickCallbacks[0][".foo"].restore();
			clickCallbacks[1][".bar"].restore();
			clickCallbacks[2][".baz"].restore();
			bindObject["someMethod"].restore();

			// test removeEvent
			eventHandler.removeEvent('click .foo');
			eventHandler.getHandlers('click').should.have.length(2);

			eventHandler.removeEvent('mouseup .boo');
			eventHandler.getHandlers('mouseup').should.have.length(1);

			eventHandler.removeEvent('click');
			let clickTestObject = { click: eventHandler.getHandlers('click') };
			clickTestObject.should.have.propertyByPath('click').eql(null);

			eventHandler.removeEvent('mouseup .koo');
			let mouseupTestObject = { mouseup: eventHandler.getHandlers('mouseup') };
			mouseupTestObject.should.have.propertyByPath('mouseup').eql(null);

			eventHandler.removeEvent('mousedown');
			Object.keys(eventHandler.config.events).should.have.length(0);

		});

	});

});
<|endoftext|>


<commit_before>/* jshint camelcase: false */
var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , dialect   = Support.getTestDialect()
  , config    = require(__dirname + "/../config/config")

chai.Assertion.includeStack = true

if (dialect.match(/^mysql/)) {
  describe("[MYSQL Specific] DAOFactory", function () {
    describe('constructor', function() {
      it("handles extended attributes (unique)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: { type: DataTypes.STRING, unique: true }
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) UNIQUE",id:"INTEGER NOT NULL auto_increment PRIMARY KEY"})
        done()
      })

      it("handles extended attributes (default)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: {type: DataTypes.STRING, defaultValue: 'foo'}
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) DEFAULT 'foo'",id:"INTEGER NOT NULL auto_increment PRIMARY KEY"})
        done()
      })

      it("handles extended attributes (null)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: {type: DataTypes.STRING, allowNull: false}
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) NOT NULL",id:"INTEGER NOT NULL auto_increment PRIMARY KEY"})
        done()
      })

      it("handles extended attributes (comment)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: {type: DataTypes.STRING, comment: 'This be\'s a comment'}
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) COMMENT 'This be\\'s a comment'",id:"INTEGER NOT NULL auto_increment PRIMARY KEY"})
        done()
      })

      it("handles extended attributes (primaryKey)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: {type: DataTypes.STRING, primaryKey: true}
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) PRIMARY KEY"})
        done()
      })

      it("adds timestamps", function(done) {
        var User1 = this.sequelize.define('User' + config.rand(), {})
        var User2 = this.sequelize.define('User' + config.rand(), {}, { timestamps: true })

        expect(User1.attributes).to.deep.equal({id:"INTEGER NOT NULL auto_increment PRIMARY KEY", updatedAt:"DATETIME NOT NULL", createdAt:"DATETIME NOT NULL"})
        expect(User2.attributes).to.deep.equal({id:"INTEGER NOT NULL auto_increment PRIMARY KEY", updatedAt:"DATETIME NOT NULL", createdAt:"DATETIME NOT NULL"})
        done()
      })

      it("adds deletedAt if paranoid", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {}, { paranoid: true })
        expect(User.attributes).to.deep.equal({id:"INTEGER NOT NULL auto_increment PRIMARY KEY", deletedAt:"DATETIME", updatedAt:"DATETIME NOT NULL", createdAt:"DATETIME NOT NULL"})
        done()
      })

      it("underscores timestamps if underscored", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {}, { paranoid: true, underscored: true })
        expect(User.attributes).to.deep.equal({id:"INTEGER NOT NULL auto_increment PRIMARY KEY", deleted_at:"DATETIME", updated_at:"DATETIME NOT NULL", created_at:"DATETIME NOT NULL"})
        done()
      })

      it('omits text fields with defaultValues', function(done) {
        var User = this.sequelize.define('User' + config.rand(), {name: {type: DataTypes.TEXT, defaultValue: 'helloworld'}})
        expect(User.attributes.name).to.equal('TEXT')
        done()
      })

      it('omits blobs fields with defaultValues', function(done) {
        var User = this.sequelize.define('User' + config.rand(), {name: {type: DataTypes.STRING.BINARY, defaultValue: 'helloworld'}})
        expect(User.attributes.name).to.equal('VARCHAR(255) BINARY')
        done()
      })
    })

    describe.only('validations', function() {
      describe('enums', function() {
        it('enum data type should be case insensitive if my collation allows it', function(done) {
          var User = this.sequelize.define('User' + config.rand(), {
            mood: {
              type: DataTypes.ENUM,
              values: ['HAPPY', 'sad', 'WhatEver']
            }
          }, {
            collate: 'utf8_general_ci'
          })

          User.sync({ force: true }).success(function() {
            User.create({mood: 'happy'}).success(function(user) {
              expect(user).to.exist
              expect(user.mood).to.equal('HAPPY')
              var u = User.build({mood: 'SAD'})
              u.save().success(function(_user) {
                expect(_user).to.exist
                expect(_user.mood).to.equal('sad')
                done()
              })
            })
          })
        })

        it('enum data type should be case sensitive if my collation enforces it', function(done) {
          var User = this.sequelize.define('User' + config.rand(), {
            mood: {
              type: DataTypes.ENUM,
              values: ['HAPPY', 'sad', 'WhatEver']
            }
          }, {
            collate: 'latin1_bin'
          })

          User.sync({ force: true }).success(function() {
            expect(function() {
              User.create({mood: 'happy'})
            }).to.throw(Error, 'Value "happy" for ENUM mood is out of allowed scope. Allowed values: HAPPY, sad, WhatEver')

            expect(function() {
              var u = User.build({mood: 'SAD'})
              u.save()
            }).to.throw(Error, 'Value "SAD" for ENUM mood is out of allowed scope. Allowed values: HAPPY, sad, WhatEver')
            done()
          })
        })
      })
    })

    describe('primaryKeys', function() {
      it("determines the correct primaryKeys", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          foo: {type: DataTypes.STRING, primaryKey: true},
          bar: DataTypes.STRING
        })
        expect(User.primaryKeys).to.deep.equal({"foo":"VARCHAR(255) PRIMARY KEY"})
        done()
      })
    })
  })
}
<commit_msg>Removed .only from tests.<commit_after>/* jshint camelcase: false */
var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , dialect   = Support.getTestDialect()
  , config    = require(__dirname + "/../config/config")

chai.Assertion.includeStack = true

if (dialect.match(/^mysql/)) {
  describe("[MYSQL Specific] DAOFactory", function () {
    describe('constructor', function() {
      it("handles extended attributes (unique)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: { type: DataTypes.STRING, unique: true }
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) UNIQUE",id:"INTEGER NOT NULL auto_increment PRIMARY KEY"})
        done()
      })

      it("handles extended attributes (default)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: {type: DataTypes.STRING, defaultValue: 'foo'}
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) DEFAULT 'foo'",id:"INTEGER NOT NULL auto_increment PRIMARY KEY"})
        done()
      })

      it("handles extended attributes (null)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: {type: DataTypes.STRING, allowNull: false}
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) NOT NULL",id:"INTEGER NOT NULL auto_increment PRIMARY KEY"})
        done()
      })

      it("handles extended attributes (comment)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: {type: DataTypes.STRING, comment: 'This be\'s a comment'}
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) COMMENT 'This be\\'s a comment'",id:"INTEGER NOT NULL auto_increment PRIMARY KEY"})
        done()
      })

      it("handles extended attributes (primaryKey)", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          username: {type: DataTypes.STRING, primaryKey: true}
        }, { timestamps: false })
        expect(User.attributes).to.deep.equal({username:"VARCHAR(255) PRIMARY KEY"})
        done()
      })

      it("adds timestamps", function(done) {
        var User1 = this.sequelize.define('User' + config.rand(), {})
        var User2 = this.sequelize.define('User' + config.rand(), {}, { timestamps: true })

        expect(User1.attributes).to.deep.equal({id:"INTEGER NOT NULL auto_increment PRIMARY KEY", updatedAt:"DATETIME NOT NULL", createdAt:"DATETIME NOT NULL"})
        expect(User2.attributes).to.deep.equal({id:"INTEGER NOT NULL auto_increment PRIMARY KEY", updatedAt:"DATETIME NOT NULL", createdAt:"DATETIME NOT NULL"})
        done()
      })

      it("adds deletedAt if paranoid", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {}, { paranoid: true })
        expect(User.attributes).to.deep.equal({id:"INTEGER NOT NULL auto_increment PRIMARY KEY", deletedAt:"DATETIME", updatedAt:"DATETIME NOT NULL", createdAt:"DATETIME NOT NULL"})
        done()
      })

      it("underscores timestamps if underscored", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {}, { paranoid: true, underscored: true })
        expect(User.attributes).to.deep.equal({id:"INTEGER NOT NULL auto_increment PRIMARY KEY", deleted_at:"DATETIME", updated_at:"DATETIME NOT NULL", created_at:"DATETIME NOT NULL"})
        done()
      })

      it('omits text fields with defaultValues', function(done) {
        var User = this.sequelize.define('User' + config.rand(), {name: {type: DataTypes.TEXT, defaultValue: 'helloworld'}})
        expect(User.attributes.name).to.equal('TEXT')
        done()
      })

      it('omits blobs fields with defaultValues', function(done) {
        var User = this.sequelize.define('User' + config.rand(), {name: {type: DataTypes.STRING.BINARY, defaultValue: 'helloworld'}})
        expect(User.attributes.name).to.equal('VARCHAR(255) BINARY')
        done()
      })
    })

    describe('validations', function() {
      describe('enums', function() {
        it('enum data type should be case insensitive if my collation allows it', function(done) {
          var User = this.sequelize.define('User' + config.rand(), {
            mood: {
              type: DataTypes.ENUM,
              values: ['HAPPY', 'sad', 'WhatEver']
            }
          }, {
            collate: 'utf8_general_ci'
          })

          User.sync({ force: true }).success(function() {
            User.create({mood: 'happy'}).success(function(user) {
              expect(user).to.exist
              expect(user.mood).to.equal('HAPPY')
              var u = User.build({mood: 'SAD'})
              u.save().success(function(_user) {
                expect(_user).to.exist
                expect(_user.mood).to.equal('sad')
                done()
              })
            })
          })
        })

        it('enum data type should be case sensitive if my collation enforces it', function(done) {
          var User = this.sequelize.define('User' + config.rand(), {
            mood: {
              type: DataTypes.ENUM,
              values: ['HAPPY', 'sad', 'WhatEver']
            }
          }, {
            collate: 'latin1_bin'
          })

          User.sync({ force: true }).success(function() {
            expect(function() {
              User.create({mood: 'happy'})
            }).to.throw(Error, 'Value "happy" for ENUM mood is out of allowed scope. Allowed values: HAPPY, sad, WhatEver')

            expect(function() {
              var u = User.build({mood: 'SAD'})
              u.save()
            }).to.throw(Error, 'Value "SAD" for ENUM mood is out of allowed scope. Allowed values: HAPPY, sad, WhatEver')
            done()
          })
        })
      })
    })

    describe('primaryKeys', function() {
      it("determines the correct primaryKeys", function(done) {
        var User = this.sequelize.define('User' + config.rand(), {
          foo: {type: DataTypes.STRING, primaryKey: true},
          bar: DataTypes.STRING
        })
        expect(User.primaryKeys).to.deep.equal({"foo":"VARCHAR(255) PRIMARY KEY"})
        done()
      })
    })
  })
}
<|endoftext|>