<commit_before>(function() {
    //
    // Connector definition
    //
    var myConnector = tableau.makeConnector();

    myConnector.init = function(initCallback) {
        // STEP 1: Require login - set username to organization id, and password
        // to the token.
        tableau.authType = tableau.authTypeEnum.basic;
        if (tableau.password){
            initCallback();
        }
        else {
            tableau.abortForAuth("Put in your organization id as username and token as a password");
        }
    };

    // NOTES: The getSchema function defines the columns you want to show up in
    // tableau and what type of data they are add more columns here, order will matter.
    myConnector.getSchema = function(schemaCallback) {
        // NOTES: If you needed to pull data from the form where they click the button
        // you could fetch it here
        var data = tableau.connectionData;

        var cols = [
            { id: "entity_id", alias: "Entity ID", dataType: tableau.dataTypeEnum.string },
            { id: "campaign_name", alias: "Campaign Name", dataType: tableau.dataTypeEnum.string },
            { id: "date", alias: "Date", dataType: tableau.dataTypeEnum.date },
            { id: "spend", alias: "Spend", dataType: tableau.dataTypeEnum.float },
            { id: "clicks", alias: "Clicks", dataType: tableau.dataTypeEnum.int },
            { id: "impressions", alias: "Impressions", dataType: tableau.dataTypeEnum.int },
            { id: "conversions", alias: "Conversions", dataType: tableau.dataTypeEnum.int },
            // STEP 3: add columns as needed
        ];

        var tableInfo = {
            id: "adstage_campaigns",
            columns: cols
        };
        schemaCallback([tableInfo]); // tell tableau about the fields and their types (can have multiple tables)
    };

    myConnector.getData = function(table, doneCallback) {
        // This makes it so AJAX calls are authenticated:
        $.ajaxSetup({
            beforeSend: function(xhr) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + tableau.password);
                xhr.setRequestHeader('Accept', 'application/json');
            }
        });
        var connectionUrl = "https://platform.adstage.io/api/organizations/" + tableau.username + "/build_report";

        var fields_list = table.tableInfo.columns.map(function(i){
            return i.id;
        });

        // STEP 2: Configure to fit needs
        var report = {
            date_range: "last_month",
            entity_level: "campaigns",
            fields: fields_list,
            filters: [{op: "gt", path: "impressions", value: 0}],
            limit: 50,
            aggregate_by: "day"
        };

        var APIPromise = makeAPIRequest(table, report, connectionUrl);

        APIPromise.then(function(response) {
            console.log("Success");
            doneCallback();
        }, function(error) {
            console.error(error);
        });
    };

    function processRows(table, data){
        if (data._embedded["adstage:time_series"]) {
            var series = data._embedded["adstage:time_series"];
            var ii, jj;
            var toRet = [];

            // mash the data into an array of objects
            for (ii = 0; ii < series.length; ++ii) {
                var meta = series[ii].meta;
                var list = series[ii].series;
                for (jj = 0; jj < list.length; ++jj) {
                    // STEP 3: add columns as needed
                    var entry = [meta.entity_id,
                                 meta.campaign_name,
                                 Date.parse(list[jj].timeframe.start),
                                 list[jj].data.spend,
                                 list[jj].data.clicks,
                                 list[jj].data.impressions,
                                 list[jj].data.conversions];
                    toRet.push(entry);
                }
            }

            table.appendRows(toRet);
        }
    }

    function handleResponse(counter, table, response, resolve, reject){
        processRows(table, response);
        if (response._links.next && counter < 100){
            $.ajax({
                url: response._links.next.href,
                type: "GET",
                contentType: 'application/json',
                dataType: 'json',
                success: function(data){
                    return handleResponse((counter + 1), table, data, resolve, reject);
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    reject("Problem fetching from AdStage data source: " + thrownError);
                }
            });
        } else {
            resolve();
        }
    }

    function makeAPIRequest(table, report, connectionUrl) {
        return new Promise(function(resolve, reject) {
            var xhr = $.ajax({
                url: connectionUrl,
                type: "POST",
                data: JSON.stringify(report),
                contentType: 'application/json',
                dataType: 'json',
                success: function(data){
                    return handleResponse(0, table, data, resolve, reject);
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    reject("Problem fetching from AdStage data source: " + thrownError);
                }
            });
        });
    }

    setupConnector = function() {
        // NOTES: If you needed to set up data to pass from the main page to the connector, set it on connectionData
        tableau.connectionData = null;
        tableau.connectionName = 'AdStage Data - Campaigns This Month'; // name the data source. This will be the data source name in Tableau
        tableau.submit();
    };

    tableau.registerConnector(myConnector);

    //
    // Setup connector UI
    //
    $(document).ready(function() {
        $("#submitButton").click(function() { // This event fires when a button is clicked
            setupConnector();
        });
        $('#tickerForm').submit(function(event) {
            event.preventDefault();
            setupConnector();
        });
    });
})();
<commit_msg>Make sure we abort<commit_after>(function() {
    //
    // Connector definition
    //
    var myConnector = tableau.makeConnector();

    myConnector.init = function(initCallback) {
        // STEP 1: Require login - set username to organization id, and password
        // to the token.
        tableau.authType = tableau.authTypeEnum.basic;
        if (tableau.password){
            initCallback();
        }
        else {
            tableau.abortForAuth("Put in your organization id as username and token as a password");
        }
    };

    // NOTES: The getSchema function defines the columns you want to show up in
    // tableau and what type of data they are add more columns here, order will matter.
    myConnector.getSchema = function(schemaCallback) {
        // NOTES: If you needed to pull data from the form where they click the button
        // you could fetch it here
        var data = tableau.connectionData;

        var cols = [
            { id: "entity_id", alias: "Entity ID", dataType: tableau.dataTypeEnum.string },
            { id: "campaign_name", alias: "Campaign Name", dataType: tableau.dataTypeEnum.string },
            { id: "date", alias: "Date", dataType: tableau.dataTypeEnum.date },
            { id: "spend", alias: "Spend", dataType: tableau.dataTypeEnum.float },
            { id: "clicks", alias: "Clicks", dataType: tableau.dataTypeEnum.int },
            { id: "impressions", alias: "Impressions", dataType: tableau.dataTypeEnum.int },
            { id: "conversions", alias: "Conversions", dataType: tableau.dataTypeEnum.int },
            // STEP 3: add columns as needed
        ];

        var tableInfo = {
            id: "adstage_campaigns",
            columns: cols
        };
        schemaCallback([tableInfo]); // tell tableau about the fields and their types (can have multiple tables)
    };

    myConnector.getData = function(table, doneCallback) {
        if (tableau.password.length == 0) {
            tableau.abortForAuth();
        }

        // This makes it so AJAX calls are authenticated:
        $.ajaxSetup({
            beforeSend: function(xhr) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + tableau.password);
                xhr.setRequestHeader('Accept', 'application/json');
            }
        });
        var connectionUrl = "https://platform.adstage.io/api/organizations/" + tableau.username + "/build_report";

        var fields_list = table.tableInfo.columns.map(function(i){
            return i.id;
        });

        // STEP 2: Configure to fit needs
        var report = {
            date_range: "last_month",
            entity_level: "campaigns",
            fields: fields_list,
            filters: [{op: "gt", path: "impressions", value: 0}],
            limit: 50,
            aggregate_by: "day"
        };

        var APIPromise = makeAPIRequest(table, report, connectionUrl);

        APIPromise.then(function(response) {
            console.log("Success");
            doneCallback();
        }, function(error) {
            console.error(error);
        });
    };

    function processRows(table, data){
        if (data._embedded["adstage:time_series"]) {
            var series = data._embedded["adstage:time_series"];
            var ii, jj;
            var toRet = [];

            // mash the data into an array of objects
            for (ii = 0; ii < series.length; ++ii) {
                var meta = series[ii].meta;
                var list = series[ii].series;
                for (jj = 0; jj < list.length; ++jj) {
                    // STEP 3: add columns as needed
                    var entry = [meta.entity_id,
                                 meta.campaign_name,
                                 Date.parse(list[jj].timeframe.start),
                                 list[jj].data.spend,
                                 list[jj].data.clicks,
                                 list[jj].data.impressions,
                                 list[jj].data.conversions];
                    toRet.push(entry);
                }
            }

            table.appendRows(toRet);
        }
    }

    function handleResponse(counter, table, response, resolve, reject){
        processRows(table, response);
        if (response._links.next && counter < 100){
            $.ajax({
                url: response._links.next.href,
                type: "GET",
                contentType: 'application/json',
                dataType: 'json',
                success: function(data){
                    return handleResponse((counter + 1), table, data, resolve, reject);
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    reject("Problem fetching from AdStage data source: " + thrownError);
                }
            });
        } else {
            resolve();
        }
    }

    function makeAPIRequest(table, report, connectionUrl) {
        return new Promise(function(resolve, reject) {
            var xhr = $.ajax({
                url: connectionUrl,
                type: "POST",
                data: JSON.stringify(report),
                contentType: 'application/json',
                dataType: 'json',
                success: function(data){
                    return handleResponse(0, table, data, resolve, reject);
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    reject("Problem fetching from AdStage data source: " + thrownError);
                }
            });
        });
    }

    setupConnector = function() {
        // NOTES: If you needed to set up data to pass from the main page to the connector, set it on connectionData
        tableau.connectionData = null;
        tableau.connectionName = 'AdStage Data - Campaigns This Month'; // name the data source. This will be the data source name in Tableau
        tableau.submit();
    };

    tableau.registerConnector(myConnector);

    //
    // Setup connector UI
    //
    $(document).ready(function() {
        $("#submitButton").click(function() { // This event fires when a button is clicked
            setupConnector();
        });
        $('#tickerForm').submit(function(event) {
            event.preventDefault();
            setupConnector();
        });
    });
})();
<|endoftext|>


<commit_before>/******************************************************************************\

The MIT License (MIT)

Copyright (c) 2013   ʞɐǝɹɟʞǝǝƃ

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

\******************************************************************************/
// CONSTANTS
const LOG_VERBOSE       = true ;
const SERVE_STATIC      = true ;
const HTTP_PORT         = 8080 ;
// koa app server
var koa                 = require("koa") ;                 // https://github.com/koajs/koa
// koa modules
var staticServer        = require("koa-static") ;          // https://github.com/koajs/static
var httpLogger          = require("koa-http-logger") ;     // https://github.com/vesln/koa-http-logger
var router              = require("koa-route") ;           // https://github.com/koajs/route
var gzip                = require("koa-gzip") ;            // https://github.com/node-modules/koa-gzip
// node utils
var _                   = require('underscore') ;          // http://underscorejs.org/
var parse               = require('co-body') ;             // https://github.com/visionmedia/co-body
var Promise             = require("bluebird") ;            // https://github.com/petkaantonov/bluebird
var colors              = require("ccolors") ;             // https://github.com/kolodny/ccolors
var path                = require("path") ;                // http://nodejs.org/docs/v0.4.9/api/path.html
var exec                = require("child_process").exec ;  // http://nodejs.org/api/child_process.html
// debug wrappers
var debug               = require('debug')('koa-static') ; // https://github.com/visionmedia/debug
var _log                = require('debug')('gwhh') ;
var _verbose            = require('debug')('verbose') ;
// wrap fs in Promise/A api

var fs                  = Promise.promisifyAll(require("fs") ) ;
var project             = process.argv[2] || process.exit(1) ;  // commandline must contain a project name
var gitHookPort         = process.argv[3] || -1 ;               // set the port to listen for github hooks on
var workspace           = path.resolve(__dirname, '..') ;       // ??bit wonky??
var repositoryContainer = path.join(workspace, project) ;       // repositoryContainer is the folder http content is served from.

// log helper - !!TODO!! should be a factory
var log = function() {
  var message = Array.prototype.slice.call(arguments).join(" , ") ;
  _log([new Date().toString().split(" ")[4].blue , process.pid.toString().magenta , message.bold.white].join(" ") ,"".white) ;
} ;

var log_verbose = function() {
  var message = Array.prototype.slice.call(arguments).join(" , ") ;
  _verbose([new Date().toString().split(" ")[4].blue , process.pid.toString().magenta , message.bold.white].join(" ") ,"".white) ;
} ;

// verify repositoryContainer exists
fs.stat(repositoryContainer, function(err, repoStats) { // ? Promise style ??

  if (repoStats && repoStats.isDirectory()) {

    if (SERVE_STATIC) {

      var app = koa() ;

      app.use(httpLogger(debug)) ;
      app.use(gzip()) ;
      app.use(staticServer(repositoryContainer)) ;

      log("static content serving from " + repositoryContainer.bold.green ) ;
      log("http on " + HTTP_PORT.toString().bold.green ) ;

      app.listen(HTTP_PORT) ;

    }

    if (!~gitHookPort) {  // Sentinel Detected

      log("githook listener disabled ".blackHi ) ;

    } else {

      var gitHookApp = koa() ;

      gitHookApp.use(httpLogger(debug)) ;
      gitHookApp.use(gzip()) ;
      gitHookApp.use(function *(){

        var body = yield parse(this);
        var repo = body.payload.repository || {} ;

        log("githook trigger for " + repo.name, body) ;

        if (repo.name === project) {

          process.chdir(repositoryContainer) ;

          // !!TODO!! conver to promise style/generator
          child = exec("git pull", function (error, stdout, stderr) {
            log_verbose("stdout: " + stdout) ;
            log_verbose("stderr: " + stderr) ;
            log((error !== null) ? "exec error: " + error : repo.name + " updated") ;
          }) ;

          process.chdir(__dirname) ;

        } else {
           this.throw(404, project +" Not Found");
        }

      });

      gitHookApp.listen(gitHookPort);
      log("githook listener on ".green + gitHookPort ) ;

    }

  } else {

    log("Invalid project: ".red + project.yellowHi + " : " + repositoryContainer.green) ;

  }

}) ;
<commit_msg>test webhook<commit_after>/******************************************************************************\

The MIT License (MIT)

Copyright (c) 2013   ʞɐǝɹɟʞǝǝƃ

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

\******************************************************************************/
// CONSTANTS
const LOG_VERBOSE       = true ;
const SERVE_STATIC      = true ;
const HTTP_PORT         = 8080 ;
// koa app server
var koa                 = require("koa") ;                 // https://github.com/koajs/koa
// koa modules
var staticServer        = require("koa-static") ;          // https://github.com/koajs/static
var httpLogger          = require("koa-http-logger") ;     // https://github.com/vesln/koa-http-logger
var router              = require("koa-route") ;           // https://github.com/koajs/route
var gzip                = require("koa-gzip") ;            // https://github.com/node-modules/koa-gzip
// node utils
var _                   = require('underscore') ;          // http://underscorejs.org/
var parse               = require('co-body') ;             // https://github.com/visionmedia/co-body
var Promise             = require("bluebird") ;            // https://github.com/petkaantonov/bluebird
var colors              = require("ccolors") ;             // https://github.com/kolodny/ccolors
var path                = require("path") ;                // http://nodejs.org/docs/v0.4.9/api/path.html
var exec                = require("child_process").exec ;  // http://nodejs.org/api/child_process.html
// debug wrappers
var debug               = require('debug')('koa-static') ; // https://github.com/visionmedia/debug
var _log                = require('debug')('gwhh') ;
var _verbose            = require('debug')('verbose') ;
// wrap fs in Promise/A api

var fs                  = Promise.promisifyAll(require("fs") ) ;
var project             = process.argv[2] || process.exit(1) ;  // commandline must contain a project name
var gitHookPort         = process.argv[3] || -1 ;               // set the port to listen for github hooks on
var workspace           = path.resolve(__dirname, '..') ;       // ??bit wonky??
var repositoryContainer = path.join(workspace, project) ;       // repositoryContainer is the folder http content is served from.

// log helper - !!TODO!! should be a factory
var log = function() {
  var message = Array.prototype.slice.call(arguments).join(" , ") ;
  _log([new Date().toString().split(" ")[4].blue , process.pid.toString().magenta , message.bold.white].join(" ") ,"".white) ;
} ;

var log_verbose = function() {
  var message = Array.prototype.slice.call(arguments).join(" , ") ;
  _verbose([new Date().toString().split(" ")[4].blue , process.pid.toString().magenta , message.bold.white].join(" ") ,"".white) ;
} ;

// verify repositoryContainer exists
fs.stat(repositoryContainer, function(err, repoStats) { // ? Promise style ??

  if (repoStats && repoStats.isDirectory()) {

    if (SERVE_STATIC) {

      var app = koa() ;

      app.use(httpLogger(debug)) ;
      app.use(gzip()) ;
      app.use(staticServer(repositoryContainer)) ;

      log("static content serving from " + repositoryContainer.bold.green ) ;
      log("http on " + HTTP_PORT.toString().bold.green ) ;

      app.listen(HTTP_PORT) ;

    }

    if (!~gitHookPort) {  // Sentinel Detected

      log("githook listener disabled ".blackHi ) ;

    } else {

      var gitHookApp = koa() ;

      gitHookApp.use(httpLogger(debug)) ;
      gitHookApp.use(gzip()) ;
      gitHookApp.use(function *(){

        var body = yield parse(this);
        var repo = body.payload.repository || {} ;

        log("githook trigger for " + repo.name, body) ;

        if (repo.name === project) {

          process.chdir(repositoryContainer) ;

          // !!TODO!! conver to promise style/generator
          child = exec("git pull", function (error, stdout, stderr) {
            log_verbose("stdout: " + stdout) ;
            log_verbose("stderr: " + stderr) ;
            log((error !== null) ? "exec error: " + error : repo.name + " updated") ;
          }) ;

          process.chdir(__dirname) ;

        } else {
           this.throw(404, project +" Not Found");
        }

      });

      gitHookApp.listen(gitHookPort);
      log("githook listener on ".green + gitHookPort ) ;

    }

  } else {

    log("Invalid project: ".red + project.yellowHi + " : " + repositoryContainer.green) ;

  }

}) ;

// test webhook on commit.
<|endoftext|>


<commit_before>/*global describe, it, before, after, beforeEach, afterEach*/

'use strict';

// stdlib
var path    = require('path');
var format  = require('util').format;
var assert  = require('assert');

// internal
var Puncher = require('..');

////////////////////////////////////////////////////////////////////////////////

describe('Puncher', function () {
  var puncher;

  beforeEach(function () {
    puncher = new Puncher();
  });

  it("should correctly calculate start/stops", function (done) {
    var result;

    puncher.start('Foo');
    setTimeout(function () {
      result = puncher.stop().result;

      var foo = result[0];

      assert.ok(105 > foo.elapsed.total && foo.elapsed.total >= 100,
        format('Expect total elapsed time %d to be about 100ms',
          foo.elapsed.total));

      assert.ok(Math.abs(foo.elapsed.total - (foo.stop - foo.start)) < 1,
        format('Expect start/stop difference %d to be about total elapsed time %d',
          foo.stop - foo.start, foo.elapsed.total));

      done();
    }, 100);
  });

  it("should properly calculate start/stops of nested scopes", function (done) {
    var result;

    puncher.start('Foo');
    setTimeout(function () {
      puncher.start('Bar');
      setTimeout(function () {
        result = puncher.stop(true).result;

        var foo = result[0], bar = foo.childs[0];

        assert.ok(205 > foo.elapsed.total && foo.elapsed.total >= 200,
          format('Expect overall time %d to be about 100ms',
            foo.elapsed.total));

        assert.ok(105 > bar.elapsed.total && bar.elapsed.total >= 100,
          format('Expect overall time of nested scope %d to be about 100ms',
            foo.elapsed.total));

        done();
      }, 100);
    }, 100);
  });

  it("should calculate missed coverage", function (done) {
    var result;

    puncher.start('Foo');
    setTimeout(function () {
      puncher.start('Bar');
      setTimeout(function () {
        result = puncher.stop(true).result;

        var foo = result[0], bar = foo.childs[0];

        assert.ok(105 > foo.elapsed.missed && foo.elapsed.missed >= 100,
          format('Expect missed coverage %d to be about 100ms',
            foo.elapsed.missed));

        assert.equal(0, bar.elapsed.missed,
          format('Expect missed coverage %d of scope without childs to be 0ms',
            bar.elapsed.missed));

        done();
      }, 100);
    }, 100);
  });

  it("should tell if there are non-closed scopes", function () {
    puncher.start('Foo').start('Bar').stop();

    assert.ok(!puncher.stopped, 'Should be non-stopped');

    puncher.stop();

    assert.ok(puncher.stopped, 'Should be stopped');
  });

  it("should allow stop all non-closed scopes", function () {
    puncher.start('Foo').start('Bar').stop(true);
    assert.ok(puncher.stopped, 'Should be stopped');
  });

  it("should support set metadata on start", function () {
    puncher.start('Foo', {bar: 'baz'}).stop();
    assert.equal(puncher.result.shift().meta.bar, 'baz');
  });

  it("should support set metadata on stop", function () {
    puncher.start('Foo', {bar: 'baz'}).stop({moo: 'moo'});
    assert.equal(puncher.result.shift().meta.bar, 'baz');
    assert.equal(puncher.result.shift().meta.moo, 'moo');
  });

  it("should use process.hrtime() if available", function (done) {
    var result, _process = true, _hrtime = null, hrtime_calls = 0;

    // Setup process.hrtime() mock
    if (process && process.hrtime) {
      _hrtime = process.hrtime;

      process.hrtime = function () {
        hrtime_calls++;
        return _hrtime.apply(null, arguments);
      };
    } else {
      if (!process) {
        _process = false;
        global.process = {};
      }
      process.hrtime = function () {
        hrtime_calls++;
        return 0; // we do not check result in this test
      };
    }

    puncher.start('Foo');
    setTimeout(function () {
      result = puncher.stop().result;

      var foo = result[0];

      assert.equal(hrtime_calls, 2);

      // Cleanup process.hrtime() mock
      if (_hrtime) {
        process.hrtime = _hrtime;
      } else {
        process.hrtime = null;
        if (_process === false) {
          global.process = null;
        }
      }

      done();
    }, 100);
  });

  it("should use Date.now() if process.hrtime() is not available", function (done) {
    var result, _process = true, _hrtime = null;

    // Delete process.hrtime()
    if (process && process.hrtime) {
      _hrtime = process.hrtime;

      process.hrtime = null;
    } else if (!process) {
      _process = false;
    }

    puncher.start('Foo');
    setTimeout(function () {
      result = puncher.stop().result;

      var foo = result[0];

      assert.ok(105 > foo.elapsed.total && foo.elapsed.total >= 100,
        format('Expect total elapsed time %d to be about 100ms',
          foo.elapsed.total));

      assert.ok(Math.abs(foo.elapsed.total - (foo.stop - foo.start)) < 1,
        format('Expect start/stop difference %d to be about total elapsed time %d',
          foo.stop - foo.start, foo.elapsed.total));

      // Restore process.hrtime()
      if (_hrtime) {
        if (_process) {
          process.hrtime = _hrtime;
        }
      }

      done();
    }, 100);
  });

  // This test is not available, because we can't delete process without breaking test.
  //it("should use Date.now() if process is not available", function () {});

});
<commit_msg>Care abour global/window<commit_after>/*global describe, it, before, after, beforeEach, afterEach, window*/

'use strict';

// stdlib
var path    = require('path');
var format  = require('util').format;
var assert  = require('assert');

// internal
var Puncher = require('..');

// for browsers compatibility
var gl = (typeof global === 'object') ? global : window;

////////////////////////////////////////////////////////////////////////////////

describe('Puncher', function () {
  var puncher;

  beforeEach(function () {
    puncher = new Puncher();
  });

  it("should correctly calculate start/stops", function (done) {
    var result;

    puncher.start('Foo');
    setTimeout(function () {
      result = puncher.stop().result;

      var foo = result[0];

      assert.ok(105 > foo.elapsed.total && foo.elapsed.total >= 100,
        format('Expect total elapsed time %d to be about 100ms',
          foo.elapsed.total));

      assert.ok(Math.abs(foo.elapsed.total - (foo.stop - foo.start)) < 1,
        format('Expect start/stop difference %d to be about total elapsed time %d',
          foo.stop - foo.start, foo.elapsed.total));

      done();
    }, 100);
  });

  it("should properly calculate start/stops of nested scopes", function (done) {
    var result;

    puncher.start('Foo');
    setTimeout(function () {
      puncher.start('Bar');
      setTimeout(function () {
        result = puncher.stop(true).result;

        var foo = result[0], bar = foo.childs[0];

        assert.ok(205 > foo.elapsed.total && foo.elapsed.total >= 200,
          format('Expect overall time %d to be about 100ms',
            foo.elapsed.total));

        assert.ok(105 > bar.elapsed.total && bar.elapsed.total >= 100,
          format('Expect overall time of nested scope %d to be about 100ms',
            foo.elapsed.total));

        done();
      }, 100);
    }, 100);
  });

  it("should calculate missed coverage", function (done) {
    var result;

    puncher.start('Foo');
    setTimeout(function () {
      puncher.start('Bar');
      setTimeout(function () {
        result = puncher.stop(true).result;

        var foo = result[0], bar = foo.childs[0];

        assert.ok(105 > foo.elapsed.missed && foo.elapsed.missed >= 100,
          format('Expect missed coverage %d to be about 100ms',
            foo.elapsed.missed));

        assert.equal(0, bar.elapsed.missed,
          format('Expect missed coverage %d of scope without childs to be 0ms',
            bar.elapsed.missed));

        done();
      }, 100);
    }, 100);
  });

  it("should tell if there are non-closed scopes", function () {
    puncher.start('Foo').start('Bar').stop();

    assert.ok(!puncher.stopped, 'Should be non-stopped');

    puncher.stop();

    assert.ok(puncher.stopped, 'Should be stopped');
  });

  it("should allow stop all non-closed scopes", function () {
    puncher.start('Foo').start('Bar').stop(true);
    assert.ok(puncher.stopped, 'Should be stopped');
  });

  it("should support set metadata on start", function () {
    puncher.start('Foo', {bar: 'baz'}).stop();
    assert.equal(puncher.result.shift().meta.bar, 'baz');
  });

  it("should support set metadata on stop", function () {
    puncher.start('Foo', {bar: 'baz'}).stop({moo: 'moo'});
    assert.equal(puncher.result.shift().meta.bar, 'baz');
    assert.equal(puncher.result.shift().meta.moo, 'moo');
  });

  it("should use process.hrtime() if available", function (done) {
    var result, _process = true, _hrtime = null, hrtime_calls = 0;

    // Setup process.hrtime() mock
    if (process && process.hrtime) {
      _hrtime = process.hrtime;

      process.hrtime = function () {
        hrtime_calls++;
        return _hrtime.apply(null, arguments);
      };
    } else {
      if (!process) {
        _process = false;
        gl.process = {};
      }
      process.hrtime = function () {
        hrtime_calls++;
        return 0; // we do not check result in this test
      };
    }

    puncher.start('Foo');
    setTimeout(function () {
      result = puncher.stop().result;

      assert.equal(hrtime_calls, 2);

      // Cleanup process.hrtime() mock
      if (_hrtime) {
        process.hrtime = _hrtime;
      } else {
        process.hrtime = null;
        if (_process === false) {
          gl.process = null;
        }
      }

      done();
    }, 100);
  });

  it("should use Date.now() if process.hrtime() is not available", function (done) {
    var result, _process = true, _hrtime = null;

    // Delete process.hrtime()
    if (process && process.hrtime) {
      _hrtime = process.hrtime;

      process.hrtime = null;
    } else if (!process) {
      _process = false;
    }

    puncher.start('Foo');
    setTimeout(function () {
      result = puncher.stop().result;

      var foo = result[0];

      assert.ok(105 > foo.elapsed.total && foo.elapsed.total >= 100,
        format('Expect total elapsed time %d to be about 100ms',
          foo.elapsed.total));

      assert.ok(Math.abs(foo.elapsed.total - (foo.stop - foo.start)) < 1,
        format('Expect start/stop difference %d to be about total elapsed time %d',
          foo.stop - foo.start, foo.elapsed.total));

      // Restore process.hrtime()
      if (_hrtime) {
        if (_process) {
          process.hrtime = _hrtime;
        }
      }

      done();
    }, 100);
  });

  // This test is not available, because we can't delete process without breaking test.
  //it("should use Date.now() if process is not available", function () {});

});
<|endoftext|>


<commit_before>define(["tests/Core", "chai", "Tone/component/Recorder", "Tone/signal/Signal", "Tone/signal/Add", "Tone/signal/Multiply",
	"Tone/signal/Scale", "Tone/source/Oscillator", "Tone/signal/Merge", "Tone/signal/Split","Tone/core/Master", "Tone/signal/EqualsZero"],
function(core, chai, Recorder, Signal, Add, Multiply, Scale, Oscillator, Merge, Split, Master, EqualsZero){

	var expect = chai.expect;

	Master.mute();

	//SIGNAL
	describe("Tone.Signal", function(){
		this.timeout(1000);

		var signal = new Signal(0);
		signal.toMaster();

		after(function(){
			signal.dispose();
		});

		it("can be created and disposed", function(){
			var s = new Signal();
			s.dispose();
		});

		it("can start with a value initially", function(){
			expect(signal.getValue()).to.equal(0);
		});

		it("can set a value", function(){
			signal.setValue(10);
			expect(signal.getValue()).to.equal(10);
		});

		it("can set a value in the future", function(done){
			signal.setValueAtTime(100, "+0.1");
			expect(signal.getValue()).to.equal(10);
			var interval = setInterval(function(){
				if (signal.getValue() === 100){
					clearInterval(interval);
					done();
				}
			}, 10);
		});

		it("can change value with sample accurate timing", function(done){
			var changeSignal = new Signal(0);
			var waitTime = 0.03;
			changeSignal.setValueAtTime(1, "+"+waitTime);//ramp after 50ms
			var recorder = new Recorder();
			changeSignal.connect(recorder);
			var delayTime = 0.05;
			recorder.record(0.1, delayTime, function(buffers){
				buffer = buffers[0];
				for (var i = 0; i < buffer.length; i++){
					if (buffer[i] === 1){
						expect(changeSignal.samplesToSeconds(i)).is.closeTo(delayTime - waitTime, 0.01);
						changeSignal.dispose();
						recorder.dispose();
						done();
						break;
					}
				}
			});
		});

		it("can sync to another signal", function(done){
			var syncTo = new Signal(1);
			var signalSync = new Signal(2);
			signalSync.sync(syncTo);
			syncTo.setValue(2);
			syncTo.noGC();
			signalSync.noGC();
			var recorder = new Recorder();
			signalSync.connect(recorder);
			recorder.record(0.1, 0.05, function(buffers){
				var buffer = buffers[0];
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(4);
				}
				signalSync.dispose();
				recorder.dispose();
				done();
			});
		});

		it("can ramp from the current value", function(done){
			signal.setValue(-10);
			signal.noGC();
			var recorder = new Recorder(1);
			signal.connect(recorder);
			var waitTime = 0.03;
			expect(signal.getValue()).to.equal(-10);
			signal.linearRampToValueNow(1, waitTime);
			recorder.record(0.1, 0.05, function(buffers){
				var buffer = buffers[0];
				for (var i = 0; i < buffer.length; i++){
					if (buffer[i] === 1){
						expect(signal.samplesToSeconds(i)).is.closeTo(waitTime, 0.01);
						done();
						break;
					}
				}
			});
		});
	});

	//ADD
	describe("Tone.Add", function(){
		this.timeout(500);

		var recorder = new Recorder();

		after(function(){
			recorder.dispose();
		});

		it("can be created and disposed", function(){
			var a = new Add(1);
			a.dispose();
		});

		it("correctly sums a signal and a number", function(done){
			var signal = new Signal(0);
			var adder = new Add(3);
			signal.connect(adder);
			adder.connect(recorder);
			recorder.record(0.1, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(3);
				}
				done();
			});
		});

		it("can handle negative values", function(done){
			var signal = new Signal(10);
			var adder = new Add(-1);
			signal.connect(adder);
			var recorder = new Recorder();
			adder.connect(recorder);
			recorder.record(0.1, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(9);
				}
				done();
			});
		});
	});

	//MULTIPLY
	describe("Tone.Multiply", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var m = new Multiply(1);
			m.dispose();
		});

		it("correctly multiplys a signal and a scalar", function(done){
			var signal = new Signal(2);
			var mult = new Multiply(10);
			signal.connect(mult);
			var recorder = new Recorder();
			mult.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(20);
				}
				signal.dispose();
				mult.dispose();
				done();
			}, 100);
		});
	});

	//SCALE
	describe("Tone.Scale", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var s = new Scale(0, 10);
			s.dispose();
		});

		it("scales an input range to an output range", function(done){
			//make an oscillator to drive the signal
			var osc = new Oscillator(1000);
			osc.start();
			var scale = new Scale(-1, 1, 10, 20);
			osc.connect(scale);
			var recorder = new Recorder();
			scale.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.be.within(10, 20);
				}
				done();
			});
		});
	});

	//MERGE
	describe("Tone.Merge", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var mer = new Merge();
			mer.dispose();
		});

		it("merge two signal into one stereo signal", function(done){
			//make an oscillator to drive the signal
			var sigL = new Signal(1);
			var sigR = new Signal(2);
			var merger = new Merge();
			sigL.connect(merger.left);
			sigR.connect(merger.right);
			var recorder = new Recorder(2);
			merger.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var lBuffer = buffers[0];
				var rBuffer = buffers[1];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < lBuffer.length; i++){
					expect(lBuffer[i]).to.equal(1);
					expect(rBuffer[i]).to.equal(2);
				}
				done();
			});
		});
	});

	//SCALE
	describe("Tone.Split", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var split = new Split();
			split.dispose();
		});

		it("merges two signal into one stereo signal and then split them back into two signals", function(done){
			//make an oscillator to drive the signal
			var sigL = new Signal(1);
			var sigR = new Signal(2);
			var merger = new Merge();
			var split = new Split();
			sigL.connect(merger.left);
			sigR.connect(merger.right);
			merger.connect(split);
			var recorderL = new Recorder();
			var recorderR = new Recorder();
			split.left.connect(recorderL);
			split.right.connect(recorderR);
			recorderL.record(0.05, 0.1, function(buffers){
				var lBuffer = buffers[0];
				for (var i = 0; i < lBuffer.length; i++){
					expect(lBuffer[i]).to.equal(1);
				}
			});
			recorderR.record(0.05, 0.1, function(buffers){
				var rBuffer = recorderR.getFloat32Array()[0];
				for (var j = 0; j < rBuffer.length; j++){
					expect(rBuffer[j]).to.equal(2);
				}
				done();
			});
		});
	});

	//EQUALS 0
	describe("Tone.EqualsZero", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var ez = new EqualsZero();
			ez.dispose();
		});

		it("outputs 1 when the incoming signal is 0", function(done){
			var signal = new Signal(0);
			var ez = new EqualsZero();
			signal.connect(ez);
			var recorder = new Recorder();
			ez.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(1);
				}
				signal.dispose();
				ez.dispose();
				done();
			}, 100);
		});

		it("outputs 0 when the incoming signal is not 0", function(done){
			var signal = new Signal(100);
			var ez = new EqualsZero();
			signal.connect(ez);
			var recorder = new Recorder();
			ez.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(0);
				}
				signal.dispose();
				ez.dispose();
				done();
			}, 100);
		});

		it("is not fooled by values very close to 0", function(done){
			var signal = new Signal(0.00001);
			var ez = new EqualsZero();
			signal.connect(ez);
			var recorder = new Recorder();
			ez.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(0);
				}
				signal.dispose();
				ez.dispose();
				done();
			}, 100);
		});

	});

});<commit_msg>threshold and switch tests<commit_after>define(["tests/Core", "chai", "Tone/component/Recorder", "Tone/signal/Signal", "Tone/signal/Add", "Tone/signal/Multiply",
	"Tone/signal/Scale", "Tone/source/Oscillator", "Tone/signal/Merge", "Tone/signal/Split","Tone/core/Master", "Tone/signal/EqualsZero",
	"Tone/signal/Threshold", "Tone/signal/Switch"],
function(core, chai, Recorder, Signal, Add, Multiply, Scale, Oscillator, Merge, Split, Master, EqualsZero, Threshold, Switch){

	var expect = chai.expect;

	Master.mute();

	//SIGNAL
	describe("Tone.Signal", function(){
		this.timeout(1000);

		var signal = new Signal(0);
		signal.toMaster();

		after(function(){
			signal.dispose();
		});

		it("can be created and disposed", function(){
			var s = new Signal();
			s.dispose();
		});

		it("can start with a value initially", function(){
			expect(signal.getValue()).to.equal(0);
		});

		it("can set a value", function(){
			signal.setValue(10);
			expect(signal.getValue()).to.equal(10);
		});

		it("can set a value in the future", function(done){
			signal.setValueAtTime(100, "+0.1");
			expect(signal.getValue()).to.equal(10);
			var interval = setInterval(function(){
				if (signal.getValue() === 100){
					clearInterval(interval);
					done();
				}
			}, 10);
		});

		it("can change value with sample accurate timing", function(done){
			var changeSignal = new Signal(0);
			var waitTime = 0.03;
			changeSignal.setValueAtTime(1, "+"+waitTime);//ramp after 50ms
			var recorder = new Recorder();
			changeSignal.connect(recorder);
			var delayTime = 0.05;
			recorder.record(0.1, delayTime, function(buffers){
				buffer = buffers[0];
				for (var i = 0; i < buffer.length; i++){
					if (buffer[i] === 1){
						expect(changeSignal.samplesToSeconds(i)).is.closeTo(delayTime - waitTime, 0.01);
						changeSignal.dispose();
						recorder.dispose();
						done();
						break;
					}
				}
			});
		});

		it("can sync to another signal", function(done){
			var syncTo = new Signal(1);
			var signalSync = new Signal(2);
			signalSync.sync(syncTo);
			syncTo.setValue(2);
			syncTo.noGC();
			signalSync.noGC();
			var recorder = new Recorder();
			signalSync.connect(recorder);
			recorder.record(0.1, 0.05, function(buffers){
				var buffer = buffers[0];
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(4);
				}
				signalSync.dispose();
				recorder.dispose();
				done();
			});
		});

		it("can ramp from the current value", function(done){
			signal.setValue(-10);
			signal.noGC();
			var recorder = new Recorder(1);
			signal.connect(recorder);
			var waitTime = 0.03;
			expect(signal.getValue()).to.equal(-10);
			signal.linearRampToValueNow(1, waitTime);
			recorder.record(0.1, 0.05, function(buffers){
				var buffer = buffers[0];
				for (var i = 0; i < buffer.length; i++){
					if (buffer[i] === 1){
						expect(signal.samplesToSeconds(i)).is.closeTo(waitTime, 0.01);
						done();
						break;
					}
				}
			});
		});
	});

	//ADD
	describe("Tone.Add", function(){
		this.timeout(500);

		var recorder = new Recorder();

		after(function(){
			recorder.dispose();
		});

		it("can be created and disposed", function(){
			var a = new Add(1);
			a.dispose();
		});

		it("correctly sums a signal and a number", function(done){
			var signal = new Signal(0);
			var adder = new Add(3);
			signal.connect(adder);
			adder.connect(recorder);
			recorder.record(0.1, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(3);
				}
				done();
			});
		});

		it("can handle negative values", function(done){
			var signal = new Signal(10);
			var adder = new Add(-1);
			signal.connect(adder);
			var recorder = new Recorder();
			adder.connect(recorder);
			recorder.record(0.1, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(9);
				}
				done();
			});
		});
	});

	//MULTIPLY
	describe("Tone.Multiply", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var m = new Multiply(1);
			m.dispose();
		});

		it("correctly multiplys a signal and a scalar", function(done){
			var signal = new Signal(2);
			var mult = new Multiply(10);
			signal.connect(mult);
			var recorder = new Recorder();
			mult.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(20);
				}
				signal.dispose();
				mult.dispose();
				done();
			});
		});
	});

	//SCALE
	describe("Tone.Scale", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var s = new Scale(0, 10);
			s.dispose();
		});

		it("scales an input range to an output range", function(done){
			//make an oscillator to drive the signal
			var osc = new Oscillator(1000);
			osc.start();
			var scale = new Scale(-1, 1, 10, 20);
			osc.connect(scale);
			var recorder = new Recorder();
			scale.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.be.within(10, 20);
				}
				done();
			});
		});
	});

	//MERGE
	describe("Tone.Merge", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var mer = new Merge();
			mer.dispose();
		});

		it("merge two signal into one stereo signal", function(done){
			//make an oscillator to drive the signal
			var sigL = new Signal(1);
			var sigR = new Signal(2);
			var merger = new Merge();
			sigL.connect(merger.left);
			sigR.connect(merger.right);
			var recorder = new Recorder(2);
			merger.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var lBuffer = buffers[0];
				var rBuffer = buffers[1];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < lBuffer.length; i++){
					expect(lBuffer[i]).to.equal(1);
					expect(rBuffer[i]).to.equal(2);
				}
				done();
			});
		});
	});

	//SCALE
	describe("Tone.Split", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var split = new Split();
			split.dispose();
		});

		it("merges two signal into one stereo signal and then split them back into two signals", function(done){
			//make an oscillator to drive the signal
			var sigL = new Signal(1);
			var sigR = new Signal(2);
			var merger = new Merge();
			var split = new Split();
			sigL.connect(merger.left);
			sigR.connect(merger.right);
			merger.connect(split);
			var recorderL = new Recorder();
			var recorderR = new Recorder();
			split.left.connect(recorderL);
			split.right.connect(recorderR);
			recorderL.record(0.05, 0.1, function(buffers){
				var lBuffer = buffers[0];
				for (var i = 0; i < lBuffer.length; i++){
					expect(lBuffer[i]).to.equal(1);
				}
			});
			recorderR.record(0.05, 0.1, function(buffers){
				var rBuffer = recorderR.getFloat32Array()[0];
				for (var j = 0; j < rBuffer.length; j++){
					expect(rBuffer[j]).to.equal(2);
				}
				done();
			});
		});
	});

	//EQUALS 0
	describe("Tone.EqualsZero", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var ez = new EqualsZero();
			ez.dispose();
		});

		it("outputs 1 when the incoming signal is 0", function(done){
			var signal = new Signal(0);
			var ez = new EqualsZero();
			signal.connect(ez);
			var recorder = new Recorder();
			ez.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(1);
				}
				signal.dispose();
				ez.dispose();
				done();
			});
		});

		it("outputs 0 when the incoming signal is not 0", function(done){
			var signal = new Signal(100);
			var ez = new EqualsZero();
			signal.connect(ez);
			var recorder = new Recorder();
			ez.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(0);
				}
				signal.dispose();
				ez.dispose();
				done();
			});
		});

		it("is not fooled by values very close to 0", function(done){
			var signal = new Signal(0.00001);
			var ez = new EqualsZero();
			signal.connect(ez);
			var recorder = new Recorder();
			ez.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(0);
				}
				signal.dispose();
				ez.dispose();
				done();
			});
		});

	});

	//THRESHOLD
	describe("Tone.Threshold", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var thresh = new Threshold();
			thresh.dispose();
		});

		it("thresholds an incoming signal to 0 when it is below the thresh", function(done){
			var signal = new Signal(0.1);
			var thresh = new Threshold(0.5);
			signal.connect(thresh);
			var recorder = new Recorder();
			thresh.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(0);
				}
				signal.dispose();
				thresh.dispose();
				done();
			});
		});

		it("thresholds an incoming signal to 1 when it is above the thresh", function(done){
			var signal = new Signal(0.8);
			var thresh = new Threshold(0.5);
			signal.connect(thresh);
			var recorder = new Recorder();
			thresh.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(1);
				}
				signal.dispose();
				thresh.dispose();
				done();
			});
		});

		it("thresholds an incoming signal that is very close to the thresh", function(done){
			var signal = new Signal(0.4999);
			var thresh = new Threshold(0.5);
			signal.connect(thresh);
			var recorder = new Recorder();
			thresh.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(0);
				}
				signal.dispose();
				thresh.dispose();
				done();
			});
		});

	});

	//Switch
	describe("Tone.Switch", function(){
		this.timeout(500);

		it("can be created and disposed", function(){
			var sw = new Switch();
			sw.dispose();
		});

		it("can stop a signal from passing through", function(done){
			var signal = new Signal(10);
			var gate = new Switch();
			signal.connect(gate);
			var recorder = new Recorder();
			gate.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(0);
				}
				signal.dispose();
				gate.dispose();
				done();
			});
		});

		it("can allow a signal to pass through", function(done){
			var signal = new Signal(10);
			var gate = new Switch();
			signal.connect(gate);
			gate.open();
			var recorder = new Recorder();
			gate.connect(recorder);
			recorder.record(0.05, 0.05, function(buffers){
				var buffer = buffers[0];
				//get the left buffer and check that all values are === 1
				for (var i = 0; i < buffer.length; i++){
					expect(buffer[i]).to.equal(10);
				}
				signal.dispose();
				gate.dispose();
				done();
			});
		});
	});

});<|endoftext|>


<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('./beaker.po.js');
var path = require('path');

var beakerPO;

describe('Beaker Tables', function () {

  beforeAll(function (done) {
    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL);
    beakerPO.openFile(path.join(__dirname, '../', 'notebooks/tables-test.bkr'));
    beakerPO.waitUntilLoadingFinished().then(done);
  });

  afterAll(function (done) {
    beakerPO.closeNotebook().then(done);
  });

  describe('Simple Table', function () {
    it('should have Key and Value columns', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Key Value Table').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        beakerPO.checkDataTableHeadByIdCell(v, 'Key\nValue');
        done();
      });
    });

    it('should have 3 columns (index, name, mass)', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Table with Index column').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        expect(beakerPO.getDataTablesTHeadByIdCell(v).all(by.css('th')).count()).toBe(6);//column names row and filter row
        beakerPO.checkDataTableHeadByIdCell(v, 'index name\nmass');
        done();
      });
    });

    it('should be sorted by 1 column (asc)', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Table with Index column').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        beakerPO.checkClass(beakerPO.getDataTablesColumnByIdCell(v, 0), 'sorting_1');
        beakerPO.checkDataTableBodyByIdCell(v, 5, '0 strange 95000000.0000');
        done();
      });
    });

    it('should have 1st column fixed', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Key Value Table').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        expect(beakerPO.getDTFCLeftBody(v).get(0).all(by.css('td')).count()).toBe(1);
        expect(beakerPO.getDTFCRightBody(v).count()).toBe(0);
        done();
      });
    });

    it('should have horizontal scroll', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Horizontal scroll').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        beakerPO.getDataTablesColumnByIdCell(v, 1).getLocation().then(function (locationBeforeScroll) {
          var x = 300;
          beakerPO.scrollDataTableHorizontally(v, x);
          beakerPO.getDataTablesColumnByIdCell(v, 1).getLocation().then(function (locationAfterScroll) {
            expect(locationBeforeScroll.x).toBe(locationAfterScroll.x + x);
            beakerPO.scrollDataTableHorizontally(v, 0);
            done();
          });
        });
      });
    });

    it('should have 1st column fixed when scrolling horizontally', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Horizontal scroll').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        beakerPO.getDTFCLeftColumn(v, 0).getLocation().then(function (locationBeforeScroll) {
          beakerPO.scrollDataTableHorizontally(v, 10000);
          expect(beakerPO.getDTFCLeftColumn(v, 0).getLocation()).toEqual(locationBeforeScroll);
          done();
        });
      });
    });
  });

  describe('Table Menu', function () {

    function checkMenus(expectedItems, actualItems, done) {
      expect(actualItems.count()).toBe(expectedItems.length);
      actualItems.each(function (element, index) {
        element.getInnerHtml().then(function (text) {
          expect(text.trim()).toBe(expectedItems[index]);
          if (done && index === expectedItems.length - 1) {
            done();
          }
        });
      });
    }

    it('should contain items', function (done) {
      var expectedItems = [
        'Reset All Interactions',
        'Use pagination',
        'Rows to Show',
        'Select All',
        'Deselect All',
        'Reverse Selection',
        'Copy to Clipboard',
        'Save All as CSV',
        'Save Selected as CSV',
        'Show All Columns',
        'Show Column',
        'Hide All Columns',
        'Search...',
        'Filter...',
        'Hide Filter'
      ];
      beakerPO.getCodeOutputCellIdBySectionTitle('Table Header').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
      });
      var firstLevelItems = beakerPO.getDataTableMenuFirstLevelItems('Table Header');
      checkMenus(expectedItems, firstLevelItems, done);
    });

    it('should contain Rows to Show submenus', function (done) {
      var menusExpected = ['10', '25', '50', '100', 'All'];
      var menusActual = beakerPO.getDataTableSubmenu('Table Header', 'Rows to Show').all(by.css('a'));
      checkMenus(menusExpected, menusActual, done);
    });

    it('should contain Show Column submenus', function (done) {
      var menusExpected = ['A', 'B', 'C', 'D'];
      var menusActual = beakerPO.getDataTableSubmenu('Table Header', 'Show Column').all(by.css('a'));
      checkMenus(menusExpected, menusActual, done);
    });

    it('should have menu icons', function(done){
      var section = 'Table Header';
      beakerPO.getDataTableMenuToggle(section).click().then(function(){
        beakerPO.checkDataTableMenuItemHasIcon(beakerPO.getDataTableMenuItem(section, 'Search...'), 'fa-search', true);
        beakerPO.checkDataTableMenuItemHasIcon(beakerPO.getDataTableMenuItem(section, 'Filter...'), 'fa-filter', true);
        done();
      });
    });

    describe('Table Menu Toggle', function () {

      it('should be in the left-most column header', function (done) {
        beakerPO.getCodeOutputCellIdBySectionTitle('Table Header').then(function (v) {
          beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
          beakerPO.getDTFCLeftColumnHeader(v, 0).getLocation().then(function (headerLocation) {
            beakerPO.getDataTableMenuToggle('Table Header').getLocation().then(function (menuToggleLocation) {
              var headerBorder = 1;
              expect(menuToggleLocation.x).toBe(headerLocation.x + headerBorder);
              expect(menuToggleLocation.y).toBe(headerLocation.y + headerBorder);
              done();
            });
          });
        });
      });

      it('should be white on hover', function (done) {
        var menuToggle = beakerPO.getDataTableMenuToggle('Table Header');
        browser.actions().mouseMove(menuToggle).perform();
        expect(menuToggle.getCssValue('color')).toBe('rgba(35, 82, 124, 1)');
        expect(menuToggle.element(by.css('span')).getCssValue('background-image')).toContain('menu_white@2x.png');
        done();
      });

    });

    describe('Table Menu Interactions', function () {
      it('should hide pagination', function (done) {
        var section = 'Table with pagination';
        var paginationMenu = beakerPO.getDataTableMenuItem(section, 'Use pagination');
        beakerPO.getCodeOutputCellIdBySectionTitle(section).then(function (v) {
          beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
          expect(beakerPO.getDataTablePaginationControl(v).isPresent()).toBe(true);
          beakerPO.getDataTableMenuToggle(section).click().then(function(){
            beakerPO.checkDataTableMenuItemHasIcon(paginationMenu, 'glyphicon-ok', true);
            paginationMenu.element(by.css('a[ng-click="doUsePagination()"]')).click().then(function(){
              expect(beakerPO.getDataTablePaginationControl(v).isPresent()).toBe(false);
              beakerPO.checkDataTableMenuItemHasIcon(paginationMenu, 'glyphicon-ok', false);
              done();
            });
          });
        });
      });

      it('should display 10 rows', function (done) {
        var section = 'Table with pagination';
        var rowsToShowMenu = beakerPO.getDataTableMenuItem(section, 'Rows to Show');

        beakerPO.getCodeOutputCellIdBySectionTitle(section).then(function (v) {
          beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
          beakerPO.getDataTableMenuToggle(section).click().then(function () {
            browser.actions().mouseMove(rowsToShowMenu).perform();
            var show10 = beakerPO.getDataTableSubMenuItem(rowsToShowMenu, '10');
            show10.element(by.css('a[ng-click="changePageLength(length)"]')).click().then(function () {
                expect(beakerPO.isDTRowInViewPort(beakerPO.getDataTablesScrollBodyByIdCell(v, 0), 10)).toBe(true);
                expect(beakerPO.isDTRowInViewPort(beakerPO.getDataTablesScrollBodyByIdCell(v, 0), 11)).toBe(false);
                done();
            });
          });
        });
      });

      it('should display All rows', function (done) {
        var section = 'Table with pagination';
        var rowsToShowMenu = beakerPO.getDataTableMenuItem(section, 'Rows to Show');

        beakerPO.getCodeOutputCellIdBySectionTitle(section).then(function (v) {
          beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
          beakerPO.getDataTableMenuToggle(section).click().then(function () {
            browser.actions().mouseMove(rowsToShowMenu).perform();
            beakerPO.getDataTableSubMenuItem(rowsToShowMenu, 'All').isDisplayed().then(
              function(isDisplayed){
                expect(isDisplayed).toBe(true);
                if(isDisplayed){
                  var showAll = beakerPO.getDataTableSubMenuItem(rowsToShowMenu, 'All');
                  showAll.element(by.css('a[ng-click="changePageLength(length)"]')).click().then(function () {
                    expect(beakerPO.isDTRowInViewPort(beakerPO.getDataTablesScrollBodyByIdCell(v, 0), 50)).toBe(true);
                  });
                }
              },
              function(error){
                expect(error).toBe("SubMenu 'All' displayed")
              }
            ).then(done);
          });
        });
      });

    });

  });
});<commit_msg>fix test<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('./beaker.po.js');
var path = require('path');

var beakerPO;

describe('Beaker Tables', function () {

  beforeAll(function (done) {
    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL);
    beakerPO.openFile(path.join(__dirname, '../', 'notebooks/tables-test.bkr'));
    beakerPO.waitUntilLoadingFinished().then(done);
  });

  afterAll(function (done) {
    beakerPO.closeNotebook().then(done);
  });

  describe('Simple Table', function () {
    it('should have Key and Value columns', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Key Value Table').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        beakerPO.checkDataTableHeadByIdCell(v, 'Key\nValue');
        done();
      });
    });

    it('should have 3 columns (index, name, mass)', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Table with Index column').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        expect(beakerPO.getDataTablesTHeadByIdCell(v).all(by.css('th')).count()).toBe(6);//column names row and filter row
        beakerPO.checkDataTableHeadByIdCell(v, 'index name\nmass');
        done();
      });
    });

    it('should be sorted by 1 column (asc)', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Table with Index column').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        beakerPO.checkClass(beakerPO.getDataTablesColumnByIdCell(v, 0), 'sorting_1');
        beakerPO.checkDataTableBodyByIdCell(v, 5, '0 strange 95000000.0000');
        done();
      });
    });

    it('should have 1st column fixed', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Key Value Table').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        expect(beakerPO.getDTFCLeftBody(v).get(0).all(by.css('td')).count()).toBe(1);
        expect(beakerPO.getDTFCRightBody(v).count()).toBe(0);
        done();
      });
    });

    it('should have horizontal scroll', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Horizontal scroll').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        beakerPO.getDataTablesColumnByIdCell(v, 1).getLocation().then(function (locationBeforeScroll) {
          var x = 300;
          beakerPO.scrollDataTableHorizontally(v, x);
          beakerPO.getDataTablesColumnByIdCell(v, 1).getLocation().then(function (locationAfterScroll) {
            expect(locationBeforeScroll.x).toBe(locationAfterScroll.x + x);
            beakerPO.scrollDataTableHorizontally(v, 0);
            done();
          });
        });
      });
    });

    it('should have 1st column fixed when scrolling horizontally', function (done) {
      beakerPO.getCodeOutputCellIdBySectionTitle('Horizontal scroll').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
        beakerPO.getDTFCLeftColumn(v, 0).getLocation().then(function (locationBeforeScroll) {
          beakerPO.scrollDataTableHorizontally(v, 10000);
          expect(beakerPO.getDTFCLeftColumn(v, 0).getLocation()).toEqual(locationBeforeScroll);
          done();
        });
      });
    });
  });

  describe('Table Menu', function () {

    function checkMenus(expectedItems, actualItems, done) {
      expect(actualItems.count()).toBe(expectedItems.length);
      actualItems.each(function (element, index) {
        element.getInnerHtml().then(function (text) {
          expect(text.trim()).toBe(expectedItems[index]);
          if (done && index === expectedItems.length - 1) {
            done();
          }
        });
      });
    }

    it('should contain items', function (done) {
      var expectedItems = [
        'Reset All Interactions',
        'Use pagination',
        'Rows to Show',
        'Select All',
        'Deselect All',
        'Reverse Selection',
        'Copy to Clipboard',
        'Save All as CSV',
        'Save Selected as CSV',
        'Show All Columns',
        'Show Column',
        'Hide All Columns',
        'Search...',
        'Filter...',
        'Hide Filter'
      ];
      beakerPO.getCodeOutputCellIdBySectionTitle('Table Header').then(function (v) {
        beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
      });
      var firstLevelItems = beakerPO.getDataTableMenuFirstLevelItems('Table Header');
      checkMenus(expectedItems, firstLevelItems, done);
    });

    it('should contain Rows to Show submenus', function (done) {
      var menusExpected = ['10', '25', '50', '100', 'All'];
      var menusActual = beakerPO.getDataTableSubmenu('Table Header', 'Rows to Show').all(by.css('a'));
      checkMenus(menusExpected, menusActual, done);
    });

    it('should contain Show Column submenus', function (done) {
      var menusExpected = ['A', 'B', 'C', 'D'];
      var menusActual = beakerPO.getDataTableSubmenu('Table Header', 'Show Column').all(by.css('a'));
      checkMenus(menusExpected, menusActual, done);
    });

    it('should have menu icons', function(done){
      var section = 'Table Header';
      beakerPO.getDataTableMenuToggle(section).click().then(function(){
        beakerPO.checkDataTableMenuItemHasIcon(beakerPO.getDataTableMenuItem(section, 'Search...'), 'fa-search', true);
        beakerPO.checkDataTableMenuItemHasIcon(beakerPO.getDataTableMenuItem(section, 'Filter...'), 'fa-filter', true);
        done();
      });
    });

    describe('Table Menu Toggle', function () {

      it('should be in the left-most column header', function (done) {
        beakerPO.getCodeOutputCellIdBySectionTitle('Table Header').then(function (v) {
          beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
          beakerPO.getDTFCLeftColumnHeader(v, 0).getLocation().then(function (headerLocation) {
            beakerPO.getDataTableMenuToggle('Table Header').getLocation().then(function (menuToggleLocation) {
              var headerBorder = 1;
              expect(menuToggleLocation.x).toBe(headerLocation.x + headerBorder);
              expect(menuToggleLocation.y).toBe(headerLocation.y + headerBorder);
              done();
            });
          });
        });
      });

      it('should be white on hover', function (done) {
        var menuToggle = beakerPO.getDataTableMenuToggle('Table Header');
        browser.actions().mouseMove(menuToggle).perform();
        expect(menuToggle.getCssValue('color')).toBe('rgba(35, 82, 124, 1)');
        expect(menuToggle.element(by.css('span')).getCssValue('background-image')).toContain('menu_white@2x.png');
        done();
      });

    });

    describe('Table Menu Interactions', function () {
      it('should hide pagination', function (done) {
        var section = 'Table with pagination';
        var paginationMenu = beakerPO.getDataTableMenuItem(section, 'Use pagination');
        beakerPO.getCodeOutputCellIdBySectionTitle(section).then(function (v) {
          beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
          expect(beakerPO.getDataTablePaginationControl(v).isPresent()).toBe(true);
          beakerPO.getDataTableMenuToggle(section).click().then(function(){
            beakerPO.checkDataTableMenuItemHasIcon(paginationMenu, 'glyphicon-ok', true);
            paginationMenu.element(by.css('a[ng-click="doUsePagination()"]')).click().then(function(){
              expect(beakerPO.getDataTablePaginationControl(v).isPresent()).toBe(false);
              beakerPO.checkDataTableMenuItemHasIcon(paginationMenu, 'glyphicon-ok', false);
              done();
            });
          });
        });
      });

      it('should display 10 rows', function (done) {
        var section = 'Table with pagination';
        var rowsToShowMenu = beakerPO.getDataTableMenuItem(section, 'Rows to Show');

        beakerPO.getCodeOutputCellIdBySectionTitle(section).then(function (v) {
          beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
          beakerPO.getDataTableMenuToggle(section).click().then(function () {
            browser.actions().mouseMove(rowsToShowMenu).perform();
            var show10 = beakerPO.getDataTableSubMenuItem(rowsToShowMenu, '10');
            show10.element(by.css('a[ng-click="changePageLength(length)"]')).click().then(function () {
                expect(beakerPO.isDTRowInViewPort(beakerPO.getDataTablesScrollBodyByIdCell(v, 0), 10)).toBe(true);
                expect(beakerPO.isDTRowInViewPort(beakerPO.getDataTablesScrollBodyByIdCell(v, 0), 11)).toBe(false);
                done();
            });
          });
        });
      });

      it('should display All rows', function (done) {
        var section = 'Table with pagination';
        browser.driver.manage().window().maximize();
        var rowsToShowMenu = beakerPO.getDataTableMenuItem(section, 'Rows to Show');

        beakerPO.getCodeOutputCellIdBySectionTitle(section).then(function (v) {
          beakerPO.waitCodeCellOutputTablePresentByIdCell(v);
          beakerPO.getDataTableMenuToggle(section).click().then(function () {
            browser.actions().mouseMove(rowsToShowMenu).perform();
            var showAll = beakerPO.getDataTableSubMenuItem(rowsToShowMenu, 'All');
            showAll.element(by.css('a[ng-click="changePageLength(length)"]')).click().then(function () {
              expect(beakerPO.isDTRowInViewPort(beakerPO.getDataTablesScrollBodyByIdCell(v, 0), 50)).toBe(true);
            });
            done();
          });
        });
      });

    });

  });
});<|endoftext|>


<commit_before>'use strict'

var assert = require('assert')
var the = require('../the-thing-is')

describe('the', function() {
  it('is a function', function() {
    assert(typeof the === 'function')
  })
})

describe('the(thing)', function() {
  it('returns an object', function() {
    assert(typeof the('thing') === 'object')
  })
})

describe('the(thing).is', function() {
  it('is a function', function() {
    assert(typeof the('thing').is === 'function')
  })
})

describe('basic checks', function(){
  describe('the().is()', function(){
    it('returns false', function() {
      assert.equal(the().is(), false)
    })
  })
  describe("the('thing').is()", function() {
    it('returns true', function() {
      assert.equal(the('thing').is(), true)
    })
  })
  describe("the(0).is('integer')", function() {
    it('returns true', function() {
      assert.equal(the(0).is('integer'), true)
    })
    // it("doesn't set an error", function() {
    //   assert(the.last.thing === 0)
    //   assert(!the.last.error)
    // })
  })
  describe("the('thing').is('gonnaGetThrown')", function() {
    it('throws a TypeError', function() {
      assert.throws(function(){
        the('thing').is('gonnaGetThrown')
      }, TypeError)
    })
    // it("doesn't set an error", function() {
    //   assert.equal(the.last.thing, 'thing')
    //   assert(!the.last.error)
    // })
  })
})

describe("expectations array", function(){
  describe("the(0).is(['integer'])", function() {
    it('returns true', function() {
      assert.equal(the(0).is(['integer']), true)
    })
  })
  describe("the(0).is(['string'])", function() {
    it('returns false', function() {
      assert.equal(the(0).is(['string']), false)
    })
  })
  describe("the('0').is(['string', 'numberString', 'integerString'])", function() {
    it('returns true', function() {
      assert.equal(the('0').is(['string', 'numberString', 'integerString']), true)
    })
  })
  describe("the('0').is(['string', 'number', 'integer'])", function() {
    it('returns false', function() {
      assert.equal(the('0').is(['string', 'number', 'integer']), false)
    })
    // it('sets the.last.error', function() {
    //   assert(the.last.error)
    // })
  })
})

describe("expectations against a standard", function(){

  describe("the('thing').is([{gonnaGetThrown:true}])", function(){
    it("should throw an error", function(){
      var whatIExpect = [{gonnaGetThrown:true}]
      assert.throws(function(){
        the('thing').is(whatIExpect)
      }, TypeError)
    })
  })

  describe("the('0').is([{number:'wrong'}])", function(){
    it("shouldn't throw an error", function(){
      var whatIExpect = [{number:'wrong'}]
      assert.doesNotThrow(function(){
        the('0').is(whatIExpect)
      })
    })
  })

  describe("the('0')", function(){
    it(".is(['string', 'integerString', {gte: 0, lte:100}])", function(){
      var whatIExpect = [
        'string', 'integerString', {
          gte: 0,
          lte: 100
        }]
      assert( the('0').is(whatIExpect) )
    })
    it(".is([{ equal:0 }])", function(){
      assert( the('0').is([{ equal: 0 }]) )
    })
    it(".is([{ exactly: '0' }])", function(){
      assert( the('0').is([{ exactly: '0' }]) )
    })
    it(".isnt([{ equal: 1 }])", function(){
      assert( the('0').isnt([{ equal: 1 }]) )
    })
    it(".isnt([{ equal: '1' }])", function(){
      assert( the('0').isnt([{ equal: '1' }]) )
    })
  })
  describe("the('101')", function(){
    it(".isnt(['string', 'integerString', {gte: 0, lte:100}])", function(){
      var whatIExpect = [
        'string', 'integerString', {
          gte: 0,
          lte: 100
        }]
      assert( the('101').isnt(whatIExpect), false )
    })
    // it("sets a meaningful (enough) error message", function(){
    //   assert.equal( the.last.error, "")
    // })
  })
})

describe('the(thing).isnt', function() {
  it('is a function', function() {
    assert(typeof the('thing').isnt === 'function')
  })
  describe('the().isnt()', function() {
    it('returns true', function() {
      assert.equal(the().isnt(), true)
    })
  })
  describe("the('thing').isnt()", function() {
    it('returns false', function() {
      assert.equal(the('thing').isnt(), false)
    })
  })
  describe("the(0).isnt('integer')", function() {
    it('returns false', function() {
      assert.equal(the(0).isnt('integer'), false)
    })
  })
  describe("the(0).isnt(['integer'])", function() {
    it('returns false', function() {
      assert.equal(the(0).isnt(['integer']), false)
    })
  })
  describe("the('thing').isnt('gonnaGetThrown')", function() {
    it('throws a TypeError', function() {
      assert.throws(function(){
        the('thing').isnt('gonnaGetThrown')
      }, TypeError)
    })
    // it("doesn't set an error", function() {
    //   assert.equal(the.last.thing, 'thing')
    //   assert(!the.last.error)
    // })
  })
})

describe('testing objects', function() {

  describe('{foo:"bar"}', function() {
    var subject = { foo: "bar" }

    it('is("plainObject")', function() {
      assert.equal(the(subject).is('plainObject'), true)
    })
    it('is({ foo: "string" })', function() {
      assert.equal(the(subject).is({ foo: "string" }), true)
    })
    it('is({foo:["string"]})', function() {
      assert.equal(the(subject).is({ foo: ["string"] }), true)
    })
    it('is({bar:["string"]}) == false', function() {
      assert.equal(the(subject).is({ bar:["string"] }), false)
    })
    it('isnt({bar:["string"]})', function() {
      assert.equal(the(subject).isnt({ bar:["string"] }), true)
    })
  })

  describe('{ foo:"bar", bar:"fizz", baz:666 }', function() {
    var subject = {
      foo: 'bar',
      bar: 'fizz',
      baz: 666
    }
    it('is("plainObject")', function() {
      assert.equal(the(subject).is('plainObject'), true)
    })
    it('is({ foo:"string", bar:"string", baz:["number", {greaterThan:0}, {lessThan:777}] })', function() {
      assert.equal(the(subject).is({
        foo: 'string',
        bar: 'string',
        baz: ['number', {greaterThan:0}, {lessThan:777}]
      }), true)
    })
    it('isnt({ flop:"string", bar:"string", baz:["number", {greaterThan:0}, {lessThan:777}] })', function() {
      assert.equal(the(subject).isnt({
        flop: 'string',
        bar: 'string',
        baz: ['number', {greaterThan:0}, {lessThan:777}]
      }), true)
    })
    it('isnt({ foo:"string", bar:"string", baz:["number", {greaterThan:666}] })', function() {
      assert.equal(the(subject).isnt({
        foo: 'string',
        bar: 'string',
        baz: ['number', {greaterThan:666}]
      }), true)
    })
  })

  describe('{foo: {bar: {baz: {buz: "fiz"}}}}', function() {
    var subject = {
      foo: {
        bar: {
          baz: {
            buz: 'fiz'
          }
        }
      }
    }
    it('is("plainObject")', function() {
      assert.equal(the(subject).is('plainObject'), true)
    })
    it('is({foo: {bar: {baz: {buz: ["string"]}}}})', function() {
      assert.equal(the(subject).is({foo: {bar: {baz: {buz: ['string']}}}}), true)
    })
    it('isnt({foo: {bar: {baz: {buz: ["number"]}}}}) - wrong type', function() {
      assert.equal(the(subject).isnt({foo: {bar: {baz: {buz: ['number']}}}}), true)
    })
    it('isnt({foo: {bar: {baz: {buz: {fiz: ["string"]}}}}}) - nested too deep', function() {
      assert.throws(function(){
        the(subject).isnt({foo: {bar: {baz: {buz: {fiz: ['string']}}}}})
      }, TypeError)
    })
  })

})

<commit_msg>Put the tests for errors back in, plus expanded object testing.<commit_after>'use strict'

var assert = require('assert')
var the = require('../the-thing-is')

describe('the', function() {
  it('is a function', function() {
    assert(typeof the === 'function')
  })
})

describe('the(thing)', function() {
  it('returns an object', function() {
    assert(typeof the('thing') === 'object')
  })
})

describe('the(thing).is', function() {
  it('is a function', function() {
    assert(typeof the('thing').is === 'function')
  })
})

describe('basic checks', function(){
  describe('the().is()', function(){
    it('returns false', function() {
      assert.equal(the().is(), false)
    })
  })
  describe("the('thing').is()", function() {
    it('returns true', function() {
      assert.equal(the('thing').is(), true)
    })
  })
  describe("the(0).is('integer')", function() {
    it('returns true', function() {
      assert.equal(the(0).is('integer'), true)
    })
    it("doesn't set an error", function() {
      assert(the.last.thing === 0)
      assert(!the.last.error)
    })
  })
  describe("the('thing').is('gonnaGetThrown')", function() {
    it('throws a TypeError', function() {
      assert.throws(function(){
        the('thing').is('gonnaGetThrown')
      }, TypeError)
    })
    it("doesn't set an error", function() {
      assert.equal(the.last.thing, 'thing')
      assert(!the.last.error)
    })
  })
})

describe("expectations array", function(){
  describe("the(0).is(['integer'])", function() {
    it('returns true', function() {
      assert.equal(the(0).is(['integer']), true)
    })
  })
  describe("the(0).is(['string'])", function() {
    it('returns false', function() {
      assert.equal(the(0).is(['string']), false)
    })
  })
  describe("the('0').is(['string', 'numberString', 'integerString'])", function() {
    it('returns true', function() {
      assert.equal(the('0').is(['string', 'numberString', 'integerString']), true)
    })
  })
  describe("the('0').is(['string', 'number', 'integer'])", function() {
    it('returns false', function() {
      assert.equal(the('0').is(['string', 'number', 'integer']), false)
    })
    it('sets the.last.wasnt', function() {
      assert.deepEqual(the.last.wasnt, ['number'])
    })
  })
})

describe("expectations against a standard", function(){

  describe("the('thing').is([{gonnaGetThrown:true}])", function(){
    it("should throw an error", function(){
      var whatIExpect = [{gonnaGetThrown:true}]
      assert.throws(function(){
        the('thing').is(whatIExpect)
      }, TypeError)
    })
  })

  describe("the('0').is([{number:'wrong'}])", function(){
    it("shouldn't throw an error", function(){
      var whatIExpect = [{number:'wrong'}]
      assert.doesNotThrow(function(){
        the('0').is(whatIExpect)
      })
    })
  })

  describe("the('0')", function(){
    it(".is(['string', 'integerString', {gte: 0, lte:100}])", function(){
      var whatIExpect = [
        'string', 'integerString', {
          gte: 0,
          lte: 100
        }]
      assert( the('0').is(whatIExpect) )
    })
    it(".is([{ equal:0 }])", function(){
      assert( the('0').is([{ equal: 0 }]) )
    })
    it(".is([{ exactly: '0' }])", function(){
      assert( the('0').is([{ exactly: '0' }]) )
    })
    it(".isnt([{ equal: 1 }])", function(){
      assert( the('0').isnt([{ equal: 1 }]) )
      assert.deepEqual( the.last.wasnt, [{equal:'1'}])
    })
    it(".isnt([{ equal: '1' }])", function(){
      assert( the('0').isnt([{ equal: '1' }]) )
      assert.deepEqual( the.last.wasnt, [{equal:'1'}])
    })
  })
  describe("the('101')", function(){
    it(".isnt(['string', 'integerString', {gte: 0, lte:100}])", function(){
      var whatIExpect = [
        'string', 'integerString', {
          gte: 0,
          lte: 100
        }]
      assert( the('101').isnt(whatIExpect), false )
    })
    it("creates a meaningful error array", function(){
      assert.deepEqual( the.last.wasnt, [{lte:100}])
    })
  })
})

describe('the(thing).isnt', function() {
  it('is a function', function() {
    assert(typeof the('thing').isnt === 'function')
  })
  describe('the().isnt()', function() {
    it('returns true', function() {
      assert.equal(the().isnt(), true)
    })
  })
  describe("the('thing').isnt()", function() {
    it('returns false', function() {
      assert.equal(the('thing').isnt(), false)
    })
  })
  describe("the(0).isnt('integer')", function() {
    it('returns false', function() {
      assert.equal(the(0).isnt('integer'), false)
    })
  })
  describe("the(0).isnt(['integer'])", function() {
    it('returns false', function() {
      assert.equal(the(0).isnt(['integer']), false)
    })
  })
  describe("the('thing').isnt('gonnaGetThrown')", function() {
    it('throws a TypeError', function() {
      assert.throws(function(){
        the('thing').isnt('gonnaGetThrown')
      }, TypeError)
    })
    it("doesn't set an error", function() {
      assert.equal(the.last.thing, 'thing')
      assert(!the.last.error)
    })
  })
})

describe('testing objects', function() {

  describe('{foo:"bar"}', function() {
    var subject = { foo: "bar" }

    it('is("plainObject")', function() {
      assert.equal(the(subject).is('plainObject'), true)
    })
    it('is({ foo: "string" })', function() {
      assert.equal(the(subject).is({ foo: "string" }), true)
    })
    it('is({foo:["string"]})', function() {
      assert.equal(the(subject).is({ foo: ["string"] }), true)
    })
    it('is({bar:["string"]}) == false', function() {
      assert.equal(the(subject).is({ bar:["string"] }), false)
    })
    it('isnt({bar:["string"]})', function() {
      assert.equal(the(subject).isnt({ bar:["string"] }), true)
    })
  })

  describe('{ foo:"bar", bar:"fizz", baz:666 }', function() {
    var subject = {
      foo: 'bar',
      bar: 'fizz',
      baz: 666
    }
    it('is("plainObject")', function() {
      assert.equal(the(subject).is('plainObject'), true)
    })
    it('is({ foo:"string", bar:"string", baz:["number", {greaterThan:0}, {lessThan:777}] })', function() {
      assert.equal(the(subject).is({
        foo: 'string',
        bar: 'string',
        baz: ['number', {greaterThan:0}, {lessThan:777}]
      }), true)
    })
    it('isnt({ flop:"string", bar:"string", baz:["number", {greaterThan:0}, {lessThan:777}] })', function() {
      assert.equal(the(subject).isnt({
        flop: 'string',
        bar: 'string',
        baz: ['number', {greaterThan:0}, {lessThan:777}]
      }), true)
    })
    it('isnt({ foo:"string", bar:"string", baz:["number", {greaterThan:666}] })', function() {
      assert.equal(the(subject).isnt({
        foo: 'string',
        bar: 'string',
        baz: ['number', {greaterThan:666}]
      }), true)
    })
  })

  describe('{foo: {bar: {baz: {buz: "fiz"}}}}', function() {
    var subject = {
      foo: {
        bar: {
          baz: {
            buz: 'fiz'
          }
        }
      }
    }
    it('is("plainObject")', function() {
      assert.equal(the(subject).is('plainObject'), true)
    })
    it('is({foo: {bar: {baz: {buz: ["string"]}}}})', function() {
      assert.equal(the(subject).is({foo: {bar: {baz: {buz: ['string']}}}}), true)
    })
    it('isnt({foo: {bar: {baz: {buz: ["number"]}}}}) - wrong type', function() {
      assert.equal(the(subject).isnt({foo: {bar: {baz: {buz: ['number']}}}}), true)
    })
    it('isnt({foo: {bar: {baz: {buz: {fiz: ["string"]}}}}}) - nested too deep', function() {
      assert.throws(function(){
        the(subject).isnt({foo: {bar: {baz: {buz: {fiz: ['string']}}}}})
      }, TypeError)
    })
  })

  describe('{foo: {bar: {baz: {buz: "fiz"}}}}', function() {
    var subject = {
      fo: {
        foo: {
          fooo: 'fooo'
        },
        oof: {
          ooof: 'ooof'
        }
      },
      bar: {
        baz: {
          buz: 'buz'
        },
        rab: {
          zub: 'zub'
        },
        zab: 'zab'
      }
    }

    it('is("plainObject")', function() {
      assert.equal(the(subject).is('plainObject'), true)
    })
    it('is({foo: {bar: {baz: {buz: ["string"]}}}})', function() {
      var whatIExpect = {
        fo: {
          foo: {
            fooo: 'string'
          },
          oof: {
            ooof: 'string'
          }
        },
        bar: {
          baz: {
            buz: 'string'
          }
        }
      }
      assert.equal(the(subject).is(whatIExpect), true)
    })
    it('isnt({foo: {bar: {baz: {buz: ["number"]}}}}) - foo not at top level', function() {
      assert.equal(the(subject).isnt({foo: {bar: {baz: {buz: ['number']}}}}), true)
      assert.deepEqual(the.last.wasnt, [{'foo':'present'}])
    })
  })

})

<|endoftext|>


<commit_before>var tape = require("tape"),
    hierarchy = require("../");

tape("treemap() has the expected defaults", function(test) {
  var t = hierarchy.treemap();
  test.ok(t.sort()({value: 2}, {value: 0}) < 0);
  test.ok(t.sort()({value: -1}, {value: 2}) > 0);
  test.deepEqual(t.children()({children: [1, 2]}), [1, 2]);
  test.equal(t.value()({value: 42}), 42);
  test.deepEqual(t.size(), [1, 1]);
  test.equal(t.padding(), null);
  test.equal(t.round(), false);
  test.equal(t.sticky(), false);
  test.equal(t.ratio(), (1 + Math.sqrt(5)) / 2);
  test.equal(t.mode(), "squarify");
  test.end();
});
<commit_msg>Fix tests.<commit_after>var tape = require("tape"),
    hierarchy = require("../");

tape("treemap() has the expected defaults", function(test) {
  var t = hierarchy.treemap();
  test.ok(t.sort()({value: 2}, {value: 0}) < 0);
  test.ok(t.sort()({value: -1}, {value: 2}) > 0);
  test.deepEqual(t.children()({children: [1, 2]}), [1, 2]);
  test.equal(t.value()({value: 42}), 42);
  test.deepEqual(t.size(), [1, 1]);
  test.equal(t.childPadding(), 0); // TODO
  test.equal(t.siblingPadding(), 0); // TODO
  test.equal(t.round(), false);
  // test.equal(t.sticky(), false); // TODO
  test.equal(t.ratio(), (1 + Math.sqrt(5)) / 2);
  test.equal(t.mode(), "squarify");
  test.end();
});
<|endoftext|>


<commit_before>// Copyright © 2013-2014 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

"use strict";

var assert = require('assert');
var updater = require('../server/updater');
var config = require('../server/config');
var analytics = require('../server/analytics');
var db = require('../server/db');

describe('Updater:', function () {

    it("Looks for new game in chunks", function () {
        var now = 10000;
        var config = {
            samplingPeriod: 3500,
            samplingChunkSize: 1000
        };

        var chunks = updater._chunks(now, config);

        assert.deepEqual([
            {start: 9000, duration: 1000},
            {start: 8000, duration: 1000},
            {start: 7000, duration: 1000},
            {start: 6500, duration: 500}
        ], chunks)
    });

    it("Converting a chunk to a service URL", function () {
        assert.equal('http://www.nanodesu.info/pastats/report/winners?start=123&duration=5',
            updater._chunkToUrl({start: 123111, duration: 5111}));
    });

    describe("After updating", function () {
        this.timeout(10 * 1000);
        before(function (done) {
            config.samplingPeriod = 60 * 60 * 1000;
            db.removeAll()
                .then(updater.update)
                .fin(done).done();
        });

        it("the database should have games", function (done) {
            db.games.count()
                .then(function (count) {
                    assert.notEqual(0, count);
                })
                .fin(done).done();
        });

        it("the database should have game statistics", function (done) {
            analytics.at(10000)
                .then(function (stats) {
                    assert.ok(stats.armyCount.values.length >= 1);
                })
                .fin(done).done()
        });
    })
});
<commit_msg>Skip slow tests with autotest<commit_after>// Copyright © 2013-2014 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

"use strict";

var assert = require('assert');
var updater = require('../server/updater');
var config = require('../server/config');
var analytics = require('../server/analytics');
var db = require('../server/db');

function describeSlow() {
    if (process.argv.indexOf('--watch') >= 0) {
        describe.skip.apply(this, arguments);
    } else {
        describe.apply(this, arguments);
    }
}

describe('Updater:', function () {

    it("Looks for new game in chunks", function () {
        var now = 10000;
        var config = {
            samplingPeriod: 3500,
            samplingChunkSize: 1000
        };

        var chunks = updater._chunks(now, config);

        assert.deepEqual([
            {start: 9000, duration: 1000},
            {start: 8000, duration: 1000},
            {start: 7000, duration: 1000},
            {start: 6500, duration: 500}
        ], chunks)
    });

    it("Converting a chunk to a service URL", function () {
        assert.equal('http://www.nanodesu.info/pastats/report/winners?start=123&duration=5',
            updater._chunkToUrl({start: 123111, duration: 5111}));
    });

    describeSlow("After updating", function () {
        this.timeout(10 * 1000);
        before(function (done) {
            config.samplingPeriod = 60 * 60 * 1000;
            db.removeAll()
                .then(updater.update)
                .fin(done).done();
        });

        it("the database should have games", function (done) {
            db.games.count()
                .then(function (count) {
                    assert.notEqual(0, count);
                })
                .fin(done).done();
        });

        it("the database should have game statistics", function (done) {
            analytics.at(10000)
                .then(function (stats) {
                    assert.ok(stats.armyCount.values.length >= 1);
                })
                .fin(done).done()
        });
    });
});
<|endoftext|>


<commit_before>var noop = require('../../utility/noop');

describe('noop', function () {
  it('is a function', function () {
    expect(noop).to.be.a('function');
  });

  it('has a length of 0', function () {
    expect(noop.length).to.equal(0);
  });
});
<commit_msg>Test that noop returns `undefined`<commit_after>var noop = require('../../utility/noop');

describe('noop', function () {
  it('is a function', function () {
    expect(noop).to.be.a('function');
  });

  it('has a length of 0', function () {
    expect(noop.length).to.equal(0);
  });

  it('returns undefined', function () {
    expect(noop()).to.equal(undefined);
  });
});
<|endoftext|>