<commit_before>/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2005 - 2009 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.mozilla.js
 *        Gecko specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Volker Mische (vmx a-t gmx dotde)
 *        Bermi Ferrer (wymeditor a-t bermi dotorg)
 *        Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
 *        Jonatan Lundin (jonatan.lundin a-t gmail dotcom)
 */

WYMeditor.WymClassMozilla = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\n";
};

WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {
    var wym = this;

    this._iframe = iframe;
    this._doc = iframe.contentDocument;

    jQuery(this._element).trigger('wymeditor:iframe_loaded');

    //add css rules from options

    var styles = this._doc.styleSheets[0];
    var aCss = eval(this._options.editorStyles);

    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);

    //init html value
    this.html(this._wym._html);

    //init designMode
    this.enableDesignMode();

    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);

    //bind external events
    this._wym.bindEvents();

    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);

    //bind editor keyup events
    jQuery(this._doc).bind("keyup", this.keyup);

    //bind editor click events
    jQuery(this._doc).bind("click", this.click);

    //bind editor focus events (used to reset designmode - Gecko bug)
    jQuery(this._doc).bind("focus", function () {
        // Fix scope
        wym.enableDesignMode.call(wym);
    });

    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);

    //add event listeners to doc elements, e.g. images
    this.listen();
};

/* @name html
 * @description Get/Set the html value
 */
WYMeditor.WymClassMozilla.prototype.html = function(html) {

  if(typeof html === 'string') {

    //disable designMode
    try { this._doc.designMode = "off"; } catch(e) {
      //do nothing
    }

    //replace em by i and strong by bold
    //(designMode issue)
    html = html.replace(/]*)>/gi, "");
    html = html.replace(/<\/em>/gi, "");
    html = html.replace(/]*)>/gi, "");
    html = html.replace(/<\/strong>/gi, "");

    //update the html body
    jQuery(this._doc.body).html(html);

    //re-init designMode
    this.enableDesignMode();
  }
  else return(jQuery(this._doc.body).html());
  return false;
};

WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {

    if(!this.selected()) return(false);

    switch(cmd) {

    case WYMeditor.INDENT: case WYMeditor.OUTDENT:

        var focusNode = this.selected();
        var sel = this._iframe.contentWindow.getSelection();
        var anchorNode = sel.anchorNode;
        if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;

        focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
        anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);

        if(focusNode && focusNode == anchorNode && focusNode.tagName.toLowerCase() == WYMeditor.LI) {

            var ancestor = focusNode.parentNode.parentNode;

            if(focusNode.parentNode.childNodes.length>1 || ancestor.tagName.toLowerCase() == WYMeditor.OL || ancestor.tagName.toLowerCase() == WYMeditor.UL) {
              this._doc.execCommand(cmd,'',null);
            }
        }

    break;

    default:

        if(param) this._doc.execCommand(cmd,'',param);
        else this._doc.execCommand(cmd,'',null);
    break;
    }

    //set to P if parent = BODY
    var container = this.selected();
    if(container.tagName.toLowerCase() == WYMeditor.BODY)
        this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);

    return(true);
};

/* @name selected
 * @description Returns the selected container
 */
WYMeditor.WymClassMozilla.prototype.selected = function() {

    var sel = this._iframe.contentWindow.getSelection();
    var node = sel.focusNode;
    if(node) {
        if(node.nodeName == "#text") return(node.parentNode);
        else return(node);
    } else return(null);
};

WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};

//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  var container = null;

  if(evt.ctrlKey){
    if(evt.keyCode == 66){
      //CTRL+b => STRONG
      wym._exec(WYMeditor.BOLD);
      return false;
    }
    if(evt.keyCode == 73){
      //CTRL+i => EMPHASIS
      wym._exec(WYMeditor.ITALIC);
      return false;
    }
  }

  else if(evt.keyCode == 13) {
    if(!evt.shiftKey){
      //fix PRE bug #73
      container = wym.selected();
      if(container && container.tagName.toLowerCase() == WYMeditor.PRE) {
        evt.preventDefault();
        wym.insert('

');
      }
    }
  }

  return true;
};

//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];

  wym._selected_image = null;
  var container = null;

  if(evt.keyCode == 13 && !evt.shiftKey) {

    //RETURN key
    //cleanup

 between paragraphs
    jQuery(wym._doc.body).children(WYMeditor.BR).remove();
  }

  if(evt.keyCode != 8 && evt.keyCode != 17 && evt.keyCode != 46 && evt.keyCode != 224 && !evt.metaKey && !evt.ctrlKey) {

    //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
    //text nodes replaced by P

    container = wym.selected();
    var name = container.tagName.toLowerCase();

    //fix forbidden main containers
    if(
      name == "strong" ||
      name == "b" ||
      name == "em" ||
      name == "i" ||
      name == "sub" ||
      name == "sup" ||
      name == "a" ) name = container.parentNode.tagName.toLowerCase();

    if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
  }
};

//click handler
WYMeditor.WymClassMozilla.prototype.click = function(evt) {

	var wym = WYMeditor.INSTANCES[this.title];
	var container = wym.selected();

	if(container && container.tagName.toLowerCase() == WYMeditor.TR) {
		jQuery(WYMeditor.TD, wym._doc.body).append('
');
	} else if (container && container.tagName.toLowerCase() == WYMeditor.BODY) {
		wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
	}
};

WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
    if(this._doc.body.contentEditable != "true") {
      try {
        this._doc.body.contentEditable = "true";
        this._doc.execCommand("styleWithCSS", '', false);
        this._doc.execCommand("enableObjectResizing", false, false);
        this._doc.execCommand("enableInlineTableEditing", false, false);
      } catch(e) { }
    }
};

WYMeditor.WymClassMozilla.prototype.openBlockTag = function(tag, attributes)
{
    attributes = this.validator.getValidTagAttributes(tag, attributes);

    // Handle Mozilla styled spans
    if (tag == 'span' && attributes.style) {
        var new_tag = this.getTagForStyle(attributes.style);
        if (new_tag) {
            tag = new_tag;
            this._tag_stack.pop();
            this._tag_stack.push(tag);
            attributes.style = '';
        }
    }

    this.output += this.helper.tag(tag, attributes, true);
};

WYMeditor.WymClassMozilla.prototype.getTagForStyle = function(style) {

  if(/bold/.test(style)) return 'strong';
  if(/italic/.test(style)) return 'em';
  if(/sub/.test(style)) return 'sub';
  if(/super/.test(style)) return 'sup';
  return false;
};

<commit_msg>Mozilla: prevent the up arrow from creating a new P.<commit_after>/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2005 - 2009 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.mozilla.js
 *        Gecko specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Volker Mische (vmx a-t gmx dotde)
 *        Bermi Ferrer (wymeditor a-t bermi dotorg)
 *        Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
 *        Jonatan Lundin (jonatan.lundin a-t gmail dotcom)
 */

WYMeditor.WymClassMozilla = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\n";
};

WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {
    var wym = this;

    this._iframe = iframe;
    this._doc = iframe.contentDocument;

    jQuery(this._element).trigger('wymeditor:iframe_loaded');

    //add css rules from options

    var styles = this._doc.styleSheets[0];
    var aCss = eval(this._options.editorStyles);

    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);

    //init html value
    this.html(this._wym._html);

    //init designMode
    this.enableDesignMode();

    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);

    //bind external events
    this._wym.bindEvents();

    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);

    //bind editor keyup events
    jQuery(this._doc).bind("keyup", this.keyup);

    //bind editor click events
    jQuery(this._doc).bind("click", this.click);

    //bind editor focus events (used to reset designmode - Gecko bug)
    jQuery(this._doc).bind("focus", function () {
        // Fix scope
        wym.enableDesignMode.call(wym);
    });

    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);

    //add event listeners to doc elements, e.g. images
    this.listen();
};

/* @name html
 * @description Get/Set the html value
 */
WYMeditor.WymClassMozilla.prototype.html = function(html) {

  if(typeof html === 'string') {

    //disable designMode
    try { this._doc.designMode = "off"; } catch(e) {
      //do nothing
    }

    //replace em by i and strong by bold
    //(designMode issue)
    html = html.replace(/]*)>/gi, "");
    html = html.replace(/<\/em>/gi, "");
    html = html.replace(/]*)>/gi, "");
    html = html.replace(/<\/strong>/gi, "");

    //update the html body
    jQuery(this._doc.body).html(html);

    //re-init designMode
    this.enableDesignMode();
  }
  else return(jQuery(this._doc.body).html());
  return false;
};

WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {

    if(!this.selected()) return(false);

    switch(cmd) {

    case WYMeditor.INDENT: case WYMeditor.OUTDENT:

        var focusNode = this.selected();
        var sel = this._iframe.contentWindow.getSelection();
        var anchorNode = sel.anchorNode;
        if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;

        focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
        anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);

        if(focusNode && focusNode == anchorNode && focusNode.tagName.toLowerCase() == WYMeditor.LI) {

            var ancestor = focusNode.parentNode.parentNode;

            if(focusNode.parentNode.childNodes.length>1 || ancestor.tagName.toLowerCase() == WYMeditor.OL || ancestor.tagName.toLowerCase() == WYMeditor.UL) {
              this._doc.execCommand(cmd,'',null);
            }
        }

    break;

    default:

        if(param) this._doc.execCommand(cmd,'',param);
        else this._doc.execCommand(cmd,'',null);
    break;
    }

    //set to P if parent = BODY
    var container = this.selected();
    if(container.tagName.toLowerCase() == WYMeditor.BODY)
        this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);

    return(true);
};

/* @name selected
 * @description Returns the selected container
 */
WYMeditor.WymClassMozilla.prototype.selected = function() {

    var sel = this._iframe.contentWindow.getSelection();
    var node = sel.focusNode;
    if(node) {
        if(node.nodeName == "#text") return(node.parentNode);
        else return(node);
    } else return(null);
};

WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};

//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  var container = null;

  if(evt.ctrlKey){
    if(evt.keyCode == 66){
      //CTRL+b => STRONG
      wym._exec(WYMeditor.BOLD);
      return false;
    }
    if(evt.keyCode == 73){
      //CTRL+i => EMPHASIS
      wym._exec(WYMeditor.ITALIC);
      return false;
    }
  }

  else if(evt.keyCode == 13) {
    if(!evt.shiftKey){
      //fix PRE bug #73
      container = wym.selected();
      if(container && container.tagName.toLowerCase() == WYMeditor.PRE) {
        evt.preventDefault();
        wym.insert('

');
      }
    }
  }

  return true;
};

//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];

  wym._selected_image = null;
  var container = null;

  if(evt.keyCode == 13 && !evt.shiftKey) {

    //RETURN key
    //cleanup

 between paragraphs
    jQuery(wym._doc.body).children(WYMeditor.BR).remove();
  }

  if(evt.keyCode != 8 && evt.keyCode != 17 && evt.keyCode != 46 && evt.keyCode != 224 && !evt.metaKey && !evt.ctrlKey) {

    //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
    //text nodes replaced by P

    container = wym.selected();
    var name = container.tagName.toLowerCase();

    //fix forbidden main containers
    if(
      name == "strong" ||
      name == "b" ||
      name == "em" ||
      name == "i" ||
      name == "sub" ||
      name == "sup" ||
      name == "a" ) name = container.parentNode.tagName.toLowerCase();

    // prevent the up arrow on the first node from creating a new P
    if(evt.keyCode == 38 && name == WYMeditor.BODY ) { //UP arrow
      var $first_p = jQuery(wym._doc.body).find('p:first');
      if($first_p.length) {
        var sel = wym._iframe.contentWindow.getSelection();
        var p_range = wym._iframe.contentWindow.document.createRange();
        p_range.setStart($first_p[0], 0);
        p_range.setEnd($first_p[0], 0);
        sel.removeAllRanges();
        sel.addRange(p_range);
        return;
      }
    }

    if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
  }
};

WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
    if(this._doc.body.contentEditable != "true") {
      try {
        this._doc.body.contentEditable = "true";
        this._doc.execCommand("styleWithCSS", '', false);
        this._doc.execCommand("enableObjectResizing", false, false);
        this._doc.execCommand("enableInlineTableEditing", false, false);
      } catch(e) { }
    }
};

WYMeditor.WymClassMozilla.prototype.openBlockTag = function(tag, attributes)
{
    attributes = this.validator.getValidTagAttributes(tag, attributes);

    // Handle Mozilla styled spans
    if (tag == 'span' && attributes.style) {
        var new_tag = this.getTagForStyle(attributes.style);
        if (new_tag) {
            tag = new_tag;
            this._tag_stack.pop();
            this._tag_stack.push(tag);
            attributes.style = '';
        }
    }

    this.output += this.helper.tag(tag, attributes, true);
};

WYMeditor.WymClassMozilla.prototype.getTagForStyle = function(style) {

  if(/bold/.test(style)) return 'strong';
  if(/italic/.test(style)) return 'em';
  if(/sub/.test(style)) return 'sub';
  if(/super/.test(style)) return 'sup';
  return false;
};

<|endoftext|>


<commit_before>/**
 * Created by karolisrusenas on 11/04/2016.
 */
import React, {PropTypes} from 'react'
import {connect} from 'react-redux'

import Card from 'material-ui/lib/card/card'
import CardActions from 'material-ui/lib/card/card-actions'
import CardTitle from 'material-ui/lib/card/card-title'
import RaisedButton from 'material-ui/lib/raised-button'
import CardText from 'material-ui/lib/card/card-text'

import Table from 'material-ui/lib/table/table'
import TableHeaderColumn from 'material-ui/lib/table/table-header-column'
import TableRow from 'material-ui/lib/table/table-row'
import TableHeader from 'material-ui/lib/table/table-header'
import TableRowColumn from 'material-ui/lib/table/table-row-column'
import TableBody from 'material-ui/lib/table/table-body'

import {Row, Col} from 'react-bootstrap'

import {fetchRecordsCount, fetchStats, wipeRecords} from '../../redux/modules/state'

export class RowWrapper extends React.Component<void, Props, void> {
  render () {
    return (
      <TableRow key={name}>
        <TableRowColumn>{this.props.name}</TableRowColumn>
        <TableRowColumn>{this.props.val}</TableRowColumn>
      </TableRow>
    )
  }
}

RowWrapper.propTypes = {
  name: PropTypes.string,
  val: PropTypes.number
}

export class StatsComponent extends React.Component<void, Props, void> {
  constructor (props) {
    super(props)
    this._fetchRecordsCount = this._fetchRecordsCount.bind(this)
    this._fetchStats = this._fetchStats.bind(this)
    this.handleWipeRecordsClick = this.handleWipeRecordsClick.bind(this)
  }

  componentDidMount () {
    this._fetchRecordsCount()
    this._fetchStats()
  }

  _fetchRecordsCount () {
    this.props.fetchRecordsCount(this.props.token)
  }

  _fetchStats () {
    this.props.fetchStats(this.props.token)
  }

  handleWipeRecordsClick () {
    this.props.wipeRecords(this.props.token)
    this._fetchRecordsCount()
  }

  getCounterRows () {
    let counters = this.props.info.stats.counters
    if (counters !== 'undefined') {
      let rows = []
      for (var key in counters) {
        if (counters.hasOwnProperty(key)) {
          rows.push(<RowWrapper key={key} name={key} val={counters[key]}/>)
        }
      }
      return rows
    }
  }

  render () {
    let recordsCountInfo = 'Captured request count: ' + this.props.info.recordsCount
    let rows = null
    if (this.props.info.stats !== 'undefined' && this.props.info.stats !== null) {
      rows = this.getCounterRows()
    }

    const counterTable = (
      <Col md={4}>

          <TableHeader displaySelectAll={false} adjustForCheckbox={false} enableSelectAll={false}>
            <TableRow>
              <TableHeaderColumn
                colSpan='2'
                tooltip='Basic statistics for requests that are passing through proxy'
                style={{textAlign: 'center'}}>
                Counters
              </TableHeaderColumn>
            </TableRow>
            <TableRow>
              <TableHeaderColumn tooltip='Name'>Name</TableHeaderColumn>
              <TableHeaderColumn tooltip='Value of this parameter'>Value</TableHeaderColumn>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows}
          </TableBody>

      </Col>
    )

    const statsInfo = (
      <Card>
        <CardTitle title={recordsCountInfo} subtitle='This section provides real-time Hoverfly metrics'/>
        <CardText>
          <Row>
            {counterTable}
          </Row>
        </CardText>
        <CardActions>
          <RaisedButton label='Wipe Records' onClick={this.handleWipeRecordsClick} secondary/>
        </CardActions>
      </Card>
    )
    return (

        {statsInfo}

    )
  }
}

StatsComponent.propTypes = {
  fetchRecordsCount: PropTypes.func.isRequired,
  fetchStats: PropTypes.func.isRequired,
  wipeRecords: PropTypes.func.isRequired,
  token: PropTypes.string,
  info: PropTypes.object.isRequired
}

export default StatsComponent

const mapStateToProps = (state) => ({
  info: state.info
})

export default connect(mapStateToProps, {
  fetchRecordsCount,
  fetchStats,
  wipeRecords
})(StatsComponent)
<commit_msg>fetching through websocket if it's available<commit_after>/**
 * Created by karolisrusenas on 11/04/2016.
 */
import React, {PropTypes} from 'react'
import {connect} from 'react-redux'

import Card from 'material-ui/lib/card/card'
import CardActions from 'material-ui/lib/card/card-actions'
import CardTitle from 'material-ui/lib/card/card-title'
import RaisedButton from 'material-ui/lib/raised-button'
import CardText from 'material-ui/lib/card/card-text'

import Table from 'material-ui/lib/table/table'
import TableHeaderColumn from 'material-ui/lib/table/table-header-column'
import TableRow from 'material-ui/lib/table/table-row'
import TableHeader from 'material-ui/lib/table/table-header'
import TableRowColumn from 'material-ui/lib/table/table-row-column'
import TableBody from 'material-ui/lib/table/table-body'

import {Row, Col} from 'react-bootstrap'

import {fetchRecordsCount, fetchStats, wipeRecords, receiveStats} from '../../redux/modules/state'

export class RowWrapper extends React.Component<void, Props, void> {
  render () {
    return (
      <TableRow key={name}>
        <TableRowColumn>{this.props.name}</TableRowColumn>
        <TableRowColumn>{this.props.val}</TableRowColumn>
      </TableRow>
    )
  }
}

RowWrapper.propTypes = {
  name: PropTypes.string,
  val: PropTypes.number
}

export class StatsComponent extends React.Component<void, Props, void> {
  constructor (props) {
    super(props)
    this._fetchRecordsCount = this._fetchRecordsCount.bind(this)
    this._fetchStats = this._fetchStats.bind(this)
    this.handleWipeRecordsClick = this.handleWipeRecordsClick.bind(this)

    this.greetWebsocket = this.greetWebsocket.bind(this)
    this.waitForSocketConnection = this.waitForSocketConnection.bind(this)
    this._cleanup = this._cleanup.bind(this)

    this.state = {
      ws: null,
      interval: 2000,
      refreshId: null
    }
  }

  greetWebsocket () {
    if (this.state.ws.readyState !== this.state.ws.open) {
      this.state.ws.send('hi')
    }
  }

  // Make the function wait until the connection is made...
  waitForSocketConnection (socket, callback) {
    setTimeout(
      function () {
        if (socket.readyState === 1) {
          if (callback != null) {
            callback()
          }
        } else {
          this.waitForSocketConnection(socket, callback)
        }
      }.bind(this), 5) // wait 5 ms for the connection...
  }

  componentWillMount () {
    if ('WebSocket' in window) {
      this.state.ws = new WebSocket('ws:/' + window.location.host + '/api/statsws')

      this.state.ws.onclose = function () {
        console.log('Connection is closed, fetching manually')
        this.state.ws = null
        this.state.refreshId = setInterval(this._fetchStats, parseInt(this.state.interval))
      }.bind(this)
    } else {
      console.log('WebSocket not supported by your browser.')
      this.state.refreshId = setInterval(this._fetchStats, parseInt(this.state.interval))
    }
  }

  _cleanup () {
    if (this.state.refreshId !== null) {
      clearInterval(this.state.refreshId)
    }
    if (this.state.ws !== null) {
      this.state.ws.close()
    }
  }

  componentWillUnmount () {
    this._cleanup()
  }

  componentDidMount () {
    this._fetchRecordsCount()

    if (this.state.ws != null) {
      this.waitForSocketConnection(this.state.ws, this.greetWebsocket)
      // getting response with data
      this.state.ws.onmessage = function (response) {
        let parsedData = JSON.parse(response.data)
        this.props.receiveStats(parsedData)
      }.bind(this)
    }
  }

  _fetchRecordsCount () {
    this.props.fetchRecordsCount(this.props.token)
  }

  _fetchStats () {
    this.props.fetchStats(this.props.token)
  }

  handleWipeRecordsClick () {
    this.props.wipeRecords(this.props.token)
    this._fetchRecordsCount()
  }

  getCounterRows () {
    let counters = this.props.info.stats.counters
    if (counters !== 'undefined') {
      let rows = []
      for (var key in counters) {
        if (counters.hasOwnProperty(key)) {
          rows.push(<RowWrapper key={key} name={key} val={counters[key]}/>)
        }
      }
      return rows
    }
  }

  render () {
    let recordsCountInfo = 'Captured request count: ' + this.props.info.recordsCount
    let rows = null
    if (this.props.info.stats !== 'undefined' && this.props.info.stats !== null) {
      rows = this.getCounterRows()
    }

    const counterTable = (
      <Col md={4}>

          <TableHeader displaySelectAll={false} adjustForCheckbox={false} enableSelectAll={false}>
            <TableRow>
              <TableHeaderColumn
                colSpan='2'
                tooltip='Basic statistics for requests that are passing through proxy'
                style={{textAlign: 'center'}}>
                Counters
              </TableHeaderColumn>
            </TableRow>
            <TableRow>
              <TableHeaderColumn tooltip='Name'>Name</TableHeaderColumn>
              <TableHeaderColumn tooltip='Value of this parameter'>Value</TableHeaderColumn>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows}
          </TableBody>

      </Col>
    )

    const statsInfo = (
      <Card>
        <CardTitle title={recordsCountInfo} subtitle='This section provides real-time Hoverfly metrics'/>
        <CardText>
          <Row>
            {counterTable}
          </Row>
        </CardText>
        <CardActions>
          <RaisedButton label='Wipe Records' onClick={this.handleWipeRecordsClick} secondary/>
        </CardActions>
      </Card>
    )
    return (

        {statsInfo}

    )
  }
}

StatsComponent.propTypes = {
  fetchRecordsCount: PropTypes.func.isRequired,
  fetchStats: PropTypes.func.isRequired,
  receiveStats: PropTypes.func.isRequired,
  wipeRecords: PropTypes.func.isRequired,
  token: PropTypes.string,
  info: PropTypes.object.isRequired
}

export default StatsComponent

const mapStateToProps = (state) => ({
  info: state.info
})

export default connect(mapStateToProps, {
  fetchRecordsCount,
  fetchStats,
  wipeRecords,
  receiveStats
})(StatsComponent)
<|endoftext|>


<commit_before>/* Compose - DOM ready */
Mailpile.compose_init = function(mid) {

  console.log('running init for composer');

  // Reset tabindex for To: field
  $('#search-query').attr('tabindex', '-1');

  // Load Crypto States
  // FIXME: needs dynamic support for multi composers on a page
  Mailpile.compose_load_crypto_states();

  // Instantiate select2
  $('.compose-address-field').each(function(key, elem) {
    Mailpile.compose_address_field($(elem).attr('id'));
  });

  // Save Text Composing Objects
  $('.compose-text').each(function(key, elem) {
      Mailpile.messages_composing[$(elem).attr('id')] = $(elem).val()
  });

  // Run Autosave
  Mailpile.compose_autosave_timer.play();
  Mailpile.compose_autosave_timer.set({ time : 20000, autostart : true });

  // Initialize Attachments
  // FIXME: needs dynamic support for multi composers on a page
  $('.compose-attachments').each(function(key, elem) {
    var mid = $(elem).data('mid');
    console.log('js uploader: ' + mid);
    uploader({
      browse_button: 'compose-attachment-pick-' + mid,
      container: 'compose-attachments-' + mid,
      mid: mid
    });
  });

  // Show Crypto Tooltips
  Mailpile.tooltip_compose_crypto_signature();
  Mailpile.tooltip_compose_crypto_encryption();
  Mailpile.tooltip_compose_contact_details();

};<commit_msg>Made Compose init to not use classes #594<commit_after>/* Compose - Create new instance of composer */
Mailpile.compose_init = function(mid) {

  // Reset tabindex for To: field
  $('#search-query').attr('tabindex', '-1');

  // Load Crypto States
  // FIXME: needs dynamic support for multi composers on a page
  Mailpile.compose_load_crypto_states();

  // Instantiate select2
  Mailpile.compose_address_field('compose-to-' + mid);
  // FIXME: move to click events
  Mailpile.compose_address_field('compose-cc-' + mid);
  Mailpile.compose_address_field('compose-bcc-' + mid);

  // Save Text Composing Objects (move to data model)
  Mailpile.messages_composing['compose-text-' + mid] = $('compose-text-' + mid).val();

  // Run Autosave
  // FIXME: this should be moved to the global event loop
  Mailpile.compose_autosave_timer.play();
  Mailpile.compose_autosave_timer.set({ time : 20000, autostart : true });

  // Initialize Attachments
  // FIXME: needs to be bound to unique ID that can be destroyed
  uploader({
    browse_button: 'compose-attachment-pick-' + mid,
    container: 'compose-attachments-' + mid,
    mid: mid
  });

  // Show Crypto Tooltips
  Mailpile.tooltip_compose_crypto_signature();
  Mailpile.tooltip_compose_crypto_encryption();
  Mailpile.tooltip_compose_contact_details();

};<|endoftext|>


<commit_before>// Helper methods for all CLASS modules are stored here.
CLASS.prototype = Object.create(Object.prototype);

/**
 * Recursively inherit the constructor properties of parent modules.
 *
 * @function super
 * @api public
 */

$descriptor.value = (function () {
    if (!$development) {
        var nodePrototype = null;

        return function () {
            if (isNull(nodePrototype)) {
                nodePrototype = Object.getPrototypeOf(Object.getPrototypeOf(this));
            } else {
                nodePrototype = Object.getPrototypeOf(nodePrototype);
            }

            if (nodePrototype === CLASS.prototype) {
                nodePrototype = null;
            } else {
                nodePrototype.constructor.apply(this, Array.prototype.slice.call(arguments));
            }
        };
    }

    var nodeName = ''; // Next parent in chain.
    var rootName = ''; // First child in chain.
    var descriptor = $descriptor;

    /**
     * @function resetChain
     * @api private
     */

    function resetChain () {
        nodeName = '';
        rootName = '';
    }

    /**
     * Check in which node the super chain is at.
     *
     * @function checkChain
     * @api private
     */

    function checkChain () {
        // If nodeName is an empty string, then start the chain from the
        // parent of the root child.
        if (isEmptyString(nodeName)) {
            nodeName = this.$parentName;

            // Even though super might be invoked in different constructors,
            // the same instance will always be referenced. rootName is used
            // to know if the chain has been broken.
            rootName = this.$name;

            // Prevent instance from having parent properties applied more than once.
            if (this.$applied) {
                throwError('Cannot invoke super more than once for ' + this.$name + ' instance.', 'SUPER');
            } else {
                descriptor.value = true;

                Object.defineProperty(this, '$applied', descriptor);
            }

        // Otherwise just move to next parent.
        } else {
            // Error out if chain is broken.
            if (this.$name !== rootName) {
                throwError('Chain started by ' + rootName + ' instance is being broken by ' + this.$name + ' instance.', 'SUPER');
            }

            nodeName = CLASS[nodeName].prototype.$parentName;
        }
    }

    /**
     * If the current node has parent, apply current node to
     * parent's constructor.
     *
     * @function applyNode
     * @param {Array} args
     * @api private
     */

    function applyNode (args) {
        if (isEmptyString(nodeName)) { return undefined; }

        var nextParent = CLASS[nodeName].prototype.$parentName;

        // Keep reference of node just in case chain gets reset.
        var temp = nodeName;

        // If there are no more parent nodes then reset chain.
        if (isEmptyString(nextParent)) {
            resetChain();
        }

        CLASS[temp].apply(this, args);
    }

    return function () {
        checkChain.call(this);
        applyNode.call(this, Array.prototype.slice.call(arguments));
    };
})();

Object.defineProperty(CLASS.prototype, 'super', $descriptor);

/**
 * Error out program whenever abstract is invoked.
 *
 * @function abstract
 * @api public
 */

$descriptor.value = (function () {
    if ($development) {
        return function () {
            var call = traceCallFromErrorStack(this, 1).split('.');
            var message = '';

            // abstract can only be invoked inside the methods of CLASS module instances.
            if (this.$name !== call[0]) {
                message = 'Cannot invoke abstract directly from ' + this.$name + ' instance.';
            } else if (call.length === 1) {
                message = 'Cannot invoke abstract inside a constructor.';
            } else {
                message = 'Invoked method is meant to be overwritten.';
            }

            throwError(message, 'ABSTRACT', this, 1);
        };
    } else {
        return function () {};
    }
})();

Object.defineProperty(CLASS.prototype, 'abstract', $descriptor);

if ($development) {
    // CLASS flag.
    $descriptor.value = true;

    Object.defineProperty(CLASS.prototype, '$isClass', $descriptor);
}
<commit_msg>{Update: class-properties.js} Make super an empty function when not in development.<commit_after>// Helper methods for all CLASS modules are stored here.
CLASS.prototype = Object.create(Object.prototype);

/**
 * Recursively inherit the constructor properties of parent modules.
 *
 * @function super
 * @api public
 */

$descriptor.value = (function () {
    if (!$development) { return function () {}; }

    var nodeName = ''; // Next parent in chain.
    var rootName = ''; // First child in chain.
    var descriptor = $descriptor;

    /**
     * @function resetChain
     * @api private
     */

    function resetChain () {
        nodeName = '';
        rootName = '';
    }

    /**
     * Check in which node the super chain is at.
     *
     * @function checkChain
     * @api private
     */

    function checkChain () {
        // If nodeName is an empty string, then start the chain from the
        // parent of the root child.
        if (isEmptyString(nodeName)) {
            nodeName = this.$parentName;

            // Even though super might be invoked in different constructors,
            // the same instance will always be referenced. rootName is used
            // to know if the chain has been broken.
            rootName = this.$name;

            // Prevent instance from having parent properties applied more than once.
            if (this.$applied) {
                throwError('Cannot invoke super more than once for ' + this.$name + ' instance.', 'SUPER');
            } else {
                descriptor.value = true;

                Object.defineProperty(this, '$applied', descriptor);
            }

        // Otherwise just move to next parent.
        } else {
            // Error out if chain is broken.
            if (this.$name !== rootName) {
                throwError('Chain started by ' + rootName + ' instance is being broken by ' + this.$name + ' instance.', 'SUPER');
            }

            nodeName = CLASS[nodeName].prototype.$parentName;
        }
    }

    /**
     * If the current node has parent, apply current node to
     * parent's constructor.
     *
     * @function applyNode
     * @param {Array} args
     * @api private
     */

    function applyNode (args) {
        if (isEmptyString(nodeName)) { return undefined; }

        var nextParent = CLASS[nodeName].prototype.$parentName;

        // Keep reference of node just in case chain gets reset.
        var temp = nodeName;

        // If there are no more parent nodes then reset chain.
        if (isEmptyString(nextParent)) {
            resetChain();
        }

        CLASS[temp].apply(this, args);
    }

    return function () {
        checkChain.call(this);
        applyNode.call(this, Array.prototype.slice.call(arguments));
    };
})();

Object.defineProperty(CLASS.prototype, 'super', $descriptor);

/**
 * Error out program whenever abstract is invoked.
 *
 * @function abstract
 * @api public
 */

$descriptor.value = (function () {
    if ($development) {
        return function () {
            var call = traceCallFromErrorStack(this, 1).split('.');
            var message = '';

            // abstract can only be invoked inside the methods of CLASS module instances.
            if (this.$name !== call[0]) {
                message = 'Cannot invoke abstract directly from ' + this.$name + ' instance.';
            } else if (call.length === 1) {
                message = 'Cannot invoke abstract inside a constructor.';
            } else {
                message = 'Invoked method is meant to be overwritten.';
            }

            throwError(message, 'ABSTRACT', this, 1);
        };
    } else {
        return function () {};
    }
})();

Object.defineProperty(CLASS.prototype, 'abstract', $descriptor);

if ($development) {
    // CLASS flag.
    $descriptor.value = true;

    Object.defineProperty(CLASS.prototype, '$isClass', $descriptor);
}
<|endoftext|>


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

	var defaultDirectiveReturnValue = {
			'restrict' : 'AE',
			'replace': true,
			'template' : '
{{token}}
'
	};

    var defaultDirectiveTranscludeReturnValue = {
        'restrict' : 'AE',
        'replace': true,
        'transclude': true,
        'template' : '
{{token}}

'
    };

	angular.module('inspector-test-mocks', ['ngRoute'])
    .config( ['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
        $routeProvider
            .when('/primitive', {
                template: '<input ng-model="primitive">'
            })
            .when('/object', {
                template: '<input ng-model="obj.key">'
            })
            .otherwise({redirectTo: '/index'});
        $locationProvider.html5Mode(true);
    }])
	.directive('directiveSharedScope', function() {
		return angular.extend({}, defaultDirectiveReturnValue);
	})
	.directive('directiveSharedScopeExplicit', function() {
		return angular.extend({'scope': false}, defaultDirectiveReturnValue);
	})
	.directive('directiveIsolatedScope', function() {
		return angular.extend({'scope': {}}, defaultDirectiveReturnValue);
	})
	.directive('directiveIsolatedScopeWithString', function() {
		return angular.extend({'scope' : {'token': '@'}}, defaultDirectiveReturnValue);
	})
	.directive('directiveIsolatedScopeWithObject', function() {
		var dest = {
                        'scope':    {
                            'tokenobj': '='
                        }
					};
		var retVal = angular.extend(dest, defaultDirectiveReturnValue);
		retVal.template = '
{{tokenobj.token}}
';
		return retVal;
	})
	.directive('directiveIsolatedScopeWithFunction', function() {
		var dest = {
					'scope':    {
									'fun': '&'
								}
                    };
		var retVal = angular.extend(dest, defaultDirectiveReturnValue);
		retVal.template = '
{{token}}
';
		return retVal;
	})
    // with transclude
    .directive('directiveSharedScopeWithTransclude', function() {
        return angular.extend({}, defaultDirectiveTranscludeReturnValue);
    })
    .directive('directiveSharedScopeExplicitWithTransclude', function() {
        return angular.extend({'scope': false}, defaultDirectiveTranscludeReturnValue);
    })
    .directive('directiveIsolatedScopeWithTransclude', function() {
        return angular.extend({'scope': {}}, defaultDirectiveTranscludeReturnValue);
    })
    .directive('directiveIsolatedScopeWithStringWithTransclude', function() {
        return angular.extend({'scope' : {'token': '@'}}, defaultDirectiveTranscludeReturnValue);
    })
    .directive('directiveIsolatedScopeWithObjectWithTransclude', function() {
        var dest = {
            'scope':    {
                'tokenobj': '='
            }
        };
        var retVal = angular.extend(dest, defaultDirectiveTranscludeReturnValue);
        retVal.template = '

{{tokenobj.token}}

';
        return retVal;
    })
    .directive('directiveIsolatedScopeWithFunctionWithTransclude', function() {
        var dest = {
            'scope':    {
                'fun': '&'
            }
        };
        var retVal = angular.extend(dest, defaultDirectiveTranscludeReturnValue);
        retVal.template = '

{{token}}

';
        return retVal;
    })
    .controller('Ctrl', ['$scope', function($scope) {
        $scope.primitive = 'val';
        $scope.obj = { key : 'val' };
    }])
    .controller('SubCtrl',['$scope', function($scope) {
    }]);
})();<commit_msg>input added to directives<commit_after>(function() {
	"use strict";

	var defaultDirectiveReturnValue = {
			'restrict' : 'AE',
			'replace': true,
			'template' : '
{{token}}<input ng-model="token">
'
	};

    var defaultDirectiveTranscludeReturnValue = {
        'restrict' : 'AE',
        'replace': true,
        'transclude': true,
        'template' : '
{{token}}<input ng-model="token">

'
    };

	angular.module('inspector-test-mocks', ['ngRoute'])
    .config( ['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
        $routeProvider
            .when('/primitive', {
                template: '<input ng-model="primitive">'
            })
            .when('/object', {
                template: '<input ng-model="obj.key">'
            })
            .otherwise({redirectTo: '/index'});
        $locationProvider.html5Mode(true);
    }])
	.directive('directiveSharedScope', function() {
		return angular.extend({}, defaultDirectiveReturnValue);
	})
	.directive('directiveSharedScopeExplicit', function() {
		return angular.extend({'scope': false}, defaultDirectiveReturnValue);
	})
	.directive('directiveIsolatedScope', function() {
		return angular.extend({'scope': {}}, defaultDirectiveReturnValue);
	})
	.directive('directiveIsolatedScopeWithString', function() {
		return angular.extend({'scope' : {'token': '@'}}, defaultDirectiveReturnValue);
	})
	.directive('directiveIsolatedScopeWithObject', function() {
		var dest = {
                        'scope':    {
                            'tokenobj': '='
                        }
					};
		var retVal = angular.extend(dest, defaultDirectiveReturnValue);
		retVal.template = '
{{tokenobj.token}}<input ng-model="tokenobj.token">
';
		return retVal;
	})
	.directive('directiveIsolatedScopeWithFunction', function() {
		var dest = {
					'scope':    {
									'fun': '&'
								}
                    };
		var retVal = angular.extend(dest, defaultDirectiveReturnValue);
		retVal.template = '
{{token}}
';
		return retVal;
	})
    // with transclude
    .directive('directiveSharedScopeWithTransclude', function() {
        return angular.extend({}, defaultDirectiveTranscludeReturnValue);
    })
    .directive('directiveSharedScopeExplicitWithTransclude', function() {
        return angular.extend({'scope': false}, defaultDirectiveTranscludeReturnValue);
    })
    .directive('directiveIsolatedScopeWithTransclude', function() {
        return angular.extend({'scope': {}}, defaultDirectiveTranscludeReturnValue);
    })
    .directive('directiveIsolatedScopeWithStringWithTransclude', function() {
        return angular.extend({'scope' : {'token': '@'}}, defaultDirectiveTranscludeReturnValue);
    })
    .directive('directiveIsolatedScopeWithObjectWithTransclude', function() {
        var dest = {
            'scope':    {
                'tokenobj': '='
            }
        };
        var retVal = angular.extend(dest, defaultDirectiveTranscludeReturnValue);
        retVal.template = '

{{tokenobj.token}}

';
        return retVal;
    })
    .directive('directiveIsolatedScopeWithFunctionWithTransclude', function() {
        var dest = {
            'scope':    {
                'fun': '&'
            }
        };
        var retVal = angular.extend(dest, defaultDirectiveTranscludeReturnValue);
        retVal.template = '

{{token}}

';
        return retVal;
    })
    .controller('Ctrl', ['$scope', function($scope) {
        $scope.primitive = 'val';
        $scope.obj = { key : 'val' };
    }])
    .controller('SubCtrl',['$scope', function($scope) {
    }]);
})();<|endoftext|>


<commit_before>const { sandbox } = require('sinon');
const { expect } = require('chai');
const { teams } = require('src/api');
const { authConf } = require('src/auth-utils');
const { fakeAuthResult } = require('tests/fakes');
const authApi = require('src/core/auth');

describe("api.teams", () => {
  beforeEach(() => {
    this.sandbox = sandbox.create();
  });

  afterEach(() => {
    this.sandbox.restore();
  });

  describe("list", () => {
    it("should list an organizations teams", () => {
      const auth = {
        type: 'token',
        token: 'abc'
      };

      const expected = [
        {id: 1},
        {id: 2}
      ];

      this.sandbox.stub(authApi.organizations, 'listTeams')
        .withArgs(23, {conf: authConf(auth)})
        .returns(fakeAuthResult(expected));

      return teams.list(23, {auth})
        .then(res => expect(res).to.deep.equal(expected));
    });
  });

  describe("get", () => {
    it("should get a team", () => {
      const auth = {
        type: 'token',
        token: 'abc'
      };

      const expected = {id: 21};

      this.sandbox.stub(authApi.teams, 'get')
        .withArgs(21, {conf: authConf(auth)})
        .returns(fakeAuthResult(expected));

      return teams.get(21, {auth})
        .then(res => expect(res).to.deep.equal(expected));
    });
  });
});
<commit_msg>Fix api.teams tests not providing params<commit_after>const { sandbox } = require('sinon');
const { expect } = require('chai');
const { teams } = require('src/api');
const { authConf } = require('src/auth-utils');
const { fakeAuthResult } = require('tests/fakes');
const authApi = require('src/core/auth');

describe("api.teams", () => {
  beforeEach(() => {
    this.sandbox = sandbox.create();
  });

  afterEach(() => {
    this.sandbox.restore();
  });

  describe("list", () => {
    it("should list an organizations teams", () => {
      const auth = {
        type: 'token',
        token: 'abc'
      };

      const expected = [
        {id: 1},
        {id: 2}
      ];

      this.sandbox.stub(authApi.organizations, 'listTeams')
        .withArgs(23, {conf: authConf(auth)})
        .returns(fakeAuthResult(expected));

      return teams.list(23, {}, {auth})
        .then(res => expect(res).to.deep.equal(expected));
    });
  });

  describe("get", () => {
    it("should get a team", () => {
      const auth = {
        type: 'token',
        token: 'abc'
      };

      const expected = {id: 21};

      this.sandbox.stub(authApi.teams, 'get')
        .withArgs(21, {conf: authConf(auth)})
        .returns(fakeAuthResult(expected));

      return teams.get(21, {}, {auth})
        .then(res => expect(res).to.deep.equal(expected));
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var setupTestHooks     = require('ember-cli-blueprint-test-helpers/lib/helpers/setup');
var BlueprintHelpers   = require('ember-cli-blueprint-test-helpers/lib/helpers/blueprint-helper');
var generateAndDestroy = BlueprintHelpers.generateAndDestroy;

describe('Acceptance: ember generate and destroy ember-suave', function() {
  setupTestHooks(this);

  it('ember-suave', function() {
    return generateAndDestroy(['ember-suave'], {
      files: [
        { file: '.jscsrc', contents: ['"preset": "ember-suave"'] }
      ]
    });
  });
});
<commit_msg>tests/blueprint: Use new testing API<commit_after>'use strict';

var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers');
var setupTestHooks = blueprintHelpers.setupTestHooks;
var emberNew = blueprintHelpers.emberNew;
var emberGenerate = blueprintHelpers.emberGenerate;

var chai = require('ember-cli-blueprint-test-helpers/chai');
var expect = chai.expect;
var file = chai.file;

describe('Acceptance: ember generate and destroy ember-suave', function() {
  setupTestHooks(this);

  it('ember-suave', function() {
    var args = ['ember-suave'];

    return emberNew()
      .then(() => emberGenerate(args))
      .then(() => {
        expect(file('.jscsrc'))
          .to.contain('"preset": "ember-suave"');
      });
  });
});
<|endoftext|>


<commit_before>describe('directive: vcRecaptcha', function () {
    'use strict';

    var $scope, $compile, $timeout, vcRecaptchaService,

        TIMEOUT_SESSION_CAPTCHA = 2 * 60 * 1000, // 2 minutes
        VALID_KEY               = '1234567890123456789012345678901234567890';

    beforeEach(function () {
        module('vcRecaptcha');

        inject(function ($rootScope, _$compile_, _$timeout_, _vcRecaptchaService_) {
            $scope   = $rootScope.$new();
            $compile = _$compile_;
            $timeout = _$timeout_;

            vcRecaptchaService = _vcRecaptchaService_;
        });
    });

    describe('invalid key', function () {
        var elementHtml, expectedMessage;

        afterEach(function () {
            expect(function () {
                var element = angular.element(elementHtml);

                $compile(element)($scope);
                $scope.$digest();
            }).toThrow(new Error(expectedMessage));
        });

        it('should throw an error - no key', function () {
            elementHtml     = '

';
            expectedMessage = 'You need to set the "key" attribute to your public reCaptcha key. If you don\'t have a key, please get one from https://www.google.com/recaptcha/admin/create';
        });

        it('should throw an error - key length is not 40 caracters long', function () {
            elementHtml     = '

';
            expectedMessage = 'You need to set the "key" attribute to your public reCaptcha key. If you don\'t have a key, please get one from https://www.google.com/recaptcha/admin/create';

            $scope.key = 'abc';
        });

        it('should throw an error - key length is not 40 caracters long - key changed', function () {
            elementHtml     = '

';
            expectedMessage = 'You need to set the "key" attribute to your public reCaptcha key. If you don\'t have a key, please get one from https://www.google.com/recaptcha/admin/create';

            $scope.key = 'abc1';
        });
    });

    describe('widgetId', function () {
        it('should be null at start', function () {
            var element = angular.element('

');

            $scope.key = VALID_KEY;

            expect(function () {
                $compile(element)($scope);
                $scope.$digest();
            }).not.toThrow();

            expect(element.isolateScope().widgetId).toBeNull();
        });
    });

    describe('form validation', function () {
        beforeEach(function () {
            $scope.key       = VALID_KEY;
            $scope.onCreate  = jasmine.createSpy('onCreate');
            $scope.onSuccess = jasmine.createSpy('onSuccess');
        });

        afterEach(function () {
            expect(vcRecaptchaService.create).toHaveBeenCalled();
        });

        it('should change the validation to false, widget just created', function () {
            var element     = angular.element(
                    '<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'
                ),

                _fakeCreate = function () {
                    return {
                        then: function (cb) {
                            var _widgetId = 'a';

                            cb(_widgetId);
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();

            expect($scope.form.$valid).toBeFalsy(); // widgetCreated
            expect($scope.onCreate).toHaveBeenCalledWith({widgetId: 'a'});
        });

        it('should change the validation to true - first timeout flushed', function () {
            var element     = angular.element('<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'),

                _fakeCreate = function (element, config) {
                    config.callback('response from google');

                    return {
                        then: function (cb) {
                            cb();
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();

            $timeout.flush(TIMEOUT_SESSION_CAPTCHA - 1);

            expect($scope.form.$valid).toBeTruthy();
        });

        it('should change the validation to false - session expired', function () {
            var element     = angular.element('<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'),

                _fakeCreate = function (element, config) {
                    // Call the expiration callback as recaptcha would do.
                    config['expired-callback']();

                    return {
                        then: function (cb) {
                            cb();
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();

            $timeout.flush(TIMEOUT_SESSION_CAPTCHA + 1);

            expect($scope.form.$valid).toBeFalsy(); // widgetCreated
        });

        it('should call the onSuccess callback with the right params', function () {
            var element     = angular.element('<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'),

                _fakeCreate = function (element, config) {
                    config.callback('response from google');

                    return {
                        then: function (cb) {
                            cb();
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();
            $timeout.flush();

            expect($scope.onSuccess).toHaveBeenCalledWith({
                response: 'response from google',
                widgetId: undefined
            });
        });

        it('the widget should be using the setted language', function () {
            var element = angular.element('<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'),

                _fakeCreate = function (element, config) {
                    config.callback(config.lang);
                    return {
                        then: function (cb) {
                            cb();
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();
            $timeout.flush();

            expect($scope.onSuccess).toHaveBeenCalledWith({
                response: 'es',
                widgetId: undefined
            });
        });
    });
});
<commit_msg>Remove site key length tests<commit_after>describe('directive: vcRecaptcha', function () {
    'use strict';

    var $scope, $compile, $timeout, vcRecaptchaService,

        TIMEOUT_SESSION_CAPTCHA = 2 * 60 * 1000, // 2 minutes
        VALID_KEY               = '1234567890123456789012345678901234567890';

    beforeEach(function () {
        module('vcRecaptcha');

        inject(function ($rootScope, _$compile_, _$timeout_, _vcRecaptchaService_) {
            $scope   = $rootScope.$new();
            $compile = _$compile_;
            $timeout = _$timeout_;

            vcRecaptchaService = _vcRecaptchaService_;
        });
    });

    describe('invalid key', function () {
        var elementHtml, expectedMessage;

        afterEach(function () {
            expect(function () {
                var element = angular.element(elementHtml);

                $compile(element)($scope);
                $scope.$digest();
            }).toThrow(new Error(expectedMessage));
        });

        it('should throw an error - no key', function () {
            elementHtml     = '

';
            expectedMessage = 'You need to set the "key" attribute to your public reCaptcha key. If you don\'t have a key, please get one from https://www.google.com/recaptcha/admin/create';
        });
    });

    describe('widgetId', function () {
        it('should be null at start', function () {
            var element = angular.element('

');

            $scope.key = VALID_KEY;

            expect(function () {
                $compile(element)($scope);
                $scope.$digest();
            }).not.toThrow();

            expect(element.isolateScope().widgetId).toBeNull();
        });
    });

    describe('form validation', function () {
        beforeEach(function () {
            $scope.key       = VALID_KEY;
            $scope.onCreate  = jasmine.createSpy('onCreate');
            $scope.onSuccess = jasmine.createSpy('onSuccess');
        });

        afterEach(function () {
            expect(vcRecaptchaService.create).toHaveBeenCalled();
        });

        it('should change the validation to false, widget just created', function () {
            var element     = angular.element(
                    '<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'
                ),

                _fakeCreate = function () {
                    return {
                        then: function (cb) {
                            var _widgetId = 'a';

                            cb(_widgetId);
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();

            expect($scope.form.$valid).toBeFalsy(); // widgetCreated
            expect($scope.onCreate).toHaveBeenCalledWith({widgetId: 'a'});
        });

        it('should change the validation to true - first timeout flushed', function () {
            var element     = angular.element('<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'),

                _fakeCreate = function (element, config) {
                    config.callback('response from google');

                    return {
                        then: function (cb) {
                            cb();
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();

            $timeout.flush(TIMEOUT_SESSION_CAPTCHA - 1);

            expect($scope.form.$valid).toBeTruthy();
        });

        it('should change the validation to false - session expired', function () {
            var element     = angular.element('<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'),

                _fakeCreate = function (element, config) {
                    // Call the expiration callback as recaptcha would do.
                    config['expired-callback']();

                    return {
                        then: function (cb) {
                            cb();
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();

            $timeout.flush(TIMEOUT_SESSION_CAPTCHA + 1);

            expect($scope.form.$valid).toBeFalsy(); // widgetCreated
        });

        it('should call the onSuccess callback with the right params', function () {
            var element     = angular.element('<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'),

                _fakeCreate = function (element, config) {
                    config.callback('response from google');

                    return {
                        then: function (cb) {
                            cb();
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();
            $timeout.flush();

            expect($scope.onSuccess).toHaveBeenCalledWith({
                response: 'response from google',
                widgetId: undefined
            });
        });

        it('the widget should be using the setted language', function () {
            var element = angular.element('<form name="form">' +
                    '<input type="text" ng-model="something" />' +
                    '
' +
                    '</form>'),

                _fakeCreate = function (element, config) {
                    config.callback(config.lang);
                    return {
                        then: function (cb) {
                            cb();
                        }
                    };
                };

            spyOn(vcRecaptchaService, 'create').and.callFake(_fakeCreate);

            $compile(element)($scope);
            $scope.$digest();
            $timeout.flush();

            expect($scope.onSuccess).toHaveBeenCalledWith({
                response: 'es',
                widgetId: undefined
            });
        });
    });
});
<|endoftext|>


<commit_before>describe("Messages", function() {
	it("can be sent to a single listener", function() {
		var calledBack = false;

		runs(function() {
			addMessageListener("test", function() {
				calledBack = true;
			});

			emitMessage("test");
		});

		runs(function() {
			expect(calledBack).toBe(true);
		});
	});

	it("can be sent to multiple listeners", function() {
		var calledbackCount = 0;

		runs(function() {
			var inc = function() {
				calledbackCount++;
			};

			addMessageListener("test", inc);
			addMessageListener("test", inc);
			addMessageListener("test", inc);

			emitMessage("test");
		});

		runs(function() {
			expect(calledbackCount).toBe(3);
		});
	});

	it("can be sent with data", function() {
		var result = "";

		runs(function() {
			var concat = function(data) {
				result += data;
			};

			addMessageListener("test", concat);
			addMessageListener("test", concat);
			addMessageListener("test", concat);

			emitMessage("test", "fighter");
		});

		runs(function() {
			expect(result).toMatch("fighterfighterfighter");
		});
	});
});<commit_msg>Add tests for suppressing messages.<commit_after>describe("Messages", function() {
	it("can be sent to a single listener", function() {
		var calledBack = false;

		runs(function() {
			addMessageListener("test", function() {
				calledBack = true;
			});

			emitMessage("test");
		});

		runs(function() {
			expect(calledBack).toBe(true);
		});
	});

	it("can be sent to multiple listeners", function() {
		var calledbackCount = 0;

		runs(function() {
			var inc = function() {
				calledbackCount++;
			};

			addMessageListener("test", inc);
			addMessageListener("test", inc);
			addMessageListener("test", inc);

			emitMessage("test");
		});

		runs(function() {
			expect(calledbackCount).toBe(3);
		});
	});

	it("can be sent with data", function() {
		var result = "";

		runs(function() {
			var concat = function(data) {
				result += data;
			};

			addMessageListener("test", concat);
			addMessageListener("test", concat);
			addMessageListener("test", concat);

			emitMessage("test", "fighter");
		});

		runs(function() {
			expect(result).toMatch("fighterfighterfighter");
		});
	});

	it("can be suppressed", function() {
		var calledBack = false;

		runs(function() {
			addMessageListener("test", function() {
				calledBack = true;
			});

			suppressMessages("test");
			emitMessage("test");
		});

		runs(function() {
			expect(calledBack).toBe(false);
		});
	});

	it("can be unsuppressed", function() {
		var calledBack = false;

		runs(function() {
			addMessageListener("test", function() {
				calledBack = true;
			});

			suppressMessages("test");
			unsuppressMessages("test");
			emitMessage("test");
		});

		runs(function() {
			expect(calledBack).toBe(true);
		});
	});
});<|endoftext|>


<commit_before>var should = require('should');
var rest = require('restler');
var async = require('async');
var config = require('./config.js');
var redis = require("redis"),rc = redis.createClient(6379,'localhost');

var host = config.hostname;
var port = config.port;
var protocol = config.protocol;

var trans, trans1 = {};

describe('Inbox', function () {

    after(function (done) {
        this.timeout(8000);
        rc.flushall();
        rc.end();
        done();
    });
    beforeEach(function (done) {
        this.timeout(8000);
        rc.flushall();
        done();
    });

    it('Should return all the transactions', function (done) {
        this.timeout(8000); //Mocha timeout
        var trans = {
            'payload': 'Test',
            'priority': 'H',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' },
                { 'id': 'q2' }
            ]
        };

        async.series([
            function (callback) {

                rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                    trans).on('complete', function (data, response) {
                        callback();
                    });

            },
            function (callback) {

                trans.payload='Test 2'
                rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                    trans).on('complete', function (data, response) {
                        callback();
                    });

            },
            function (callback) {

                var checkQueue = function (queue, callback) {
                    rest.post(protocol + '://' + host + ':' + port + '/queue/' + queue + '/pop')
                        .on('complete', function (data, response) {
                            data.should.have.property('data');
                            data.data.length.should.be.equal(2);
                            data.data.should.include('Test');
                            data.data.should.include('Test 2');
                            callback();
                        });
                }

                checkQueue('q1', checkQueue.bind({}, 'q2', callback));
            }
        ], function () {
            done();
        });
    });

    it('Should return the high priority transaction', function (done) {

        var transLow = {
            'payload': 'Low priority',
            'priority': 'L',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' },
                { 'id': 'q2' }
            ]
        };

        var transHigh = {
            'payload': 'High priority',
            'priority': 'H',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' }
            ]
        };

        async.series([
            function (callback) {
                rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                    transLow).on('complete', function (data, response) {
                        callback();
                    });
            },
            function (callback) {
                rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                    transHigh).on('complete', function (data, response) {
                        callback();
                    });
            },
            function (callback) {
                rest.post(protocol + '://' + host + ':' + port + '/queue/q1/pop?max=1')
                    .on('complete', function (data, response) {
                        data.should.have.property('data');
                        data.data.length.should.be.equal(1);
                        (data.data.pop()).should.be.equal('High priority');
                        callback();
                    });
            }
        ], function () {
            done();
        });
    });

    it('Should return empty data (timeout)', function (done) {
        this.timeout(8000); //Mocha timeout

        var trans5 = {
            'payload': 'Test timeout',
            'priority': 'L',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' }
            ]
        };

        var funcs = [
            function (cb) {
                rest.post(protocol + '://' + host + ':' + port + '/queue/q1/pop?timeout=1',
                    {headers: {'Accept': 'application/json'}})
                    .on('complete', function (data, response) {
                        //console.log(data);
                        data.data.length.should.be.equal(0);
                        cb();

                    });
            },
            function (cb) {
                setTimeout(function () {
                    rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                        trans5).on('complete', function (data, response) {
                            cb();
                        });
                }, 2000);

            }
        ];

        var cb = function () {
            done();
        };

        async.parallel(funcs, cb);
    });

    it('Should not return empty data (timeout)', function (done) {
        this.timeout(8000); //Mocha timeout
        var trans6 = {
            'payload': 'Test timeout',
            'priority': 'L',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' }
            ]
        };

        var funcs = [
            function (cb) {
                rest.post(protocol + '://' + host + ':' + port + '/queue/q1/pop?timeout=3',
                    {headers: {'Accept': 'application/json'}})
                    .on('complete', function (data, response) {
                        data.data.length.should.be.equal(1);
                        data.data.should.include('Test timeout');
                        cb();
                    });
            },
            function (cb) {
                setTimeout(function () {
                    rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                        trans6).on('complete', function (data, response) {
                            cb();
                        });
                }, 1000);

            }
        ];

        var cb = function () {
            done();
        };

        async.parallel(funcs, cb);
    });

});
<commit_msg>improve some tests<commit_after>var should = require('should');
var rest = require('restler');
var async = require('async');
var config = require('./config.js');
var redis = require("redis"),rc = redis.createClient(6379,'localhost');

var host = config.hostname;
var port = config.port;
var protocol = config.protocol;

var trans, trans1 = {};

describe('Inbox', function () {

    after(function (done) {
        this.timeout(8000);
        rc.flushall();
        rc.end();
        done();
    });
    beforeEach(function (done) {
        this.timeout(8000);
        rc.flushall();
        done();
    });

    it('Should return all the transactions', function (done) {
        this.timeout(8000); //Mocha timeout
        var trans = {
            'payload': 'Test',
            'priority': 'H',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' },
                { 'id': 'q2' }
            ]
        };

        async.series([
            function (callback) {

                rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                    trans).on('complete', function (data, response) {
                        callback();
                    });

            },
            function (callback) {

                trans.payload='Test 2';
                rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                    trans).on('complete', function (data, response) {
                        callback();
                    });

            },
            function (callback) {

                var checkQueue = function (queue, callback) {
                    rest.post(protocol + '://' + host + ':' + port + '/queue/' + queue + '/pop')
                        .on('complete', function (data, response) {
                            data.should.not.have.property('error');
                            data.should.have.property('ok');
                            data.should.have.property('data');
                            data.data.length.should.be.equal(2);
                            data.data.should.include('Test');
                            data.data.should.include('Test 2');
                            callback();
                        });
                };

                checkQueue('q1', checkQueue.bind({}, 'q2', callback));
            }
        ], function () {
            done();
        });
    });

    it('Should return the high priority transaction', function (done) {

        var transLow = {
            'payload': 'Low priority',
            'priority': 'L',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' },
                { 'id': 'q2' }
            ]
        };

        var transHigh = {
            'payload': 'High priority',
            'priority': 'H',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' }
            ]
        };

        async.series([
            function (callback) {
                rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                    transLow).on('complete', function (data, response) {
                        callback();
                    });
            },
            function (callback) {
                rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                    transHigh).on('complete', function (data, response) {
                        callback();
                    });
            },
            function (callback) {
                rest.post(protocol + '://' + host + ':' + port + '/queue/q1/pop?max=1')
                    .on('complete', function (data, response) {
                    data.should.not.have.property('error');
                    data.should.have.property('ok');
                    data.should.have.property('data');
                    data.data.length.should.be.equal(1);
                        (data.data.pop()).should.be.equal('High priority');
                        callback();
                    });
            }
        ], function () {
            done();
        });
    });

    it('Should return empty data (timeout)', function (done) {
        this.timeout(8000); //Mocha timeout

        var trans5 = {
            'payload': 'Test timeout',
            'priority': 'L',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' }
            ]
        };

        var funcs = [
            function (cb) {
                rest.post(protocol + '://' + host + ':' + port + '/queue/q1/pop?timeout=1',
                    {headers: {'Accept': 'application/json'}})
                    .on('complete', function (data, response) {
                        //console.log(data);
                       data.should.not.have.property('error');
                       data.should.have.property('ok');
                       data.should.have.property('data');
                       data.data.length.should.be.equal(0);
                        cb();

                    });
            },
            function (cb) {
                setTimeout(function () {
                    rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                        trans5).on('complete', function (data, response) {
                            cb();
                        });
                }, 2000);

            }
        ];

        var cb = function () {
            done();
        };

        async.parallel(funcs, cb);
    });

    it('Should not return empty data (timeout)', function (done) {
        this.timeout(8000); //Mocha timeout
        var trans6 = {
            'payload': 'Test timeout',
            'priority': 'L',
            'callback': protocol + '://foo.bar',
            'queue': [
                { 'id': 'q1' }
            ]
        };

        var funcs = [
            function (cb) {
                rest.post(protocol + '://' + host + ':' + port + '/queue/q1/pop?timeout=3',
                    {headers: {'Accept': 'application/json'}})
                    .on('complete', function (data, response) {
                        data.should.not.have.property('error');
                        data.should.have.property('ok');
                        data.should.have.property('data');
                        data.data.length.should.be.equal(1);
                        data.data.should.include('Test timeout');
                        cb();
                    });
            },
            function (cb) {
                setTimeout(function () {
                    rest.postJson(protocol + '://' + host + ':' + port + '/trans',
                        trans6).on('complete', function (data, response) {
                            cb();
                        });
                }, 1000);

            }
        ];

        var cb = function () {
            done();
        };

        async.parallel(funcs, cb);
    });

});
<|endoftext|>


<commit_before>var linkify = require('../public/javascripts/transform');
var tests = {};
var valid, invalid, inline;

valid = {
  values: [
    'http://www.example.org/',
    'https://www.example.org',
    'http://www.example.co.uk/',
    'https://example.org',
    'chat.meatspac.es',
    '(chat.meatspac.es)',
    'chat.meatspac.es.',
    'chat.meatspac.es/channel',
    'https://example.org./path/to/stuff',
    'http://www.example.org:8080/',
    'http://example.org:8080/',
    'This is a link... example.org.',
    'This is a link... example.org, take a look!',
    '(This is a link... example.org)',
    'Link: chat.meatspac.es/channel?',
    'Link: chat.meatspac.es/channel:',
    'Link: chat.meatspac.es/channel;',
    'Link: chat.meatspac.es/channel!',
    '(This is a link... chat.meatspac.es/channel)',
    'This is a link... chat.meatspac.es/channel.',
    'This is a link... chat.meatspac.es/channel, or not',
    'http://example.com/channel/bar(parens)',
    'http://example.com/comma,here/',
    '@twitter',
    '@a @b @c',
    '@a @b @c',
    '@a @b @c',
    '/r/puppies',
    '1.1.1.1',
    'http://1.1.1.1',
    'http://meat.spaces should be treated like a link',
    'test.com/"/onmouseover="alert(document.cookie)',
    // Stuff is escaped before it gets to linkify via the .textContent API
    'test.com/">&lt/a>&ltscript>alert(document.cookie);&lt/script>&lta href="http://example.com',
    // XSS #96
    'x.it/onmouseover=alert(null);//\nx.it/onmouseover=alert(null);//',
    'test.com/onmouseover=alert(1)// est.com/onmouseover=alert(1)//',
    // Don't encode the same portion of text twice
    'test.com/@test'
  ],

  expects: [
    'http://www.example.org/',
    'https://www.example.org',
    'http://www.example.co.uk/',
    'https://example.org',
    'chat.meatspac.es',
    'chat.meatspac.es',
    'chat.meatspac.es',
    'chat.meatspac.es/channel',
    'https://example.org./path/to/stuff',
    'http://www.example.org:8080/',
    'http://example.org:8080/',
    'example.org',
    'example.org',
    'example.org',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'http://example.com/channel/bar(parens)',
    'http://example.com/comma,here/',
    '@twitter',
    '@a',
    '@b',
    '@c',
    '/r/puppies',
    '1.1.1.1',
    'http://1.1.1.1',
    'http://meat.spaces should be treated like a link',
    'test.com/"/onmouseover="alert(document.cookie)',
    'test.com/">&lt/a>&ltscript>alert(document.cookie);&lt/script>&lta href="http://example.com',
    'x.it/onmouseover=alert(null);//\nx.it/onmouseover=alert(null);//',
    'test.com/onmouseover=alert(1)// est.com/onmouseover=alert(1)//',
    'test.com/@test'
  ]
};

valid.values.forEach(function(value, i) {
  tests[value] = function(test) {
    test.ok(linkify(value).indexOf(valid.expects[i]) !== -1);
    test.done();
  };
});

invalid = {
  values: [
    '7.0.3',
    'a.0.3',
    'a.b.c',
    'what happens when it\'s inline? 1.1.1 like that?',
    'meat.spaces is not a link'
  ],
  expects: [
    '7.0.3',
    'a.0.3',
    'a.b.c',
    'what happens when it\'s inline? 1.1.1 like that?',
    'meat.spaces is not a link'
  ]
};

invalid.values.forEach(function(value, i) {
  tests[value] = function(test) {
    test.equal(linkify(value), invalid.expects[i]);
    test.done();
  };
});

inline = {
  values: [
    'An inline link, like example.com, is replaced inline',
    'An inline link, like http://example.com, is replaced inline',
    'An inline twitter handle, like @twitter, is replaced inline',
    'An inline subreddit, like /r/puppies, is replaced inline',
    'All linkables, ie. example.com, @twitter, and /r/puppies are replaced inline',
    'Hey Edna is doing an AMA over on /r/iama, check it out http://www.reddit.com/r/IAmA/comments/1phhx1/we_are_mozilla_ask_us_anything'
  ],
  expects: [
    'An inline link, like example.com, is replaced inline',
    'An inline link, like http://example.com, is replaced inline',
    'An inline twitter handle, like @twitter, is replaced inline',
    'An inline subreddit, like /r/puppies, is replaced inline',
    'All linkables, ie. example.com, @twitter, and /r/puppies are replaced inline',
    'Hey Edna is doing an AMA over on /r/iama, check it out http://www.reddit.com/r/IAmA/comments/1phhx1/we_are_mozilla_ask_us_anything'
  ]
};

inline.values.forEach(function(value, i) {
  tests[value] = function(test) {
    test.equal(linkify(value), inline.expects[i]);
    test.done();
  };
});

module.exports = tests;
<commit_msg>fixing tests: linkify => transform<commit_after>var transform = require('../public/javascripts/transform');
var tests = {};
var valid, invalid, inline;

valid = {
  values: [
    'http://www.example.org/',
    'https://www.example.org',
    'http://www.example.co.uk/',
    'https://example.org',
    'chat.meatspac.es',
    '(chat.meatspac.es)',
    'chat.meatspac.es.',
    'chat.meatspac.es/channel',
    'https://example.org./path/to/stuff',
    'http://www.example.org:8080/',
    'http://example.org:8080/',
    'This is a link... example.org.',
    'This is a link... example.org, take a look!',
    '(This is a link... example.org)',
    'Link: chat.meatspac.es/channel?',
    'Link: chat.meatspac.es/channel:',
    'Link: chat.meatspac.es/channel;',
    'Link: chat.meatspac.es/channel!',
    '(This is a link... chat.meatspac.es/channel)',
    'This is a link... chat.meatspac.es/channel.',
    'This is a link... chat.meatspac.es/channel, or not',
    'http://example.com/channel/bar(parens)',
    'http://example.com/comma,here/',
    '@twitter',
    '@a @b @c',
    '@a @b @c',
    '@a @b @c',
    '/r/puppies',
    '1.1.1.1',
    'http://1.1.1.1',
    'http://meat.spaces should be treated like a link',
    'test.com/"/onmouseover="alert(document.cookie)',
    // Stuff is escaped before it gets to transform via the .textContent API
    'test.com/">&lt/a>&ltscript>alert(document.cookie);&lt/script>&lta href="http://example.com',
    // XSS #96
    'x.it/onmouseover=alert(null);//\nx.it/onmouseover=alert(null);//',
    'test.com/onmouseover=alert(1)// est.com/onmouseover=alert(1)//',
    // Don't encode the same portion of text twice
    'test.com/@test'
  ],

  expects: [
    'http://www.example.org/',
    'https://www.example.org',
    'http://www.example.co.uk/',
    'https://example.org',
    'chat.meatspac.es',
    'chat.meatspac.es',
    'chat.meatspac.es',
    'chat.meatspac.es/channel',
    'https://example.org./path/to/stuff',
    'http://www.example.org:8080/',
    'http://example.org:8080/',
    'example.org',
    'example.org',
    'example.org',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'chat.meatspac.es/channel',
    'http://example.com/channel/bar(parens)',
    'http://example.com/comma,here/',
    '@twitter',
    '@a',
    '@b',
    '@c',
    '/r/puppies',
    '1.1.1.1',
    'http://1.1.1.1',
    'http://meat.spaces should be treated like a link',
    'test.com/"/onmouseover="alert(document.cookie)',
    'test.com/">&lt/a>&ltscript>alert(document.cookie);&lt/script>&lta href="http://example.com',
    'x.it/onmouseover=alert(null);//\nx.it/onmouseover=alert(null);//',
    'test.com/onmouseover=alert(1)// est.com/onmouseover=alert(1)//',
    'test.com/@test'
  ]
};

valid.values.forEach(function(value, i) {
  tests[value] = function(test) {
    test.ok(transform(value).indexOf(valid.expects[i]) !== -1);
    test.done();
  };
});

invalid = {
  values: [
    '7.0.3',
    'a.0.3',
    'a.b.c',
    'what happens when it\'s inline? 1.1.1 like that?',
    'meat.spaces is not a link'
  ],
  expects: [
    '7.0.3',
    'a.0.3',
    'a.b.c',
    'what happens when it\'s inline? 1.1.1 like that?',
    'meat.spaces is not a link'
  ]
};

invalid.values.forEach(function(value, i) {
  tests[value] = function(test) {
    test.equal(transform(value), invalid.expects[i]);
    test.done();
  };
});

inline = {
  values: [
    'An inline link, like example.com, is replaced inline',
    'An inline link, like http://example.com, is replaced inline',
    'An inline twitter handle, like @twitter, is replaced inline',
    'An inline subreddit, like /r/puppies, is replaced inline',
    'All linkables, ie. example.com, @twitter, and /r/puppies are replaced inline',
    'Hey Edna is doing an AMA over on /r/iama, check it out http://www.reddit.com/r/IAmA/comments/1phhx1/we_are_mozilla_ask_us_anything'
  ],
  expects: [
    'An inline link, like example.com, is replaced inline',
    'An inline link, like http://example.com, is replaced inline',
    'An inline twitter handle, like @twitter, is replaced inline',
    'An inline subreddit, like /r/puppies, is replaced inline',
    'All linkables, ie. example.com, @twitter, and /r/puppies are replaced inline',
    'Hey Edna is doing an AMA over on /r/iama, check it out http://www.reddit.com/r/IAmA/comments/1phhx1/we_are_mozilla_ask_us_anything'
  ]
};

inline.values.forEach(function(value, i) {
  tests[value] = function(test) {
    test.equal(transform(value), inline.expects[i]);
    test.done();
  };
});

module.exports = tests;
<|endoftext|>


<commit_before>import {Dialog} from 'ui/dialog';
import {expect} from 'chai';
import {jsdom} from 'jsdom';
import constant from 'lodash.constant';
import sinon from 'sinon';
import shuffle from 'lodash.shuffle';

import datasetPolyfill from '../dataset-polyfill-jsdom';

function random_string(len) {
	return shuffle('abcdefghijhklmnopqrstuvwxyz0123456789').slice(0, len).join('');
}

describe('Dialog({aboutToClose, className, content, id})', () => {
	beforeEach(() => {
		const document = jsdom('<!DOCTYPE html>');
		global.document = document;
		global.window = document.defaultView;
		datasetPolyfill(global.window);
	});

	afterEach(() => {
		window.close();
	});

	describe('run()', () => {
		it('returns a promise', () => {
			const dialog = Dialog({content: ''});
			expect(dialog.run()).to.be.a('promise');
		});
		it('creates exactly one body > div#modal-overlay element', () => {
			const dialog = Dialog({content: ''});
			dialog.run();
			expect(document.querySelectorAll('body > div#modal-overlay'))
				.to.have.lengthOf(1);
		});
		it('creates exactly one body > div.dialog element', () => {
			const dialog = Dialog({content: ''});
			dialog.run();
			expect(document.querySelectorAll('body > div.dialog'))
				.to.have.lengthOf(1);
		});
		it('creates exactly one \'cancel\' button', () => {
			const dialog = Dialog({content: ''});
			dialog.run();
			expect(document.querySelectorAll('body > .dialog button[data-role="cancel"]'))
				.to.have.lengthOf(1);
		});
		it('creates exactly one \'ok\' button', () => {
			const dialog = Dialog({content: ''});
			dialog.run();
			expect(document.querySelectorAll('body > .dialog button[data-role="ok"]'))
				.to.have.lengthOf(1);
		});
		it('adds the specified className to the div.dialog element', () => {
			const dialog = Dialog({content: '', className: ['foo', 'bar']});
			dialog.run();
			expect(document.querySelector('body > .dialog').className.split(' '))
				.to.have.lengthOf(3);
		});
		it('adds the specified id to the div.dialog element', () => {
			const dialog = Dialog({content: '', id: 'foo'});
			dialog.run();
			expect(document.querySelector('body > div.dialog').id).to.equal('foo');
		});
		it('adds the specified content string to the div.dialog element', () => {
			const dialog = Dialog({content: 'foo'});
			dialog.run();
			expect(document.querySelector('body > .dialog > .content-wrapper').innerHTML).to.equal('foo');
		});
		it('adds the specified content element to the div.dialog element', () => {
			const content = document.createElement('div');
			const dialog = Dialog({content});
			content.id = 'foo';
			dialog.run();
			expect(document.querySelectorAll('body > .dialog > .content-wrapper > div#foo'))
				.to.have.lengthOf(1);
		});
		it('calls back aboutToClose with \'ok\' when ok button is clicked', () => {
			const aboutToClose = sinon.spy();
			const dialog = Dialog({aboutToClose, content: ''});
			dialog.run();
			document.querySelector('body > .dialog button[data-role="ok"]').click();
			expect(aboutToClose).to.have.been.calledWith('ok');
		});
		it('calls back aboutToClose with \'cancel\' when cancel button is clicked', () => {
			const aboutToClose = sinon.spy();
			const dialog = Dialog({aboutToClose, content: ''});
			dialog.run();
			document.querySelector('body > .dialog button[data-role="cancel"]').click();
			expect(aboutToClose).to.have.been.calledWith('cancel');
		});
		it('fulfills the returned promise with the value returned by aboutToClose', () => {
			const aboutToClose = constant(random_string(12));
			const dialog = Dialog({aboutToClose, content: ''});
			const promise = dialog.run();
			document.querySelector('body > .dialog button[data-role="cancel"]').click();
			return expect(promise).to.eventually.equal(aboutToClose());
		});
		it('removes body > div#modal-overlay element from the DOM when a button is clicked', () => {
			const dialog = Dialog({content: ''});
			dialog.run();
			document.querySelector('body > .dialog button[data-role="cancel"]').click();
			expect(document.querySelectorAll('body > #modal-overlay'))
				.to.have.lengthOf(0);
		});
		it('removes body > div.dialog element from the DOM when a button is clicked', () => {
			const dialog = Dialog({content: ''});
			dialog.run();
			document.querySelector('body > .dialog button[data-role="cancel"]').click();
			expect(document.querySelectorAll('body > .dialog'))
				.to.have.lengthOf(0);
		});
	});
});
<commit_msg>Fix dialog tests<commit_after>import {default as Dialog} from 'ui/dialog';
import View from 'ui/view';

import {expect} from 'chai';
import {jsdom} from 'jsdom';
import constant from 'lodash.constant';
import sinon from 'sinon';
import shuffle from 'lodash.shuffle';

import datasetPolyfill from '../dataset-polyfill-jsdom';

function random_string(len) {
	return shuffle('abcdefghijhklmnopqrstuvwxyz0123456789').slice(0, len).join('');
}

describe('Dialog({el, childView, classNames, buttons, aboutToClose})', () => {
	beforeEach(() => {
		const document = jsdom('<!DOCTYPE html>');
		global.document = document;
		global.window = document.defaultView;
		datasetPolyfill(global.window);
	});

	afterEach(() => {
		window.close();
	});

	describe('run()', () => {
		it('returns a promise', () => {
			const childView = View();
			const dialog = Dialog({childView});
			expect(dialog.run()).to.be.a('promise');
		});
		it('inserts exactly one .dialog element in the wrapping element', () => {
			const childView = View();
			const dialog = Dialog({childView});
			dialog.run();
			expect(document.querySelectorAll('body > .dialog'))
				.to.have.lengthOf(1);
		});
		it('inserts exactly one .dialog-button-box in the .dialog element', () => {
			const childView = View();
			const dialog = Dialog({childView});
			dialog.run();
			expect(document.querySelectorAll('body > .dialog > .dialog-button-box'))
				.to.have.lengthOf(1);
		});
		it('inserts the childView in the .dialog element', () => {
			const childView = View({id: 'child-view-id'});
			const dialog = Dialog({childView});
			dialog.run();
			expect(document.querySelectorAll('body > .dialog > #child-view-id'))
				.to.have.lengthOf(1);
		});
		it('calls back aboutToClose with \'ok\' when ok button is clicked', () => {
			const aboutToClose = sinon.spy();
			const childView = View({id: 'child-view-id'});
			const dialog = Dialog({childView, aboutToClose});
			dialog.run();
			document.querySelector('body > .dialog button[data-role="ok"]').click();
			expect(aboutToClose).to.have.been.calledWith('ok');
		});
		it('calls back aboutToClose with \'cancel\' when cancel button is clicked', () => {
			const aboutToClose = sinon.spy();
			const childView = View({id: 'child-view-id'});
			const dialog = Dialog({childView, aboutToClose});
			dialog.run();
			document.querySelector('body > .dialog button[data-role="cancel"]').click();
			expect(aboutToClose).to.have.been.calledWith('cancel');
		});
		it('fulfills the returned promise with the value returned by aboutToClose', () => {
			const aboutToClose = constant(random_string(12));
			const childView = View({id: 'child-view-id'});
			const dialog = Dialog({childView, aboutToClose});
			dialog.run();
			const promise = dialog.run();
			document.querySelector('body > .dialog button[data-role="cancel"]').click();
			return expect(promise).to.eventually.equal(aboutToClose());
		});
		it('removes the dialog from the DOM when a button is clicked', () => {
			const childView = View({id: 'child-view-id'});
			const dialog = Dialog({childView});
			dialog.run();
			document.querySelector('body > .dialog button[data-role="cancel"]').click();
			expect(document.querySelectorAll('body > .dialog'))
				.to.have.lengthOf(0);
		});
	});
});
<|endoftext|>


<commit_before>"use strict"

const app = require('express')()

app.get('/', (req, res) => {
    let html = [200, 300, 400, 500]
        .map((statusCode) => `<a href="${statusCode}">${statusCode}</a><br />`)
        .join('')

    console.log(`Visit on /`)

    res.writeHead(200, {'Content-Type': 'text/html'})
    res.end(html)
});

app.get('/:responseCode', (req, res) => {
    let responseCode = req.params.responseCode

    console.log(`Visit on ${responseCode}`)

    res.status(responseCode).send(`Responsecode ${responseCode}`)
});

let server = app.listen(4020,  () => {
    let host = 'localhost'
    let port = server.address().port

    console.log('Testing server listening at http://%s:%s', host, port)
});
<commit_msg>fix tests<commit_after>"use strict"

let app = require('express')()

app.get('/', (req, res) => {
    let html = [200, 300, 400, 500]
        .map((statusCode) => `<a href="${statusCode}">${statusCode}</a><br />`)
        .join('')

    console.log(`Visit on /`)

    res.writeHead(200, {'Content-Type': 'text/html'})
    res.end(html)
});

app.get('/:responseCode', (req, res) => {
    let responseCode = req.params.responseCode

    console.log(`Visit on ${responseCode}`)

    res.status(responseCode).send(`Responsecode ${responseCode}`)
});

let server = app.listen(4020,  () => {
    let host = 'localhost'
    let port = server.address().port

    console.log('Testing server listening at http://%s:%s', host, port)
});
<|endoftext|>