<commit_before>/**
 * Fusion.Widget.Select
 *
 * $Id: Select.js 2036 2010-01-14 19:59:41Z madair $
 *
 * Copyright (c) 2007, DM Solutions Group Inc.
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

 /********************************************************************
 * Class: Fusion.Widget.Select
 *
 * perform a selection on map features
 *
 * **********************************************************************/

Fusion.Widget.Select = OpenLayers.Class(Fusion.Widget, {
    isExclusive: true,
    uiClass: Jx.Button,
    selectionType: 'INTERSECTS',
    nTolerance : 3,     //default pixel tolerance for a point click
    bActiveOnly: false, //only select feature(s) on the active layer?
    maxFeatures: 0,     //default of 0 selects all features (i.e. no maximum)
    pointClickSingleSelect: true, //default of true causes a point click always to select only a single feature

    initializeWidget: function(widgetTag) {
        this.asCursor = ['auto'];

        this.enable = Fusion.Widget.Select.prototype.enable;

        var json = widgetTag.extension;

        this.selectionType = json.SelectionType ? json.SelectionType[0] : 'INTERSECTS';

        if (json.Tolerance && (parseInt(json.Tolerance[0]) > 0)) {
            this.nTolerance = parseInt(json.Tolerance[0]);
        }

        if (json.MaxFeatures) {
            this.maxFeatures = parseInt(json.MaxFeatures[0]);
        }

        if(json.PointClickSingleSelect) {
            this.pointClickSingleSelect = (json.PointClickSingleSelect[0] != 'false');
        }

        this.bActiveOnly = (json.QueryActiveLayer &&
                           (json.QueryActiveLayer[0] == 'true' ||
                            json.QueryActiveLayer[0] == '1')) ? true : false;

        this.bComputeMetadata = (json.ComputeMetadata &&
                           (json.ComputeMetadata[0] == 'true' ||
                            json.ComputeMetadata[0] == '1')) ? true : false;

        if (this.bActiveOnly) {
            this.getMap().registerForEvent(Fusion.Event.MAP_ACTIVE_LAYER_CHANGED, OpenLayers.Function.bind(this.enable, this));
        }

        var mapWidget = this.getMap();
        this.map = mapWidget.oMapOL;
        this.handler = new OpenLayers.Handler.Box(this,{done: this.execute});
        //this.shiftHandler = new OpenLayers.Handler.Box(this,{done: this.extend},
        //                                {keyMask:OpenLayers.Handler.MOD_SHIFT});
        mapWidget.handlers.push(this.handler);
        //mapWidget.handlers.push(this.shiftHandler);

    },

    shouldActivateWith: function(widget) {
        return (widget instanceof Fusion.Widget.Select &&
                widget.bActiveOnly == this.bActiveOnly);

    },
    enable: function() {
        if (this.bActiveOnly) {
            var layer = this.getMap().getActiveLayer();
            if (layer && layer.selectable) {
                Fusion.Widget.prototype.enable.apply(this, []);
            } else {
                this.disable();
            }
        } else {
            Fusion.Widget.prototype.enable.apply(this,[]);
        }
    },

    /**
       * activate the widget (listen to mouse events and change cursor)
       * This function should be defined for all functions that register
       * as a widget in the map
       */
    activate: function() {
        this.handler.activate();
        //this.shiftHandler.activate();
        this.getMap().setCursor(this.asCursor);
        this.getMap().supressContextMenu(true);
    },

    /**
       * deactivate the widget (listen to mouse events and change cursor)
       * This function should be defined for all functions that register
       * as a widget in the map
       **/
    deactivate: function() {
        this.handler.deactivate();
        //this.shiftHandler.deactivate();
        this.getMap().setCursor('auto');
        this.getMap().supressContextMenu(false);
    },

    /**
       *  set the extants of the map based on the pixel coordinates
       * passed
       *
       * Parameters:
        *   position will be either an instance of OpenLayers.Bounds when the mouse has
        *   moved, or an OpenLayers.Pixel for click without dragging on the map
        **/
    execute : function(position, extend) {
        //ctrl click is used to launch a URL defined on the feature. See ClickCTRL widget
        if (this.keyModifiers & OpenLayers.Handler.MOD_CTRL) {
          //return;
        }

        var nRight, nTop;
        var nLeft = position.left;
        var nBottom = position.bottom;
        var maxFeaturesToSelect = this.maxFeatures;

        if (position instanceof OpenLayers.Bounds) {
          nRight = position.right;
          nTop = position.top;
        } else { // it's a pixel
          nRight = nLeft = position.x;
          nTop = nBottom = position.y;
          if(this.pointClickSingleSelect) {
              maxFeaturesToSelect = 1;
          }
        }

        var sMin = this.getMap().pixToGeo(nLeft,nBottom);
        var sMax = this.getMap().pixToGeo(nRight,nTop);
        var nXDelta = Math.abs(nLeft-nRight);
        var nYDelta = Math.abs(nBottom- nTop);

        var options = {};
        if (nXDelta <=this.nTolerance && nYDelta <=this.nTolerance) {
            var dfGeoTolerance = this.getMap().pixToGeoMeasure(this.nTolerance);
            sMin.x = sMin.x-dfGeoTolerance;
            sMin.y = sMin.y-dfGeoTolerance;
            sMax.x = sMax.x+dfGeoTolerance;
            sMax.y = sMax.y+dfGeoTolerance;
        }

        options.geometry = 'POLYGON(('+ sMin.x + ' ' +  sMin.y + ', ' +  sMax.x + ' ' +  sMin.y + ', ' + sMax.x + ' ' +  sMax.y + ', ' + sMin.x + ' ' +  sMax.y + ', ' + sMin.x + ' ' +  sMin.y + '))';
        options.selectionType = this.selectionType;
        options.maxFeatures = maxFeaturesToSelect;
        options.computed = this.bComputeMetadata;

        if (this.bActiveOnly) {
            var layer = this.getMap().getActiveLayer();
            if (layer) {
                options.layers = layer.layerName;
            } else {
                return;
            }
        }

        if (this.handler.dragHandler.evt.shiftKey) {
            options.extendSelection = true;
        }

        this.getMap().query(options);
    },

    /**
        * handler for extending the selection when the shift key is pressed
        *
        * Parameters:
        * evt - the OpenLayers.Event object that is being responded to
        */
    extend: function(position) {
        this.execute(position, true);
    },

    /**
        * calculate the keyboard modifier mask for this event
        *
        * Parameters:
        * evt - the OpenLayers.Event object that is being responded to
        */
    setModifiers: function(evt) {
        this.keyModifiers =
            (evt.shiftKey ? OpenLayers.Handler.MOD_SHIFT : 0) |
            (evt.ctrlKey  ? OpenLayers.Handler.MOD_CTRL  : 0) |
            (evt.altKey   ? OpenLayers.Handler.MOD_ALT   : 0);
    },

    /**
        * clears the keyboard modifier mask for this event
        *
        * Parameters:
        * evt - the OpenLayers.Event object that is being responded to
        */
    clearModifiers: function(evt) {
      this.keyModifiers = 0;
    },

    /**
        * allows run-time setting of widget parameters
        *
        * Parameters:
        * param - the widget parameter name to set; for the Select widget these may be:
        *               'Tolerance' and 'SelectionType'
        * value - the value to sue for the parameter
        */
    setParameter : function(param, value) {
        if (param == "Tolerance" && value > 0) {
            this.nTolerance = value;
        }
        if (param == 'SelectionType') {
            this.selectionType = value;
        }
    }
});
<commit_msg>HCCGENERAL-142: Remove context menu suppression on activation of Select widget. I do not know why this was in there, but there has been no observable problems of having a context menu on an active Select widget.<commit_after>/**
 * Fusion.Widget.Select
 *
 * $Id: Select.js 2036 2010-01-14 19:59:41Z madair $
 *
 * Copyright (c) 2007, DM Solutions Group Inc.
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

 /********************************************************************
 * Class: Fusion.Widget.Select
 *
 * perform a selection on map features
 *
 * **********************************************************************/

Fusion.Widget.Select = OpenLayers.Class(Fusion.Widget, {
    isExclusive: true,
    uiClass: Jx.Button,
    selectionType: 'INTERSECTS',
    nTolerance : 3,     //default pixel tolerance for a point click
    bActiveOnly: false, //only select feature(s) on the active layer?
    maxFeatures: 0,     //default of 0 selects all features (i.e. no maximum)
    pointClickSingleSelect: true, //default of true causes a point click always to select only a single feature

    initializeWidget: function(widgetTag) {
        this.asCursor = ['auto'];

        this.enable = Fusion.Widget.Select.prototype.enable;

        var json = widgetTag.extension;

        this.selectionType = json.SelectionType ? json.SelectionType[0] : 'INTERSECTS';

        if (json.Tolerance && (parseInt(json.Tolerance[0]) > 0)) {
            this.nTolerance = parseInt(json.Tolerance[0]);
        }

        if (json.MaxFeatures) {
            this.maxFeatures = parseInt(json.MaxFeatures[0]);
        }

        if(json.PointClickSingleSelect) {
            this.pointClickSingleSelect = (json.PointClickSingleSelect[0] != 'false');
        }

        this.bActiveOnly = (json.QueryActiveLayer &&
                           (json.QueryActiveLayer[0] == 'true' ||
                            json.QueryActiveLayer[0] == '1')) ? true : false;

        this.bComputeMetadata = (json.ComputeMetadata &&
                           (json.ComputeMetadata[0] == 'true' ||
                            json.ComputeMetadata[0] == '1')) ? true : false;

        if (this.bActiveOnly) {
            this.getMap().registerForEvent(Fusion.Event.MAP_ACTIVE_LAYER_CHANGED, OpenLayers.Function.bind(this.enable, this));
        }

        var mapWidget = this.getMap();
        this.map = mapWidget.oMapOL;
        this.handler = new OpenLayers.Handler.Box(this,{done: this.execute});
        //this.shiftHandler = new OpenLayers.Handler.Box(this,{done: this.extend},
        //                                {keyMask:OpenLayers.Handler.MOD_SHIFT});
        mapWidget.handlers.push(this.handler);
        //mapWidget.handlers.push(this.shiftHandler);

    },

    shouldActivateWith: function(widget) {
        return (widget instanceof Fusion.Widget.Select &&
                widget.bActiveOnly == this.bActiveOnly);

    },
    enable: function() {
        if (this.bActiveOnly) {
            var layer = this.getMap().getActiveLayer();
            if (layer && layer.selectable) {
                Fusion.Widget.prototype.enable.apply(this, []);
            } else {
                this.disable();
            }
        } else {
            Fusion.Widget.prototype.enable.apply(this,[]);
        }
    },

    /**
       * activate the widget (listen to mouse events and change cursor)
       * This function should be defined for all functions that register
       * as a widget in the map
       */
    activate: function() {
        this.handler.activate();
        //this.shiftHandler.activate();
        this.getMap().setCursor(this.asCursor);
        //this.getMap().supressContextMenu(true);
    },

    /**
       * deactivate the widget (listen to mouse events and change cursor)
       * This function should be defined for all functions that register
       * as a widget in the map
       **/
    deactivate: function() {
        this.handler.deactivate();
        //this.shiftHandler.deactivate();
        this.getMap().setCursor('auto');
        this.getMap().supressContextMenu(false);
    },

    /**
       *  set the extants of the map based on the pixel coordinates
       * passed
       *
       * Parameters:
        *   position will be either an instance of OpenLayers.Bounds when the mouse has
        *   moved, or an OpenLayers.Pixel for click without dragging on the map
        **/
    execute : function(position, extend) {
        //ctrl click is used to launch a URL defined on the feature. See ClickCTRL widget
        if (this.keyModifiers & OpenLayers.Handler.MOD_CTRL) {
          //return;
        }

        var nRight, nTop;
        var nLeft = position.left;
        var nBottom = position.bottom;
        var maxFeaturesToSelect = this.maxFeatures;

        if (position instanceof OpenLayers.Bounds) {
          nRight = position.right;
          nTop = position.top;
        } else { // it's a pixel
          nRight = nLeft = position.x;
          nTop = nBottom = position.y;
          if(this.pointClickSingleSelect) {
              maxFeaturesToSelect = 1;
          }
        }

        var sMin = this.getMap().pixToGeo(nLeft,nBottom);
        var sMax = this.getMap().pixToGeo(nRight,nTop);
        var nXDelta = Math.abs(nLeft-nRight);
        var nYDelta = Math.abs(nBottom- nTop);

        var options = {};
        if (nXDelta <=this.nTolerance && nYDelta <=this.nTolerance) {
            var dfGeoTolerance = this.getMap().pixToGeoMeasure(this.nTolerance);
            sMin.x = sMin.x-dfGeoTolerance;
            sMin.y = sMin.y-dfGeoTolerance;
            sMax.x = sMax.x+dfGeoTolerance;
            sMax.y = sMax.y+dfGeoTolerance;
        }

        options.geometry = 'POLYGON(('+ sMin.x + ' ' +  sMin.y + ', ' +  sMax.x + ' ' +  sMin.y + ', ' + sMax.x + ' ' +  sMax.y + ', ' + sMin.x + ' ' +  sMax.y + ', ' + sMin.x + ' ' +  sMin.y + '))';
        options.selectionType = this.selectionType;
        options.maxFeatures = maxFeaturesToSelect;
        options.computed = this.bComputeMetadata;

        if (this.bActiveOnly) {
            var layer = this.getMap().getActiveLayer();
            if (layer) {
                options.layers = layer.layerName;
            } else {
                return;
            }
        }

        if (this.handler.dragHandler.evt.shiftKey) {
            options.extendSelection = true;
        }

        this.getMap().query(options);
    },

    /**
        * handler for extending the selection when the shift key is pressed
        *
        * Parameters:
        * evt - the OpenLayers.Event object that is being responded to
        */
    extend: function(position) {
        this.execute(position, true);
    },

    /**
        * calculate the keyboard modifier mask for this event
        *
        * Parameters:
        * evt - the OpenLayers.Event object that is being responded to
        */
    setModifiers: function(evt) {
        this.keyModifiers =
            (evt.shiftKey ? OpenLayers.Handler.MOD_SHIFT : 0) |
            (evt.ctrlKey  ? OpenLayers.Handler.MOD_CTRL  : 0) |
            (evt.altKey   ? OpenLayers.Handler.MOD_ALT   : 0);
    },

    /**
        * clears the keyboard modifier mask for this event
        *
        * Parameters:
        * evt - the OpenLayers.Event object that is being responded to
        */
    clearModifiers: function(evt) {
      this.keyModifiers = 0;
    },

    /**
        * allows run-time setting of widget parameters
        *
        * Parameters:
        * param - the widget parameter name to set; for the Select widget these may be:
        *               'Tolerance' and 'SelectionType'
        * value - the value to sue for the parameter
        */
    setParameter : function(param, value) {
        if (param == "Tolerance" && value > 0) {
            this.nTolerance = value;
        }
        if (param == 'SelectionType') {
            this.selectionType = value;
        }
    }
});
<|endoftext|>


<commit_before>import inspect from '../index'
import { expect } from 'chai'
// eslint-disable-next-line id-length
const h = (name, attributes, ...children) => {
  const container = document.createElement(name)
  for (const key in attributes) {
    container.setAttribute(key, attributes[key])
  }
  for (const i in children) {
    container.appendChild(children[i])
  }
  return container
}
describe('HTMLElement', () => {
  beforeEach(() => {
    if (typeof HTMLElement !== 'function') {
      class HTMLElement {
        constructor(tagName) {
          this.tagName = tagName.toUpperCase()
          this.attributes = {}
          this.children = []
        }

        appendChild(element) {
          this.children.push(element)
        }

        getAttribute(name) {
          return this.attributes[name]
        }

        setAttribute(name, value) {
          this.attributes[name] = value
        }

        getAttributeNames() {
          return Object.keys(this.attributes)
        }
      }
      global.document = {}
      global.document.createElement = tagName => new HTMLElement(tagName)
      global.HTMLElement = HTMLElement
    }
  })

  it('returns `<div></div>` for an empty div', () => {
    expect(inspect(h('div'))).to.equal('

')
  })

  it('returns `<div id="foo"></div>` for a div with an id', () => {
    expect(inspect(h('div', { id: 'foo' }))).to.equal('

')
  })

  it('returns `<div id="foo" aria-live="foo" hidden></div>` for a div with an id', () => {
    expect(inspect(h('div', { id: 'foo', 'aria-live': 'bar', hidden: '' }))).to.equal(
      '

'
    )
  })

  it('returns output including children', () => {
    expect(
      inspect(h('div', { id: 'foo', hidden: '' }, h('pre', {}, h('code', {}, h('span', { style: 'color:red' })))))
    ).to.equal('

')
  })

  describe('truncate', () => {
    let template = null
    beforeEach(() => {
      template = h('div', { id: 'foo', hidden: '' }, h('pre', {}, h('code', {}, h('span', { style: 'color:red' }))))
    })

    it('returns the full representation when truncate is over string length', () => {
      expect(inspect(template, { truncate: 100 })).to.equal(
        '

'
      )
    })

    it('truncates arguments values longer than truncate (81)', () => {
      expect(inspect(template, { truncate: 81 })).to.equal(
        '

'
      )
    })

    it('truncates arguments values longer than truncate (78)', () => {
      expect(inspect(template, { truncate: 78 })).to.equal(
        '

'
      )
    })

    it('truncates arguments values longer than truncate (77)', () => {
      expect(inspect(template, { truncate: 77 })).to.equal('

…(1)

')
    })

    it('truncates arguments values longer than truncate (64)', () => {
      expect(inspect(template, { truncate: 64 })).to.equal('

…(1)

')
    })

    it('truncates arguments values longer than truncate (63)', () => {
      expect(inspect(template, { truncate: 63 })).to.equal('

…(1)

')
    })

    it('truncates arguments values longer than truncate (51)', () => {
      expect(inspect(template, { truncate: 51 })).to.equal('

…(1)

')
    })

    it('truncates arguments values longer than truncate (49)', () => {
      expect(inspect(template, { truncate: 49 })).to.equal('
…(1)
')
    })

    it('truncates arguments values longer than truncate (26)', () => {
      expect(inspect(template, { truncate: 26 })).to.equal('
…(1)
')
    })

    it('truncates arguments values longer than truncate (25)', () => {
      expect(inspect(template, { truncate: 25 })).to.equal('
…(1)
')
    })

    it('truncates arguments values longer than truncate (24)', () => {
      expect(inspect(template, { truncate: 24 })).to.equal('
…(1)
')
    })

    it('truncates arguments values longer than truncate (23)', () => {
      expect(inspect(template, { truncate: 23 })).to.equal('
…(1)
')
    })

    it('disregards truncate when it cannot truncate further (18)', () => {
      expect(inspect(template, { truncate: 18 })).to.equal('
…(1)
')
    })

    it('disregards truncate when it cannot truncate further (1)', () => {
      expect(inspect(template, { truncate: 1 })).to.equal('
…(1)
')
    })
  })

  describe('colors', () => {
    it('returns element as cyan, with attribute names in yellow and values as string colour', () => {
      expect(inspect(h('div', { id: 'foo' }), { colors: true })).to.equal(
        '\u001b[36m
\u001b[39m\u001b[36m
\u001b[39m'
      )
    })
  })
})
<commit_msg>test(html): check if global defined<commit_after>import inspect from '../index'
import { expect } from 'chai'
// eslint-disable-next-line id-length
const h = (name, attributes, ...children) => {
  const container = document.createElement(name)
  for (const key in attributes) {
    container.setAttribute(key, attributes[key])
  }
  for (const i in children) {
    container.appendChild(children[i])
  }
  return container
}
describe('HTMLElement', () => {
  beforeEach(() => {
    if (typeof HTMLElement !== 'function') {
      class HTMLElement {
        constructor(tagName) {
          this.tagName = tagName.toUpperCase()
          this.attributes = {}
          this.children = []
        }

        appendChild(element) {
          this.children.push(element)
        }

        getAttribute(name) {
          return this.attributes[name]
        }

        setAttribute(name, value) {
          this.attributes[name] = value
        }

        getAttributeNames() {
          return Object.keys(this.attributes)
        }
      }
      if (typeof global === 'undefined') {
        window.document.createElement = tagName => new HTMLElement(tagName)
        window.HTMLElement = HTMLElement
      } else {
        global.document = {}
        global.document.createElement = tagName => new HTMLElement(tagName)
        global.HTMLElement = HTMLElement
      }
    }
  })

  it('returns `<div></div>` for an empty div', () => {
    expect(inspect(h('div'))).to.equal('

')
  })

  it('returns `<div id="foo"></div>` for a div with an id', () => {
    expect(inspect(h('div', { id: 'foo' }))).to.equal('

')
  })

  it('returns `<div id="foo" aria-live="foo" hidden></div>` for a div with an id', () => {
    expect(inspect(h('div', { id: 'foo', 'aria-live': 'bar', hidden: '' }))).to.equal(
      '

'
    )
  })

  it('returns output including children', () => {
    expect(
      inspect(h('div', { id: 'foo', hidden: '' }, h('pre', {}, h('code', {}, h('span', { style: 'color:red' })))))
    ).to.equal('

')
  })

  describe('truncate', () => {
    let template = null
    beforeEach(() => {
      template = h('div', { id: 'foo', hidden: '' }, h('pre', {}, h('code', {}, h('span', { style: 'color:red' }))))
    })

    it('returns the full representation when truncate is over string length', () => {
      expect(inspect(template, { truncate: 100 })).to.equal(
        '

'
      )
    })

    it('truncates arguments values longer than truncate (81)', () => {
      expect(inspect(template, { truncate: 81 })).to.equal(
        '

'
      )
    })

    it('truncates arguments values longer than truncate (78)', () => {
      expect(inspect(template, { truncate: 78 })).to.equal(
        '

'
      )
    })

    it('truncates arguments values longer than truncate (77)', () => {
      expect(inspect(template, { truncate: 77 })).to.equal('

…(1)

')
    })

    it('truncates arguments values longer than truncate (64)', () => {
      expect(inspect(template, { truncate: 64 })).to.equal('

…(1)

')
    })

    it('truncates arguments values longer than truncate (63)', () => {
      expect(inspect(template, { truncate: 63 })).to.equal('

…(1)

')
    })

    it('truncates arguments values longer than truncate (51)', () => {
      expect(inspect(template, { truncate: 51 })).to.equal('

…(1)

')
    })

    it('truncates arguments values longer than truncate (49)', () => {
      expect(inspect(template, { truncate: 49 })).to.equal('
…(1)
')
    })

    it('truncates arguments values longer than truncate (26)', () => {
      expect(inspect(template, { truncate: 26 })).to.equal('
…(1)
')
    })

    it('truncates arguments values longer than truncate (25)', () => {
      expect(inspect(template, { truncate: 25 })).to.equal('
…(1)
')
    })

    it('truncates arguments values longer than truncate (24)', () => {
      expect(inspect(template, { truncate: 24 })).to.equal('
…(1)
')
    })

    it('truncates arguments values longer than truncate (23)', () => {
      expect(inspect(template, { truncate: 23 })).to.equal('
…(1)
')
    })

    it('disregards truncate when it cannot truncate further (18)', () => {
      expect(inspect(template, { truncate: 18 })).to.equal('
…(1)
')
    })

    it('disregards truncate when it cannot truncate further (1)', () => {
      expect(inspect(template, { truncate: 1 })).to.equal('
…(1)
')
    })
  })

  describe('colors', () => {
    it('returns element as cyan, with attribute names in yellow and values as string colour', () => {
      expect(inspect(h('div', { id: 'foo' }), { colors: true })).to.equal(
        '\u001b[36m
\u001b[39m\u001b[36m
\u001b[39m'
      )
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

var isArguments = require('../../function/is-arguments')
  , toPosInt    = require('../../number/to-pos-integer')
  , callable    = require('../../object/valid-callable')
  , validValue  = require('../../object/valid-value')
  , isString    = require('../../string/is-string')

  , isArray = Array.isArray, call = Function.prototype.call;

module.exports = function (arrayLike/*, mapFn, thisArg*/) {
	var mapFn = arguments[1], thisArg = arguments[2], Constructor, i, arr, l, char, code, iterator
	  , result;

	arrayLike = Object(validValue(arrayLike));

	if (!this || !Array.isPrototypeOf(this)) Constructor = Array;
	else Constructor = this;
	if (mapFn != null) callable(mapFn);

	if (!isArray(arrayLike)) {
		if (isString(arrayLike)) {
			l = arrayLike.length;
			arr = new Constructor();
			for (i = 0; i < l; ++i) {
				char = arrayLike[i];
				if ((i + 1) < l) {
					code = char.charCodeAt(0);
					if ((code >= 0xD800) && (code <= 0xDBFF)) char += arrayLike[++i];
				}
				arr.push(char);
			}
			return arr;
		}
		if ((typeof arrayLike['@@iterator'] === 'function')) {
			arr = new Constructor();
			iterator = arrayLike['@@iterator']();
			result = iterator.next();
			i = 0;
			while (!result.done) {
				arr[i] = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
				result = iterator.next();
				++i;
			}
			return arr;
		}
	}

	l = toPosInt(arrayLike.length);
	if (mapFn != null) {
		arr = new Constructor(l);
		for (i = 0; i < l; ++i) arr[i] = call.call(mapFn, thisArg, arrayLike[i], i);
		return arr;
	}

	if (isArguments(arrayLike)) {
		if (l !== 1) return Constructor.apply(null, arrayLike);
		arr = new Constructor(1);
		arr[0] = arrayLike[0];
		return arr;
	}

	arr = new Constructor(l);
	for (i = 0; i < l; ++i) arr[i] = arrayLike[i];
	return arr;
};
<commit_msg>Assure map processing of string chars<commit_after>'use strict';

var isArguments = require('../../function/is-arguments')
  , toPosInt    = require('../../number/to-pos-integer')
  , callable    = require('../../object/valid-callable')
  , validValue  = require('../../object/valid-value')
  , isString    = require('../../string/is-string')

  , isArray = Array.isArray, call = Function.prototype.call;

module.exports = function (arrayLike/*, mapFn, thisArg*/) {
	var mapFn = arguments[1], thisArg = arguments[2], Constructor, i, arr, l, char, code, iterator
	  , result;

	arrayLike = Object(validValue(arrayLike));

	if (!this || !Array.isPrototypeOf(this)) Constructor = Array;
	else Constructor = this;
	if (mapFn != null) callable(mapFn);

	if (!isArray(arrayLike)) {
		if (isString(arrayLike)) {
			l = arrayLike.length;
			arr = new Constructor();
			for (i = 0; i < l; ++i) {
				char = arrayLike[i];
				if ((i + 1) < l) {
					code = char.charCodeAt(0);
					if ((code >= 0xD800) && (code <= 0xDBFF)) char += arrayLike[++i];
				}
				arr.push(mapFn ? call.call(mapFn, thisArg, char, i) : char);
			}
			return arr;
		}
		if ((typeof arrayLike['@@iterator'] === 'function')) {
			arr = new Constructor();
			iterator = arrayLike['@@iterator']();
			result = iterator.next();
			i = 0;
			while (!result.done) {
				arr[i] = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
				result = iterator.next();
				++i;
			}
			return arr;
		}
	}

	l = toPosInt(arrayLike.length);
	if (mapFn != null) {
		arr = new Constructor(l);
		for (i = 0; i < l; ++i) arr[i] = call.call(mapFn, thisArg, arrayLike[i], i);
		return arr;
	}

	if (isArguments(arrayLike)) {
		if (l !== 1) return Constructor.apply(null, arrayLike);
		arr = new Constructor(1);
		arr[0] = arrayLike[0];
		return arr;
	}

	arr = new Constructor(l);
	for (i = 0; i < l; ++i) arr[i] = arrayLike[i];
	return arr;
};
<|endoftext|>


<commit_before>console.log('Server application running...');

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

http.listen(3000, function () {
    console.log('listening on *:3000');
});

io.on('connection', function (socket) {
    console.log('New user connected');

    socket.emit('hi', 'data');

    socket.on('hi', function (data) {
        console.log(data);
    });

    socket.on('disconnect', function () {
        console.log('User disconnected');
    });
});

//app.get('/', function (req, res) {
//    res.sendfile('index.html');
//});

<commit_msg>server new events<commit_after>console.log('Server application running...');

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

var clipboardSize = 5;
var clipboard = {}

for (var i = 1; i <= clipboardSize; i++) {
	clipboard[i] = {
				"type": "",
				"value": ""
			};
}

http.listen(3000, function () {
    console.log('listening on *:3000');
});

io.on('connection', function (socket) {
    console.log('New user connected');

    socket.emit('hi', 'data');

    socket.on('hi', function (data) {
        console.log(data);
    });

	socket.on('text', function(data) {
		console.log('received: ' + data);
		clipboard[0].type = "text";
		clipboard[0].value = data;
	});

	socket.on('demand', function(data) {
		if (data <= clipboardSize && data > 0) {
			console.log('sending: ' + textData);
			socket.emit('text', clipboard[data].value);
		}
	});

    socket.on('disconnect', function () {
        console.log('User disconnected');
    });
});

//app.get('/', function (req, res) {
//    res.sendfile('index.html');
//});

<|endoftext|>


<commit_before>var should = require('./init.js');
var mixin = require('../mixins/cacheModel');
var DataSource = require('loopback-datasource-juggler').DataSource;
var db;
var Person;
var options;

describe('Couchbase tests', function() {
  before(function() {
    db = getDataSource('loopback-connector-couchbase3');
    Person = db.createModel('person', {id: Number, name: String, age: Number});
    persons = [
      {
        id: 1,
        name: 'Mary',
        age: 34
      },
      {
        id: 2,
        name: 'Charlie',
        age: 24
      }
    ];
    options = {
      backend: 'couchbase',
      ttl: 3  //s
    };
  });

  it('create should create new item', function(done) {
    return Person.create(persons[0]).then(function(res) {
      res.name.should.eql('Mary');
      done();
    }).catch(function(err) {
      done(err);
    });
  });

  it('create should create new item with mixin EXPIRE in 3s', function(done) {
    mixin(Person, options);
    return Person.create(persons[1]).then(function(res) {
      res.name.should.eql('Charlie');
      setTimeout(function() {
        return Person.findById(persons[1].id.toString()).then(function(res) {
          done(new Error('expected an error'));
        }).catch(function(err) {
          should.exist(err);
          done();
        });
      }, options.ttl * 1000);
    }).catch(function(err) {
      done(err);
    });
  });

  it('remove one exist document', function(done) {
    return Person.removeById(persons[0].id).then(function() {
      done();
    }).catch(function(err) {
      done(err);
    });
  });

  it('create error with none-couchbase connector', function(done) {
    db = new DataSource('memory');
    Person = db.createModel('person', {id: Number, name: String, age: Number});
    mixin(Person, options);
    return Person.create(persons[1]).then(function(res) {
      done(new Error('expected an error'));
    }).catch(function(err) {
      should.exist(err);
      done();
    });
  });
});
<commit_msg>set setTimeout() to (options.ttl + 1) * 1000 for system latency<commit_after>var should = require('./init.js');
var mixin = require('../mixins/cacheModel');
var DataSource = require('loopback-datasource-juggler').DataSource;
var db;
var Person;
var options;

describe('Couchbase tests', function() {
  before(function() {
    db = getDataSource('loopback-connector-couchbase3');
    Person = db.createModel('person', {id: Number, name: String, age: Number});
    persons = [
      {
        id: 1,
        name: 'Mary',
        age: 34
      },
      {
        id: 2,
        name: 'Charlie',
        age: 24
      }
    ];
    options = {
      backend: 'couchbase',
      ttl: 3  //s
    };
  });

  it('create should create new item', function(done) {
    return Person.create(persons[0]).then(function(res) {
      res.name.should.eql('Mary');
      done();
    }).catch(function(err) {
      done(err);
    });
  });

  it('create should create new item with mixin EXPIRE in 3s', function(done) {
    mixin(Person, options);
    return Person.create(persons[1]).then(function(res) {
      res.name.should.eql('Charlie');
      setTimeout(function() {
        return Person.findById(persons[1].id.toString()).then(function(res) {
          done(new Error('expected an error'));
        }).catch(function(err) {
          should.exist(err);
          done();
        });
      }, (options.ttl + 1) * 1000);
    }).catch(function(err) {
      done(err);
    });
  });

  it('remove one exist document', function(done) {
    return Person.removeById(persons[0].id).then(function() {
      done();
    }).catch(function(err) {
      done(err);
    });
  });

  it('create error with none-couchbase connector', function(done) {
    db = new DataSource('memory');
    Person = db.createModel('person', {id: Number, name: String, age: Number});
    mixin(Person, options);
    return Person.create(persons[1]).then(function(res) {
      done(new Error('expected an error'));
    }).catch(function(err) {
      should.exist(err);
      done();
    });
  });
});
<|endoftext|>


<commit_before>const { app, BrowserWindow } = require('electron');
const path = require('path');
const url = require('url');

let mainWin = null;

const getMainURL = () => {
  // For development
  if (process.env.NODE_ENV === 'development') {
    return url.format({
      host: '127.0.0.1:9555',
      protocol: 'http',
      slashes: true
    });
  }

  // For production
  return url.format({
    pathname: path.join(__dirname, './index.html'),
    protocol: 'file:',
    slashes: true
  });
}

const createMainWin = () => {
  mainWin = new BrowserWindow({width: 800, height: 600});
  console.log(getMainURL())
  mainWin.loadURL(getMainURL());

  // Open the DevTools.
  mainWin.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWin.on('closed', () => {
    mainWin = null;
  });
}

// When electron intializes and is ready to open window
app.on('ready', () => {
  createMainWin();
});

// Runs when all windows are closed
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWin === null) {
    createMainWin();
  }
});
<commit_msg>Follow eslint rules<commit_after>const { app, BrowserWindow } = require('electron');
const path = require('path');
const url = require('url');

let mainWin = null;

const getMainURL = () => {
  // For development
  if (process.env.NODE_ENV === 'development') {
    return url.format({
      host: '127.0.0.1:9555',
      protocol: 'http',
      slashes: true
    });
  }

  // For production
  return url.format({
    pathname: path.join(__dirname, './index.html'),
    protocol: 'file:',
    slashes: true
  });
};

const createMainWin = () => {
  mainWin = new BrowserWindow({width: 800, height: 600});
  mainWin.loadURL(getMainURL());

  // Open the DevTools.
  mainWin.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWin.on('closed', () => {
    mainWin = null;
  });
};

// When electron intializes and is ready to open window
app.on('ready', () => {
  createMainWin();
});

// Runs when all windows are closed
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWin === null) {
    createMainWin();
  }
});
<|endoftext|>


<commit_before>var Dissolve = require("../index");

describe("loop", function() {
  it("should emit data 3 times then end", function(done) {
    var reader = Dissolve().loop(function(end) {
      this.uint8("x").tap(function() {
        if (this.vars.x === 0) {
          return end(true);
        } else {
          this.emit("data", this.vars.x);
        }
      });
    }).tap(function() {
      this.emit("done");
    });

    var counter = 0;

    reader.on("data", function(e) {
      counter++;
    });

    reader.on("done", function() {
      if (counter !== 3) {
        return done(Error("invalid counter value"));
      } else {
        return done();
      }
    });

    reader.write(Buffer([0x01, 0x01, 0x01, 0x00, 0x02]));
  });
});
<commit_msg>added a test for named loops<commit_after>var Dissolve = require("../index");

describe("loop", function() {
  it("should emit data 3 times then end", function(done) {
    var reader = Dissolve().loop(function(end) {
      this.uint8("x").tap(function() {
        if (this.vars.x === 0) {
          return end(true);
        } else {
          this.emit("data", this.vars.x);
        }
      });
    }).tap(function() {
      this.emit("done");
    });

    var counter = 0;

    reader.on("data", function(e) {
      counter++;
    });

    reader.on("done", function() {
      if (counter !== 3) {
        return done(Error("invalid counter value"));
      } else {
        return done();
      }
    });

    reader.write(Buffer([0x01, 0x01, 0x01, 0x00, 0x02]));
  });

  it("should populate an array correctly", function(done) {
    var reader = Dissolve().loop("things", function(end) {
      this.uint8("x").tap(function() {
        if (this.vars.x === 0) {
          return end(true);
        }
      });
    }).tap(function() {
      this.emit("data", this.vars);
    });

    reader.on("data", function(e) {
      if (typeof e !== "object" || e === null) {
        return done(Error("invalid payload for data event"));
      }

      if (!Array.isArray(e.things)) {
        return done(Error("array property not set or not correct type"));
      }

      if (e.things.length !== 3) {
        return done(Error("invalid number of entries"));
      }

      return done();
    });

    reader.write(Buffer([0x01, 0x01, 0x01, 0x00]));
  });
});
<|endoftext|>


<commit_before>
var _     = require('lodash');
var chalk = require('chalk');

module.exports = function(options){

  var defaultOptions = require('./defaults.js')();
  options            = _.defaultsDeep(options, defaultOptions);
  var baseBuildName  = chalk.bgWhite( chalk.black('[ ' + 'Base Build ' + chalk.red('Angular') + ' ]') ) + ' ';

  /*
    ==========================
    Read gulp files
    ==========================
  */
  for(key in options.modules){
    var value    = options.modules[key];
    var category = chalk.green(' external ');
    var useMode  = '';

    !options.modulesData[key] && (options.modulesData[key] = {});
    !options.modulesData[key].notStart ? (useMode = 'required') : (useMode = 'using');

    options.modulesData[key].requireName = value;

    if(defaultOptions.modulesData[key] && value === defaultOptions.modulesData[key].defaultValue && key != 'gulp'){
      category = chalk.cyan(' built-in ');
      !options.modulesData[key].notStart && require(value)(options);
    } else if(key === 'gulp') {
      options.modulesData[key].isDefault = false;
      !options.modulesData[key].notStart && require(value);
    } else {
      options.modulesData[key].isDefault = false;
      options.modulesData[key].requireName = process.cwd() + "/" + value;
      !options.modulesData[key].notStart && require( options.modulesData[key].requireName );
    }

    console.log( baseBuildName + useMode + category + chalk.magenta(value) + ' module');

  }
}<commit_msg>Refactoring no main.js<commit_after>
var _     = require('lodash');
var chalk = require('chalk');

module.exports = function(options){

  var defaultOptions = require('./defaults.js')();
  options            = _.defaultsDeep(options, defaultOptions);
  var baseBuildName  = chalk.bgWhite( chalk.black('[ ' + 'Base Build ' + chalk.underline.red('Angular') + ' ]') ) + ' ';

  /*
    ==========================
    Read gulp files
    ==========================
  */
  for(key in options.modules){
    var value      = options.modules[key];
    var category   = chalk.green(' external ');
    var useMode    = '';

    !options.modulesData[key] && (options.modulesData[key] = {});
    var moduleData = options.modulesData[key];

    !moduleData.notStart ? (useMode = 'required') : (useMode = 'using');

    moduleData.requireName = value;

    if(defaultOptions.modulesData[key] && value === defaultOptions.modulesData[key].defaultValue && !moduleData.isExternal){
      category = chalk.cyan(' built-in ');
      !moduleData.notStart && require(value)(options);
    } else if(key === 'gulp') {
      moduleData.isDefault = false;
      !moduleData.notStart && require(value);
    } else {
      moduleData.isDefault = false;
      moduleData.requireName = process.cwd() + "/" + value;
      !moduleData.notStart && require( moduleData.requireName );
    }

    console.log( baseBuildName + useMode + category + chalk.magenta(value) + ' module');

  }
}<|endoftext|>


<commit_before>/**
 * pubfood
 */

/* global yieldbot googletag*/
/*eslint no-unused-vars: 0*/

'use strict';

window.googletag = window.googletag || {};
googletag.cmd = googletag.cmd || [];
var ybotq = ybotq || [];

var pubfoodContrib = {
  slots: [
    {
      name: '/2476204/multi-size',
      sizes: [
        [300, 250],
        [300, 600]
      ],
      elementId: 'div-multi-size',
      bidProviders: [
        'yieldbot',
        'walkathon'
      ]
    },
    {
      name: '/2476204/leaderboard',
      sizes: [
        [728, 90]
      ],
      elementId: 'div-leaderboard',
      bidProviders: [
        'yieldbot',
        'walkathon',
        'carsales'
      ]
    }
  ],
  auctionProvider: {
    name: 'Google',
    libUri: '//www.googletagservices.com/tag/js/gpt.js',
    init: function(targeting, done) {
/* array of targeting objects
      {
        type: 'page',
        targeting: {
          yb_ad: 'y'
        }
      },
      {
        type: 'slot',
        name: '/2476204/multi-size',
        id: 'somerandomid',
        elementId: 'div-multi-size',
        sizes: [
          [300, 250],
          [300, 600]
        ],
        // a flattened list from all bidders
        targeting: {
          foo: ['bar', 'foo.bar'], // from bidder 1 & 2
          foooo: ['bar'], // from bidder 2
          provider1_bid: '400',
          provider2_bid: '200'
        },
        bids: [
          {
            provider: 'provider1',
            id: '1212121',
            targeting: {
              bid: '400',
              foo: 'bar'
            }
          }
        ]
      }
*/
      googletag.cmd.push(function() {
        var i;
        for (i = 0; i < targeting.length; i++) {
          var slot = targeting[i];

          var gptslot = googletag.defineSlot(slot.name, slot.sizes, slot.elementId)
              .addService(googletag.pubads());

          for (var p in slot.targeting) {
            gptslot.setTargeting(p, slot.targeting[p]);
          }
        }
      });
      googletag.cmd.push(function() {
        googletag.pubads().enableSingleRequest();
        googletag.enableServices();
        done();
      });

      googletag.cmd.push(function() { googletag.display('div-leaderboard'); });
      googletag.cmd.push(function() { googletag.display('div-multi-size'); });

    },
    refresh: function(targeting, done) {

      googletag.cmd.push(function() {
        googletag.refresh();
        done();
      });
    }
  },
  bidProviders: [
    {
      name: 'yieldbot',
      slotParams: {
        '/2476204/multi-size': 'medrec',
        '/2476204/leaderboard': 'leaderboard'
      },
      libUri: '//cdn.yldbt.com/js/yieldbot.intent.js',
      init: function(slots, pushBid, done) {

        /* Slot object
        {
          name: '/2476204/multi-size',
          sizes: [
            [300, 250],
            [300, 600]
          ],
          elementId: 'div-multi-size',
          params: {
            option1: 'use this for locality to the slot definition'
          }
        }
        */
        var slotMap = {};
        var slotParams = this.slotParams;
        ybotq.push(function() {
          yieldbot.psn('1234');

          for (var k = 0; k < slots.length; k++) {
            var slot = slots[k];
            var ybslot = slotParams[slot.name];

            yieldbot.defineSlot(ybslot, {
              sizes: slot.sizes
            });
            slotMap[ybslot] = slot.name;
          }
          yieldbot.enableAsync();
          yieldbot.go();

        });

        ybotq.push(function() {
          var i;

          var pageSlots = yieldbot.getPageCriteria().split(','); //sidebar:300x250:800,test_slot:300x250:200
          for (i = 0; i < pageSlots.length; i++) {

            var slotInfo = pageSlots[i].split(':'); //sidebar:300x250:800
            var slot = slotInfo[0];
            var size = slotInfo[1];
            var bid = 0;
            if (slotInfo.length && slotInfo[2]) {
              bid = parseFloat(slotInfo[2], 10);
            }

            var sizes = size.split('x');
            sizes[0] = parseInt(sizes[0], 10);
            sizes[1] = parseInt(sizes[1], 10);

            // submit my bid...
            var bidObject = {
              slot: slotMap[slot] || 'undefined_slot',
              value: bid,
              sizes: sizes,
              targeting: {
                ybot_ad: 'y',
                ybot_slot: slot
              },
              label: 'price'
            };
            pushBid(bidObject);
          }

          done();
        });
      },
      refresh: function(slots, pushBid, done) {
        done();
      }
    },
    {
      name: 'carsales',
      libUri: '../test/fixture/lib.js',
      init: function(slots, pushBid, done) {
        done();
      },
      refresh: function(slots, pushBid, done) {
        done();
      }
    },
    {
      name: 'walkathon',
      libUri: '../test/fixture/lib.js',
      init: function(slots, pushBid, done) {
        done();
      },
      refresh: function(slots, pushBid, done) {
        done();
      }
    }
  ]
};
<commit_msg>integration test refresh from googletag.PubAdsService.<commit_after>/**
 * pubfood
 */

/* global yieldbot googletag*/
/*eslint no-unused-vars: 0*/

'use strict';

window.googletag = window.googletag || {};
googletag.cmd = googletag.cmd || [];
var ybotq = ybotq || [];

var pubfoodContrib = {
  slots: [
    {
      name: '/2476204/multi-size',
      sizes: [
        [300, 250],
        [300, 600]
      ],
      elementId: 'div-multi-size',
      bidProviders: [
        'yieldbot',
        'walkathon'
      ]
    },
    {
      name: '/2476204/leaderboard',
      sizes: [
        [728, 90]
      ],
      elementId: 'div-leaderboard',
      bidProviders: [
        'yieldbot',
        'walkathon',
        'carsales'
      ]
    }
  ],
  auctionProvider: {
    name: 'Google',
    libUri: '//www.googletagservices.com/tag/js/gpt.js',
    init: function(targeting, done) {
/* array of targeting objects
      {
        type: 'page',
        targeting: {
          yb_ad: 'y'
        }
      },
      {
        type: 'slot',
        name: '/2476204/multi-size',
        id: 'somerandomid',
        elementId: 'div-multi-size',
        sizes: [
          [300, 250],
          [300, 600]
        ],
        // a flattened list from all bidders
        targeting: {
          foo: ['bar', 'foo.bar'], // from bidder 1 & 2
          foooo: ['bar'], // from bidder 2
          provider1_bid: '400',
          provider2_bid: '200'
        },
        bids: [
          {
            provider: 'provider1',
            id: '1212121',
            targeting: {
              bid: '400',
              foo: 'bar'
            }
          }
        ]
      }
*/
      googletag.cmd.push(function() {
        var i;
        for (i = 0; i < targeting.length; i++) {
          var slot = targeting[i];

          var gptslot = googletag.defineSlot(slot.name, slot.sizes, slot.elementId)
              .addService(googletag.pubads());

          for (var p in slot.targeting) {
            gptslot.setTargeting(p, slot.targeting[p]);
          }
        }
      });
      googletag.cmd.push(function() {
        googletag.pubads().enableSingleRequest();
        googletag.enableServices();
        done();
      });

      googletag.cmd.push(function() { googletag.display('div-leaderboard'); });
      googletag.cmd.push(function() { googletag.display('div-multi-size'); });

    },
    refresh: function(targeting, done) {
      if (googletag) {
        googletag.pubads().refresh();
        done();
      }
    }
  },
  bidProviders: [
    {
      name: 'yieldbot',
      slotParams: {
        '/2476204/multi-size': 'medrec',
        '/2476204/leaderboard': 'leaderboard'
      },
      libUri: '//cdn.yldbt.com/js/yieldbot.intent.js',
      init: function(slots, pushBid, done) {

        /* Slot object
        {
          name: '/2476204/multi-size',
          sizes: [
            [300, 250],
            [300, 600]
          ],
          elementId: 'div-multi-size',
          params: {
            option1: 'use this for locality to the slot definition'
          }
        }
        */
        var slotMap = {};
        var slotParams = this.slotParams;
        ybotq.push(function() {
          yieldbot.psn('1234');

          for (var k = 0; k < slots.length; k++) {
            var slot = slots[k];
            var ybslot = slotParams[slot.name];

            yieldbot.defineSlot(ybslot, {
              sizes: slot.sizes
            });
            slotMap[ybslot] = slot.name;
          }
          yieldbot.enableAsync();
          yieldbot.go();

        });

        ybotq.push(function() {
          var i;

          var pageSlots = yieldbot.getPageCriteria().split(','); //sidebar:300x250:800,test_slot:300x250:200
          for (i = 0; i < pageSlots.length; i++) {

            var slotInfo = pageSlots[i].split(':'); //sidebar:300x250:800
            var slot = slotInfo[0];
            var size = slotInfo[1];
            var bid = 0;
            if (slotInfo.length && slotInfo[2]) {
              bid = parseFloat(slotInfo[2], 10);
            }

            var sizes = size.split('x');
            sizes[0] = parseInt(sizes[0], 10);
            sizes[1] = parseInt(sizes[1], 10);

            // submit my bid...
            var bidObject = {
              slot: slotMap[slot] || 'undefined_slot',
              value: bid,
              sizes: sizes,
              targeting: {
                ybot_ad: 'y',
                ybot_slot: slot
              },
              label: 'price'
            };
            pushBid(bidObject);
          }

          done();
        });
      },
      refresh: function(slots, pushBid, done) {
        done();
      }
    },
    {
      name: 'carsales',
      libUri: '../test/fixture/lib.js',
      init: function(slots, pushBid, done) {
        done();
      },
      refresh: function(slots, pushBid, done) {
        done();
      }
    },
    {
      name: 'walkathon',
      libUri: '../test/fixture/lib.js',
      init: function(slots, pushBid, done) {
        done();
      },
      refresh: function(slots, pushBid, done) {
        done();
      }
    }
  ]
};
<|endoftext|>


<commit_before>(function () {
  "use strict";

  var lih = require('../builder/list_item_hunter');
  var of = require('../builder/object_factory');
  var extend = require('util')._extend;

  // fake pattern creators
  function createFakeListPattern(customProps) {
    var inputs = {
      abspath: '/home/fakeuser/pl/source/_patterns/01-molecules/01-lists/00-list.mustache',
      subdir: '01-molecules\\01-lists',
      filename: '00-list.mustache',
      data: {}
    };
    var pattern = new of.oPattern(inputs.abspath, inputs.subdir, inputs.filename, inputs.data);

    return extend(pattern, customProps);
  }

  function createFakePatternLab(customProps) {
    var pl = {
      "listitems": {
        "1": [
          { "title": "Foo" }
        ],
        "2": [
          { "title": "Foo" },
          { "title": "Bar" }
        ]
      },
      "data": {
        "link": {},
        "partials": []
      },
      "config": {"debug": false}
    };

    return extend(pl, customProps);
  }

  exports['list_item_hunter'] = {
    'process_list_item_partials finds and outputs basic repeating blocks': function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.two}}{{ title }}{{/listItems.two}}",
        "extendedTemplate": "{{#listItems.two}}{{ title }}{{/listItems.two}}",
        "key": "test-patternName"
      });
      var patternlab = createFakePatternLab();
      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "FooBar" );

      test.done();
    },

    'process_list_item_partials listitems with lowercase name' : function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listitems.two}}{{ title }}{{/listitems.two}}",
        "extendedTemplate" : "{{#listitems.two}}{{ title }}{{/listitems.two}}",
        "key": "test-patternName"
      });
      var patternlab = createFakePatternLab();
      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "FooBar" );

      test.done();
    },

    'process_list_item_partials finds partials and outputs repeated renders': function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.two}}{{ title }}{{/listItems.two}}",
        "extendedTemplate": "{{#listItems.two}}{{> test-simple }}{{/listItems.two}}",
        "key": "test-patternName"
      });

      var patternlab = createFakePatternLab({
        "patterns": [
          {
            "template": "{{ title }}",
            "extendedTemplate" : "{{ title }}",
            "key": "test-simple",
            "jsonFileData" : {}
          }
        ]
      });

      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "FooBar" );

      test.done();
    },

    'process_list_item_partials finds verbose partials and outputs repeated renders' : function(test){
      var pattern1 = createFakeListPattern({
        "template": "{{#listItems.one}}{{> 00-test/00-foo }}{{/listItems.one}}",
        "extendedTemplate" : "{{#listItems.one}}{{> 00-test/00-foo }}{{/listItems.one}}",
        "key": "test-patternName1"
      });

      var pattern2 = createFakeListPattern({
        "template": "{{#listItems.two}}{{> 00-test/01-bar.mustache }}{{/listItems.two}}",
        "extendedTemplate" : "{{#listItems.two}}{{> 00-test/01-bar.mustache }}{{/listItems.two}}",
        "key": "test-patternName2"
      });

      var patternlab = createFakePatternLab({
        "patterns": [
          of.oPattern.create('/home/fakeuser/pl/source/_patterns/00-atoms/00-test/00-foo.mustache', "00-atoms/00-test", "00-foo.mustache", null, {
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}"
          }),
          of.oPattern.create('/home/fakeuser/pl/source/_patterns/00-atoms/00-test/00-bar.mustache', "00-atoms/00-test", "00-bar.mustache", null, {
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}"
          })
        ]
      });

      var list_item_hunter = new lih();

      debugger;

      //act
      list_item_hunter.process_list_item_partials(pattern1, patternlab);
      list_item_hunter.process_list_item_partials(pattern2, patternlab);

      //assert
      test.equals(pattern1.extendedTemplate, "Foo" );
      test.equals(pattern2.extendedTemplate, "FooBar" );

      test.done();
    },

    'process_list_item_partials overwrites listItem property if that property is in local .listitem.json': function(test) {
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.two}}{{ title }}{{/listItems.two}}",
        "extendedTemplate": "{{#listItems.two}}{{> test-simple }}{{/listItems.two}}",
        "key": "test-patternName",
        "jsonFileData": {},
        "listitems": {
          "2": [
            { "title": "One" },
            { "title": "Two" }
          ]
        }
      });
      var patternlab = createFakePatternLab({
        "patterns": [
          createFakeListPattern({
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}",
            "key": "test-simple",
            "jsonFileData": {}
          })
        ]
      });
      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "OneTwo" );

      test.done();
    },

    'process_list_item_partials keeps listItem property if that property is not in local .listitem.json' : function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.one}}{{ title }}{{/listItems.one}}",
        "extendedTemplate": "{{#listItems.one}}{{> test-simple }}{{/listItems.one}}",
        "key": "test-patternName",
        "jsonFileData": {},
        "listitems": {
          "2": [
            { "title": "One" },
            { "title": "Two" }
          ]
        }
      });
      var patternlab = createFakePatternLab({
        "patterns": [
          createFakeListPattern({
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}",
            "key": "test-simple",
            "jsonFileData" : {}
          })
        ]
      });
      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "Foo" );

      test.done();
    },

    'process_list_item_partials uses local listItem property if that property is not set globally' : function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.one}}{{ title }}{{/listItems.one}}",
        "extendedTemplate": "{{#listItems.one}}{{> test-simple }}{{/listItems.one}}",
        "key": "test-patternName",
        "jsonFileData": {},
        "listitems": {
          "1": [
            { "title": "One" }
          ],
          "2": [
            { "title": "One" },
            { "title": "Two" }
          ]
        }
      });

      var patternlab = createFakePatternLab({
        "patterns": [
          createFakeListPattern({
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}",
            "key": "test-simple",
            "jsonFileData": {}
          })
        ]
      });
      delete patternlab.listitems["1"]; // remove the "1" list

      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(typeof patternlab.listitems["1"], "undefined");
      test.equals(currentPattern.extendedTemplate, "One" );

      test.done();
    }

  };

})();
<commit_msg>Fix (?) partial name; unit test now passes<commit_after>(function () {
  "use strict";

  var lih = require('../builder/list_item_hunter');
  var of = require('../builder/object_factory');
  var extend = require('util')._extend;

  // fake pattern creators
  function createFakeListPattern(customProps) {
    var inputs = {
      abspath: '/home/fakeuser/pl/source/_patterns/01-molecules/01-lists/00-list.mustache',
      subdir: '01-molecules\\01-lists',
      filename: '00-list.mustache',
      data: {}
    };
    var pattern = new of.oPattern(inputs.abspath, inputs.subdir, inputs.filename, inputs.data);

    return extend(pattern, customProps);
  }

  function createFakePatternLab(customProps) {
    var pl = {
      "listitems": {
        "1": [
          { "title": "Foo" }
        ],
        "2": [
          { "title": "Foo" },
          { "title": "Bar" }
        ]
      },
      "data": {
        "link": {},
        "partials": []
      },
      "config": {"debug": false}
    };

    return extend(pl, customProps);
  }

  exports['list_item_hunter'] = {
    'process_list_item_partials finds and outputs basic repeating blocks': function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.two}}{{ title }}{{/listItems.two}}",
        "extendedTemplate": "{{#listItems.two}}{{ title }}{{/listItems.two}}",
        "key": "test-patternName"
      });
      var patternlab = createFakePatternLab();
      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "FooBar" );

      test.done();
    },

    'process_list_item_partials listitems with lowercase name' : function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listitems.two}}{{ title }}{{/listitems.two}}",
        "extendedTemplate" : "{{#listitems.two}}{{ title }}{{/listitems.two}}",
        "key": "test-patternName"
      });
      var patternlab = createFakePatternLab();
      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "FooBar" );

      test.done();
    },

    'process_list_item_partials finds partials and outputs repeated renders': function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.two}}{{ title }}{{/listItems.two}}",
        "extendedTemplate": "{{#listItems.two}}{{> test-simple }}{{/listItems.two}}",
        "key": "test-patternName"
      });

      var patternlab = createFakePatternLab({
        "patterns": [
          {
            "template": "{{ title }}",
            "extendedTemplate" : "{{ title }}",
            "key": "test-simple",
            "jsonFileData" : {}
          }
        ]
      });

      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "FooBar" );

      test.done();
    },

    'process_list_item_partials finds verbose partials and outputs repeated renders' : function(test){
      var pattern1 = createFakeListPattern({
        "template": "{{#listItems.one}}{{> atoms-foo }}{{/listItems.one}}",
        "extendedTemplate" : "{{#listItems.one}}{{> atoms-foo }}{{/listItems.one}}",
        "key": "test-patternName1"
      });

      var pattern2 = createFakeListPattern({
        "template": "{{#listItems.two}}{{> atoms-bar }}{{/listItems.two}}",
        "extendedTemplate" : "{{#listItems.two}}{{> atoms-bar }}{{/listItems.two}}",
        "key": "test-patternName2"
      });

      var patternlab = createFakePatternLab({
        "patterns": [
          of.oPattern.create('/home/fakeuser/pl/source/_patterns/00-atoms/00-test/00-foo.mustache', "00-atoms/00-test", "00-foo.mustache", null, {
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}"
          }),
          of.oPattern.create('/home/fakeuser/pl/source/_patterns/00-atoms/00-test/00-bar.mustache', "00-atoms/00-test", "00-bar.mustache", null, {
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}"
          })
        ]
      });

      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(pattern1, patternlab);
      list_item_hunter.process_list_item_partials(pattern2, patternlab);

      //assert
      test.equals(pattern1.extendedTemplate, "Foo" );
      test.equals(pattern2.extendedTemplate, "FooBar" );

      test.done();
    },

    'process_list_item_partials overwrites listItem property if that property is in local .listitem.json': function(test) {
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.two}}{{ title }}{{/listItems.two}}",
        "extendedTemplate": "{{#listItems.two}}{{> test-simple }}{{/listItems.two}}",
        "key": "test-patternName",
        "jsonFileData": {},
        "listitems": {
          "2": [
            { "title": "One" },
            { "title": "Two" }
          ]
        }
      });
      var patternlab = createFakePatternLab({
        "patterns": [
          createFakeListPattern({
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}",
            "key": "test-simple",
            "jsonFileData": {}
          })
        ]
      });
      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "OneTwo" );

      test.done();
    },

    'process_list_item_partials keeps listItem property if that property is not in local .listitem.json' : function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.one}}{{ title }}{{/listItems.one}}",
        "extendedTemplate": "{{#listItems.one}}{{> test-simple }}{{/listItems.one}}",
        "key": "test-patternName",
        "jsonFileData": {},
        "listitems": {
          "2": [
            { "title": "One" },
            { "title": "Two" }
          ]
        }
      });
      var patternlab = createFakePatternLab({
        "patterns": [
          createFakeListPattern({
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}",
            "key": "test-simple",
            "jsonFileData" : {}
          })
        ]
      });
      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(currentPattern.extendedTemplate, "Foo" );

      test.done();
    },

    'process_list_item_partials uses local listItem property if that property is not set globally' : function(test){
      //arrange
      //setup current pattern from what we would have during execution
      var currentPattern = createFakeListPattern({
        "template": "{{#listItems.one}}{{ title }}{{/listItems.one}}",
        "extendedTemplate": "{{#listItems.one}}{{> test-simple }}{{/listItems.one}}",
        "key": "test-patternName",
        "jsonFileData": {},
        "listitems": {
          "1": [
            { "title": "One" }
          ],
          "2": [
            { "title": "One" },
            { "title": "Two" }
          ]
        }
      });

      var patternlab = createFakePatternLab({
        "patterns": [
          createFakeListPattern({
            "template": "{{ title }}",
            "extendedTemplate": "{{ title }}",
            "key": "test-simple",
            "jsonFileData": {}
          })
        ]
      });
      delete patternlab.listitems["1"]; // remove the "1" list

      var list_item_hunter = new lih();

      //act
      list_item_hunter.process_list_item_partials(currentPattern, patternlab);

      //assert
      test.equals(typeof patternlab.listitems["1"], "undefined");
      test.equals(currentPattern.extendedTemplate, "One" );

      test.done();
    }

  };

})();
<|endoftext|>


<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';

describe('Service Inspector', function() {
  var charmData, conn, container, db, env, ecs, models, service, utils, view, Y;

  before(function(done) {
    Y = YUI(GlobalConfig).use([
      'environment-change-set',
      'charmstore-api',
      'juju-tests-utils',
      'juju-views',
      'node-event-simulate',
      'service-inspector'
    ], function(Y) {
      models = Y.namespace('juju.models');
      utils = Y.namespace('juju-tests.utils');
      charmData = utils.loadFixture(
          'data/mediawiki-api-response.json', true);
      done();
    });
  });

  beforeEach(function() {
    container = utils.makeContainer(this, 'container');
    db = new models.Database();
    conn = new utils.SocketStub();
    db = new models.Database();
    ecs = new Y.juju.EnvironmentChangeSet();
    env = new Y.juju.environments.GoEnvironment({conn: conn, ecs: ecs});
    env.connect();
  });

  afterEach(function(done) {
    db.destroy();
    env.after('destroy', function() { done(); });
    env.destroy();
  });

  var setUpInspector = function(service) {
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);

    if (!service) {
      service = db.services.add({
        id: charm.get('package_name'),
        charm: charm.get('id')
      });
    }

    var fakeStore = new Y.juju.charmstore.APIv4({});
    fakeStore.getIconPath = function(id) {
      return '/icon/' + id;
    };

    view = new Y.juju.views.environment({
      container: container,
      db: db,
      env: env,
      charmstore: fakeStore
    });

    view.render();

    container.append(
        '

');

    var inspector = new Y.juju.views.ServiceInspector({
      db: db,
      model: service,
      env: env,
      environment: view,
      charmModel: charm,
      topo: view.topo,
      charmstore: fakeStore
    });
    return inspector;
  };

  it('can render charm details', function() {
    var inspector = setUpInspector();
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    this._cleanups.push(stubShow.reset);
    inspector.render();
    assert.equal(stubShow.lastArguments()[0], 'overview');

    inspector.set('showCharm', true);
    inspector.render();
    assert.equal(stubShow.lastArguments()[0], 'charmDetails');
  });

  it('can re-render charm details', function() {
    var inspector = setUpInspector();
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    this._cleanups.push(stubShow.reset);
    var stubDetailsRender = utils.makeStubMethod(
        inspector.views.charmDetails, 'render');
    this._cleanups.push(stubDetailsRender.reset);
    inspector.set('showCharm', true);
    // The first call to render uses showViewlet
    inspector.render();
    // Call count is 3 because 'overview' and 'inspectorHeader' are also
    // displayed.
    assert.equal(stubShow.callCount(), 3);
    assert.equal(stubDetailsRender.callCount(), 0);
    assert.equal(stubShow.lastArguments()[0], 'charmDetails');

    inspector.views.charmDetails.set('rendered', true);
    inspector.render();
    assert.equal(stubShow.callCount(), 3);
    assert.equal(stubDetailsRender.callCount(), 1);
  });

  it('handles rendering details when they\'re "destroyed"', function() {
    var inspector = setUpInspector();
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    this._cleanups.push(stubShow.reset);
    inspector.set('showCharm', true);
    // The first call to render uses showViewlet
    inspector.render();
    // Call count is 3 because 'overview' and 'inspectorHeader' are also
    // displayed.
    assert.equal(stubShow.callCount(), 3);
    assert.equal(stubShow.lastArguments()[0], 'charmDetails');

    inspector.views.charmDetails.destroy();
    inspector.render();
    assert.equal(stubShow.callCount(), 4);
    assert.equal(stubShow.lastArguments()[0], 'charmDetails');
  });

  it('handles re-rendering the overview', function() {
    var inspector = setUpInspector();
    inspector.get('container').append(
      '

');
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    this._cleanups.push(stubShow.reset);
    var stubOverviewRender = utils.makeStubMethod(
        inspector.views.overview, 'render');
    this._cleanups.push(stubOverviewRender.reset);
    var stubHeaderRender = utils.makeStubMethod(
        inspector.views.inspectorHeader, 'render');
    this._cleanups.push(stubHeaderRender.reset);

    inspector.renderUI();
    // Two calls two showViewlet, one for inspectorHeader, one for overview.
    assert.equal(stubShow.callCount(), 2);
    assert.equal(stubOverviewRender.callCount(), 0);
    assert.equal(stubHeaderRender.callCount(), 0);

    inspector.renderUI();
    assert.equal(stubShow.callCount(), 2);
    assert.equal(stubOverviewRender.callCount(), 1);
    assert.equal(stubHeaderRender.callCount(), 1);
  });

  it('can render unit details', function() {
    var inspector = setUpInspector();
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    inspector.render();
    assert.equal(stubShow.lastArguments()[0], 'overview');
    inspector.set('activeUnit', 0);
    inspector.render();
    assert.equal(stubShow.lastArguments()[0], 'unitDetails');
  });

  it('fires the changeState event when the charm uri is clicked', function() {
    var inspector = setUpInspector();
    inspector.render();
    var fireStub = utils.makeStubMethod(inspector, 'fire');
    this._cleanups.push(fireStub.reset);
    inspector.get('container').one('.charm-url').simulate('click');
    assert.equal(fireStub.calledOnce(), true);
    var fireArgs = fireStub.lastArguments();
    assert.equal(fireArgs[0], 'changeState');
    assert.deepEqual(
        fireArgs[1],
        { sectionA: { metadata: { unit: null, charm: true }}});
  });

  it('can dismiss notifications', function() {
    // Create a ghost service with a fake charm.
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);
    service = db.services.ghostService(charm);
    var stubDismiss = utils.makeStubMethod(
        Y.juju.viewlets.InspectorHeader.prototype, '_dismissMessage');
    this._cleanups.push(stubDismiss.reset);
    var inspector = setUpInspector(service);
    inspector.render();
    inspector.get('container').one('span[dismiss]').simulate('click');
    assert.equal(stubDismiss.callCount(), 1);
  });

  it('actually dismisses the "added service" message', function() {
    // Create a ghost service with a fake charm.
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);
    service = db.services.ghostService(charm);
    var inspector = setUpInspector(service);
    inspector.render();
    var message = container.one('.ghost-message');
    // The message is initially displayed.
    assert.strictEqual(message.hasClass('hidden'), false);
    // Click the "Dismiss" button.
    inspector.get('container').one('span[dismiss]').simulate('click');
    // The message is now hidden.
    assert.strictEqual(message.hasClass('hidden'), true);
    // The model has been annotated so that the message will not be displayed
    // in the future.
    assert.strictEqual(service.get('hideHelp'), true);
  });

  it('does not show the "added service" message if dismissed', function() {
    // Create a ghost service with a fake charm.
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);
    service = db.services.ghostService(charm);
    service.set('hideHelp', true);
    var inspector = setUpInspector(service);
    inspector.render();
    var message = container.one('.ghost-message');
    // The message is not displayed.
    assert.isNull(message);
  });

  it('shows the footer for the overview', function() {
    var inspector = setUpInspector();
    inspector.render();
    container.one('.tab').simulate('click');
    assert.equal(container.one('.viewlet-manager-footer').hasClass('hidden'),
        false);
  });

  it('does not show the footer for non-overview tabs', function() {
    var inspector = setUpInspector();
    inspector.render();
    container.one('.viewlet-manager-navigation li:last-child .tab').simulate(
        'click');
    assert.equal(container.one('.viewlet-manager-footer').hasClass('hidden'),
        true);
  });

  it('hides the change version button for pending', function() {
    // Create a ghost service with a fake charm.
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);
    service = db.services.ghostService(charm);
    var inspector = setUpInspector(service);
    inspector.render();
    assert.equal(container.one('.change-version-trigger').hasClass('hidden'),
        true);
    // Update the pending status and check that the button shows again.
    service.set('pending', false);
    inspector.render();
    assert.equal(container.one('.change-version-trigger').hasClass('hidden'),
        false);
  });
});
<commit_msg>Fixed lint.<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';

describe('Service Inspector', function() {
  var charmData, conn, container, db, env, ecs, models, service, utils, view, Y;

  before(function(done) {
    Y = YUI(GlobalConfig).use([
      'environment-change-set',
      'charmstore-api',
      'juju-tests-utils',
      'juju-views',
      'node-event-simulate',
      'service-inspector'
    ], function(Y) {
      models = Y.namespace('juju.models');
      utils = Y.namespace('juju-tests.utils');
      charmData = utils.loadFixture(
          'data/mediawiki-api-response.json', true);
      done();
    });
  });

  beforeEach(function() {
    container = utils.makeContainer(this, 'container');
    db = new models.Database();
    conn = new utils.SocketStub();
    db = new models.Database();
    ecs = new Y.juju.EnvironmentChangeSet();
    env = new Y.juju.environments.GoEnvironment({conn: conn, ecs: ecs});
    env.connect();
  });

  afterEach(function(done) {
    db.destroy();
    env.after('destroy', function() { done(); });
    env.destroy();
  });

  var setUpInspector = function(service) {
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);

    if (!service) {
      service = db.services.add({
        id: charm.get('package_name'),
        charm: charm.get('id')
      });
    }

    var fakeStore = new Y.juju.charmstore.APIv4({});
    fakeStore.getIconPath = function(id) {
      return '/icon/' + id;
    };

    view = new Y.juju.views.environment({
      container: container,
      db: db,
      env: env,
      charmstore: fakeStore
    });

    view.render();

    container.append(
        '

');

    var inspector = new Y.juju.views.ServiceInspector({
      db: db,
      model: service,
      env: env,
      environment: view,
      charmModel: charm,
      topo: view.topo,
      charmstore: fakeStore
    });
    return inspector;
  };

  it('can render charm details', function() {
    var inspector = setUpInspector();
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    this._cleanups.push(stubShow.reset);
    inspector.render();
    assert.equal(stubShow.lastArguments()[0], 'overview');

    inspector.set('showCharm', true);
    inspector.render();
    assert.equal(stubShow.lastArguments()[0], 'charmDetails');
  });

  it('can re-render charm details', function() {
    var inspector = setUpInspector();
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    this._cleanups.push(stubShow.reset);
    var stubDetailsRender = utils.makeStubMethod(
        inspector.views.charmDetails, 'render');
    this._cleanups.push(stubDetailsRender.reset);
    inspector.set('showCharm', true);
    // The first call to render uses showViewlet
    inspector.render();
    // Call count is 3 because 'overview' and 'inspectorHeader' are also
    // displayed.
    assert.equal(stubShow.callCount(), 3);
    assert.equal(stubDetailsRender.callCount(), 0);
    assert.equal(stubShow.lastArguments()[0], 'charmDetails');

    inspector.views.charmDetails.set('rendered', true);
    inspector.render();
    assert.equal(stubShow.callCount(), 3);
    assert.equal(stubDetailsRender.callCount(), 1);
  });

  it('handles rendering details when they\'re "destroyed"', function() {
    var inspector = setUpInspector();
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    this._cleanups.push(stubShow.reset);
    inspector.set('showCharm', true);
    // The first call to render uses showViewlet
    inspector.render();
    // Call count is 3 because 'overview' and 'inspectorHeader' are also
    // displayed.
    assert.equal(stubShow.callCount(), 3);
    assert.equal(stubShow.lastArguments()[0], 'charmDetails');

    inspector.views.charmDetails.destroy();
    inspector.render();
    assert.equal(stubShow.callCount(), 4);
    assert.equal(stubShow.lastArguments()[0], 'charmDetails');
  });

  it('handles re-rendering the overview', function() {
    var inspector = setUpInspector();
    inspector.get('container').append(
        '

');
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    this._cleanups.push(stubShow.reset);
    var stubOverviewRender = utils.makeStubMethod(
        inspector.views.overview, 'render');
    this._cleanups.push(stubOverviewRender.reset);
    var stubHeaderRender = utils.makeStubMethod(
        inspector.views.inspectorHeader, 'render');
    this._cleanups.push(stubHeaderRender.reset);

    inspector.renderUI();
    // Two calls two showViewlet, one for inspectorHeader, one for overview.
    assert.equal(stubShow.callCount(), 2);
    assert.equal(stubOverviewRender.callCount(), 0);
    assert.equal(stubHeaderRender.callCount(), 0);

    inspector.renderUI();
    assert.equal(stubShow.callCount(), 2);
    assert.equal(stubOverviewRender.callCount(), 1);
    assert.equal(stubHeaderRender.callCount(), 1);
  });

  it('can render unit details', function() {
    var inspector = setUpInspector();
    var stubShow = utils.makeStubMethod(inspector, 'showViewlet');
    inspector.render();
    assert.equal(stubShow.lastArguments()[0], 'overview');
    inspector.set('activeUnit', 0);
    inspector.render();
    assert.equal(stubShow.lastArguments()[0], 'unitDetails');
  });

  it('fires the changeState event when the charm uri is clicked', function() {
    var inspector = setUpInspector();
    inspector.render();
    var fireStub = utils.makeStubMethod(inspector, 'fire');
    this._cleanups.push(fireStub.reset);
    inspector.get('container').one('.charm-url').simulate('click');
    assert.equal(fireStub.calledOnce(), true);
    var fireArgs = fireStub.lastArguments();
    assert.equal(fireArgs[0], 'changeState');
    assert.deepEqual(
        fireArgs[1],
        { sectionA: { metadata: { unit: null, charm: true }}});
  });

  it('can dismiss notifications', function() {
    // Create a ghost service with a fake charm.
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);
    service = db.services.ghostService(charm);
    var stubDismiss = utils.makeStubMethod(
        Y.juju.viewlets.InspectorHeader.prototype, '_dismissMessage');
    this._cleanups.push(stubDismiss.reset);
    var inspector = setUpInspector(service);
    inspector.render();
    inspector.get('container').one('span[dismiss]').simulate('click');
    assert.equal(stubDismiss.callCount(), 1);
  });

  it('actually dismisses the "added service" message', function() {
    // Create a ghost service with a fake charm.
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);
    service = db.services.ghostService(charm);
    var inspector = setUpInspector(service);
    inspector.render();
    var message = container.one('.ghost-message');
    // The message is initially displayed.
    assert.strictEqual(message.hasClass('hidden'), false);
    // Click the "Dismiss" button.
    inspector.get('container').one('span[dismiss]').simulate('click');
    // The message is now hidden.
    assert.strictEqual(message.hasClass('hidden'), true);
    // The model has been annotated so that the message will not be displayed
    // in the future.
    assert.strictEqual(service.get('hideHelp'), true);
  });

  it('does not show the "added service" message if dismissed', function() {
    // Create a ghost service with a fake charm.
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);
    service = db.services.ghostService(charm);
    service.set('hideHelp', true);
    var inspector = setUpInspector(service);
    inspector.render();
    var message = container.one('.ghost-message');
    // The message is not displayed.
    assert.isNull(message);
  });

  it('shows the footer for the overview', function() {
    var inspector = setUpInspector();
    inspector.render();
    container.one('.tab').simulate('click');
    assert.equal(container.one('.viewlet-manager-footer').hasClass('hidden'),
        false);
  });

  it('does not show the footer for non-overview tabs', function() {
    var inspector = setUpInspector();
    inspector.render();
    container.one('.viewlet-manager-navigation li:last-child .tab').simulate(
        'click');
    assert.equal(container.one('.viewlet-manager-footer').hasClass('hidden'),
        true);
  });

  it('hides the change version button for pending', function() {
    // Create a ghost service with a fake charm.
    var charm = new models.Charm(charmData.charm);
    db.charms.add(charm);
    service = db.services.ghostService(charm);
    var inspector = setUpInspector(service);
    inspector.render();
    assert.equal(container.one('.change-version-trigger').hasClass('hidden'),
        true);
    // Update the pending status and check that the button shows again.
    service.set('pending', false);
    inspector.render();
    assert.equal(container.one('.change-version-trigger').hasClass('hidden'),
        false);
  });
});
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";
var MAX_TOKEN_COUNT = 1000;
var useragent = require("../lib/useragent");
var TokenizerModule = require("../tokenizer");

function patch(obj, name, regexp, replacement) {
    eval("obj['" + name + "']=" + obj[name].toString().replace(
        regexp, replacement
    ));
}

if (useragent.isIE && useragent.isIE < 10 && window.top.document.compatMode === "BackCompat")
    useragent.isOldIE = true;

if (typeof document != "undefined" && !document.documentElement.querySelector) {
    useragent.isOldIE = true;
    var qs = function(el, selector) {
        if (selector.charAt(0) == ".") {
            var classNeme = selector.slice(1);
        } else {
            var m = selector.match(/(\w+)=(\w+)/);
            var attr = m && m[1];
            var attrVal = m && m[2];
        }
        for (var i = 0; i < el.all.length; i++) {
            var ch = el.all[i];
            if (classNeme) {
                if (ch.className.indexOf(classNeme) != -1)
                    return ch;
            } else if (attr) {
                if (ch.getAttribute(attr) == attrVal)
                    return ch;
            }
        }
    };
    var sb = require("./searchbox").SearchBox.prototype;
    patch(
        sb, "$initElements",
        /([^\s=]*).querySelector\((".*?")\)/g,
        "qs($1, $2)"
    );
}

var compliantExecNpcg = /()??/.exec("")[1] === undefined;
if (compliantExecNpcg)
    return;
var proto = TokenizerModule.Tokenizer.prototype;
TokenizerModule.Tokenizer_orig = TokenizerModule.Tokenizer;
proto.getLineTokens_orig = proto.getLineTokens;

patch(
    TokenizerModule, "Tokenizer",
    "ruleRegExps.push(adjustedregex);\n",
    function(m) {
        return m + '\
        if (state[i].next && RegExp(adjustedregex).test(""))\n\
            rule._qre = RegExp(adjustedregex, "g");\n\
        ';
    }
);
TokenizerModule.Tokenizer.prototype = proto;
patch(
    proto, "getLineTokens",
    /if \(match\[i \+ 1\] === undefined\)\s*continue;/,
    "if (!match[i + 1]) {\n\
        if (value)continue;\n\
        var qre = state[mapping[i]]._qre;\n\
        if (!qre) continue;\n\
        qre.lastIndex = lastIndex;\n\
        if (!qre.exec(line) || qre.lastIndex != lastIndex)\n\
            continue;\n\
    }"
);

patch(
    require("ace/mode/text").Mode.prototype, "getTokenizer",
    /Tokenizer/,
    "TokenizerModule.Tokenizer"
);

useragent.isOldIE = true;

});
<commit_msg>fix tests<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";
var MAX_TOKEN_COUNT = 1000;
var useragent = require("../lib/useragent");
var TokenizerModule = require("../tokenizer");

function patch(obj, name, regexp, replacement) {
    eval("obj['" + name + "']=" + obj[name].toString().replace(
        regexp, replacement
    ));
}

if (useragent.isIE && useragent.isIE < 10 && window.top.document.compatMode === "BackCompat")
    useragent.isOldIE = true;

if (typeof document != "undefined" && !document.documentElement.querySelector) {
    useragent.isOldIE = true;
    var qs = function(el, selector) {
        if (selector.charAt(0) == ".") {
            var classNeme = selector.slice(1);
        } else {
            var m = selector.match(/(\w+)=(\w+)/);
            var attr = m && m[1];
            var attrVal = m && m[2];
        }
        for (var i = 0; i < el.all.length; i++) {
            var ch = el.all[i];
            if (classNeme) {
                if (ch.className.indexOf(classNeme) != -1)
                    return ch;
            } else if (attr) {
                if (ch.getAttribute(attr) == attrVal)
                    return ch;
            }
        }
    };
    var sb = require("./searchbox").SearchBox.prototype;
    patch(
        sb, "$initElements",
        /([^\s=]*).querySelector\((".*?")\)/g,
        "qs($1, $2)"
    );
}

var compliantExecNpcg = /()??/.exec("")[1] === undefined;
if (compliantExecNpcg)
    return;
var proto = TokenizerModule.Tokenizer.prototype;
TokenizerModule.Tokenizer_orig = TokenizerModule.Tokenizer;
proto.getLineTokens_orig = proto.getLineTokens;

patch(
    TokenizerModule, "Tokenizer",
    "ruleRegExps.push(adjustedregex);\n",
    function(m) {
        return m + '\
        if (state[i].next && RegExp(adjustedregex).test(""))\n\
            rule._qre = RegExp(adjustedregex, "g");\n\
        ';
    }
);
TokenizerModule.Tokenizer.prototype = proto;
patch(
    proto, "getLineTokens",
    /if \(match\[i \+ 1\] === undefined\)\s*continue;/,
    "if (!match[i + 1]) {\n\
        if (value)continue;\n\
        var qre = state[mapping[i]]._qre;\n\
        if (!qre) continue;\n\
        qre.lastIndex = lastIndex;\n\
        if (!qre.exec(line) || qre.lastIndex != lastIndex)\n\
            continue;\n\
    }"
);

patch(
    require("../mode/text").Mode.prototype, "getTokenizer",
    /Tokenizer/,
    "TokenizerModule.Tokenizer"
);

useragent.isOldIE = true;

});
<|endoftext|>