<commit_before>// Dependencies:
//   miner/js/plot-util.js
//   d3.js

function mouseover(d) {
    var focus = d3.select("g.focus");
    translate_value = "translate(" + mouseover.conf.xscale(d.x);
    // var text_anchor = mouseover.conf.xscale(d.x) > d3.mean(mouseover.conf.xscale.range()) ? "end" : "start";
    if (conf.stacked) {
      translate_value = translate_value + mouseover.conf.yscale(d3.max([d.y0, d.y])) + ")");
      }
    else {
      translate_value = translate_value + mouseover.conf.yscale(d.y) + ")");
      }
    focus.attr("transform", translate_value);
    console.log('translate = ' + translate_value);
    var tt = d.heading + ": " + (d.y).toFixed(1) + "%";
    var text = focus.select("text").text(tt).node();
    var SVGRect = text.getBBox();
    focus.select("rect").attr("x", SVGRect.x).attr("y", SVGRect.y).attr("width", SVGRect.width).attr("height", SVGRect.height);
    console.log(d);
    console.log(mouseover.conf.xscale(d.x));
    console.log(d3.mean(mouseover.conf.xscale.range()));
    console.log("translate(" + mouseover.conf.xscale(d.x) + "," + mouseover.conf.yscale(d.y0) + ")");
}
mouseover.conf = null;

function mouseout(d) {
  var focus = d3.select("g.focus");
  focus.select("text").text("");
  focus.select("rect").attr("width", 0).attr("height", 0);

  // FIXME: doesn't work
  // selector = ".row-"+d.row + ".col-"+d.col;
  // console.log('mouse out selector: ' + selector);
  // console.log(d);
  // d3.select().classed('hover', false);
}

function bar_plot(d3data, conf) {
    default_conf         = {"plot_container_id": "plot_container", "container_width": 960, "container_height": 500, "margin": {top: 30, right: 80, bottom: 30, left: 50}};

    conf                   = typeof conf                   == "undefined" ? default_conf                                : conf;
    conf.plot_container_id = typeof conf.plot_container_id == "undefined" ? default_conf.plot_container_id              : conf.plot_container_id;
    conf.margin            = typeof conf.margin            == "undefined" ? default_conf.margin                         : conf.margin;
    conf.container_width   = typeof conf.container_width   == "undefined" ? default_conf.container_width                : conf.container_width;
    conf.container_height  = typeof conf.container_height  == "undefined" ? default_conf.container_height               : conf.container_height;
    conf.width             = typeof conf.width             == "undefined" ? conf.container_width - conf.margin.left - conf.margin.right  : conf.width;
    conf.height            = typeof conf.height            == "undefined" ? conf.container_height - conf.margin.top  - conf.margin.bottom : conf.height;

    xlabel  = typeof conf.xlabel == "undefined" ? d3data[0][0] : conf.xlabel;
    xfield  = typeof d3data[0][0] == "string" ? d3data[0][0] : conf.xlabel;
    ylabel  = typeof conf.ylabel == "undefined" ? d3data[1][0] : conf.ylabel;
    ylabels = ((typeof conf.ylabel == "object") && (d3data.length == (1 + conf.ylabel.length))) ? conf.ylabel : d3data.slice(1).map(function(d) {return d[0];});
    var num_layers = ylabels.length;

    console.log(ylabels);
    console.log(xfield);

    // TODO: standardize on the "series" data structure below which is also used in the line-plot
    var layers = split_d3_series(d3data);
    for (var i=0; i<layers.length; i++) {
        for (var j=0; j<layers[i].length; j++) {
            layers[i][j].series = layers[i];
            layers[i][j].layer  = layers[i];
            layers[i][j].col = i;
            layers[i][j].row = j;
            layers[i][j].heading = ylabels[i];
        }
    }
    console.log('layers (d3data as arrays of objects with x,y properties)');
    console.log(layers);

    d3data = arrays_as_objects(d3data);
    var num_stacks = d3data.length; // number of samples per layer

    conf.xscale = d3.scale.ordinal()
        .domain(d3data.map(function(d) { return d[xfield]; }))
        .rangeRoundBands([0, conf.width], 0.1);
    conf.xlabel = "Horizontal Value (Time?)";
    conf.yscale = d3.scale.linear().range([conf.height, 0]);
    conf.ylabel = "Vertical Value";

    d3data.sort(function(a, b) { return a[xfield] - b[xfield]; });

    var color = d3.scale.linear()
        .domain([0, num_layers - 1])
        .range(["#aad", "#556"]);

    console.log('all_series');
    var all_series = ylabels.map(function(name) {
      var series = { name: name, values: null };
      series.values = d3data.map(function(d) {
            return { series: series, x: d[xfield], y: +d[name] };
      }); // d3data.map(function(d) {
      return series;
    });
    console.log(all_series);

    var ymin = d3.min(all_series, function(series) { return d3.min(series.values, function(d) { console.log(d); return d.y; }); });
    var ymax = d3.max(all_series, function(series) { return d3.max(series.values, function(d) { console.log(d); return d.y; }); });

    console.log([ymin, ymax]);

    conf.yGroupMax = ymax;
    conf.yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });

    // plot starts out stacked
    conf.yscale = d3.scale.linear()
        .domain([0, conf.yStackMax])
        .range([conf.height, 0]);

    var svg = create_svg_element(conf);

    // don't put a tick mark on bar-plots
    var xAxis = create_xaxis(conf).tickSize(0).tickPadding(6).orient("bottom");

    var yAxis = create_yaxis(conf).ticks(10, "%");

    // var yAxis = d3.svg.axis()
    //     .scale(conf.yscale)
    //     .orient("left");

    // // need something like this here to append the series data to each rect
    // var series = svg.selectAll(".series")
    //     .data(all_series)
    //   .enter().append("g")
    //     .attr("class", "series");

    var layer = svg.selectAll(".layer")
        .data(layers)
      .enter().append("g")
        .attr("class", "layer")
        .style("fill", function(d, i) { return color(i); });

      // chart.selectAll(".bar")
      //     .data(d3data)
      //   .enter().append("rect")
      //     .attr("class", "bar")
      //     .attr("x", function(d) { return x(d.name); })
      //     .attr("y", function(d) { return conf.yscale(d.value); })
      //     .attr("height", function(d) { return conf.height - y(d.value); })
      //     .attr("width", x.rangeBand());
    var rect_element;

    mouseover.conf = conf;
    mouseout.conf = conf;
    var rect = layer.selectAll("rect")
        .data(function(d) { console.log(d); return d; })
      .enter().append("rect")
        .attr("x", function(d) { return conf.xscale(d[xfield]); })
        .attr("y", conf.height)
        .attr("width", conf.xscale.rangeBand())
        .attr("class", function(d) { return "bar row-" + d.row + " col-" + d.col; })
        .attr("height", 0)
        .on("mouseover", mouseover)
        .on("mouseout", mouseout);
    //    .on("click", mouseclick);

    rect.transition()
        .delay(function(d, i) { return i * 10; })
        .attr("y", function(d) { return conf.yscale(d.y0 + d.y); })
        .attr("height", function(d) { return conf.yscale(d.y0) - conf.yscale(d.y0 + d.y); });

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + conf.height + ")")
        .call(xAxis);

    d3.selectAll("input").on("change", change);

    // focus must be the last SVG element so it will be on top
    var focus = svg.append("g").attr("class", "focus");
    var text = focus.append("text").attr("x", 0).attr("y", -12).attr("text-anchor", "start");
    focus = insert_text_background(focus);

    if (typeof conf.stacked == "undefined") {
        var timeout = setTimeout(function() {
          d3.select("input[value=\"grouped\"]").property("checked", true).each(change);
        }, 2000); }
    else {
        d3.select(conf.stacked == true ? "input[value=\"stacked\"]" : "input[value=\"grouped\"]").property("checked", true).each(change);
    }

    function change() {
      clearTimeout(timeout);
      if (this.value === "grouped") { transitionGrouped(); }
      else { transitionStacked(); }
    }

    function transitionGrouped() {
      conf.yscale.domain([0, conf.yGroupMax]);

      rect.transition()
          .duration(500)
          .delay(function(d, i) { return i * 10; })
          .attr("x", function(d, i, j) { return conf.xscale(d[xfield]) + conf.xscale.rangeBand() / num_layers * j; })
          .attr("width", conf.xscale.rangeBand() / num_layers)
        .transition()
          .attr("y", function(d) { return conf.yscale(d.y); })
          .attr("height", function(d) { return conf.height - conf.yscale(d.y); });
      conf.stacked = false;
    }

    function transitionStacked() {
      conf.yscale.domain([0, conf.yStackMax]);

      rect.transition()
          .duration(500)
          .delay(function(d, i) { return i * 10; })
          .attr("y", function(d) { return conf.yscale(d.y0 + d.y); })
          .attr("height", function(d) { return conf.yscale(d.y0) - conf.yscale(d.y0 + d.y); })
        .transition()
          .attr("x", function(d) { return conf.xscale(d[xfield]); })
          .attr("width", conf.xscale.rangeBand());
      conf.stacked = true;
    }

} // function bar_plot(d3data)
<commit_msg>del )<commit_after>// Dependencies:
//   miner/js/plot-util.js
//   d3.js

function mouseover(d) {
    var focus = d3.select("g.focus");
    translate_value = "translate(" + mouseover.conf.xscale(d.x);
    // var text_anchor = mouseover.conf.xscale(d.x) > d3.mean(mouseover.conf.xscale.range()) ? "end" : "start";
    if (conf.stacked) {
      translate_value = translate_value + mouseover.conf.yscale(d3.max([d.y0, d.y])) + ")";
      }
    else {
      translate_value = translate_value + mouseover.conf.yscale(d.y) + ")";
      }
    focus.attr("transform", translate_value);
    console.log('translate = ' + translate_value);
    var tt = d.heading + ": " + (d.y).toFixed(1) + "%";
    var text = focus.select("text").text(tt).node();
    var SVGRect = text.getBBox();
    focus.select("rect").attr("x", SVGRect.x).attr("y", SVGRect.y).attr("width", SVGRect.width).attr("height", SVGRect.height);
    console.log(d);
    console.log(mouseover.conf.xscale(d.x));
    console.log(d3.mean(mouseover.conf.xscale.range()));
    console.log("translate(" + mouseover.conf.xscale(d.x) + "," + mouseover.conf.yscale(d.y0) + ")");
}
mouseover.conf = null;

function mouseout(d) {
  var focus = d3.select("g.focus");
  focus.select("text").text("");
  focus.select("rect").attr("width", 0).attr("height", 0);

  // FIXME: doesn't work
  // selector = ".row-"+d.row + ".col-"+d.col;
  // console.log('mouse out selector: ' + selector);
  // console.log(d);
  // d3.select().classed('hover', false);
}

function bar_plot(d3data, conf) {
    default_conf         = {"plot_container_id": "plot_container", "container_width": 960, "container_height": 500, "margin": {top: 30, right: 80, bottom: 30, left: 50}};

    conf                   = typeof conf                   == "undefined" ? default_conf                                : conf;
    conf.plot_container_id = typeof conf.plot_container_id == "undefined" ? default_conf.plot_container_id              : conf.plot_container_id;
    conf.margin            = typeof conf.margin            == "undefined" ? default_conf.margin                         : conf.margin;
    conf.container_width   = typeof conf.container_width   == "undefined" ? default_conf.container_width                : conf.container_width;
    conf.container_height  = typeof conf.container_height  == "undefined" ? default_conf.container_height               : conf.container_height;
    conf.width             = typeof conf.width             == "undefined" ? conf.container_width - conf.margin.left - conf.margin.right  : conf.width;
    conf.height            = typeof conf.height            == "undefined" ? conf.container_height - conf.margin.top  - conf.margin.bottom : conf.height;

    xlabel  = typeof conf.xlabel == "undefined" ? d3data[0][0] : conf.xlabel;
    xfield  = typeof d3data[0][0] == "string" ? d3data[0][0] : conf.xlabel;
    ylabel  = typeof conf.ylabel == "undefined" ? d3data[1][0] : conf.ylabel;
    ylabels = ((typeof conf.ylabel == "object") && (d3data.length == (1 + conf.ylabel.length))) ? conf.ylabel : d3data.slice(1).map(function(d) {return d[0];});
    var num_layers = ylabels.length;

    console.log(ylabels);
    console.log(xfield);

    // TODO: standardize on the "series" data structure below which is also used in the line-plot
    var layers = split_d3_series(d3data);
    for (var i=0; i<layers.length; i++) {
        for (var j=0; j<layers[i].length; j++) {
            layers[i][j].series = layers[i];
            layers[i][j].layer  = layers[i];
            layers[i][j].col = i;
            layers[i][j].row = j;
            layers[i][j].heading = ylabels[i];
        }
    }
    console.log('layers (d3data as arrays of objects with x,y properties)');
    console.log(layers);

    d3data = arrays_as_objects(d3data);
    var num_stacks = d3data.length; // number of samples per layer

    conf.xscale = d3.scale.ordinal()
        .domain(d3data.map(function(d) { return d[xfield]; }))
        .rangeRoundBands([0, conf.width], 0.1);
    conf.xlabel = "Horizontal Value (Time?)";
    conf.yscale = d3.scale.linear().range([conf.height, 0]);
    conf.ylabel = "Vertical Value";

    d3data.sort(function(a, b) { return a[xfield] - b[xfield]; });

    var color = d3.scale.linear()
        .domain([0, num_layers - 1])
        .range(["#aad", "#556"]);

    console.log('all_series');
    var all_series = ylabels.map(function(name) {
      var series = { name: name, values: null };
      series.values = d3data.map(function(d) {
            return { series: series, x: d[xfield], y: +d[name] };
      }); // d3data.map(function(d) {
      return series;
    });
    console.log(all_series);

    var ymin = d3.min(all_series, function(series) { return d3.min(series.values, function(d) { console.log(d); return d.y; }); });
    var ymax = d3.max(all_series, function(series) { return d3.max(series.values, function(d) { console.log(d); return d.y; }); });

    console.log([ymin, ymax]);

    conf.yGroupMax = ymax;
    conf.yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });

    // plot starts out stacked
    conf.yscale = d3.scale.linear()
        .domain([0, conf.yStackMax])
        .range([conf.height, 0]);

    var svg = create_svg_element(conf);

    // don't put a tick mark on bar-plots
    var xAxis = create_xaxis(conf).tickSize(0).tickPadding(6).orient("bottom");

    var yAxis = create_yaxis(conf).ticks(10, "%");

    // var yAxis = d3.svg.axis()
    //     .scale(conf.yscale)
    //     .orient("left");

    // // need something like this here to append the series data to each rect
    // var series = svg.selectAll(".series")
    //     .data(all_series)
    //   .enter().append("g")
    //     .attr("class", "series");

    var layer = svg.selectAll(".layer")
        .data(layers)
      .enter().append("g")
        .attr("class", "layer")
        .style("fill", function(d, i) { return color(i); });

      // chart.selectAll(".bar")
      //     .data(d3data)
      //   .enter().append("rect")
      //     .attr("class", "bar")
      //     .attr("x", function(d) { return x(d.name); })
      //     .attr("y", function(d) { return conf.yscale(d.value); })
      //     .attr("height", function(d) { return conf.height - y(d.value); })
      //     .attr("width", x.rangeBand());
    var rect_element;

    mouseover.conf = conf;
    mouseout.conf = conf;
    var rect = layer.selectAll("rect")
        .data(function(d) { console.log(d); return d; })
      .enter().append("rect")
        .attr("x", function(d) { return conf.xscale(d[xfield]); })
        .attr("y", conf.height)
        .attr("width", conf.xscale.rangeBand())
        .attr("class", function(d) { return "bar row-" + d.row + " col-" + d.col; })
        .attr("height", 0)
        .on("mouseover", mouseover)
        .on("mouseout", mouseout);
    //    .on("click", mouseclick);

    rect.transition()
        .delay(function(d, i) { return i * 10; })
        .attr("y", function(d) { return conf.yscale(d.y0 + d.y); })
        .attr("height", function(d) { return conf.yscale(d.y0) - conf.yscale(d.y0 + d.y); });

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + conf.height + ")")
        .call(xAxis);

    d3.selectAll("input").on("change", change);

    // focus must be the last SVG element so it will be on top
    var focus = svg.append("g").attr("class", "focus");
    var text = focus.append("text").attr("x", 0).attr("y", -12).attr("text-anchor", "start");
    focus = insert_text_background(focus);

    if (typeof conf.stacked == "undefined") {
        var timeout = setTimeout(function() {
          d3.select("input[value=\"grouped\"]").property("checked", true).each(change);
        }, 2000); }
    else {
        d3.select(conf.stacked == true ? "input[value=\"stacked\"]" : "input[value=\"grouped\"]").property("checked", true).each(change);
    }

    function change() {
      clearTimeout(timeout);
      if (this.value === "grouped") { transitionGrouped(); }
      else { transitionStacked(); }
    }

    function transitionGrouped() {
      conf.yscale.domain([0, conf.yGroupMax]);

      rect.transition()
          .duration(500)
          .delay(function(d, i) { return i * 10; })
          .attr("x", function(d, i, j) { return conf.xscale(d[xfield]) + conf.xscale.rangeBand() / num_layers * j; })
          .attr("width", conf.xscale.rangeBand() / num_layers)
        .transition()
          .attr("y", function(d) { return conf.yscale(d.y); })
          .attr("height", function(d) { return conf.height - conf.yscale(d.y); });
      conf.stacked = false;
    }

    function transitionStacked() {
      conf.yscale.domain([0, conf.yStackMax]);

      rect.transition()
          .duration(500)
          .delay(function(d, i) { return i * 10; })
          .attr("y", function(d) { return conf.yscale(d.y0 + d.y); })
          .attr("height", function(d) { return conf.yscale(d.y0) - conf.yscale(d.y0 + d.y); })
        .transition()
          .attr("x", function(d) { return conf.xscale(d[xfield]); })
          .attr("width", conf.xscale.rangeBand());
      conf.stacked = true;
    }

} // function bar_plot(d3data)
<|endoftext|>


<commit_before>
describe('Lytics', function () {

var analytics = window.analytics || require('analytics')
  , assert = require('assert')
  , sinon = require('sinon')
  , tick = require('next-tick')
  , when = require('when');

var settings = {
  cid: 'x',
  cookie: 'lytics_cookie'
};

before(function () {
  var spy = this.spy = sinon.spy();
  analytics.ready(spy);
  analytics.initialize({ Lytics: settings });
});

describe('initialize', function () {
  it('should load library and call ready', function (done) {
    this.timeout(10000);
    var spy = this.spy;
    when(function () { return window.jstag.bind; }, function () {
      assert(spy.called);
      done();
    });
  });

  it('should store options with defaults', function () {
    var options = analytics._providers[0].options;
    assert(options.cid == settings.cid);
    assert(options.cookie == settings.cookie);
    assert(options.delay == 200);
    assert(options.initialPageview);
    assert(options.sessionTimeout == 1800);
    assert(options.url == '//c.lytics.io');
  });

  it('should pass options to lytics', function () {
    var options = window.jstag._c;
    assert(options.cid == settings.cid);
    assert(options.cookie == settings.cookie);
  });
});

describe('identify', function () {
  beforeEach(function () {
    this.stub = sinon.stub(window.jstag, 'send');
    analytics._user.clear();
  });

  afterEach(function () {
    this.stub.restore();
  });

  it('should send an id', function () {
    analytics.identify('id');
    assert(this.stub.calledWith({ _uid: 'id' }));
  });

  it('should send traits', function () {
    analytics.identify({ trait: true });
    assert(this.stub.calledWith({ trait: true }));
  });

  it('should send an id and traits', function () {
    analytics.identify('id', { trait: true });
    assert(this.stub.calledWith({ _uid: 'id', trait: true }));
  });
});

describe('track', function () {
  beforeEach(function () {
    this.stub = sinon.stub(window.jstag, 'send');
    analytics._user.clear();
  });

  afterEach(function () {
    this.stub.restore();
  });

  it('should send an event', function () {
    analytics.track('event');
    assert(this.stub.calledWith({ _e: 'event' }));
  });

  it('should send an event and properties', function () {
    analytics.track('event', { property: true });
    assert(this.stub.calledWith({ _e: 'event', property: true }));
  });
});

describe('pageview', function () {
  beforeEach(function () {
    this.stub = sinon.stub(window.jstag, 'send');
  });

  afterEach(function () {
    this.stub.restore();
  });

  it('should call send', function () {
    analytics.pageview();
    assert(this.spy.called);
  });
});

});
<commit_msg>lytics: cleanup<commit_after>
describe('Lytics', function () {

var analytics = window.analytics || require('analytics')
  , assert = require('assert')
  , sinon = require('sinon')
  , tick = require('next-tick')
  , when = require('when');

var settings = {
  cid: 'x',
  cookie: 'lytics_cookie'
};

before(function (done) {
  this.timeout(10000);
  this.spy = sinon.spy();
  analytics.ready(this.spy);
  analytics.initialize({ Lytics: settings });
  this.integration = analytics._integrations.Lytics;
  this.options = this.integration.options;
  when(function () { return window.jstag.bind; }, done);
});

describe('#key', function () {
  it('cid', function () {
    assert(this.integration.key == 'cid');
  });
});

describe('#defaults', function () {
  it('cid', function () {
    assert(this.integration.defaults.cid === '');
  });

  it('cookie', function () {
    assert(this.integration.defaults.cookie === 'seerid');
  });

  it('delay', function () {
    assert(this.integration.defaults.delay === 200);
  });

  it('initialPageview', function () {
    assert(this.integration.defaults.initialPageview === true);
  });

  it('sessionTimeout', function () {
    assert(this.integration.defaults.sessionTimeout === 1800);
  });

  it('url', function () {
    assert(this.integration.defaults.url === '//c.lytics.io');
  });
});

describe('#initialize', function () {
  it('should load library and call ready', function () {
    assert(this.spy.called);
  });

  it('should store options with defaults', function () {
    assert(this.options.cid == settings.cid);
    assert(this.options.cookie == settings.cookie);
    assert(this.options.delay == 200);
    assert(this.options.initialPageview);
    assert(this.options.sessionTimeout == 1800);
    assert(this.options.url == '//c.lytics.io');
  });

  it('should pass options to lytics', function () {
    assert(this.options.cid == settings.cid);
    assert(this.options.cookie == settings.cookie);
  });
});

describe('#identify', function () {
  beforeEach(function () {
    this.stub = sinon.stub(window.jstag, 'send');
    analytics._user.clear();
  });

  afterEach(function () {
    this.stub.restore();
  });

  it('should send an id', function () {
    analytics.identify('id');
    assert(this.stub.calledWith({ _uid: 'id' }));
  });

  it('should send traits', function () {
    analytics.identify({ trait: true });
    assert(this.stub.calledWith({ trait: true }));
  });

  it('should send an id and traits', function () {
    analytics.identify('id', { trait: true });
    assert(this.stub.calledWith({ _uid: 'id', trait: true }));
  });
});

describe('#track', function () {
  beforeEach(function () {
    this.stub = sinon.stub(window.jstag, 'send');
    analytics._user.clear();
  });

  afterEach(function () {
    this.stub.restore();
  });

  it('should send an event', function () {
    analytics.track('event');
    assert(this.stub.calledWith({ _e: 'event' }));
  });

  it('should send an event and properties', function () {
    analytics.track('event', { property: true });
    assert(this.stub.calledWith({ _e: 'event', property: true }));
  });
});

describe('#pageview', function () {
  beforeEach(function () {
    this.stub = sinon.stub(window.jstag, 'send');
  });

  afterEach(function () {
    this.stub.restore();
  });

  it('should call send', function () {
    analytics.pageview();
    assert(this.spy.called);
  });
});

});
<|endoftext|>


<commit_before>app.factory('socket', ['$rootScope', function ($rootScope) {
  var socket = io.connect('http://192.168.59.103');
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      })
    }
  };
}]);
<commit_msg>dynamically pull server ip for socket<commit_after>app.factory('socket', ['$rootScope', function ($rootScope) {
  var socket = io.connect('http://' + server.address.address);
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      })
    }
  };
}]);
<|endoftext|>


<commit_before>var
  bify = require('browserify'),
  rs = require('readable-stream'),
  util = require('util'),
  pathmodify = require('../'),
  path = require('path'),
  assert = require('assert'),
  sinon = require('sinon'),
  assign = Object.assign || require('object-assign'),
  vm = require('vm'),
  // Like core paths module, but tailored for the purposes of these tests.
  tests_path = {},
  b;

tests_path.join = function join () {
  return path.join.apply(path, arguments).replace('\\', this.sep);
};

// Transform stream to test programatic transforms.
function Xform () {
  rs.Transform.apply(this, arguments);
}

util.inherits(Xform, rs.Transform);

Xform.prototype._transform = function (chunk, enc, cb) {
  this.push(chunk.toString().replace("lowercase", "UPPERCASE"));
  cb();
};

describe('Plugin', function () {
  var
    options = {},
    paths = {};

  options.browserify = {
    entries: ['./src/entry'],
    basedir: __dirname,
  };

  paths.sep = '/';
  tests_path.sep = paths.sep;

  paths.src = tests_path.join(__dirname, 'src');
  paths.prefix = 'app';
  paths.subdir = 'a';
  paths.basename = paths.subdir;
  paths.ext = '.js';
  paths.require_id = tests_path.join(
    paths.prefix, paths.subdir, paths.basename
  );
  paths.alias_id = tests_path.join(paths.src, paths.subdir, paths.basename + paths.ext);

  /**
   * Make a browserify instance with a certain configuration.
   * This config will work for a bunch of tests.
   */
  function make_bundler (opts) {
    opts = opts || {};

    return bify(opts.browserify)
      .plugin(pathmodify(), opts.plugin)
      .transform(function (file) { return new Xform; })
    ;
  }
  // make_bundler

  /**
   * Make callback for b.bundle().
   * This callback will work for a bunch of tests.
   * @param object Opts options
   * @param function|undefined done Test framework callback.
   * @return function
   */
  function make_bundle_cb (opts, done) {
    opts = opts || {};
    return function (err, src) {
      if (err) return done(err);

      var c = {};
      vm.runInNewContext(src.toString(), c);

      if (opts.require_id) {
        assert.equal(
          c.require(opts.require_id),
          'UPPERCASE ' + paths.require_id + paths.ext
        );
      }

      if (done) done();
    };
  }
  // make_bundle_cb

  /**
   * Run the "standard" test.
   * This can be reused as the bulk of many of the tests.
   * @param object plugin_opts Pathmodify options.
   * @param object opts Test options.
   * @param function done Test framework callback.
   */
  function run_test (plugin_opts, opts, done) {
    make_bundler({
      browserify: options.browserify,
      plugin: plugin_opts,
    })
      .bundle(make_bundle_cb(opts, done));
  }
  // run_test

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via function, expose as 'whatever', and apply programmatic transform.",
    function (done) {
      function aliaser (input) {
        var
          prefix = [paths.prefix, paths.sep].join(''),
          output = {};

        if (input.id.indexOf(prefix) === 0) {
          output.id = tests_path.join(
            paths.src,
            input.id.substr(prefix.length)
          );

          if (input.opts && input.opts.filename) {
            output.id = './' + path.relative(
              path.dirname(input.opts.filename),
              output.id
            );
          }

          output.expose = "whatever";
        }
        return output;
      }
      // aliaser

      run_test({
        mods: [aliaser]
      }, {require_id: 'whatever'}, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: paths.require_id};
      run_test({
        mods: [pathmodify.mod.id(
          opts.require_id,
          paths.alias_id,
          true
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          paths.alias_id,
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification with function replacement, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          function (rec) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            return {id: tests_path.join(
              paths.src, paths.subdir, paths.basename + paths.ext
            )};
          },
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'whatever' via function, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          paths.alias_id,
          function (rec, alias) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            assert.notStrictEqual(alias, undefined);
            assert.strictEqual(typeof alias.id, 'string');
            assert.ok(alias.id.length > 0);

            return opts.require_id;
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            paths.prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        mods: [pathmodify.mod.dir(
          paths.prefix,
          paths.src,
          true
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification, expose as 'whatever/a/a' via function, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            expose_prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        mods: [pathmodify.mod.dir(
          paths.prefix,
          paths.src,
          function (rec, alias) {
            return tests_path.join(
              expose_prefix,
              rec.id.substr(paths.prefix.length)
            );
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification with function replacement, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            paths.prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        mods: [pathmodify.mod.dir(
          paths.prefix,
          function (rec) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            return {id: tests_path.join(
              paths.src, paths.subdir, paths.basename + paths.ext
            )};
          },
          true
        )]
      }, opts, done);
    }
  );

  var from_re = /^app\/(a\/a)$/;

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: paths.require_id};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          tests_path.join(paths.src, '$1' + paths.ext),
          true
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          tests_path.join(paths.src, '$1' + paths.ext),
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification with function replacement, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          function (rec, opts) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            return {id: tests_path.join(
              paths.src, opts.matches[1] + paths.ext
            )};
          },
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'whatever' via function, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          tests_path.join(paths.src, '$1' + paths.ext),
          function (rec, alias) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            assert.notStrictEqual(alias, undefined);
            assert.strictEqual(typeof alias.id, 'string');
            assert.ok(alias.id.length > 0);

            return opts.require_id;
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'app/a/a' via function returning bool, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: paths.require_id};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          paths.alias_id,
          function (rec, alias) {
            return true;
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should reset `rec` props for each iteration of the mods loop.",
    function (done) {
      var opts = {};
      run_test({
        mods: [
          function (rec, opts) {
            rec.id = 'bogus';
          },
          pathmodify.mod.id(paths.require_id, function (rec) {
            assert.strictEqual(rec.id, paths.require_id);

            return {id: tests_path.join(
              paths.src, paths.subdir, paths.basename + paths.ext
            )};
          })
        ]
      }, opts, done);
    }
  );

  it(
    "Should iterate mods loop until an alias is emitted.",
    function (done) {
      var
        opts = {},
        i = 0;
      run_test({
        mods: [
          // Matches from but doesn't modify so shouldn't terminate loop.
          pathmodify.mod.re(from_re, function (rec) {}),

          // Should be iterated to and emit alias.
          pathmodify.mod.re(
            from_re,
            tests_path.join(paths.src, '$1' + paths.ext)
          )
        ]
      }, opts, done);
    }
  );

  it(
    "Should call user mod functions in context of mod.",
    function (done) {
      var
        opts = {},
        i = 0;

      run_test({
        mods: [
          pathmodify.mod.id(paths.require_id, function (rec) {
            assert.strictEqual(this.from, paths.require_id);
          }),

          function mod () {
            assert.strictEqual(this, mod);
          },

          // Update ID so test doesn't fail for that
          pathmodify.mod.id(paths.require_id, paths.alias_id)
        ]
      }, opts, done);
    }
  );

  it(
    "Should work on rebundle.",
    function (done) {
      var
        opts = {},
        i = 0,
        module_count = 0,
        bundle_cb,
        bundle_times = 2,
        bundles_pending = bundle_times;

      var mod_funcs = {
        id: sinon.spy(function (rec) {
          assert(
            this.from === paths.require_id,
            "from should equal: " + paths.require_id
          );
        }),

        custom: sinon.spy(function mod () {
          assert(this === mod_funcs.custom);
        }),
      };

      var b = make_bundler({
        browserify: options.browserify,
        plugin: {
          mods: [
            pathmodify.mod.id(paths.require_id, mod_funcs.id),
            mod_funcs.custom,
            // Update ID so test doesn't fail for that
            pathmodify.mod.id(paths.require_id, paths.alias_id)
          ]
        },
      });

      function module_counter () {
        ++module_count;
      }

      // Count number of modules (entry files + require()'s) for the first
      // bundle. This will establish how many times some of the aliasing
      // functions should be called.
      b.on('file', module_counter);

      bundle_cb = make_bundle_cb(
        opts,
        function (err) {
          b.removeListener('file', module_counter);
          if (! --bundles_pending || err) {
            if (! err) {
              // Should only be invoked once, for the require('app/a/a') in
              // entry.
              assert(
                mod_funcs.id.callCount === 1,
                "`id` mod should've been called once"
              );

              // Should be invokved once per module (as it'll match everything
              // and change nothing).
              assert(
                mod_funcs.custom.callCount === module_count,
                "custom mod func should've been called once per module: " + module_count
              );
            }
            return done(err);
          }
          else b.bundle(bundle_cb);
        }
      );

      b.bundle(bundle_cb);
    }
  );
});
<commit_msg>Refactor run_test() parameterization.<commit_after>var
  bify = require('browserify'),
  rs = require('readable-stream'),
  util = require('util'),
  pathmodify = require('../'),
  path = require('path'),
  assert = require('assert'),
  sinon = require('sinon'),
  assign = Object.assign || require('object-assign'),
  vm = require('vm'),
  // Like core paths module, but tailored for the purposes of these tests.
  tests_path = {},
  b;

tests_path.join = function join () {
  return path.join.apply(path, arguments).replace('\\', this.sep);
};

// Transform stream to test programatic transforms.
function Xform () {
  rs.Transform.apply(this, arguments);
}

util.inherits(Xform, rs.Transform);

Xform.prototype._transform = function (chunk, enc, cb) {
  this.push(chunk.toString().replace("lowercase", "UPPERCASE"));
  cb();
};

describe('Plugin', function () {
  var
    options = {},
    paths = {};

  options.browserify = {
    entries: ['./src/entry'],
    basedir: __dirname,
  };

  paths.sep = '/';
  tests_path.sep = paths.sep;

  paths.src = tests_path.join(__dirname, 'src');
  paths.prefix = 'app';
  paths.subdir = 'a';
  paths.basename = paths.subdir;
  paths.ext = '.js';
  paths.require_id = tests_path.join(
    paths.prefix, paths.subdir, paths.basename
  );
  paths.alias_id = tests_path.join(paths.src, paths.subdir, paths.basename + paths.ext);

  /**
   * Make a browserify instance with a certain configuration.
   * This config will work for a bunch of tests.
   */
  function make_bundler (opts) {
    opts = opts || {};

    return bify(opts.browserify)
      .plugin(pathmodify(), opts.plugin)
      .transform(function (file) { return new Xform; })
    ;
  }
  // make_bundler

  /**
   * Make callback for b.bundle().
   * This callback will work for a bunch of tests.
   * @param object Opts options
   * @param function|undefined done Test framework callback.
   * @return function
   */
  function make_bundle_cb (opts, done) {
    opts = opts || {};
    return function (err, src) {
      if (err) return done(err);

      var c = {};
      vm.runInNewContext(src.toString(), c);

      // Require this to be explicitly `null` to avoid, as otherwise it's too
      // easy to accidentally greenlight a bunch of tests that aren't actually
      // testing what they're supposed to.
      if (opts.require_id !== null) {
        assert.equal(
          c.require(opts.require_id),
          'UPPERCASE ' + paths.require_id + paths.ext
        );
      }

      if (done) done();
    };
  }
  // make_bundle_cb

  /**
   * Run the "standard" test.
   * This can be reused as the bulk of many of the tests.
   * @param object plugin_opts Pathmodify options.
   * @param object opts Test options.
   * @param function done Test framework callback.
   */
  function run_test (local_opts) {
    local_opts = local_opts || {};

    make_bundler({
      browserify: local_opts.browserify || options.browserify,
      plugin: local_opts.plugin,
    })
      .bundle(make_bundle_cb(local_opts.test, local_opts.done));
  }
  // run_test

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via function, expose as 'whatever', and apply programmatic transform.",
    function (done) {
      function aliaser (input) {
        var
          prefix = [paths.prefix, paths.sep].join(''),
          output = {};

        if (input.id.indexOf(prefix) === 0) {
          output.id = tests_path.join(
            paths.src,
            input.id.substr(prefix.length)
          );

          if (input.opts && input.opts.filename) {
            output.id = './' + path.relative(
              path.dirname(input.opts.filename),
              output.id
            );
          }

          output.expose = "whatever";
        }
        return output;
      }
      // aliaser

      run_test({
        plugin: {
          mods: [aliaser]
        },
        test: {require_id: 'whatever'},
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: paths.require_id};
      run_test({
        plugin: {
          mods: [pathmodify.mod.id(
            opts.require_id,
            paths.alias_id,
            true
          )],
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        plugin: {
          mods: [pathmodify.mod.id(
            paths.require_id,
            paths.alias_id,
            opts.require_id
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification with function replacement, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        plugin: {
          mods: [pathmodify.mod.id(
            paths.require_id,
            function (rec) {
              assert.notStrictEqual(rec, undefined);
              assert.strictEqual(typeof rec.id, 'string');
              assert.ok(rec.id.length > 0);

              return {id: tests_path.join(
                paths.src, paths.subdir, paths.basename + paths.ext
              )};
            },
            opts.require_id
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'whatever' via function, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        plugin: {
          mods: [pathmodify.mod.id(
            paths.require_id,
            paths.alias_id,
            function (rec, alias) {
              assert.notStrictEqual(rec, undefined);
              assert.strictEqual(typeof rec.id, 'string');
              assert.ok(rec.id.length > 0);

              assert.notStrictEqual(alias, undefined);
              assert.strictEqual(typeof alias.id, 'string');
              assert.ok(alias.id.length > 0);

              return opts.require_id;
            }
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            paths.prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        plugin: {
          mods: [pathmodify.mod.dir(
            paths.prefix,
            paths.src,
            true
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification, expose as 'whatever/a/a' via function, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            expose_prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        plugin: {
          mods: [pathmodify.mod.dir(
            paths.prefix,
            paths.src,
            function (rec, alias) {
              return tests_path.join(
                expose_prefix,
                rec.id.substr(paths.prefix.length)
              );
            }
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification with function replacement, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            paths.prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        plugin: {
          mods: [pathmodify.mod.dir(
            paths.prefix,
            function (rec) {
              assert.notStrictEqual(rec, undefined);
              assert.strictEqual(typeof rec.id, 'string');
              assert.ok(rec.id.length > 0);

              return {id: tests_path.join(
                paths.src, paths.subdir, paths.basename + paths.ext
              )};
            },
            true
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  var from_re = /^app\/(a\/a)$/;

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: paths.require_id};
      run_test({
        plugin: {
          mods: [pathmodify.mod.re(
            from_re,
            tests_path.join(paths.src, '$1' + paths.ext),
            true
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        plugin: {
          mods: [pathmodify.mod.re(
            from_re,
            tests_path.join(paths.src, '$1' + paths.ext),
            opts.require_id
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification with function replacement, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        plugin: {
          mods: [pathmodify.mod.re(
            from_re,
            function (rec, opts) {
              assert.notStrictEqual(rec, undefined);
              assert.strictEqual(typeof rec.id, 'string');
              assert.ok(rec.id.length > 0);

              return {id: tests_path.join(
                paths.src, opts.matches[1] + paths.ext
              )};
            },
            opts.require_id
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'whatever' via function, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        plugin: {
          mods: [pathmodify.mod.re(
            from_re,
            tests_path.join(paths.src, '$1' + paths.ext),
            function (rec, alias) {
              assert.notStrictEqual(rec, undefined);
              assert.strictEqual(typeof rec.id, 'string');
              assert.ok(rec.id.length > 0);

              assert.notStrictEqual(alias, undefined);
              assert.strictEqual(typeof alias.id, 'string');
              assert.ok(alias.id.length > 0);

              return opts.require_id;
            }
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'app/a/a' via function returning bool, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: paths.require_id};
      run_test({
        plugin: {
          mods: [pathmodify.mod.id(
            paths.require_id,
            paths.alias_id,
            function (rec, alias) {
              return true;
            }
          )]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should reset `rec` props for each iteration of the mods loop.",
    function (done) {
      var opts = {require_id: null};
      run_test({
        plugin: {
          mods: [
            function (rec, opts) {
              rec.id = 'bogus';
            },
            pathmodify.mod.id(paths.require_id, function (rec) {
              assert.strictEqual(rec.id, paths.require_id);

              return {id: tests_path.join(
                paths.src, paths.subdir, paths.basename + paths.ext
              )};
            })
          ],
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should iterate mods loop until an alias is emitted.",
    function (done) {
      var
        opts = {require_id: null},
        i = 0;
      run_test({
        plugin: {
          mods: [
            // Matches from but doesn't modify so shouldn't terminate loop.
            pathmodify.mod.re(from_re, function (rec) {}),

            // Should be iterated to and emit alias.
            pathmodify.mod.re(
              from_re,
              tests_path.join(paths.src, '$1' + paths.ext)
            )
          ]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should call user mod functions in context of mod.",
    function (done) {
      var
        opts = {require_id: null},
        i = 0;

      run_test({
        plugin: {
          mods: [
            pathmodify.mod.id(paths.require_id, function (rec) {
              assert.strictEqual(this.from, paths.require_id);
            }),

            function mod () {
              assert.strictEqual(this, mod);
            },

            // Update ID so test doesn't fail for that
            pathmodify.mod.id(paths.require_id, paths.alias_id)
          ]
        },
        test: opts,
        done: done,
      });
    }
  );

  it(
    "Should work on rebundle.",
    function (done) {
      var
        opts = {require_id: null},
        i = 0,
        module_count = 0,
        bundle_cb,
        bundle_times = 2,
        bundles_pending = bundle_times;

      var mod_funcs = {
        id: sinon.spy(function (rec) {
          assert(
            this.from === paths.require_id,
            "from should equal: " + paths.require_id
          );
        }),

        custom: sinon.spy(function mod () {
          assert(this === mod_funcs.custom);
        }),
      };

      var b = make_bundler({
        browserify: options.browserify,
        plugin: {
          mods: [
            pathmodify.mod.id(paths.require_id, mod_funcs.id),
            mod_funcs.custom,
            // Update ID so test doesn't fail for that
            pathmodify.mod.id(paths.require_id, paths.alias_id)
          ]
        },
      });

      function module_counter () {
        ++module_count;
      }

      // Count number of modules (entry files + require()'s) for the first
      // bundle. This will establish how many times some of the aliasing
      // functions should be called.
      b.on('file', module_counter);

      bundle_cb = make_bundle_cb(
        opts,
        function (err) {
          b.removeListener('file', module_counter);
          if (! --bundles_pending || err) {
            if (! err) {
              // Should only be invoked once, for the require('app/a/a') in
              // entry.
              assert(
                mod_funcs.id.callCount === 1,
                "`id` mod should've been called once"
              );

              // Should be invokved once per module (as it'll match everything
              // and change nothing).
              assert(
                mod_funcs.custom.callCount === module_count,
                "custom mod func should've been called once per module: " + module_count
              );
            }
            return done(err);
          }
          else b.bundle(bundle_cb);
        }
      );

      b.bundle(bundle_cb);
    }
  );
});
<|endoftext|>


<commit_before>/* global QUnit */
const {Swal, SwalWithoutAnimation} = require('./helpers')
const $ = require('jquery')
import { triggerEscape, TIMEOUT } from './helpers.js'

QUnit.test('confirm button /w useRejections: true', (assert) => {
  const done = assert.async()

  SwalWithoutAnimation({
    title: 'Confirm me',
    useRejections: true
  }).then((result) => {
    assert.equal(result, true)
    done()
  })

  Swal.clickConfirm()
})

QUnit.test('cancel button /w useRejections: true', (assert) => {
  const done = assert.async()

  SwalWithoutAnimation({
    title: 'Cancel me',
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.cancel)
      done()
    }
  )

  Swal.clickCancel()
})

QUnit.test('esc key /w useRejections: true', (assert) => {
  const done = assert.async()

  SwalWithoutAnimation({
    title: 'Esc me',
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.esc)
      done()
    }
  )

  triggerEscape()
})

QUnit.test('backdrop click /w useRejections: true', (assert) => {
  const done = assert.async()

  Swal({
    title: 'Backdrop click',
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.backdrop)
      done()
    }
  )

  $('.swal2-container').click()
})

QUnit.test('timer /w useRejections: true', (assert) => {
  const done = assert.async()

  SwalWithoutAnimation({
    title: 'Timer test',
    timer: 10,
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.timer)
      done()
    }
  )
})

QUnit.test('close button /w useRejections: true', (assert) => {
  const done = assert.async()

  Swal({
    title: 'Close button test',
    showCloseButton: true,
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.close)
      done()
    }
  )

  const $closeButton = $('.swal2-close')
  assert.ok($closeButton.is(':visible'))
  $closeButton.click()
})

QUnit.test('input text /w useRejections: true', (assert) => {
  const done = assert.async()

  const string = 'Live for yourself'
  Swal({
    input: 'text',
    useRejections: true
  }).then((result) => {
    assert.equal(result, string)
    done()
  })

  $('.swal2-input').val(string)
  Swal.clickConfirm()
})

QUnit.test('built-in email validation /w useRejections: true', (assert) => {
  const done = assert.async()

  var validEmailAddress = 'team+support+a.b@example.com'
  Swal({
    input: 'email',
    useRejections: true
  }).then((result) => {
    assert.equal(result, validEmailAddress)
    done()
  })

  $('.swal2-input').val(validEmailAddress)
  Swal.clickConfirm()
})

QUnit.test('input select /w useRejections: true', (assert) => {
  const done = assert.async()

  const selected = 'dos'
  Swal({
    input: 'select',
    inputOptions: {uno: 1, dos: 2},
    useRejections: true
  }).then((result) => {
    assert.equal(result, selected)
    done()
  })

  $('.swal2-select').val(selected)
  Swal.clickConfirm()
})

QUnit.test('input checkbox /w useRejections: true', (assert) => {
  const done = assert.async()

  Swal({
    input: 'checkbox',
    inputAttributes: {
      name: 'test-checkbox'
    },
    useRejections: true
  }).then((result) => {
    assert.equal(checkbox.attr('name'), 'test-checkbox')
    assert.equal(result, '1')
    done()
  })

  const checkbox = $('.swal2-checkbox input')
  checkbox.prop('checked', true)
  Swal.clickConfirm()
})

QUnit.test('validation error /w expectRejections: true', (assert) => {
  const done = assert.async()
  const inputValidator = (value) => !value ? Promise.reject('no falsy values') : Promise.resolve()

  SwalWithoutAnimation({input: 'text', inputValidator, expectRejections: true})
  assert.ok($('.swal2-validationerror').is(':hidden'))
  setTimeout(() => {
    const initialModalHeight = $('.swal2-modal').outerHeight()

    Swal.clickConfirm()
    setTimeout(() => {
      assert.ok($('.swal2-validationerror').is(':visible'))
      assert.equal($('.swal2-validationerror').text(), 'no falsy values')
      assert.ok($('.swal2-input').attr('aria-invalid'))
      assert.ok($('.swal2-modal').outerHeight() > initialModalHeight)

      $('.swal2-input').val('blah-blah').trigger('input')
      assert.ok($('.swal2-validationerror').is(':hidden'))
      assert.notOk($('.swal2-input').attr('aria-invalid'))
      assert.ok($('.swal2-modal').outerHeight() === initialModalHeight)
      done()
    }, TIMEOUT)
  }, TIMEOUT)
})
<commit_msg>chore: get rid of one more instable deprecated test<commit_after>/* global QUnit */
const {Swal, SwalWithoutAnimation} = require('./helpers')
const $ = require('jquery')
import { triggerEscape } from './helpers.js'

QUnit.test('confirm button /w useRejections: true', (assert) => {
  const done = assert.async()

  SwalWithoutAnimation({
    title: 'Confirm me',
    useRejections: true
  }).then((result) => {
    assert.equal(result, true)
    done()
  })

  Swal.clickConfirm()
})

QUnit.test('cancel button /w useRejections: true', (assert) => {
  const done = assert.async()

  SwalWithoutAnimation({
    title: 'Cancel me',
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.cancel)
      done()
    }
  )

  Swal.clickCancel()
})

QUnit.test('esc key /w useRejections: true', (assert) => {
  const done = assert.async()

  SwalWithoutAnimation({
    title: 'Esc me',
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.esc)
      done()
    }
  )

  triggerEscape()
})

QUnit.test('backdrop click /w useRejections: true', (assert) => {
  const done = assert.async()

  Swal({
    title: 'Backdrop click',
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.backdrop)
      done()
    }
  )

  $('.swal2-container').click()
})

QUnit.test('timer /w useRejections: true', (assert) => {
  const done = assert.async()

  SwalWithoutAnimation({
    title: 'Timer test',
    timer: 10,
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.timer)
      done()
    }
  )
})

QUnit.test('close button /w useRejections: true', (assert) => {
  const done = assert.async()

  Swal({
    title: 'Close button test',
    showCloseButton: true,
    useRejections: true
  }).then(
    () => {},
    (dismiss) => {
      assert.equal(dismiss, Swal.DismissReason.close)
      done()
    }
  )

  const $closeButton = $('.swal2-close')
  assert.ok($closeButton.is(':visible'))
  $closeButton.click()
})

QUnit.test('input text /w useRejections: true', (assert) => {
  const done = assert.async()

  const string = 'Live for yourself'
  Swal({
    input: 'text',
    useRejections: true
  }).then((result) => {
    assert.equal(result, string)
    done()
  })

  $('.swal2-input').val(string)
  Swal.clickConfirm()
})

QUnit.test('built-in email validation /w useRejections: true', (assert) => {
  const done = assert.async()

  var validEmailAddress = 'team+support+a.b@example.com'
  Swal({
    input: 'email',
    useRejections: true
  }).then((result) => {
    assert.equal(result, validEmailAddress)
    done()
  })

  $('.swal2-input').val(validEmailAddress)
  Swal.clickConfirm()
})

QUnit.test('input select /w useRejections: true', (assert) => {
  const done = assert.async()

  const selected = 'dos'
  Swal({
    input: 'select',
    inputOptions: {uno: 1, dos: 2},
    useRejections: true
  }).then((result) => {
    assert.equal(result, selected)
    done()
  })

  $('.swal2-select').val(selected)
  Swal.clickConfirm()
})

QUnit.test('input checkbox /w useRejections: true', (assert) => {
  const done = assert.async()

  Swal({
    input: 'checkbox',
    inputAttributes: {
      name: 'test-checkbox'
    },
    useRejections: true
  }).then((result) => {
    assert.equal(checkbox.attr('name'), 'test-checkbox')
    assert.equal(result, '1')
    done()
  })

  const checkbox = $('.swal2-checkbox input')
  checkbox.prop('checked', true)
  Swal.clickConfirm()
})
<|endoftext|>


<commit_before>
;(function() {

    var app = this;

    var WebSocket = function WebSocket(url) {
        this.ws = new WebSocket(url);
    };

    WebSocket.prototype = Object.create(global.App.Core.Base.prototype);
    WebSocket.prototype.constructor = WebSocket;

    global.App.Module.WebSocket = WebSocket;

}.call(this || window));

<commit_msg>extend websocket with base class<commit_after>
;(function() {

    var global = this;

    var WebSocket = function WebSocket(url) {
        App.Core.Base.call(this);
        this.ws = new global.WebSocket(url);
        this._listen();
    };

    WebSocket.prototype = Object.create(App.Core.Base.prototype);
    WebSocket.prototype.constructor = WebSocket;

    WebSocket.prototype._listen = function() {
        this.ws.addEventListener('open', this._onopen.bind(this));
        this.ws.addEventListener('close', this._onclose.bind(this));
        this.ws.addEventListener('message', this._onmessage.bind(this));
    };

    WebSocket.prototype._onopen = function() {
        this.emit('open');
    };

    WebSocket.prototype._onclose = function() {
        this.emit('open');
    };

    WebSocket.prototype._onmessage = function(msg) {
        this.emit('message', msg);
    };

    WebSocket.prototype.send = function(msg) {
        var data = {
            type: 'message',
            data: msg
        };
        this.ws.send(JSON.stringify(data));
    };

    App.Module.WebSocket = WebSocket;

}.call(this || window));

<|endoftext|>


<commit_before>var WebsocketServer = require('ws').Server;
var config = require('../../config/config');
var redis = require('redis');
var redisClient = redis.createClient(config['REDIS_PORT'], config['FOXRIVER_IP']);
var computeOrderKey = require('./redisKeyCompute').computeOrderKey;
var computeCustomerKey = require('./redisKeyCompute').computeCustomerKey;
var TTL = require('./redisKeyCompute').TTL;
var NO_INFLIGHT_ORDER = require('./redisKeyCompute').NO_INFLIGHT_ORDER;
var INFLIGHT_ORDERS = require('./redisKeyCompute').INFLIGHT_ORDERS;
var writeWS = require('./writeWS');
var async = require('async');

module.exports = function(winston) {

	function retrieveInFlightOrders(callback) {
		redisClient.lrange(INFLIGHT_ORDERS, 0, -1, function(err, customersList) {
			if (err) {
				return callback('cannot retrieve list of inflight orders');
			}
			var subscriber;
			subscriber = redis.createClient(config['REDIS_PORT'], config['FOXRIVER_IP']);
			subscriber.on('subscribe', function(channel, count) {

			});
			subscriber.on('message', function(channel, message) {

			});

			callback(null, customersList);
		});
	}

	function retrieveOrdersKeys(customersList, callback) {
		var multi = redisClient.multi();
		var inFlightOrdersKeys = [];
		customersList.forEach(function(customer, index) {
			multi.get(customer);
		});
		multi.exec(function (err, replies) {
			if (err) {
				return callback('batch orders keys retrieval failed');
			}

			replies.forEach(function(orderKey, index) {
				if (orderKey === null || orderKey === NO_INFLIGHT_ORDER) {
					winston.warn(index + ' doesnt exist, deleting automatically');
					redisClient.lrem(INFLIGHT_ORDERS, 0, customersList[index]);
				} else {
					inFlightOrdersKeys.push(orderKey);
				}
			});
			callback(null, inFlightOrdersKeys);
		});
	}

	function retrieveOrdersInfo(ordersKeysList, callback) {
		var multi = redisClient.multi();
		var ordersInfo = [];
		ordersKeysList.forEach(function(orderKey, index) {
			multi.get(orderKey);
		});
		multi.exec(function (err, replies) {
			if (err) {
				return callback('batch orders info retrieval failed');
			}

			replies.forEach(function(orderInfo, index) {
				if (orderInfo === null) {
					return callback('item #' + index + ' has no order info.');
				}
				ordersInfo.push(JSON.parse(orderInfo));
			});
			callback(null, ordersKeysList, ordersInfo);
		});
	}

	function retrieveDeliveryTime(ordersKeysList, ordersInfo, callback) {
		var multi = redisClient.multi();
		ordersKeysList.forEach(function(orderKey, index) {
			var deliveryTimeKey = orderKey + ':deliveryTime';
			multi.get(deliveryTimeKey);
		});
		multi.exec(function (err, replies) {
			if (err) {
				return callback('batch orders deliveryTime retrieval failed');
			}

			replies.forEach(function(deliveryTime, index) {
				if (deliveryTime === null) {
					return callback('item #' + index + ' has no deliveryTime');
				}
				ordersInfo[index].deliveryTime = deliveryTime;
			});
			callback(null, ordersInfo);
		});
	}

	function subscribeToInFlightList(ws) {
		return function(ordersInfo, callback) {
			subscriber = redis.createClient(config['REDIS_PORT'], config['FOXRIVER_IP']);
			subscriber.on('subscribe', function(channel, count) {
				winston.info('barista subscribes to ' + INFLIGHT_ORDERS);
			});
			subscriber.on('message', function(channel, newCustomer) {
				if (channel !== INFLIGHT_ORDERS) {
					return winston.error(customer + ' shouldnt be subscribed to ' + customerChannel);
				}

				winston.info('new customer to the list ' + newCustomer);

				async.waterfall([
					function(callback) {
						callback(null, [newCustomer])
					},
					retrieveOrdersKeys,
					retrieveOrdersInfo
				], function(err, result) {
					callback(null, result);
				});
			});
			subscriber.subscribe(INFLIGHT_ORDERS);

			ws.on('close', function() {
				winston.info('barista unsubscribe from ' + INFLIGHT_ORDERS);
				subscriber.unsubscribe();
				subscriber.end();
			});

			callback(null, ordersInfo);
		}
	}

	return function handleGetInFlightOrders(params, ws) {

		async.waterfall([
			retrieveInFlightOrders,
			retrieveOrdersKeys,
			retrieveOrdersInfo,
			retrieveDeliveryTime,
			subscribeToInFlightList(ws)
		],
			function(err, result) {
				if (err) {
					winston.error(err);
					return writeWS(ws, 500, err, {});
				}
				writeWS(ws, 200, '', {
					orders: result
				});
			}
		);
	};
};<commit_msg>we need delivery time too.<commit_after>var WebsocketServer = require('ws').Server;
var config = require('../../config/config');
var redis = require('redis');
var redisClient = redis.createClient(config['REDIS_PORT'], config['FOXRIVER_IP']);
var computeOrderKey = require('./redisKeyCompute').computeOrderKey;
var computeCustomerKey = require('./redisKeyCompute').computeCustomerKey;
var TTL = require('./redisKeyCompute').TTL;
var NO_INFLIGHT_ORDER = require('./redisKeyCompute').NO_INFLIGHT_ORDER;
var INFLIGHT_ORDERS = require('./redisKeyCompute').INFLIGHT_ORDERS;
var writeWS = require('./writeWS');
var async = require('async');

module.exports = function(winston) {

	function retrieveInFlightOrders(callback) {
		redisClient.lrange(INFLIGHT_ORDERS, 0, -1, function(err, customersList) {
			if (err) {
				return callback('cannot retrieve list of inflight orders');
			}
			var subscriber;
			subscriber = redis.createClient(config['REDIS_PORT'], config['FOXRIVER_IP']);
			subscriber.on('subscribe', function(channel, count) {

			});
			subscriber.on('message', function(channel, message) {

			});

			callback(null, customersList);
		});
	}

	function retrieveOrdersKeys(customersList, callback) {
		var multi = redisClient.multi();
		var inFlightOrdersKeys = [];
		customersList.forEach(function(customer, index) {
			multi.get(customer);
		});
		multi.exec(function (err, replies) {
			if (err) {
				return callback('batch orders keys retrieval failed');
			}

			replies.forEach(function(orderKey, index) {
				if (orderKey === null || orderKey === NO_INFLIGHT_ORDER) {
					winston.warn(index + ' doesnt exist, deleting automatically');
					redisClient.lrem(INFLIGHT_ORDERS, 0, customersList[index]);
				} else {
					inFlightOrdersKeys.push(orderKey);
				}
			});
			callback(null, inFlightOrdersKeys);
		});
	}

	function retrieveOrdersInfo(ordersKeysList, callback) {
		var multi = redisClient.multi();
		var ordersInfo = [];
		ordersKeysList.forEach(function(orderKey, index) {
			multi.get(orderKey);
		});
		multi.exec(function (err, replies) {
			if (err) {
				return callback('batch orders info retrieval failed');
			}

			replies.forEach(function(orderInfo, index) {
				if (orderInfo === null) {
					return callback('item #' + index + ' has no order info.');
				}
				ordersInfo.push(JSON.parse(orderInfo));
			});
			callback(null, ordersInfo, ordersKeysList);
		});
	}

	function retrieveDeliveryTime(ordersInfo, ordersKeysList, callback) {
		var multi = redisClient.multi();
		ordersKeysList.forEach(function(orderKey, index) {
			var deliveryTimeKey = orderKey + ':deliveryTime';
			multi.get(deliveryTimeKey);
		});
		multi.exec(function (err, replies) {
			if (err) {
				return callback('batch orders deliveryTime retrieval failed');
			}

			replies.forEach(function(deliveryTime, index) {
				if (deliveryTime === null) {
					return callback('item #' + index + ' has no deliveryTime');
				}
				ordersInfo[index].deliveryTime = deliveryTime;
			});
			callback(null, ordersInfo);
		});
	}

	function subscribeToInFlightList(ws) {
		return function(ordersInfo, callback) {
			subscriber = redis.createClient(config['REDIS_PORT'], config['FOXRIVER_IP']);
			subscriber.on('subscribe', function(channel, count) {
				winston.info('barista subscribes to ' + INFLIGHT_ORDERS);
			});
			subscriber.on('message', function(channel, newCustomer) {
				if (channel !== INFLIGHT_ORDERS) {
					return winston.error(customer + ' shouldnt be subscribed to ' + customerChannel);
				}

				winston.info('new customer to the list ' + newCustomer);

				async.waterfall([
					function(callback) {
						callback(null, [newCustomer])
					},
					retrieveOrdersKeys,
					retrieveOrdersInfo,
					retrieveDeliveryTime
				], function(err, result) {
					callback(null, result);
				});
			});
			subscriber.subscribe(INFLIGHT_ORDERS);

			ws.on('close', function() {
				winston.info('barista unsubscribe from ' + INFLIGHT_ORDERS);
				subscriber.unsubscribe();
				subscriber.end();
			});

			callback(null, ordersInfo);
		}
	}

	return function handleGetInFlightOrders(params, ws) {

		async.waterfall([
			retrieveInFlightOrders,
			retrieveOrdersKeys,
			retrieveOrdersInfo,
			retrieveDeliveryTime,
			subscribeToInFlightList(ws)
		],
			function(err, result) {
				if (err) {
					winston.error(err);
					return writeWS(ws, 500, err, {});
				}
				writeWS(ws, 200, '', {
					orders: result
				});
			}
		);
	};
};<|endoftext|>


<commit_before>/*!
 * map-files <https://github.com/jonschlinkert/map-files>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var assert = require('assert');
var matter = require('gray-matter');
var extend = require('extend-shallow');
var relative = require('relative');
var glob = require('globby');
var mapFiles = require('..');
require('should');

function files(patterns, opts) {
  var o = {};
  o.name = function (fp) {
    return path.basename(fp, path.extname(fp));
  };
  o.read = function (fp) {
    var res = {};
    res.content = fs.readFileSync(fp, 'utf8');
    res.path = relative(fp);
    return res;
  };
  opts = extend({}, o, opts);
  return mapFiles(patterns, opts);
};

describe('files', function () {
  it('should load files from a glob pattern.', function () {
    var cache = files('test/fixtures/*.txt');

    cache.should.have.property('a');
    cache.should.have.property('b');
    cache.should.have.property('c');
    cache.should.eql({
      a: { content: 'AAA', path: 'test/fixtures/a.txt' },
      b: { content: 'BBB', path: 'test/fixtures/b.txt' },
      c: { content: 'CCC', path: 'test/fixtures/c.txt' }
    });
  });

  it('should use a cwd.', function () {
    var cache = files('*.txt', {cwd: 'test/fixtures'});

    cache.should.have.property('a');
    cache.should.have.property('b');
    cache.should.have.property('c');
    cache.should.eql({
      a: { content: 'AAA', path: 'test/fixtures/a.txt' },
      b: { content: 'BBB', path: 'test/fixtures/b.txt' },
      c: { content: 'CCC', path: 'test/fixtures/c.txt' }
    });
  });

  it('should rename the key with a custom function.', function () {
    var cache = files('test/fixtures/*.txt', {
      name: function(filepath) {
        return relative(filepath);
      }
    })
    cache.should.have.property('test/fixtures/a.txt');
    cache.should.have.property('test/fixtures/b.txt');
    cache.should.have.property('test/fixtures/c.txt');
  });

  it('should read files with a custom function.', function () {
    var cache = files('test/fixtures/*.txt', {
      read: function(filepath) {
        var res = matter.read(filepath);
        res.path = relative(res.path);
        return res;
      }
    });
    cache.should.have.property('a', { data: {}, content: 'AAA', orig: 'AAA', path: 'test/fixtures/a.txt' });
    cache.should.have.property('b', { data: {}, content: 'BBB', orig: 'BBB', path: 'test/fixtures/b.txt' });
    cache.should.have.property('c', { data: {}, content: 'CCC', orig: 'CCC', path: 'test/fixtures/c.txt' });
  });

  it('should require files with a custom function.', function () {
    var cache = files('test/fixtures/*.js', {
      read: function (filepath) {
        return {
          path: relative(filepath),
          helper: require(path.resolve(filepath))
        }
      }
    });
    cache.should.have.property('a');
    cache.should.have.property('b');
    cache.should.have.property('c');
    cache['a'].path.should.equal('test/fixtures/a.js');
    cache['a'].helper.should.be.an.object;
    cache['a'].helper.should.be.a.function;
  });

  it('should use multiple custom functions.', function () {
    var cache = files('test/fixtures/*.txt', {
      read: function(filepath) {
        var res = matter.read(filepath);
        res.path = relative(res.path);
        return res;
      },
      name: function(filepath) {
        return relative(filepath);
      }
    });
    cache.should.have.property('test/fixtures/a.txt', { data: {}, content: 'AAA', orig: 'AAA', path: 'test/fixtures/a.txt' });
    cache.should.have.property('test/fixtures/b.txt', { data: {}, content: 'BBB', orig: 'BBB', path: 'test/fixtures/b.txt' });
    cache.should.have.property('test/fixtures/c.txt', { data: {}, content: 'CCC', orig: 'CCC', path: 'test/fixtures/c.txt' });
  });

  it('readme example #2.', function () {
    var cache = files('test/fixtures/*.js', {
      read: function (fp) {
        return require(path.resolve(fp));
      }
    });
    // console.log(cache);
  });
});
<commit_msg>caching tests<commit_after>/*!
 * map-files <https://github.com/jonschlinkert/map-files>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var assert = require('assert');
var matter = require('gray-matter');
var extend = require('extend-shallow');
var relative = require('relative');
var glob = require('globby');
var mapFiles = require('..');
require('should');

function files(patterns, opts) {
  var o = {};
  o.name = function (fp) {
    return path.basename(fp, path.extname(fp));
  };
  o.read = function (fp) {
    var res = {};
    res.content = fs.readFileSync(fp, 'utf8');
    res.path = relative(fp);
    return res;
  };
  opts = extend({}, o, opts);
  var res = mapFiles(patterns, opts);
  return res;
};

describe('files', function () {
  it('should cache files when `opts.cache` is true.', function () {
    var res = files('test/fixtures/*.txt', {cache: true});
    mapFiles.should.have.property('cache');
    mapFiles.cache.should.have.property('glob:' + path.resolve('test/fixtures/*.txt'));
    mapFiles.cache.should.have.property('files:' + path.resolve('test/fixtures/*.txt'));
    res.should.have.property('a');
    res.should.have.property('b');
    res.should.have.property('c');
    res.should.eql({
      a: { content: 'AAA', path: 'test/fixtures/a.txt' },
      b: { content: 'BBB', path: 'test/fixtures/b.txt' },
      c: { content: 'CCC', path: 'test/fixtures/c.txt' }
    });
  });

  // it('should load files from a glob pattern.', function () {
  //   var cache = files('test/fixtures/*.txt');

  //   cache.should.have.property('a');
  //   cache.should.have.property('b');
  //   cache.should.have.property('c');
  //   cache.should.eql({
  //     a: { content: 'AAA', path: 'test/fixtures/a.txt' },
  //     b: { content: 'BBB', path: 'test/fixtures/b.txt' },
  //     c: { content: 'CCC', path: 'test/fixtures/c.txt' }
  //   });
  // });

  // it('should use a cwd.', function () {
  //   var cache = files('*.txt', {cwd: 'test/fixtures'});

  //   cache.should.have.property('a');
  //   cache.should.have.property('b');
  //   cache.should.have.property('c');
  //   cache.should.eql({
  //     a: { content: 'AAA', path: 'test/fixtures/a.txt' },
  //     b: { content: 'BBB', path: 'test/fixtures/b.txt' },
  //     c: { content: 'CCC', path: 'test/fixtures/c.txt' }
  //   });
  // });

  // it('should rename the key with a custom function.', function () {
  //   var cache = files('test/fixtures/*.txt', {
  //     name: function(filepath) {
  //       return relative(filepath);
  //     }
  //   })
  //   cache.should.have.property('test/fixtures/a.txt');
  //   cache.should.have.property('test/fixtures/b.txt');
  //   cache.should.have.property('test/fixtures/c.txt');
  // });

  // it('should read files with a custom function.', function () {
  //   var cache = files('test/fixtures/*.txt', {
  //     read: function(filepath) {
  //       var res = matter.read(filepath);
  //       res.path = relative(res.path);
  //       return res;
  //     }
  //   });
  //   cache.should.have.property('a', { data: {}, content: 'AAA', orig: 'AAA', path: 'test/fixtures/a.txt' });
  //   cache.should.have.property('b', { data: {}, content: 'BBB', orig: 'BBB', path: 'test/fixtures/b.txt' });
  //   cache.should.have.property('c', { data: {}, content: 'CCC', orig: 'CCC', path: 'test/fixtures/c.txt' });
  // });

  // it('should require files with a custom function.', function () {
  //   var cache = files('test/fixtures/*.js', {
  //     read: function (filepath) {
  //       return {
  //         path: relative(filepath),
  //         helper: require(path.resolve(filepath))
  //       }
  //     }
  //   });
  //   cache.should.have.property('a');
  //   cache.should.have.property('b');
  //   cache.should.have.property('c');
  //   cache['a'].path.should.equal('test/fixtures/a.js');
  //   cache['a'].helper.should.be.an.object;
  //   cache['a'].helper.should.be.a.function;
  // });

  // it('should use multiple custom functions.', function () {
  //   var cache = files('test/fixtures/*.txt', {
  //     read: function(filepath) {
  //       var res = matter.read(filepath);
  //       res.path = relative(res.path);
  //       return res;
  //     },
  //     name: function(filepath) {
  //       return relative(filepath);
  //     }
  //   });
  //   cache.should.have.property('test/fixtures/a.txt', { data: {}, content: 'AAA', orig: 'AAA', path: 'test/fixtures/a.txt' });
  //   cache.should.have.property('test/fixtures/b.txt', { data: {}, content: 'BBB', orig: 'BBB', path: 'test/fixtures/b.txt' });
  //   cache.should.have.property('test/fixtures/c.txt', { data: {}, content: 'CCC', orig: 'CCC', path: 'test/fixtures/c.txt' });
  // });

  // it('readme example #2.', function () {
  //   var cache = files('test/fixtures/*.js', {
  //     read: function (fp) {
  //       return require(path.resolve(fp));
  //     }
  //   });
  //   // console.log(cache);
  // });
});
<|endoftext|>