<commit_before>'use strict';

/**
 * Test dependencies
 */
var mocha = require('mocha'),
    sinon = require('sinon'),
    expect = require('chai').expect,
    rewire = require('rewire'),
    logger = rewire('../lib/logger.js');

describe('Logger', function() {

    /**
     * Interface validator mock
     */
    var interfaceValidator,

        /**
         * Mock adapter
         */
        adapter,

        /**
         * Interface array mock
         */
        interfaceMock = [
            'error',
            'info',
            'debug',
            'warning'
        ];

    /**
     * Returns logger adapter mock
     * @returns {{error: *, info: *, warning: *, debug: *}}
     */
    function getLoggerAdapterMock() {
        return {
            error: sinon.stub(),
            info: sinon.stub(),
            warning: sinon.stub(),
            debug: sinon.stub()
        };
    }

    /**
     * Returns mock interface validator object
     * @returns {{validate: *}}
     */
    function getInterfaceValidatorMock() {
        return {
            validate: sinon.stub()
        };
    }

    beforeEach(function() {
        interfaceValidator = getInterfaceValidatorMock();
        logger.__set__('interfaceValidator', interfaceValidator);
    });

    describe('configuration', function() {
        describe('#setLogger()', function() {

            /**
             * The logger interface name
             * @type {string}
             */
            var interfaceName = 'LoggerInterface';

            it('should call the validate method with the given adapter, interface and name', function() {
                var mock = getLoggerAdapterMock();
                logger.setLogger(mock);

                expect(interfaceValidator.validate.calledWith(interfaceName, mock, interfaceMock)).to.equal(true);
            });

            it('should return it self for chaining', function() {
                expect(logger.setLogger(getLoggerAdapterMock())).to.equal(logger);
            });

            it('try calling the API without setting an adapter will do nothing', function() {
                expect(logger.error('hey')).to.equal(undefined);
            });
        });
    });

    describe('module api', function() {

        /**
         * Object message mock
         */
        var objectMessage = {
            msg: 'The force was not found..'
        };

        /**
         * Set a mock adapter before every test
         */
        beforeEach(function() {
            adapter = getLoggerAdapterMock();
            logger.setLogger(adapter);
        });

        describe('#error()', function() {
            it('should call the adapter error method with the message', function() {
                logger.error(objectMessage);

                expect(adapter.error.calledWith(objectMessage));
            });
        });

        describe('#warning()', function() {
            it('should call the adapter warning method with the message', function() {
                logger.error(objectMessage);

                expect(adapter.warning.calledWith(objectMessage));
            });
        });

        describe('#info()', function() {
            it('should call the adapter info method with the message', function() {
                logger.error(objectMessage);

                expect(adapter.info.calledWith(objectMessage));
            });
        });

        describe('#debug()', function() {
            it('should call the adapter debug method with the message', function() {
                logger.error(objectMessage);

                expect(adapter.debug.calledWith(objectMessage));
            });
        });
    });
});<commit_msg>(feature) added tests to the new console adapter<commit_after>'use strict';

/**
 * Test dependencies
 */
var mocha = require('mocha'),
    sinon = require('sinon'),
    expect = require('chai').expect,
    rewire = require('rewire'),
    logger = rewire('../lib/logger.js');

describe('Logger', function() {

    /**
     * Interface validator mock
     */
    var interfaceValidator,

        /**
         * Mock adapter
         */
        adapter,

        /**
         * Interface array mock
         */
        interfaceMock = [
            'error',
            'info',
            'debug',
            'warning'
        ];

    /**
     * Returns logger adapter mock
     * @returns {{error: *, info: *, warning: *, debug: *}}
     */
    function getLoggerAdapterMock() {
        return {
            error: sinon.stub(),
            info: sinon.stub(),
            warning: sinon.stub(),
            debug: sinon.stub()
        };
    }

    /**
     * Returns mock interface validator object
     * @returns {{validate: *}}
     */
    function getInterfaceValidatorMock() {
        return {
            validate: sinon.stub()
        };
    }

    beforeEach(function() {
        interfaceValidator = getInterfaceValidatorMock();
        logger.__set__('interfaceValidator', interfaceValidator);
    });

    describe('configuration', function() {
        describe('#setLogger()', function() {

            /**
             * The logger interface name
             * @type {string}
             */
            var interfaceName = 'LoggerInterface';

            it('should call the validate method with the given adapter, interface and name', function() {
                var mock = getLoggerAdapterMock();
                logger.setLogger(mock);

                expect(interfaceValidator.validate.calledWith(interfaceName, mock, interfaceMock)).to.equal(true);
            });

            it('should return it self for chaining', function() {
                expect(logger.setLogger(getLoggerAdapterMock())).to.equal(logger);
            });

            it('try calling the API without setting an adapter will do nothing', function() {
                expect(logger.error('hey')).to.equal(undefined);
            });
        });
    });

    describe('module api', function() {

        /**
         * Object message mock
         */
        var objectMessage = {
            msg: 'The force was not found..'
        };

        /**
         * Set a mock adapter before every test
         */
        beforeEach(function() {
            adapter = getLoggerAdapterMock();
            logger.setLogger(adapter);
        });

        describe('#error()', function() {
            it('should call the adapter error method with the message', function() {
                logger.error(objectMessage);

                expect(adapter.error.calledWith(objectMessage));
            });
        });

        describe('#warning()', function() {
            it('should call the adapter warning method with the message', function() {
                logger.error(objectMessage);

                expect(adapter.warning.calledWith(objectMessage));
            });
        });

        describe('#info()', function() {
            it('should call the adapter info method with the message', function() {
                logger.error(objectMessage);

                expect(adapter.info.calledWith(objectMessage));
            });
        });

        describe('#debug()', function() {
            it('should call the adapter debug method with the message', function() {
                logger.error(objectMessage);

                expect(adapter.debug.calledWith(objectMessage));
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert')
var Promise = require('../')

var i = 0
var sampleA, sampleB

function next() {
  return new Promise(function (resolve) {
    i++
    /*
    if (i % 100000 === 0) {
      global.gc()
      console.dir(process.memoryUsage())
    }
    */
    if (i === 100000 && typeof global.gc === 'function') {
      global.gc()
      sampleA = process.memoryUsage()
    }
    if (i > 100000 * 5) {
      if (typeof global.gc === 'function') {
        global.gc()
        sampleB = process.memoryUsage()
        console.log('Memory usage at start:');
        console.dir(sampleA)
        console.log('Memory usage at end:');
        console.dir(sampleB)
        assert(sampleA.rss * 1.2 > sampleB.rss, 'RSS should not grow by more than 20%')
        assert(sampleA.heapTotal * 1.2 > sampleB.heapTotal, 'heapTotal should not grow by more than 20%')
        assert(sampleA.heapUsed * 1.2 > sampleB.heapUsed, 'heapUsed should not grow by more than 20%')
      }
    } else {
      setImmediate(resolve)
    }
  }).then(next)
}

if (typeof global.gc !== 'function') {
  console.warn('You must run with --expose-gc to test for memory leak.')
}
next().done()
<commit_msg>Don't measure resident swap size<commit_after>'use strict';

var assert = require('assert')
var Promise = require('../')

var i = 0
var sampleA, sampleB

function next() {
  return new Promise(function (resolve) {
    i++
    /*
    if (i % 100000 === 0) {
      global.gc()
      console.dir(process.memoryUsage())
    }
    */
    if (i === 100000 && typeof global.gc === 'function') {
      global.gc()
      sampleA = process.memoryUsage()
    }
    if (i > 100000 * 5) {
      if (typeof global.gc === 'function') {
        global.gc()
        sampleB = process.memoryUsage()
        console.log('Memory usage at start:');
        console.dir(sampleA)
        console.log('Memory usage at end:');
        console.dir(sampleB)
        assert(sampleA.heapTotal * 1.2 > sampleB.heapTotal, 'heapTotal should not grow by more than 20%')
        assert(sampleA.heapUsed * 1.2 > sampleB.heapUsed, 'heapUsed should not grow by more than 20%')
      }
    } else {
      setImmediate(resolve)
    }
  }).then(next)
}

if (typeof global.gc !== 'function') {
  console.warn('You must run with --expose-gc to test for memory leak.')
}
next().done()
<|endoftext|>


<commit_before>/* eslint-env mocha */

/* global gc */

if (typeof gc === 'undefined') {
  throw new Error('Memory test should be run with --expose-gc');
}

console.log('Running memory test...');

var assert = require('assert');

var Reader = require('../');

var fs = require('fs');
var file = 'test/data/GeoIP2-Precision-ISP-Test.mmdb';
var fileSize = fs.statSync(file).size;

var readers = [];

var start = process.memoryUsage();

console.log('Initial RSS: %s', start.rss);

var num = 5000;

// TEST DESTROY
console.log('\nTesting cleanup...');

// Do a few loops of loading lots of stuff into mem and chucking it away

var i, j, mem;

for (j = 0; j < 10; j += 1) {

  readers = [];

  gc();

  for (i = 0; i < num; i++) {
    readers.push(new Reader(file));
  }

  gc();

  mem = process.memoryUsage();

  console.log('Pass %s RSS: %s', j, mem.rss);

  // We've loaded ${num} copies of the file into mem, they should be there
  // 0.75 in case initial RSS was a bit high.
  assert(mem.rss - start.rss > num * fileSize * 0.75);

  // Dispose + gc + reload shouldn't increase the mem too much
  assert(mem.rss - start.rss < num * fileSize * 1.5);
}

// If we actually get to this point without crashing, it must have worked
console.log('Good!\n');

readers = [];

gc();

// TEST RELOAD
console.log('\nTesting reloading...');

for (i = 0; i < num; i++) {
  readers.push(new Reader(file));
}

for (j = 0; j < 10; j += 1) {

  readers.forEach(function(r) {
    r.reloadSync(file);
    assert.strictEqual(r.lookup('1.128.0.0').isp, 'Telstra Internet');
  });

  gc();

  mem = process.memoryUsage();

  console.log('Pass %s RSS: %s', j, mem.rss);

  // We've loaded ${num} copies of the file into mem, they should be there
  // 0.75 in case initial RSS was a bit high.
  assert(mem.rss - start.rss > num * fileSize * 0.75);

  // Dispose + gc + reload shouldn't increase the mem too much
  assert(mem.rss - start.rss < num * fileSize * 1.5);
}

console.log('Good!');
<commit_msg>Looks like node 7's GC isn't as aggressive. Keep the reload threshold at 1.75<commit_after>/* eslint-env mocha */

/* global gc */

if (typeof gc === 'undefined') {
  throw new Error('Memory test should be run with --expose-gc');
}

console.log('Running memory test...');

var assert = require('assert');

var Reader = require('../');

var fs = require('fs');
var file = 'test/data/GeoIP2-Precision-ISP-Test.mmdb';
var fileSize = fs.statSync(file).size;

var readers = [];

var start = process.memoryUsage();

console.log('Initial RSS: %s', start.rss);

var num = 5000;

// TEST DESTROY
console.log('\nTesting cleanup...');

// Do a few loops of loading lots of stuff into mem and chucking it away

var i, j, mem;

for (j = 0; j < 10; j += 1) {

  readers = [];

  gc();

  for (i = 0; i < num; i++) {
    readers.push(new Reader(file));
  }

  gc();

  mem = process.memoryUsage();

  console.log('Pass %s RSS: %s', j, mem.rss);

  // We've loaded ${num} copies of the file into mem, they should be there
  // 0.75 in case initial RSS was a bit high.
  assert(mem.rss - start.rss > num * fileSize * 0.75);

  // Dispose + gc + reload shouldn't increase the mem too much
  assert(mem.rss - start.rss < num * fileSize * 1.5);
}

// If we actually get to this point without crashing, it must have worked
console.log('Good!\n');

readers = [];

gc();

// TEST RELOAD
console.log('\nTesting reloading...');

for (i = 0; i < num; i++) {
  readers.push(new Reader(file));
}

for (j = 0; j < 10; j += 1) {

  readers.forEach(function(r) {
    r.reloadSync(file);
    assert.strictEqual(r.lookup('1.128.0.0').isp, 'Telstra Internet');
  });

  gc();

  mem = process.memoryUsage();

  console.log('Pass %s RSS: %s', j, mem.rss);

  // We've loaded ${num} copies of the file into mem, they should be there
  // 0.75 in case initial RSS was a bit high.
  assert(mem.rss - start.rss > num * fileSize * 0.75);

  // Dispose + gc + reload shouldn't increase the mem too much
  assert(mem.rss - start.rss < num * fileSize * 1.75);
}

console.log('Good!');
<|endoftext|>


<commit_before>PDRClient.controller('AssessmentsCtrl', ['$scope', '$location', 'SessionService', 'assessments',
    function($scope, $location, SessionService, assessments) {

      $scope.assessments = assessments;
      $scope.user        = SessionService.getCurrentUser();
      $scope.role        = null;

      $scope.$watch('user', function(){
        if(!$scope.user) return;

        $scope.role = $scope.user.role;
      });

      $scope.consensusReportIcon = function(assessment) {
        if (assessment.links['report']['active'] == true)
          return 'fa-check';

        return 'fa-spinner';
      }

      $scope.roundNumber = function(number) {
        return Math.floor(number);
      }

      $scope.meetingTime = function(date) {
        if(date != null)
          return moment(date).format("Do MMM YYYY");

        return "TBD"
      }

      $scope.backgroundColor = function(assessment) {
        if(assessment.status == "draft")
          return '#b1bbbf';
        else if(assessment.status == "assessment")
          return $scope.percentBackgroundColor(assessment.percent_completed);
        return "#4e5e66";
      }

      $scope.gotoLocation = function(location) {
        if(location)
          $location.url(location);
      };

      $scope.activeAssessmentLink = function(assessment) {
        if($scope.responseLink(assessment))
          return 'active';
        return '';
      };

      $scope.responseLink = function(assessment) {
        switch(assessment.assessment_link) {
          case 'new_response':
            return '/assessments/' + assessment.id + '/responses';
          case 'response':
            return '/assessments/' + assessment.id + '/responses/' + assessment.responses[0].id;
          case 'consensus':
            return '/assessments/' + assessment.id + '/consensus/' + assessment.response.consensus.id;
          case 'none':
            return false;
        }
      };

      $scope.responseLinkDisabled = function(assessment) {
        if(_.isEmpty(assessment.responses) && !assessment.is_participant)
          return true;
        return false;
      }

      $scope.percentBackgroundColor = function(percent) {
        switch(true) {
          case percent < 20:
            return '#f7bcb9';
          case percent  < 40:
            return '#f29b95';
          case percent < 60:
            return '#ee7972';
          case percent < 80:
            return '#046262';
          default:
            return '#884541';
        }
      }
    }
]);
<commit_msg>URL fixes<commit_after>PDRClient.controller('AssessmentsCtrl', ['$scope', '$location', 'SessionService', 'assessments',
    function($scope, $location, SessionService, assessments) {

      $scope.assessments = assessments;
      $scope.user        = SessionService.getCurrentUser();
      $scope.role        = null;

      $scope.$watch('user', function(){
        if(!$scope.user) return;

        $scope.role = $scope.user.role;
      });

      $scope.consensusReportIcon = function(assessment) {
        if (assessment.links['report']['active'] == true)
          return 'fa-check';

        return 'fa-spinner';
      }

      $scope.roundNumber = function(number) {
        return Math.floor(number);
      }

      $scope.meetingTime = function(date) {
        if(date != null)
          return moment(date).format("Do MMM YYYY");

        return "TBD"
      }

      $scope.backgroundColor = function(assessment) {
        if(assessment.status == "draft")
          return '#b1bbbf';
        else if(assessment.status == "assessment")
          return $scope.percentBackgroundColor(assessment.percent_completed);
        return "#4e5e66";
      }

      $scope.gotoLocation = function(location) {
        if(location)
          $location.url(location);
      };

      $scope.activeAssessmentLink = function(assessment) {
        if($scope.responseLink(assessment))
          return 'active';
        return '';
      };

      $scope.responseLink = function(assessment) {
        switch(assessment.assessment_link) {
          case 'new_response':
            return '/assessments/' + assessment.id + '/responses';
          case 'response':
            return '/assessments/' + assessment.id + '/responses/' + assessment.responses[0].id;
          case 'consensus':
            return '/assessments/' + assessment.id + '/consensus/' + assessment.consensus.id;
          case 'none':
            return false;
        }
      };

      $scope.responseLinkDisabled = function(assessment) {
        if(_.isEmpty(assessment.responses) && !assessment.is_participant)
          return true;
        return false;
      }

      $scope.percentBackgroundColor = function(percent) {
        switch(true) {
          case percent < 20:
            return '#f7bcb9';
          case percent  < 40:
            return '#f29b95';
          case percent < 60:
            return '#ee7972';
          case percent < 80:
            return '#046262';
          default:
            return '#884541';
        }
      }
    }
]);
<|endoftext|>


<commit_before>test("do while", function() {
    do {
        assert(true);
        return;
    } while(false);
    assert(false, "did not execute");
});

test("do while and continue", function() {
    var flag = false;
    do {
        if(flag) {
            assert(false, "loop executed again after continue in do..while(false)");
        }
        flag = true;
        continue;
    } while(false);
    assert(true);
});

test("with", function() {
    var b = 0;
    var x = { a: 1 };
    with(x) {
        assert_equal("number", typeof a);
        assert_equal(1, a);
        var y = 2;
        b = 3;
        a = 4;
    }
    assert_equal(4, x.a);
    assert_equal(2, y);
    assert_equal("undefined", typeof x.b);
    assert_equal(3, b);
});

test("default in switch", function() {
    switch(1) {
        case 1: assert(true); break;
        default: assert(false); break;
    }

    switch(2) {
        case 1: assert(false); break;
        default: assert(true); break;
    }

    switch(1) {
        default: assert(false); break;
        case 1: assert(true); break;
    }

    switch(2) {
        default: assert(true); break;
        case 1: assert(false); break;
    }
});

test("combo-assignment-arithmetic on member", function() {
    var x = { a: 1 };
    assert_equal(3, x.a += 2);
    assert_equal(3, x.a);
});

test("combo-assignment-arithmetic on index", function() {
    var x = { a: 1 };
    assert_equal(3, x["a"] += 2);
    assert_equal(3, x["a"]);
});

test("assignment non-lval throws", function() {
    try {
        eval("hi() = 123");
        assert(false, "didn't throw");
    } catch(e) {
        assert(e instanceof SyntaxError);
    }
});

test("combo-assignment-arithmetic on non-lval throws", function() {
    try {
        eval("hi() += 123");
        assert(false, "didn't throw");
    } catch(e) {
        assert(e instanceof SyntaxError);
    }
});

test("post-increment", function() {
    var i = 0;
    var a = [1];
    var o = { x: 2 };
    assert_equal(0, i++);
    assert_equal(1, a[0]++);
    assert_equal(2, o.x++);
    assert_equal(1, i);
    assert_equal(2, a[0]);
    assert_equal(3, o.x);
});

test("pre-increment", function() {
    var i = 0;
    var a = [1];
    var o = { x: 2 };
    assert_equal(1, ++i);
    assert_equal(2, ++a[0]);
    assert_equal(3, ++o.x);
    assert_equal(1, i);
    assert_equal(2, a[0]);
    assert_equal(3, o.x);
});

test("post/pre increment on non-lval throws", function() {
    try {
        eval("hi()++;");
        assert(false, "didn't throw");
    } catch(e) {
        assert(e instanceof SyntaxError);
    }
    try {
        eval("++hi();");
        assert(false, "didn't throw");
    } catch(e) {
        assert(e instanceof SyntaxError);
    }
});

test("calling", function() {
    var x = { a: function() { return this; } };
    assert_equal(x, x["a"]());
    assert_equal(x, x.a());
    assert_equal(123, Number(x.a.call(123)));
    function closure() {
        var fn = x.a;
        assert_equal(this, fn());
    }
    closure();
});

test("delete", function() {
    window.x = 123;
    var y = { a:1, b:2, c:3 };
    var z = [1,2,3,4];

    assert_equal("number", typeof x);
    delete x;
    assert_equal("undefined", typeof x);

    assert_equal("number", typeof y.b);
    delete y.b;
    assert_equal("undefined", typeof y.b);

    assert_equal("number", typeof y.c);
    with(y) delete c;
    assert_equal("undefined", typeof y.c);

    assert("1,2,3,4" == z);
    delete z[2];
    assert("1,2,,4" == z);

    var fncalled = false;
    function fn() { fncalled = true; }
    assert_equal(true, delete fn());
    assert_equal("function", typeof fn);
    assert_equal("undefined", typeof fn());
    assert_equal(true, fncalled);

    function Fn() { }
    Fn.prototype.hi = 123;
    assert_equal(true, delete Fn.prototype);
    assert_equal(123, Fn.prototype.hi);
});

test("break label", function() {
    br: while(true) {
        while(true) {
            break br;
            assert(false, "did not break");
        }
        assert(false, "did not escape second loop");
    }
    assert(true);
});

test("can't continue to non existant label", function() {
    try {
        eval('while(false) continue foo;');
    } catch(e) {
        assert(e instanceof SyntaxError);
        assert(/foo/.test(e.toString()));
    }
});

test("labelled continue while", function() {
    var x = false;
    a:while(true) {
        if(x) {
            assert(true);
            return;
        }
        while(true) {
            x = true;
            continue a;
            assert(false, "did not continue");
        }
    }
});

test("labelled continue do-while", function() {
    a:do {
        do {
            continue a;
            assert(false);
        } while(false);
        assert(false);
    } while(false);
});

test("labelled continue for-loop", function() {
    var x = false;
    function init() {
        if(x) {
            assert(false, "reran initializer");
        }
        x = true;
    }
    var i = 0;
    a: for(init(); i < 10; i++) {
        assert(true);
        do {
            continue a;
            assert(false);
        } while(false);
        assert(false);
    }
    assert(true);
});

test("labelled continue for-in", function() {
    var a = 0, c = [1, 2, 3, 4, 5];
    l: for(var x in c) {
        if(c.hasOwnProperty(x)) {
            do {
                a += c[x];
                continue l;
                assert(false);
            } while(false);
            assert(false);
        }
    }
    assert_equal(15, a);
});

test("floating point is used for large numbers but not for small numbers", function() {
    assert_equal(99999999999999999999999999999999999999, 99999999999999999999999999999999999999 + 1);
    assert(999999 !== 999999 + 1);
});<commit_msg>variable redeclaration<commit_after>test("do while", function() {
    do {
        assert(true);
        return;
    } while(false);
    assert(false, "did not execute");
});

test("do while and continue", function() {
    var flag = false;
    do {
        if(flag) {
            assert(false, "loop executed again after continue in do..while(false)");
        }
        flag = true;
        continue;
    } while(false);
    assert(true);
});

test("with", function() {
    var b = 0;
    var x = { a: 1 };
    with(x) {
        assert_equal("number", typeof a);
        assert_equal(1, a);
        var y = 2;
        b = 3;
        a = 4;
    }
    assert_equal(4, x.a);
    assert_equal(2, y);
    assert_equal("undefined", typeof x.b);
    assert_equal(3, b);
});

test("default in switch", function() {
    switch(1) {
        case 1: assert(true); break;
        default: assert(false); break;
    }

    switch(2) {
        case 1: assert(false); break;
        default: assert(true); break;
    }

    switch(1) {
        default: assert(false); break;
        case 1: assert(true); break;
    }

    switch(2) {
        default: assert(true); break;
        case 1: assert(false); break;
    }
});

test("combo-assignment-arithmetic on member", function() {
    var x = { a: 1 };
    assert_equal(3, x.a += 2);
    assert_equal(3, x.a);
});

test("combo-assignment-arithmetic on index", function() {
    var x = { a: 1 };
    assert_equal(3, x["a"] += 2);
    assert_equal(3, x["a"]);
});

test("assignment non-lval throws", function() {
    try {
        eval("hi() = 123");
        assert(false, "didn't throw");
    } catch(e) {
        assert(e instanceof SyntaxError);
    }
});

test("combo-assignment-arithmetic on non-lval throws", function() {
    try {
        eval("hi() += 123");
        assert(false, "didn't throw");
    } catch(e) {
        assert(e instanceof SyntaxError);
    }
});

test("post-increment", function() {
    var i = 0;
    var a = [1];
    var o = { x: 2 };
    assert_equal(0, i++);
    assert_equal(1, a[0]++);
    assert_equal(2, o.x++);
    assert_equal(1, i);
    assert_equal(2, a[0]);
    assert_equal(3, o.x);
});

test("pre-increment", function() {
    var i = 0;
    var a = [1];
    var o = { x: 2 };
    assert_equal(1, ++i);
    assert_equal(2, ++a[0]);
    assert_equal(3, ++o.x);
    assert_equal(1, i);
    assert_equal(2, a[0]);
    assert_equal(3, o.x);
});

test("post/pre increment on non-lval throws", function() {
    try {
        eval("hi()++;");
        assert(false, "didn't throw");
    } catch(e) {
        assert(e instanceof SyntaxError);
    }
    try {
        eval("++hi();");
        assert(false, "didn't throw");
    } catch(e) {
        assert(e instanceof SyntaxError);
    }
});

test("calling", function() {
    var x = { a: function() { return this; } };
    assert_equal(x, x["a"]());
    assert_equal(x, x.a());
    assert_equal(123, Number(x.a.call(123)));
    function closure() {
        var fn = x.a;
        assert_equal(this, fn());
    }
    closure();
});

test("delete", function() {
    window.x = 123;
    var y = { a:1, b:2, c:3 };
    var z = [1,2,3,4];

    assert_equal("number", typeof x);
    delete x;
    assert_equal("undefined", typeof x);

    assert_equal("number", typeof y.b);
    delete y.b;
    assert_equal("undefined", typeof y.b);

    assert_equal("number", typeof y.c);
    with(y) delete c;
    assert_equal("undefined", typeof y.c);

    assert("1,2,3,4" == z);
    delete z[2];
    assert("1,2,,4" == z);

    var fncalled = false;
    function fn() { fncalled = true; }
    assert_equal(true, delete fn());
    assert_equal("function", typeof fn);
    assert_equal("undefined", typeof fn());
    assert_equal(true, fncalled);

    function Fn() { }
    Fn.prototype.hi = 123;
    assert_equal(true, delete Fn.prototype);
    assert_equal(123, Fn.prototype.hi);
});

test("break label", function() {
    br: while(true) {
        while(true) {
            break br;
            assert(false, "did not break");
        }
        assert(false, "did not escape second loop");
    }
    assert(true);
});

test("can't continue to non existant label", function() {
    try {
        eval('while(false) continue foo;');
    } catch(e) {
        assert(e instanceof SyntaxError);
        assert(/foo/.test(e.toString()));
    }
});

test("labelled continue while", function() {
    var x = false;
    a:while(true) {
        if(x) {
            assert(true);
            return;
        }
        while(true) {
            x = true;
            continue a;
            assert(false, "did not continue");
        }
    }
});

test("labelled continue do-while", function() {
    a:do {
        do {
            continue a;
            assert(false);
        } while(false);
        assert(false);
    } while(false);
});

test("labelled continue for-loop", function() {
    var x = false;
    function init() {
        if(x) {
            assert(false, "reran initializer");
        }
        x = true;
    }
    var i = 0;
    a: for(init(); i < 10; i++) {
        assert(true);
        do {
            continue a;
            assert(false);
        } while(false);
        assert(false);
    }
    assert(true);
});

test("labelled continue for-in", function() {
    var a = 0, c = [1, 2, 3, 4, 5];
    l: for(var x in c) {
        if(c.hasOwnProperty(x)) {
            do {
                a += c[x];
                continue l;
                assert(false);
            } while(false);
            assert(false);
        }
    }
    assert_equal(15, a);
});

test("floating point is used for large numbers but not for small numbers", function() {
    assert_equal(99999999999999999999999999999999999999, 99999999999999999999999999999999999999 + 1);
    assert(999999 !== 999999 + 1);
});

test("redeclaring a variable", function() {
    assert_equal(123, (function(a) {
       var a;
       return a;
    })(123));
});<|endoftext|>


<commit_before>import React from 'react';
import Tree from 'react-ui-tree';
import {Button, ButtonGroup, FormControl, Modal} from 'react-bootstrap';
import ManagingModalSharing from '../managing_actions/ManagingModalSharing';
import CollectionStore from '../stores/CollectionStore';
import CollectionActions from '../actions/CollectionActions';
import UserInfoIcon from '../UserInfoIcon';
import PermissionIcons from '../PermissionIcons'

export default class MyCollections extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      active: {id: null},
      deleted_ids: [],

      tree: {
        label: 'My Collections',
        id: -1,
        children: [{}]
      },
      modalProps: {
        show: false,
        title: "",
        component: "",
        action: null,
        collection: {},
        selectUsers: true,
      }
    }

    this.onStoreChange = this.onStoreChange.bind(this);
  }

  componentDidMount() {
    CollectionStore.listen(this.onStoreChange)
    CollectionActions.fetchUnsharedCollectionRoots()
  }

  componentWillUnmount() {
    CollectionStore.unlisten(this.onStoreChange)
  }

  onStoreChange(state) {
    let children = state.unsharedRoots.length > 0 ? state.unsharedRoots : [{}];

    this.setState({
      tree: {
        label: 'My Collections',
        children: children
      }
    });
  }

  handleChange(tree) {
    this.setState({
      tree: tree
    });
  }

  isActive(node) {
    return node === this.state.active ? "node is-active" : "node";
  }

  hasChildren(node) {
    return node.children && node.children.length > 0
  }

  label(node) {
    if(node.label == "My Collections") {
      return (

          My Collections

      )
    } else {
      return (
        <FormControl className="collection-label" type="text"
          value={node.label || ''}
          onChange={(e)=>{this.handleLabelChange(e,node)}}
        />
      )
    }
  }

  handleLabelChange(e,node) {
    node.label = e.target.value;
    this.setState({
      tree: this.state.tree
    });
  }

  // TODO: confirmation before start the updating process?
  bulkUpdate() {
    // filter empty objects
    let collections = this.state.tree.children.filter((child) => {
      return child.label
    });

    let params = {
      collections: collections,
      deleted_ids: this.state.deleted_ids
    }

    CollectionActions.bulkUpdateUnsharedCollections(params);
  }

  actions(node) {
    if(node.label == "My Collections") {
      return (

          <Button bsSize="xsmall" bsStyle="warning"
            onClick={this.bulkUpdate.bind(this)}>
            Update
          </Button>
          {this.addButton(node)}

      )
    } else {
      return (
        <ButtonGroup className="actions">
          <Button bsSize="xsmall" bsStyle="primary"
            onClick={()=>this.doSync(node,'CreateSync')}>

          </Button>
          {this.addButton(node)}
          <Button bsSize="xsmall" bsStyle="danger" onClick={this.deleteCollection.bind(this, node)}>

          </Button>
        </ButtonGroup>
      )
    }
  }

  renderSync(node) {
    let syncOut = node.sync_collections_users;
    let users = [];

    if (syncOut) {
      users = syncOut.map((collection,ind)=>{
        return(

              <UserInfoIcon type={collection.user.type}/> {collection.user.name}
                <PermissionIcons pl={collection.permission_level}/>

            <ButtonGroup className="actions">
              <Button bsSize="xsmall" bsStyle="primary"
                onClick={()=>this.doSync(collection,'EditSync')}>
                   edit
              </Button>
              <Button bsSize="xsmall" bsStyle="danger"
                onClick={()=>CollectionActions.deleteSync({id: collection.id})}
              >

              </Button>
            </ButtonGroup>

        )
      })
    }
    return(

{users.map(u=>u)}

    )
  }

  doSync(node,action){
    let {modalProps,active} = this.state
    modalProps.title = action == "CreateSync"
      ? "Synchronize '"+node.label+"'"
      : "Edit Synchronization"
    modalProps.show = true
    modalProps.action = action
    modalProps.collection = node
    modalProps.selectUsers =  action == "CreateSync"
      ? true
      : false
    active = node
    this.setState({modalProps,active})
  }

  addButton(node) {
    return (
      <Button bsSize="xsmall" bsStyle="success" onClick={this.addSubcollection.bind(this, node)}>

      </Button>
    )
  }

  addSubcollection(node) {
    if(node.children) {
      node.children.push({
        id: Math.random(),
        label: 'New Collection',
        isNew: true
      });
    } else {
      node.children = [{
        id: Math.random(),
        label: 'New Collection',
        isNew: true
      }];
    }
  }

  deleteCollection(node) {
    let children = node.children || [];
    let parent = this.findParentById(this.state.tree, node.id);

    this.removeNodeById(parent, node.id)
    this.appendChildrenToParent(parent, children)

    if(!node.isNew) {
      let deleted_ids = this.state.deleted_ids.concat([node.id])

      this.setState({
        deleted_ids: deleted_ids
      })
    }
  }

  appendChildrenToParent(parent, children) {
    if(children.length > 0) {
      children.forEach((child) => {
        parent.children.push(child);
      });
    } else if (parent.label == 'My Collections') {
      parent.children.push({});
    }
  }

  findParentById(root, id) {
    if(!root.children) {
      root.children = [];
      return null;
    }

    let children = root.children;

    for(let i = 0; i < children.length; i++) {
      if(children[i].id == id) {
        return root;
      } else {
        let parent = this.findParentById(children[i], id);
        if(parent) {
          return parent
        }
      }
    }
  }

  removeNodeById(parent, id) {
    parent.children = parent.children.filter((child) => {
      return child.id != id
    });
  }

  onClickNode(node) {
    if (node.is_locked) {
      this.setState({
        active: {id: null}
      });
    } else {
      this.setState({
        active: node
      });
    }
  }

  handleModalHide() {
    this.setState({
      modalProps: {
        show: false,
        title: "",
        component: "",
        action: null,
        collection: {},
        selectUsers: true,
      }
    });
  }

  renderNode(node) {
    if(!Object.keys(node).length == 0) {
      return (

            {this.label(node)}
            {this.actions(node)}

        {this.renderSync(node)}

      );
    }
  }
  render() {
    let mPs = this.state.modalProps
    let mPsC = mPs.collection
    return (

        <Tree
          paddingLeft={20}                         // left padding for children nodes in pixels
          tree={this.state.tree}                   // tree object
          isNodeCollapsed={this.isNodeCollapsed}
          onChange={this.handleChange.bind(this)}  // onChange(tree) tree object changed
          renderNode={this.renderNode.bind(this)}  // renderNode(node) return react element
        />
        <Modal animation show={mPs.show} onHide={this.handleModalHide.bind(this)}>
          <Modal.Header closeButton>
            <Modal.Title>{mPs.title}</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <ManagingModalSharing collectionId={mPsC.id}
              onHide={this.handleModalHide.bind(this)}
              permissionLevel={mPsC.permission_level}
              sampleDetailLevel={mPsC.sample_detail_level} reactionDetailLevel={mPsC.reaction_detail_level}
              wellplateDetailLevel={mPsC.wellplate_detail_level} screenDetailLevel={mPsC.screen_detail_level}
              selectUsers={mPs.selectUsers}
              collAction={mPs.action}/>
            </Modal.Body>
        </Modal>

    )
  }
}
<commit_msg>fix node rendering for root node rendering to no depend on node (collection)'s  label<commit_after>import React from 'react';
import Tree from 'react-ui-tree';
import {Button, ButtonGroup, FormControl, Modal} from 'react-bootstrap';
import ManagingModalSharing from '../managing_actions/ManagingModalSharing';
import CollectionStore from '../stores/CollectionStore';
import CollectionActions from '../actions/CollectionActions';
import UserInfoIcon from '../UserInfoIcon';
import PermissionIcons from '../PermissionIcons'

export default class MyCollections extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      active: {id: null},
      deleted_ids: [],

      tree: {
        label: 'My Collections',
        id: -1,
        children: [{}]
      },
      modalProps: {
        show: false,
        title: "",
        component: "",
        action: null,
        collection: {},
        selectUsers: true,
      }
    }

    this.onStoreChange = this.onStoreChange.bind(this);
  }

  componentDidMount() {
    CollectionStore.listen(this.onStoreChange)
    CollectionActions.fetchUnsharedCollectionRoots()
  }

  componentWillUnmount() {
    CollectionStore.unlisten(this.onStoreChange)
  }

  onStoreChange(state) {
    let children = state.unsharedRoots.length > 0 ? state.unsharedRoots : [{}];

    this.setState({
      tree: {
        label: 'My Collections',
        id: -1,
        children: children
      }
    });
  }

  handleChange(tree) {
    this.setState({
      tree: tree
    });
  }

  isActive(node) {
    return node === this.state.active ? "node is-active" : "node";
  }

  hasChildren(node) {
    return node.children && node.children.length > 0
  }

  label(node) {
    if(node.id == -1) {
      return (

          My Collections

      )
    } else {
      return (
        <FormControl className="collection-label" type="text"
          value={node.label || ''}
          onChange={(e)=>{this.handleLabelChange(e,node)}}
        />
      )
    }
  }

  handleLabelChange(e,node) {
    node.label = e.target.value;
    this.setState({
      tree: this.state.tree
    });
  }

  // TODO: confirmation before start the updating process?
  bulkUpdate() {
    // filter empty objects
    let collections = this.state.tree.children.filter((child) => {
      return child.label
    });

    let params = {
      collections: collections,
      deleted_ids: this.state.deleted_ids
    }

    CollectionActions.bulkUpdateUnsharedCollections(params);
  }

  actions(node) {
    if(node.id == -1) {
      return (

          <Button bsSize="xsmall" bsStyle="warning"
            onClick={this.bulkUpdate.bind(this)}>
            Update
          </Button>
          {this.addButton(node)}

      )
    } else {
      return (
        <ButtonGroup className="actions">
          <Button bsSize="xsmall" bsStyle="primary"
            onClick={()=>this.doSync(node,'CreateSync')}>

          </Button>
          {this.addButton(node)}
          <Button bsSize="xsmall" bsStyle="danger" onClick={this.deleteCollection.bind(this, node)}>

          </Button>
        </ButtonGroup>
      )
    }
  }

  renderSync(node) {
    let syncOut = node.sync_collections_users;
    let users = [];

    if (syncOut) {
      users = syncOut.map((collection,ind)=>{
        return(

              <UserInfoIcon type={collection.user.type}/> {collection.user.name}
                <PermissionIcons pl={collection.permission_level}/>

            <ButtonGroup className="actions">
              <Button bsSize="xsmall" bsStyle="primary"
                onClick={()=>this.doSync(collection,'EditSync')}>
                   edit
              </Button>
              <Button bsSize="xsmall" bsStyle="danger"
                onClick={()=>CollectionActions.deleteSync({id: collection.id})}
              >

              </Button>
            </ButtonGroup>

        )
      })
    }
    return(

{users.map(u=>u)}

    )
  }

  doSync(node,action){
    let {modalProps,active} = this.state
    modalProps.title = action == "CreateSync"
      ? "Synchronize '"+node.label+"'"
      : "Edit Synchronization"
    modalProps.show = true
    modalProps.action = action
    modalProps.collection = node
    modalProps.selectUsers =  action == "CreateSync"
      ? true
      : false
    active = node
    this.setState({modalProps,active})
  }

  addButton(node) {
    return (
      <Button bsSize="xsmall" bsStyle="success" onClick={this.addSubcollection.bind(this, node)}>

      </Button>
    )
  }

  addSubcollection(node) {
    if(node.children) {
      node.children.push({
        id: Math.random(),
        label: 'New Collection',
        isNew: true
      });
    } else {
      node.children = [{
        id: Math.random(),
        label: 'New Collection',
        isNew: true
      }];
    }
  }

  deleteCollection(node) {
    let children = node.children || [];
    let parent = this.findParentById(this.state.tree, node.id);

    this.removeNodeById(parent, node.id)
    this.appendChildrenToParent(parent, children)

    if(!node.isNew) {
      let deleted_ids = this.state.deleted_ids.concat([node.id])

      this.setState({
        deleted_ids: deleted_ids
      })
    }
  }

  appendChildrenToParent(parent, children) {
    if(children.length > 0) {
      children.forEach((child) => {
        parent.children.push(child);
      });
    } else if (parent.label == 'My Collections') {
      parent.children.push({});
    }
  }

  findParentById(root, id) {
    if(!root.children) {
      root.children = [];
      return null;
    }

    let children = root.children;

    for(let i = 0; i < children.length; i++) {
      if(children[i].id == id) {
        return root;
      } else {
        let parent = this.findParentById(children[i], id);
        if(parent) {
          return parent
        }
      }
    }
  }

  removeNodeById(parent, id) {
    parent.children = parent.children.filter((child) => {
      return child.id != id
    });
  }

  onClickNode(node) {
    if (node.is_locked) {
      this.setState({
        active: {id: null}
      });
    } else {
      this.setState({
        active: node
      });
    }
  }

  handleModalHide() {
    this.setState({
      modalProps: {
        show: false,
        title: "",
        component: "",
        action: null,
        collection: {},
        selectUsers: true,
      }
    });
  }

  renderNode(node) {
    if(!Object.keys(node).length == 0) {
      return (

            {this.label(node)}
            {this.actions(node)}

        {this.renderSync(node)}

      );
    }
  }
  render() {
    let mPs = this.state.modalProps
    let mPsC = mPs.collection
    return (

        <Tree
          paddingLeft={20}                         // left padding for children nodes in pixels
          tree={this.state.tree}                   // tree object
          isNodeCollapsed={this.isNodeCollapsed}
          onChange={this.handleChange.bind(this)}  // onChange(tree) tree object changed
          renderNode={this.renderNode.bind(this)}  // renderNode(node) return react element
        />
        <Modal animation show={mPs.show} onHide={this.handleModalHide.bind(this)}>
          <Modal.Header closeButton>
            <Modal.Title>{mPs.title}</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <ManagingModalSharing collectionId={mPsC.id}
              onHide={this.handleModalHide.bind(this)}
              permissionLevel={mPsC.permission_level}
              sampleDetailLevel={mPsC.sample_detail_level} reactionDetailLevel={mPsC.reaction_detail_level}
              wellplateDetailLevel={mPsC.wellplate_detail_level} screenDetailLevel={mPsC.screen_detail_level}
              selectUsers={mPs.selectUsers}
              collAction={mPs.action}/>
            </Modal.Body>
        </Modal>

    )
  }
}
<|endoftext|>


<commit_before>Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

var admonitus = {};
admonitus.transFreqNoToName = function(num)
{
	switch (num)
	{
	case 0:
		return "One-time";
	case 1:
		return "Daily";
	case 2:
		return "Weekly";
	case 3:
		return "Monthly";
	default:
		return "Invalid";
	}
}

var mainObj = function() {
	console.log("It works!");
	$("input[name=startingat]").val((new Date()).toDateInputValue());

	$("#deleteModal").on('show.bs.modal',
		function(e)
		{
	    	$("button[name=deleteConfirm]").attr("data-id", $(e.relatedTarget).data('id'));
		}
	);

	$(document).on('click', "button[name=deleteConfirm]",
		function(e)
		{
			var id = $(this).attr("data-id");
			console.log("Delete id " + id);

			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/delete/" + id
			});

			$("#remindersList").find("tr[id=" + id + "]").remove();
		}
	);

	$("#reminderForm").submit(function(e) {
		e.preventDefault();

		var request = {
			"frequency": $("input[name=frequency]:checked").val(),
			"text": $("input[name=text]").val(),
			"startingat": $("input[name=startingat]").val()
		}
		$.ajax({
			type : "POST",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/add",
			data : request
		});
	});

	$.ajax({
		type : "GET",
		dataType : "json",
		url : "/Admonitus/ctl/Reminder/get",
		success : function(data) {

			$.each(data, function(index, entry) {
				newrow = $("#template").clone();
				newrow.find("td.number").text(index + 1);
				newrow.find("td.text").text(entry['text']);
				newrow.find("button[name=deleteButton]").attr('data-id', entry['id']);
				newrow.attr("id", entry['id']);
				newrow.find("td.startingat").text(new Date(entry['datestart']).format('d-M-Y'))
				newrow.find("td.frequency").text(
					admonitus.transFreqNoToName(entry['frequency'])
				);

				newrow.show();
				$("#remindersList").append(newrow);
			});

		}

	});
}

$("document").ready(mainObj);
<commit_msg>Implement login action<commit_after>Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

var admonitus = {};
admonitus.transFreqNoToName = function(num)
{
	switch (num)
	{
	case 0:
		return "One-time";
	case 1:
		return "Daily";
	case 2:
		return "Weekly";
	case 3:
		return "Monthly";
	default:
		return "Invalid";
	}
}

var mainObj = function() {
	console.log("It works!");
	$("input[name=startingat]").val((new Date()).toDateInputValue());

	$(document).on("click", "#loginButton",
		function(e)
		{
			e.preventDefault();
			var request = {
				"email": $("input[id=loginEmail]").val(),
				"password": $("input[id=loginPassword]").val()
			}
			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/User/login",
				data: request
			});
		}
	);

	$("#deleteModal").on('show.bs.modal',
		function(e)
		{
	    	$("button[name=deleteConfirm]").attr("data-id", $(e.relatedTarget).data('id'));
		}
	);

	$(document).on('click', "button[name=deleteConfirm]",
		function(e)
		{
			var id = $(this).attr("data-id");
			console.log("Delete id " + id);

			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/delete/" + id
			});

			$("#remindersList").find("tr[id=" + id + "]").remove();
		}
	);

	$("#reminderForm").submit(function(e) {
		e.preventDefault();

		var request = {
			"frequency": $("input[name=frequency]:checked").val(),
			"text": $("input[name=text]").val(),
			"startingat": $("input[name=startingat]").val()
		}
		$.ajax({
			type : "POST",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/add",
			data : request
		});
	});

	$.ajax({
		type : "GET",
		dataType : "json",
		url : "/Admonitus/ctl/Reminder/get",
		success : function(data) {

			$.each(data, function(index, entry) {
				newrow = $("#template").clone();
				newrow.find("td.number").text(index + 1);
				newrow.find("td.text").text(entry['text']);
				newrow.find("button[name=deleteButton]").attr('data-id', entry['id']);
				newrow.attr("id", entry['id']);
				newrow.find("td.startingat").text(new Date(entry['datestart']).format('d-M-Y'))
				newrow.find("td.frequency").text(
					admonitus.transFreqNoToName(entry['frequency'])
				);

				newrow.show();
				$("#remindersList").append(newrow);
			});

		}

	});
}

$("document").ready(mainObj);
<|endoftext|>


<commit_before>'use strict';
(function(){
    var Handler = require('./handler.js');
    var azure = require('azure-storage');
    var keyConverter = require('../utils/keyConverter.js');
    var Promise = require('promise');
    let connectionString = process.env.AzureWebJobsDashboard;
    let entGen = azure.TableUtilities.entityGenerator;
    var readTableCreated = false;

    module.exports = function(context, event) {
        var eventFetcher = (id, knownVersion, newVersion) => {
            let tableService = azure.createTableService(connectionString);
            context.log(`Executing event fetcher Id ${id} Known Version ${knownVersion} new version ${newVersion}`);

            var q = `PartitionKey eq '${String(id)}' and RowKey gt '${keyConverter.toVersionKey(knownVersion)}' and RowKey le '${keyConverter.toVersionKey(newVersion)}'`;
            context.log(`Query: ${q}`);
            var query = new azure.TableQuery()
                .where(q);

            var result = new Promise((fulfill, reject) => {
                tableService.queryEntities('SeasonEvents', query, null, function(err, result){
                    if (err){reject(err);}
                    fulfill(result.entries);
                });
            });

            return result;
        };

        var writer = (round, playerId, stat) => {
            var tableService = azure.createTableService(connectionString);
            context.log(`Asked to write ${round} ${playerId} ${JSON.stringify(stat)}`);
            var result = (new Promise((fulfill, reject)=>{
                if (readTableCreated){
                    fulfill();
                    return;
                }

                tableService.createTableIfNotExists('StatsReadModels', function(error, result, response) {
                    if (error) {reject(error);}
                    context.log(`Ensured StatsReadModels table, result ${JSON.stringify(result)}`);
                    readTableCreated = true;
                    fulfill();
                });
            })).then(() => {return new Promise((fulfill, reject) => {
                var entity = {
                    PartitionKey: entGen.String(String(playerId)),
                    RowKey: entGen.String(String(round)),
                    Stat: JSON.stringify(stat)
                };

                tableService.insertEntity('StatsReadModels', entity, function(error, result, response) {
                    if (error) {
                        reject(error);
                    }
                    context.log(`New stat written ${playerId} ${round} ${stat}`);
                    fulfill();
                });
            })});

            return result;
        };

        var versionWriter = (year, version) => {
            let tableService = azure.createTableService(connectionString);
            var result = (new Promise((fulfill, reject)=>{
                tableService.createTableIfNotExists('StatsReadVersion', function(error, result, response) {
                    if (error) {reject(error);}
                    context.log(`Ensured StatsReadVersion table, result ${JSON.stringify(result)}`);
                    fulfill();
                });
            })).then(() => {return new Promise((fulfill, reject) => {
                var versionRow = {
                    PartitionKey: entGen.String(String(year)),
                    RowKey: entGen.String(String(version))
                };

                tableService.insertEntity('StatsReadVersion', versionRow, function(error, result, response) {
                    if (error) {
                        reject(error);
                    }
                    context.log(`New version written ${year} ${version}`);
                    fulfill();
                });
            })});

            return result;
        };

        var handler = new Handler(context.log,
            eventFetcher,
            writer,
            versionWriter);

        handler.process(0, event);
    }
})();<commit_msg>stringify<commit_after>'use strict';
(function(){
    var Handler = require('./handler.js');
    var azure = require('azure-storage');
    var keyConverter = require('../utils/keyConverter.js');
    var Promise = require('promise');
    let connectionString = process.env.AzureWebJobsDashboard;
    let entGen = azure.TableUtilities.entityGenerator;
    var readTableCreated = false;

    module.exports = function(context, event) {
        var eventFetcher = (id, knownVersion, newVersion) => {
            let tableService = azure.createTableService(connectionString);
            context.log(`Executing event fetcher Id ${id} Known Version ${knownVersion} new version ${newVersion}`);

            var q = `PartitionKey eq '${String(id)}' and RowKey gt '${keyConverter.toVersionKey(knownVersion)}' and RowKey le '${keyConverter.toVersionKey(newVersion)}'`;
            context.log(`Query: ${q}`);
            var query = new azure.TableQuery()
                .where(q);

            var result = new Promise((fulfill, reject) => {
                tableService.queryEntities('SeasonEvents', query, null, function(err, result){
                    if (err){reject(err);}
                    fulfill(result.entries);
                });
            });

            return result;
        };

        var writer = (round, playerId, stat) => {
            var tableService = azure.createTableService(connectionString);
            context.log(`Asked to write ${round} ${playerId} ${JSON.stringify(stat)}`);
            var result = (new Promise((fulfill, reject)=>{
                if (readTableCreated){
                    fulfill();
                    return;
                }

                tableService.createTableIfNotExists('StatsReadModels', function(error, result, response) {
                    if (error) {reject(error);}
                    context.log(`Ensured StatsReadModels table, result ${JSON.stringify(result)}`);
                    readTableCreated = true;
                    fulfill();
                });
            })).then(() => {return new Promise((fulfill, reject) => {
                var entity = {
                    PartitionKey: entGen.String(String(playerId)),
                    RowKey: entGen.String(String(round)),
                    Stat: JSON.stringify(stat)
                };

                tableService.insertEntity('StatsReadModels', entity, function(error, result, response) {
                    if (error) {
                        reject(error);
                    }
                    context.log(`New stat written ${playerId} ${round} ${JSON.stringify(stat)}`);
                    fulfill();
                });
            })});

            return result;
        };

        var versionWriter = (year, version) => {
            let tableService = azure.createTableService(connectionString);
            var result = (new Promise((fulfill, reject)=>{
                tableService.createTableIfNotExists('StatsReadVersion', function(error, result, response) {
                    if (error) {reject(error);}
                    context.log(`Ensured StatsReadVersion table, result ${JSON.stringify(result)}`);
                    fulfill();
                });
            })).then(() => {return new Promise((fulfill, reject) => {
                var versionRow = {
                    PartitionKey: entGen.String(String(year)),
                    RowKey: entGen.String(String(version))
                };

                tableService.insertEntity('StatsReadVersion', versionRow, function(error, result, response) {
                    if (error) {
                        reject(error);
                    }
                    context.log(`New version written ${year} ${version}`);
                    fulfill();
                });
            })});

            return result;
        };

        var handler = new Handler(context.log,
            eventFetcher,
            writer,
            versionWriter);

        handler.process(0, event);
    }
})();<|endoftext|>


<commit_before>// Given a collection of distinct numbers, return all possible permutations.

// For example,
// [1,2,3] have the following permutations:
// [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

var permute = function(nums) {
    var numsLen = nums.length,
        result = [];

    function getPermutations (currentArray, candidateArray) {
        var candidateArrayLen = candidateArray.length, index;
        if (candidateArrayLen < 1) {
            result.push(currentArray.slice());
        }
        else {
            for (index = 0; index < candidateArrayLen; index++) {
                var nextCandidate = candidateArray.slice();
                currentArray.push(candidateArray[index]);
                nextCandidate.splice(index, 1);
                getPermutations (currentArray, nextCandidate);
                currentArray.pop();
            }
        }
    }
    getPermutations([], nums);
    return result;
};
<commit_msg>add logic to algo<commit_after>// Given a collection of distinct numbers, return all possible permutations.

// For example,
// [1,2,3] have the following permutations:
// [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

// Logic
// create a result array to push our permutations in and return
// create a get getPermutations function that takes in an array, and our input
  // create a base case, if input array is empty push copy of current array into result
  // if input array is not empty, loop through input array
  // else
    // create a copy of our input array for our next input
    // push the item of the inputArr that the for loop is on, into the currentArr
    // splice the index of the nextInput array
    // run the getPermutations function on the current array and nextInput array
    // pop last array in current array

  // run get permutations function on an empty arr and nums or our input
  // return result

var permute = function(nums) {
    //nums are distinct numbers.
    var result = [];

    function getPermutations (currentArray, inputArr) {
        if (inputArr.length < 1) {
            result.push(currentArray.slice()); //Here we must do a copy. Because an array is an object,
                                               // every time we're passing its reference into a new function.
        } else {
            for (var i = 0; i < inputArr.length; i++) {
                var nextInput = inputArr.slice(); //Same reason, array is object, copy is needed.
                currentArray.push(inputArr[i]);
                nextInput.splice(i, 1);
                getPermutations (currentArray, nextInput);
                currentArray.pop();
            }
        }
    }

    getPermutations([], nums);
    return result;
};
<|endoftext|>


<commit_before>'use strict';

var createMockServer = require('../lib/test-server/index.js');
var configuration = require('../config/configuration.js');

describe('<Mock server>', function() {

  before(function(done) {
    var server = createMockServer();
    var port = configuration.test.port;
    server.listen(port, function() {
      console.log('Mock server running on port ' + port);
      done();
    });
  });

  it('should handle batch calls smartly', function(done) {
    // TODO
    done();
  });

});<commit_msg>Test for mock `GET /batch`<commit_after>'use strict';

var should = require('should');

var Anyfetch = require('../lib/index.js');
var createMockServer = require('../lib/test-server/index.js');
var configuration = require('../config/configuration.js');

describe('<Mock server>', function() {
  var anyfetch = new Anyfetch(configuration.test.login, configuration.test.password);

  before(function(done) {
    var server = createMockServer();
    var port = configuration.test.port;
    server.listen(port, function() {
      var apiHost = 'http://localhost:' + port;
      console.log('Mock server running on ' + apiHost);
      anyfetch.setApiHost(apiHost);

      done();
    });
  });

  it('should respond with all the mocks we asked for', function(done) {
    var pages = ['/document_types', '/providers', '/users', '/company'];
    anyfetch.getBatch({ pages: pages }, function(err, res) {
      should(err).not.be.ok;
      should(res.body).be.ok;
      res.body.should.have.keys(pages);
      done();
    });
  });
});<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var terst = require('terst')
var testutil = require('testutil')
var fse = require('../')

var TEST_DIR = ''

describe('output', function () {
  beforeEach(function() {
    TEST_DIR = testutil.createTestDir('fs-extra')
  })

  afterEach(function(done) {
    fse.remove(TEST_DIR, done)
  })

  describe('+ outputFile', function() {
    describe('> when the file and directory does not exist', function() {
      it('should create the file', function(done) {
        var file = path.join(TEST_DIR, Math.random() + 't-ne', Math.random() + '.txt')
        F (fs.existsSync(file))
        fse.outputFile(file, 'hi jp', function(err) {
          F (err)
          T (fs.existsSync(file))
          EQ (fs.readFileSync(file, 'utf8'), 'hi jp')
          done()
        })
      })
    })

    describe('> when the file does exist', function() {
      it('should still modify the file', function(done) {
        var file = path.join(TEST_DIR, Math.random() + 't-e', Math.random() + '.txt')
        fse.mkdirsSync(path.dirname(file))
        fs.writeFileSync(file, 'hello world')
        fse.outputFile(file, 'hello jp', function(err) {
          if (err) return done(err)
          EQ (fs.readFileSync(file, 'utf8'), 'hello jp')
          done()
        })
      })
    })
  })

  describe('+ outputFileSync', function() {
    describe('> when the file and directory does not exist', function() {
      it('should create the file', function() {
        var file = path.join(TEST_DIR, Math.random() + 'ts-ne', Math.random() + '.txt')
        F (fs.existsSync(file))
        fse.outputFileSync(file, 'hello man')
        T (fs.existsSync(file))
        EQ (fs.readFileSync(file, 'utf8'), 'hello man')
      })
    })

    describe('> when the file does exist', function() {
      it('should still modify the file', function() {
        var file = path.join(TEST_DIR, Math.random() + 'ts-e', Math.random() + '.txt')
        fse.mkdirsSync(path.dirname(file))
        fs.writeFileSync(file, 'hello world')
        fse.outputFileSync(file, 'hello man')
        EQ (fs.readFileSync(file, 'utf8'), 'hello man')
      })
    })
  })
})
<commit_msg>test/output.test: dropped terst for assert<commit_after>var assert = require('assert')
var fs = require('fs')
var path = require('path')
var testutil = require('testutil')
var fse = require('../')

var TEST_DIR = ''

describe('output', function () {
  beforeEach(function() {
    TEST_DIR = testutil.createTestDir('fs-extra')
  })

  afterEach(function(done) {
    fse.remove(TEST_DIR, done)
  })

  describe('+ outputFile', function() {
    describe('> when the file and directory does not exist', function() {
      it('should create the file', function(done) {
        var file = path.join(TEST_DIR, Math.random() + 't-ne', Math.random() + '.txt')
        assert(!fs.existsSync(file))
        fse.outputFile(file, 'hi jp', function(err) {
          assert.ifError(err)
          assert(fs.existsSync(file))
          assert.equal(fs.readFileSync(file, 'utf8'), 'hi jp')
          done()
        })
      })
    })

    describe('> when the file does exist', function() {
      it('should still modify the file', function(done) {
        var file = path.join(TEST_DIR, Math.random() + 't-e', Math.random() + '.txt')
        fse.mkdirsSync(path.dirname(file))
        fs.writeFileSync(file, 'hello world')
        fse.outputFile(file, 'hello jp', function(err) {
          if (err) return done(err)
          assert.equal(fs.readFileSync(file, 'utf8'), 'hello jp')
          done()
        })
      })
    })
  })

  describe('+ outputFileSync', function() {
    describe('> when the file and directory does not exist', function() {
      it('should create the file', function() {
        var file = path.join(TEST_DIR, Math.random() + 'ts-ne', Math.random() + '.txt')
        assert(!fs.existsSync(file))
        fse.outputFileSync(file, 'hello man')
        assert(fs.existsSync(file))
        assert.equal(fs.readFileSync(file, 'utf8'), 'hello man')
      })
    })

    describe('> when the file does exist', function() {
      it('should still modify the file', function() {
        var file = path.join(TEST_DIR, Math.random() + 'ts-e', Math.random() + '.txt')
        fse.mkdirsSync(path.dirname(file))
        fs.writeFileSync(file, 'hello world')
        fse.outputFileSync(file, 'hello man')
        assert.equal(fs.readFileSync(file, 'utf8'), 'hello man')
      })
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

const alpha = require('../')();

test(`sector performance data works`, () => {
  expect.assertions(11);
  return alpha.performance.sector().then(data => {
    expect(data['Meta Data']).toBeDefined();
    expect(data['Rank A: Real-Time Performance']).toBeDefined();
    expect(data['Rank B: 1 Day Performance']).toBeDefined();
    expect(data['Rank C: 5 Day Performance']).toBeDefined();
    expect(data['Rank D: 1 Month Performance']).toBeDefined();
    expect(data['Rank E: 3 Month Performance']).toBeDefined();
    expect(data['Rank F: Year-to-Date (YTD) Performance']).toBeDefined();
    expect(data['Rank G: 1 Year Performance']).toBeDefined();
    expect(data['Rank H: 3 Year Performance']).toBeDefined();
    expect(data['Rank I: 5 Year Performance']).toBeDefined();
    expect(data['Rank J: 10 Year Performance']).toBeDefined();
  });
});
<commit_msg>Adding additional timeout on test ci.<commit_after>'use strict';

jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
const alpha = require('../')();

test(`sector performance data works`, () => {
  expect.assertions(11);
  return alpha.performance.sector().then(data => {
    expect(data['Meta Data']).toBeDefined();
    expect(data['Rank A: Real-Time Performance']).toBeDefined();
    expect(data['Rank B: 1 Day Performance']).toBeDefined();
    expect(data['Rank C: 5 Day Performance']).toBeDefined();
    expect(data['Rank D: 1 Month Performance']).toBeDefined();
    expect(data['Rank E: 3 Month Performance']).toBeDefined();
    expect(data['Rank F: Year-to-Date (YTD) Performance']).toBeDefined();
    expect(data['Rank G: 1 Year Performance']).toBeDefined();
    expect(data['Rank H: 3 Year Performance']).toBeDefined();
    expect(data['Rank I: 5 Year Performance']).toBeDefined();
    expect(data['Rank J: 10 Year Performance']).toBeDefined();
  });
});
<|endoftext|>


<commit_before>var tap = require("tap")
  , test = tap.test
  , plan = tap.plan
  , account
  , creature
  , resource;

//
// Testing metadata
//
var testDatasource = "memory";

test("load resource module", function (t) {
  resource = require('../');
  t.ok(resource, "object loaded")
  t.end()
});

test("define creature resource - with datasource config", function (t) {
  creature = resource.define('creature', { config: { datasource: testDatasource }});

  creature.property('life', {
    "type": "number"
  });

  creature.property('metadata', {
    "type": "object"
  });

  creature.property('items', {
    "type": "array"
  });

  t.type(creature.config, 'object', 'configuration defined - creature.config is object');
  t.equal(testDatasource, creature.config.datasource, ('configuration defined - creature.config.datasource == "' + testDatasource + '"'));

  t.type(creature.methods, 'object', 'methods defined - creature.methods is object');
  t.type(creature.methods.create, 'function', 'methods defined - methods.create is function');
  t.type(creature.methods.get, 'function', 'methods defined - methods.get is function');
  t.type(creature.methods.find, 'function', 'methods defined - methods.find is function');
  t.type(creature.methods.destroy, 'function', 'methods defined - methods.destroy is function');

  t.type(creature.create, 'function', 'methods hoisted - creature.create is function');
  t.type(creature.get, 'function', 'methods hoisted - creature.get is function');
  t.type(creature.find, 'function', 'methods hoisted - creature.find is function');
  t.type(creature.destroy, 'function', 'methods hoisted - creature.destroy is function');

  t.end()
});

test("define account resource - with datasource config", function (t) {
  account = resource.define('account', { config: { datasource: testDatasource }});

  account.property('name', {
    "type": "string"
  });

  account.property('email', {
    "type": "string"
  });

  t.type(account.config, 'object', 'configuration defined - account.config is object');
  t.equal(testDatasource, account.config.datasource, ('configuration defined - account.config.datasource == "' + testDatasource + '"'));

  t.end()
});

//
// A simple data object to use for testing resource properties of type "object"
//
var data = {
  "foo": "bar",
  "abc": 123,
  "data" : {
    "prop1" : "foo",
    "prop2" : "bar"
  }
},
items = [
  { "foo": "bar" },
  { "abc": 123 }
];

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 0, 'no creatures');
    t.end();
  });
});

test("executing creature.create", function (t) {
  creature.create({
    id: 'bobby',
    metadata: data,
    items: items // array property currently has serialization issue
  }, function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.equal(result.id, 'bobby', 'id is correct');
    t.type(result.metadata, 'object', 'metadata is object');
    t.equal(result.metadata.foo, 'bar');
    t.equal(result.metadata.abc, 123);
    t.equal(result.metadata.data.prop1, 'foo');
    t.equal(result.metadata.data.prop2, 'bar');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing creature.create - when already created", function (t) {
  creature.create({
    id: 'bobby',
    metadata: data,
    items: items // array property current has serialization issue
  }, function(err, result){
    t.type(err, 'object', 'an error');
    t.equal(!result, true, 'no result');
    t.equal(err.message, 'bobby already exists', 'bobby already exists');
    t.end();
  });
});

test("executing creature.get", function (t) {
  creature.get('bobby', function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.type(result.metadata, 'object', 'metadata is object');
    t.equal(result.metadata.foo, 'bar');
    t.equal(result.metadata.abc, 123);
    t.equal(result.metadata.data.prop1, 'foo');
    t.equal(result.metadata.data.prop2, 'bar');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result) {
    t.equal(result.length, 1, 'one creature');
    t.end();
  });
});

test("executing creature.create - with bad input", function (t) {
  creature.create({ id: 'larry', life: "abc" }, function(err, result){
    t.type(err, 'object', 'continues correct validation error - err is object');
    t.type(err.errors, 'object', 'continues correct validation error - err.errors is object');
    t.equal(err.errors.length, 1, 'continues correct validation error - one validation error');
    t.equal(err.errors[0].attribute, 'type', 'continues correct validation error - attribute == "type"');
    t.equal(err.errors[0].property, 'life', 'continues correct validation error - property == "life"');
    t.equal(err.errors[0].expected, 'number', 'continues correct validation error - expected == "number"');
    t.equal(err.errors[0].actual, 'string', 'continues correct validation error - actual == "string"');
    t.end();
  });
});

test("executing creature.get", function (t) {
  creature.get('larry', function(err, result){
    t.type(err, 'object', 'could not find larry');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 1);
    t.end();
  });
});

test("executing creature.update", function (t) {
  creature.update({ id: 'bobby', life: 9999 , items: items }, function(err, result){
    t.type(err, 'null', 'updated bobby - no error');
    t.type(result, 'object', 'updated bobby - result is object');
    t.equal(result.life, 9999, 'updated bobby - result.life == 9999');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing create.update - when creature does not exist", function (t) {
  creature.update({ id: 'larry' }, function (err, result) {
    t.type(err, 'object', 'an error');
    t.equal(!result, true, 'no result');
    t.equal(err.message, 'larry not found', 'could not find larry');
    t.end();
  });
});

test("executing creature.updateOrCreate - with a new id", function (t) {
  creature.updateOrCreate({ id: 'larry', items: items  }, function (err, result) {
    t.type(err, 'null', 'created larry - no error');
    t.type(result, 'object', 'created larry - result is object');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing create.updateOrCreate = with existing id", function (t) {
  creature.updateOrCreate({ id: 'bobby', life: 5, items: items  }, function (err, result) {
    t.type(err, 'null', 'updated bobby - no error');
    t.type(result, 'object', 'updated bobby - result is object');
    t.equal(result.life, 5, 'updated bobby - result.life == 5');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing account.create with same id as a creature", function (t) {
  account.create({
    id: 'bobby'
  }, function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.equal(result.id, 'bobby', 'id is correct');
    t.end();
  });
});

test("executing creature.destroy", function (t) {
  t.plan(2);
  creature.destroy('bobby', function(err, result){
    t.type(result, 'null', 'destroyed bobby');
  });
  creature.destroy('larry', function(err, result){
    t.type(result, 'null', 'destroyed larry');
  });
});

test("executing account.destroy", function (t) {
  t.plan(1);
  account.destroy('bobby', function(err, result){
    t.type(result, 'null', 'destroyed bobby');
  });
});

test("executing creature.get", function (t) {
  creature.get('bobby', function(err, result){
    t.type(err, 'object', 'could not find bobby');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 0, 'no creatures');
    t.end();
  });
});

test("persist creature to couchdb", function (t) {
  creature.persist({ name: "big-test", type: "couchdb", options: { cache: false }});
  t.end();
});

//
// Tests for modifying instances outside the use of jugglingdb
// (example: modifying a couchdb doc with futon)
//
test("modify persisted documents outside of jugglingdb", function (t) {
  var request = require('request');

  creature.updateOrCreate({ id: "korben", life: 10, items: [], metadata: {} }, function (err, korben) {
    t.error(err, 'successfully created korben');

    t.doesNotThrow(function () {
      t.equal(korben.life, 10, 'korben has life 10');
    }, 'korben is an object');

    var uri = 'http://localhost:5984/big-test/creature%2Fkorben';

    request({
      uri: uri,
      json: true
    }, function (err, res, doc) {
      t.error(err, 'successfully requested couchdb document');

      doc.life = 100;

      request({
        method: 'PUT',
        uri: uri,
        json: doc
      }, function (err, res, body) {
        t.error(err, 'no error');
        t.equal(res.statusCode, 201, 'document was successfully updated');
        t.ok(body.ok, 'couchdb says ok');

        creature.get('korben', function (err, korben) {
          t.error(err, 'successfully got korben');

          t.doesNotThrow(function () {
            t.equal(korben.life, 100, 'korben has life 100');
            korben.life = 50;
          }, 'korben is an object');

          creature.update(korben, function (err, korben) {
            t.error(err, 'successfully updated korben');

            t.doesNotThrow(function () {
              t.equal(korben.life, 50, 'korben has life 50');
            }, 'korben is an object');

            creature.destroy(korben.id, function (err) {
              t.error(err, 'korben was destroyed');
              t.end();
            });
          });
        });
      });
    });
  });
});
<commit_msg>[test] [fix] Removed errant test<commit_after>var tap = require("tap")
  , test = tap.test
  , plan = tap.plan
  , account
  , creature
  , resource;

//
// Testing metadata
//
var testDatasource = "memory";

test("load resource module", function (t) {
  resource = require('../');
  t.ok(resource, "object loaded")
  t.end()
});

test("define creature resource - with datasource config", function (t) {
  creature = resource.define('creature', { config: { datasource: testDatasource }});

  creature.property('life', {
    "type": "number"
  });

  creature.property('metadata', {
    "type": "object"
  });

  creature.property('items', {
    "type": "array"
  });

  t.type(creature.config, 'object', 'configuration defined - creature.config is object');
  t.equal(testDatasource, creature.config.datasource, ('configuration defined - creature.config.datasource == "' + testDatasource + '"'));

  t.type(creature.methods, 'object', 'methods defined - creature.methods is object');
  t.type(creature.methods.create, 'function', 'methods defined - methods.create is function');
  t.type(creature.methods.get, 'function', 'methods defined - methods.get is function');
  t.type(creature.methods.find, 'function', 'methods defined - methods.find is function');
  t.type(creature.methods.destroy, 'function', 'methods defined - methods.destroy is function');

  t.type(creature.create, 'function', 'methods hoisted - creature.create is function');
  t.type(creature.get, 'function', 'methods hoisted - creature.get is function');
  t.type(creature.find, 'function', 'methods hoisted - creature.find is function');
  t.type(creature.destroy, 'function', 'methods hoisted - creature.destroy is function');

  t.end()
});

test("define account resource - with datasource config", function (t) {
  account = resource.define('account', { config: { datasource: testDatasource }});

  account.property('name', {
    "type": "string"
  });

  account.property('email', {
    "type": "string"
  });

  t.type(account.config, 'object', 'configuration defined - account.config is object');
  t.equal(testDatasource, account.config.datasource, ('configuration defined - account.config.datasource == "' + testDatasource + '"'));

  t.end()
});

//
// A simple data object to use for testing resource properties of type "object"
//
var data = {
  "foo": "bar",
  "abc": 123,
  "data" : {
    "prop1" : "foo",
    "prop2" : "bar"
  }
},
items = [
  { "foo": "bar" },
  { "abc": 123 }
];

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 0, 'no creatures');
    t.end();
  });
});

test("executing creature.create", function (t) {
  creature.create({
    id: 'bobby',
    metadata: data,
    items: items // array property currently has serialization issue
  }, function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.equal(result.id, 'bobby', 'id is correct');
    t.type(result.metadata, 'object', 'metadata is object');
    t.equal(result.metadata.foo, 'bar');
    t.equal(result.metadata.abc, 123);
    t.equal(result.metadata.data.prop1, 'foo');
    t.equal(result.metadata.data.prop2, 'bar');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing creature.create - when already created", function (t) {
  creature.create({
    id: 'bobby',
    metadata: data,
    items: items // array property current has serialization issue
  }, function(err, result){
    t.type(err, 'object', 'an error');
    t.equal(!result, true, 'no result');
    t.equal(err.message, 'bobby already exists', 'bobby already exists');
    t.end();
  });
});

test("executing creature.get", function (t) {
  creature.get('bobby', function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.type(result.metadata, 'object', 'metadata is object');
    t.equal(result.metadata.foo, 'bar');
    t.equal(result.metadata.abc, 123);
    t.equal(result.metadata.data.prop1, 'foo');
    t.equal(result.metadata.data.prop2, 'bar');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result) {
    t.equal(result.length, 1, 'one creature');
    t.end();
  });
});

test("executing creature.create - with bad input", function (t) {
  creature.create({ id: 'larry', life: "abc" }, function(err, result){
    t.type(err, 'object', 'continues correct validation error - err is object');
    t.type(err.errors, 'object', 'continues correct validation error - err.errors is object');
    t.equal(err.errors.length, 1, 'continues correct validation error - one validation error');
    t.equal(err.errors[0].attribute, 'type', 'continues correct validation error - attribute == "type"');
    t.equal(err.errors[0].property, 'life', 'continues correct validation error - property == "life"');
    t.equal(err.errors[0].expected, 'number', 'continues correct validation error - expected == "number"');
    t.equal(err.errors[0].actual, 'string', 'continues correct validation error - actual == "string"');
    t.end();
  });
});

test("executing creature.get", function (t) {
  creature.get('larry', function(err, result){
    t.type(err, 'object', 'could not find larry');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 1);
    t.end();
  });
});

test("executing creature.update", function (t) {
  creature.update({ id: 'bobby', life: 9999 , items: items }, function(err, result){
    t.type(err, 'null', 'updated bobby - no error');
    t.type(result, 'object', 'updated bobby - result is object');
    t.equal(result.life, 9999, 'updated bobby - result.life == 9999');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing create.update - when creature does not exist", function (t) {
  creature.update({ id: 'larry' }, function (err, result) {
    t.type(err, 'object', 'an error');
    t.equal(!result, true, 'no result');
    t.equal(err.message, 'larry not found', 'could not find larry');
    t.end();
  });
});

test("executing creature.updateOrCreate - with a new id", function (t) {
  creature.updateOrCreate({ id: 'larry', items: items  }, function (err, result) {
    t.type(err, 'null', 'created larry - no error');
    t.type(result, 'object', 'created larry - result is object');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing create.updateOrCreate = with existing id", function (t) {
  creature.updateOrCreate({ id: 'bobby', life: 5, items: items  }, function (err, result) {
    t.type(err, 'null', 'updated bobby - no error');
    t.type(result, 'object', 'updated bobby - result is object');
    t.equal(result.life, 5, 'updated bobby - result.life == 5');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing account.create with same id as a creature", function (t) {
  account.create({
    id: 'bobby'
  }, function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.equal(result.id, 'bobby', 'id is correct');
    t.end();
  });
});

test("executing creature.destroy", function (t) {
  t.plan(2);
  creature.destroy('bobby', function(err, result){
    t.type(result, 'null', 'destroyed bobby');
  });
  creature.destroy('larry', function(err, result){
    t.type(result, 'null', 'destroyed larry');
  });
});

test("executing account.destroy", function (t) {
  t.plan(1);
  account.destroy('bobby', function(err, result){
    t.type(result, 'null', 'destroyed bobby');
  });
});

test("executing creature.get", function (t) {
  creature.get('bobby', function(err, result){
    t.type(err, 'object', 'could not find bobby');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 0, 'no creatures');
    t.end();
  });
});

test("persist creature to couchdb", function (t) {
  creature.persist({ name: "big-test", type: "couchdb", options: { cache: false }});
  t.end();
});<|endoftext|>