<commit_before>import 'should'
import $ from 'teaspoon'
import React, { Component, PropTypes } from 'react'

import Selection from '../src/Selection.jsx'
import Selectable from '../src/Selectable.jsx'
import InputManager from '../src/InputManager.js'

describe("Selection", () => {
  const Blah = class A extends Component {
    static displayName = 'A'
    static propTypes = {
      name: PropTypes.string,
      children: PropTypes.any
    }
    render() {
      return (

hi {this.props.name}

          {this.props.children}

      )
    }
  }
  const Child = class B extends Component {
    static displayName='B'
    static propTypes = {
      value: PropTypes.string,
      id: PropTypes.number
    }
    render() {
      return
{this.props.value}

    }
  }
  const options = {
    value: (props) => props.value,
    key: (props) => props.id,
    cacheBounds: true
  }
  const SelectableChild = Selectable(Child, options)
  describe("higher-order container creation", () => {
    it("should make a component", () => {
      const Thing = Selection(Blah)
      Thing.displayName.should.be.eql('Selection(A)')

      const stuff = $(<Thing>
hi
</Thing>).render()

      stuff.find('.foo').text().should.eql('hi')

      const nextstuff = $(<Thing name="Greg" />).render()

      nextstuff.find('p').text().should.eql('hi Greg')
    })

    it("should error if a non-component is passed in", () => {
      expect(() => {
        Selection(false)
      }).to.throw('Component is not a class, must be a stateful React Component class')
    })

    it("should force a container div for ", () => {
      const Thing = Selection(() => null, { containerDiv: false })

      const stuff = $(<Thing />).render()
      expect(stuff[0].containerDiv).to.be.true
    })

    it("should pull displayname from displayName", () => {
      const Thing = Selection( class {
        static displayName = 'Hi'
        render() {}
      })
      Thing.displayName.should.equal('Selection(Hi)')
    })

    it("should pull displayname from name if displayName is not present", () => {
      const Thing = Selection( class Hi {
        render() {}
      })
      Thing.displayName.should.match(/^Selection\((Hi|Component)\)$/) // IE 10/11
    })
  })

  describe("updateState", () => {
    const Thing = Selection(Blah, {
      sorter: (a, b) => a > b ? 1 : (a  {
      stuff = $(<Thing />).render()
      component = stuff[0]
    })
    afterEach(() => {
      stuff.unmount()
    })

    it("should keep state the same if passed null", () => {
      component.setState({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3 },
        selectedValues: { 4: 4, 5: 5, 6: 6 },
        containerBounds: component.bounds
      })

      component.state.should.eql({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3},
        selectedNodeList: [],
        selectedValues: { 4: 4, 5: 5, 6: 6},
        selectedValueList: [],
        containerBounds: component.bounds
      })

      component.updateState(null, null, null)

      component.state.should.eql({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3},
        selectedNodeList: [],
        selectedValues: { 4: 4, 5: 5, 6: 6},
        selectedValueList: [],
        containerBounds: component.bounds
      })
    })
    it("should set values if passed", () => {
      component.setState({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3},
        selectedValues: { 4: 4, 5: 5, 6: 6},
        containerBounds: component.bounds
      })

      component.state.should.eql({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3},
        selectedNodeList: [],
        selectedValues: { 4: 4, 5: 5, 6: 6},
        selectedValueList: [],
        containerBounds: component.bounds
      })

      component.updateState(true, { hi: 'hi' }, { there: 'there' })

      component.state.should.eql({
        selecting: true,
        selectedNodes: { hi: 'hi' },
        selectedNodeList: [],
        selectedValues: { there: 'there' },
        selectedValueList: [],
        containerBounds: component.bounds
      })
    })

    it("should call onSelectSlot if constantSelect is enabled", () => {
      const spy = sinon.spy()
      stuff = $((
        <Thing selectable constantSelect onSelectSlot={spy}>
          <SelectableChild value="hi" key={1} />
          <SelectableChild value="hi2" key={2} />
          <SelectableChild value="hi3" key={3} />
        </Thing>
          )).render()
      const children = stuff.find(SelectableChild)
      component = stuff[0]
      component.bounds = { hi: 'hi' }
      const selectable1 = children[0]
      const selectable2 = children[1]
      const selectable3 = children[2]

      component.updateState(null, {
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      }, {
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })

      expect(spy.called).to.be.true

      spy.args[0].should.have.length(5)
      spy.args[0][0].should.be.eql({
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })
      expect(spy.args[0][1]()).to.eql({
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      })
      expect(spy.args[0][2]).to.eql(['hi', 'hi2', 'hi3'])
      expect(spy.args[0][3]()).to.eql([
        {node: selectable1},
        {node: selectable2},
        {node: selectable3}
      ])
      expect(spy.args[0][4]).to.eql({hi: 'hi'})
    })
    it("should not call onSelectSlot if constantSelection is disabled", () => {
      const spy = sinon.spy()
      stuff = $((
        <Thing selectable onSelectSlot={spy}>
          <SelectableChild value="hi" key={1} />
          <SelectableChild value="hi2" key={2} />
          <SelectableChild value="hi3" key={3} />
        </Thing>
      )).render()
      const children = stuff.find(SelectableChild)
      component = stuff[0]
      component.bounds = { hi: 'hi' }
      const selectable1 = children[0]
      const selectable2 = children[1]
      const selectable3 = children[2]

      component.updateState(null, {
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      }, {
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })

      expect(spy.called).to.be.false
    })
  })

  describe("propagateFinishedSelect", () => {
    const Thing = Selection(Blah, {
      sorter: (a, b) => a > b ? 1 : (a  {
      spy = sinon.spy()
      stuff = $((
        <Thing selectable constantSelect onFinishSelect={spy}>
        <SelectableChild value="hi" key={1}/>
        <SelectableChild value="hi2" key={2}/>
        <SelectableChild value="hi3" key={3}/>
        </Thing>
      )).render()
      component = stuff[0]
      const children = stuff.find(SelectableChild)
      component = stuff[0]
      component.bounds = {hi: 'hi'}
      selectable1 = children[0]
      selectable2 = children[1]
      selectable3 = children[2]
    })

    afterEach(() => {
      stuff.unmount()
    })

    it("should return our info", () => {
      component.updateState(null, {
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      }, {
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })

      component.propagateFinishedSelect()

      expect(spy.called).to.be.true

      spy.args[0].should.have.length(5)
      spy.args[0][0].should.be.eql({
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })
      expect(spy.args[0][1]()).to.eql({
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      })
      expect(spy.args[0][2]).to.eql(['hi', 'hi2', 'hi3'])
      expect(spy.args[0][3]()).to.eql([
        {node: selectable1},
        {node: selectable2},
        {node: selectable3}
      ])
      expect(spy.args[0][4]).to.eql({hi: 'hi'})
    })
  })

  describe("invalid", () => {
    const Thing = Selection(Blah)
    let spy
    let stuff
    let component

    beforeEach(() => {
      spy = sinon.spy()
    })
    afterEach(() => {
      stuff.unmount()
    })

    it("should call onTouchStart if defined and event is a touch event", () => {
      stuff = $(<Thing onTouchStart={spy}/>).render(true)

      component = stuff[0]
      component.invalid('hi', 'touchstart')

      expect(spy.called).to.be.true
    })
    it("should call onMouseDown if defined and event is a mouse event", () => {
      stuff = $(<Thing onMouseDown={spy}/>).render(true)

      component = stuff[0]
      component.invalid('hi', 'mousedown')

      expect(spy.called).to.be.true
    })
  })

  describe("start", () => {
    const Thing = Selection(Blah)
    let spy
    let stuff
    let component

    beforeEach(() => {
      spy = sinon.spy()
    })

    it("should call select if constantSelect is active", () => {
      stuff = $(<Thing constantSelect />).render()

      component = stuff[0]

      component.selectionManager.select = spy
      component.start(1, 2, 3)

      expect(spy.called).to.be.true
    })

    it("should call deselect if constantSelect is not active", () => {
      stuff = $(<Thing />).render()

      component = stuff[0]

      component.selectionManager.deselect = spy
      component.start(1, 2, 3)

      expect(spy.called).to.be.true
    })
  })

  describe("cancel", () => {
    const Thing = Selection(Blah)
    let spy
    let stuff
    let component

    beforeEach(() => {
      spy = sinon.spy()
      stuff = $(<Thing />).render()
      component = stuff[0]
    })

    it("should call deselect", () => {
      component.selectionManager.deselect = spy

      component.cancel()

      expect(spy.called).to.be.true
    })

    it("should call propageFinishedSelect", () => {
      component.propagateFinishedSelect = spy
      component.cancel()

      expect(spy.called).to.be.true
    })

    it("should turn off selection", () => {
      component.setState = spy
      component.cancel()

      expect(spy.called).to.be.true

      spy.args[0][0].should.eql({ selecting: false })
    })
  })

  describe("end", () => {
    const Thing = Selection(Blah)

    it("should call propagateFinishedSelect and deselect if constantSelect is on", () => {
      const stuff = $(<Thing selectable constantSelect />).render()
      const component = stuff[0]
      component.propagateFinishedSelect = sinon.spy()
      component.selectionManager.deselect = sinon.spy()
      component.end(1, 2, 3)

      expect(component.propagateFinishedSelect.called).to.be.true
      expect(component.selectionManager.deselect.called).to.be.true
    })
    it("should select any items in the selection rectangle, and propagateFinishedSelect", () => {
      const stuff = $(<Thing selectable />).render()
      const component = stuff[0]
      component.propagateFinishedSelect = sinon.spy()
      component.selectionManager.select = sinon.spy()
      component.end(1, 2, 3)

      expect(component.propagateFinishedSelect.called).to.be.true
      expect(component.selectionManager.select.called).to.be.true
    })
  })

  describe("change", () => {
    const Thing = Selection(Blah)

    it("should enable selection", () => {
      const stuff = $(<Thing />).render()
      const component = stuff[0]
      component.setState = sinon.spy()

      component.change(1)

      expect(component.setState.called).to.be.true
      component.setState.args[0][0].should.eql({
        selecting: true
      })
    })
    it("should call select if constantSelect is enabled", () => {
      const stuff = $(<Thing constantSelect />).render()
      const component = stuff[0]
      component.selectionManager.select = sinon.spy()

      component.change(1)

      expect(component.selectionManager.select.called).to.be.true
    })
  })

  describe("makeInputManager", () => {
    const Thing = Selection(Blah)

    it("should do nothing if ref is null", () => {
      const spy = sinon.spy()

      const im = function(...args) {
        spy(...args)
      }

      const stuff = $(<Thing />).render()
      stuff[0].makeInputManager(null, im)

      expect(spy.called).to.be.false
    })
    it("should set up inputManager and ref on first valid call", () => {
      const spy = sinon.spy()
      let watch = null

      const im = function(...args) {
        spy(...args)
        watch = this
      }

      const stuff = $(<Thing />).render()
      const component = stuff[0]
      component.makeInputManager('hi', im)

      expect(spy.called).to.be.true
      watch.should.equal(component.inputManager)
      component.ref.should.equal('hi')
    })
    it("should do nothing if ref is the same as a previous call", () => {
      const spy = sinon.spy()

      const im = function(...args) {
        spy(...args)
      }

      const stuff = $(<Thing />).render()
      const component = stuff[0]
      component.makeInputManager('hi', im)
      component.makeInputManager('hi', im)

      expect(spy.calledOnce).to.be.true
    })
    it("should umount inputManager and re-set if ref changes", () => {
      const spy = sinon.spy()
      const spy2 = sinon.spy()

      class im {
        constructor(...args) {
          spy(...args)
        }
        unmount(...args) {
          spy2(...args)
        }
      }

      const stuff = $(<Thing />).render()
      const component = stuff[0]
      component.makeInputManager('hi', im)
      component.makeInputManager('hi2', im)

      expect(spy.calledTwice).to.be.true
      expect(spy2.called).to.be.true
    })
  })

  describe("render", () => {
    it("should create a container div if containerDiv is specified")
    it("should pass in all props")
    describe("container div", () => {
      it("should capture mousedown")
      it("should capture touchstart")
    })
    describe("raw component", () => {
      it("should capture mousedown")
      it("should capture touchstart")
    })
  })
})
<commit_msg>fix eslint issues<commit_after>import 'should'
import $ from 'teaspoon'
import React, { Component, PropTypes } from 'react'

import Selection from '../src/Selection.jsx'
import Selectable from '../src/Selectable.jsx'

describe("Selection", () => {
  const Blah = class A extends Component {
    static displayName = 'A'
    static propTypes = {
      name: PropTypes.string,
      children: PropTypes.any
    }
    render() {
      return (

hi {this.props.name}

          {this.props.children}

      )
    }
  }
  const Child = class B extends Component {
    static displayName='B'
    static propTypes = {
      value: PropTypes.string,
      id: PropTypes.number
    }
    render() {
      return
{this.props.value}

    }
  }
  const options = {
    value: (props) => props.value,
    key: (props) => props.id,
    cacheBounds: true
  }
  const SelectableChild = Selectable(Child, options)
  describe("higher-order container creation", () => {
    it("should make a component", () => {
      const Thing = Selection(Blah)
      Thing.displayName.should.be.eql('Selection(A)')

      const stuff = $(<Thing>
hi
</Thing>).render()

      stuff.find('.foo').text().should.eql('hi')

      const nextstuff = $(<Thing name="Greg" />).render()

      nextstuff.find('p').text().should.eql('hi Greg')
    })

    it("should error if a non-component is passed in", () => {
      expect(() => {
        Selection(false)
      }).to.throw('Component is not a class, must be a stateful React Component class')
    })

    it("should force a container div for ", () => {
      const Thing = Selection(() => null, { containerDiv: false })

      const stuff = $(<Thing />).render()
      expect(stuff[0].containerDiv).to.be.true
    })

    it("should pull displayname from displayName", () => {
      const Thing = Selection( class {
        static displayName = 'Hi'
        render() {}
      })
      Thing.displayName.should.equal('Selection(Hi)')
    })

    it("should pull displayname from name if displayName is not present", () => {
      const Thing = Selection( class Hi {
        render() {}
      })
      Thing.displayName.should.match(/^Selection\((Hi|Component)\)$/) // IE 10/11
    })
  })

  describe("updateState", () => {
    const Thing = Selection(Blah, {
      sorter: (a, b) => a > b ? 1 : (a  {
      stuff = $(<Thing />).render()
      component = stuff[0]
    })
    afterEach(() => {
      stuff.unmount()
    })

    it("should keep state the same if passed null", () => {
      component.setState({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3 },
        selectedValues: { 4: 4, 5: 5, 6: 6 },
        containerBounds: component.bounds
      })

      component.state.should.eql({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3},
        selectedNodeList: [],
        selectedValues: { 4: 4, 5: 5, 6: 6},
        selectedValueList: [],
        containerBounds: component.bounds
      })

      component.updateState(null, null, null)

      component.state.should.eql({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3},
        selectedNodeList: [],
        selectedValues: { 4: 4, 5: 5, 6: 6},
        selectedValueList: [],
        containerBounds: component.bounds
      })
    })
    it("should set values if passed", () => {
      component.setState({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3},
        selectedValues: { 4: 4, 5: 5, 6: 6},
        containerBounds: component.bounds
      })

      component.state.should.eql({
        selecting: false,
        selectedNodes: { 1: 1, 2: 2, 3: 3},
        selectedNodeList: [],
        selectedValues: { 4: 4, 5: 5, 6: 6},
        selectedValueList: [],
        containerBounds: component.bounds
      })

      component.updateState(true, { hi: 'hi' }, { there: 'there' })

      component.state.should.eql({
        selecting: true,
        selectedNodes: { hi: 'hi' },
        selectedNodeList: [],
        selectedValues: { there: 'there' },
        selectedValueList: [],
        containerBounds: component.bounds
      })
    })

    it("should call onSelectSlot if constantSelect is enabled", () => {
      const spy = sinon.spy()
      stuff = $((
        <Thing selectable constantSelect onSelectSlot={spy}>
          <SelectableChild value="hi" key={1} />
          <SelectableChild value="hi2" key={2} />
          <SelectableChild value="hi3" key={3} />
        </Thing>
          )).render()
      const children = stuff.find(SelectableChild)
      component = stuff[0]
      component.bounds = { hi: 'hi' }
      const selectable1 = children[0]
      const selectable2 = children[1]
      const selectable3 = children[2]

      component.updateState(null, {
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      }, {
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })

      expect(spy.called).to.be.true

      spy.args[0].should.have.length(5)
      spy.args[0][0].should.be.eql({
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })
      expect(spy.args[0][1]()).to.eql({
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      })
      expect(spy.args[0][2]).to.eql(['hi', 'hi2', 'hi3'])
      expect(spy.args[0][3]()).to.eql([
        {node: selectable1},
        {node: selectable2},
        {node: selectable3}
      ])
      expect(spy.args[0][4]).to.eql({hi: 'hi'})
    })
    it("should not call onSelectSlot if constantSelection is disabled", () => {
      const spy = sinon.spy()
      stuff = $((
        <Thing selectable onSelectSlot={spy}>
          <SelectableChild value="hi" key={1} />
          <SelectableChild value="hi2" key={2} />
          <SelectableChild value="hi3" key={3} />
        </Thing>
      )).render()
      const children = stuff.find(SelectableChild)
      component = stuff[0]
      component.bounds = { hi: 'hi' }
      const selectable1 = children[0]
      const selectable2 = children[1]
      const selectable3 = children[2]

      component.updateState(null, {
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      }, {
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })

      expect(spy.called).to.be.false
    })
  })

  describe("propagateFinishedSelect", () => {
    const Thing = Selection(Blah, {
      sorter: (a, b) => a > b ? 1 : (a  {
      spy = sinon.spy()
      stuff = $((
        <Thing selectable constantSelect onFinishSelect={spy}>
        <SelectableChild value="hi" key={1}/>
        <SelectableChild value="hi2" key={2}/>
        <SelectableChild value="hi3" key={3}/>
        </Thing>
      )).render()
      component = stuff[0]
      const children = stuff.find(SelectableChild)
      component = stuff[0]
      component.bounds = {hi: 'hi'}
      selectable1 = children[0]
      selectable2 = children[1]
      selectable3 = children[2]
    })

    afterEach(() => {
      stuff.unmount()
    })

    it("should return our info", () => {
      component.updateState(null, {
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      }, {
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })

      component.propagateFinishedSelect()

      expect(spy.called).to.be.true

      spy.args[0].should.have.length(5)
      spy.args[0][0].should.be.eql({
        3: 'hi3',
        1: 'hi',
        2: 'hi2'
      })
      expect(spy.args[0][1]()).to.eql({
        3: {node: selectable3},
        1: {node: selectable1},
        2: {node: selectable2}
      })
      expect(spy.args[0][2]).to.eql(['hi', 'hi2', 'hi3'])
      expect(spy.args[0][3]()).to.eql([
        {node: selectable1},
        {node: selectable2},
        {node: selectable3}
      ])
      expect(spy.args[0][4]).to.eql({hi: 'hi'})
    })
  })

  describe("invalid", () => {
    const Thing = Selection(Blah)
    let spy
    let stuff
    let component

    beforeEach(() => {
      spy = sinon.spy()
    })
    afterEach(() => {
      stuff.unmount()
    })

    it("should call onTouchStart if defined and event is a touch event", () => {
      stuff = $(<Thing onTouchStart={spy}/>).render(true)

      component = stuff[0]
      component.invalid('hi', 'touchstart')

      expect(spy.called).to.be.true
    })
    it("should call onMouseDown if defined and event is a mouse event", () => {
      stuff = $(<Thing onMouseDown={spy}/>).render(true)

      component = stuff[0]
      component.invalid('hi', 'mousedown')

      expect(spy.called).to.be.true
    })
  })

  describe("start", () => {
    const Thing = Selection(Blah)
    let spy
    let stuff
    let component

    beforeEach(() => {
      spy = sinon.spy()
    })

    it("should call select if constantSelect is active", () => {
      stuff = $(<Thing constantSelect />).render()

      component = stuff[0]

      component.selectionManager.select = spy
      component.start(1, 2, 3)

      expect(spy.called).to.be.true
    })

    it("should call deselect if constantSelect is not active", () => {
      stuff = $(<Thing />).render()

      component = stuff[0]

      component.selectionManager.deselect = spy
      component.start(1, 2, 3)

      expect(spy.called).to.be.true
    })
  })

  describe("cancel", () => {
    const Thing = Selection(Blah)
    let spy
    let stuff
    let component

    beforeEach(() => {
      spy = sinon.spy()
      stuff = $(<Thing />).render()
      component = stuff[0]
    })

    it("should call deselect", () => {
      component.selectionManager.deselect = spy

      component.cancel()

      expect(spy.called).to.be.true
    })

    it("should call propageFinishedSelect", () => {
      component.propagateFinishedSelect = spy
      component.cancel()

      expect(spy.called).to.be.true
    })

    it("should turn off selection", () => {
      component.setState = spy
      component.cancel()

      expect(spy.called).to.be.true

      spy.args[0][0].should.eql({ selecting: false })
    })
  })

  describe("end", () => {
    const Thing = Selection(Blah)

    it("should call propagateFinishedSelect and deselect if constantSelect is on", () => {
      const stuff = $(<Thing selectable constantSelect />).render()
      const component = stuff[0]
      component.propagateFinishedSelect = sinon.spy()
      component.selectionManager.deselect = sinon.spy()
      component.end(1, 2, 3)

      expect(component.propagateFinishedSelect.called).to.be.true
      expect(component.selectionManager.deselect.called).to.be.true
    })
    it("should select any items in the selection rectangle, and propagateFinishedSelect", () => {
      const stuff = $(<Thing selectable />).render()
      const component = stuff[0]
      component.propagateFinishedSelect = sinon.spy()
      component.selectionManager.select = sinon.spy()
      component.end(1, 2, 3)

      expect(component.propagateFinishedSelect.called).to.be.true
      expect(component.selectionManager.select.called).to.be.true
    })
  })

  describe("change", () => {
    const Thing = Selection(Blah)

    it("should enable selection", () => {
      const stuff = $(<Thing />).render()
      const component = stuff[0]
      component.setState = sinon.spy()

      component.change(1)

      expect(component.setState.called).to.be.true
      component.setState.args[0][0].should.eql({
        selecting: true
      })
    })
    it("should call select if constantSelect is enabled", () => {
      const stuff = $(<Thing constantSelect />).render()
      const component = stuff[0]
      component.selectionManager.select = sinon.spy()

      component.change(1)

      expect(component.selectionManager.select.called).to.be.true
    })
  })

  describe("makeInputManager", () => {
    const Thing = Selection(Blah)

    it("should do nothing if ref is null", () => {
      const spy = sinon.spy()

      const im = function(...args) {
        spy(...args)
      }

      const stuff = $(<Thing />).render()
      stuff[0].makeInputManager(null, im)

      expect(spy.called).to.be.false
    })
    it("should set up inputManager and ref on first valid call", () => {
      const spy = sinon.spy()
      let watch = null

      const im = function(...args) {
        spy(...args)
        watch = this
      }

      const stuff = $(<Thing />).render()
      const component = stuff[0]
      component.makeInputManager('hi', im)

      expect(spy.called).to.be.true
      watch.should.equal(component.inputManager)
      component.ref.should.equal('hi')
    })
    it("should do nothing if ref is the same as a previous call", () => {
      const spy = sinon.spy()

      const im = function(...args) {
        spy(...args)
      }

      const stuff = $(<Thing />).render()
      const component = stuff[0]
      component.makeInputManager('hi', im)
      component.makeInputManager('hi', im)

      expect(spy.calledOnce).to.be.true
    })
    it("should umount inputManager and re-set if ref changes", () => {
      const spy = sinon.spy()
      const spy2 = sinon.spy()

      class im {
        constructor(...args) {
          spy(...args)
        }
        unmount(...args) {
          spy2(...args)
        }
      }

      const stuff = $(<Thing />).render()
      const component = stuff[0]
      component.makeInputManager('hi', im)
      component.makeInputManager('hi2', im)

      expect(spy.calledTwice).to.be.true
      expect(spy2.called).to.be.true
    })
  })

  describe("render", () => {
    it("should create a container div if containerDiv is specified")
    it("should pass in all props")
    describe("container div", () => {
      it("should capture mousedown")
      it("should capture touchstart")
    })
    describe("raw component", () => {
      it("should capture mousedown")
      it("should capture touchstart")
    })
  })
})
<|endoftext|>


<commit_before>/*
Copyright 2016 - 2018 by Jan Dockx

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict'

const must = require('must')
const os = require('os')

// noinspection FunctionNamingConventionJS
function x () {
  if (arguments.length <= 0) {
    return []
  }
  return Array.prototype.reduce.call(
    arguments,
    (acc, arrayI) => {
      const ret = []
      acc.forEach(elementSoFar => { arrayI.forEach(elementOfI => { ret.push(elementSoFar.concat([elementOfI])) }) })
      return ret
    },
    [[]]
  )
}

function expectOwnFrozenProperty (subject, propertyName) {
  const propertyDescriptor = Object.getOwnPropertyDescriptor(subject, propertyName)
  propertyDescriptor.must.be.truthy()
  propertyDescriptor.enumerable.must.be.true()
  propertyDescriptor.configurable.must.be.false()
  propertyDescriptor.writable.must.be.false()
  const failFunction = function () {
    // noinspection MagicNumberJS
    subject[propertyName] = 42 + ' some outlandish other value'
  }
  failFunction.must.throw(TypeError)
}

// noinspection FunctionNamingConventionJS
function prototypeThatHasOwnPropertyDescriptor (subject, propertyName) {
  if (!subject) {
    return subject
  }
  if (Object.getOwnPropertyDescriptor(subject, propertyName)) {
    return subject
  }
  return prototypeThatHasOwnPropertyDescriptor(Object.getPrototypeOf(subject), propertyName)
}

// noinspection FunctionNamingConventionJS
function expectDerivedPropertyOnAPrototype (subject, propertyName, configurable) {
  const prototype = prototypeThatHasOwnPropertyDescriptor(subject, propertyName)
  const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, propertyName)
  propertyDescriptor.must.be.truthy()
  propertyDescriptor.enumerable.must.be.true()
  propertyDescriptor.configurable.must.equal(configurable)
  propertyDescriptor.must.not.have.property('writable')
  propertyDescriptor.get.must.be.a.function()
  must(propertyDescriptor.set).be.falsy()
}

// noinspection FunctionNamingConventionJS
function expectConfigurableDerivedPropertyOnAPrototype (subject, propertyName) {
  expectDerivedPropertyOnAPrototype(subject, propertyName, true)
}

// noinspection FunctionNamingConventionJS
function expectFrozenDerivedPropertyOnAPrototype (subject, propertyName) {
  expectDerivedPropertyOnAPrototype(subject, propertyName, false)
}

function expectFrozenPropertyOnAPrototype (subject, propertyName) {
  const prototype = prototypeThatHasOwnPropertyDescriptor(subject, propertyName)
  expectOwnFrozenProperty(prototype, propertyName)
}

// noinspection FunctionNamingConventionJS
function expectFrozenReadOnlyArrayPropertyWithPrivateBackingField (subject, propName, privatePropName) {
  subject.must.have.ownProperty(privatePropName) // array not shared
  subject[privatePropName].must.be.an.array()
  this.expectOwnFrozenProperty(subject, privatePropName)
  subject[propName].must.be.an.array()
  this.expectFrozenDerivedPropertyOnAPrototype(subject, propName)
  const failFunction = function () {
    // noinspection MagicNumberJS
    subject[propName] = 42 + ' some outlandish other value'
  }
  failFunction.must.throw(TypeError)
}

function expectToBeArrayOfFunctions (a) {
  a.must.be.an.array()
  a.forEach(element => { element.must.be.a.function() })
}

const doLog = false

// noinspection FunctionNamingConventionJS
function log () {
  if (doLog) {
    console.log.apply(undefined, arguments)
    console.log()
  }
}

function showStack (exc) {
  log('Exception stack%s---------------%s%s', os.EOL, os.EOL, exc.stack)
}

function regExpEscape (s) {
  // http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
}

function propertyIsWritable (object, propertyName) {
  const prototype = prototypeThatHasOwnPropertyDescriptor(object, propertyName)
  const pd = prototype && Object.getOwnPropertyDescriptor(prototype, propertyName)
  return !pd || pd.writable
}

function anyCasesGenerators (discriminator) {
  // noinspection JSPrimitiveTypeWrapperUsage,MagicNumberJS
  const generators = [
    () => new Error('This is a ' + discriminator + ' case'),
    () => undefined,
    () => null,
    () => 1,
    () => 0,
    () => 'a string that is used as a ' + discriminator,
    () => '',
    () => true,
    () => false,
    () => new Date(),
    () => /foo/,
    () => function () { return 'this simulates a ' + discriminator },
    // eslint-disable-next-line
    () => new Number(42),
    // eslint-disable-next-line
    () => new Boolean(false),
    // eslint-disable-next-line
    () => new String(discriminator + ' string'),
    () => arguments,
    () => ({}),
    () => ({a: 1, b: 'b', c: {}, d: {d1: undefined, d2: 'd2', d3: {d31: 31}}}),
    () => []
  ]
  const result = generators.slice()
  result.push(() => generators.map(g => g()))
  return result
}

// http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// noinspection OverlyComplexFunctionJS
function environment () {
  // eslint-disable-next-line
  if ((new Function('try {return this === global;}catch(e){return false;}'))()) {
    return 'node'
  }
  // noinspection JSUnresolvedVariable
  if (
    // eslint-disable-next-line
    (!!window.opr && !!opr.addons) ||
    !!window.opera ||
    navigator.userAgent.indexOf(' OPR/') >= 0
  ) {
    return 'opera'
  }
  // noinspection JSUnresolvedVariable
  if (typeof InstallTrigger !== 'undefined') {
    return 'firefox'
  }
  // this no longer detects safari in v11
  // noinspection JSUnresolvedVariable
  if (/constructor/i.test(window.HTMLElement) ||
      (function (p) {
        return p.toString() === '[object SafariRemoteNotification]'
      })(
        // eslint-disable-next-line
        !window['safari'] || safari.pushNotification
      )) {
    return 'safari'
  }
  // noinspection PointlessBooleanExpressionJS,JSUnresolvedVariable
  if (/* @cc_on!@ */false || !!document.documentMode) {
    return 'ie'
  }
  // noinspection JSUnresolvedVariable
  if (window.StyleMedia) {
    return 'edge'
  }
  // noinspection JSUnresolvedVariable
  if (!!window.chrome && !!window.chrome.webstore) {
    return 'chrome'
  }
  // noinspection JSUnresolvedVariable
  if (window.CSS) {
    // noinspection JSUnresolvedVariable
    if (navigator.userAgent.indexOf('Safari') >= 0) {
      return 'safari'
    } else {
      return 'blink'
    }
  }
  // eslint-disable-next-line
  if ((new Function('try {return this === window;}catch(e){ return false;}'))()) {
    return 'browser'
  }
  return undefined
}

function trimLineAndColumnPattern (stackLine) {
  return stackLine
    // node, chrome
    .replace(/:\d*:\d*\)$/, ')')
    // other browsers
    .replace(/:\d*:\d*$/, '')
}

function mustBeCallerLocation (actual, expected) {
  expected.must.be.a.string()
  trimLineAndColumnPattern(expected).must.equal(trimLineAndColumnPattern(actual))
}

module.exports = {
  x: x,
  expectOwnFrozenProperty: expectOwnFrozenProperty,
  expectConfigurableDerivedPropertyOnAPrototype: expectConfigurableDerivedPropertyOnAPrototype,
  expectFrozenDerivedPropertyOnAPrototype: expectFrozenDerivedPropertyOnAPrototype,
  expectFrozenReadOnlyArrayPropertyWithPrivateBackingField: expectFrozenReadOnlyArrayPropertyWithPrivateBackingField,
  expectFrozenPropertyOnAPrototype: expectFrozenPropertyOnAPrototype,
  expectToBeArrayOfFunctions: expectToBeArrayOfFunctions,
  log: log,
  showStack: showStack,
  regExpEscape: regExpEscape,
  propertyIsWritable: propertyIsWritable,
  anyCasesGenerators: anyCasesGenerators,
  environment: environment(),
  mustBeCallerLocation: mustBeCallerLocation
}
<commit_msg>recognize headless-chrome as environment<commit_after>/*
Copyright 2016 - 2018 by Jan Dockx

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict'

const must = require('must')
const os = require('os')

// noinspection FunctionNamingConventionJS
function x () {
  if (arguments.length <= 0) {
    return []
  }
  return Array.prototype.reduce.call(
    arguments,
    (acc, arrayI) => {
      const ret = []
      acc.forEach(elementSoFar => { arrayI.forEach(elementOfI => { ret.push(elementSoFar.concat([elementOfI])) }) })
      return ret
    },
    [[]]
  )
}

function expectOwnFrozenProperty (subject, propertyName) {
  const propertyDescriptor = Object.getOwnPropertyDescriptor(subject, propertyName)
  propertyDescriptor.must.be.truthy()
  propertyDescriptor.enumerable.must.be.true()
  propertyDescriptor.configurable.must.be.false()
  propertyDescriptor.writable.must.be.false()
  const failFunction = function () {
    // noinspection MagicNumberJS
    subject[propertyName] = 42 + ' some outlandish other value'
  }
  failFunction.must.throw(TypeError)
}

// noinspection FunctionNamingConventionJS
function prototypeThatHasOwnPropertyDescriptor (subject, propertyName) {
  if (!subject) {
    return subject
  }
  if (Object.getOwnPropertyDescriptor(subject, propertyName)) {
    return subject
  }
  return prototypeThatHasOwnPropertyDescriptor(Object.getPrototypeOf(subject), propertyName)
}

// noinspection FunctionNamingConventionJS
function expectDerivedPropertyOnAPrototype (subject, propertyName, configurable) {
  const prototype = prototypeThatHasOwnPropertyDescriptor(subject, propertyName)
  const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, propertyName)
  propertyDescriptor.must.be.truthy()
  propertyDescriptor.enumerable.must.be.true()
  propertyDescriptor.configurable.must.equal(configurable)
  propertyDescriptor.must.not.have.property('writable')
  propertyDescriptor.get.must.be.a.function()
  must(propertyDescriptor.set).be.falsy()
}

// noinspection FunctionNamingConventionJS
function expectConfigurableDerivedPropertyOnAPrototype (subject, propertyName) {
  expectDerivedPropertyOnAPrototype(subject, propertyName, true)
}

// noinspection FunctionNamingConventionJS
function expectFrozenDerivedPropertyOnAPrototype (subject, propertyName) {
  expectDerivedPropertyOnAPrototype(subject, propertyName, false)
}

function expectFrozenPropertyOnAPrototype (subject, propertyName) {
  const prototype = prototypeThatHasOwnPropertyDescriptor(subject, propertyName)
  expectOwnFrozenProperty(prototype, propertyName)
}

// noinspection FunctionNamingConventionJS
function expectFrozenReadOnlyArrayPropertyWithPrivateBackingField (subject, propName, privatePropName) {
  subject.must.have.ownProperty(privatePropName) // array not shared
  subject[privatePropName].must.be.an.array()
  this.expectOwnFrozenProperty(subject, privatePropName)
  subject[propName].must.be.an.array()
  this.expectFrozenDerivedPropertyOnAPrototype(subject, propName)
  const failFunction = function () {
    // noinspection MagicNumberJS
    subject[propName] = 42 + ' some outlandish other value'
  }
  failFunction.must.throw(TypeError)
}

function expectToBeArrayOfFunctions (a) {
  a.must.be.an.array()
  a.forEach(element => { element.must.be.a.function() })
}

const doLog = false

// noinspection FunctionNamingConventionJS
function log () {
  if (doLog) {
    console.log.apply(undefined, arguments)
    console.log()
  }
}

function showStack (exc) {
  log('Exception stack%s---------------%s%s', os.EOL, os.EOL, exc.stack)
}

function regExpEscape (s) {
  // http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
}

function propertyIsWritable (object, propertyName) {
  const prototype = prototypeThatHasOwnPropertyDescriptor(object, propertyName)
  const pd = prototype && Object.getOwnPropertyDescriptor(prototype, propertyName)
  return !pd || pd.writable
}

function anyCasesGenerators (discriminator) {
  // noinspection JSPrimitiveTypeWrapperUsage,MagicNumberJS
  const generators = [
    () => new Error('This is a ' + discriminator + ' case'),
    () => undefined,
    () => null,
    () => 1,
    () => 0,
    () => 'a string that is used as a ' + discriminator,
    () => '',
    () => true,
    () => false,
    () => new Date(),
    () => /foo/,
    () => function () { return 'this simulates a ' + discriminator },
    // eslint-disable-next-line
    () => new Number(42),
    // eslint-disable-next-line
    () => new Boolean(false),
    // eslint-disable-next-line
    () => new String(discriminator + ' string'),
    () => arguments,
    () => ({}),
    () => ({a: 1, b: 'b', c: {}, d: {d1: undefined, d2: 'd2', d3: {d31: 31}}}),
    () => []
  ]
  const result = generators.slice()
  result.push(() => generators.map(g => g()))
  return result
}

// http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// noinspection OverlyComplexFunctionJS
function environment () {
  // eslint-disable-next-line
  if ((new Function('try {return this === global;}catch(e){return false;}'))()) {
    return 'node'
  }
  // noinspection JSUnresolvedVariable
  if (
    // eslint-disable-next-line
    (!!window.opr && !!opr.addons) ||
    !!window.opera ||
    navigator.userAgent.indexOf(' OPR/') >= 0
  ) {
    return 'opera'
  }
  // noinspection JSUnresolvedVariable
  if (typeof InstallTrigger !== 'undefined') {
    return 'firefox'
  }
  // this no longer detects safari in v11
  // noinspection JSUnresolvedVariable
  if (/constructor/i.test(window.HTMLElement) ||
      (function (p) {
        return p.toString() === '[object SafariRemoteNotification]'
      })(
        // eslint-disable-next-line
        !window['safari'] || safari.pushNotification
      )) {
    return 'safari'
  }
  // noinspection PointlessBooleanExpressionJS,JSUnresolvedVariable
  if (/* @cc_on!@ */false || !!document.documentMode) {
    return 'ie'
  }
  // noinspection JSUnresolvedVariable
  if (window.StyleMedia) {
    return 'edge'
  }
  // noinspection JSUnresolvedVariable
  if (!!window.chrome && !!window.chrome.webstore) {
    return 'chrome'
  }
  // noinspection JSUnresolvedVariable
  if (window.CSS) {
    // noinspection JSUnresolvedVariable
    const ua = navigator.userAgent
    if (ua.indexOf('HeadlessChrome')) {
      return 'headless-chrome'
    }
    if (ua.indexOf('Safari') >= 0) {
      return 'safari'
    }
    return 'blink'
  }
  // eslint-disable-next-line
  if ((new Function('try {return this === window;}catch(e){ return false;}'))()) {
    return 'browser'
  }
  return undefined
}

function trimLineAndColumnPattern (stackLine) {
  return stackLine
    // node, chrome
    .replace(/:\d*:\d*\)$/, ')')
    // other browsers
    .replace(/:\d*:\d*$/, '')
}

function mustBeCallerLocation (actual, expected) {
  expected.must.be.a.string()
  trimLineAndColumnPattern(expected).must.equal(trimLineAndColumnPattern(actual))
}

module.exports = {
  x: x,
  expectOwnFrozenProperty: expectOwnFrozenProperty,
  expectConfigurableDerivedPropertyOnAPrototype: expectConfigurableDerivedPropertyOnAPrototype,
  expectFrozenDerivedPropertyOnAPrototype: expectFrozenDerivedPropertyOnAPrototype,
  expectFrozenReadOnlyArrayPropertyWithPrivateBackingField: expectFrozenReadOnlyArrayPropertyWithPrivateBackingField,
  expectFrozenPropertyOnAPrototype: expectFrozenPropertyOnAPrototype,
  expectToBeArrayOfFunctions: expectToBeArrayOfFunctions,
  log: log,
  showStack: showStack,
  regExpEscape: regExpEscape,
  propertyIsWritable: propertyIsWritable,
  anyCasesGenerators: anyCasesGenerators,
  environment: environment(),
  mustBeCallerLocation: mustBeCallerLocation
}
<|endoftext|>


<commit_before>var movies = require('./data.json')

module.exports = function(app) {
  app.requestsProcessed = 0

  app.get('/api/movies', function(req, res) {
    app.requestsProcessed++

    res.json(movies)
  })

  app.get('/api/params/:where', function(req, res) {
    app.requestsProcessed++

    res.json(movies)
  })

  app.get('/api/writeandend', function(req, res) {
    app.requestsProcessed++

    res.write('a')
    res.write('b')
    res.write('c')

    res.end()
  })

  app.get('/api/writebufferandend', function(req, res) {
    app.requestsProcessed++

    if (process.versions.node.indexOf('4') === 0) {
      res.write(new Buffer([0x61]))
      res.write(new Buffer([0x62]))
      res.write(new Buffer([0x63]))
    } else {
      res.write(Buffer.from('a'))
      res.write(Buffer.from('b'))
      res.write(Buffer.from('c'))
    }

    res.end()
  })

  app.get('/api/testheaderblacklist', function(req, res) {
    app.requestsProcessed++
    res.set('x-blacklisted', app.requestsProcessed)
    res.set('x-notblacklisted', app.requestsProcessed)

    res.json(movies)
  })

  app.get('/api/testcachegroup', function(req, res) {
    app.requestsProcessed++
    req.apicacheGroup = 'cachegroup'

    res.json(movies)
  })

  app.get('/api/text', function(req, res) {
    app.requestsProcessed++

    res.send('plaintext')
  })

  app.get('/api/html', function(req, res) {
    app.requestsProcessed++

    res.send('<html>')
  })

  app.get('/api/missing', function(req, res) {
    app.requestsProcessed++

    res.status(404)
    res.json({ success: false, message: 'Resource not found' })
  })

  app.get('/api/movies/:index', function(req, res) {
    app.requestsProcessed++

    res.json(movies[index])
  })

  return app
}
<commit_msg>Add Content-Type in test responses so compression will compress them.<commit_after>var movies = require('./data.json')

module.exports = function(app) {
  app.requestsProcessed = 0

  app.get('/api/movies', function(req, res) {
    app.requestsProcessed++

    res.json(movies)
  })

  app.get('/api/params/:where', function(req, res) {
    app.requestsProcessed++

    res.json(movies)
  })

  app.get('/api/writeandend', function(req, res) {
    app.requestsProcessed++

    res.header('Content-Type', 'text/plain')
    res.write('a')
    res.write('b')
    res.write('c')

    res.end()
  })

  app.get('/api/writebufferandend', function(req, res) {
    app.requestsProcessed++

    res.header('Content-Type', 'text/plain')
    if (process.versions.node.indexOf('4') === 0) {
      res.write(new Buffer([0x61]))
      res.write(new Buffer([0x62]))
      res.write(new Buffer([0x63]))
    } else {
      res.write(Buffer.from('a'))
      res.write(Buffer.from('b'))
      res.write(Buffer.from('c'))
    }

    res.end()
  })

  app.get('/api/testheaderblacklist', function(req, res) {
    app.requestsProcessed++
    res.set('x-blacklisted', app.requestsProcessed)
    res.set('x-notblacklisted', app.requestsProcessed)

    res.json(movies)
  })

  app.get('/api/testcachegroup', function(req, res) {
    app.requestsProcessed++
    req.apicacheGroup = 'cachegroup'

    res.json(movies)
  })

  app.get('/api/text', function(req, res) {
    app.requestsProcessed++
    res.header('Content-Type', 'text/plain')

    res.send('plaintext')
  })

  app.get('/api/html', function(req, res) {
    app.requestsProcessed++
    res.header('Content-Type', 'text/html')

    res.send('<html>')
  })

  app.get('/api/missing', function(req, res) {
    app.requestsProcessed++

    res.status(404)
    res.json({ success: false, message: 'Resource not found' })
  })

  app.get('/api/movies/:index', function(req, res) {
    app.requestsProcessed++

    res.json(movies[index])
  })

  return app
}
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');

describe('ecomfe-module:app', function () {
    it('creates files', function () {
        var done = false;

        runs(function () {
            helpers.run(path.join(__dirname, '../../app'))
                .inDir(path.join(os.tmpdir(), './temp-test'))
                // .withOptions({'skip-install': true})
                .withPrompt({
                    githubUser: 'nighca',
                    moduleName: 'test-module',
                    doInstall: false
                }).on('end', function () {
                    done = true;
                });
        });

        waitsFor(function() {
            return done;
        });

        runs(function() {
            assert.file([
                '.editorconfig',
                '.eslintrc',
                '.gitignore',
                '.npmignore',
                '.travis.yml',
                'package.json',
                'README.md',
                'LICENSE'
            ]);
        });
    });
});
<commit_msg>add test cases<commit_after>'use strict';

var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');

describe('ecomfe-module:app', function () {
    it('creates files', function () {
        var done = false;

        runs(function () {
            helpers.run(path.join(__dirname, '../../app'))
                .inDir(path.join(os.tmpdir(), './temp-test1'))
                .withPrompt({
                    githubUser: 'nighca',
                    moduleName: 'test-module'
                }).on('end', function () {
                    done = true;
                });
        });

        waitsFor(function() {
            return done;
        });

        runs(function() {
            assert.file([
                '.editorconfig',
                '.eslintrc',
                '.gitignore',
                '.npmignore',
                '.travis.yml',
                'package.json',
                'README.md',
                'LICENSE'
            ]);
        });
    });

    it('creates files in curr dir if module name matches dirname', function () {
        var done = false;

        runs(function () {
            helpers.run(path.join(__dirname, '../../app'))
                .inDir(path.join(os.tmpdir(), './temp-test2'))
                .withPrompt({
                    githubUser: 'nighca',
                    moduleName: 'temp-test2'
                }).on('end', function () {
                    done = true;
                });
        });

        waitsFor(function() {
            return done;
        });

        runs(function() {
            assert.file([
                '.editorconfig',
                '.eslintrc',
                '.gitignore',
                '.npmignore',
                '.travis.yml',
                'package.json',
                'README.md',
                'LICENSE'
            ]);
        });
    });

    it('use empty info with wrong github account', function () {
        var done = false;

        runs(function () {
            helpers.run(path.join(__dirname, '../../app'))
                .inDir(path.join(os.tmpdir(), './temp-test3'))
                .withPrompt({
                    githubUser: 'SOMEBODY_DOES_NOT_EXIST',
                    moduleName: 'test-module'
                }).on('end', function () {
                    done = true;
                });
        });

        waitsFor(function() {
            return done;
        });

        runs(function() {
            assert.file([
                '.editorconfig',
                '.eslintrc',
                '.gitignore',
                '.npmignore',
                '.travis.yml',
                'package.json',
                'README.md',
                'LICENSE'
            ]);

            var packageInfo = require(path.join(os.tmpdir(), './temp-test', 'test-module/package.json'));
            assert.deepEqual(packageInfo.author, {
                name: '',
                email: '',
                url: ''
            });
        });
    });

});
<|endoftext|>


<commit_before>suite('Audit Logs', () => {
  let _ = require('lodash');
  let assert = require('assert');
  let monitoring = require('../');
  let AWS = require('aws-sdk-mock');
  let testing = require('taskcluster-lib-testing');

  let logName = 'mocked-stream';
  let monitor = null;
  let records = {};

  setup(async () => {
    AWS.mock('Firehose', 'describeDeliveryStream', (params, callback) => {
      records[params.DeliveryStreamName] = [];
      callback(null, {DeliveryStreamDescription: {DeliveryStreamStatus: 'ACTIVE'}});
    });
    AWS.mock('Firehose', 'putRecord', (params, callback) => {
      if (params.Record.Data.indexOf('\n') === -1) {
        return callback(new Error('Must always submit at least 1 record!'), null);
      }
      if (Buffer.byteLength(params.Record.Data, 'utf-8') > 1000 * 1000) {
        return callback(new Error('Record size too large!'), null);
      }
      let DeliveryStreamName = params.DeliveryStreamName;
      let r = params.Record.Data.split('\n').map(x => x.trim());
      r.pop(); // To get rid of empty space at end
      records[DeliveryStreamName] = records[DeliveryStreamName].concat(r);
      callback(null, {FailedPutCount: 0});
    });

    monitor = await monitoring({
      project: 'tc-lib-monitor',
      credentials: {clientId: 'test-client', accessToken: 'test'},
      patchGlobal: false,
      reportStatsumErrors: false,
      reportAuditLogErrors: false,
      resourceInterval: 1,
      aws: {credentials: {accessKeyId: 'foo', secretAccessKey: 'bar'}, region: 'us-east-1'},
      logName,
    });
  });

  teardown(() => {
    AWS.restore();
    records = {};
  });

  test('should write logs on explicit flush', async function() {
    let subject = {test: 123};
    monitor.log(subject);
    await monitor.flush();
    assert.equal(records[logName].length, 1);
    assert.deepEqual(records[logName].map(JSON.parse)[0], subject);
  });

  test('should not write 0 logs on flush', async function() {
    await monitor.flush();
    assert.equal(records[logName].length, 0);
  });

  test('should write logs with newlines in them', async function() {
    let subject = {test: 'abc\n123'};
    monitor.log(subject);
    await monitor.flush();
    assert.equal(records[logName].length, 1);
    assert.deepEqual(records[logName].map(JSON.parse)[0], subject);
  });

  test('should write logs on 500 records', async function() {
    let subjects = _.range(5302).map(i => ({foo: i}));
    subjects.forEach(subject => monitor.log(subject));
    await monitor.flush();
    assert.equal(records[logName].length, 5302);
    assert.deepEqual(records[logName].map(JSON.parse), subjects);
  });

  test('should write logs on too many bytes', async function() {
    // This should get the records to be over 4MB in total
    let subjects = _.range(250).map(i => ({foo: i, bar: _.repeat('#', 16000)}));
    subjects.forEach(subject => monitor.log(subject));
    await monitor.flush();
    assert.equal(records[logName].length, 250);
    assert.deepEqual(records[logName].map(JSON.parse), subjects);
  });

  test('should write logs on timeout', async function() {
    let subject = {test: 1000, timerthing: true};
    monitor.log(subject);
    await testing.poll(async () => {
      assert.equal(records[logName].length, 1);
      assert.deepEqual(records[logName].map(JSON.parse)[0], subject);
    });
    subject = {test: 2000, timerthing: true};
    monitor.log(subject);
    await testing.poll(async () => {
      assert.equal(records[logName].length, 2);
      assert.deepEqual(records[logName].map(JSON.parse)[1], subject);
    });
  });

  test('should eventually stop trying to resubmit', async function() {
    AWS.restore('Firehose', 'putRecord');
    AWS.mock('Firehose', 'putRecord', (params, callback) => {
      return callback({statusCode: 500, message: 'uh oh!', retryable: true}, null);
    });
    let closed = false;
    monitor.log({test: 'foobar'});
    monitor.flush().then(() => {closed = true;});
    await testing.sleep(1000);
    assert(closed, 'Failed to reject permanently failing submission.');
  });

  test('should resubmit all on error', async function() {
    let tried = false;
    AWS.restore('Firehose', 'putRecord');
    AWS.mock('Firehose', 'putRecord', (params, callback) => {
      if (!tried) {
        tried = true;
        return callback({statusCode: 500, message: 'uh oh!', retryable: true}, null);
      }
      let DeliveryStreamName = params.DeliveryStreamName;
      let r = params.Record.Data.split('\n').map(x => x.trim());
      r.pop();
      records[DeliveryStreamName] = records[DeliveryStreamName].concat(r);
      callback(null, {FailedPutCount: 0});
    });
    monitor.log({test: 'foobar'});
    monitor.log({test: 'foobar2'});
    await monitor.flush();
    await testing.poll(async () => {
      assert.equal(records[logName].length, 2);
    });
  });

  test('should resubmit all on error even with multiple chunks', async function() {
    let tried = false;
    let submissions = 0;
    AWS.restore('Firehose', 'putRecord');
    AWS.mock('Firehose', 'putRecord', (params, callback) => {
      submissions++;
      if (!tried) {
        tried = true;
        return callback({statusCode: 500, message: 'uh oh!', retryable: true}, null);
      }
      let DeliveryStreamName = params.DeliveryStreamName;
      let r = params.Record.Data.split('\n').map(x => x.trim());
      r.pop();
      records[DeliveryStreamName] = records[DeliveryStreamName].concat(r);
      callback(null, {FailedPutCount: 0});
    });
    let subjects = _.range(999).map(i => ({foo: Array(5000).join('x')}));
    subjects.forEach(subject => monitor.log(subject));
    await monitor.flush();
    await testing.poll(async () => {
      assert.equal(records[logName].length, 999);
    });
    assert.equal(submissions, 7); // We would normally need 6 submissions
  });
});
<commit_msg>fix intermittent auditlog test<commit_after>suite('Audit Logs', () => {
  let _ = require('lodash');
  let assert = require('assert');
  let monitoring = require('../');
  let AWS = require('aws-sdk-mock');
  let testing = require('taskcluster-lib-testing');

  let logName = 'mocked-stream';
  let monitor = null;
  let records = {};

  setup(async () => {
    AWS.mock('Firehose', 'describeDeliveryStream', (params, callback) => {
      records[params.DeliveryStreamName] = [];
      callback(null, {DeliveryStreamDescription: {DeliveryStreamStatus: 'ACTIVE'}});
    });
    AWS.mock('Firehose', 'putRecord', (params, callback) => {
      if (params.Record.Data.indexOf('\n') === -1) {
        return callback(new Error('Must always submit at least 1 record!'), null);
      }
      if (Buffer.byteLength(params.Record.Data, 'utf-8') > 1000 * 1000) {
        return callback(new Error('Record size too large!'), null);
      }
      let DeliveryStreamName = params.DeliveryStreamName;
      let r = params.Record.Data.split('\n').map(x => x.trim());
      r.pop(); // To get rid of empty space at end
      records[DeliveryStreamName] = records[DeliveryStreamName].concat(r);
      callback(null, {FailedPutCount: 0});
    });

    monitor = await monitoring({
      project: 'tc-lib-monitor',
      credentials: {clientId: 'test-client', accessToken: 'test'},
      patchGlobal: false,
      reportStatsumErrors: false,
      reportAuditLogErrors: false,
      resourceInterval: 1,
      aws: {credentials: {accessKeyId: 'foo', secretAccessKey: 'bar'}, region: 'us-east-1'},
      logName,
    });
  });

  teardown(() => {
    AWS.restore();
    records = {};
  });

  test('should write logs on explicit flush', async function() {
    let subject = {test: 123};
    monitor.log(subject);
    await monitor.flush();
    assert.equal(records[logName].length, 1);
    assert.deepEqual(records[logName].map(JSON.parse)[0], subject);
  });

  test('should not write 0 logs on flush', async function() {
    await monitor.flush();
    assert.equal(records[logName].length, 0);
  });

  test('should write logs with newlines in them', async function() {
    let subject = {test: 'abc\n123'};
    monitor.log(subject);
    await monitor.flush();
    assert.equal(records[logName].length, 1);
    assert.deepEqual(records[logName].map(JSON.parse)[0], subject);
  });

  test('should write logs on 500 records', async function() {
    let subjects = _.range(5302).map(i => ({foo: i}));
    subjects.forEach(subject => monitor.log(subject));
    await monitor.flush();
    assert.equal(records[logName].length, 5302);
    assert.deepEqual(records[logName].map(JSON.parse), subjects);
  });

  test('should write logs on too many bytes', async function() {
    // This should get the records to be over 4MB in total
    let subjects = _.range(250).map(i => ({foo: i, bar: _.repeat('#', 16000)}));
    subjects.forEach(subject => monitor.log(subject));
    await monitor.flush();
    assert.equal(records[logName].length, 250);
    assert.deepEqual(records[logName].map(JSON.parse), subjects);
  });

  test('should write logs on timeout', async function() {
    let subject = {test: 1000, timerthing: true};
    monitor.log(subject);
    await testing.poll(async () => {
      assert.equal(records[logName].length, 1);
      assert.deepEqual(records[logName].map(JSON.parse)[0], subject);
    });
    subject = {test: 2000, timerthing: true};
    monitor.log(subject);
    await testing.poll(async () => {
      assert.equal(records[logName].length, 2);
      assert.deepEqual(records[logName].map(JSON.parse)[1], subject);
    });
  });

  test('should eventually stop trying to resubmit', async function() {
    AWS.restore('Firehose', 'putRecord');
    AWS.mock('Firehose', 'putRecord', (params, callback) => {
      return callback({statusCode: 500, message: 'uh oh!', retryable: true}, null);
    });
    let closed = false;
    monitor.log({test: 'foobar'});
    await monitor.flush().then(() => {closed = true;});
    assert(closed, 'Failed to reject permanently failing submission.');
  });

  test('should resubmit all on error', async function() {
    let tried = false;
    AWS.restore('Firehose', 'putRecord');
    AWS.mock('Firehose', 'putRecord', (params, callback) => {
      if (!tried) {
        tried = true;
        return callback({statusCode: 500, message: 'uh oh!', retryable: true}, null);
      }
      let DeliveryStreamName = params.DeliveryStreamName;
      let r = params.Record.Data.split('\n').map(x => x.trim());
      r.pop();
      records[DeliveryStreamName] = records[DeliveryStreamName].concat(r);
      callback(null, {FailedPutCount: 0});
    });
    monitor.log({test: 'foobar'});
    monitor.log({test: 'foobar2'});
    await monitor.flush();
    await testing.poll(async () => {
      assert.equal(records[logName].length, 2);
    });
  });

  test('should resubmit all on error even with multiple chunks', async function() {
    let tried = false;
    let submissions = 0;
    AWS.restore('Firehose', 'putRecord');
    AWS.mock('Firehose', 'putRecord', (params, callback) => {
      submissions++;
      if (!tried) {
        tried = true;
        return callback({statusCode: 500, message: 'uh oh!', retryable: true}, null);
      }
      let DeliveryStreamName = params.DeliveryStreamName;
      let r = params.Record.Data.split('\n').map(x => x.trim());
      r.pop();
      records[DeliveryStreamName] = records[DeliveryStreamName].concat(r);
      callback(null, {FailedPutCount: 0});
    });
    let subjects = _.range(999).map(i => ({foo: Array(5000).join('x')}));
    subjects.forEach(subject => monitor.log(subject));
    await monitor.flush();
    await testing.poll(async () => {
      assert.equal(records[logName].length, 999);
    });
    assert.equal(submissions, 7); // We would normally need 6 submissions
  });
});
<|endoftext|>


<commit_before>var Sails = require('sails'),
        sails;

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

before(function (done) {

    var testConfig = {
        environment: 'test',
        models: {
            connection: 'test',
            migrate: 'drop'
        },
        port: 1338,
        log: {
            level: 'warn'
        }
    };
    Sails.lift(testConfig, function (err, server) {
        sails = server;
        if (err)
            return done(err);
        // here you can load fixtures, etc.
        done(err, sails);
    });
});

after(function (done) {
    // here you can clear fixtures, etc.
    sails.lower(done);
});<commit_msg>Disabled grunt tasks during tests<commit_after>const Sails = require('sails');
let sails;

before(function (done) {

    var testConfig = {
        environment: 'test',
        models: {
            connection: 'test',
            migrate: 'drop'
        },
        port: 1338,
        log: {
            level: 'warn'
        },
        hooks: {grunt: false}
    };
    Sails.lift(testConfig, function (err, server) {
        sails = server;
        if (err)
            return done(err);
        // here you can load fixtures, etc.
        done(err, sails);
    });
});

after(function (done) {
    // here you can clear fixtures, etc.
    sails.lower(done);
});<|endoftext|>


<commit_before><commit_msg>Test factory.<commit_after>describe( 'ccLibrary', function () {
	beforeEach( function () {
		module( 'ccApp' );
	} );

	it( 'getCountries() query the Geonames.org api for countries data',
		inject( function ($httpBackend, $q, ccLibraryService) {
			$httpBackend.when( 'JSONP', 'http://api.geonames.org/countryInfoJSON?callback=JSON_CALLBACK&username=hanoman_sakti' )
				.respond( {
					geonames: [{key: 0}, {key: 1}, {key: 2}]
				} );
			var countries;
			$q.when( ccLibraryService.getCountries() ).then( function (result) {
				countries = result.geonames
			} );

			$httpBackend.flush();

			expect( countries.length ).toBe( 3 );

			$httpBackend.verifyNoOutstandingRequest();
		} ) );
} );<|endoftext|>


<commit_before>'use strict';
const Path = require('path');

const { test } = require('tap');

const startCLI = require('./start-cli');

test('stepping through breakpoints', (t) => {
  const script = Path.join('examples', 'break.js');
  const cli = startCLI([script]);

  function onFatal(error) {
    cli.quit();
    throw error;
  }

  return cli.waitForInitialBreak()
    .then(() => cli.waitForPrompt())
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:1`,
        'pauses in the first line of the script');
      t.match(
        cli.output,
        /> 1 \(function \([^)]+\) \{ const x = 10;/,
        'shows the source and marks the current line');
    })
    .then(() => cli.stepCommand('n'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:2`,
        'pauses in next line of the script');
      t.match(
        cli.output,
        '> 2 let name = \'World\';',
        'marks the 2nd line');
    })
    .then(() => cli.stepCommand('next'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:3`,
        'pauses in next line of the script');
      t.match(
        cli.output,
        '> 3 name = \'Robin\';',
        'marks the 3nd line');
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:10`,
        'pauses on the next breakpoint');
      t.match(
        cli.output,
        '>10 debugger;',
        'marks the debugger line');
    })

    // Prepare additional breakpoints
    .then(() => cli.command('sb("break.js", 6)'))
    .then(() => t.notMatch(cli.output, 'Could not resolve breakpoint'))
    .then(() => cli.command('sb("otherFunction()")'))
    .then(() => cli.command('sb(16)'))
    .then(() => t.notMatch(cli.output, 'Could not resolve breakpoint'))
    .then(() => cli.command('breakpoints'))
    .then(() => {
      t.match(cli.output, `#0 ${script}:6`);
      t.match(cli.output, `#1 ${script}:16`);
    })

    .then(() => cli.command('list()'))
    .then(() => {
      t.match(cli.output, '>10 debugger;', 'prints and marks current line');
      t.strictDeepEqual(
        cli.parseSourceLines(),
        [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
        'prints 5 lines before and after');
    })
    .then(() => cli.command('list(2)'))
    .then(() => {
      t.match(cli.output, '>10 debugger;', 'prints and marks current line');
      t.strictDeepEqual(
        cli.parseSourceLines(),
        [8, 9, 10, 11, 12],
        'prints 2 lines before and after');
    })

    .then(() => cli.stepCommand('s'))
    .then(() => cli.stepCommand(''))
    .then(() => {
      t.match(
        cli.output,
        'break in timers.js',
        'entered timers.js');
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:16`,
        'found breakpoint we set above w/ line number only');
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:6`,
        'found breakpoint we set above w/ line number & script');
    })
    .then(() => cli.stepCommand(''))
    .then(() => {
      t.match(
        cli.output,
        `debugCommand in ${script}:14`,
        'found function breakpoint we set above');
    })
    .then(() => cli.quit())
    .then(null, onFatal);
});

test('sb before loading file', (t) => {
  const script = Path.join('examples', 'cjs', 'index.js');
  const otherScript = Path.join('examples', 'cjs', 'other.js');
  const cli = startCLI([script]);

  function onFatal(error) {
    cli.quit();
    throw error;
  }

  return cli.waitForInitialBreak()
    .then(() => cli.waitForPrompt())
    .then(() => cli.command('sb("other.js", 3)'))
    .then(() => {
      t.match(
        cli.output,
        'not loaded yet',
        'warns that the script was not loaded yet');
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${otherScript}:3`,
        'found breakpoint in file that was not loaded yet');
    })
    .then(() => cli.quit())
    .then(null, onFatal);
});

test('clearBreakpoint', (t) => {
  const script = Path.join('examples', 'break.js');
  const cli = startCLI([script]);

  function onFatal(error) {
    cli.quit();
    throw error;
  }

  return cli.waitForInitialBreak()
    .then(() => cli.waitForPrompt())
    .then(() => cli.command('sb("break.js", 3)'))
    .then(() => cli.command('sb("break.js", 9)'))
    .then(() => cli.command('breakpoints'))
    .then(() => {
      t.match(cli.output, `#0 ${script}:3`);
      t.match(cli.output, `#1 ${script}:9`);
    })
    .then(() => cli.command('clearBreakpoint("break.js", 4)'))
    .then(() => {
      t.match(cli.output, 'Could not find breakpoint');
    })
    .then(() => cli.command('clearBreakpoint("not-such-script.js", 3)'))
    .then(() => {
      t.match(cli.output, 'Could not find breakpoint');
    })
    .then(() => cli.command('clearBreakpoint("break.js", 3)'))
    .then(() => cli.command('breakpoints'))
    .then(() => {
      t.match(cli.output, `#0 ${script}:9`);
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:9`,
        'hits the 2nd breakpoint because the 1st was cleared');
    })
    .then(() => cli.quit())
    .then(null, onFatal);
});
<commit_msg>test: Use useful break location<commit_after>'use strict';
const Path = require('path');

const { test } = require('tap');

const startCLI = require('./start-cli');

test('stepping through breakpoints', (t) => {
  const script = Path.join('examples', 'break.js');
  const cli = startCLI([script]);

  function onFatal(error) {
    cli.quit();
    throw error;
  }

  return cli.waitForInitialBreak()
    .then(() => cli.waitForPrompt())
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:1`,
        'pauses in the first line of the script');
      t.match(
        cli.output,
        /> 1 \(function \([^)]+\) \{ const x = 10;/,
        'shows the source and marks the current line');
    })
    .then(() => cli.stepCommand('n'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:2`,
        'pauses in next line of the script');
      t.match(
        cli.output,
        '> 2 let name = \'World\';',
        'marks the 2nd line');
    })
    .then(() => cli.stepCommand('next'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:3`,
        'pauses in next line of the script');
      t.match(
        cli.output,
        '> 3 name = \'Robin\';',
        'marks the 3nd line');
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:10`,
        'pauses on the next breakpoint');
      t.match(
        cli.output,
        '>10 debugger;',
        'marks the debugger line');
    })

    // Prepare additional breakpoints
    .then(() => cli.command('sb("break.js", 6)'))
    .then(() => t.notMatch(cli.output, 'Could not resolve breakpoint'))
    .then(() => cli.command('sb("otherFunction()")'))
    .then(() => cli.command('sb(16)'))
    .then(() => t.notMatch(cli.output, 'Could not resolve breakpoint'))
    .then(() => cli.command('breakpoints'))
    .then(() => {
      t.match(cli.output, `#0 ${script}:6`);
      t.match(cli.output, `#1 ${script}:16`);
    })

    .then(() => cli.command('list()'))
    .then(() => {
      t.match(cli.output, '>10 debugger;', 'prints and marks current line');
      t.strictDeepEqual(
        cli.parseSourceLines(),
        [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
        'prints 5 lines before and after');
    })
    .then(() => cli.command('list(2)'))
    .then(() => {
      t.match(cli.output, '>10 debugger;', 'prints and marks current line');
      t.strictDeepEqual(
        cli.parseSourceLines(),
        [8, 9, 10, 11, 12],
        'prints 2 lines before and after');
    })

    .then(() => cli.stepCommand('s'))
    .then(() => cli.stepCommand(''))
    .then(() => {
      t.match(
        cli.output,
        'break in timers.js',
        'entered timers.js');
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:16`,
        'found breakpoint we set above w/ line number only');
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:6`,
        'found breakpoint we set above w/ line number & script');
    })
    .then(() => cli.stepCommand(''))
    .then(() => {
      t.match(
        cli.output,
        `debugCommand in ${script}:14`,
        'found function breakpoint we set above');
    })
    .then(() => cli.quit())
    .then(null, onFatal);
});

test('sb before loading file', (t) => {
  const script = Path.join('examples', 'cjs', 'index.js');
  const otherScript = Path.join('examples', 'cjs', 'other.js');
  const cli = startCLI([script]);

  function onFatal(error) {
    cli.quit();
    throw error;
  }

  return cli.waitForInitialBreak()
    .then(() => cli.waitForPrompt())
    .then(() => cli.command('sb("other.js", 2)'))
    .then(() => {
      t.match(
        cli.output,
        'not loaded yet',
        'warns that the script was not loaded yet');
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${otherScript}:2`,
        'found breakpoint in file that was not loaded yet');
    })
    .then(() => cli.quit())
    .then(null, onFatal);
});

test('clearBreakpoint', (t) => {
  const script = Path.join('examples', 'break.js');
  const cli = startCLI([script]);

  function onFatal(error) {
    cli.quit();
    throw error;
  }

  return cli.waitForInitialBreak()
    .then(() => cli.waitForPrompt())
    .then(() => cli.command('sb("break.js", 3)'))
    .then(() => cli.command('sb("break.js", 9)'))
    .then(() => cli.command('breakpoints'))
    .then(() => {
      t.match(cli.output, `#0 ${script}:3`);
      t.match(cli.output, `#1 ${script}:9`);
    })
    .then(() => cli.command('clearBreakpoint("break.js", 4)'))
    .then(() => {
      t.match(cli.output, 'Could not find breakpoint');
    })
    .then(() => cli.command('clearBreakpoint("not-such-script.js", 3)'))
    .then(() => {
      t.match(cli.output, 'Could not find breakpoint');
    })
    .then(() => cli.command('clearBreakpoint("break.js", 3)'))
    .then(() => cli.command('breakpoints'))
    .then(() => {
      t.match(cli.output, `#0 ${script}:9`);
    })
    .then(() => cli.stepCommand('cont'))
    .then(() => {
      t.match(
        cli.output,
        `break in ${script}:9`,
        'hits the 2nd breakpoint because the 1st was cleared');
    })
    .then(() => cli.quit())
    .then(null, onFatal);
});
<|endoftext|>


<commit_before>module.exports = {
  root: true,
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react/recommended',
    'prettier',
    'prettier/@typescript-eslint',
    'prettier/react',
  ],
  plugins: ['react-hooks'],
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  settings: {
    react: {
      version: '16.8',
    },
  },
  env: { browser: true, es6: true },
  rules: {
    'react-hooks/rules-of-hooks': 'error',
    'react-hooks/exhaustive-deps': 'warn',
    'no-console': 'warn',
    'no-alert': 'error',
    'no-var': 'error',
    'prefer-const': 'error',
    'linebreak-style': ['error', 'unix'],
    'react/no-unescaped-entities': 'off',
    'react/prop-types': 'off',
    'react/no-unsafe': ['error', { checkAliases: true }],
  },
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      parser: '@typescript-eslint/parser',
      parserOptions: {
        ecmaVersion: 2018,
        sourceType: 'module',
        ecmaFeatures: {
          jsx: true,
        },
        warnOnUnsupportedTypeScriptVersion: true,
      },
      rules: {
        'no-undef': 'off',
        '@typescript-eslint/explicit-function-return-type': 'off',
        '@typescript-eslint/no-non-null-assertion': 'off',
        '@typescript-eslint/explicit-member-accessibility': 'off',
        '@typescript-eslint/interface-name-prefix': 'off',
        '@typescript-eslint/no-use-before-define': 'off',
        '@typescript-eslint/camelcase': 'off',
        '@typescript-eslint/no-object-literal-type-assertion': 'off',
      },
    },
    {
      files: ['*.spec.ts', '*.spec.tsx'],
      env: {
        node: true,
        jest: true,
      },
    },
  ],
};
<commit_msg>linter: disable eval<commit_after>module.exports = {
  root: true,
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react/recommended',
    'prettier',
    'prettier/@typescript-eslint',
    'prettier/react',
  ],
  plugins: ['react-hooks'],
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  settings: {
    react: {
      version: '16.8',
    },
  },
  env: { browser: true, es6: true },
  rules: {
    'react-hooks/rules-of-hooks': 'error',
    'react-hooks/exhaustive-deps': 'warn',
    'no-console': 'warn',
    'no-alert': 'error',
    'no-var': 'error',
    'no-eval': 'error',
    'no-implied-eval': 'error',
    'prefer-const': 'error',
    'linebreak-style': ['error', 'unix'],
    'react/no-unescaped-entities': 'off',
    'react/prop-types': 'off',
    'react/no-unsafe': ['error', { checkAliases: true }],
  },
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      parser: '@typescript-eslint/parser',
      parserOptions: {
        ecmaVersion: 2018,
        sourceType: 'module',
        ecmaFeatures: {
          jsx: true,
        },
        warnOnUnsupportedTypeScriptVersion: true,
      },
      rules: {
        'no-undef': 'off',
        '@typescript-eslint/explicit-function-return-type': 'off',
        '@typescript-eslint/no-non-null-assertion': 'off',
        '@typescript-eslint/explicit-member-accessibility': 'off',
        '@typescript-eslint/interface-name-prefix': 'off',
        '@typescript-eslint/no-use-before-define': 'off',
        '@typescript-eslint/camelcase': 'off',
        '@typescript-eslint/no-object-literal-type-assertion': 'off',
      },
    },
    {
      files: ['*.spec.ts', '*.spec.tsx'],
      env: {
        node: true,
        jest: true,
      },
    },
  ],
};
<|endoftext|>


<commit_before>var tape = require("tape"),
    jsdom = require("jsdom"),
    d3 = Object.assign(
      require("../"),
      require("d3-selection")
    );

/*************************************
 ************ Components *************
 *************************************/
var paragraph = d3.component({
  render: function (selection, d){ selection.text(d); },
  tagName: "p"
});

var heading = d3.component({
  render: function (selection, d){ selection.text(d); },
  tagName: "h"
});

var post = d3.component({
  render: function (selection, d){
    selection
      .call(heading, d.title)
      .call(paragraph, d.content);
  },
  tagName: "div"
});

var apple = d3.component({
  render: function (selection, d){ selection.text(d); },
  tagName:"span",
  className: "apple"
});
var orange = d3.component({
  render: function (selection, d){ selection.text(d); },
  tagName:"span",
  className: "orange"
});
var fruit = d3.component({
  render: function (selection, d){
    selection
      .call(apple, d === "apple" || [])
      .call(orange, d === "orange" || []);
  },
  tagName: "div"
});
var fruitBasket = d3.component({
  render: function (selection, d){
    selection
      .call(apple, d.apples || [])
      .call(orange, d.oranges || []);
  },
  tagName: "div"
});

/*************************************
 ************ Utilities **************
 *************************************/
function createDiv(){
  return d3.select(jsdom.jsdom().body).append("div");
}

/*************************************
 ************** Tests ****************
 *************************************/
tape("A component should render a single instance.", function(test) {
  var div = createDiv();
  div.call(paragraph, "foo");
  test.equal(div.html(), "
foo
");
  test.end();
});

tape("A component should render multiple instances.", function(test) {
  var div = createDiv();

  // Enter
  div.call(paragraph, [ "foo", "bar" ]);
  test.equal(div.html(), "
foo

bar
");

  // Update + Enter
  div.call(paragraph, [ "fooz", "barz", "baz" ]);
  test.equal(div.html(), "
fooz

barz

baz
");

  // Exit
  div.call(paragraph, []);
  test.equal(div.html(), "");

  test.end();
});

tape("Nested components.", function(test) {
  var div = createDiv();

  div.call(post, {
    title: "Title",
    content: "Content here."
  });

  test.equal(div.html(), [
    "
",
      "<h>Title</h>",
      "
Content here.
",
    "
"
  ].join(""));

  test.end();
});

tape("Nested components multiple instances.", function(test) {
  var div = createDiv();

  // Enter
  div.call(post, [
    { title: "A", content: "a" },
    { title: "B", content: "b" },
  ]);
  test.equal(div.html(), [
    "
<h>A</h>
a

",
    "
<h>B</h>
b

"
  ].join(""));

  // Enter + Update
  div.call(post, [
    { title: "D", content: "d" },
    { title: "E", content: "e" },
    { title: "F", content: "f" },
  ]);
  test.equal(div.html(), [
    "
<h>D</h>
d

",
    "
<h>E</h>
e

",
    "
<h>F</h>
f

"
  ].join(""));

  // Exit
  div.call(post, []);
  test.equal(div.html(), "");

  test.end();
});

tape("Conditional components with classes.", function(test) {
  var div = createDiv();

  // Enter
  div.call(fruit, ["apple", "orange", "apple", "apple", "orange"]);
  test.equal(div.html(), [
    '
true
',
    '
true
',
    '
true
',
    '
true
',
    '
true
'
  ].join(""));

  // Update + Exit
  div.call(fruit, ["orange", "apple", "apple"]);
  test.equal(div.html(), [
    '
true
',
    '
true
',
    '
true
'
  ].join(""));

  test.end();
});

tape("Multiple nested component types.", function(test) {
  var div = createDiv();

  // Enter
  div.call(fruitBasket, {
    apples: ["Red Delicious", "Honeycrisp"],
    oranges: ["Navel", "Mandarin", "Pomelo"]
  });
  test.equal(div.html(), [
    "
",
      'Red Delicious',
      'Honeycrisp',
      'Navel',
      'Mandarin',
      'Pomelo',
    "
"
  ].join(""));

  test.end();
});
<commit_msg>Add more extensive basket test<commit_after>var tape = require("tape"),
    jsdom = require("jsdom"),
    d3 = Object.assign(
      require("../"),
      require("d3-selection")
    );

/*************************************
 ************ Components *************
 *************************************/
var paragraph = d3.component({
  render: function (selection, d){ selection.text(d); },
  tagName: "p"
});

var heading = d3.component({
  render: function (selection, d){ selection.text(d); },
  tagName: "h"
});

var post = d3.component({
  render: function (selection, d){
    selection
      .call(heading, d.title)
      .call(paragraph, d.content);
  },
  tagName: "div"
});

var apple = d3.component({
  render: function (selection, d){ selection.text(d); },
  tagName:"span",
  className: "apple"
});
var orange = d3.component({
  render: function (selection, d){ selection.text(d); },
  tagName:"span",
  className: "orange"
});
var fruit = d3.component({
  render: function (selection, d){
    selection
      .call(apple, d === "apple" || [])
      .call(orange, d === "orange" || []);
  },
  tagName: "div"
});
var fruitBasket = d3.component({
  render: function (selection, d){
    selection
      .call(apple, d.apples || [])
      .call(orange, d.oranges || []);
  },
  tagName: "div"
});

/*************************************
 ************** Tests ****************
 *************************************/
tape("A component should render a single instance.", function(test) {
  var div = createDiv();
  div.call(paragraph, "foo");
  test.equal(div.html(), "
foo
");
  test.end();
});

tape("A component should render multiple instances.", function(test) {
  var div = createDiv();

  // Enter
  div.call(paragraph, [ "foo", "bar" ]);
  test.equal(div.html(), "
foo

bar
");

  // Update + Enter
  div.call(paragraph, [ "fooz", "barz", "baz" ]);
  test.equal(div.html(), "
fooz

barz

baz
");

  // Exit
  div.call(paragraph, []);
  test.equal(div.html(), "");

  test.end();
});

tape("Nested components.", function(test) {
  var div = createDiv();

  div.call(post, {
    title: "Title",
    content: "Content here."
  });

  test.equal(div.html(), [
    "
",
      "<h>Title</h>",
      "
Content here.
",
    "
"
  ].join(""));

  test.end();
});

tape("Nested components multiple instances.", function(test) {
  var div = createDiv();

  // Enter
  div.call(post, [
    { title: "A", content: "a" },
    { title: "B", content: "b" },
  ]);
  test.equal(div.html(), [
    "
<h>A</h>
a

",
    "
<h>B</h>
b

"
  ].join(""));

  // Enter + Update
  div.call(post, [
    { title: "D", content: "d" },
    { title: "E", content: "e" },
    { title: "F", content: "f" },
  ]);
  test.equal(div.html(), [
    "
<h>D</h>
d

",
    "
<h>E</h>
e

",
    "
<h>F</h>
f

"
  ].join(""));

  // Exit
  div.call(post, []);
  test.equal(div.html(), "");

  test.end();
});

tape("Conditional components with classes.", function(test) {
  var div = createDiv();

  // Enter
  div.call(fruit, ["apple", "orange", "apple", "apple", "orange"]);
  test.equal(div.html(), [
    '
true
',
    '
true
',
    '
true
',
    '
true
',
    '
true
'
  ].join(""));

  // Update + Exit
  div.call(fruit, ["orange", "apple", "apple"]);
  test.equal(div.html(), [
    '
true
',
    '
true
',
    '
true
'
  ].join(""));

  test.end();
});

tape("Multiple nested component types.", function(test) {
  var div = createDiv();

  // Enter
  div.call(fruitBasket, {
    apples: ["Red Delicious", "Honeycrisp"],
    oranges: ["Navel", "Mandarin", "Pomelo"]
  });
  test.equal(div.html(), [
    "
",
      'Red Delicious',
      'Honeycrisp',
      'Navel',
      'Mandarin',
      'Pomelo',
    "
"
  ].join(""));

  // Update + Enter + Exit
  div.call(fruitBasket, [
    {
      apples: ["Red Delicious", "Honeycrisp", "Granny Nice"],
      oranges: ["Navel", "Pomelo"]
    },
    {
      oranges: ["Mandarin"]
    }
  ]);
  test.equal(div.html(), [
    "
",
      'Red Delicious',
      'Honeycrisp',
      'Navel',
      'Pomelo',
      'Granny Nice',
    "
",
    "
",
      'Mandarin',
    "
"
  ].join(""));

  test.end();
});

/*************************************
 ************ Utilities **************
 *************************************/
function createDiv(){
  return d3.select(jsdom.jsdom().body).append("div");
}
<|endoftext|>


<commit_before>var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  app.quit();
});

// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600, frame: false});

  // and load the index.html of the app.
  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});
<commit_msg>[frameless window] Resize window's size making more fit the content.<commit_after>var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  app.quit();
});

// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 360, height: 300, frame: false});

  // and load the index.html of the app.
  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});
<|endoftext|>


<commit_before>import React from 'react'
import test from 'ava'
import { shallow } from 'enzyme'
import proxyquire from 'proxyquire'
import mockboxGL from 'mapbox-gl-js-mock'
import DataSelection from '../../app/assets/scripts/utils/data-selection'

const { Map } = proxyquire.noCallThru().load('../../app/assets/scripts/components/map', {
  'mapbox-gl': mockboxGL
})

test('map test', t => {
  const dataSelection = DataSelection({})
  const component = shallow(<Map dataSelection={dataSelection} />)

  t.truthy(component.hasClass('map'))

  // mock mount
  const instance = component.instance()
  t.notThrows(() => instance.componentDidMount())
})
<commit_msg>Fixes failing map test<commit_after>import React from 'react'
import test from 'ava'
import { shallow } from 'enzyme'
import proxyquire from 'proxyquire'
import mockboxGL from 'mapbox-gl-js-mock'
import DataSelection from '../../app/assets/scripts/utils/data-selection'

const { Map } = proxyquire.noCallThru().load('../../app/assets/scripts/components/map', {
  'mapbox-gl': mockboxGL
})

test('map test', t => {
  const dataSelection = DataSelection({})
  const component = shallow(<Map dataSelection={dataSelection} />)

  t.truthy(component.hasClass('map'))

  // mock mount
  let instance = component.instance()
  instance._adjustOpacity = () => {}
  t.notThrows(() => instance.componentDidMount())
})
<|endoftext|>