Esempio n. 1
0
module.exports = testCase({
    setUp: function(finished) {
        sandbox = {
            console: {
                warn: consoleWrapper,
                error: consoleWrapper,
                log: consoleWrapper
            }
        };

        sandbox.window = sandbox;
        consoleMsg = undefined;
        finished();
    },
    simpleModule: function(test) {
        test.expect(2);
        translate(
            module1Path,
            undefined,
            function result(err, src, files) {
                var module1;

                if(err) {throw err;}
                test.deepEqual(files, [module1Path]);
                run(src, module1Path);
                module1 = sandbox.modules[module1Path];
                test.equal(module1(), 2);
                test.done();
            }
        );
    },
    singleRequirement: function(test) {
        test.expect(2);
        translate(
            module2Path,
            undefined,
            function result(err, src, files) {
                var module2;

                if(err) {throw err;}
                test.deepEqual(files.sort(), [module1Path, module2Path].sort());
                run(src, module2Path);
                module2 = sandbox.modules[module2Path];
                test.equal(module2(), 3);
                test.done();
            }
        );
    },
    unknownInitModule: function(test) {
        test.expect(1);
        translate(
            folder1,
            undefined,
            function result(err, src) {
                if(err) {throw err;}
                run(src, __dirname + '/folder1');
                test.equal(consoleMsg, 'Cannot initialize unknown module ' + __dirname + '/folder1');
                test.done();
            }
        );
    },
    circularDependency: function(test) {
        test.expect(1);
        translate(
            folder1,
            undefined,
            function result(err, src) {
                if(err) {throw err;}
                run(src, circular1Path);
                test.equal(
                    consoleMsg,
                    'node2browser error: circular dependency detected.\n'
                        + 'module ' + __dirname + '/folder1/circular2.js is requiring '
                        + __dirname + '/folder1/circular1.js and vice versa.'
                    );
                test.done();
            }
        );
    },
    packageJSON: function(test) {
        test.expect(4);
        translate(
            otherModulePath,
            undefined,
            function result(err, src, files) {
                if(err) {throw err;}
                run(src, __dirname + '/folder2/package.json');
                test.deepEqual(
                    files.sort(),
                    [
                        __dirname + '/folder2/package.json',
                        __dirname + '/folder2/otherModule1.js',
                        __dirname + '/folder2/otherModule2.js',
                        __dirname + '/folder2/otherModule3.js',
                        __dirname + '/folder2/otherModule4.js'
                    ].sort()
                );
                // if package.json has been initialized, then otherModule2,
                // otherModule3 and otherModule4 must be objects
                test.equal(typeof sandbox.modules[__dirname + '/folder2/otherModule2.js'], 'object');
                test.equal(typeof sandbox.modules[__dirname + '/folder2/otherModule3.js'], 'object');
                test.equal(typeof sandbox.modules[__dirname + '/folder2/otherModule4.js'], 'object');
                test.done();
            }
        );
    },
    withPathModifier: function(test) {
        function finished(err ,src) {
            var module1 = 'node_modules/folder4/module1.js';

            if(err) {throw err;}
            run(src, module1);
            module1 = sandbox.modules[module1];
            test.equal(consoleMsg, undefined);
            test.equal(module1, 'module2');
            test.done();
        }

        function pathModifier(path) {
            if (/.*node_modules\//gi.test(path)) {
                return 'node_modules/' + path.replace(/.*node_modules\//gi, '');
            } else {
                return path;
            }
        }

        test.expect(2);
        translate(folder4, pathModifier, finished);
    },
    withFalsyPathModifier: function(test) {
        function finished(err, src) {
            if(err) {throw err;}
            test.strictEqual(src, '');
            test.done();
        }

        function pathModifier(path) {
            return false;
        }

        test.expect(1);
        translate(folder4, pathModifier, finished);
    },
    writingBrowserTest: function(test) {
        var nodeUnitPath = pathUtil.dirname(require.resolve('nodeunit')) + '/examples/browser/nodeunit.js',
            nodeUnit = fs.readFileSync(nodeUnitPath, 'utf8');

        function finished(err, src) {
            var testModule = 'node_modules/test.js';

            if(err) {throw err;}
            run(src, testModule);
            src = setup(src, testModule);
            src = nodeUnit + src;
            fs.writeFileSync(__dirname + '/browser/modules.js', src, 'utf8');
            test.done();
        }

        function pathModifier(path) {
            if (/.*node_modules\//gi.test(path)) {
                return 'node_modules/' + path.replace(/.*node_modules\//gi, '');
            } else {
                return path;
            }
        }

        translate(browserModules, pathModifier, finished);
    }
});
Esempio n. 2
0
module.exports = testCase({
    noDependencies: function(test) {
        var path = __dirname + '/node_modules/noDependencies.js';

        test.expect(3);
        getDependencies(path, load(path), function(err, result) {
            test.strictEqual(err, null);
            test.equal(result instanceof Array, true);
            test.equal(result.length, 0);
            test.done();
        });
    },
    someDependencies: function(test) {
        var expected = [
                __dirname + '/node_modules/noDependencies.js',
                __dirname + '/node_modules/package.json',
                __dirname + '/getDependencies.js'
            ],
            path = __dirname + '/node_modules/someDependencies.js';

        test.expect(2);
        getDependencies(path, load(path), function(err, result) {
            test.strictEqual(err, null);
            test.deepEqual(expected.sort(), result.sort());
            test.done();
        });
    },
    packageDependencies: function(test) {
        var expected = [
                __dirname + '/node_modules/noDependencies.js'
            ],
            path = __dirname + '/node_modules/package.json';

        test.expect(3);
        getDependencies(path, load(path), function(err, result) {
            test.strictEqual(err, null);
            test.equal(result instanceof Array, true);
            test.deepEqual(expected, result);
            test.done();
        });
    },
    wrongRequire: function(test) {
        var path = __dirname + '/node_modules/errors/wrongRequire.js';

        test.expect(2);
        getDependencies(path, load(path), function(err, result) {
            test.equal(typeof err, 'object');
            test.equal(err.message, 'Cannot find module ./asdasdasdasds');
            test.done();
        });
    },
    wrongPackage: function(test) {
        var path = __dirname + '/node_modules/errors/package.json';

        test.expect(2);
        getDependencies(path, load(path), function(err, result) {
            test.equal(typeof err, 'object');
            test.equal(err.message, 'Unexpected end of input');
            test.done();
        });
    }
});
(function () {

    'use strict';

    var sinon = require('sinon'),
        testCase = require('nodeunit').testCase;

    exports.options_test = {
        'endsWith string extension function': testCase({
            'should match correct trailing substring': function (test) {
                test.ok("abcdefabcabc".endsWidth("cabc"), '"abcdefabcabc" ends with "cabc"');
                test.ok("abcdefabcabc".endsWidth("abc"), '"abcdefabcabc" ends with "abc"');
                test.ok("abcdefabcabc".endsWidth("bc"), '"abcdefabcabc" ends with "bc"');
                test.ok("abcdefabcabc".endsWidth("c"), '"abcdefabcabc" ends with "c"');
                test.ok("abcdefabcabc".endsWidth("abcdefabcabc"), '"abcdefabcabc" ends with "abcdefabcabc"');
                test.ok("abcdefabcabc".endsWidth(""), '"abcdefabcabc" ends with ""');

                // end
                test.done();
            },
            'should not-match incorrect trailing substring': function (test) {
                test.ok(!"abcdefabcabc".endsWidth("ab"), '"abcdefabcabc" does not ends with "ab"');
                test.ok(!"abcdefabcabc".endsWidth("abcd"), '"abcdefabcabc" does not ends with "abcd"');
                test.ok(!"abcdefabcabc".endsWidth("def"), '"abcdefabcabc" does not ends with "def"');
                test.ok(!"abcdefabcabc".endsWidth("cb"), '"abcdefabcabc" does not ends with "cb"');

                // end
                test.done();
            }
        }),
        'option validation': testCase({
            setUp: function (callback) {
                this.mockGrunt = {
                    log: {
                        subhead: sinon.spy.create(),
                        errorlns: sinon.spy.create()
                    }
                };
                this._validateOptions = require('../../tasks/options.js')._validate(this.mockGrunt);
                callback();
            },
            'should display errors for empty options': function (test) {
                // given
                var options = {};

                // when
                var valid = this._validateOptions(options);

                // then
                test.deepEqual(this.mockGrunt.log.subhead.args, [
                    [ 'no maintainer details provided!!' ],
                    [ 'no short description provided!!' ],
                    [ 'no long description provided!!' ]
                ]);
                test.deepEqual(this.mockGrunt.log.errorlns.args, [
                    [ 'please add the \'maintainer\' option specifying the name and email in your debian_package configuration in your Gruntfile.js or add \'DEBFULLNAME\' and \'DEBEMAIL\' environment variable (i.e. export DEBFULLNAME="James D Bloom" && export DEBEMAIL="*****@*****.**")' ],
                    [ 'please add the \'short_description\' option in your debian_package configuration in your Gruntfile.js or add a \'description\' field to package.json' ],
                    [ 'please add the \'long_description\' option in your debian_package configuration in your Gruntfile.js or add a multi line \'description\' field to package.json (note: the first line is used as the short description and the remaining lines are used as the long description)' ]
                ]);
                test.deepEqual(options, {});
                test.ok(!valid, 'returns not valid');

                // end
                test.done();
            },
            'should display no errors for correct options': function (test) {
                // given
                var options = {
                    maintainer: {
                        name: 'James D Bloom',
                        email: '*****@*****.**'
                    },
                    short_description: 'the short description',
                    long_description: 'the long description added to the debian package',
                    working_directory: 'dir'
                };

                // when
                var valid = this._validateOptions(options);

                // then
                test.deepEqual(this.mockGrunt.log.subhead.args, []);
                test.deepEqual(this.mockGrunt.log.errorlns.args, []);
                test.deepEqual(options, {
                    maintainer: {
                        name: 'James D Bloom',
                        email: '*****@*****.**'
                    },
                    short_description: 'the short description',
                    long_description: ' the long description added to the debian package',
                    working_directory: 'dir/',
                    package_name: 'debian_package',
                    package_location: 'dir/debian_package'
                });
                test.ok(valid, 'returns valid');

                // end
                test.done();
            },
            'should display when maintainer details not provided': function (test) {
                // given
                var options = {
                    maintainer: {
                    },
                    short_description: 'the short description',
                    long_description: 'the long description added to the debian package'
                };

                // when
                var valid = this._validateOptions(options);

                // then
                test.deepEqual(this.mockGrunt.log.subhead.args, [
                    [ 'no maintainer name provided!!' ],
                    [ 'no maintainer email provided!!' ]
                ]);
                test.deepEqual(this.mockGrunt.log.errorlns.args, [
                    [ 'please add the \'maintainer.name\' option in your debian_package configuration in your Gruntfile.js or add a \'DEBFULLNAME\' environment variable (i.e. export DEBFULLNAME="James D Bloom")' ],
                    [ 'please add the \'maintainer.email\' option in your debian_package configuration in your Gruntfile.js or add a \'DEBEMAIL\' environment variable (i.e. export DEBEMAIL="*****@*****.**")' ]
                ]);
                test.deepEqual(options, {
                    maintainer: {
                    },
                    short_description: 'the short description',
                    long_description: ' the long description added to the debian package'
                });
                test.ok(!valid, 'returns not valid');

                // end
                test.done();
            }
        })
    };

})();
Esempio n. 4
0
var persist = require("../lib/persist");
var type = persist.type;
var nodeunit = require("nodeunit");
var util = require("util");
var testUtils = require("../test_helpers/test_utils");

exports['Select'] = nodeunit.testCase({
  "use database.json to connect": function(test) {
    persist.connect(function(err, connection) {
      connection.runSql(testUtils.doNothingSql, function(err) {
        if(err) { console.log(err); return; }
        test.done();
      });
    });
  }

});
Esempio n. 5
0
module.exports = testCase({
	setUp: function (callback) {
		jQuery = $ = helpers.recreate_doc(static_document);
		callback();
	},
	tearDown: function (callback) {
		// clean up
		callback();
	},
	"css(String|Hash)": function(test) {
		test.expect(18);

		//test.equals( jQuery('#main').css("display"), 'block', 'Check for css property "display"');

		test.ok( jQuery('#nothiddendiv').is(':visible'), 'Modifying CSS display: Assert element is visible');
		jQuery('#nothiddendiv').css({display: 'none'});
		test.ok( !jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is hidden');
		jQuery('#nothiddendiv').css({display: 'block'});
		test.ok( jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is visible');

		var div = jQuery( "<div>" );

		// These should be "auto" (or some better value)
		// temporarily provide "0px" for backwards compat
		test.equals( div.css("width"), "0px", "Width on disconnected node." );
		test.equals( div.css("height"), "0px", "Height on disconnected node." );

		div.css({ width: 4, height: 4 });

		test.equals( div.css("width"), "4px", "Width on disconnected node." );
		test.equals( div.css("height"), "4px", "Height on disconnected node." );

		var div2 = jQuery( "<div style='display:none;'><input type='text' style='height:20px;'/><textarea style='height:20px;'/><div style='height:20px;'></div></div>").appendTo("body");

		test.equals( div2.find("input").css("height"), "20px", "Height on hidden input." );
		test.equals( div2.find("textarea").css("height"), "20px", "Height on hidden textarea." );
		test.equals( div2.find("div").css("height"), "20px", "Height on hidden textarea." );

		div2.remove();

		// handle negative numbers by ignoring #1599, #4216
		jQuery('#nothiddendiv').css({ 'width': 1, 'height': 1 });

		var width = parseFloat(jQuery('#nothiddendiv').css('width')), height = parseFloat(jQuery('#nothiddendiv').css('height'));
		jQuery('#nothiddendiv').css({ width: -1, height: -1 });
		//test.equals( parseFloat(jQuery('#nothiddendiv').css('width')), width, 'Test negative width ignored')
		//test.equals( parseFloat(jQuery('#nothiddendiv').css('height')), height, 'Test negative height ignored')

		test.equals( jQuery('<div style="display: none;">').css('display'), 'none', 'Styles on disconnected nodes');

		//jQuery('#floatTest').css('float', 'right');
		//test.equals( jQuery('#floatTest').css('float'), 'right', 'Modified CSS float using "float": Assert float is right');
		//jQuery('#floatTest').css({'font-size': '30px'});
		//test.equals( jQuery('#floatTest').css('font-size'), '30px', 'Modified CSS font-size: Assert font-size is 30px');

		/*jQuery.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
			jQuery('#foo').css({opacity: n});
			test.equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
			jQuery('#foo').css({opacity: parseFloat(n)});
			test.equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
		});*/
		jQuery('#foo').css({opacity: ''});
		test.equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when set to an empty String" );

		//test.equals( jQuery('#empty').css('opacity'), '0', "Assert opacity is accessible via filter property set in stylesheet in IE" );
		//jQuery('#empty').css({ opacity: '1' });
		//test.equals( jQuery('#empty').css('opacity'), '1', "Assert opacity is taken from style attribute when set vs stylesheet in IE with filters" );

		var div = jQuery('#nothiddendiv'), child = jQuery('#nothiddendivchild');

		//test.equals( parseInt(div.css("fontSize")), 16, "Verify fontSize px set." );
		//test.equals( parseInt(div.css("font-size")), 16, "Verify fontSize px set." );
		//test.equals( parseInt(child.css("fontSize")), 16, "Verify fontSize px set." );
		//test.equals( parseInt(child.css("font-size")), 16, "Verify fontSize px set." );

		child.css("height", "100%");
		test.equals( child[0].style.height, "100%", "Make sure the height is being set correctly." );

		child.attr("class", "em");
		//test.equals( parseInt(child.css("fontSize")), 32, "Verify fontSize em set." );

		// Have to verify this as the result depends upon the browser's CSS
		// support for font-size percentages
		child.attr("class", "prct");
		var prctval = parseInt(child.css("fontSize")), checkval = 0;
		if ( prctval === 16 || prctval === 24 ) {
			checkval = prctval;
		}

		//test.equals( prctval, checkval, "Verify fontSize % set." );

		test.equals( typeof child.css("width"), "string", "Make sure that a string width is returned from css('width')." );

		var old = child[0].style.height;

		// Test NaN
		child.css("height", parseFloat("zoo"));
		test.equals( child[0].style.height, old, "Make sure height isn't changed on NaN." );

		// Test null
		child.css("height", null);
		test.equals( child[0].style.height, old, "Make sure height isn't changed on null." );

		old = child[0].style.fontSize;

		// Test NaN
		child.css("font-size", parseFloat("zoo"));
		test.equals( child[0].style.fontSize, old, "Make sure font-size isn't changed on NaN." );

		// Test null
		child.css("font-size", null);
		test.equals( child[0].style.fontSize, old, "Make sure font-size isn't changed on null." );
		test.done();
	}	
});
module.exports = testCase(
{
  setUp: function (callback) {
    servicebustestutil.setUpTest(module.exports, testPrefix, function (err, newServiceBusService) {
      serviceBusService = newServiceBusService;
      callback();
    });
  },

  tearDown: function (callback) {
    servicebustestutil.tearDownTest(module.exports, serviceBusService, testPrefix, callback);
  },

  testCreateQueue: function (test) {
    var queueName = testutil.generateId(queueNamesPrefix, queueNames);

    serviceBusService.createQueue(queueName, function (createError, queue) {
      test.equal(createError, null);
      test.notEqual(queue, null);

      test.done();
    });
  },

  testDeleteQueue: function (test) {
    var queueName = testutil.generateId(queueNamesPrefix, queueNames);

    serviceBusService.deleteQueue(queueName, function (error1) {
      test.notEqual(error1, null);
      test.equal(error1.code, '404');

      serviceBusService.createQueue(queueName, function (error2, createResponse1) {
        test.equal(error2, null);
        test.notEqual(createResponse1, null);

        serviceBusService.deleteQueue(queueName, function (error3, deleteResponse2) {
          test.equal(error3, null);
          test.notEqual(deleteResponse2, null);

          test.done();
        });
      });
    });
  },

  testGetQueue: function (test) {
    var queueName = testutil.generateId(queueNamesPrefix, queueNames);

    serviceBusService.createQueue(queueName, function (createError, queue) {
      test.equal(createError, null);
      test.notEqual(queue, null);

      serviceBusService.getQueue(queueName, function (getError, getQueue) {
        test.equal(getError, null);
        test.notEqual(getQueue, null);

        test.done();
      });
    });
  },

  testListQueue: function (test) {
    var queueName1 = testutil.generateId(queueNamesPrefix, queueNames);
    var queueName2 = testutil.generateId(queueNamesPrefix, queueNames);

    serviceBusService.createQueue(queueName1, function (createError1, queue1) {
      test.equal(createError1, null);
      test.notEqual(queue1, null);

      serviceBusService.createQueue(queueName2, function (createError2, queue2) {
        test.equal(createError2, null);
        test.notEqual(queue2, null);

        serviceBusService.listQueues(function (getError, queues) {
          test.equal(getError, null);
          test.notEqual(queues, null);
          test.equal(queues.length, 2);

          test.done();
        });
      });
    });
  },

  testSendQueueMessage: function (test) {
    var queueName = testutil.generateId(queueNamesPrefix, queueNames);

    serviceBusService.createQueue(queueName, function (createError, queue) {
      test.equal(createError, null);
      test.notEqual(queue, null);

      serviceBusService.sendQueueMessage(queueName, 'hi there', function (sendError) {
        test.equal(sendError, null);

        test.done();
      });
    });
  },

  testReceiveQueueMessage: function (test) {
    var queueName = testutil.generateId(queueNamesPrefix, queueNames);
    var messageText = 'hi there again';

    serviceBusService.createQueue(queueName, function (createError, queue) {
      test.equal(createError, null);
      test.notEqual(queue, null);

      serviceBusService.sendQueueMessage(queueName, messageText, function (sendError) {
        test.equal(sendError, null);

        // read the message
        serviceBusService.receiveQueueMessage(queueName, function (receiveError, message) {
          test.equal(receiveError, null);
          test.equal(message, messageText);

          serviceBusService.receiveQueueMessage(queueName, function (receiveError2, emptyMessage) {
            test.notEqual(receiveError2, null);
            test.equal(emptyMessage, null);

            test.done();
          });
        });
      });
    });
  },

  testCreateTopic: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);

    serviceBusService.createTopic(topicName, function (createError, topic) {
      test.equal(createError, null);
      test.notEqual(topic, null);

      test.done();
    });
  },

  testDeleteTopic: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);

    serviceBusService.deleteTopic(topicName, function (error1) {
      test.notEqual(error1, null);
      test.equal(error1.code, '404');

      serviceBusService.createTopic(topicName, function (error2, createResponse1) {
        test.equal(error2, null);
        test.notEqual(createResponse1, null);

        serviceBusService.deleteTopic(topicName, function (error3, deleteResponse2) {
          test.equal(error3, null);
          test.notEqual(deleteResponse2, null);

          test.done();
        });
      });
    });
  },

  testGetTopic: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);

    serviceBusService.createTopic(topicName, function (createError, topic) {
      test.equal(createError, null);
      test.notEqual(topic, null);

      serviceBusService.getTopic(topicName, function (getError, getTopic) {
        test.equal(getError, null);
        test.notEqual(getTopic, null);

        test.done();
      });
    });
  },

  testListTopics: function (test) {
    var topicName1 = testutil.generateId(topicNamesPrefix, topicNames);
    var topicName2 = testutil.generateId(topicNamesPrefix, topicNames);

    serviceBusService.createTopic(topicName1, function (createError1, topic1) {
      test.equal(createError1, null);
      test.notEqual(topic1, null);

      serviceBusService.createTopic(topicName2, function (createError2, topic2) {
        test.equal(createError2, null);
        test.notEqual(topic2, null);

        serviceBusService.listTopics(function (listError, listTopics) {
          test.equal(listError, null);
          test.notEqual(listTopics, null);
          test.equal(listTopics.length, 2);

          test.done();
        });
      });
    });
  },

  testCreateSubscription: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);
    var subscriptionName = testutil.generateId(subscriptionNamesPrefix, subscriptionNames);

    serviceBusService.createTopic(topicName, function (createError, topic) {
      test.equal(createError, null);
      test.notEqual(topic, null);

      serviceBusService.createSubscription(topicName, subscriptionName, function (createSubscriptionError, subscription) {
        test.equal(createSubscriptionError, null);
        test.notEqual(subscription, null);

        test.done();
      });
    });
  },

  testDeleteSubscription: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);
    var subscriptionName = testutil.generateId(subscriptionNamesPrefix, subscriptionNames);

    serviceBusService.deleteSubscription(topicName, subscriptionName, function (error1) {
      test.notEqual(error1, null);
      test.equal(error1.code, '404');

      serviceBusService.createTopic(topicName, function (error2, createResponse1) {
        test.equal(error2, null);
        test.notEqual(createResponse1, null);

        serviceBusService.createSubscription(topicName, subscriptionName, function (error3, createResponse3) {
          test.equal(error3, null);
          test.notEqual(createResponse3, null);

          serviceBusService.deleteSubscription(topicName, subscriptionName, function (error4, deleteResponse4) {
            test.equal(error4, null);
            test.notEqual(deleteResponse4, null);

            test.done();
          });
        });
      });
    });
  },

  testGetSubscription: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);
    var subscriptionName = testutil.generateId(subscriptionNamesPrefix, subscriptionNames);

    serviceBusService.createTopic(topicName, function (createError1, topic) {
      test.equal(createError1, null);
      test.notEqual(topic, null);

      serviceBusService.createSubscription(topicName, subscriptionName, function (createError2, subscription) {
        test.equal(createError2, null);
        test.notEqual(subscription, null);

        serviceBusService.getSubscription(topicName, subscriptionName, function (getError, getTopic) {
          test.equal(getError, null);
          test.notEqual(getTopic, null);

          test.done();
        });
      });
    });
  },

  testListSubscriptions: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);
    var subscriptionName1 = testutil.generateId(subscriptionNamesPrefix, subscriptionNames);
    var subscriptionName2 = testutil.generateId(subscriptionNamesPrefix, subscriptionNames);

    serviceBusService.createTopic(topicName, function (createError1, topic) {
      test.equal(createError1, null);
      test.notEqual(topic, null);

      serviceBusService.createSubscription(topicName, subscriptionName1, function (createError2, subscription1) {
        test.equal(createError2, null);
        test.notEqual(subscription1, null);

        serviceBusService.createSubscription(topicName, subscriptionName2, function (createError3, subscription2) {
          test.equal(createError3, null);
          test.notEqual(subscription2, null);

          serviceBusService.listSubscriptions(topicName, function (listError, subscriptions) {
            test.equal(listError, null);
            test.notEqual(subscriptions, null);
            test.equal(subscriptions.length, 2);

            test.done();
          });
        });
      });
    });
  },

  testCreateRule: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);
    var subscriptionName = testutil.generateId(subscriptionNamesPrefix, subscriptionNames);
    var ruleName = testutil.generateId(ruleNamesPrefix, ruleNames);

    serviceBusService.createTopic(topicName, function (createError, topic) {
      test.equal(createError, null);
      test.notEqual(topic, null);

      serviceBusService.createSubscription(topicName, subscriptionName, function (createSubscriptionError, subscription) {
        test.equal(createSubscriptionError, null);
        test.notEqual(subscription, null);

        serviceBusService.createRule(topicName, subscriptionName, ruleName, function (createRuleError, rule) {
          test.equal(createRuleError, null);
          test.notEqual(rule, null);
          test.done();
        });
      });
    });
  },

  testDeleteRule: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);
    var subscriptionName = testutil.generateId(subscriptionNamesPrefix, subscriptionNames);
    var ruleName = testutil.generateId(ruleNamesPrefix, ruleNames);

    serviceBusService.deleteSubscription(topicName, subscriptionName, function (error1) {
      test.notEqual(error1, null);
      test.equal(error1.code, '404');

      serviceBusService.createTopic(topicName, function (error2, createResponse1) {
        test.equal(error2, null);
        test.notEqual(createResponse1, null);

        serviceBusService.createSubscription(topicName, subscriptionName, function (error3, createResponse3) {
          test.equal(error3, null);
          test.notEqual(createResponse3, null);

          serviceBusService.createRule(topicName, subscriptionName, ruleName, function (error4, createResponse4) {
            test.equal(error4, null);
            test.notEqual(createResponse4, null);

            serviceBusService.deleteRule(topicName, subscriptionName, ruleName, function (error5, deleteResponse5) {
              test.equal(error5, null);
              test.notEqual(deleteResponse5, null);

              test.done();
            });
          });
        });
      });
    });
  },

  testListRule: function (test) {
    var topicName = testutil.generateId(topicNamesPrefix, topicNames);
    var subscriptionName = testutil.generateId(subscriptionNamesPrefix, subscriptionNames);
    var ruleName1 = testutil.generateId(ruleNamesPrefix, ruleNames);
    var ruleName2 = testutil.generateId(ruleNamesPrefix, ruleNames);

    serviceBusService.createTopic(topicName, function (createError, topic) {
      test.equal(createError, null);
      test.notEqual(topic, null);

      serviceBusService.createSubscription(topicName, subscriptionName, function (createSubscriptionError, subscription) {
        test.equal(createSubscriptionError, null);
        test.notEqual(subscription, null);

        serviceBusService.createRule(topicName, subscriptionName, ruleName1, function (createRuleError1, rule1) {
          test.equal(createRuleError1, null);
          test.notEqual(rule1, null);

          serviceBusService.createRule(topicName, subscriptionName, ruleName2, function (createRuleError2, rule2) {
            test.equal(createRuleError2, null);
            test.notEqual(rule2, null);

            serviceBusService.listRules(topicName, subscriptionName, function (listError, rules) {
              test.equal(listError, null);
              test.notEqual(rules, null);
              test.equal(rules.length, 3);

              test.done();
            });
          });
        });
      });
    });
  }
});
Esempio n. 7
0
module.exports = simpleEvents({

  setUp: function (callback) {
    var EventEmitter2;

    if(typeof require !== 'undefined') {
      EventEmitter2 = require(file).EventEmitter2;
    }
    else {
      EventEmitter2 = window.EventEmitter2;
    }

    this.emitter = new EventEmitter2();
    callback();
  },

  tearDown: function (callback) {
    //clean up?
    callback();
  },

  '1. A listener added with `once` should only listen once and then be removed.': function (test) {

    var emitter = this.emitter;
    
    emitter.once('test1', function () {
      test.ok(true, 'The event was raised once');
    });

    emitter.emit('test1');
    emitter.emit('test1');

    test.expect(1);
    test.done();

  },
  '2. A listener with a TTL of 4 should only listen 4 times.': function (test) {

    var emitter = this.emitter;

    emitter.many('test1', 4, function (value1) {
      test.ok(true, 'The event was raised 4 times.');
    });

    emitter.emit('test1', 1);
    emitter.emit('test1', 2);
    emitter.emit('test1', 3);
    emitter.emit('test1', 4);
    emitter.emit('test1', 5);

    test.expect(4);
    test.done();

  },
  '3. A listener with a TTL of 4 should only listen 4 times and pass parameters.': function (test) {

    var emitter = this.emitter;

    emitter.many('test1', 4, function (value1, value2, value3) {
      test.ok(typeof value1 !== 'undefined', 'got value 1');
      test.ok(typeof value2 !== 'undefined', 'got value 2');
      test.ok(typeof value3 !== 'undefined', 'got value 3');
    });

    emitter.emit('test1', 1, 'A', false);
    emitter.emit('test1', 2, 'A', false);
    emitter.emit('test1', 3, 'A', false);
    emitter.emit('test1', 4, 'A', false);
    emitter.emit('test1', 5, 'A', false);

    test.done();

  },
  '4. Remove an event listener by signature.': function (test) {

    var emitter = this.emitter;
    var count = 0;

    function f1(event) {
      "event A";
      test.ok(true, 'The event was raised less than 3 times.');
    }

    emitter.on('test1', f1);
    
    function f2(event) {
      "event B";
      test.ok(true, 'The event was raised less than 3 times.');  
    }    
    
    emitter.on('test1', f2);

    function f3(event) {
      "event C";
      test.ok(true, 'The event was raised less than 3 times.');
    }

    emitter.on('test1', f3);

    emitter.removeListener('test1', f2);

    emitter.emit('test1');

    test.expect(2);
    test.done();

  },
  '5. `removeListener` and `once`': function(test) {
    
    var emitter = this.emitter;
    var functionA = function() { test.ok(true, 'Event was fired'); };

    emitter.once('testA', functionA);
    emitter.removeListener('testA', functionA);

    emitter.emit('testA');

    test.expect(0);
    test.done();
  }
  
});
Esempio n. 8
0
		var expectedPath = path.join(expectedDir, script);
		var content = fs.readFileSync(testPath, 'utf-8');
		var outputCompress = compress(content);

		// Check if the noncompressdata is larger or same size as the compressed data
		test.ok(content.length >= outputCompress.length);

		// Check that a recompress gives the same result
		var outputReCompress = compress(content);
		test.equal(outputCompress, outputReCompress);

		// Check if the compressed output is what is expected
		var expected = fs.readFileSync(expectedPath, 'utf-8');
		test.equal(outputCompress, expected.replace(/(\r?\n)+$/, ""));

		test.done();
	};
};

var tests = {};

var scripts = fs.readdirSync(testDir);
for (var i in scripts) {
	var script = scripts[i];
	if (/\.js$/.test(script)) {
		tests[script] = getTester(script);
	}
}

module.exports = nodeunit.testCase(tests);
Esempio n. 9
0
        // ************************************************************
    
        'Low Salary for a 18 year old' : testCase({
            setUp: function (callback) {
                var persona = {
                    age : 18,
                    income : 25000
                };

                var tc = new TaxCalculator(persona);
                tc.setTaxYear('2009_10');
                this.tc = tc;

                callback();
            },
            tearDown: function (callback) {
                delete this.tc;

                callback();
            },

            testDeduction : function(test) {
                test.equals(3705, this.tc.calculate());
            
                test.done();
            }
        }),
    
        'Medium Salary for a 18 year old' : testCase({
            setUp: function (callback) {
Esempio n. 10
0
module.exports = testCase({
  /*
  setUp: function (callback) {
    this.foo = 'bar';
    callback();
  },
   */
  test1: function (test) {
    test.equals('bar', 'bar');
    test.done();
  },
  escape: function (test) {
    test.equals(builder.escape(''), '');
    test.equals(builder.escape('hoge'), 'hoge');
    test.equals(builder.escape('hoge hoge'), 'hoge hoge');
    test.equals(builder.escape('hoge,pos'), 'hoge,pos');
    test.equals(builder.escape('hoge"pos'), 'hoge""pos');
    test.equals(builder.escape('hoge\'pos'), 'hoge\'pos');
    test.equals(builder.escape('"hoge"pos'), '""hoge""pos');
    test.equals(builder.escape('hoge""pos'), 'hoge""""pos');
    test.done();
  },
  build: function (test) {
    test.equals(builder.build([]), '');
    test.equals(builder.build(['']), '""\n');
    test.equals(builder.build(['','']), '"",""\n');
    test.equals(builder.build(['a']), '"a"\n');
    test.equals(builder.build(['aa']), '"aa"\n');
    test.equals(builder.build(['a"b']), '"a""b"\n');
    test.equals(builder.build(['a','b']), '"a","b"\n');
    test.equals(builder.build(['a"x','b']), '"a""x","b"\n');
    test.equals(builder.build(['a"','b']), '"a""","b"\n');
    test.equals(builder.build(['a','b', 'c']), '"a","b","c"\n');
    test.equals(builder.build(['a','b', '', 'c']), '"a","b","","c"\n');
    test.equals(builder.build(['a','b', null, 'c']), '"a","b","","c"\n');
    test.equals(builder.build(['a','b', undefined, 'c']), '"a","b","","c"\n');
    test.equals(builder.build(['a','b', 0, 'c']), '"a","b","0","c"\n');
    test.done();
  }
});
module.exports = testCase({
    setUp: function (callback) {
	
		var _this = this;
			new HunposTagger(
				'/Users/ironman/projects/node_projects/node-nltools/hunpos-1.0/en_wsj.model',
				'/Users/ironman/projects/node_projects/node-nltools/hunpos-1.0/hunpos-tag', 
				function(pos){
					_this.pos = pos;
	        callback();
				}
			);
    },

    tearDown: function (callback) {
			callback();
    },

    interrogative0: function (test) {
			this.pos.tag(['sally','ran','?'], function(posObj) {
				sentObj(posObj,function(sen){					
					test.equals(sen.type(), "INTERROGATIVE","Question sentence by punct.");
					test.done();
				})
			});
    },

    interrogative1: function (test) {
			this.pos.tag(['sally','?'], function(posObj) {
				sentObj(posObj,function(sen){					
					test.equals(sen.type(), "INTERROGATIVE","Question sentence by punct.");
					test.done();
				})
			});
    },

    interrogative2: function (test) {
			this.pos.tag(['?'], function(posObj) {
				sentObj(posObj,function(sen){					
					test.equals(sen.type(), "INTERROGATIVE","Question sentence by punct.");
					test.done();
				})
			});
    },

		// interrogative word (5w's) no punct
    interrogative3: function (test) {
			this.pos.tag("Who ran".split(" "), function(posObj) {
				sentObj(posObj,function(sen){					
					test.equals(sen.type(), "INTERROGATIVE","Question sentence by pos.");
					test.done();
				})
			});
    },

    interrogative4: function (test) {
			this.pos.tag("How did".split(" "), function(posObj) {
				sentObj(posObj,function(sen){					
					test.equals(sen.type(), "INTERROGATIVE","Question sentence by pos.");
					test.done();
				})
			});
    },

		// tag questions ending in possive pronoun
    interrogative5: function (test) {
			this.pos.tag("Oh I must , must I".split(" "), function(posObj) {
				sentObj(posObj,function(sen){		
					test.equals(sen.type(), "INTERROGATIVE","Question sentence by pos.");
					test.done();
				})
			});
    },

		// tag questions ending in possive pronoun
    interrogative6: function (test) {
			this.pos.tag("You want to see that again , do you".split(" "), function(posObj) {
				sentObj(posObj,function(sen){		
					test.equals(sen.type(), "INTERROGATIVE","Question sentence by pos.");
					test.done();
				})
			});
    },

    command0: function (test) {
			this.pos.tag("Sit down !".split(" "), function(posObj) {
				sentObj(posObj,function(sen){		
					test.equals(sen.type(), "COMMAND","Command by punct.");
					test.done();
				})
			});
    },

		// implicit you overrides punct.
    command1: function (test) {
			this.pos.tag("shut the hell up .".split(" "), function(posObj) {
				sentObj(posObj,function(sen){		
					test.equals(sen.type(), "COMMAND","Command by implicit you.");
					test.done();
				})
			});
		},

    declarative0: function (test) {
			this.pos.tag("I think it is time to go .".split(" "), function(posObj) {
				sentObj(posObj,function(sen){		
					test.equals(sen.type(), "DECLARATIVE","declarative by punct.");
					test.done();
				})
			});
    },

		// Probaby should be command.
    declarative1: function (test) {
			this.pos.tag("Janice , shut the hell up .".split(" "), function(posObj) {
				sentObj(posObj,function(sen){		
					test.equals(sen.type(), "DECLARATIVE","declarative by punct.");
					test.done();
				})
			});
    },


});
Esempio n. 12
0
module.exports = simpleEvents({

  setUp: function (callback) {

    if(typeof require !== 'undefined') {
      this.EventEmitter2 = require(file).EventEmitter2;
    }
    else {
      this.EventEmitter2 = window.EventEmitter2;
    }

    this.emitter = new this.EventEmitter2;
    callback();
  },

  tearDown: function (callback) {
    //clean up?
    callback();
  },

  'setMaxListener1. default behavior of 10 listeners.' : function (test) {
    var emitter = this.emitter;

    for (var i = 0; i < 10; i++) {
      emitter.on('foobar', function () {
        test.ok(true, 'event was raised');
      });
    }

    var listeners = emitter.listeners('foobar');
    test.equal(listeners.length, 10, 'should only have 10');

    test.expect(1);
    test.done();
  },

  'setMaxListener2. If we added more than 10, should not see them' : function (test) {
    var emitter = this.emitter;

    for (var i = 0; i < 10 ; i++) {
      emitter.on('foobar2', function () {
        test.ok(true, 'event was raised');
      });
    }
    console.log('should see EE2 complaining:');
    emitter.on('foobar2', function () {
      test.ok(true, 'event was raised');
    });
    console.log('move on');

    var listeners = emitter.listeners('foobar2');
    test.equal(listeners.length, 11, 'should have 11');
    test.ok(emitter._events['foobar2'].warned, 'should have been warned');

    test.expect(2);
    test.done();
  },

  'setMaxListener3. if we set maxListener to be greater before adding' : function (test) {
    var emitter = this.emitter;
    var type = 'foobar3';

    // set to 20
    emitter.setMaxListeners(20);

    for (var i = 0; i < 15 ; i++) {
      emitter.on(type, function () {
        test.ok(true, 'event was raised');
      });
    }

//    require('eyes').inspect(emitter._events);

    var listeners = emitter.listeners(type);
    test.equal(listeners.length, 15, 'should have 15');
    test.ok(!(emitter._events[type].warned), 'should not have been set');

    test.expect(2);
    test.done();
  },

  'setMaxListener4. should be able to change it right at 10' : function (test) {
    var emitter = this.emitter;
    var type = 'foobar4';

    for (var i = 0; i < 10 ; i++) {
      emitter.on(type, function () {
        test.ok(true, 'event was raised');
      });
    }

    emitter.setMaxListeners(9001);
    emitter.on(type, function () {
      test.ok(true, 'event was raised');
    });

//    require('eyes').inspect(emitter._events);

    var listeners = emitter.listeners(type);
    test.equal(listeners.length, 11, 'should have 11');
    test.ok(!(emitter._events[type].warned), 'should not have been set');

    test.expect(2);
    test.done();
  },

  'setMaxListener5. if we set maxListener to be 0 should add endlessly' : function (test) {
    var emitter = this.emitter;
    var type = 'foobar';

    // set to 0
    emitter.setMaxListeners(0);

    for (var i = 0; i < 25 ; i++) {
      emitter.on(type, function () {
        test.ok(true, 'event was raised');
      });
    }

    var listeners = emitter.listeners(type);
    test.equal(listeners.length, 25, 'should have 25');
    test.ok(!(emitter._events[type].warned), 'should not have been set');

    test.expect(2);
    test.done();
  },
  'maxListeners parameter. Passing maxListeners as a parameter should override default.' : function (test) {
    var emitter = new this.EventEmitter2({
      maxListeners: 2
    });
    console.log(emitter, test.equal, test.ok);
    emitter.on('a', function () {});
    emitter.on('a', function () {});
    emitter.on('a', function () {});    
    test.ok(emitter._events.a.warned,
      '.on() should warn when maxListeners is exceeded.');
    test.done();
  }
});
module.exports = testCase({
         setUp: function(callback){
           this.conn = new fb_binding.createConnection();
           this.conn.connectSync(cfg.db, cfg.user, cfg.password, cfg.role);
           this.conn.querySync('create table PREPARED_TEST_TABLE ( test_field1 INT, test_field2 VARCHAR(10))');
           var sql =  'create or alter procedure TEST_PROC(\n'+
               '"INPUT" varchar(25))\n'+
               'returns (\n'+
               '"OUTPUT" varchar(25))\n'+
               'as\n'+
               'BEGIN\n'+
               '  output = input;\n'+
               '  suspend;\n'+
               'END\n';
           this.conn.querySync(sql);
           callback();
         },
         tearDown: function(callback){
           this.conn.disconnect();
           this.conn = null;
           var conn = new fb_binding.createConnection();
           conn.connectSync(cfg.db, cfg.user, cfg.password, cfg.role);
           conn.querySync('drop table PREPARED_TEST_TABLE');    
           conn.querySync('drop procedure TEST_PROC');    
           conn.disconnect();
           callback();
         },
         commitAll: function(test){
           var data = [
            [1,'string 1'],
            [2,'string 2'],
            [3,'string 3'],
            [4,null]
           ];

           test.expect(2+data.length*2);
           var stmt = this.conn.prepareSync('insert into PREPARED_TEST_TABLE (test_field1, test_field2) values (?,?)');
           test.ok(stmt, 'statement returned');
           var i;
           for(i=0;i<data.length;i++)
           {
            stmt.execSync.apply(stmt,data[i]);
           }
           this.conn.commitSync();
           var res = this.conn.querySync('select * from PREPARED_TEST_TABLE');
           var rows = res.fetchSync('all',false);
           test.equal(data.length,rows.length,'number of records');
           for(i=0;i<data.length;i++)
           {
            test.equal(data[i][0],rows[i][0],'first field');
            test.equal(data[i][1],rows[i][1],'second field');
           }
           test.done();
         },
         commitEvery:function(test){
            var data = [
            [1,'string 1'],
            [2,'string 2'],
            [3,'string 3'],
            [4,null]
           ];
           
           test.expect(3+data.length*2);
           var stmt = this.conn.prepareSync('insert into PREPARED_TEST_TABLE (test_field1, test_field2) values (?,?)');
           test.ok(stmt, 'statement returned');
           var i;
           for(i=0;i<data.length;i++)
           {
            if(!this.conn.inTransaction) this.conn.startTransactionSync();
            stmt.execSync.apply(stmt,data[i]);
            this.conn.commitSync();
           }; 
           

           var stmt = this.conn.prepareSync('select test_field2 from PREPARED_TEST_TABLE where test_field1=?');
           
           test.ok(stmt, 'statement returned');
           
           if(!this.conn.inTransaction) this.conn.startTransactionSync();
           test.ok(this.conn.inTransaction, 'inTransaction');
           for(i=0;i<data.length;i++)
           {
            stmt.execSync(data[i][0]);
            var row = stmt.fetchSync("all",true);
            test.ok(row, 'row returned');
            //console.log(sys.inspect(row));
            test.equal(data[i][1],row[0].TEST_FIELD2,'test_field2 equal');
           }
           test.done();
             
         },
         badArgNum:function(test){
           test.expect(2);
           var stmt = this.conn.prepareSync('insert into PREPARED_TEST_TABLE (test_field1, test_field2) values (?,?)');
           test.ok(stmt, 'statement returned');
           test.throws(function(){
             stmt.execSync(0);
           },'wrong number of arguments');
           test.done();
         },
         asyncExec:function(test){
           test.expect(3);
           var stmt = this.conn.prepareSync('insert into PREPARED_TEST_TABLE (test_field1, test_field2) values (?,?)');
           var data = [1,'boo'];
           stmt.exec(data[0],data[1]);
           var self = this;
           stmt.once('result',function(err){
                test.ok(!err,'no error on insert');
        	var stmt1 = self.conn.prepareSync('select test_field2 from PREPARED_TEST_TABLE');                          
        	stmt1.once('result',function(err){
        	  test.ok(!err,'no error on select');
        	  var row = stmt1.fetchSync("all",false); 
        	  test.equal(data[1],row[0][0],'returned data equal');
        	  test.done();
        	});
        	stmt1.exec();
           });
           
         },
         execProcSync:function(test){
            test.expect(2);
            var stmt = this.conn.prepareSync('execute procedure TEST_PROC(?)');
            var data = 'test';
            var res = stmt.execSync(data);
            test.ok(res,'have result');
            test.equal(res.OUTPUT,data,'returned data equal'); 
            test.done();
         },
         execProcAsync:function(test){
            test.expect(2);
            var stmt = this.conn.prepareSync('execute procedure TEST_PROC(?)');
            var data = 'testAsync';
            stmt.exec(data);
            stmt.once('result',function(err,res){
		test.ok(res,'have result');
        	test.equal(res.OUTPUT,data,'returned data equal'); 
        	test.done();               
            });
         }          
         
});
Esempio n. 14
0
exports['FilterChain()'] = testCase({
    'it should not load any filters if there are none specified': function (test) {
        var config = { beforeUrlExpansionFilters: {}, afterUrlExpansionFilters: {} };
        var chain = new FilterChain(config);

        test.deepEqual([], chain.beforeFilters);
        test.deepEqual([], chain.afterFilters);

        test.done();
    },
    'it should not load any disabled filters': function (test) {
        var config = { beforeUrlExpansionFilters: { hashtag_filter: { enabled: false } }, afterUrlExpansionFilters: { hashtag_filter: { enabled: false } } };
        var chain = new FilterChain(config);

        test.deepEqual([], chain.beforeFilters);
        test.deepEqual([], chain.afterFilters);

        test.done();
    },
    'it should instantiate the specified before filter': function (test) {
        var config = { beforeUrlExpansionFilters: { hashtag_filter: { hashtags: [] } }, afterUrlExpansionFilters: {} };
        var chain = new FilterChain(config);

        test.equals(true, chain.beforeFilters[0] instanceof HashtagFilter);
        test.deepEqual([], chain.afterFilters);

        test.done();
    },
    'it should instantiate the specified after filter': function (test) {
        var config = { beforeUrlExpansionFilters: {}, afterUrlExpansionFilters: { hashtag_filter: { hashtags: [] } } };
        var chain = new FilterChain(config);

        test.deepEqual([], chain.beforeFilters);
        test.equals(true, chain.afterFilters[0] instanceof HashtagFilter);

        test.done();
    }
});
Esempio n. 15
0
exports.autoescape = testCase({
    setUp: function (callback) {
        swig.init({});
        callback();
    },

    on: function (test) {
        var tpl = swig.compile('{% autoescape true %}{{ foo }}{% endautoescape %}');
        test.strictEqual(tpl({ foo: '<\'single\' & "double" quotes>' }), '&lt;&#39;single&#39; &amp; &quot;double&quot; quotes&gt;');
        test.done();
    },

    off: function (test) {
        var tpl = swig.compile('{% autoescape false %}{{ foo }}{% endautoescape %}');
        test.strictEqual(tpl({ foo: '<\'single\' & "double" quotes>' }), '<\'single\' & "double" quotes>');
        test.done();
    },

    'resets after endautoescape': function (test) {
        var tpl = swig.compile('{% autoescape false %}{% endautoescape %}{{ foo }}');
        test.strictEqual(tpl({ foo: '<\'single\' & "double" quotes>' }), '&lt;&#39;single&#39; &amp; &quot;double&quot; quotes&gt;');
        test.done();
    },

    js: function (test) {
        var tpl = swig.compile('{% autoescape true "js" %}{{ foo }}{% endautoescape %}');
        test.strictEqual(tpl({ foo: '"double quotes" and \'single quotes\'' }), '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027');
        test.strictEqual(tpl({ foo: '<script>and this</script>' }), '\\u003Cscript\\u003Eand this\\u003C/script\\u003E');
        test.strictEqual(tpl({ foo: '\\ : backslashes, too' }), '\\u005C : backslashes, too');
        test.strictEqual(tpl({ foo: 'and lots of whitespace: \r\n\t\v\f\b' }), 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008');
        test.strictEqual(tpl({ foo: 'and "special" chars = -1;' }), 'and \\u0022special\\u0022 chars \\u003D \\u002D1\\u003B');
        test.done();
    }
});
var tests = testCase({
  setUp: function(callback) {
    callback();        
  },
  
  tearDown: function(callback) {
    callback();        
  },

  'Should Correctly Generate an Insert Command' : function(test) {
    var full_collection_name = "db.users";
    var insert_command = new InsertCommand({bson_serializer: {BSON:BSON}}, full_collection_name);
    insert_command.add({name: 'peter pan'});
    insert_command.add({name: 'monkey king'});
    // assert the length of the binary
    test.equal(81, insert_command.toBinary().length);
    test.done();
  },

  'Should Correctly Generate an Update Command' : function(test) {
    var full_collection_name = "db.users";
    var flags = UpdateCommand.DB_UPSERT;
    var selector = {name: 'peter pan'};
    var document = {name: 'peter pan junior'};
    // Create the command
    var update_command = new UpdateCommand({bson_serializer: {BSON:BSON}}, full_collection_name, selector, document, flags);
    // assert the length of the binary
    test.equal(90, update_command.toBinary().length);
    test.done();
  },
  
  'Should Correctly Generate a Delete Command' : function(test) {
    var full_collection_name = "db.users";      
    var selector = {name: 'peter pan'};
    // Create the command
    var delete_command = new DeleteCommand({bson_serializer: {BSON:BSON}}, full_collection_name, selector);
    // assert the length of the binary
    test.equal(58, delete_command.toBinary().length);
    test.done();
  },
  
  'Should Correctly Generate a Get More Command' : function(test) {
    var full_collection_name = "db.users";    
    var numberToReturn = 100;
    var cursorId = Long.fromNumber(10000222);
    // Create the command
    var get_more_command = new GetMoreCommand({bson_serializer: {BSON:BSON}}, full_collection_name, numberToReturn, cursorId);
    // assert the length of the binary
    test.equal(41, get_more_command.toBinary().length);
    test.done();
  },
  
  'Should Correctly Generate a Kill Cursors Command' : function(test) {
    Array.prototype.toXml = function() {}    
    var cursorIds = [Long.fromNumber(1), Long.fromNumber(10000222)];
    // Create the command
    var kill_cursor_command = new KillCursorCommand({bson_serializer: {BSON:BSON}}, cursorIds);
    // assert the length of the binary
    test.equal(40, kill_cursor_command.toBinary().length);
    test.done();
  },
  
  'Should Correctly Generate a Query Command' : function(test) {
    var full_collection_name = "db.users";
    var options = QueryCommand.OPTS_SLAVE;
    var numberToSkip = 100;
    var numberToReturn = 200;
    var query = {name:'peter pan'};
    var query_command = new QueryCommand({bson_serializer: {BSON:BSON}}, full_collection_name, options, numberToSkip, numberToReturn, query, null);
    // assert the length of the binary
    test.equal(62, query_command.toBinary().length);
    // Generate command with return field filter
    query_command = new QueryCommand({bson_serializer: {BSON:BSON}}, full_collection_name, options, numberToSkip, numberToReturn, query, { a : 1, b : 1, c : 1});
    test.equal(88, query_command.toBinary().length);
    test.done();
  },
  
  'Should Correctly Generate and parse a Reply Object' : function(test) {
    var reply_message = BinaryParser.fromInt(0) + BSON.encodeLong(Long.fromNumber(1222)) + BinaryParser.fromInt(100) + BinaryParser.fromInt(2);
    reply_message = reply_message + BSON.serialize({name:'peter pan'}) + BSON.serialize({name:'captain hook'});
    var message = BinaryParser.fromInt(reply_message.length + 4*4) + BinaryParser.fromInt(2) + BinaryParser.fromInt(1) + BinaryParser.fromInt(BaseCommand.OP_QUERY) + reply_message;
    // Parse the message into a proper reply object
    var mongo_reply = new MongoReply({bson_deserializer: {BSON:BSON},
      bson_serializer: {BSON:BSON}}, message);
    test.equal(2, mongo_reply.requestId);
    test.equal(1, mongo_reply.responseTo);
    test.equal(0, mongo_reply.responseFlag);
    test.equal(Long.fromNumber(1222).toString(), mongo_reply.cursorId.toString());
    test.equal(100, mongo_reply.startingFrom);
    test.equal(2, mongo_reply.numberReturned);
    test.equal(2, mongo_reply.documents.length);
    test.deepEqual({name:'peter pan'}, mongo_reply.documents[0]);
    test.deepEqual({name:'captain hook'}, mongo_reply.documents[1]);
    test.done();
  },
});
Esempio n. 17
0
var nodeunit = require('nodeunit');

var path = require('path'),
    biorythm = require(path.resolve('libs', 'biorythm'));

var testBirtyday = "19780729",
    testDate = "20151225";

exports['biorythm library'] = nodeunit.testCase({
  'Get biorythm messages': function (test) {
    var messages = biorythm.getBioMessage(testBirtyday);

    test.equal(typeof messages.summary, 'string');
    test.equal(typeof messages.physical, 'string');
    test.equal(typeof messages.emotion, 'string');
    test.equal(typeof messages.intellect, 'string');
    test.done();
  },

  'Get biorythm messages with specific date': function (test) {
    var messages = biorythm.getBioMessage(testBirtyday, testDate);

    test.equal(typeof messages.summary, 'string');
    test.equal(typeof messages.physical, 'string');
    test.equal(typeof messages.emotion, 'string');
    test.equal(typeof messages.intellect, 'string');
    test.done();
  },
});
Esempio n. 18
0
exports['dispatch event'] = testcase({
  setUp: function(cb){
    this.doc = require('../level1/core/files/hc_staff.xml').hc_staff();
    cb();
  },

  tearDown: function(cb){
    _tearDown.call(this, 'doc');
    cb();
  },

  'a null reference passed to dispatchEvent': function (test) {
    var doc = this.doc;
    test.throws(function(){ doc.dispatchEvent(null) }, TypeError, 'should throw an exception');
    // TODO: figure out the best way to test (exception.code == 0) and (exception.message == 'Null event')
    test.done();
  },

  'a created but not initialized event passed to dispatchEvent': function (test) {
    var doc = this.doc,
        event_types = ['Events', 'MutationEvents', 'UIEvents', 'MouseEvents', 'HTMLEvents'];
    test.expect(event_types.length);
    event_types.forEach(function(type){
      test.throws(function(){ doc.dispatchEvent(doc.createEvent(type)) }, doc.defaultView.DOMException, 'should throw an exception for ' + type);
    })
    test.done();
  },

  'an Event initialized with a empty name passed to dispatchEvent': function (test) {
    var doc = this.doc,
        event = doc.createEvent("Events");
    event.initEvent("",false,false);
    test.throws(function(){ doc.dispatchEvent(event) }, doc.defaultView.DOMException, 'should throw an exception');
    test.done();
  },

  // An EventListener registered on the target node with capture false, should receive any event fired on that node.
  'EventListener with capture false': function (test) {
    var monitor = new EventMonitor();
    this.doc.addEventListener("foo", monitor.handleEvent, false);
    var event = this.doc.createEvent("Events");
    event.initEvent("foo",true,false);
    test.expect(7);
    test.strictEqual(event.eventPhase, 0);
    test.strictEqual(event.currentTarget, null);
    this.doc.dispatchEvent(event);
    test.equal(monitor.atEvents.length, 1, 'should receive atEvent');
    test.equal(monitor.bubbledEvents.length, 0, 'should not receive at bubble phase');
    test.equal(monitor.capturedEvents.length, 0, 'should not receive at capture phase');
    test.strictEqual(event.eventPhase, 0);
    test.strictEqual(event.currentTarget, null);
    test.done();
  },

  // An EventListener registered on the target node with capture true, should receive any event fired on that node.
  'EventListener with capture true': function (test) {
    var monitor = new EventMonitor();
    this.doc.addEventListener("foo", monitor.handleEvent, true);
    var event = this.doc.createEvent("Events");
    event.initEvent("foo",true,false);
    test.expect(7);
    test.strictEqual(event.eventPhase, 0);
    test.strictEqual(event.currentTarget, null);
    this.doc.dispatchEvent(event);
    test.equal(monitor.atEvents.length, 1, 'should receive atEvent');
    test.equal(monitor.bubbledEvents.length, 0, 'should not receive at bubble phase');
    test.equal(monitor.capturedEvents.length, 0, 'should not receive at capture phase');
    test.strictEqual(event.eventPhase, 0);
    test.strictEqual(event.currentTarget, null);
    test.done();
  },

  // The same monitor is registered twice and an event is dispatched.  The monitor should receive only one handleEvent call.
  'EventListener is registered twice': function (test) {
    var monitor = new EventMonitor();
    this.doc.addEventListener("foo", monitor.handleEvent, false);
    this.doc.addEventListener("foo", monitor.handleEvent, false);
    var event = this.doc.createEvent("Events");
    event.initEvent("foo",true,false);
    this.doc.dispatchEvent(event);
    test.expect(3);
    test.equal(monitor.atEvents.length, 1, 'should receive atEvent only once');
    test.equal(monitor.bubbledEvents.length, 0, 'should not receive at bubble phase');
    test.equal(monitor.capturedEvents.length, 0, 'should not receive at capture phase');
    test.done();
  },

  // The same monitor is registered twice, removed once, and an event is dispatched. The monitor should receive only no handleEvent calls.
  'EventListener is registered twice, removed once': function (test) {
    var monitor = new EventMonitor();
    this.doc.addEventListener("foo", monitor.handleEvent, false);
    this.doc.addEventListener("foo", monitor.handleEvent, false);
    this.doc.removeEventListener("foo", monitor.handleEvent, false);
    var event = this.doc.createEvent("Events");
    event.initEvent("foo",true,false);
    this.doc.dispatchEvent(event);
    test.equal(monitor.allEvents.length, 0, 'should not receive any handleEvent calls');
    test.done();
  },

  // A monitor is added, multiple calls to removeEventListener are made with similar but not identical arguments, and an event is dispatched.
  // The monitor should receive handleEvent calls.
  'EventListener is registered, other listeners (similar but not identical) are removed': function (test) {
    var monitor = new EventMonitor();
    var other = {handleEvent: function(){}}
    this.doc.addEventListener("foo", monitor.handleEvent, false);
    this.doc.removeEventListener("foo", monitor.handleEvent, true);
    this.doc.removeEventListener("food", monitor.handleEvent, false);
    this.doc.removeEventListener("foo", other.handleEvent, false);
    var event = this.doc.createEvent("Events");
    event.initEvent("foo",true,false);
    this.doc.dispatchEvent(event);
    test.equal(monitor.allEvents.length, 1, 'should still receive the handleEvent call');
    test.done();
  },

  // Two listeners are registered on the same target, each of which will remove both itself and the other on the first event.  Only one should see the event since event listeners can never be invoked after being removed.
  'two EventListeners which both handle by unregistering itself and the other': function (test) {
    // setup
    var es = [];
    var ls = [];
    var EventListener1 = function() { ls.push(this); }
    var EventListener2 = function() { ls.push(this); }
    EventListener1.prototype.handleEvent = function(event) { _handleEvent(event); }
    EventListener2.prototype.handleEvent = function(event) { _handleEvent(event); }
    var _handleEvent = function(event) {
      es.push(event);
      ls.forEach(function(l){
        event.currentTarget.removeEventListener("foo", l.handleEvent, false);
      })
    }
    // test
    var listener1 = new EventListener1();
    var listener2 = new EventListener2();
    this.doc.addEventListener("foo", listener1.handleEvent, false);
    this.doc.addEventListener("foo", listener2.handleEvent, false);
    var event = this.doc.createEvent("Events");
    event.initEvent("foo",true,false);
    this.doc.dispatchEvent(event);
    test.equal(es.length, 1, 'should only be handled by one EventListener');
    test.done();
  }
})
module.exports = testCase({
    
    setUp : function(callback){
      converterManager = {};
      cn = contentNegotiation.create(converterManager);
      callback();
    },
    
    'should allow content negotiation request': function (assert) {
      request = {
        headers:{
          "content-type":"application/json;xsd=1"
        },
        body : '{"client":{"id":1,"name":"carlos"}}'
      };
      
      invoked = false;
      chain = {
        doChain : function(request,response){
        invoked = true;
        }
      };
      
      converterManager.getConverter = function(format){
        return {
          toObject : function(text){
            return JSON.parse(text);
          },
          toString : function(obj){
            if (!obj || obj == null ) return "";
            return JSON.stringify(obj);
          }
        }
      }
      
      response= {data:{name:'car'}};
      
      cn.execute(request,response,chain);
      assert.ok(request.data != null);
      assert.ok(request.data.client != null);
      assert.ok(request.data.client.id != null);
      assert.ok(request.data.client.name != null);
      assert.equal(request.data.client.id,1);
      assert.equal(request.data.client.name,'carlos');
      assert.ok(invoked);
      assert.equal(response.body,'{"name":"car"}');
      
      
      assert.done();
    },
    
    
    'should return response is content-type not defined or not supported' : function(assert){
      chain = {
        doChain : function(request,response){
        }
      };
      request = {
        headers : {}
      };
      response ={};
      
      converterManager.getConverter = function(format){
      }
      
      cn.execute(request,response,chain);
      assert.equal(response.statusCode,500);
      assert.equal(response.body,"content-type is not informed");
      assert.done();
    }
});
Esempio n. 20
0
exports['Select'] = nodeunit.testCase({
  setUp: function (callback) {
    var self = this;

    this.Phone = persist.define("Phone", {
      "number": { type: type.STRING, dbColumnName: 'numbr' }
    });

    this.Person = persist.define("Person", {
      "name": type.STRING,
      "age": type.INTEGER
    }).hasMany(this.Phone);

    this.Person.onLoad = function (person) {
      person.nameAndAge = person.name + ": " + person.age;
    };

    this.Company = persist.define("Company", {
      "name": type.STRING
    }).hasMany(this.Person, { through: "CompanyPerson" });

    this.Phone.hasOne(this.Person, { name: "modifiedBy", foreignKey: "modified_by_person_id" });

    testUtils.connect(persist, {}, function (err, connection) {
      if (err) {
        console.log(err);
        return;
      }

      self.connection = connection;
      self.person1 = new self.Person({ name: "Bob O'Neill", age: 21 });
      self.person2 = new self.Person({ name: "john", age: 23 });
      self.phone1 = new self.Phone({ person: self.person1, number: '111-2222', modifiedBy: self.person1 });
      self.phone2 = new self.Phone({ person: self.person1, number: '222-3333', modifiedBy: self.person1 });
      self.phone3 = new self.Phone({ person: self.person2, number: '333-4444', modifiedBy: self.person1 });
      self.company1 = new self.Company({ people: [self.person1, self.person2], name: "Near Infinity" });
      self.connection.save([self.person1, self.person2, self.phone1, self.phone2, self.phone3, self.company1], function (err) {
        if (err) {
          console.log(err);
          return;
        }
        callback();
      });
    });
  },

  tearDown: function (callback) {
    if (this.connection) {
      this.connection.close();
    }
    callback();
  },

  "all": function (test) {
    this.Person.using(this.connection).all(function (err, people) {
      if (err) {
        console.error(err);
        return;
      }
      test.equals(people.length, 2);
      test.equals(people[0].name, "Bob O'Neill");
      console.log(people[0].nameAndAge, "Bob O\'Neill: 21");
      test.equals(JSON.stringify(people[0]), '{"phones":{},"companies":{},"modifiedBy":{},"name":"Bob O\'Neill","age":21,"id":' + people[0].id + ',"nameAndAge":"Bob O\'Neill: 21"}');
      test.equals(people[1].name, 'john');

      test.done();
    });
  },

  "all with include": function (test) {
    this.Person
      .include(["phones", "companies"])
      .all(this.connection, function (err, people) {
        if (err) {
          console.error(err);
          return;
        }

        people.sort(function (a, b) { return a.name > b.name; });
        test.equals(people.length, 2);
        test.equals(people[0].name, "Bob O'Neill");
        test.equals(people[0].phones.length, 2);
        var phones = people[0].phones.sort(function (a, b) { return a.number > b.number; });
        test.equals(phones[0].number, "111-2222");
        test.equals(phones[1].number, "222-3333");
        test.equals(people[0].companies.length, 1);
        test.equals(people[0].companies[0].name, "Near Infinity");
        //TODO: console.log(JSON.stringify(people[0]));
        //TODO: test.equals(JSON.stringify(people[0]), '{"name":"Bob O\'Neill","age":21,"id":1,"phones":[{"number":"111-2222"},{"number":"222-3333"}]}');
        test.equals(people[1].name, 'john');
        test.equals(people[1].phones.length, 1);
        test.equals(people[1].phones[0].number, "333-4444");
        test.equals(people[1].companies.length, 1);
        test.equals(people[1].companies[0].name, "Near Infinity");

        test.done();
      });
  },

  "include one from the many": function (test) {
    this.Phone
      .include("person")
      .include("modifiedBy")
      .where("numbr = ?", "111-2222")
      .first(this.connection, function (err, phone) {
        if (err) {
          console.error(err);
          return;
        }

        test.equals(phone.number, "111-2222");
        test.ok(phone.person);
        test.equals(phone.person.name, "Bob O'Neill");
        test.ok(phone.modifiedBy);
        test.equals(phone.modifiedBy.name, "Bob O'Neill");

        test.done();
      });
  },

  "where query for associated data": function (test) {
    this.Person
      .include("phones")
      .where("phones.number = ?", "111-2222")
      .first(this.connection, function (err, person) {
        if (err) {
          console.error(err);
          return;
        }

        test.equals(person.name, "Bob O'Neill");

        test.done();
      });
  },

  "where query for associated data (count)": function (test) {
    this.Person
      .include("phones")
      .where("phones.number = ?", "111-2222")
      .count(this.connection, function (err, count) {
        if (err) {
          console.error(err);
          return;
        }

        test.equals(count, 1);

        test.done();
      });
  },

  "include with conflicting column names": function (test) {
    var self = this;
    this.Person.using(this.connection).where("name = ?", "Bob O'Neill").first(function (err, p1) {
      if (err) {
        console.error(err);
        return;
      }

      self.Person
        .include("phones")
        .where("id = ?", p1.id)
        .first(self.connection, function (err, p2) {
          if (err) {
            console.error(err);
            return;
          }

          test.ok(p2);
          test.ok(p2.phones);

          test.done();
        });
    });
  },

  "include with no children": function (test) {
    var self = this;
    this.Phone.deleteAll(this.connection, function (err) {
      if (err) {
        console.error(err);
        return;
      }

      self.Person
        .include("phones")
        .where("name = ?", "Bob O'Neill")
        .first(self.connection, function (err, p2) {
          if (err) {
            console.error(err);
            return;
          }

          test.ok(p2);
          test.ok(p2.phones);
          test.equal(p2.phones.length, 0);

          test.done();
        });
    });
  },

  "get by id": function (test) {
    var self = this;
    var person1Id = self.person1.id;

    this.Person
      .getById(this.connection, person1Id, function (err, person) {
        if (err) {
          console.error(err);
          return;
        }

        test.equals(person.name, "Bob O'Neill");

        test.done();
      });
  },

  "get by id with include": function (test) {
    var self = this;
    var person1Id = self.person1.id;

    this.Person
      .include("phones")
      .getById(this.connection, person1Id, function (err, person) {
        if (err) {
          console.error(err);
          return;
        }

        test.equals(person.name, "Bob O'Neill");
        test.equals(person.phones.length, 2);

        test.done();
      });
  },

  "count": function (test) {
    this.Person.using(this.connection).count(function (err, count) {
      if (err) {
        console.error(err);
        return;
      }
      test.equals(count, 2);
      test.done();
    });
  },

  "order by desc": function (test) {
    this.Person.using(this.connection).orderBy("name", persist.Descending).all(function (err, people) {
      test.ifError(err);
      test.equals(people.length, 2);
      test.equals(people[0].name, 'john');
      test.equals(people[1].name, "Bob O'Neill");

      test.done();
    });
  },

  "each": function (test) {
    var count = 0;
    this.Person.using(this.connection).orderBy("name").each(function (err, person) {
      test.ifError(err);
      if (count == 0) {
        test.equals(person.name, "Bob O'Neill");
        count++;
      } else if (count == 1) {
        test.equals(person.name, 'john');
        count++;
      } else {
        throw new Error("Invalid count");
      }
    }, function () { test.done(); });
  },

  "where": function (test) {
    this.Person.using(this.connection).where("name = ?", "Bob O'Neill").all(function (err, people) {
      test.ifError(err);
      test.equals(people.length, 1);
      test.equals(people[0].name, "Bob O'Neill");

      test.done();
    });
  },

  "whereIn count": function (test) {
    this.Person.using(this.connection).include("phones").whereIn("phones.number", ["111-2222", "222-3333"]).count(function (err, count) {
      test.ifError(err);
      test.equals(count, 2);

      test.done();
    });
  },

  "whereIn names": function (test) {
    this.Person.using(this.connection).include("phones").whereIn("phones.number", ["111-2222", "222-3333"]).all(function (err, people) {
      test.ifError(err);
      test.equals(people.length, 1);
      test.equals(people[0].name, "Bob O'Neill");

      test.done();
    });
  },


  "hash based where": function (test) {
    this.Person.using(this.connection).where({'name': "Bob O'Neill", 'age': '21'}).all(function (err, people) {
      test.ifError(err);
      test.equals(people.length, 1);
      test.equals(people[0].name, "Bob O'Neill");

      test.done();
    });
  },

  "first": function (test) {
    this.Person.using(this.connection).where("name = ?", "Bob O'Neill").first(function (err, person) {
      test.ifError(err);
      test.ok(person);
      test.equals(person.name, "Bob O'Neill");
      test.done();
    });
  },

  "first with include": function (test) {
    var self = this;
    this.Person
      .include("phones")
      .where("name = ?", "Bob O'Neill").first(self.connection, function (err, person) {
        test.ifError(err);
        test.ok(person);
        test.equals(person.name, "Bob O'Neill");
        test.equals(person.phones.length, 2);
        test.done();
      });
  },

  "first that doesn't match anything": function (test) {
    this.Person.using(this.connection).where("name = ?", "Bad Name").first(function (err, person) {
      test.ifError(err);
      test.equals(person, null);
      test.done();
    });
  },

  "last": function(test) {
    this.Person.using(this.connection).last(function (err, person) {
      test.ifError(err);
      test.ok(person);
      test.equals(person.name, "john");
      test.done();
    });
  },

  "last with include": function (test) {
    var self = this;
    this.Person
      .include("phones")
      .last(self.connection, function (err, person) {
        test.ifError(err);
        test.ok(person);
        test.equals(person.name, "john");
        test.equals(person.phones.length, 1);
        test.done();
      });
  },

  "last that doesn't match anything": function (test) {
    this.Person.using(this.connection).where("name = ?", "Bad Name").last(function (err, person) {
      test.ifError(err);
      test.equals(person, null);
      test.done();
    });
  },

  "where empty string": function (test) {
    this.Person.using(this.connection).where("name = ?", "").all(function (err, people) {
      test.ifError(err);
      test.equals(people.length, 0);
      test.done();
    });
  },

  "min": function (test) {
    this.Person.using(this.connection).min("age", function (err, age) {
      if (err) {
        console.log(err);
        return;
      }
      test.equals(age, 21);
      test.done();
    });
  },

  "max": function (test) {
    this.Person.using(this.connection).max("age", function (err, age) {
      if (err) {
        console.log(err);
        return;
      }
      test.equals(age, 23);
      test.done();
    });
  },

  "sum": function (test) {
    this.Person.using(this.connection).sum("age", function (err, age) {
      if (err) {
        console.log(err);
        return;
      }
      test.equals(age, 44);
      test.done();
    });
  },

  "limit": function (test) {
    this.Phone.limit(1, 1).orderBy("number").all(this.connection, function (err, phones) {
      if (err) {
        console.log(err);
        return;
      }
      test.equals(phones.length, 1);
      test.equals(phones[0].number, "222-3333");
      test.done();
    });
  },

  "associated data": function (test) {
    var self = this;
    this.Person.using(this.connection).where("name = ?", "Bob O'Neill").first(function (err, person) {
      if (err) {
        console.log(err);
        return;
      }
      person.phones.all(function (err, phones) {
        if (err) {
          console.log(err);
          return;
        }
        test.equals(phones.length, 2);
        test.equals(phones[0].number, '111-2222');
        test.equals(phones[0].personId, person.id);
        test.equals(phones[1].number, '222-3333');
        test.equals(phones[1].personId, person.id);

        phones[0].person.first(function (err, p) {
          if (err) {
            console.log(err);
            return;
          }

          test.equals(p.name, "Bob O'Neill");

          test.done();
        });
      });
    });
  },

  "JSON datatype": function (test) {
    var self = this;
    MyPerson = persist.define("Person", {
      "name": type.STRING,
      "txt": type.JSON
    });

    var person1 = new MyPerson({"name": "joe1", "txt": '{"address": "123 Elm St", "emails": [ "*****@*****.**", "*****@*****.**" ]}'});
    var person2 = new MyPerson({"name": "joe2", "txt": 'invalid JSON'});

    this.connection.save([person1, person2], function (err) {
      if (err) {
        console.log(err);
        return;
      }

      MyPerson.where("name = ?", "joe1").first(self.connection, function (err, p) {
        if (err) {
          console.log(err);
          return;
        }

        test.ok(p.txt);
        test.equal(p.txt.address, '123 Elm St');
        test.equal(p.txt.emails.length, 2);
        test.equal(p.txt.emails[0], '*****@*****.**');
        test.equal(p.txt.emails[1], '*****@*****.**');

        MyPerson.where("name = ?", "joe2").first(self.connection, function (err, p) {
          if (err) {
            console.log(err);
            return;
          }

          test.ok(p.txt);
          test.equal(p.txt, 'invalid JSON');

          test.done();
        });
      });
    });
  }

});
Esempio n. 21
0
var util = require('sys'),
    Events = require('events').EventEmitter,
    nodeunit  = require('nodeunit'),
    testCase  = require('nodeunit').testCase,
    StompFrame = require('../lib/frame').StompFrame;

// Mock net object so we never try to send any real data
var connectionObserver = new Events();
connectionObserver.writeBuffer = [];
connectionObserver.write = function(data) {
    this.writeBuffer.push(data);
};

module.exports = testCase({

  setUp: function(callback) {
    callback();
  },

  tearDown: function(callback) {
    connectionObserver.writeBuffer = [];
    callback();
  }

});
Esempio n. 22
0
exports['Insert'] = nodeunit.testCase({
  setUp: function (callback) {
    var self = this;

    this.Address = persist.define("Address", {
      "address": type.STRING,
      "city": type.STRING,
      "state": type.STRING,
      "zip": type.STRING
    });
    
    this.Phone = persist.define("Phone", {
      "number": { type: type.STRING, dbColumnName: 'numbr' }
    });

    this.PrimaryKeyTest = persist.define("PrimaryKeyTest", {
      "id": { dbColumnName: 'my_pk_id', primaryKey: true },
      "name": type.STRING
    });

    this.testDate1 = new Date(2011, 10, 30, 12, 15);
    this.testDate2 = new Date(2011, 10, 30, 12, 15);

    this.Person = persist.define("Person", {
      "name": type.STRING,
      "age": type.INTEGER,
      "createdDate": { type: persist.DateTime, defaultValue: function () { return self.testDate1 } },
      "lastUpdated": { type: persist.DateTime }
    })
      .hasMany(this.Phone)
      .hasMany(this.Address)
      .on('beforeSave', function (obj) {
        obj.lastUpdated = self.testDate2;
      })
      .on('afterSave', function (obj) {
        if (!obj.updateCount) {
          obj.updateCount = 0;
        }
        obj.updateCount++;
      });

    this.Person.validate = function (obj, connection, callback) {
      if (obj.name === 'bad name') {
        return callback(false, 'You had a bad name');
      }
      return callback(true);
    };
    
    this.Address.validate = function(obj, connection, callback) {
      var errors = [];
      
      if (obj.address === 'bad address') {
        errors.push({address: 'You had a bad address'});
      }
      
      if (obj.city === '') {
        errors.push({city: 'City cannot be blank'});
      }
      
      if (obj.state === 'ABC') {
        errors.push({state: 'State is invalid'});
      }
      
      var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
      if (!zipCodePattern.test(obj.zip)) {
        errors.push({zip: 'Invalid zip code'});
      }
      
      if (errors.length > 0) {
        return callback(false, errors);
      }
      
      return callback(true);
    };

    testUtils.connect(persist, {}, function (err, connection) {
      self.connection = connection;
      callback();
    });
  },

  tearDown: function (callback) {
    if (this.connection) {
      this.connection.close();
    }
    callback();
  },

  "primary key without auto increment": function (test) {
    var self = this;
    var ID = 1001,
        item = new this.PrimaryKeyTest({id: ID, name: 'item-1001'});
    self.connection.save(item, function (err, obj) {
      if (err) {
        return console.log(err);
      }

      test.equals(obj.id, ID);

      self.PrimaryKeyTest.all(self.connection, function (err, qItems) {
        if (err) {
          return console.log(err);
        }
        test.equals(qItems.length, 1);
        test.equals(qItems[0].id, ID);

        test.done();
      });
    });
  },

  "primary key not named id": function (test) {
    var self = this;
    var item1 = new this.PrimaryKeyTest({name: 'item1'});
    var item2 = new this.PrimaryKeyTest({name: 'item2'});
    self.connection.save([item1, item2], function (err) {
      if (err) {
        return console.log(err);
      }

      self.PrimaryKeyTest.all(self.connection, function (err, items) {
        if (err) {
          return console.log(err);
        }

        test.equals(items.length, 2);
        test.equals(items[0].name, 'item1');
        test.ok(items[0].id);
        test.equals(items[1].name, 'item2');
        test.ok(items[1].id);
        var item2Id = items[1].id;

        items[0].delete(self.connection, function (err) {
          if (err) {
            return console.log(err);
          }

          items[1].name = 'only item';
          items[1].save(self.connection, function (err) {
            if (err) {
              return console.log(err);
            }

            self.PrimaryKeyTest.all(self.connection, function (err, items) {
              if (err) {
                return console.log(err);
              }

              test.equals(items.length, 1);
              test.equals(items[0].name, 'only item');
              test.equals(items[0].id, item2Id);

              test.done();
            });
          });
        });
      });
    });
  },

  "save with no associations": function (test) {
    var self = this;
    var person1 = new this.Person({ name: "Bob O'Neill" });

    person1.save(self.connection, function (err, p) {
      test.ifError(err);
      assert.isNotNullOrUndefined(p.id, "p.id is null or undefined");
      test.equals(p.name, "Bob O'Neill");
      test.equals(p.createdDate, self.testDate1);
      test.equals(p.lastUpdated, self.testDate2);
      test.equals(p.updateCount, 1);

      person1.save(self.connection, function (err, p) {
        test.equals(p.updateCount, 2);
        test.done();
      });
    });
  },

  "new person age set to 0": function (test) {
    var self = this;
    var person1 = new this.Person({ name: "Bob O'Neill", age: 0 });

    person1.save(self.connection, function (err, p) {
      test.ifError(err);
      assert.isNotNullOrUndefined(p.id, "p.id is null or undefined");
      test.equals(p.name, "Bob O'Neill");
      test.equals(p.age, 0);
      test.done();
    });
  },

  "validation with single message": function (test) {
    var self = this;
    var person1 = new this.Person({ name: "bad name", age: 0 });

    person1.save(self.connection, function (err, p) {
      test.equals('Validation failed: You had a bad name', err.message);
      test.done();
    });
  },
  
  "validation with custom object": function (test) {
    var self = this;
    var address1 = new this.Address({address: 'bad address',
                                     city: '',
                                     state: 'ABC',
                                     zip: 'abcde'});
    
    address1.save(self.connection, function(err, p) {
      test.equals('You had a bad address', err[0].address);
      test.equals('City cannot be blank', err[1].city);
      test.equals('State is invalid', err[2].state);
      test.equals('Invalid zip code', err[3].zip);
      test.done();
    });
  }

});
Esempio n. 23
0
var testCase = require('nodeunit').testCase,
    linkHelper = require('../../lib/link_helper');

const URL_ONE = 'http://example.com';
const URL_TWO = 'http://example.org';

exports['cleanUrls'] = testCase({
    'returns the same urls if they are clean': function (test) {
        var urls = ['http://example.com', 'http://example.org'];
        var expectedUrls = ['http://example.com/', 'http://example.org/'];
        test.deepEqual(expectedUrls, linkHelper.cleanUrls(urls));
        test.done();
    },
    'removes feedburner params': function (test) {
        var urls = ['http://x.ch?utm_campaign=test', 'http://x.ch?utm_source=test', 'http://x.ch?utm_medium=test', 'http://x.ch?utm_content=test'];
        var expectedUrls = ['http://x.ch/', 'http://x.ch/', 'http://x.ch/', 'http://x.ch/'];
        test.deepEqual(expectedUrls, linkHelper.cleanUrls(urls));
        test.done();
    }
});

exports['linkUrls'] = testCase({
    'text without any urls': function (test) {
        var text = 'hello world';
        test.equals(text, linkHelper.linkUrls(text, [], []));
        test.done();
    },
    'text with a single url': function (test) {
        var text = 'an url: http://example.com';
        test.equals('an url: <a href="http://example.com">http://example.com</a>', linkHelper.linkUrls(text, ['http://example.com'], ['http://example.com']));
        test.done();
module.exports = testCase({
  setUp: function (callback) {
    this.connection = mongoose.createConnection('mongodb://localhost/database_cleaner');
    this.connection.db.createCollection("database_cleaner_collection", null, function (err, collection) {
      collection.insertAll([{a:1}, {b:2}], function() {
        callback();
      });
    });
  },
  tearDown: function (callback) {
    this.connection.close();
    this.connection = null;
    callback();
  },
  'should delete all collections items': function(test) {
    var db = this.connection.db;
    databaseCleaner.clean(db, function () {
      db.collections( function (skip, collections) {
        var total_collections = collections.length;
        collections.forEach(function (collection) {
          if (collection.collectionName != 'system.indexes') {
            collection.count({}, function (err, count) {
              test.equal(count, 0);
              total_collections--;
              if (total_collections <= 0) {
                test.done();
              }
            });
          } else { 
            total_collections--; 
          }
        });
      });
    });
  },
  'should not delete system.indexes collection': function(test) {
    var db = this.connection.db;
    databaseCleaner.clean(db, function () {
      db.collection('system.indexes', function (skip, collection) {
        collection.count({}, function (err, count) {
          test.ok(count > 0);
          test.done();
        });
      });
    });
  }
});
Esempio n. 25
0
exports.Tags = testCase({
    'undefined tag throws error': function (test) {
        test.throws(function () {
            parser.parse('{% foobar %}', {});
        }, Error);
        test.done();
    },

    'basic tag': function (test) {
        var output = parser.parse('{% blah %}', { blah: {} });
        test.deepEqual([{
            type: parser.TOKEN_TYPES.LOGIC,
            line: 1,
            name: 'blah',
            args: [],
            compile: {},
            strip: { before: false, after: false, start: false, end: false },
            parent: []
        }], output);

        output = parser.parse('{% blah "foobar" %}', { blah: {} });
        test.deepEqual([{
            type: parser.TOKEN_TYPES.LOGIC,
            line: 1,
            name: 'blah',
            args: ['"foobar"'],
            compile: {},
            strip: { before: false, after: false, start: false, end: false },
            parent: []
        }], output, 'args appended');

        output = parser.parse('{% blah "foobar" barfoo %}', { blah: {} });
        test.deepEqual([{
            type: parser.TOKEN_TYPES.LOGIC,
            line: 1,
            name: 'blah',
            args: ['"foobar"', 'barfoo'],
            compile: {},
            strip: { before: false, after: false, start: false, end: false },
            parent: []
        }], output, 'multiple args appended');

        test.done();
    },

    'basic tag with ends': function (test) {
        var output = parser.parse('{% blah %}{% endblah %}', { blah: { ends: true } });
        test.deepEqual([{
            type: parser.TOKEN_TYPES.LOGIC,
            line: 1,
            name: 'blah',
            args: [],
            compile: { ends: true },
            tokens: [],
            strip: { before: false, after: false, start: false, end: false },
            parent: []
        }], output);
        test.done();
    },

    'multi-line tag': function (test) {
        var output = parser.parse('{% blah \n arg1 %}{% endblah\n %}', { blah: { ends: true } });
        test.deepEqual([{
            type: parser.TOKEN_TYPES.LOGIC,
            line: 1,
            name: 'blah',
            args: ['arg1'],
            compile: { ends: true },
            tokens: [],
            strip: { before: false, after: false, start: false, end: false },
            parent: []
        }], output);
        test.done();
    },

    'line number included in token': function (test) {
        var output = parser.parse('hi!\n\n\n{% blah %}{% endblah %}', { blah: { ends: true } });
        test.deepEqual({
            type: parser.TOKEN_TYPES.LOGIC,
            line: 4,
            name: 'blah',
            args: [],
            compile: { ends: true },
            tokens: [],
            strip: { before: false, after: false, start: false, end: false },
            parent: []
        }, output[1]);
        test.done();
    },

    'throws if should have end but no end found': function (test) {
        test.throws(function () {
            parser.parse('{% blah %}', { blah: { ends: true }});
        }, Error);
        test.done();
    },

    'throws if not end but end found': function (test) {
        test.throws(function () {
            parser.parse('{% blah %}{% endblah %}', { blah: {}});
        }, Error);
        test.done();
    },

    'throws on unbalanced end tag': function (test) {
        test.throws(function () {
            parser.parse('{% blah %}{% endfoo %}', { blah: { ends: true }, foo: { ends: true }});
        }, Error);
        test.done();
    },

    'tag with contents': function (test) {
        var output = parser.parse('{% blah %}hello{% endblah %}', { blah: { ends: true } });
        test.deepEqual([{
            type: parser.TOKEN_TYPES.LOGIC,
            line: 1,
            name: 'blah',
            args: [],
            compile: { ends: true },
            tokens: ['hello'],
            strip: { before: false, after: false, start: false, end: false },
            parent: []
        }], output);
        test.done();
    },

    'arguments': function (test) {
        var output = parser.parse('{% foo "hi" %}', { foo: {} });
        test.deepEqual(output[0].args, ['"hi"'], 'string');

        output = parser.parse('{% foo "hi mom" %}', { foo: {} });
        test.deepEqual(output[0].args, ['"hi mom"'], 'string with space');

        output = parser.parse('{% foo "{" "[" & ^ ; * , a "]" "}" %}', { foo: {} });
        test.deepEqual(output[0].args, ['"{"', '"["', '&', '^', ';', '*', ',', 'a', '"]"', '"}"'], 'random chars');

        output = parser.parse('{% foo "hi,mom" %}', { foo: {} });
        test.deepEqual(output[0].args, ['"hi,mom"'], 'string with comma');

        output = parser.parse('{% foo "hi\", \"mom" %}', { foo: {} });
        test.deepEqual(output[0].args, ['"hi\", \"mom"'], 'double-quote string with comma');

        output = parser.parse("{% foo 'hi\', \'mom' %}", { foo: {} });
        test.deepEqual(output[0].args, ['\'hi\', \'mom\''], 'single-quote string with comma');

        output = parser.parse("{% foo [] %}", { foo: {} });
        test.deepEqual(output[0].args, ['[]'], 'empty array');

        output = parser.parse("{% foo {} %}", { foo: {} });
        test.deepEqual(output[0].args, ['{}'], 'empty object');

        output = parser.parse("{% foo ['hi', 'your', 'mom'] %}", { foo: {} });
        test.deepEqual(output[0].args, ['[\'hi\', \'your\', \'mom\']'], 'array');

        output = parser.parse("{% foo { 'foo': 1, 'bar': true } %}", { foo: {} });
        test.deepEqual(output[0].args, ['{ \'foo\': 1, \'bar\': true }'], 'object');

        output = parser.parse("{% foo { 'bar': true } 'foo' [] %}", { foo: {} });
        test.deepEqual(output[0].args, ['{ \'bar\': true }', "'foo'", '[]'], 'combo');

        test.done();
    },

    'bad string arguments throws': function (test) {
        test.throws(function () {
            parser.parse('{% foo "blah is foo %}', { foo: {} });
        });
        test.done();
    }
});
Esempio n. 26
0
module.exports = testCase({

  setUp: function(callback) {
    // Stub out setInterval()
    this._orig_setInterval = setInterval;
    setInterval = function(){};
    this.http_server = {};
    this.obj_ut = new LogServer(this.http_server);
    callback();
  },

  tearDown: function(callback) {
    setInterval = this._orig_setInterval;
    callback();
  },

  test_constructor: function(test) {
    test.deepEqual(this.http_server, this.obj_ut.http_server);
    test.deepEqual({}, this.obj_ut.nodes);
    test.deepEqual({}, this.obj_ut.web_clients);
    test.equal(0, this.obj_ut.message_count);
    test.done();
  },

  test_listen: function(test) {
    // Stub out Socket.io
    var io_listening = false;
    io.listen = function() {
      io_listening = true;
    }

    // Stub out http server
    var http_listening = false;
    this.obj_ut.http_server.listen = function() {
      http_listening = true;
    }

    // Stub out register()
    var registered = false;
    this.obj_ut.register = function() {
      registered = true;
    }

    this.obj_ut.listen();
    test.ok(io_listening);
    test.ok(http_listening);
    test.ok(registered);
    test.done();
  },

  test_announce_node: function(test) {
    // Stub out models.Node()
    _node.Node = function(nlabel, logs, web_client, log_server) {
      this.nlabel = nlabel;
      this.logs = logs;
      this.web_client = web_client;
      this.log_server = log_server;
    }

    // Test socket.io client
    var test_client = {
      sent_messages: [],
      send: function(msg) {
        this.sent_messages.push(msg);
      },
      nlabel: 'node1'
    }

    // Test server message
    var server_message = {
      label: 'node1',
      logs: {'log1': {}, 'log2': {}}
    }

    // Fake out web_clients
    var fake_web_client = {
      node: null,
      add_node: function(node) {
        this.node = node;
      }
    }
    this.obj_ut.web_clients = [fake_web_client, fake_web_client];
    this.obj_ut.announce_node(test_client, server_message);
    var test_node = this.obj_ut.nodes[test_client.nlabel]
    test.equal(test_client.nlabel, test_node.nlabel);
    test.deepEqual(server_message.logs, test_node.logs);
    test.deepEqual(test_client, test_node.web_client);
    test.deepEqual(this.obj_ut, test_node.log_server);
    __(this.obj_ut.web_clients).each(function(wc) {
      test.ok(wc.node);
    });

    // Announce node that already exists
    var new_node_created = false;
    _node.Node = function(nlabel, logs, web_client, log_server) {
      new_node_created = true;
    }
    this.obj_ut.announce_node(test_client, server_message);
    test.deepEqual([{
      type: 'node_already_exists'
    }], test_client.sent_messages);
    test.ok(!new_node_created);
    test.done();
  },

  test_announce_web_client: function(test) {
    // Stub out models.WebClient()
    _wc.WebClient = function(web_client, log_server) {
      this.web_client = web_client;
      this.log_server = log_server;
      this.nodes = [];
      this.add_node = function(node) {
        this.nodes.push(node);
      }
    }

    // Test socket.io client
    var test_client = {
      sessionId: 666
    }

    // Fake nodes
    this.obj_ut.nodes = {
      'node1' : 'node1_object',
      'node2' : 'node2_object'
    }

    this.obj_ut.announce_web_client(test_client);
    var web_client = this.obj_ut.web_clients[666];
    test.deepEqual(test_client, web_client.web_client);
    test.deepEqual(this.obj_ut, web_client.log_server);
    test.deepEqual(['node1_object','node2_object'], web_client.nodes);
    test.done();
  },

  test_register: function(test) {
    // Stub out client callbacks
    var fake_client = {
      sessionId: 666,
      events: {},
      nlabel: 'node1',
      ctype: 'node',
      on: function(event, callback) {
        this.events[event] = callback;
      },
      trigger_event: function(event, data) {
        this.events[event](data);
      }
    }

    // Stub out connection callback
    this.obj_ut.io = {
      events: {},
      broadcasts: [],
      on: function(event, callback) {
        this.events[event] = callback;
      },
      broadcast: function(message) {
        this.broadcasts.push(message);
      },
      trigger_event: function(event, data) {
        this.events[event](data);
      }
    }

    // Stub out setInterval
    var _orig_setInterval = setInterval
    setInterval = function(callback, interval) {
      callback();
    }

    this.obj_ut.register();
    this.obj_ut.io.trigger_event('connection', fake_client);

    // Stub out announce_node
    var n_announce_client;
    var n_announce_message;
    this.obj_ut.announce_node = function(client, message) {
      n_announce_client = client;
      n_announce_message = message;
    }

    // Stub out announce_web_client
    var w_announce_client;
    this.obj_ut.announce_web_client = function(client) {
      w_announce_client = client;
    }

    // Announce web client
    var wc_announce_message = {type: 'announce', client_type: 'web_client'};
    fake_client.trigger_event('message', wc_announce_message);
    test.deepEqual(fake_client, w_announce_client);

    // Announce node
    var announce_message = {type: 'announce', client_type: 'node'};
    fake_client.trigger_event('message', announce_message);
    test.deepEqual(fake_client, n_announce_client);
    test.deepEqual(announce_message, n_announce_message);

    // Ensure clients are removed from pools
    this.obj_ut.nodes['node1'] = 'stuff';
    fake_client.trigger_event('disconnect');
    test.deepEqual({}, this.obj_ut.nodes);

    // Ensure stats & heartbeats are being broadcasted
    test.deepEqual([{
      type: 'stats',
      message_count: 0,
    },{ type: 'heartbeat' }], this.obj_ut.io.broadcasts);

    // Restore setInterval
    setInterval = _orig_setInterval;
    test.done();
  }
});