<commit_before>/** Class implementing the bar chart view. */
class BarChart {

    /**
     * Create a bar chart instance and pass the other views in.
     * @param worldMap
     * @param infoPanel
     * @param allData
     */
    constructor(worldMap, infoPanel, allData) {
        this.worldMap = worldMap;
        this.infoPanel = infoPanel;
        this.allData = allData;
    }

    /**
     * Render and update the bar chart based on the selection of the data type in the drop-down box
     */
    updateBarChart(selectedDimension) {

        // ******* TODO: PART I *******

        console.log(selectedDimension);

        // Create the x and y scales; make
        // sure to leave room for the axes

        // Create colorScale

        // Create the axes (hint: use #xAxis and #yAxis)
        let svg = d3.select("#barChart");

        let width = parseInt(svg.attr("width"));
        let height = parseInt(svg.attr("height"));

        this.Yaxis('#xAxis', selectedDimension, width, height, this.allData);
        this.Xaxis('#yAxis', 'year', width, height, this.allData);

        // Create the bars (hint: use #bars)

        let aScale = d3.scaleLinear()
            .domain([0, d3.max(this.allData, d => d[selectedDimension])])
            .range([0, height]);

        this.updateABarGraphWithData('#bars', selectedDimension, aScale, this.allData, width, height);

        // ******* TODO: PART II *******

        // Implement how the bars respond to click events
        // Color the selected bar to indicate is has been selected.
        // Make sure only the selected bar has this new color.

        // Call the necessary update functions for when a user clicks on a bar.
        // Note: think about what you want to update when a different bar is selected.

    }

    /**
     *  Check the drop-down box for the currently selected data type and update the bar chart accordingly.
     *
     *  There are 4 attributes that can be selected:
     *  goals, matches, attendance and teams.
     */
    chooseData() {
        // ******* TODO: PART I *******
        //Changed the selected data when a user selects a different
        // menu item from the drop down.

        let e = document.getElementById('dataset');

        let selectedData = e.options[e.selectedIndex].value;
        this.updateBarChart(selectedData);
    }

    Xaxis(idName, dataName, width, height, data) {
        let svg = d3.select(idName);

        let padding = 100;

        //let spacing = height / data.length;

        let min = d3.min(data, function (d) {
            return d[dataName];
        });
        let max = d3.max(data, function (d) {
            return d[dataName];
        });

        let ticks = this.getYears(data);

        console.log("min: " + min);
        console.log("max: " + max);

        let xScale = d3.scaleTime()
            .domain([new Date(min, 0, 1), new Date(max, 0, 1)])
            //.domain([min, max])
            .range([0, width - padding + 20])
            //.rangeRound([0,width - padding + 20], 100)
             .nice();

        // let xScale = d3.scaleLinear()
        //     .domain([min, max])
        //     //.range([0, width - padding + 20])
        //     .rangeRound([0,width - padding + 20], 10)
        //     .nice();

        // let color = d3.scaleLinear()
        //     .domain([min, max])
        //     .range(["darkred", "lightgray", "steelblue"]);

        // let ticks = data.filter(function (d) {
        //     return d.year;
        // });

        console.log(ticks.length);

        let xAxis = d3.axisBottom();
        xAxis.scale(xScale)
            .ticks(d3.timeYear.every(4))
            .ticks(20)
            //.tickPadding([10])
            //.tickValues(ticks)
            .tickFormat(d3.timeFormat("%Y"));

        // css class for the axis
        svg.classed("axis", true)
        //.attr("transform", "translate(" + 75 + "," + 355 + ")")
            .attr("transform", "translate(" + 75 + "," + 355 + ")")
            .call(xAxis)
            .selectAll("text")
            .attr("y", 0)
            .attr("x", 10)
            //.attr("dy", ".35em")
            .attr("dy", ".35em")
            .attr("transform", "rotate(90)")
            .style("text-anchor", "start");
    }

    Yaxis(idName, dataName, width, height, data) {
        let svg = d3.select(idName);

        let padding = 45;

        // let spacing = height / data.length;

        let min = d3.min(data, function (d) {
            return d[dataName];
        });
        let max = d3.max(data, function (d) {
            return d[dataName];
        });

        console.log("min: " + min);
        console.log("max: " + max);
        let yScale = d3.scaleLinear()
            .domain([max, min])
            .range([10, height - padding])
            .nice();

        // let color = d3.scaleLinear()
        //     .domain([min, max])
        //     .range(["darkred", "lightgray", "steelblue"]);

        let yAxis = d3.axisLeft();
        yAxis.scale(yScale);

        // css class for the axis
        svg.classed("axis", true)
            .attr("transform", "translate(" + 75 + "," + 0 + ")")
            .call(yAxis);
    }

    updateABarGraphWithData(idName, dataName, scale, data, width, height) {

        //data = [70, 100, 30];

        //let data_name = 'goals';
        let svg = d3.select(idName);

        // add padding on all sides
        let padding = 75;
        let spacing = width / data.length;

        let min = d3.min(data, function (d) {
            return d[dataName];
        });
        let max = d3.max(data, function (d) {
            return d[dataName];
        });

        let aScale = d3.scaleLinear()
            .domain([min, max])
            //.range([height - padding, 10]);
            //.rangeRound([10,height - padding + 20], 10);
            .range([10, height - padding + 20]);
        //.range([0, height]);

        // svg.attr({
        //     width: width + 2 * padding,
        //     height: height + 2 * padding
        // });

        let barWidth = (width - padding) / data.length;

        data = BarChart.sortData(data, dataName);

        let bars = svg.selectAll("rect")
            .data(data);

        let newBars = bars.enter().append("rect")
            .attr("x", function (d, i) {
                return (i * barWidth) + padding;
            })
            .attr("y", function (d, i) {
                let nd = aScale(d[dataName]);
                return (height - nd - 45);
            })
            .attr("width", barWidth - 5)
            //.attr("width", barWidth)
            .attr("height", function (d) {
                let nd = d[dataName];
                return aScale(nd);
            })
            .style("opacity", 0)
            .classed("barChart", true);

        bars.exit()
            .style("opacity", 1)
            .transition()
            .duration(3000)
            .style("opacity", 0)
            .remove();

        bars = newBars.merge(bars);

        bars.transition()
            .duration(3000)
            .attr("x", function (d, i) {
                return (i * barWidth) + padding;
            })
            .attr("y", function (d, i) {
                let nd = aScale(d[dataName]);
                return (height - nd - 45);
            })
            .attr("width", barWidth - 5)
            //.attr("width", barWidth)
            .attr("height", function (d) {
                let nd = d[dataName];
                return aScale(nd);
            })
            .style("fill", "steelblue")
            .style("opacity", 1);
    }

    getYears(data) {
        let values = [];
        for (let i = 0, len = data.length; i < len; i++) {
            values.push(new Date(data[i].year, 0, 1));
            //values.push(data[i].year);
        }
        return values;
    };

    static sortData(data, dataName) {
        data = data.sort(function compare(a, b) {
            if (a['year'] < b['year'])
                return -1;
            else if (a['year'] > b['year'])
                return 1;
            else
                return 0;
        });
        return data;
    }

}<commit_msg>X axis spaced by fours working<commit_after>/** Class implementing the bar chart view. */
class BarChart {

    /**
     * Create a bar chart instance and pass the other views in.
     * @param worldMap
     * @param infoPanel
     * @param allData
     */
    constructor(worldMap, infoPanel, allData) {
        this.worldMap = worldMap;
        this.infoPanel = infoPanel;
        this.allData = allData;
    }

    /**
     * Render and update the bar chart based on the selection of the data type in the drop-down box
     */
    updateBarChart(selectedDimension) {

        // ******* TODO: PART I *******

        console.log(selectedDimension);

        // Create the x and y scales; make
        // sure to leave room for the axes

        // Create colorScale

        // Create the axes (hint: use #xAxis and #yAxis)
        let svg = d3.select("#barChart");

        let width = parseInt(svg.attr("width"));
        let height = parseInt(svg.attr("height"));

        this.Yaxis('#xAxis', selectedDimension, width, height, this.allData);
        this.Xaxis('#yAxis', 'year', width, height, this.allData);

        // Create the bars (hint: use #bars)

        let aScale = d3.scaleLinear()
            .domain([0, d3.max(this.allData, d => d[selectedDimension])])
            .range([0, height]);

        this.updateABarGraphWithData('#bars', selectedDimension, aScale, this.allData, width, height);

        // ******* TODO: PART II *******

        // Implement how the bars respond to click events
        // Color the selected bar to indicate is has been selected.
        // Make sure only the selected bar has this new color.

        // Call the necessary update functions for when a user clicks on a bar.
        // Note: think about what you want to update when a different bar is selected.

    }

    /**
     *  Check the drop-down box for the currently selected data type and update the bar chart accordingly.
     *
     *  There are 4 attributes that can be selected:
     *  goals, matches, attendance and teams.
     */
    chooseData() {
        // ******* TODO: PART I *******
        //Changed the selected data when a user selects a different
        // menu item from the drop down.

        let e = document.getElementById('dataset');

        let selectedData = e.options[e.selectedIndex].value;
        this.updateBarChart(selectedData);
    }

    Xaxis(idName, dataName, width, height, data) {
        let svg = d3.select(idName);

        let padding = 100;

        //let spacing = height / data.length;

        let min = d3.min(data, function (d) {
            return d[dataName];
        });
        let max = d3.max(data, function (d) {
            return d[dataName];
        });

        let ticks = this.getYears(data);

        console.log("min: " + min);
        console.log("max: " + max);

        let xScale = d3.scaleTime()
            .domain([new Date(min, 0, 1), new Date(max, 0, 1)])
            //.domain([min, max])
            //.range([0, width - padding + 20])
            .rangeRound([0,width - padding + 20], 100)
             .nice();

        console.log(ticks.length);

        let xAxis = d3.axisBottom();
        xAxis.scale(xScale)
            .ticks(d3.timeYear.every(4))
            //.ticks(20)
            //.tickPadding([10])
            //.tickValues(ticks)
            .tickFormat(d3.timeFormat("%Y"));

        // css class for the axis
        svg.classed("axis", true)
        //.attr("transform", "translate(" + 75 + "," + 355 + ")")
            .attr("transform", "translate(" + 75 + "," + 355 + ")")
            .call(xAxis)
            .selectAll("text")
            .attr("y", 0)
            .attr("x", 10)
            //.attr("dy", ".35em")
            .attr("dy", ".35em")
            .attr("transform", "rotate(90)")
            .style("text-anchor", "start");
    }

    Yaxis(idName, dataName, width, height, data) {
        let svg = d3.select(idName);

        let padding = 45;

        // let spacing = height / data.length;

        let min = d3.min(data, function (d) {
            return d[dataName];
        });
        let max = d3.max(data, function (d) {
            return d[dataName];
        });

        console.log("min: " + min);
        console.log("max: " + max);
        let yScale = d3.scaleLinear()
            .domain([max, min])
            .range([10, height - padding])
            .nice();

        // let color = d3.scaleLinear()
        //     .domain([min, max])
        //     .range(["darkred", "lightgray", "steelblue"]);

        let yAxis = d3.axisLeft();
        yAxis.scale(yScale);

        // css class for the axis
        svg.classed("axis", true)
            .attr("transform", "translate(" + 75 + "," + 0 + ")")
            .call(yAxis);
    }

    updateABarGraphWithData(idName, dataName, scale, data, width, height) {

        //data = [70, 100, 30];

        //let data_name = 'goals';
        let svg = d3.select(idName);

        // add padding on all sides
        let padding = 75;
        let spacing = width / data.length;

        let min = d3.min(data, function (d) {
            return d[dataName];
        });
        let max = d3.max(data, function (d) {
            return d[dataName];
        });

        let aScale = d3.scaleLinear()
            .domain([min, max])
            //.range([height - padding, 10]);
            //.rangeRound([10,height - padding + 20], 10);
            .range([10, height - padding + 20]);
        //.range([0, height]);

        // svg.attr({
        //     width: width + 2 * padding,
        //     height: height + 2 * padding
        // });

        let barWidth = (width - padding) / data.length;

        data = BarChart.sortData(data, dataName);

        let bars = svg.selectAll("rect")
            .data(data);

        let newBars = bars.enter().append("rect")
            .attr("x", function (d, i) {
                return (i * barWidth) + padding;
            })
            .attr("y", function (d, i) {
                let nd = aScale(d[dataName]);
                return (height - nd - 45);
            })
            .attr("width", barWidth - 5)
            //.attr("width", barWidth)
            .attr("height", function (d) {
                let nd = d[dataName];
                return aScale(nd);
            })
            .style("opacity", 0)
            .classed("barChart", true);

        bars.exit()
            .style("opacity", 1)
            .transition()
            .duration(3000)
            .style("opacity", 0)
            .remove();

        bars = newBars.merge(bars);

        bars.transition()
            .duration(3000)
            .attr("x", function (d, i) {
                return (i * barWidth) + padding;
            })
            .attr("y", function (d, i) {
                let nd = aScale(d[dataName]);
                return (height - nd - 45);
            })
            .attr("width", barWidth - 5)
            //.attr("width", barWidth)
            .attr("height", function (d) {
                let nd = d[dataName];
                return aScale(nd);
            })
            .style("fill", "steelblue")
            .style("opacity", 1);
    }

    getYears(data) {
        let values = [];
        for (let i = 0, len = data.length; i < len; i++) {
            values.push(new Date(data[i].year, 0, 1));
            //values.push(data[i].year);
        }
        return values;
    };

    static sortData(data, dataName) {
        data = data.sort(function compare(a, b) {
            if (a['year'] < b['year'])
                return -1;
            else if (a['year'] > b['year'])
                return 1;
            else
                return 0;
        });
        return data;
    }

}<|endoftext|>


<commit_before>var assert = require('assert');
var request = require('supertest');
var zetta = require('zetta');
var zrx = require('zrx');
var Photocell = require('zetta-photocell-mock-driver');

var MemoryDeviceRegistry = require('./mocks/memory_device_registry');
var MemoryPeerRegistry = require('./mocks/memory_peer_registry');
var MockEtcd = require('./mocks/mock_etcd');
var VersionClient = require('../version_client');
var ServiceRegistryClient = require('../service_registry_client');
var RouterClient = require('../router_client');
var Proxy = require('../proxy');

describe('Proxy Websockets', function() {
  var hub = null;
  var proxy = null;
  var etcd = null;
  var target = null;
  var proxyUrl = null;
  var newTarget = null;
  var serviceRegistryClient = null;

  beforeEach(function(done) {
    etcd = new MockEtcd();

    etcd.set('/zetta/version', '{"version":"1"}');

    var versionClient = new VersionClient({ client: etcd });
    serviceRegistryClient = new ServiceRegistryClient({ client: etcd });
    var routerClient = new RouterClient({ client: etcd });

    target = zetta({registry: new MemoryDeviceRegistry(), peerRegistry: new MemoryPeerRegistry() });
    hub = zetta({registry: new MemoryDeviceRegistry(), peerRegistry: new MemoryPeerRegistry() });
    target.silent();
    hub.silent();

    target.name('target.1');
    hub.name('hub.1');
    hub.use(Photocell);

    target.listen(0, function(err) {
      if(err) {
        return done(err);
      }

      var cloud = 'http://localhost:' + target.httpServer.server.address().port;
      serviceRegistryClient.add('cloud-target', cloud, '1');

      proxy = new Proxy(serviceRegistryClient, routerClient, versionClient);
      proxy.listen(0, function(err) {
        if(err) {
          return done(err);
        }

        proxyUrl = 'http://localhost:' + proxy._server.address().port;

        hub.link(proxyUrl);

        hub.listen(0, function() {
          var called = false;
          hub.pubsub.subscribe('_peer/connect', function(topic, data) {
            if (!called) {
              called = true;
              done();
            }
          });
        });
      });
    });

  });

  afterEach(function(done) {
    target.httpServer.server.close();
    hub.httpServer.server.close();
    proxy._server.close();
    if(newTarget) {
      newTarget.httpServer.server.close();
    }
    done();
  });

  it('will should recieve photocell data', function(done) {
    var c = zrx()
      .load(proxyUrl)
      .peer('hub.1')
      .device(function(d) { return d.type === 'photocell'; })
      .stream('intensity')
      .subscribe(function() {
        c.dispose();
        done();
      });
  })

  it('second ws client connecting should continue to recv data after first client disconnects', function(done) {
    var createClient = function(cb) {
      return zrx()
        .load(proxyUrl)
        .peer('hub.1')
        .device(function(d) { return d.type === 'photocell'; })
        .stream('intensity')
        .subscribe(cb);
    }

    var c1Count = 0;
    var c2Count = 0;
    var c1 = createClient(function() { c1Count++; });
    var c2 = createClient(function() { c2Count++; });

    setTimeout(function() {
      c1.dispose();
      c2Count=0;
      setTimeout(function() {
        if (c2Count === 0) {
          throw new Error('Havnt recieved anymore ws messages after first client disconnects')
        }
        done();
      }, 200);
    }, 200)
  });

  it('it should disconnect ws if peer disconnects', function(done) {
    var c = zrx()
      .load(proxyUrl)
      .peer('hub.1')
      .device(function(d) { return d.type === 'photocell'; })
      .stream('intensity')
      .subscribe(function() {
        proxy._routerClient.emit('change', []);
        setTimeout(function() {
          assert.equal(Object.keys(proxy._cache).length, 0);
          assert.equal(Object.keys(proxy._subscriptions).length, 0);
          done();
        }, 5)
      });
  });

});
<commit_msg>Added failing test for ws client issue<commit_after>var assert = require('assert');
var request = require('supertest');
var zetta = require('zetta');
var zrx = require('zrx');
var Photocell = require('zetta-photocell-mock-driver');

var MemoryDeviceRegistry = require('./mocks/memory_device_registry');
var MemoryPeerRegistry = require('./mocks/memory_peer_registry');
var MockEtcd = require('./mocks/mock_etcd');
var VersionClient = require('../version_client');
var ServiceRegistryClient = require('../service_registry_client');
var RouterClient = require('../router_client');
var Proxy = require('../proxy');

describe('Proxy Websockets', function() {
  var hub = null;
  var proxy = null;
  var etcd = null;
  var target = null;
  var proxyUrl = null;
  var newTarget = null;
  var serviceRegistryClient = null;

  beforeEach(function(done) {
    etcd = new MockEtcd();

    etcd.set('/zetta/version', '{"version":"1"}');

    var versionClient = new VersionClient({ client: etcd });
    serviceRegistryClient = new ServiceRegistryClient({ client: etcd });
    var routerClient = new RouterClient({ client: etcd });

    target = zetta({registry: new MemoryDeviceRegistry(), peerRegistry: new MemoryPeerRegistry() });
    hub = zetta({registry: new MemoryDeviceRegistry(), peerRegistry: new MemoryPeerRegistry() });
    target.silent();
    hub.silent();

    target.name('target.1');
    hub.name('hub.1');
    hub.use(Photocell);

    target.listen(0, function(err) {
      if(err) {
        return done(err);
      }

      var cloud = 'http://localhost:' + target.httpServer.server.address().port;
      serviceRegistryClient.add('cloud-target', cloud, '1');

      proxy = new Proxy(serviceRegistryClient, routerClient, versionClient);
      proxy.listen(0, function(err) {
        if(err) {
          return done(err);
        }

        proxyUrl = 'http://localhost:' + proxy._server.address().port;

        hub.link(proxyUrl);

        hub.listen(0, function() {
          var called = false;
          hub.pubsub.subscribe('_peer/connect', function(topic, data) {
            if (!called) {
              called = true;
              done();
            }
          });
        });
      });
    });

  });

  afterEach(function(done) {
    target.httpServer.server.close();
    hub.httpServer.server.close();
    proxy._server.close();
    if(newTarget) {
      newTarget.httpServer.server.close();
    }
    done();
  });

  it('will should recieve photocell data', function(done) {
    var c = zrx()
      .load(proxyUrl)
      .peer('hub.1')
      .device(function(d) { return d.type === 'photocell'; })
      .stream('intensity')
      .subscribe(function() {
        c.dispose();
        done();
      });
  })

  it('ws should not disconnect after etcd router updates', function(done) {
    var c = zrx()
      .load(proxyUrl)
      .peer('hub.1')
      .device(function(d) { return d.type === 'photocell'; })
      .stream('intensity')
      .subscribe(function() {
        etcd._trigger('/router/zetta', []);
        setTimeout(function() {
          assert.equal(Object.keys(proxy._cache).length, 1);
          done();
        }, 10);
      });
  })

  it('second ws client connecting should continue to recv data after first client disconnects', function(done) {
    var createClient = function(cb) {
      return zrx()
        .load(proxyUrl)
        .peer('hub.1')
        .device(function(d) { return d.type === 'photocell'; })
        .stream('intensity')
        .subscribe(cb);
    }

    var c1Count = 0;
    var c2Count = 0;
    var c1 = createClient(function() { c1Count++; });
    var c2 = createClient(function() { c2Count++; });

    setTimeout(function() {
      c1.dispose();
      c2Count=0;
      setTimeout(function() {
        if (c2Count === 0) {
          throw new Error('Havnt recieved anymore ws messages after first client disconnects')
        }
        done();
      }, 200);
    }, 200)
  });

  it('it should disconnect ws if peer disconnects', function(done) {
    var c = zrx()
      .load(proxyUrl)
      .peer('hub.1')
      .device(function(d) { return d.type === 'photocell'; })
      .stream('intensity')
      .subscribe(function() {
        proxy._routerClient.emit('change', []);
        setTimeout(function() {
          assert.equal(Object.keys(proxy._cache).length, 0);
          assert.equal(Object.keys(proxy._subscriptions).length, 0);
          done();
        }, 5)
      });
  });

});
<|endoftext|>


<commit_before>'use strict';
const v8Profiler = require('v8-profiler');
const analysisLib = require('v8-analytics');

module.exports = function (_common, config, logger, utils) {

    /**
     * @param {object} option @param {string} msg @param {object} data
     * @description 模板方法，生成真正的结构化数据
     */
    function template(option, msg, data) {
        data = data || {};
        //组装数据
        const result = {
            "sequence": 0,
            "machineUnique": option.unique,
            "projectName": option.name,
            "processPid": option.pid,
            "loadingMsg": msg,
            "data": data
        };

        return result;
    }

    /**
     * @param {object} params
     * @description 用于组装 profiler 的 key
     */
    function composeKey(params) {
        const key = {
            pid: params.pid,
            opt: params.opt,
            name: params.name,
            server: params.server,
        }

        return JSON.stringify(key);
    }

    /**
     * @param {string} title
     * @description 进行 cpu profiling 操作
     */
    function cpuProfilerP(title) {
        return new Promise((resolve) => {
            title = title || '';
            v8Profiler.startProfiling(title, true);

            setTimeout(() => {
                const profiler = v8Profiler.stopProfiling(title);
                profiler.delete();
                resolve(profiler);
            }, config.profiler.cpu.profiling_time);
        })
    }

    /**
     * @param {string} type @param {object} params @param {object} profiler
     * @description 对 profiling 得到的结果进行解析
     */
    function analyticsP(type, profiler, params) {
        params = params || {};
        const result = {};
        if (type === 'cpu') {
            const optional = config.profiler.cpu.optional;
            result.longFunctions = analysisLib(profiler, params.timeout || optional.timeout, false, true, { limit: params.long_limit || optional.long_limit }/*, config.filterFunction*/);
            result.topExecutingFunctions = analysisLib(profiler, 1, false, true, { limit: params.top_limit || optional.top_limit }/*, config.filterFunction*/);
            result.bailoutFunctions = analysisLib(profiler, null, true, true, { limit: params.bail_limit || optional.bail_limit }/*, config.filterFunction*/);
        }

        return result;
    }

    return { template, composeKey, cpuProfilerP, analyticsP }
}<commit_msg>cpu analysis timeout<commit_after>'use strict';
const v8Profiler = require('v8-profiler');
const analysisLib = require('v8-analytics');

module.exports = function (_common, config, logger, utils) {

    /**
     * @param {object} option @param {string} msg @param {object} data
     * @description 模板方法，生成真正的结构化数据
     */
    function template(option, msg, data) {
        data = data || {};
        //组装数据
        const result = {
            "sequence": 0,
            "machineUnique": option.unique,
            "projectName": option.name,
            "processPid": option.pid,
            "loadingMsg": msg,
            "data": data
        };

        return result;
    }

    /**
     * @param {object} params
     * @description 用于组装 profiler 的 key
     */
    function composeKey(params) {
        const key = {
            pid: params.pid,
            opt: params.opt,
            name: params.name,
            server: params.server,
        }

        return JSON.stringify(key);
    }

    /**
     * @param {string} title
     * @description 进行 cpu profiling 操作
     */
    function cpuProfilerP(title) {
        return new Promise((resolve) => {
            title = title || '';
            v8Profiler.startProfiling(title, true);

            setTimeout(() => {
                const profiler = v8Profiler.stopProfiling(title);
                profiler.delete();
                resolve(profiler);
            }, config.profiler.cpu.profiling_time);
        })
    }

    /**
     * @param {string} type @param {object} params @param {object} profiler
     * @description 对 profiling 得到的结果进行解析
     */
    function analyticsP(type, profiler, params) {
        params = params || {};
        const result = {};
        if (type === 'cpu') {
            const optional = config.profiler.cpu.optional;
            result.timeout = params.timeout || optional.timeout;
            result.longFunctions = analysisLib(profiler, params.timeout || optional.timeout, false, true, { limit: params.long_limit || optional.long_limit }/*, config.filterFunction*/);
            result.topExecutingFunctions = analysisLib(profiler, 1, false, true, { limit: params.top_limit || optional.top_limit }/*, config.filterFunction*/);
            result.bailoutFunctions = analysisLib(profiler, null, true, true, { limit: params.bail_limit || optional.bail_limit }/*, config.filterFunction*/);
        }

        return result;
    }

    return { template, composeKey, cpuProfilerP, analyticsP }
}<|endoftext|>


<commit_before>import expect from 'expect';
import sinon from 'sinon';
import Avenger, { QuerySet, QuerySetInput } from '../../src';
import queries from '../../fixtures/queries';

describe('Avenger', () => {

  const API = {
    fetchWorklist: (_id) => Promise.resolve({ worklist: { _id } }),
    fetchSamples: () => Promise.resolve({ samples: [] })
  };

  it('should be instantiable and accept valid queries set', () => {
    const { worklist } = queries(API);
    const av = new Avenger({ worklist });

    expect(av).toBeAn(Avenger);
  });

  describe('QuerySet', () => {
    const { worklist, worklistSamples } = queries(API);
    const av = new Avenger({ worklist, worklistSamples });
    const qsInput = { queries: { worklistSamples }, state: { worklistId: 'foo' } };

    it('should be created given a valid input', () => {
      const qs = av.querySet(qsInput);

      expect(qs).toBeAn(QuerySet);
    });

    it('should be run()able and return a Promise', () => {
      const qs = av.querySet(qsInput);

      expect(qs.run()).toBeAn(Promise);
    });

    it('should resolve the run() promise with the entire data set', () => {
      const qs = av.querySet(qsInput);

      return qs.run().then(data => {
        expect(data).toEqual({ worklistSamples: { samples: { samples: [] } } });
      });
    });

    it('should emit change events, more than 1, in case of success', () => {
      const qs = av.querySet(qsInput);
      const spy = sinon.spy();
      qs.on('change', spy);

      return qs.run().then(() => {
        console.log(spy);
        expect(spy.callCount).toBeGreaterThan(1);
      });
    });

  });

});
<commit_msg>linter<commit_after>import expect from 'expect';
import sinon from 'sinon';
import Avenger, { QuerySet } from '../../src';
import queries from '../../fixtures/queries';

describe('Avenger', () => {

  const API = {
    fetchWorklist: (_id) => Promise.resolve({ worklist: { _id } }),
    fetchSamples: () => Promise.resolve({ samples: [] })
  };

  it('should be instantiable and accept valid queries set', () => {
    const { worklist } = queries(API);
    const av = new Avenger({ worklist });

    expect(av).toBeAn(Avenger);
  });

  describe('QuerySet', () => {
    const { worklist, worklistSamples } = queries(API);
    const av = new Avenger({ worklist, worklistSamples });
    const qsInput = { queries: { worklistSamples }, state: { worklistId: 'foo' } };

    it('should be created given a valid input', () => {
      const qs = av.querySet(qsInput);

      expect(qs).toBeAn(QuerySet);
    });

    it('should be run()able and return a Promise', () => {
      const qs = av.querySet(qsInput);

      expect(qs.run()).toBeAn(Promise);
    });

    it('should resolve the run() promise with the entire data set', () => {
      const qs = av.querySet(qsInput);

      return qs.run().then(data => {
        expect(data).toEqual({ worklistSamples: { samples: { samples: [] } } });
      });
    });

    it('should emit change events, more than 1, in case of success', () => {
      const qs = av.querySet(qsInput);
      const spy = sinon.spy();
      qs.on('change', spy);

      return qs.run().then(() => {
        console.log(spy);
        expect(spy.callCount).toBeGreaterThan(1);
      });
    });

  });

});
<|endoftext|>


<commit_before>// tests for levelup API compatibility

var path = require('path')
var concat = require('concat-stream')

module.exports.putGet = function(test, common) {
  test('.put + .get', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        dat.get('foo', function(err, data) {
          t.notOk(err, 'no err')
          t.equal(data.bar, "baz")
          setImmediate(done)
        })
      })
    })
  })
}

module.exports.del = function(test, common) {
  test('.del', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        dat.del('foo', function(err, data) {
          t.notOk(err, 'no err')
          setImmediate(done)
        })
      })
    })
  })
}

module.exports.createReadStream = function(test, common) {
  test('.createReadStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.createReadStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 row')
          t.ok(rows[0].key, '.key')
          t.ok(rows[0].value, '.value')
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.readStream = function(test, common) {
  test('.readStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.readStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 row')
          t.ok(rows[0].key, '.key')
          t.ok(rows[0].value, '.value')
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.createValueStream = function(test, common) {
  test('.createValueStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.readStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 row')
          t.ok(rows[0], '.key')
          t.ok(rows[0], '.value')
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.valueStream = function(test, common) {
  test('.valueStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.readStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 row')
          t.ok(rows[0], '.key')
          t.ok(rows[0], '.value')
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.createKeyStream = function(test, common) {
  test('.createKeyStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.createKeyStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 key')
          t.equal(rows[0].key, 'foo')
          t.equal(rows[0].version, 1)
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.keyStream = function(test, common) {
  test('.keyStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.keyStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 key')
          t.equal(rows[0].key, 'foo')
          t.equal(rows[0].version, 1)
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.createWriteStream = function(test, common) {
  test('.createWriteStream', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ objects: true })

      ws.on('end', function() {
        var rs = dat.keyStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 key')
          t.equal(rows[0].key, 'foo')
          t.equal(rows[0].version, 1)
          setImmediate(done)
        }))
      })

      ws.write({"key": "foo", "b": "bar", "c": "hello"})
      ws.end()
    })
  })
}

module.exports.writeStream = function(test, common) {
  test('.writeStream', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.writeStream({ objects: true })

      ws.on('end', function() {
        var rs = dat.keyStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 key')
          t.equal(rows[0].key, 'foo')
          t.equal(rows[0].version, 1)
          setImmediate(done)
        }))
      })

      ws.write({"key": "foo", "b": "bar", "c": "hello"})
      ws.end()
    })
  })
}

module.exports.isOpen = function(test, common) {
  test('.isOpen', function(t) {
    common.getDat(t, function(dat, done) {
      var state = dat.isOpen()
      t.equal(state, true, 'open')
      done()
    })
  })
}

module.exports.isClosed = function(test, common) {
  test('.isClosed', function(t) {
    common.getDat(t, function(dat, done) {
      var state = dat.isClosed()
      t.equal(state, false, 'is not closed')
      done()
    })
  })
}

module.exports.all = function (test, common) {
  module.exports.putGet(test, common)
  module.exports.del(test, common)
  module.exports.createReadStream(test, common)
  module.exports.readStream(test, common)
  module.exports.createValueStream(test, common)
  module.exports.valueStream(test, common)
  module.exports.createKeyStream(test, common)
  module.exports.keyStream(test, common)
  module.exports.createWriteStream(test, common)
  module.exports.writeStream(test, common)
  module.exports.isOpen(test, common)
  module.exports.isClosed(test, common)
  // module.exports.batch(test, common)
}
<commit_msg>fix valueStream tests<commit_after>// tests for levelup API compatibility

var path = require('path')
var concat = require('concat-stream')

module.exports.putGet = function(test, common) {
  test('.put + .get', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        dat.get('foo', function(err, data) {
          t.notOk(err, 'no err')
          t.equal(data.bar, "baz")
          setImmediate(done)
        })
      })
    })
  })
}

module.exports.del = function(test, common) {
  test('.del', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        dat.del('foo', function(err, data) {
          t.notOk(err, 'no err')
          setImmediate(done)
        })
      })
    })
  })
}

module.exports.createReadStream = function(test, common) {
  test('.createReadStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.createReadStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 row')
          t.ok(rows[0].key, '.key')
          t.ok(rows[0].value, '.value')
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.readStream = function(test, common) {
  test('.readStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.readStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 row')
          t.ok(rows[0].key, '.key')
          t.ok(rows[0].value, '.value')
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.createValueStream = function(test, common) {
  test('.createValueStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.createValueStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 row')
          t.equal(rows[0].bar, 'baz', 'baz')
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.valueStream = function(test, common) {
  test('.valueStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.valueStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 row')
          t.equal(rows[0].bar, 'baz', 'baz')
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.createKeyStream = function(test, common) {
  test('.createKeyStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.createKeyStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 key')
          t.equal(rows[0].key, 'foo')
          t.equal(rows[0].version, 1)
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.keyStream = function(test, common) {
  test('.keyStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put('foo', {"bar": "baz"}, function(err, doc) {
        if (err) throw err
        var rs = dat.keyStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 key')
          t.equal(rows[0].key, 'foo')
          t.equal(rows[0].version, 1)
          setImmediate(done)
        }))
      })
    })
  })
}

module.exports.createWriteStream = function(test, common) {
  test('.createWriteStream', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ objects: true })

      ws.on('end', function() {
        var rs = dat.keyStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 key')
          t.equal(rows[0].key, 'foo')
          t.equal(rows[0].version, 1)
          setImmediate(done)
        }))
      })

      ws.write({"key": "foo", "b": "bar", "c": "hello"})
      ws.end()
    })
  })
}

module.exports.writeStream = function(test, common) {
  test('.writeStream', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.writeStream({ objects: true })

      ws.on('end', function() {
        var rs = dat.keyStream()
        rs.pipe(concat(function(rows) {
          t.equal(rows.length, 1, '1 key')
          t.equal(rows[0].key, 'foo')
          t.equal(rows[0].version, 1)
          setImmediate(done)
        }))
      })

      ws.write({"key": "foo", "b": "bar", "c": "hello"})
      ws.end()
    })
  })
}

module.exports.isOpen = function(test, common) {
  test('.isOpen', function(t) {
    common.getDat(t, function(dat, done) {
      var state = dat.isOpen()
      t.equal(state, true, 'open')
      done()
    })
  })
}

module.exports.isClosed = function(test, common) {
  test('.isClosed', function(t) {
    common.getDat(t, function(dat, done) {
      var state = dat.isClosed()
      t.equal(state, false, 'is not closed')
      done()
    })
  })
}

module.exports.all = function (test, common) {
  module.exports.putGet(test, common)
  module.exports.del(test, common)
  module.exports.createReadStream(test, common)
  module.exports.readStream(test, common)
  module.exports.createValueStream(test, common)
  module.exports.valueStream(test, common)
  module.exports.createKeyStream(test, common)
  module.exports.keyStream(test, common)
  module.exports.createWriteStream(test, common)
  module.exports.writeStream(test, common)
  module.exports.isOpen(test, common)
  module.exports.isClosed(test, common)
  // module.exports.batch(test, common)
}
<|endoftext|>


<commit_before>'use strict';

describe('ProAct.Registry', function () {
  describe('examples', function () {
    it ('Counter system', function () {
      ProAct.registry.make('s:plus'); // One stream to count.
      ProAct.registry.make('s:minus', 'map(-)'); // One stream to count with negative sign.
      ProAct.registry.make('s:counts', '<<(s:plus, s:minus)|acc(+)'); // One stream that depends on the above ones and sums.
      ProAct.registry.prob('counter', 0, '<<(s:counts)'); // One ProAct.Val to store the result.

      expect(ProAct.registry.get('po:counter').v).toEqual(0);

      ProAct.registry.s('plus').trigger(1);
      expect(ProAct.registry.get('po:counter').v).toEqual(1);

      ProAct.registry.s('minus').trigger(1);
      expect(ProAct.registry.get('po:counter').v).toEqual(0);

      ProAct.registry.s('plus').trigger(2);
      expect(ProAct.registry.get('po:counter').v).toEqual(2);
    });
  });
});
<commit_msg>Fixed registry spec.<commit_after>'use strict';

describe('ProAct.Registry', function () {
  describe('examples', function () {
    it ('Counter system', function () {
      ProAct.registry.make('s:plus'); // One stream to count.
      ProAct.registry.make('s:minus', 'map(-)'); // One stream to count with negative sign.
      ProAct.registry.make('s:counts', '<<(s:plus, s:minus)|acc(+)'); // One stream that depends on the above ones and sums.
      ProAct.registry.prob('counter', 0, '<<(s:counts)'); // One ProAct.Property to store the result.

      expect(ProAct.registry.get('po:counter').v).toEqual(0);

      ProAct.registry.s('plus').trigger(1);
      expect(ProAct.registry.get('po:counter').v).toEqual(1);

      ProAct.registry.s('minus').trigger(1);
      expect(ProAct.registry.get('po:counter').v).toEqual(0);

      ProAct.registry.s('plus').trigger(2);
      expect(ProAct.registry.get('po:counter').v).toEqual(2);
    });
  });
});
<|endoftext|>


<commit_before>describe('cli parser', function () {
    var _ = require('lodash'),
        sinon = require('sinon'),
        newman = require('../../'),
        commander = require('commander'),
        newmanCLI,

        /**
         * Wrap newmanCLI callback to extract options passed to sinon `newman` stub.
         *
         * @param {String[]} argv - Argument vector.
         * @param {String} command - Newman command name, used for `sinon` result lookup.
         * @param {Function} callback - The callback function invoked on the completion of commander parsing.
         */
        cli = (argv, command, callback) => {
            newmanCLI(argv, (err) => {
                callback(err, _.get(newman, [command, 'lastCall', 'returnValue']));
            });
        };

    beforeEach(function () {
        // removes all listeners assigned previously to avoid exceeding MaxListeners.
        commander.removeAllListeners();

        // delete require cache to use program instance for consecutive runs.
        delete require.cache[require.resolve('../../bin/newman')];
        newmanCLI = require('../../bin/newman');
    });

    describe('Run Command', function () {
        // stub `newman.run`, directly return options passed to `newman.run` in newmanCLI.
        before(function () {
            sinon.stub(newman, 'run').callsFake((options) => {
                return options;
            });
        });

        // restore original `newman.run` function.
        after(function () {
            newman.run.restore();
        });

        it('should pass default options correctly', function (done) {
            cli('node newman.js run collection.json'.split(' '), 'run',
                function (err, opts) {
                    expect(err).to.be.null;

                    // explicitly match object to track addition/deletion of properties.
                    expect(opts).to.eql({
                        collection: 'collection.json',
                        reporters: ['cli'],
                        delayRequest: 0,
                        globalVar: [],
                        color: 'auto',
                        timeout: 0,
                        timeoutRequest: 0,
                        timeoutScript: 0,
                        reporterOptions: {},
                        reporter: { cli: {} }
                    });

                    done();
                });
        });

        it('should handle standard run command (run collection.json and -e)', function (done) {
            cli('node newman.js run myCollection.json --environment env.json -n 2'.split(' '), 'run',
                function (err, opts) {
                    expect(err).to.be.null;
                    expect(opts).to.be.ok;
                    expect(opts.iterationCount, 'should have iterationCount of 2').to.equal(2);
                    expect(opts.collection).to.equal('myCollection.json');
                    expect(opts.environment).to.equal('env.json');

                    done();
                });
        });

        it('should throw an error for invalid --iteration-count values', function (done) {
            cli('node newman.js run myCollection.json -n -3.14'.split(' '), 'run', function (err) {
                expect(err).to.have.property('message', 'The value must be a positive integer.');

                done();
            });
        });

        describe('--global-var', function () {
            // test for 'should throw an error for missing --global-var values' has been moved to
            // cli/run-options.test.js since commander throws custom error in case of argument
            //  mismatch and that is better handled through exec and stderr check.
            it('should handle --global-var values without an `=`', function (done) {
                cli('node newman.js run myCollection.json --global-var foo'.split(' '), 'run', function (err, opts) {
                    expect(err).to.be.null;
                    expect(opts.globalVar).to.eql([
                        { key: 'foo', value: undefined }
                    ]);

                    done();
                });
            });
        });

        describe('--color', function () {
            it('should have color `auto` by default', function (done) {
                cli('node newman.js run myCollection.json'.split(' '), 'run',
                    function (err, opts) {
                        expect(err).to.be.null;
                        expect(opts.color).to.equal('auto');
                        done();
                    });
            });

            it('should have color enabled with `--color on`', function (done) {
                cli('node newman.js run myCollection.json --color on'.split(' '), 'run',
                    function (err, opts) {
                        expect(err).to.be.null;
                        expect(opts.color).to.equal('on');
                        done();
                    });
            });

            it('should have color disabled with `--color off`', function (done) {
                cli('node newman.js run myCollection.json --color off'.split(' '), 'run',
                    function (err, opts) {
                        expect(err).to.be.null;
                        expect(opts.color).to.equal('off');
                        done();
                    });
            });

            it('should throw an error for invalid --color values', function (done) {
                cli('node newman.js run myCollection.json --color --disable-unicode'.split(' '), 'run', function (err) {
                    expect(err).to.have.property('message', 'invalid value `--disable-unicode` for option color');

                    done();
                });
            });
        });

        it('should load all arguments (except reporters)', function (done) {
            cli(('node newman.js run ' +
                'myCollection.json ' +
                '-e myEnv.json ' +
                '-g myGlobals.json ' +
                '-d path/to/csv.csv ' +
                '--folder myFolder ' +
                '--export-environment exported_env.json ' +
                '--export-globals exported_glob.json ' +
                '--postman-api-key POSTMAN_API_KEY ' +
                '--reporter-cli-no-summary ' +
                '--iteration-count 23 ' +
                '--reporters json ' +
                '--global-var foo=bar --global-var alpha==beta= ' +
                '--color off ' +
                '--delay-request 12000 ' +
                '--timeout 10000 ' +
                '--timeout-request 5000 ' +
                '--timeout-script 5000 ' +
                '--ignore-redirects ' +
                '--bail ' +
                '--suppress-exit-code ' +
                '-k').split(' '), 'run', function (err, opts) {
                expect(err).to.be.null;

                expect(opts).to.be.ok;
                expect(opts.collection).to.equal('myCollection.json');
                expect(opts.environment).to.equal('myEnv.json');
                expect(opts.folder).to.equal('myFolder');
                expect(opts.exportEnvironment).to.equal('exported_env.json');
                expect(opts.iterationData).to.equal('path/to/csv.csv');
                expect(opts.globals).to.equal('myGlobals.json');
                expect(opts.exportGlobals).to.equal('exported_glob.json');
                expect(opts.postmanApiKey).to.equal('POSTMAN_API_KEY');
                expect(opts.delayRequest, 'should have delayRequest of 12000').to.equal(12000);
                expect(opts.timeout, 'should have timeout of 10000').to.equal(10000);
                expect(opts.timeoutRequest, 'should have timeoutRequest of 5000').to.equal(5000);
                expect(opts.timeoutScript, 'should have timeoutScript of 5000').to.equal(5000);
                expect(opts.ignoreRedirects, 'should have ignoreRedirects to be true').to.equal(true);
                expect(opts.insecure, 'shoudl have insecure to be true').to.equal(true);

                expect(opts.color).to.equal('off');

                expect(opts.reporters).to.contain('json');
                expect(opts.reporters).to.not.contain('junit');

                expect(opts.globalVar).to.eql([
                    { key: 'foo', value: 'bar' },
                    { key: 'alpha', value: '=beta=' }
                ]);

                expect(opts.bail, 'should have bail to be true').to.equal(true);
                expect(opts.suppressExitCode, 'should have suppressExitCode to be true').to.equal(true);

                done();
            });
        });

        it('should load all arguments (including reporters)', function (done) {
            cli(('node newman.js run ' +
                'myCollection.json ' +
                '-e myEnv.json ' +
                '-g myGlobals.json ' +
                '-d /path/to/csv.csv ' +
                '--folder myFolder ' +
                '--disable-unicode ' +
                '--export-environment exported_env.json ' +
                '--export-globals exported_glob.json ' +
                '--reporter-cli-no-summary ' +
                '--reporter-cli-no-success-assertions ' +
                '--iteration-count 23 ' +
                '--reporters json ' +
                '--color on ' +
                '--delay-request 12000 ' +
                '--timeout 10000 ' +
                '--timeout-request 5000 ' +
                '--timeout-script 5000 ' +
                '--ignore-redirects ' +
                '-k ' +
                '--bail folder,failure ' +
                '--global-var foo=bar --global-var alpha==beta= ' +
                '--reporter-json-output ./omg.txt ' +
                '--reporter-use everything').split(' '), 'run', function (err, opts) {
                expect(err).to.be.null;

                expect(opts).to.be.ok;
                expect(opts.collection).to.equal('myCollection.json');
                expect(opts.environment).to.equal('myEnv.json');
                expect(opts.folder).to.equal('myFolder');
                expect(opts.disableUnicode, 'should have disableUnicode to be true').to.equal(true);

                expect(opts.exportEnvironment).to.equal('exported_env.json');
                expect(opts.iterationData).to.equal('/path/to/csv.csv');
                expect(opts.globals).to.equal('myGlobals.json');

                expect(opts.exportGlobals).to.equal('exported_glob.json');
                expect(opts.delayRequest, 'should have delayRequest of 12000').to.equal(12000);
                expect(opts.timeout, 'should have timeout of 10000').to.equal(10000);
                expect(opts.timeoutRequest, 'should have timeoutRequest of 5000').to.equal(5000);
                expect(opts.timeoutScript, 'should have timeoutScript of 5000').to.equal(5000);
                expect(opts.ignoreRedirects, 'should have ignoreRedirects to be true').to.equal(true);
                expect(opts.insecure, 'should have insecure to be true').to.equal(true);

                expect(opts.globalVar).to.eql([
                    { key: 'foo', value: 'bar' },
                    { key: 'alpha', value: '=beta=' }
                ]);
                expect(opts.bail).to.eql([
                    'folder',
                    'failure'
                ]);

                expect(opts.color).to.equal('on');

                expect(opts.reporters).to.contain('json');
                expect(opts.reporters).to.not.contain('verbose');
                expect(opts.reporters).to.not.contain('junit');

                // Generic reporter options
                expect(opts.reporterOptions).to.be.ok;
                expect(opts.reporterOptions.use).to.equal('everything');
                expect(opts.reporterOptions.cliNoSuccessAssertions
                    , 'should have cliNoSuccessAssertions to be true').to.equal(true);

                // Individual reporter options
                expect(opts.reporter).to.be.ok;

                // Validate JSON reporter configuration
                expect(opts.reporter.json).to.be.ok;
                expect(opts.reporter.json.output).to.equal('./omg.txt');
                expect(opts.reporter.json.use).to.equal('everything');

                done();
            });
        });

        it('should turn off newman banner if --reporter-cli-no-banner is set', function (done) {
            cli('node newman.js run myCollection.json --reporter-cli-no-banner'.split(' '), 'run',
                function (err, opts) {
                    expect(err).to.be.null;
                    expect(opts).to.be.ok;
                    expect(opts.reporter.cli.noBanner, 'should have noBanner to be true').to.equal(true);

                    done();
                });
        });
    });
});
<commit_msg>Minor: update test<commit_after>describe('cli parser', function () {
    var _ = require('lodash'),
        sinon = require('sinon'),
        newman = require('../../'),
        commander = require('commander'),
        newmanCLI,

        /**
         * Wrap newmanCLI callback to extract options passed to sinon `newman` stub.
         *
         * @param {String[]} argv - Argument vector.
         * @param {String} command - Newman command name, used for `sinon` result lookup.
         * @param {Function} callback - The callback function invoked on the completion of commander parsing.
         */
        cli = (argv, command, callback) => {
            newmanCLI(argv, (err) => {
                callback(err, _.get(newman, [command, 'lastCall', 'returnValue']));
            });
        };

    beforeEach(function () {
        // removes all listeners assigned previously to avoid exceeding MaxListeners.
        commander.removeAllListeners();

        // delete require cache to use program instance for consecutive runs.
        delete require.cache[require.resolve('../../bin/newman')];
        newmanCLI = require('../../bin/newman');
    });

    describe('Run Command', function () {
        // stub `newman.run`, directly return options passed to `newman.run` in newmanCLI.
        before(function () {
            sinon.stub(newman, 'run').callsFake((options) => {
                return options;
            });
        });

        // restore original `newman.run` function.
        after(function () {
            newman.run.restore();
        });

        it('should pass default options correctly', function (done) {
            cli('node newman.js run collection.json'.split(' '), 'run',
                function (err, opts) {
                    expect(err).to.be.null;

                    // explicitly match object to track addition/deletion of properties.
                    expect(opts).to.eql({
                        collection: 'collection.json',
                        reporters: ['cli'],
                        delayRequest: 0,
                        globalVar: [],
                        color: 'auto',
                        timeout: 0,
                        timeoutRequest: 0,
                        timeoutScript: 0,
                        reporterOptions: {},
                        reporter: { cli: {} }
                    });

                    done();
                });
        });

        it('should handle standard run command (run collection.json and -e)', function (done) {
            cli('node newman.js run myCollection.json --environment env.json -n 2'.split(' '), 'run',
                function (err, opts) {
                    expect(err).to.be.null;
                    expect(opts).to.be.ok;
                    expect(opts.iterationCount, 'should have iterationCount of 2').to.equal(2);
                    expect(opts.collection).to.equal('myCollection.json');
                    expect(opts.environment).to.equal('env.json');

                    done();
                });
        });

        it('should throw an error for invalid --iteration-count values', function (done) {
            cli('node newman.js run myCollection.json -n -3.14'.split(' '), 'run', function (err) {
                expect(err).to.have.property('message', 'The value must be a positive integer.');

                done();
            });
        });

        describe('--global-var', function () {
            // test for 'should throw an error for missing --global-var values' has been moved to
            // cli/run-options.test.js since commander throws custom error in case of argument
            //  mismatch and that is better handled through exec and stderr check.
            it('should handle --global-var values without an `=`', function (done) {
                cli('node newman.js run myCollection.json --global-var foo'.split(' '), 'run', function (err, opts) {
                    expect(err).to.be.null;
                    expect(opts.globalVar).to.eql([
                        { key: 'foo', value: undefined }
                    ]);

                    done();
                });
            });
        });

        describe('--color', function () {
            it('should have color `auto` by default', function (done) {
                cli('node newman.js run myCollection.json'.split(' '), 'run',
                    function (err, opts) {
                        expect(err).to.be.null;
                        expect(opts.color).to.equal('auto');
                        done();
                    });
            });

            it('should have color enabled with `--color on`', function (done) {
                cli('node newman.js run myCollection.json --color on'.split(' '), 'run',
                    function (err, opts) {
                        expect(err).to.be.null;
                        expect(opts.color).to.equal('on');
                        done();
                    });
            });

            it('should have color disabled with `--color off`', function (done) {
                cli('node newman.js run myCollection.json --color off'.split(' '), 'run',
                    function (err, opts) {
                        expect(err).to.be.null;
                        expect(opts.color).to.equal('off');
                        done();
                    });
            });

            it('should throw an error for invalid --color values', function (done) {
                cli('node newman.js run myCollection.json --color --disable-unicode'.split(' '), 'run', function (err) {
                    expect(err).to.have.property('message',
                        'invalid value `--disable-unicode` for --color. Expected: auto|on|off');

                    done();
                });
            });
        });

        it('should load all arguments (except reporters)', function (done) {
            cli(('node newman.js run ' +
                'myCollection.json ' +
                '-e myEnv.json ' +
                '-g myGlobals.json ' +
                '-d path/to/csv.csv ' +
                '--folder myFolder ' +
                '--export-environment exported_env.json ' +
                '--export-globals exported_glob.json ' +
                '--postman-api-key POSTMAN_API_KEY ' +
                '--reporter-cli-no-summary ' +
                '--iteration-count 23 ' +
                '--reporters json ' +
                '--global-var foo=bar --global-var alpha==beta= ' +
                '--color off ' +
                '--delay-request 12000 ' +
                '--timeout 10000 ' +
                '--timeout-request 5000 ' +
                '--timeout-script 5000 ' +
                '--ignore-redirects ' +
                '--bail ' +
                '--suppress-exit-code ' +
                '-k').split(' '), 'run', function (err, opts) {
                expect(err).to.be.null;

                expect(opts).to.be.ok;
                expect(opts.collection).to.equal('myCollection.json');
                expect(opts.environment).to.equal('myEnv.json');
                expect(opts.folder).to.equal('myFolder');
                expect(opts.exportEnvironment).to.equal('exported_env.json');
                expect(opts.iterationData).to.equal('path/to/csv.csv');
                expect(opts.globals).to.equal('myGlobals.json');
                expect(opts.exportGlobals).to.equal('exported_glob.json');
                expect(opts.postmanApiKey).to.equal('POSTMAN_API_KEY');
                expect(opts.delayRequest, 'should have delayRequest of 12000').to.equal(12000);
                expect(opts.timeout, 'should have timeout of 10000').to.equal(10000);
                expect(opts.timeoutRequest, 'should have timeoutRequest of 5000').to.equal(5000);
                expect(opts.timeoutScript, 'should have timeoutScript of 5000').to.equal(5000);
                expect(opts.ignoreRedirects, 'should have ignoreRedirects to be true').to.equal(true);
                expect(opts.insecure, 'shoudl have insecure to be true').to.equal(true);

                expect(opts.color).to.equal('off');

                expect(opts.reporters).to.contain('json');
                expect(opts.reporters).to.not.contain('junit');

                expect(opts.globalVar).to.eql([
                    { key: 'foo', value: 'bar' },
                    { key: 'alpha', value: '=beta=' }
                ]);

                expect(opts.bail, 'should have bail to be true').to.equal(true);
                expect(opts.suppressExitCode, 'should have suppressExitCode to be true').to.equal(true);

                done();
            });
        });

        it('should load all arguments (including reporters)', function (done) {
            cli(('node newman.js run ' +
                'myCollection.json ' +
                '-e myEnv.json ' +
                '-g myGlobals.json ' +
                '-d /path/to/csv.csv ' +
                '--folder myFolder ' +
                '--disable-unicode ' +
                '--export-environment exported_env.json ' +
                '--export-globals exported_glob.json ' +
                '--reporter-cli-no-summary ' +
                '--reporter-cli-no-success-assertions ' +
                '--iteration-count 23 ' +
                '--reporters json ' +
                '--color on ' +
                '--delay-request 12000 ' +
                '--timeout 10000 ' +
                '--timeout-request 5000 ' +
                '--timeout-script 5000 ' +
                '--ignore-redirects ' +
                '-k ' +
                '--bail folder,failure ' +
                '--global-var foo=bar --global-var alpha==beta= ' +
                '--reporter-json-output ./omg.txt ' +
                '--reporter-use everything').split(' '), 'run', function (err, opts) {
                expect(err).to.be.null;

                expect(opts).to.be.ok;
                expect(opts.collection).to.equal('myCollection.json');
                expect(opts.environment).to.equal('myEnv.json');
                expect(opts.folder).to.equal('myFolder');
                expect(opts.disableUnicode, 'should have disableUnicode to be true').to.equal(true);

                expect(opts.exportEnvironment).to.equal('exported_env.json');
                expect(opts.iterationData).to.equal('/path/to/csv.csv');
                expect(opts.globals).to.equal('myGlobals.json');

                expect(opts.exportGlobals).to.equal('exported_glob.json');
                expect(opts.delayRequest, 'should have delayRequest of 12000').to.equal(12000);
                expect(opts.timeout, 'should have timeout of 10000').to.equal(10000);
                expect(opts.timeoutRequest, 'should have timeoutRequest of 5000').to.equal(5000);
                expect(opts.timeoutScript, 'should have timeoutScript of 5000').to.equal(5000);
                expect(opts.ignoreRedirects, 'should have ignoreRedirects to be true').to.equal(true);
                expect(opts.insecure, 'should have insecure to be true').to.equal(true);

                expect(opts.globalVar).to.eql([
                    { key: 'foo', value: 'bar' },
                    { key: 'alpha', value: '=beta=' }
                ]);
                expect(opts.bail).to.eql([
                    'folder',
                    'failure'
                ]);

                expect(opts.color).to.equal('on');

                expect(opts.reporters).to.contain('json');
                expect(opts.reporters).to.not.contain('verbose');
                expect(opts.reporters).to.not.contain('junit');

                // Generic reporter options
                expect(opts.reporterOptions).to.be.ok;
                expect(opts.reporterOptions.use).to.equal('everything');
                expect(opts.reporterOptions.cliNoSuccessAssertions
                    , 'should have cliNoSuccessAssertions to be true').to.equal(true);

                // Individual reporter options
                expect(opts.reporter).to.be.ok;

                // Validate JSON reporter configuration
                expect(opts.reporter.json).to.be.ok;
                expect(opts.reporter.json.output).to.equal('./omg.txt');
                expect(opts.reporter.json.use).to.equal('everything');

                done();
            });
        });

        it('should turn off newman banner if --reporter-cli-no-banner is set', function (done) {
            cli('node newman.js run myCollection.json --reporter-cli-no-banner'.split(' '), 'run',
                function (err, opts) {
                    expect(err).to.be.null;
                    expect(opts).to.be.ok;
                    expect(opts.reporter.cli.noBanner, 'should have noBanner to be true').to.equal(true);

                    done();
                });
        });
    });
});
<|endoftext|>


<commit_before>// run with `yarn test`
import { SearchEx, FigureSearchEx } from "search_ex.js"

describe("x = toLisp of fromLisp of x", () => {
  ;[
    ["figure", "do si do"],
    ["figure", "swing", "partners", "*", 8],
    ["formation", "improper"],
    ["progression"],
    ["or", ["figure", "do si do"], ["figure", "swing"]],
    ["and", ["figure", "do si do"], ["figure", "swing"]],
    ["&", ["progression"], ["figure", "star"]],
    ["then", ["figure", "do si do"], ["figure", "swing"]],
    ["no", ["progression"]],
    ["not", ["figure", "do si do"]],
    ["all", ["figure", "do si do"]],
    ["count", ["progression"], ">", 0],
    ["compare", ["constant", 4], "<", ["constant", 6]],
    ["constant", 5],
    ["constant", 0],
    ["tag", "verified"],
    ["count-matches", ["figure", "*"]],
  ].forEach(function(lisp, i) {
    test(JSON.stringify(lisp), () =>
      expect(SearchEx.fromLisp(lisp).toLisp()).toEqual(lisp)
    )
  })
})

describe("cast", () => {
  ;[
    {
      op: "then",
      from: ["progression"],
      want: ["then", ["progression"], ["figure", "*"]],
    },
    {
      op: "then",
      from: ["not", ["progression"]],
      want: ["then", ["not", ["progression"]], ["figure", "*"]],
    },
    { op: "then", from: ["and"], want: ["then"] },
    {
      op: "then",
      from: ["and", ["progression"]],
      want: ["then", ["progression"]],
    },
    {
      op: "then",
      from: ["and", ["progression"], ["figure", "chain"]],
      want: ["then", ["progression"], ["figure", "chain"]],
    },
    {
      op: "and",
      from: ["figure", "swing"],
      want: ["and", ["figure", "swing"], ["figure", "*"]],
    },
    { op: "figure", from: ["and"], want: ["figure", "*"] },
    { op: "formation", from: ["and"], want: ["formation", "improper"] },
    { op: "progression", from: ["and"], want: ["progression"] },
    { op: "no", from: ["and"], want: ["no", ["and"]] },
    { op: "no", from: ["not", ["figure", "*"]], want: ["no", ["figure", "*"]] },
    {
      op: "no",
      from: ["or", ["figure", "swing"], ["figure", "chain"]],
      want: ["no", ["or", ["figure", "swing"], ["figure", "chain"]]],
    },
    { op: "not", from: ["and"], want: ["not", ["and"]] },
    {
      op: "not",
      from: ["no", ["figure", "*"]],
      want: ["not", ["figure", "*"]],
    },
    {
      op: "not",
      from: ["or", ["figure", "swing"], ["figure", "chain"]],
      want: ["not", ["or", ["figure", "swing"], ["figure", "chain"]]],
    },
    { op: "all", from: ["and"], want: ["all", ["and"]] },
    {
      op: "all",
      from: ["no", ["figure", "*"]],
      want: ["all", ["figure", "*"]],
    },
    {
      op: "all",
      from: ["or", ["figure", "swing"], ["figure", "chain"]],
      want: ["all", ["or", ["figure", "swing"], ["figure", "chain"]]],
    },
    { op: "count", from: ["and"], want: ["count", ["and"], ">", 0] },
    {
      op: "count",
      from: ["no", ["figure", "*"]],
      want: ["count", ["figure", "*"], ">", 0],
    },
    {
      op: "count",
      from: ["or", ["figure", "swing"], ["figure", "chain"]],
      want: ["count", ["or", ["figure", "swing"], ["figure", "chain"]], ">", 0],
    },
    {
      op: "compare",
      from: ["progression"],
      want: ["compare", ["constant", 0], ">", ["constant", 0]],
    },
    { op: "constant", from: ["tag", "verified"], want: ["constant", 0] },
    { op: "tag", from: ["constant", 7], want: ["tag", "verified"] },
    {
      op: "count-matches",
      from: ["constant", 7],
      want: ["count-matches", ["figure", "*"]],
    },
  ].forEach(function({ from, op, want }, i) {
    const fromEx = SearchEx.fromLisp(from)
    const got = fromEx.castTo(op).toLisp()
    test(`${fromEx}.castTo('${op}') ≈> ${JSON.stringify(want)}`, () => {
      expect(got).toEqual(want)
    })
  })
})

test("casts", () => {})

describe("ellipsis", () => {
  test("with parameters specified", () => {
    const searchEx = new FigureSearchEx({
      move: "swing",
      parameters: ["*", "*", 8],
    })
    const bigLisp = ["figure", "swing", "*", "*", 8]
    const shortLisp = ["figure", "swing"]
    expect(searchEx.toLisp()).toEqual(bigLisp)
    expect(searchEx.ellipsis).toEqual(true)
    searchEx.ellipsis = false
    expect(searchEx.ellipsis).toEqual(false)
    expect(searchEx.toLisp()).toEqual(shortLisp)
    searchEx.ellipsis = true
    expect(searchEx.ellipsis).toEqual(true)
    expect(searchEx.toLisp()).toEqual(bigLisp)
  })

  test("without parameters left off", () => {
    const searchEx = new FigureSearchEx({ move: "swing" })
    const bigLisp = ["figure", "swing", "*", "*", "*"]
    const shortLisp = ["figure", "swing"]
    expect(searchEx.ellipsis).toEqual(false)
    expect(searchEx.toLisp()).toEqual(shortLisp)
    searchEx.ellipsis = true
    expect(searchEx.ellipsis).toEqual(true)
    expect(searchEx.toLisp()).toEqual(bigLisp)
    searchEx.ellipsis = false
    expect(searchEx.ellipsis).toEqual(false)
    expect(searchEx.toLisp()).toEqual(shortLisp)
  })
})
test("copy", () => {
  const originalLisp = ["and", ["figure", "do si do"], ["figure", "swing"]]
  const original = SearchEx.fromLisp(originalLisp)
  const copy = original.copy()
  copy.subexpressions[0].move = "circle"
  expect(copy.toLisp()).toEqual([
    "and",
    ["figure", "circle"],
    ["figure", "swing"],
  ])
  expect(original.toLisp()).toEqual(originalLisp)
})
<commit_msg>clean up search_ex.spec<commit_after>// run with `yarn test`
import { SearchEx, FigureSearchEx } from "search_ex.js"

describe("x = toLisp of fromLisp of x", () => {
  ;[
    ["figure", "do si do"],
    ["figure", "swing", "partners", "*", 8],
    ["formation", "improper"],
    ["progression"],
    ["or", ["figure", "do si do"], ["figure", "swing"]],
    ["and", ["figure", "do si do"], ["figure", "swing"]],
    ["&", ["progression"], ["figure", "star"]],
    ["then", ["figure", "do si do"], ["figure", "swing"]],
    ["no", ["progression"]],
    ["not", ["figure", "do si do"]],
    ["all", ["figure", "do si do"]],
    ["count", ["progression"], ">", 0],
    ["compare", ["constant", 4], "<", ["constant", 6]],
    ["constant", 5],
    ["constant", 0],
    ["tag", "verified"],
    ["count-matches", ["figure", "*"]],
  ].forEach(function(lisp, i) {
    test(JSON.stringify(lisp), () =>
      expect(SearchEx.fromLisp(lisp).toLisp()).toEqual(lisp)
    )
  })
})

describe("cast", () => {
  ;[
    {
      op: "then",
      from: ["progression"],
      want: ["then", ["progression"], ["figure", "*"]],
    },
    {
      op: "then",
      from: ["not", ["progression"]],
      want: ["then", ["not", ["progression"]], ["figure", "*"]],
    },
    { op: "then", from: ["and"], want: ["then"] },
    {
      op: "then",
      from: ["and", ["progression"]],
      want: ["then", ["progression"]],
    },
    {
      op: "then",
      from: ["and", ["progression"], ["figure", "chain"]],
      want: ["then", ["progression"], ["figure", "chain"]],
    },
    {
      op: "and",
      from: ["figure", "swing"],
      want: ["and", ["figure", "swing"], ["figure", "*"]],
    },
    { op: "figure", from: ["and"], want: ["figure", "*"] },
    { op: "formation", from: ["and"], want: ["formation", "improper"] },
    { op: "progression", from: ["and"], want: ["progression"] },
    { op: "no", from: ["and"], want: ["no", ["and"]] },
    { op: "no", from: ["not", ["figure", "*"]], want: ["no", ["figure", "*"]] },
    {
      op: "no",
      from: ["or", ["figure", "swing"], ["figure", "chain"]],
      want: ["no", ["or", ["figure", "swing"], ["figure", "chain"]]],
    },
    { op: "not", from: ["and"], want: ["not", ["and"]] },
    {
      op: "not",
      from: ["no", ["figure", "*"]],
      want: ["not", ["figure", "*"]],
    },
    {
      op: "not",
      from: ["or", ["figure", "swing"], ["figure", "chain"]],
      want: ["not", ["or", ["figure", "swing"], ["figure", "chain"]]],
    },
    { op: "all", from: ["and"], want: ["all", ["and"]] },
    {
      op: "all",
      from: ["no", ["figure", "*"]],
      want: ["all", ["figure", "*"]],
    },
    {
      op: "all",
      from: ["or", ["figure", "swing"], ["figure", "chain"]],
      want: ["all", ["or", ["figure", "swing"], ["figure", "chain"]]],
    },
    { op: "count", from: ["and"], want: ["count", ["and"], ">", 0] },
    {
      op: "count",
      from: ["no", ["figure", "*"]],
      want: ["count", ["figure", "*"], ">", 0],
    },
    {
      op: "count",
      from: ["or", ["figure", "swing"], ["figure", "chain"]],
      want: ["count", ["or", ["figure", "swing"], ["figure", "chain"]], ">", 0],
    },
    {
      op: "compare",
      from: ["progression"],
      want: ["compare", ["constant", 0], ">", ["constant", 0]],
    },
    { op: "constant", from: ["tag", "verified"], want: ["constant", 0] },
    { op: "tag", from: ["constant", 7], want: ["tag", "verified"] },
    {
      op: "count-matches",
      from: ["constant", 7],
      want: ["count-matches", ["figure", "*"]],
    },
  ].forEach(function({ from, op, want }, i) {
    const fromEx = SearchEx.fromLisp(from)
    const got = fromEx.castTo(op).toLisp()
    test(`${fromEx}.castTo('${op}') ≈> ${JSON.stringify(want)}`, () => {
      expect(got).toEqual(want)
    })
  })
})

describe("ellipsis", () => {
  test("with parameters specified", () => {
    const searchEx = new FigureSearchEx({
      move: "swing",
      parameters: ["*", "*", 8],
    })
    const bigLisp = ["figure", "swing", "*", "*", 8]
    const shortLisp = ["figure", "swing"]
    expect(searchEx.toLisp()).toEqual(bigLisp)
    expect(searchEx.ellipsis).toEqual(true)
    searchEx.ellipsis = false
    expect(searchEx.ellipsis).toEqual(false)
    expect(searchEx.toLisp()).toEqual(shortLisp)
    searchEx.ellipsis = true
    expect(searchEx.ellipsis).toEqual(true)
    expect(searchEx.toLisp()).toEqual(bigLisp)
  })

  test("without parameters left off", () => {
    const searchEx = new FigureSearchEx({ move: "swing" })
    const bigLisp = ["figure", "swing", "*", "*", "*"]
    const shortLisp = ["figure", "swing"]
    expect(searchEx.ellipsis).toEqual(false)
    expect(searchEx.toLisp()).toEqual(shortLisp)
    searchEx.ellipsis = true
    expect(searchEx.ellipsis).toEqual(true)
    expect(searchEx.toLisp()).toEqual(bigLisp)
    searchEx.ellipsis = false
    expect(searchEx.ellipsis).toEqual(false)
    expect(searchEx.toLisp()).toEqual(shortLisp)
  })
})
test("copy", () => {
  const originalLisp = ["and", ["figure", "do si do"], ["figure", "swing"]]
  const original = SearchEx.fromLisp(originalLisp)
  const copy = original.copy()
  copy.subexpressions[0].move = "circle"
  expect(copy.toLisp()).toEqual([
    "and",
    ["figure", "circle"],
    ["figure", "swing"],
  ])
  expect(original.toLisp()).toEqual(originalLisp)
  expect(originalLisp[1][1]).toEqual("do si do")
})
<|endoftext|>


<commit_before>describe('Collapse:', function() {
  beforeEach(function() {
    loadFixtures('collapse_fixture.html');
    locastyle.collapse.init();

    window.test = {
      eventFunctionTest: function() {
        // fake function
      }
    };

    // spyOnEvent(window, 'ls-collapse-open');
    // spyOnEvent($('#myCollapse4 a'), 'click');
    // spyOn(window.test, "eventFunctionTest");

  });

  describe('When click to open collapse', function() {
    it('should target be visible', function() {
      $('#myCollapse1 [data-ls-module="collapse"]').trigger('click');
      expect($('#collapse1')).toBeVisible();
    });

    it("should trigger the event collapse:opened", function() {
      var spyEvent = spyOnEvent(document, 'collapse:opened');
      $('[data-ls-module="collapse"]').trigger("click");
      expect('collapse:opened').toHaveBeenTriggeredOn(document)
    });
  });

  describe('When click on opened collapse', function() {
    it("should trigger the event collapse:closed", function() {
      var spyEvent = spyOnEvent(document, 'collapse:closed');
      $('[data-dismiss="collapse"]').trigger("click");
      expect('collapse:closed').toHaveBeenTriggeredOn(document);
    });
  });

  describe('When collapse have a class ls-collapse-opened', function() {
    it('should target be visible', function() {
      expect($('.ls-collapse-opened #collapse2')).toBeVisible();
    });
  });

  describe('When collapse have a class ls-collapse-opened-always', function() {
    it('should target be not hidden', function() {
      $('#myCollapse3 [data-ls-module="collapse"]').trigger('click');
      expect($('.ls-collapse-opened-always #collapse3')).toBeVisible();
    });
  });

  describe('Group / Accordeon', function() {

    it('open collapse, close others', function() {
      var $collapseClose = $('#collapse4');
      var $collapseCloseBody = $collapseClose.find('.ls-collapse-body');
      var $collapseOpen = $('#collapse5');
      var $collapseOpenTitle = $collapseOpen.find('.ls-collapse-body');
      $collapseOpen.trigger("click");
      expect($collapseOpen.is(':visible')).toBe(true);
      expect($collapseClose.is(':visible')).toBe(true);
      $collapseClose.trigger("click");
      expect($collapseOpen.is(':visible')).toBe(true);
      expect($collapseClose.is(':visible')).toBe(true);
    });

  });

});
<commit_msg>add jasmine tests of event on the collapse<commit_after>describe('Collapse:', function() {

  beforeEach(function() {
    loadFixtures('collapse_fixture.html');
    locastyle.collapse.init();

  });

  describe('When click to open collapse', function() {
    it('should target be visible', function() {
      $('#myCollapse1 [data-ls-module="collapse"]').trigger('click');
      expect($('#collapse1')).toBeVisible();
    });

    it("should trigger the event collapse:opened", function() {
      var spyEvent = spyOnEvent(document, 'collapse:opened');
      $('#myCollapse1 [data-ls-module="collapse"]').trigger("click");
      expect('collapse:opened').toHaveBeenTriggeredOn(document);

      var spyEvent = spyOnEvent(document, 'collapse:closed');
      $('#myCollapse1 [data-ls-module="collapse"]').trigger("click");
      expect('collapse:closed').toHaveBeenTriggeredOn(document);
    });

  });

  describe('When collapse have a class ls-collapse-opened', function() {
    it('should target be visible', function() {
      expect($('.ls-collapse-opened #collapse2')).toBeVisible();
    });
  });

  describe('When collapse have a class ls-collapse-opened-always', function() {
    it('should target be not hidden', function() {
      $('#myCollapse3 [data-ls-module="collapse"]').trigger('click');
      expect($('.ls-collapse-opened-always #collapse3')).toBeVisible();
    });
  });

  describe('Group / Accordeon', function() {

    it('open collapse, close others', function() {
      var $collapseClose = $('#collapse4');
      var $collapseCloseBody = $collapseClose.find('.ls-collapse-body');
      var $collapseOpen = $('#collapse5');
      var $collapseOpenTitle = $collapseOpen.find('.ls-collapse-body');
      $collapseOpen.trigger("click");
      expect($collapseOpen.is(':visible')).toBe(true);
      expect($collapseClose.is(':visible')).toBe(true);
      $collapseClose.trigger("click");
      expect($collapseOpen.is(':visible')).toBe(true);
      expect($collapseClose.is(':visible')).toBe(true);
    });

  });

});
<|endoftext|>


<commit_before>import { metric } from '../text-formatters.js'
import { nonNegativeInteger } from '../validators.js'
import { BaseService } from '../index.js'
import {
  dockerBlue,
  buildDockerUrl,
  getDockerHubUser,
} from './docker-helpers.js'

export default class DockerStars extends BaseService {
  static category = 'rating'
  static route = buildDockerUrl('stars')
  static examples = [
    {
      title: 'Docker Stars',
      namedParams: {
        user: '_',
        repo: 'ubuntu',
      },
      staticPreview: this.render({ stars: 9000 }),
    },
  ]

  static defaultBadgeData = { label: 'docker stars' }

  static render({ stars }) {
    return {
      message: metric(stars),
      color: dockerBlue,
    }
  }

  async fetch({ user, repo }) {
    const url = `https://hub.docker.com/v2/repositories/${getDockerHubUser(
      user
    )}/${repo}/stars/count/`
    const { buffer } = await this._request({
      url,
      errorMessages: { 404: 'repo not found' },
    })
    return this.constructor._validate(buffer, nonNegativeInteger)
  }

  async handle({ user, repo }) {
    const stars = await this.fetch({ user, repo })
    return this.constructor.render({ stars })
  }
}
<commit_msg>fix [dockerstars] service (#8316)<commit_after>import Joi from 'joi'
import { metric } from '../text-formatters.js'
import { nonNegativeInteger } from '../validators.js'
import { BaseJsonService } from '../index.js'
import {
  dockerBlue,
  buildDockerUrl,
  getDockerHubUser,
} from './docker-helpers.js'

const schema = Joi.object({
  star_count: nonNegativeInteger.required(),
}).required()

export default class DockerStars extends BaseJsonService {
  static category = 'rating'
  static route = buildDockerUrl('stars')
  static examples = [
    {
      title: 'Docker Stars',
      namedParams: {
        user: '_',
        repo: 'ubuntu',
      },
      staticPreview: this.render({ stars: 9000 }),
    },
  ]

  static defaultBadgeData = { label: 'docker stars' }

  static render({ stars }) {
    return {
      message: metric(stars),
      color: dockerBlue,
    }
  }

  async fetch({ user, repo }) {
    return this._requestJson({
      schema,
      url: `https://hub.docker.com/v2/repositories/${getDockerHubUser(
        user
      )}/${repo}/`,
      errorMessages: { 404: 'repo not found' },
    })
  }

  async handle({ user, repo }) {
    const { star_count } = await this.fetch({ user, repo })
    return this.constructor.render({ stars: star_count })
  }
}
<|endoftext|>


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

	describe('vui-list', function() {

		beforeEach(function () {
			jasmine.addMatchers(vui.jasmine.dom.matchers);
		});

		describe('selectors', function() {

			it('defines a ".vui-list" selector', function() {
				expect(document).toHaveCssSelector('.vui-list');
			});

			it('defines a ".vui-list.vui-compact > li" selector', function() {
				expect(document).toHaveCssSelector('.vui-list.vui-compact > li');
			});

			it('defines a ".vui-list.vui-no-separator > li" selector', function() {
				expect(document).toHaveCssSelector('.vui-list.vui-no-separator > li');
			});

		});

	});

})();
<commit_msg>Adding more selector tests.<commit_after>(function() {
	'use strict';

	describe('vui-list', function() {

		beforeEach(function () {
			jasmine.addMatchers(vui.jasmine.dom.matchers);
		});

		describe('selectors', function() {

			it('defines a ".vui-list" selector', function() {
				expect(document).toHaveCssSelector('.vui-list');
			});

			it('defines a ".vui-list > li" selector', function() {
				expect(document).toHaveCssSelector('.vui-list > li');
			});

			it('defines a ".vui-list.vui-compact > li" selector', function() {
				expect(document).toHaveCssSelector('.vui-list.vui-compact > li');
			});

			it('defines a ".vui-list.vui-no-separator > li" selector', function() {
				expect(document).toHaveCssSelector('.vui-list.vui-no-separator > li');
			});

			it('defines a ".vui-list > .vui-selected" selector', function() {
				expect(document).toHaveCssSelector('.vui-list > .vui-selected');
			});

			it('defines a ".vui-list > .vui-active" selector', function() {
				expect(document).toHaveCssSelector('.vui-list > .vui-active');
			});

			it('defines a ".vui-list > .vui-active.vui-selected" selector', function() {
				expect(document).toHaveCssSelector('.vui-list > .vui-active.vui-selected');
			});

		});

	});

})();
<|endoftext|>


<commit_before>// Thanks to Brandon Keepers -
describe('JSHint', function () {
  var options = {curly: true, white: false, indent: 2},
      files = /^\/public\/javascripts\/(models|collections|views)|.*spec\.js$/;

  function get(path) {
    path = path + "?" + new Date().getTime();

    var xhr;
    try {
      xhr = new jasmine.XmlHttpRequest();
      xhr.open("GET", path, false);
      xhr.send(null);
    } catch (e) {
      throw new Error("couldn't fetch " + path + ": " + e);
    }
    if (xhr.status < 200 || xhr.status > 299) {
      throw new Error("Could not load '" + path + "'.");
    }

    return xhr.responseText;
  }

  _.each(document.getElementsByTagName('script'), function (element) {
    var script = element.getAttribute('src');
    if (!files.test(script)) {
      return;
    }
    console.debug(script);

    it(script, function () {
      var self = this;
      var source = get(script);
      var result = JSHINT(source, options);
      _.each(JSHINT.errors, function (error) {
        self.addMatcherResult(new jasmine.ExpectationResult({
          passed: false,
          message: "line " + error.line + ' - ' + error.reason + ' - ' + error.evidence
        }));
      });
      expect(true).toBe(true); // force spec to show up if there are no errors
    });

  });
});
<commit_msg>Remove console.debug from jshint spec<commit_after>// Thanks to Brandon Keepers -
describe('JSHint', function () {
  var options = {curly: true, white: false, indent: 2},
      files = /^\/public\/javascripts\/(models|collections|views)|.*spec\.js$/;

  function get(path) {
    path = path + "?" + new Date().getTime();

    var xhr;
    try {
      xhr = new jasmine.XmlHttpRequest();
      xhr.open("GET", path, false);
      xhr.send(null);
    } catch (e) {
      throw new Error("couldn't fetch " + path + ": " + e);
    }
    if (xhr.status < 200 || xhr.status > 299) {
      throw new Error("Could not load '" + path + "'.");
    }

    return xhr.responseText;
  }

  _.each(document.getElementsByTagName('script'), function (element) {
    var script = element.getAttribute('src');
    if (!files.test(script)) {
      return;
    }

    it(script, function () {
      var self = this;
      var source = get(script);
      var result = JSHINT(source, options);
      _.each(JSHINT.errors, function (error) {
        self.addMatcherResult(new jasmine.ExpectationResult({
          passed: false,
          message: "line " + error.line + ' - ' + error.reason + ' - ' + error.evidence
        }));
      });
      expect(true).toBe(true); // force spec to show up if there are no errors
    });

  });
});
<|endoftext|>