<commit_before>var downsize = require("./"),
    chai = require("chai"),
    mocha = require("mocha");
chai.should();

describe("Word-wise truncation", function () {

    it("should be able to truncate across nested tags", function () {
        downsize("
this is a test of word downsizing
", {words: 5})
            .should.equal("
this is a test of
");
    });

    it("should be able to truncate even if a single quote is found inside a string of double quotes or vice-versa", function () {
        downsize('

hello world
', { words: 1 })
            .should.equal('

hello
');
    });

    it("should be able to naively balance HTML markup", function () {
        downsize("

this is a test of word downsizing some stuff
", {words: 5})
            .should.equal("

this is a test of

");
    });

    it("should be able to naively balance HTML markup", function () {
        downsize("

this is a test of word downsizing some stuff
", {words: 5})
            .should.equal("

this is a test of

");
    });

    it("should ignore erroneously unescaped carets", function () {
        downsize("
this < is a test of word downsizing some stuff
", {words: 5})
            .should.equal("
this < is a test of
");

        downsize("
this < is a > test < test > test of word downsizing some stuff
", {words: 5})
            .should.equal("
this < is a > test < test
");
    });

    it("should ignore comments in markup, and carets in comments", function () {
        downsize("
this  test of word downsizing some stuff
", {words: 2})
            .should.equal("
this  test
");
    });

    it("should understand implicitly void tags, and not attempt to close them", function () {
        downsize("
test  stuffo some stuff
", {words: 2})
            .should.equal("
test  stuffo
");
    });

    it("should understand self-closing tags, and not attempt to close them", function () {
        downsize("
test <random selfclosing /> stuffo some stuff
", {words: 2})
            .should.equal("
test <random selfclosing /> stuffo
");
    });

    it("should understand self-closing tags, even marked up poorly.", function () {
        downsize("
test <random selfclosing / > stuffo some stuff
", {words: 2})
            .should.equal("
test <random selfclosing / > stuffo
");
    });

    it("should close unknown tags appropriately", function () {
        downsize("
test <unknown> stuffo some stuff
", {words: 2})
            .should.equal("
test <unknown> stuffo</unknown>
");
    });

    it("should permit unescaped carets inside double-quoted strings", function () {
        downsize("
test string <img \"<stuffo>\"> stuffo some stuff
", {words: 3})
            .should.equal("
test string <img \"<stuffo>\"> stuffo
");
    });

    it("should permit unescaped carets inside single-quoted strings", function () {
        downsize("
test string <img '<stuffo>'> stuffo some stuff
", {words: 3})
            .should.equal("
test string <img '<stuffo>'> stuffo
");
    });

    it("should properly recognised manually closed elements, and do not re-close elements", function () {
        downsize("
tag closing test

There should only

be one terminating para
", {words: 7})
            .should.equal("
tag closing test

There should only

be
");
    });

    it("should properly handle unicode languages", function () {
        downsize("Рэпудёандаэ конжыквуюнтюр эю прё, нэ квуй янжольэнж квюальизквюэ чадипжкёнг. Ед кюм жкрипта", {words: 3})
            .should.equal("Рэпудёандаэ конжыквуюнтюр эю");
    });

    it("should properly handle unicode languages across nested tags", function () {
        downsize("
Рэпудёандаэ конжыквуюнтюр эю прё, нэ квуй янжольэнж квюальизквюэ чадипжкёнг. Ед кюм жкрипта
", {words: 3})
            .should.equal("
Рэпудёандаэ конжыквуюнтюр эю
");
    });

    it("should not have trailing empty tags", function () {
        downsize("
there are five words here
what", {words: 5})
            .should.equal("
there are five words here
");
    });

    it("should await the end of the containing paragraph", function () {
        downsize("
there are more than seven words in this paragraph

this is unrelated
", {words: 7, contextualTags: ["p", "ul", "ol", "pre", "blockquote"]})
            .should.equal("
there are more than seven words in this paragraph
");
    });

    it("should await the end of the containing unordered list", function () {
        downsize("

item one

item two

item three

paragraph
", {words: 5, contextualTags: ["p", "ul", "ol", "pre", "blockquote"]})
            .should.equal("

item one

item two

item three

");
    });

    it("should handle truncation to zero words", function () {
        downsize("
this is a test of word downsizing
", {words: 0})
            .should.equal("

");
    });

    it("should handle truncation to zero words with a string number input for backwards compatibility", function () {
        downsize("
this is a test of word downsizing
", {words: "0"})
            .should.equal("

");
    });

});

describe("Character based truncation", function () {
    it("should properly character-truncate across tag boundries", function () {
        downsize("
abcdefghij

klmnop

qrs
", {characters: 15})
            .should.equal("
abcdefghij

klmno
");

        downsize("
a

b

cdefghij

klmnop

qrs
", {characters: 15})
            .should.equal("
a

b

cdefghij

klmno
");

    });

    it("should await the end of the containing paragraph", function () {
        downsize("
there are many more than seven characters in this paragraph

this is unrelated
", {characters: 7, contextualTags: ["p", "ul", "ol", "pre", "blockquote"]})
            .should.equal("
there are many more than seven characters in this paragraph
");
    });

});

describe("Appending", function () {
    it("should properly append an ellipsis where required for word truncation", function () {
        downsize("
abcdefghij

klmnop

qrs
", {characters: 15, append: "..."})
            .should.equal("
abcdefghij

klmno...
");
    });

    it("should properly append an ellipsis where required for character truncation", function () {
        downsize("
here's some text.
", {words: 2, append: "... (read more)"})
            .should.equal("
here's some... (read more)
");
    });

    it("should not append an ellipsis where not required", function () {
        downsize("
here's some text.
", {words: 5, append: "..."})
            .should.equal("
here's some text.
");
    });
});

describe("Performance", function () {
    var perfTestSeed = "";
    for (var i = 0; i < 1000000; i++) {
        perfTestSeed += "
word truncate performance test
\n";
    }

    describe("truncate five words from a four-million word corpus one hundred thousand times", function () {
        it("benchmark time should be under twenty seconds", function () {
            var startTime = Date.now();
            for (i = 0; i < 100000; i++) {
                downsize(perfTestSeed, {"words": 5});
            }
            (Date.now() - startTime).should.be.lte(20*1000);
        });
    });
});
<commit_msg>added tests for tagless input<commit_after>var downsize = require("./"),
    chai = require("chai"),
    mocha = require("mocha");
chai.should();

describe("Word-wise truncation", function () {

    it("should be able to handle tagless input", function () {
        downsize("this is a test of tagless input", {words: 5})
            .should.equal("this is a test of");
    });

    it("should be able to truncate across nested tags", function () {
        downsize("
this is a test of word downsizing
", {words: 5})
            .should.equal("
this is a test of
");
    });

    it("should be able to truncate even if a single quote is found inside a string of double quotes or vice-versa", function () {
        downsize('

hello world
', { words: 1 })
            .should.equal('

hello
');
    });

    it("should be able to naively balance HTML markup", function () {
        downsize("

this is a test of word downsizing some stuff
", {words: 5})
            .should.equal("

this is a test of

");
    });

    it("should be able to naively balance HTML markup", function () {
        downsize("

this is a test of word downsizing some stuff
", {words: 5})
            .should.equal("

this is a test of

");
    });

    it("should ignore erroneously unescaped carets", function () {
        downsize("
this < is a test of word downsizing some stuff
", {words: 5})
            .should.equal("
this < is a test of
");

        downsize("
this < is a > test < test > test of word downsizing some stuff
", {words: 5})
            .should.equal("
this < is a > test < test
");
    });

    it("should ignore comments in markup, and carets in comments", function () {
        downsize("
this  test of word downsizing some stuff
", {words: 2})
            .should.equal("
this  test
");
    });

    it("should understand implicitly void tags, and not attempt to close them", function () {
        downsize("
test  stuffo some stuff
", {words: 2})
            .should.equal("
test  stuffo
");
    });

    it("should understand self-closing tags, and not attempt to close them", function () {
        downsize("
test <random selfclosing /> stuffo some stuff
", {words: 2})
            .should.equal("
test <random selfclosing /> stuffo
");
    });

    it("should understand self-closing tags, even marked up poorly.", function () {
        downsize("
test <random selfclosing / > stuffo some stuff
", {words: 2})
            .should.equal("
test <random selfclosing / > stuffo
");
    });

    it("should close unknown tags appropriately", function () {
        downsize("
test <unknown> stuffo some stuff
", {words: 2})
            .should.equal("
test <unknown> stuffo</unknown>
");
    });

    it("should permit unescaped carets inside double-quoted strings", function () {
        downsize("
test string <img \"<stuffo>\"> stuffo some stuff
", {words: 3})
            .should.equal("
test string <img \"<stuffo>\"> stuffo
");
    });

    it("should permit unescaped carets inside single-quoted strings", function () {
        downsize("
test string <img '<stuffo>'> stuffo some stuff
", {words: 3})
            .should.equal("
test string <img '<stuffo>'> stuffo
");
    });

    it("should properly recognised manually closed elements, and do not re-close elements", function () {
        downsize("
tag closing test

There should only

be one terminating para
", {words: 7})
            .should.equal("
tag closing test

There should only

be
");
    });

    it("should properly handle unicode languages", function () {
        downsize("Рэпудёандаэ конжыквуюнтюр эю прё, нэ квуй янжольэнж квюальизквюэ чадипжкёнг. Ед кюм жкрипта", {words: 3})
            .should.equal("Рэпудёандаэ конжыквуюнтюр эю");
    });

    it("should properly handle unicode languages across nested tags", function () {
        downsize("
Рэпудёандаэ конжыквуюнтюр эю прё, нэ квуй янжольэнж квюальизквюэ чадипжкёнг. Ед кюм жкрипта
", {words: 3})
            .should.equal("
Рэпудёандаэ конжыквуюнтюр эю
");
    });

    it("should not have trailing empty tags", function () {
        downsize("
there are five words here
what", {words: 5})
            .should.equal("
there are five words here
");
    });

    it("should await the end of the containing paragraph", function () {
        downsize("
there are more than seven words in this paragraph

this is unrelated
", {words: 7, contextualTags: ["p", "ul", "ol", "pre", "blockquote"]})
            .should.equal("
there are more than seven words in this paragraph
");
    });

    it("should await the end of the containing unordered list", function () {
        downsize("

item one

item two

item three

paragraph
", {words: 5, contextualTags: ["p", "ul", "ol", "pre", "blockquote"]})
            .should.equal("

item one

item two

item three

");
    });

    it("should handle truncation to zero words", function () {
        downsize("
this is a test of word downsizing
", {words: 0})
            .should.equal("

");
    });

    it("should handle truncation to zero words with a string number input for backwards compatibility", function () {
        downsize("
this is a test of word downsizing
", {words: "0"})
            .should.equal("

");
    });

});

describe("Character based truncation", function () {

    it("should be able to handle tagless input", function () {
        downsize("this is a test of tagless input", {characters: 6})
            .should.equal("this i");
    });

    it("should properly character-truncate across tag boundries", function () {
        downsize("
abcdefghij

klmnop

qrs
", {characters: 15})
            .should.equal("
abcdefghij

klmno
");

        downsize("
a

b

cdefghij

klmnop

qrs
", {characters: 15})
            .should.equal("
a

b

cdefghij

klmno
");

    });

    it("should await the end of the containing paragraph", function () {
        downsize("
there are many more than seven characters in this paragraph

this is unrelated
", {characters: 7, contextualTags: ["p", "ul", "ol", "pre", "blockquote"]})
            .should.equal("
there are many more than seven characters in this paragraph
");
    });

});

describe("Appending", function () {
    it("should properly append an ellipsis where required for word truncation", function () {
        downsize("
abcdefghij

klmnop

qrs
", {characters: 15, append: "..."})
            .should.equal("
abcdefghij

klmno...
");
    });

    it("should properly append an ellipsis where required for character truncation", function () {
        downsize("
here's some text.
", {words: 2, append: "... (read more)"})
            .should.equal("
here's some... (read more)
");
    });

    it("should not append an ellipsis where not required", function () {
        downsize("
here's some text.
", {words: 5, append: "..."})
            .should.equal("
here's some text.
");
    });
});

describe("Performance", function () {
    var perfTestSeed = "";
    for (var i = 0; i < 1000000; i++) {
        perfTestSeed += "
word truncate performance test
\n";
    }

    describe("truncate five words from a four-million word corpus one hundred thousand times", function () {
        it("benchmark time should be under twenty seconds", function () {
            var startTime = Date.now();
            for (i = 0; i < 100000; i++) {
                downsize(perfTestSeed, {"words": 5});
            }
            (Date.now() - startTime).should.be.lte(20*1000);
        });
    });
});
<|endoftext|>


<commit_before>var utyls = require('./');
var assert=require('chai').assert;

 var utobj=new utyls();

 //Tests for isChar
//TODO: Add More Tests eg: Create a custom datatype and try to pass it.
describe('Tests for isChar->',function(){

it('Passes Integer',function(){

   assert.strictEqual(utobj.isChar(7),false,"");

});

it('Passes Char',function(){

   assert.strictEqual(utobj.isChar('g'),true,"");

});

it('Passes String',function(){

   assert.strictEqual(utobj.isChar('string'),false,"")

});

it('Passes float/double',function(){

   assert.strictEqual(utobj.isChar(5.67),false,"");

});
});

//Tests for isInteger

describe("Tests for isInteger->",function(){

   it("Passes char",function(){

      assert.strictEqual(utobj.isInteger('7'),false,"");

   });

   it("Passes String",function(){

      assert.strictEqual(utobj.isInteger("787"),false,"");

   });

   it("Passes double/float",function(){

      assert.strictEqual(utobj.isInteger(6.78),false,"");

   });

   it("Passes Integer",function(){

      assert.strictEqual(utobj.isInteger(7),true,"");

   });

});

//TODO: Need More Tests to be written

describe("Tests for leftpad",function(){

   it("Without default arguement",function(){

       assert.strictEqual(utobj.leftpad("7",3),"**7","");
   });

   it("With default arguement",function(){

       assert.strictEqual(utobj.leftpad("7",3,"0"),"007","");

   });

   it("Passes required length less than string length",function(){

      assert.strictEqual(utobj.leftpad("788",2,"6"),"788","");

   });

   it("Passes a string instead of padding character",function(){

      assert.strictEqual(utobj.leftpad("776",10,"607"),undefined,"") ;
   });

   it("Passes negative length as required  length",function(){

      assert.strictEqual(utobj.leftpad("gha",-9),"gha","");

   });

   it("Passes empty string ",function(){

      assert.strictEqual(utobj.leftpad("",10),"**********","");
   });

   it("Passes String and required length",function(){

      assert.strictEqual(utobj.leftpad("ThisisTextoflength50",50),"******************************ThisisTextoflength50","");
   });

   it("Passes string and a double value as required length",function(){

      assert.strictEqual(utobj.leftpad("",2.34),undefined,"");

   });

   it("Passes string and a required double value with a padding character",function(){

     assert.strictEqual(utobj.leftpad("",2.34,'0'),undefined,"");
   });

   it("Passes string and fraction(when solved integer) as required length",function(){

    assert.strictEqual(utobj.leftpad("",21/7),"***","");
   });

   it("Passes string and fraction(when solved double) as required length",function(){

    assert.strictEqual(utobj.leftpad("",22/7),undefined,"");
   });

});

<commit_msg>Added more tests for isInteger<commit_after>var utyls = require('./');
var assert=require('chai').assert;

 var utobj=new utyls();

 //Tests for isChar
//TODO: Add More Tests eg: Create a custom datatype and try to pass it.
describe('Tests for isChar->',function(){

it('Passes Integer',function(){

   assert.strictEqual(utobj.isChar(7),false,"");

});

it('Passes Char',function(){

   assert.strictEqual(utobj.isChar('g'),true,"");

});

it('Passes String',function(){

   assert.strictEqual(utobj.isChar('string'),false,"")

});

it('Passes float/double',function(){

   assert.strictEqual(utobj.isChar(5.67),false,"");

});
});

//Tests for isInteger

describe("Tests for isInteger->",function(){

   it("Passes char",function(){

      assert.strictEqual(utobj.isInteger('7'),false,"");

   });

   it("Passes String",function(){

      assert.strictEqual(utobj.isInteger("787"),false,"");

   });

   it("Passes double/float",function(){

      assert.strictEqual(utobj.isInteger(6.78),false,"");

   });

   it("Passes Integer",function(){

      assert.strictEqual(utobj.isInteger(7),true,"");

   });

   it("Passes string with ascii characters",function(){

    assert.strictEqual(utobj.isInteger("utyls"),false,"");

   });

   it("Passes fraction resulting in integer",function(){

   assert.strictEqual(utobj.isInteger(21/3),true,"");

   });

   it("Passes fraction resulting in double",function(){

   assert.strictEqual(utobj.isInteger(22/3),false,"");

   });

   it("Passes string with special characters",function(){

   assert.strictEqual(utobj.isInteger('*$'),false,"");

   });

   it("Passes special character",function(){

   assert.strictEqual(utobj.isInteger('*'),false,"");

   });

   it("Passes character",function(){

   assert.strictEqual(utobj.isInteger('u'),false,"");

   });

   it("Passes Zero",function(){

   assert.strictEqual(utobj.isInteger(0),true,"");

   });

   it("Passes Negative Integer",function(){

   assert.strictEqual(utobj.isInteger(-7),true,"");

   });

   it("Passes Negative double/float",function(){

   assert.strictEqual(utobj.isInteger(-7.84),false,"");

   });

   it("Passes negative fraction resulting in integer",function(){

   assert.strictEqual(utobj.isInteger(-21/7),true,"");

   });

   it("Passes negative fraction resulting integer t2",function(){

   assert.strictEqual(utobj.isInteger(-21/-3),true,"");

   });

   it("Passes negative fraction resulting in double",function(){

   assert.strictEqual(utobj.isInteger(-22/7),false,"");

   });

});

//TODO: More Tests to be written

describe("Tests for leftpad",function(){

   it("Without default arguement",function(){

       assert.strictEqual(utobj.leftpad("7",3),"**7","");
   });

   it("With default arguement",function(){

       assert.strictEqual(utobj.leftpad("7",3,"0"),"007","");

   });

   it("Passes required length less than string length",function(){

      assert.strictEqual(utobj.leftpad("788",2,"6"),"788","");

   });

   it("Passes a string instead of padding character",function(){

      assert.strictEqual(utobj.leftpad("776",10,"607"),undefined,"") ;
   });

   it("Passes negative length as required  length",function(){

      assert.strictEqual(utobj.leftpad("gha",-9),"gha","");

   });

   it("Passes empty string ",function(){

      assert.strictEqual(utobj.leftpad("",10),"**********","");
   });

   it("Passes String and required length",function(){

      assert.strictEqual(utobj.leftpad("ThisisTextoflength50",50),"******************************ThisisTextoflength50","");
   });

   it("Passes string and a double value as required length",function(){

      assert.strictEqual(utobj.leftpad("",2.34),undefined,"");

   });

   it("Passes string and a required double value with a padding character",function(){

     assert.strictEqual(utobj.leftpad("",2.34,'0'),undefined,"");
   });

   it("Passes string and fraction(when solved integer) as required length",function(){

    assert.strictEqual(utobj.leftpad("",21/7),"***","");
   });

   it("Passes string and fraction(when solved double) as required length",function(){

    assert.strictEqual(utobj.leftpad("",22/7),undefined,"");
   });

});

<|endoftext|>


<commit_before>$(document).ready(function(){
    var nofinv = 1;
    $('#id_invoicenumber').addClass('invoice'+' '+nofinv);
    $('#id_invoicestatus').addClass('invoiceadditional'+' '+nofinv);
    $('#id_paidon').addClass('paid'+' '+nofinv);
    $('#id_rejectreason').addClass('reject'+' '+nofinv);
    $("#id_amount").addClass("amount"+" "+nofinv);
    $("#id_currency").addClass("currency"+" "+nofinv);
    $("#id_reasonother").addClass("other"+" "+nofinv);
    $('.addhiddendata:first').find('#id_invoicenumber').attr('id', 'id_invoicenumber'+nofinv);
    $('.addhiddendata:first').find('#id_invoicestatus').attr('id', 'id_invoicestatus'+nofinv);
    $('.addhiddendata:first').find('#id_paidon').attr('id', 'id_paidon'+nofinv);
    $('.addhiddendata:first').find('#id_rejectreason').attr('id', 'id_rejectreason'+nofinv);
    $(".addhiddendata:first").find("#id_amount").attr("id", "id_amount"+nofinv);
    $(".addhiddendata:first").find("#id_currency").attr("id", "id_currency"+nofinv);
    $("#id_reasonother").attr("id", "id_reasonother"+nofinv);

    $('#trbutton').on('click', function(){
	$('#trbutton').fadeOut('slow', function(){
	    $('#trform').fadeIn('slow');
	    $('#ptrack').html('Please fill in all the fields.');
	});
    });

    $('#id_reminderdate').datepicker({
	dateFormat: 'yy-mm-dd',
	constrainInput: false
    });
    $('.paid:first').datepicker({
	dateFormat: 'yy-mm-dd',
	constrainInput: false
    });

    var $name = $('#vclerk').attr('value');
    $('#id_clerk').val($name);

    $('#id_clerk').attr('readonly', true);
    $('#id_actiondate').attr('readonly', true);

    $('#id_market').on('change', function(){
	//show the ccode choice if is hidden
	if ($('#id_ccode').is(':hidden')) {$('#id_ccode').show()};

	$('#id_ccode option').each(function(){
	    $(this).show();
	});

	var market = $('#id_market').val();
	if (market == 'IT') {
	    var marketArray = ['', '11', '13', '15', '16'];
	} else if (market == 'DE') {
	    var marketArray = ['', '13', '52', '55', '60', '64', '66'];
	} else if (market == 'PT' || market == 'PL' || market == 'NL' || market == 'NO') {
	    var marketArray = ['', '10'];
	} else if (market == 'BE') {
	    var marketArray = ['', '12', '14', '18', '31'];
	} else if (market == 'SE') {
	    var marketArray = ['', '16'];
	} else if (market == 'FI') {
	    var marketArray = ['', '11'];
	} else if (market == 'DK') {
	    var marketArray = ['', '12'];
	} else {
	    var marketArray = [''];
	}

	$('#id_ccode option').each(function(){
	    var ccodeOpt = $(this).val();
	    if ($.inArray(ccodeOpt, marketArray) > -1){
		;
	    } else {
		$(this).hide();
	    }
	});

    });

    $(document).on('change', '.status', function() {
	var status = $(this).val();
	var nextform = $(this).parent().parent().parent().next();

	if (nextform.is(':hidden')){
	    ;
	} else {
	    nextform.hide();
	    if (nextform.find('.paid').is(':hidden')) {nextform.find('.paid').show()};
	    if (nextform.find('.other').is(':hidden')) {nextform.find('.other').show()};
	    if (nextform.find('.reject').is(':hidden')) {nextform.find('.reject').show()};
	    nextform.find('label').show();
	}

	if (status == 'RJ'){
	    nextform.find('.paid').hide();
	    nextform.find('label:last').hide();
	    nextform.fadeIn('slow');
	} else if (status == 'PD') {
	    nextform.find('.reject').hide();
	    nextform.find(".other").hide();
	    nextform.find('label:first').hide();
	    nextform.find('label:first').next().next("label").hide();
	    nextform.fadeIn('slow');
	};
    });

    $('#addbutt').on('click', function() {
	var formToApp = $('.addhiddendata:first').clone();
	formToApp.find('button').remove();
	formToApp.find('.paid').removeClass('hasDatepicker');
	formToApp.find('.paid').val('');
	formToApp.find('#id_invoicenumber1').removeClass('invoice'+' '+nofinv);
	formToApp.find('#id_invoicestatus1').removeClass('invoiceadditional'+' '+nofinv);
	formToApp.find('#id_paidon1').removeClass('paid'+' '+nofinv);
	formToApp.find('#id_rejectreason1').removeClass('reject'+' '+nofinv);
	formToApp.find("#id_amount1").removeClass("amount"+" "+nofinv);
	formToApp.find("#id_currency1").removeClass("currency"+" "+nofinv);
	formToApp.find("#id_reasonother1").removeClass("other"+" "+nofinv);
	nofinv = nofinv + 1;
	formToApp.find('#id_rejectreason1').addClass('reject'+' '+nofinv);
	formToApp.find('#id_rejectreason1').attr('name', 'reject'+nofinv);
	formToApp.find('#id_rejectreason1').attr('id', 'id_rejectreason'+nofinv);
	formToApp.find('#id_paidon1').addClass('paid'+' '+nofinv);
	formToApp.find('#id_paidon1').attr('name', 'paid'+nofinv);
	formToApp.find('#id_paidon1').attr('id', 'id_paidon'+nofinv);
	formToApp.find('#id_invoicenumber1').addClass('invoice'+' '+nofinv);
	formToApp.find('#id_invoicenumber1').attr('name', 'invoicenumber'+nofinv);
	formToApp.find('#id_invoicenumber1').attr('id', 'id_invoicenumber'+nofinv);
	formToApp.find('#id_invoicestatus1').addClass('invoiceadditional'+' '+nofinv);
	formToApp.find('#id_invoicestatus1').attr('name', 'invoicestatus'+nofinv);
	formToApp.find('#id_invoicestatus1').attr('id', 'id_invoicestatus'+nofinv);
	formToApp.find("#id_amount1").addClass("amount"+" "+nofinv);
	formToApp.find("#id_amount1").attr("name", "amount"+nofinv);
	formToApp.find("#id_amount1").attr("id", "id_amount"+nofinv);
	formToApp.find("#id_currency1").addClass("currency"+" "+nofinv);
	formToApp.find("#id_currency1").attr("name", "currency"+nofinv);
	formToApp.find("#id_currency1").attr("id", "id_currency"+nofinv);
	formToApp.find('#id_reasonother1').addClass('other'+' '+nofinv);
	formToApp.find('#id_reasonother1').attr('name', 'reasonother'+nofinv);
	formToApp.find('#id_reasonother1').attr('id', 'id_reasonother'+nofinv);
	$('#vendorform').before(formToApp);
	formToApp.find('.paid').datepicker({
	    dateFormat: 'yy-mm-dd',
	    constrainInput: false
	});
    });

    $('#rembutt').on('click', function() {
	//Remove additional invoices if there are at least 2 of them.
	if ($('.invoice').length == 1) {
	    ;
	} else {
	    $('.addhiddendata:last').remove();
	};
    });

    $('#id_reminderdate').on('change', function() {
	var rdate = $(this).val().split('-');
	var market = $('#id_market').val();
	$('#id_remindernumber').val('');
	$('#id_remindernumber').val(market+rdate[0]+rdate[1]+rdate[2]+'/');
    });

    function DunningTrack() {
	// get the total number of invoices.
	var invo = $('.invoice').length;

	var data = new Array()

	//loop through the invoice to create our data to post
	for (x = 1; x <= invo; x++) {
	    var formn = 'form'+x;
	    var obj = {
		market: $('#id_market').val(),
		ccode: $('#id_ccode').val(),
		clerk: $('#id_clerk').val(),
		actiondate: $('#id_actiondate').val(),
		reminderdate: $('#id_actiondate').val(),
		level: $('#id_level').val(),
		amount: $("#id_amount"+x).val(),
		currency: $("#id_currency"+x).val(),
		remindernumber: $('#id_remindernumber').val(),
		vendor: $('#id_vendor').val(),
		mailvendor: $('#id_mailvendor').val(),
		invoicenumber: $('#id_invoicenumber'+x).val(),
		invoicestatus: $('#id_invoicestatus'+x).val(),
		actiontaken: actionArray(),
		rejectreason: $('#id_rejectreason'+x).val(),
		paidon: $('#id_paidon'+x).val()
		//attachment:
	    };
	    data.push(obj);
	}

	//setup the AJAX request
	$.ajaxSetup({
	    type: 'POST',
	    dataType: 'json'
	});

	//the real AJAX request
	$.ajax({
	    url: '/ajax/',
	    data: {
		form_type: 'multi',
		mass_data: JSON.stringify(data)
	    },
	    success: window.location.replace("/main/"),
	    error: function (ajaxObj, textStatus, error) {
		alert(error);
	    }
	});
	return true;
    };

    $('#trackbutton').on('click', ValidateForm);
    $("#trform :input").on("change", function() {
	if ( $(this).val() != "" ) {
	    if ( $(this).parent().parent().hasClass("has-error") ) {
		$(this).parent().parent().removeClass("has-error");
	    }
	}
    });

    function ValidateForm() {
	DunningTrack();
    };
});

function SuccessfulTracking() {
    alert("Item correctly tracked");
};

function actionArray() {
    var actionPool = $(".actioncheck :input");
    var actionList = new Array()

    $.each(actionPool, function() {
	if ($(this).prop("checked")) {actionList.push($(this).val())}
    });

    actionList = actionList.join(",")
    return actionList;
};

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};

function isInteger(value) {
    var intPattern = new RegExp(/^[0-9]+$/)
    return intPattern.test(value);
};
<commit_msg>This function throws a basic JS check on the form. The first check looks for empty input elements and if found, we add a class "has-error" to that element to get recognized by the user as "wrong" filled (honestly not filled at all). The second check looks if email address is e-mail like and if the vendor number is numeric. Whenever an error occurs we increment our counter by 1, in the end if the counter is > 0 event which triggers the AJAX request to save the form isn't called.<commit_after>$(document).ready(function(){
    var nofinv = 1;
    $('#id_invoicenumber').addClass('invoice'+' '+nofinv);
    $('#id_invoicestatus').addClass('invoiceadditional'+' '+nofinv);
    $('#id_paidon').addClass('paid'+' '+nofinv);
    $('#id_rejectreason').addClass('reject'+' '+nofinv);
    $("#id_amount").addClass("amount"+" "+nofinv);
    $("#id_currency").addClass("currency"+" "+nofinv);
    $("#id_reasonother").addClass("other"+" "+nofinv);
    $('.addhiddendata:first').find('#id_invoicenumber').attr('id', 'id_invoicenumber'+nofinv);
    $('.addhiddendata:first').find('#id_invoicestatus').attr('id', 'id_invoicestatus'+nofinv);
    $('.addhiddendata:first').find('#id_paidon').attr('id', 'id_paidon'+nofinv);
    $('.addhiddendata:first').find('#id_rejectreason').attr('id', 'id_rejectreason'+nofinv);
    $(".addhiddendata:first").find("#id_amount").attr("id", "id_amount"+nofinv);
    $(".addhiddendata:first").find("#id_currency").attr("id", "id_currency"+nofinv);
    $("#id_reasonother").attr("id", "id_reasonother"+nofinv);

    $('#trbutton').on('click', function(){
	$('#trbutton').fadeOut('slow', function(){
	    $('#trform').fadeIn('slow');
	    $('#ptrack').html('Please fill in all the fields.');
	});
    });

    $('#id_reminderdate').datepicker({
	dateFormat: 'yy-mm-dd',
	constrainInput: false
    });
    $('.paid:first').datepicker({
	dateFormat: 'yy-mm-dd',
	constrainInput: false
    });

    var $name = $('#vclerk').attr('value');
    $('#id_clerk').val($name);

    $('#id_clerk').attr('readonly', true);
    $('#id_actiondate').attr('readonly', true);

    $('#id_market').on('change', function(){
	//show the ccode choice if is hidden
	if ($('#id_ccode').is(':hidden')) {$('#id_ccode').show()};

	$('#id_ccode option').each(function(){
	    $(this).show();
	});

	var market = $('#id_market').val();
	if (market == 'IT') {
	    var marketArray = ['', '11', '13', '15', '16'];
	} else if (market == 'DE') {
	    var marketArray = ['', '13', '52', '55', '60', '64', '66'];
	} else if (market == 'PT' || market == 'PL' || market == 'NL' || market == 'NO') {
	    var marketArray = ['', '10'];
	} else if (market == 'BE') {
	    var marketArray = ['', '12', '14', '18', '31'];
	} else if (market == 'SE') {
	    var marketArray = ['', '16'];
	} else if (market == 'FI') {
	    var marketArray = ['', '11'];
	} else if (market == 'DK') {
	    var marketArray = ['', '12'];
	} else {
	    var marketArray = [''];
	}

	$('#id_ccode option').each(function(){
	    var ccodeOpt = $(this).val();
	    if ($.inArray(ccodeOpt, marketArray) > -1){
		;
	    } else {
		$(this).hide();
	    }
	});

    });

    $(document).on('change', '.status', function() {
	var status = $(this).val();
	var nextform = $(this).parent().parent().parent().next();

	if (nextform.is(':hidden')){
	    ;
	} else {
	    nextform.hide();
	    if (nextform.find('.paid').is(':hidden')) {nextform.find('.paid').show()};
	    if (nextform.find('.other').is(':hidden')) {nextform.find('.other').show()};
	    if (nextform.find('.reject').is(':hidden')) {nextform.find('.reject').show()};
	    nextform.find('label').show();
	}

	if (status == 'RJ'){
	    nextform.find('.paid').hide();
	    nextform.find('label:last').hide();
	    nextform.fadeIn('slow');
	} else if (status == 'PD') {
	    nextform.find('.reject').hide();
	    nextform.find(".other").hide();
	    nextform.find('label:first').hide();
	    nextform.find('label:first').next().next("label").hide();
	    nextform.fadeIn('slow');
	};
    });

    $('#addbutt').on('click', function() {
	var formToApp = $('.addhiddendata:first').clone();
	formToApp.find('button').remove();
	formToApp.find('.paid').removeClass('hasDatepicker');
	formToApp.find('.paid').val('');
	formToApp.find('#id_invoicenumber1').removeClass('invoice'+' '+nofinv);
	formToApp.find('#id_invoicestatus1').removeClass('invoiceadditional'+' '+nofinv);
	formToApp.find('#id_paidon1').removeClass('paid'+' '+nofinv);
	formToApp.find('#id_rejectreason1').removeClass('reject'+' '+nofinv);
	formToApp.find("#id_amount1").removeClass("amount"+" "+nofinv);
	formToApp.find("#id_currency1").removeClass("currency"+" "+nofinv);
	formToApp.find("#id_reasonother1").removeClass("other"+" "+nofinv);
	nofinv = nofinv + 1;
	formToApp.find('#id_rejectreason1').addClass('reject'+' '+nofinv);
	formToApp.find('#id_rejectreason1').attr('name', 'reject'+nofinv);
	formToApp.find('#id_rejectreason1').attr('id', 'id_rejectreason'+nofinv);
	formToApp.find('#id_paidon1').addClass('paid'+' '+nofinv);
	formToApp.find('#id_paidon1').attr('name', 'paid'+nofinv);
	formToApp.find('#id_paidon1').attr('id', 'id_paidon'+nofinv);
	formToApp.find('#id_invoicenumber1').addClass('invoice'+' '+nofinv);
	formToApp.find('#id_invoicenumber1').attr('name', 'invoicenumber'+nofinv);
	formToApp.find('#id_invoicenumber1').attr('id', 'id_invoicenumber'+nofinv);
	formToApp.find('#id_invoicestatus1').addClass('invoiceadditional'+' '+nofinv);
	formToApp.find('#id_invoicestatus1').attr('name', 'invoicestatus'+nofinv);
	formToApp.find('#id_invoicestatus1').attr('id', 'id_invoicestatus'+nofinv);
	formToApp.find("#id_amount1").addClass("amount"+" "+nofinv);
	formToApp.find("#id_amount1").attr("name", "amount"+nofinv);
	formToApp.find("#id_amount1").attr("id", "id_amount"+nofinv);
	formToApp.find("#id_currency1").addClass("currency"+" "+nofinv);
	formToApp.find("#id_currency1").attr("name", "currency"+nofinv);
	formToApp.find("#id_currency1").attr("id", "id_currency"+nofinv);
	formToApp.find('#id_reasonother1').addClass('other'+' '+nofinv);
	formToApp.find('#id_reasonother1').attr('name', 'reasonother'+nofinv);
	formToApp.find('#id_reasonother1').attr('id', 'id_reasonother'+nofinv);
	$('#vendorform').before(formToApp);
	formToApp.find('.paid').datepicker({
	    dateFormat: 'yy-mm-dd',
	    constrainInput: false
	});
    });

    $('#rembutt').on('click', function() {
	//Remove additional invoices if there are at least 2 of them.
	if ($('.invoice').length == 1) {
	    ;
	} else {
	    $('.addhiddendata:last').remove();
	};
    });

    $('#id_reminderdate').on('change', function() {
	var rdate = $(this).val().split('-');
	var market = $('#id_market').val();
	$('#id_remindernumber').val('');
	$('#id_remindernumber').val(market+rdate[0]+rdate[1]+rdate[2]+'/');
    });

    function DunningTrack() {
	// get the total number of invoices.
	var invo = $('.invoice').length;

	var data = new Array()

	//loop through the invoice to create our data to post
	for (x = 1; x <= invo; x++) {
	    var formn = 'form'+x;
	    var obj = {
		market: $('#id_market').val(),
		ccode: $('#id_ccode').val(),
		clerk: $('#id_clerk').val(),
		actiondate: $('#id_actiondate').val(),
		reminderdate: $('#id_actiondate').val(),
		level: $('#id_level').val(),
		amount: $("#id_amount"+x).val(),
		currency: $("#id_currency"+x).val(),
		remindernumber: $('#id_remindernumber').val(),
		vendor: $('#id_vendor').val(),
		mailvendor: $('#id_mailvendor').val(),
		invoicenumber: $('#id_invoicenumber'+x).val(),
		invoicestatus: $('#id_invoicestatus'+x).val(),
		actiontaken: actionArray(),
		rejectreason: $('#id_rejectreason'+x).val(),
		paidon: $('#id_paidon'+x).val()
		//attachment:
	    };
	    data.push(obj);
	}

	//setup the AJAX request
	$.ajaxSetup({
	    type: 'POST',
	    dataType: 'json'
	});

	//the real AJAX request
	$.ajax({
	    url: '/ajax/',
	    data: {
		form_type: 'multi',
		mass_data: JSON.stringify(data)
	    },
	    success: window.location.replace("/main/"),
	    error: function (ajaxObj, textStatus, error) {
		alert(error);
	    }
	});
	return true;
    };

    $('#trackbutton').on('click', ValidateForm);
    $("#trform :input").on("change", function() {
	if ( $(this).val() != "" ) {
	    if ( $(this).parent().parent().hasClass("has-error") ) {
		$(this).parent().parent().removeClass("has-error");
	    }
	}
    });

    function ValidateForm() {
	DunningTrack();
    };
});

function SuccessfulTracking() {
    alert("Item correctly tracked");
};

function actionArray() {
    var actionPool = $(".actioncheck :input");
    var actionList = new Array()

    $.each(actionPool, function() {
	if ($(this).prop("checked")) {actionList.push($(this).val())}
    });

    actionList = actionList.join(",")
    return actionList;
};

function ValidateForm() {
    error = 0;
    var howManyErrors = $(".has-error").length;
    var fieldsToCheck = ["market", "ccode", "reminderdate", "remindernumber",
			 "level", "vendor", "mailvendor"]
    if ( howManyErrors == 0 ) {
	//checks if some fields are not correctly filled (1st check)
	$.each(fieldsToCheck, function() {
	    if ($("#id_"+this).val() == "") {
		if (! $("#id_"+this).parent().parent().hasClass("has-error")) {
		    $("#id_"+this).parent().parent().addClass("has-error");
		    error++;
		}
	    } else {
		if ($("id_"+this).parent().parent().hasClass(".has-error")) {
		    $("#id_"+this).removeClass("has-error");
		}
	    };
	});
    } else {
	// no errors
	;
    }
    // return the total number of errors
    var errorSum = error + additionalErrorCheck()
    return errorSum
};

function additionalErrorCheck() {
    var error = 0;
    var vendor = $("#id_vendor")
    var mailVendor = $("#id_mailvendor")

    //check if email field is e-mail like
    if ( !isValidEmailAddress(mailVendor.val()) ) {
	if ( !mailVendor.hasClass("has-error") ) { mailVendor.parent().parent().addClass("has-error") }
	error++
    };

    //check if vendor number has 9 characters or if starts with 100 or if there are no characters into the field
    if ( !(vendor.val().length == 9) || !(vendor.val().substr(0, 3) == "100") || !isInteger(vendor.val()) ) {
	if ( ! vendor.hasClass("has-error") ) { vendor.parent().parent().addClass("has-error") }
	error++
    };

    //returns the number of errors
    return error
};

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};

function isInteger(value) {
    var intPattern = new RegExp(/^[0-9]+$/)
    return intPattern.test(value);
};
<|endoftext|>


<commit_before>import parse from './module';

const test = require('tape-catch');
const {safeLoad: yaml} = require('js-yaml');
// const {readFileSync, readdirSync} = require('fs');
const {readFileSync} = require('fs');
const {resolve} = require('path');
const ord = require('ord');
const tosource = require('tosource');
const {jsdom} = require('jsdom');
const arrayFrom = require('array-from');
const {DOMParser} = require('xmldom');

const specDirectory = resolve(__dirname,
  'node_modules/parametric-svg-spec/specs'
);

// const specs = readdirSync(specDirectory)
const specs = ['usage-xml.yaml']
  .map((filename) => yaml(readFileSync(
    resolve(specDirectory, filename)
  )));

specs.forEach(({name, tests}) => tests.forEach((
  {description, ast, document, mode}
) => {
  test(`${name}: ${description}`, (is) => {
    const rootElement = mode === 'html' ?
      jsdom(document).defaultView.document.body.parentNode :
      new DOMParser().parseFromString(document).documentElement;

    const {attributes} = parse(rootElement);

    is.equal(
      attributes.size,
      ast.length,
      'the AST has the right number of attributes'
    );

    ast.forEach((expected, index) => {
      const n = index + 1;
      const nth = `${n}${ord(n)}`;
      const actual = arrayFrom(attributes)[index];

      is.deepEqual(
        actual.address,
        expected.address,
        `the \`address\` matches in the ${nth} parametric attribute`
      );

      is.equal(
        actual.name,
        expected.name,
        `the \`name\` matches in the ${nth} parametric attribute`
      );

      is.deepEqual(
        actual.dependencies,
        expected.dependencies,
        `the \`dependencies\` match in the ${nth} parametric attribute`
      );

      expected.relation.forEach(({input, output: expectedOutput}) => {
        const inputArguments = input.map(tosource).join(', ');

        is.deepEqual(
          actual.relation(...input),
          expectedOutput,
          `the \`relation\` in the ${nth} parametric attribute returns ` +
          'the expected value when called with the arguments ' +
          `\`(${inputArguments})\`.`
        );
      });
    });

    is.end();
  });
}));
<commit_msg>Switch HTML5 tests back on<commit_after>import parse from './module';

const test = require('tape-catch');
const {safeLoad: yaml} = require('js-yaml');
// const {readFileSync, readdirSync} = require('fs');
const {readFileSync} = require('fs');
const {resolve} = require('path');
const ord = require('ord');
const tosource = require('tosource');
const {jsdom} = require('jsdom');
const arrayFrom = require('array-from');
const {DOMParser} = require('xmldom');

const specDirectory = resolve(__dirname,
  'node_modules/parametric-svg-spec/specs'
);

// const specs = readdirSync(specDirectory)
const specs = ['usage-html5.yaml', 'usage-xml.yaml']
  .map((filename) => yaml(readFileSync(
    resolve(specDirectory, filename)
  )));

specs.forEach(({name, tests}) => tests.forEach((
  {description, ast, document, mode}
) => {
  test(`${name}: ${description}`, (is) => {
    const rootElement = mode === 'html' ?
      jsdom(document).defaultView.document.body.parentNode :
      new DOMParser().parseFromString(document).documentElement;

    const {attributes} = parse(rootElement);

    is.equal(
      attributes.size,
      ast.length,
      'the AST has the right number of attributes'
    );

    ast.forEach((expected, index) => {
      const n = index + 1;
      const nth = `${n}${ord(n)}`;
      const actual = arrayFrom(attributes)[index];

      is.deepEqual(
        actual.address,
        expected.address,
        `the \`address\` matches in the ${nth} parametric attribute`
      );

      is.equal(
        actual.name,
        expected.name,
        `the \`name\` matches in the ${nth} parametric attribute`
      );

      is.deepEqual(
        actual.dependencies,
        expected.dependencies,
        `the \`dependencies\` match in the ${nth} parametric attribute`
      );

      expected.relation.forEach(({input, output: expectedOutput}) => {
        const inputArguments = input.map(tosource).join(', ');

        is.deepEqual(
          actual.relation(...input),
          expectedOutput,
          `the \`relation\` in the ${nth} parametric attribute returns ` +
          'the expected value when called with the arguments ' +
          `\`(${inputArguments})\`.`
        );
      });
    });

    is.end();
  });
}));
<|endoftext|>


<commit_before>/*
Name:           fibonacci - test.js
Source & docs:  https://github.com/fvdm/nodejs-fibonacci
Feedback:       https://github.com/fvdm/nodejs-fibonacci/issues
License:        Unlicense (public domain)
*/

var path = require ('path');
var dir = path.dirname (module.filename);

var EventEmitter = require ('events').EventEmitter;
var pkg = require (path.join (dir, 'package.json'));
var app = require (path.join (dir));

var eventResultEmitted = false;
var eventDoneEmitted = false;
var errors = 0;
var warnings = 0;
var queue = [];
var next = 0;

var queueLength = 4;

// Setup
var iterations = 1000;
var expectNumber = '43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875';

/**
 * ANSI colorize a string
 *
 * @param color {String} - The color to add
 * @param str {String} - The string to alter
 * @returns {String}
 */

function colorStr (color, str) {
  var colors = {
    red: '\u001b[31m',
    green: '\u001b[32m',
    yellow: '\u001b[33m',
    blue: '\u001b[34m',
    magenta: '\u001b[35m',
    cyan: '\u001b[36m',
    gray: '\u001b[37m',
    bold: '\u001b[1m',
    plain: '\u001b[0m'
  };

  return colors [color] + str + colors.plain;
}

/**
 * console.log with style
 *
 * @param [type] {String=plain} - Formatting style
 * @param str {String} - The string to alter
 * @returns {void}
 */

function log (type, str) {
  var types = {
    fail: ['red', 'FAIL'],
    good: ['green', 'good'],
    warn: ['yellow', 'warn'],
    info: ['cyan', 'info']
  };

  if (!str) {
    str = type;
    type = 'plain';
  }

  switch (type) {
    case 'error': console.log (colorStr ('red', colorStr ('bold', 'ERROR   ')) + str + '\n'); break;
    case 'note': console.log (colorStr ('bold', str)); break;
    case 'plain': console.log (str); break;
    default:
      console.log (colorStr (types[type][0], types[type][1]) + '    ' + str);
      break;
  }
}

/**
 * Detect and wrap string type
 *
 * @param str {String} - The string
 * @returns {String}
 */

function typeStr (str) {
  if (typeof str === 'string') {
    str = '"' + str + '"';
  } else if (str instanceof Object) {
    str = 'Object';
  } else if (str instanceof Array) {
    str = 'Array';
  } else if (str instanceof Error) {
    str = 'Error';
  }

  return colorStr ('magenta', str);
}

// handle exits
process.on ('exit', function processExit () {
  console.log ();
  log ('info', errors + ' errors');
  log ('info', warnings + ' warnings');
  console.log ();

  if (errors) {
    process.exit (1);
  } else {
    process.exit (0);
  }
});

// prevent errors from killing the process
process.on ('uncaughtException', function uncaughtException (err) {
  console.log (err);
  console.log ();
  console.log (err.stack);
  console.log ();
  errors++;
});

/**
 * Queue to prevent flooding
 *
 * @returns {void}
 */

function doNext () {
  next++;
  console.log();
  if (queue [next]) {
    console.log ();
    queue [next] ();
  }
}

/**
 * doTest checks for error
 * else runs specified tests
 *
 * @param {Error} err
 * @param {String} label
 * @param {Array} tests
 * @returns {void}
 *
 * doTest(err, 'label text', [
 *   ['fail', 'feeds', typeof feeds, 'object'],
 *   ['warn', 'music', music instanceof Array, true],
 *   ['info', 'tracks', music.length]
 * ]);
 */

function doTest (err, label, tests) {
  var level = 'good';
  var test;
  var i;

  if (err instanceof Error) {
    log ('error', label);
    console.dir (err, { depth: null, colors: true });
    console.log ();
    console.log (err.stack);
    console.log ();
    errors++;

    doNext ();
    return;
  }

  log ('note', colorStr ('blue', '(' + (next + 1) + '/' + queueLength + ') ') + label);

  for (i = 0; i < tests.length; i++) {
    test = {
      level: tests [i] [0],
      label: tests [i] [1],
      result: tests [i] [2],
      expect: tests [i] [3]
    };

    if (test.result === test.expect) {
      log ('good', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is exactly ' + typeStr (test.expect));
    }

    if (test.level === 'fail' && test.result !== test.expect) {
      errors++;
      level = 'fail';
      log ('fail', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is not ' + typeStr (test.expect));
    }

    if (test.level === 'warn' && test.result !== test.expect) {
      warnings++;
      level = level !== 'fail' && 'warn';
      log ('warn', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is not ' + typeStr (test.expect));
    }

    if (test.level === 'info') {
      log ('info', colorStr ('blue', test.label) + ': ' + typeStr (test.result));
    }
  }

  doNext ();
}

// module basics
queue.push (function () {
  doTest (null, 'module', [
    ['fail', 'exports', typeof app, 'object'],
    ['fail', 'instance', app instanceof EventEmitter, true],
    ['fail', '.iterate', app && app.iterate instanceof Function, true],
    ['fail', '.kill', app && app.kill instanceof Function, true]
  ]);
});

// process events
app.on ('result', function () {
  eventResultEmitted = true;
});

app.on ('done', function (result) {
  eventDoneEmitted = true;

  doTest (null, 'event result', [
    ['fail', 'result emit', eventResultEmitted, true]
  ]);

  doTest (null, 'event done', [
    ['fail', 'result number', result && typeof result.number, 'string'],
    ['fail', 'result length', result && typeof result.length, 'number'],
    ['fail', 'result iterations', result && result.iterations, String (iterations)],
    ['fail', 'result ms', result && typeof result.ms, 'number'],
    ['info', 'result ms', result && result.ms],
    ['fail', 'result value', result && result.number, expectNumber]
  ]);
});

// iterate
queue.push (function () {
  var result = app.iterate (iterations);

  doTest (null, 'iterate return', [
    ['fail', 'result type', result instanceof Object, true],
    ['fail', 'result number', result && result.number, expectNumber]
  ]);
});

// Start the tests
log ('note', 'Running tests...\n');
log ('note', 'Node.js:  ' + process.versions.node);
log ('note', 'Module:   ' + pkg.version);
console.log ();

queue [0] ();
<commit_msg>Test: rewrite script to dotest module<commit_after>/*
Name:           fibonacci - test.js
Source & docs:  https://github.com/fvdm/nodejs-fibonacci
Feedback:       https://github.com/fvdm/nodejs-fibonacci/issues
License:        Unlicense (public domain)
*/

var dotest = require ('dotest');
var app = require ('./');

var eventResult = false;
var eventDone = false;

var iterations = 1000;
var expectNumber = '43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875';

// process events
app.on ('result', function (result) {
  eventResult = result;
});

app.on ('done', function (result) {
  eventDone = result;
});

// module basics
dotest.add ('Module', function (test) {
  test ()
    .isObject ('fail', 'exports', app)
    .isExactly ('fail', 'interface', app instanceof EventEmitter, true)
    .isFunction ('fail', '.iterate', app && app.iterate)
    .isFunction ('fail', '.kill', app && app.kill)
  ]);
});

// iterate
dotest.add ('Method .iterate', function (test) {
  var result = app.iterate (iterations);

  test ()
    .isObject ('fail', '.iterate return', result)
    .isExactly ('fail', '.iterate .number', result && result.number, expectNumber)
    .done ();
});

// events
dotest.add ('Events', function (test) {
  dotest.onExit (function () {
    test ()
      .isObject ('fail', 'Event result', eventResult)
      .isObject ('fail', 'Event done', eventDone)
      .info ('Number found in ' + eventDone.ms + ' ms')
      .done ();
  });
});

// Start the tests
dotest.run ();
<|endoftext|>


<commit_before>var path = require('path')
var should = require("chai").should()
var Animal = require(path.join(process.cwd() + '/Animal'));
var Cheer = require(path.join(process.cwd() + '/Cheers.js'));
var cp = require('child_process');

describe('Tests', function() {
    it('Truthiness', function () {
      	true.should.equal(true);
    });
});

describe.only('Cheers', function() {
	it('should check letters are correct', function () {
		var cheer = new Cheer('Scott')
		cheer.name.should.equal('Scott')
	});

	it('should correctly assign a or an', function () {
		var cheer = new Cheer('A')
		var output = cheer.hurrah()
		output.should.equal('Give me an A!\n')
	});

	it('should correctly assign spaces', function () {
		var cheer = new Cheer('A B')
		var output = cheer.hurrah()
		output.should.equal('Give me an A!\nGive me a B!\n')
	});

	it('should correctly assign caps', function () {
		var cheer = new Cheer('a')
		var output = cheer.hurrah()
		output.should.equal('Give me an A!\n')
	});

	it('should skip non alphabet characters', function () {
		var cheer = new Cheer('a!')
		var output = cheer.hurrah()
		output.should.equal('Give me an A!\n')
	});

});

describe('CLI', function() {
	it('should thank me for downloading', function (done) {
		cp.execFile('./app.js', function (err, stdout) {
			stdout.should.equal('Thanks for downloading my app!!!!');
			done();
		});
	});
});

describe('Animal', function () {

	describe('#updateHealthStats()', function() {
		it('should change the health', function(){
			var animal = new Animal();
			var health = animal.health

			animal.updateHealthStats(function () {
				animal.health.should.not.equal(health)
				done();

			});
		});
	});

	describe('constructor', function () {

		it('should accept a type', function() {
			var cat = new Animal('cat')
			cat.type.should.equal('cat')

		});

		it('should return an animal object', function () {
			var animal = new Animal();

			animal.should.be.an('object');
			animal.should.be.an.instanceOf(Animal);
		});

		it('should be alive', function () {
			var animal = new Animal();

			animal.isAlive.should.be.true;
		});

		it('should have 100% health', function() {
			var animal = new Animal();
			animal.health.should.equal(1);
		});

	});
});

describe('#beCute()', function() {
	it('should make the animal cute', function() {
		var animal = new Animal();
		should.not.exist(animal.isCute)
		animal.beCute();
		animal.isCute.should.be.true
	})
})

describe('Array', function () {
	describe('#filter()', function () {
		it('should return an array of items that return truthy in the inn fn', function () {
			var array = [1,2,3,4,5]

			var output = array.filter(function (item) {
				return item % 2;
			})

			output.should.eql([1,3,5])
		});
	});

	describe('#map()', function () {
		it('should createa  new array with a return value of the inner function', function (){
			var array = [1,2,3,4,5];

			var output = array.map(function (item) {
				return item * item;
			});

			output.should.eql([1,4,9,16,25])

		});

		it('should keep the same length', function () {
			var array = [1,2,3,4,5];

			var arrayLength = array.map(function (item) {
				return false;
			}).length;

			arrayLength.should.equal(array.length);
		});

		it('should not mutate the original array', function () {

			var array = [1,2,3,4,5]

			array.map(function() {
				return false
			});

			array.should.eql([1,2,3,4,5])

		})
	});
});<commit_msg>fixed test file<commit_after>var path = require('path')
var should = require("chai").should()
var Animal = require(path.join(process.cwd() + '/Animal'));
var Cheer = require(path.join(process.cwd() + '/cheers.js'));
var cp = require('child_process');

describe('Tests', function() {
    it('Truthiness', function () {
      	true.should.equal(true);
    });
});

describe.only('Cheers', function() {
	it('should check letters are correct', function () {
		var cheer = new Cheer('Scott')
		cheer.name.should.equal('Scott')
	});

	it('should correctly assign a or an', function () {
		var cheer = new Cheer('A')
		var output = cheer.hurrah()
		output.should.equal('Give me an A!\n')
	});

	it('should correctly assign spaces', function () {
		var cheer = new Cheer('A B')
		var output = cheer.hurrah()
		output.should.equal('Give me an A!\nGive me a B!\n')
	});

	it('should correctly assign caps', function () {
		var cheer = new Cheer('a')
		var output = cheer.hurrah()
		output.should.equal('Give me an A!\n')
	});

});

describe('CLI', function() {
	it('should thank me for downloading', function (done) {
		cp.execFile('./app.js', function (err, stdout) {
			stdout.should.equal('Thanks for downloading my app!!!!');
			done();
		});
	});
});

describe('Animal', function () {

	describe('#updateHealthStats()', function() {
		it('should change the health', function(){
			var animal = new Animal();
			var health = animal.health

			animal.updateHealthStats(function () {
				animal.health.should.not.equal(health)
				done();

			});
		});
	});

	describe('constructor', function () {

		it('should accept a type', function() {
			var cat = new Animal('cat')
			cat.type.should.equal('cat')

		});

		it('should return an animal object', function () {
			var animal = new Animal();

			animal.should.be.an('object');
			animal.should.be.an.instanceOf(Animal);
		});

		it('should be alive', function () {
			var animal = new Animal();

			animal.isAlive.should.be.true;
		});

		it('should have 100% health', function() {
			var animal = new Animal();
			animal.health.should.equal(1);
		});

	});
});

describe('#beCute()', function() {
	it('should make the animal cute', function() {
		var animal = new Animal();
		should.not.exist(animal.isCute)
		animal.beCute();
		animal.isCute.should.be.true
	})
})

describe('Array', function () {
	describe('#filter()', function () {
		it('should return an array of items that return truthy in the inn fn', function () {
			var array = [1,2,3,4,5]

			var output = array.filter(function (item) {
				return item % 2;
			})

			output.should.eql([1,3,5])
		});
	});

	describe('#map()', function () {
		it('should createa  new array with a return value of the inner function', function (){
			var array = [1,2,3,4,5];

			var output = array.map(function (item) {
				return item * item;
			});

			output.should.eql([1,4,9,16,25])

		});

		it('should keep the same length', function () {
			var array = [1,2,3,4,5];

			var arrayLength = array.map(function (item) {
				return false;
			}).length;

			arrayLength.should.equal(array.length);
		});

		it('should not mutate the original array', function () {

			var array = [1,2,3,4,5]

			array.map(function() {
				return false
			});

			array.should.eql([1,2,3,4,5])

		})
	});
});<|endoftext|>


<commit_before>/*
Name:           gtmetrix - test.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-gtmetrix
Feedback:       https://github.com/fvdm/nodejs-gtmetrix/issues
License:        Unlicense / Public Domain (see UNLICENSE file)
                (https://github.com/fvdm/nodejs-gtmetrix/raw/develop/LICENSE)
*/

var path = require ('path');
var dotest = require ('dotest');
var app = require (path.join (__dirname, path.sep));

// Setup
// $ env GTMETRIX_EMAIL= GTMETRIX_APIKEY= npm test
var email = process.env.GTMETRIX_EMAIL || null;
var apikey = process.env.GTMETRIX_APIKEY || null;
var timeout = process.env.GTMETRIX_TIMEOUT || 5000;
var location = process.env.GTMETRIX_LOCATION || 2;
var browser = process.env.GTMETRIX_BROWSER || 3;

var gtmetrix = app ({
  email: email,
  apikey: apikey,
  timeout: timeout
});

var cache = {
  url: 'http://example.net/',
  location: location,
  browser: browser
};

dotest.add ('account.status', function (test) {
  gtmetrix.account.status (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('browsers.list', function (test) {
  gtmetrix.browsers.list (function (err, data) {
    test (err)
      .isArray ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isObject ('warn', 'data[0]', data && data [0])
      .done ();
  });
});

dotest.add ('browsers.get', function (test) {
  gtmetrix.browsers.get (3, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.id', data && data.id, 3)
      .done ();
  });
});

dotest.add ('locations.list', function (test) {
  gtmetrix.locations.list (function (err, data) {
    test (err)
      .isArray ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isObject ('warn', 'data[0]', data && data [0])
      .done ();
  });
});

dotest.add ('test.create', function (test) {
  gtmetrix.test.create (cache, function (err, data) {
    cache.test = data;
    test (err)
      .isObject ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('test.get - without polling', function (test) {
  gtmetrix.test.get (cache.test.test_id, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isString ('warn', 'data.state', data && data.state)
      .done ();
  });
});

dotest.add ('test.get - with polling', function (test) {
  gtmetrix.test.get (cache.test.test_id, 5000, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.state', data && data.state, 'completed')
      .done ();
  });
});

dotest.add ('test.get resource - binary with polling', function (test) {
  gtmetrix.test.get (cache.test.test_id, 'screenshot', 5000, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('test.get resource - non-binary with polling', function (test) {
  gtmetrix.test.get (cache.test.test_id, 'yslow', 5000, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.u', data && data.u, cache.url)
      .done ();
  });
});

dotest.add ('Error: API error - without polling', function (test) {
  gtmetrix.test.get ('0', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: API error - resource with default polling', function (test) {
  gtmetrix.test.get ('0', 'yslow', true, function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: request failed (timeout)', function (test) {
  var tmp = app ({
    email: email,
    apikey: apikey,
    timeout: 1
  });

  tmp.account.status (function (err, data) {
    var error = err && err.error;

    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'request failed')
      .isError ('fail', 'err.error', error)
      .isExactly ('warn', 'err.error.code', error && error.code, 'TIMEOUT')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

// Start the tests
dotest.run (1000);
<commit_msg>Test(main): Improved test coverage<commit_after>/*
Name:           gtmetrix - test.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-gtmetrix
Feedback:       https://github.com/fvdm/nodejs-gtmetrix/issues
License:        Unlicense / Public Domain (see UNLICENSE file)
                (https://github.com/fvdm/nodejs-gtmetrix/raw/develop/LICENSE)
*/

var path = require ('path');
var dotest = require ('dotest');
var app = require (path.join (__dirname, path.sep));

// Setup
// $ env GTMETRIX_EMAIL= GTMETRIX_APIKEY= npm test
var email = process.env.GTMETRIX_EMAIL || null;
var apikey = process.env.GTMETRIX_APIKEY || null;
var timeout = process.env.GTMETRIX_TIMEOUT || 5000;
var location = process.env.GTMETRIX_LOCATION || 2;
var browser = process.env.GTMETRIX_BROWSER || 3;

var gtmetrix = app ({
  email: email,
  apikey: apikey,
  timeout: timeout
});

var cache = {
  url: 'http://example.net/',
  location: location,
  browser: browser
};

dotest.add ('account.status', function (test) {
  gtmetrix.account.status (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('browsers.list', function (test) {
  gtmetrix.browsers.list (function (err, data) {
    test (err)
      .isArray ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isObject ('warn', 'data[0]', data && data [0])
      .done ();
  });
});

dotest.add ('browsers.get', function (test) {
  gtmetrix.browsers.get (3, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.id', data && data.id, 3)
      .done ();
  });
});

dotest.add ('locations.list', function (test) {
  gtmetrix.locations.list (function (err, data) {
    test (err)
      .isArray ('fail', 'data', data)
      .isNotEmpty ('fail', 'data', data)
      .isObject ('warn', 'data[0]', data && data [0])
      .done ();
  });
});

dotest.add ('test.create', function (test) {
  gtmetrix.test.create (cache, function (err, data) {
    cache.test = data;
    test (err)
      .isObject ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('test.get - without polling', function (test) {
  gtmetrix.test.get (cache.test.test_id, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isString ('warn', 'data.state', data && data.state)
      .done ();
  });
});

dotest.add ('test.get - with polling', function (test) {
  gtmetrix.test.get (cache.test.test_id, 5000, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.state', data && data.state, 'completed')
      .done ();
  });
});

dotest.add ('test.get resource - binary with polling', function (test) {
  gtmetrix.test.get (cache.test.test_id, 'report-pdf-full', 5000, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('test.get resource - non-binary with polling', function (test) {
  gtmetrix.test.get (cache.test.test_id, 'yslow', 5000, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.u', data && data.u, cache.url)
      .done ();
  });
});

dotest.add ('Error: API error - without polling', function (test) {
  gtmetrix.test.get ('0', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: API error - resource with default polling', function (test) {
  gtmetrix.test.get ('0', 'yslow', true, function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: request failed (timeout)', function (test) {
  var tmp = app ({
    email: email,
    apikey: apikey,
    timeout: 1
  });

  tmp.account.status (function (err, data) {
    var error = err && err.error;

    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'request failed')
      .isError ('fail', 'err.error', error)
      .isExactly ('warn', 'err.error.code', error && error.code, 'TIMEOUT')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

// Start the tests
dotest.run (1000);
<|endoftext|>


<commit_before>'use strict';
var test = require('ava');
var claim = require('./');

test('.pass()', function (t) {
	claim.pass();
	t.end();
});

test('.fail()', function (t) {
	claim.throws(function () {
		claim.fail();
	});

	t.end();
});

test('.ok()', function (t) {
	claim.throws(function () {
		claim.ok(0);
		claim.ok(false);
	});

	claim.doesNotThrow(function () {
		claim.ok(1);
		claim.ok(true);
	});

	t.end();
});

test('.notOk()', function (t) {
	claim.throws(function () {
		claim.notOk(1);
		claim.notOk(true);
	});

	claim.doesNotThrow(function () {
		claim.notOk(0);
		claim.notOk(false);
	});

	t.end();
});

test('should be true', function (t) {
	claim.true(true);
	t.end();
});

test('should be false', function (t) {
	claim.false(false);
	t.end();
});

test('should be equal', function (t) {
	claim.is('foo', 'foo');
	t.end();
});

test('should not be equal', function (t) {
	claim.not('foo', 'bar');
	t.end();
});

test('should be same', function (t) {
	claim.same({a: 'a'}, {a: 'a'});
	claim.same(['a', 'b'], ['a', 'b']);
	t.end();
});

test('should not be same', function (t) {
	claim.notSame({a: 'a'}, {a: 'b'});
	claim.notSame(['a', 'b'], ['c', 'd']);
	t.end();
});

test('should throw an error', function (t) {
	claim.throws(function () {
		claim.is('foo', 'bar');
	});

	t.end();
});

test('should not throw an error', function (t) {
	claim.doesNotThrow(function () {
		claim.is('foo', 'foo');
	});

	t.end();
});

test('should not be an error', function (t) {
	claim.error(false);
	t.end();
});

test('should match a regex', function (t) {
	claim.regexTest(/^abc$/, 'abc');
	t.end();
});

test('should be an error', function (t) {
	try {
		claim.ifError(new Error());
	} catch (err) {
		t.assert(err);
	}

	t.end();
});
<commit_msg>improve `.pass()` test<commit_after>'use strict';
var test = require('ava');
var claim = require('./');

test('.pass()', function (t) {
	claim.doesNotThrow(function () {
		claim.pass();
	});

	t.end();
});

test('.fail()', function (t) {
	claim.throws(function () {
		claim.fail();
	});

	t.end();
});

test('.ok()', function (t) {
	claim.throws(function () {
		claim.ok(0);
		claim.ok(false);
	});

	claim.doesNotThrow(function () {
		claim.ok(1);
		claim.ok(true);
	});

	t.end();
});

test('.notOk()', function (t) {
	claim.throws(function () {
		claim.notOk(1);
		claim.notOk(true);
	});

	claim.doesNotThrow(function () {
		claim.notOk(0);
		claim.notOk(false);
	});

	t.end();
});

test('should be true', function (t) {
	claim.true(true);
	t.end();
});

test('should be false', function (t) {
	claim.false(false);
	t.end();
});

test('should be equal', function (t) {
	claim.is('foo', 'foo');
	t.end();
});

test('should not be equal', function (t) {
	claim.not('foo', 'bar');
	t.end();
});

test('should be same', function (t) {
	claim.same({a: 'a'}, {a: 'a'});
	claim.same(['a', 'b'], ['a', 'b']);
	t.end();
});

test('should not be same', function (t) {
	claim.notSame({a: 'a'}, {a: 'b'});
	claim.notSame(['a', 'b'], ['c', 'd']);
	t.end();
});

test('should throw an error', function (t) {
	claim.throws(function () {
		claim.is('foo', 'bar');
	});

	t.end();
});

test('should not throw an error', function (t) {
	claim.doesNotThrow(function () {
		claim.is('foo', 'foo');
	});

	t.end();
});

test('should not be an error', function (t) {
	claim.error(false);
	t.end();
});

test('should match a regex', function (t) {
	claim.regexTest(/^abc$/, 'abc');
	t.end();
});

test('should be an error', function (t) {
	try {
		claim.ifError(new Error());
	} catch (err) {
		t.assert(err);
	}

	t.end();
});
<|endoftext|>


<commit_before>/*
Name:         openkvk - test.js
Description:  Test script for openkvk.js
Source:       https://github.com/fvdm/nodejs-openkvk
Feedback:     https://github.com/fvdm/nodejs-openkvk/issues
License:      Public Domain / Unlicense (see LICENSE file)
*/

var dotest = require ('dotest');
var app = require ('./');

// Setup
var timeout = process.env.testTimeout || 5000;

// Tests
dotest.add ('Module', function (test) {
  test ()
    .isFunction ('fail', 'exports', app)
    .done ();
});

dotest.add ('Error: invalid params', function (test) {
  app (null, function (err) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid params')
      .done ();
  });
});

dotest.add ('Error: no results', function (test) {
  var params = {
    entity: 'software',
    country: 'NL',
    term: null,
    limit: 1,
    price: 0
  };

  app (params, timeout, function (err) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'no results')
      .done ();
  });
});

dotest.add ('Search by ID', function (test) {
  var params = {
    id: 512939461
  };

  app (params, timeout, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.trackId', data && data.trackId, params.id)
      .done ();
  });
});

dotest.add ('Search by term', function (test) {
  var params = {
    entity: 'software',
    country: 'NL',
    term: 'github',
    limit: 1,
    price: 0
  };

  app (params, timeout, function (err, data) {
    var item = data && data.results && data.results [0];

    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.resultCount', data && data.resultCount, 1)
      .isArray ('fail', 'data.results', data && data.results)
      .isNotEmpty ('fail', 'data.results', data && data.results)
      .isObject ('fail', 'data.results[0]', item)
      .isExactly ('fail', 'data.results[0].kind', item && item.kind, 'software')
      .done ();
  });
});

// Start the tests
dotest.run ();
<commit_msg>test(main): Add http error test<commit_after>/*
Name:         openkvk - test.js
Description:  Test script for openkvk.js
Source:       https://github.com/fvdm/nodejs-openkvk
Feedback:     https://github.com/fvdm/nodejs-openkvk/issues
License:      Public Domain / Unlicense (see LICENSE file)
*/

var dotest = require ('dotest');
var app = require ('./');

// Setup
var timeout = process.env.testTimeout || 5000;

// Tests
dotest.add ('Module', function (test) {
  test ()
    .isFunction ('fail', 'exports', app)
    .done ();
});

dotest.add ('Error: invalid params', function (test) {
  app (null, function (err) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid params')
      .done ();
  });
});

dotest.add ('Error: no results', function (test) {
  var params = {
    entity: 'software',
    country: 'NL',
    term: null,
    limit: 1,
    price: 0
  };

  app (params, timeout, function (err) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'no results')
      .done ();
  });
});

dotest.add ('Error: http error', function (test) {
  app ({}, 1, function (err, data) {
    test (null)
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'http error')
      .isUndefined ('fail', 'err.statusCode', err && err.statusCode)
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Search by ID', function (test) {
  var params = {
    id: 512939461
  };

  app (params, timeout, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.trackId', data && data.trackId, params.id)
      .done ();
  });
});

dotest.add ('Search by term', function (test) {
  var params = {
    entity: 'software',
    country: 'NL',
    term: 'github',
    limit: 1,
    price: 0
  };

  app (params, timeout, function (err, data) {
    var item = data && data.results && data.results [0];

    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('fail', 'data.resultCount', data && data.resultCount, 1)
      .isArray ('fail', 'data.results', data && data.results)
      .isNotEmpty ('fail', 'data.results', data && data.results)
      .isObject ('fail', 'data.results[0]', item)
      .isExactly ('fail', 'data.results[0].kind', item && item.kind, 'software')
      .done ();
  });
});

// Start the tests
dotest.run ();
<|endoftext|>


<commit_before>// test.js

import test from 'ava'
import fn from './'

test('copy files and shout', t => {
  fn(['file1', 'file2', 'dir'], 'dest')
})

test('copy single files', t => {
  fn('file', 'dest')
})
<commit_msg>Fix test<commit_after>// test.js

import test from 'ava'
import fn from './'

test('copy files and shout', t => {
  fn(['LICENSE', 'package.json', 'demo'], 'dest')
})

test('copy single files', t => {
  fn('LICENSE', 'dest')
})
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-3 10:39:41<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var average = require('./')
var test = require('tape')
var polygon = require('turf-polygon')
var point = require('turf-point')
var featurecollection =  require('turf-featurecollection')

test('median', function(t){
  var poly1 = polygon([[[0,0],[10,0],[10,10], [0,10]]])
  var poly2 = polygon([[[10,0],[20,10],[20,20], [20,0]]])
  var polyFC = featurecollection([poly1, poly2])
  var pt1 = point(1,1, {population: 500})
  var pt2 = point(1,3, {population: 400})
  var pt3 = point(14,2, {population: 600})
  var pt4 = point(13,1, {population: 500})
  var pt5 = point(19,7, {population: 200})
  var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5])

  var medianed = average(polyFC, ptFC, 'population', 'pop_med')

  t.equal(medianed.features[0].geometry.type, 'Polygon')
  t.equal(medianed.features[0].properties.pop_med, 450)
  t.equal(medianed.features[1].properties.pop_med, 500)

  t.end()
})<commit_msg>fixed up test naming<commit_after>var median = require('./')
var test = require('tape')
var polygon = require('turf-polygon')
var point = require('turf-point')
var featurecollection =  require('turf-featurecollection')

test('median', function(t){
  var poly1 = polygon([[[0,0],[10,0],[10,10], [0,10]]])
  var poly2 = polygon([[[10,0],[20,10],[20,20], [20,0]]])
  var polyFC = featurecollection([poly1, poly2])
  var pt1 = point(1,1, {population: 500})
  var pt2 = point(1,3, {population: 400})
  var pt3 = point(14,2, {population: 600})
  var pt4 = point(13,1, {population: 500})
  var pt5 = point(19,7, {population: 200})
  var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5])

  var medianed = median(polyFC, ptFC, 'population', 'pop_med')

  t.equal(medianed.features[0].geometry.type, 'Polygon')
  t.equal(medianed.features[0].properties.pop_med, 450)
  t.equal(medianed.features[1].properties.pop_med, 500)

  t.end()
})<|endoftext|>


<commit_before>var test = require('tape');
var center = require('./');
var fs = require('fs');

var boxFC = JSON.parse(fs.readFileSync(__dirname+'/fixtures/in/box.geojson'));
var blockFC = JSON.parse(fs.readFileSync(__dirname+'/fixtures/in/block.geojson'));

test('center', function(t){
  var boxFcCenter = center(boxFC);
  t.ok(boxFcCenter, 'should return the proper center for a FeatureCollection');
  t.deepEqual(boxFcCenter.geometry.coordinates, [65.56640625, 43.59448261855401]);

  var blockFcCenter = center(blockFC.features[0]);
  t.ok(blockFcCenter, 'should return the proper center for a FeatureCollection');
  t.deepEqual(blockFcCenter.geometry.coordinates, [-114.02900261988646,51.05007001220118]);

  boxFC.features.push(boxFcCenter);
  blockFC.features.push(blockFcCenter);
  fs.writeFileSync(__dirname+'/fixtures/out/box_out.geojson', JSON.stringify(boxFC,null,2));
  fs.writeFileSync(__dirname+'/fixtures/out/block_out.geojson', JSON.stringify(blockFC,null,2));

  t.end();
});
<commit_msg>test name typo<commit_after>var test = require('tape');
var center = require('./');
var fs = require('fs');

var boxFC = JSON.parse(fs.readFileSync(__dirname+'/fixtures/in/box.geojson'));
var blockFC = JSON.parse(fs.readFileSync(__dirname+'/fixtures/in/block.geojson'));

test('centroid', function(t){
  var boxFcCenter = center(boxFC);
  t.ok(boxFcCenter, 'should return the proper center for a FeatureCollection');
  t.deepEqual(boxFcCenter.geometry.coordinates, [65.56640625, 43.59448261855401]);

  var blockFcCenter = center(blockFC.features[0]);
  t.ok(blockFcCenter, 'should return the proper center for a FeatureCollection');
  t.deepEqual(blockFcCenter.geometry.coordinates, [-114.02900261988646,51.05007001220118]);

  boxFC.features.push(boxFcCenter);
  blockFC.features.push(blockFcCenter);
  fs.writeFileSync(__dirname+'/fixtures/out/box_out.geojson', JSON.stringify(boxFC,null,2));
  fs.writeFileSync(__dirname+'/fixtures/out/block_out.geojson', JSON.stringify(blockFC,null,2));

  t.end();
});
<|endoftext|>


<commit_before>var tape = require('tape')
var through = require('through2')
var each = require('./')

tape('each', function (t) {
  var s = through.obj()
  s.write('a')
  s.write('b')
  s.write('c')
  s.end()

  s.on('end', function () {
    t.end()
  })

  var expected = ['a', 'b', 'c']
  each(s, function (data, next) {
    t.same(data, expected.shift())
    next()
  })
})

tape('each and callback', function (t) {
  var s = through.obj()
  s.write('a')
  s.write('b')
  s.write('c')
  s.end()

  var expected = ['a', 'b', 'c']
  each(s, function (data, next) {
    t.same(data, expected.shift())
    next()
  }, function () {
    t.end()
  })
})

tape('each (write after)', function (t) {
  var s = through.obj()
  s.on('end', function () {
    t.end()
  })

  var expected = ['a', 'b', 'c']
  each(s, function (data, next) {
    t.same(data, expected.shift())
    next()
  })

  setTimeout(function () {
    s.write('a')
    s.write('b')
    s.write('c')
    s.end()
  }, 100)
})

tape('each error', function (t) {
  var s = through.obj()
  s.write('hello')
  s.on('error', function (err) {
    t.same(err.message, 'stop')
    t.end()
  })

  each(s, function (data, next) {
    next(new Error('stop'))
  })
})

tape('each error and callback', function (t) {
  var s = through.obj()
  s.write('hello')

  each(s, function (data, next) {
    next(new Error('stop'))
  }, function (err) {
    t.same(err.message, 'stop')
    t.end()
  })
})

tape('each with falsey values', function (t) {
  var s = through.obj()
  s.write(0)
  s.write(false)
  s.write(undefined)
  s.end()

  s.on('end', function () {
    t.end()
  })

  var expected = [0, false]
  var count = 0
  each(s, function (data, next) {
    count++
    t.same(data, expected.shift())
    next()
  }, function () {
    t.same(count, 2)
  })
})

<commit_msg>add huge stack test<commit_after>var tape = require('tape')
var through = require('through2')
var each = require('./')

tape('each', function (t) {
  var s = through.obj()
  s.write('a')
  s.write('b')
  s.write('c')
  s.end()

  s.on('end', function () {
    t.end()
  })

  var expected = ['a', 'b', 'c']
  each(s, function (data, next) {
    t.same(data, expected.shift())
    next()
  })
})

tape('each and callback', function (t) {
  var s = through.obj()
  s.write('a')
  s.write('b')
  s.write('c')
  s.end()

  var expected = ['a', 'b', 'c']
  each(s, function (data, next) {
    t.same(data, expected.shift())
    next()
  }, function () {
    t.end()
  })
})

tape('each (write after)', function (t) {
  var s = through.obj()
  s.on('end', function () {
    t.end()
  })

  var expected = ['a', 'b', 'c']
  each(s, function (data, next) {
    t.same(data, expected.shift())
    next()
  })

  setTimeout(function () {
    s.write('a')
    s.write('b')
    s.write('c')
    s.end()
  }, 100)
})

tape('each error', function (t) {
  var s = through.obj()
  s.write('hello')
  s.on('error', function (err) {
    t.same(err.message, 'stop')
    t.end()
  })

  each(s, function (data, next) {
    next(new Error('stop'))
  })
})

tape('each error and callback', function (t) {
  var s = through.obj()
  s.write('hello')

  each(s, function (data, next) {
    next(new Error('stop'))
  }, function (err) {
    t.same(err.message, 'stop')
    t.end()
  })
})

tape('each with falsey values', function (t) {
  var s = through.obj()
  s.write(0)
  s.write(false)
  s.write(undefined)
  s.end()

  s.on('end', function () {
    t.end()
  })

  var expected = [0, false]
  var count = 0
  each(s, function (data, next) {
    count++
    t.same(data, expected.shift())
    next()
  }, function () {
    t.same(count, 2)
  })
})

tape('huge stack', function (t) {
  var s = through.obj()

  for (var i = 0; i < 5000; i++) {
    s.write('foo')
  }

  s.end()

  each(s, function (data, cb) {
    if (data !== 'foo') t.fail('bad data')
    cb()
  }, function (err) {
    t.error(err, 'no error')
    t.end()
  })
})
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-13 20:52:46<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>
var assert = require('assert')
var treeDiff = require('./index')

var nodes = {
  1: [],
  2: [1],
  3: [2],
  4: [2],
  5: [4],
  6: [3, 5],
  7: [6],
  8: [5],
  9: [8]
}

/* the graph:

    4-5-8-9
   /   \
1-2-3---6-7

*/

var readParents = function(id, cb) {
  cb(null, nodes[id])
}

describe('tree-difference', function() {
  it('should find the subtree that connects one node with another', function(done) {
    var expected = [9, 8]
    treeDiff(7, 9, readParents, function(err, res) {
      assert.deepEqual(res, expected)
      done()
    })
  })
})
<commit_msg>refactor test, add more<commit_after>
var assert = require('assert')
var treeDiff = require('./index')

var nodes = {
  1: [],
  2: [1],
  3: [2],
  4: [2],
  5: [4],
  6: [3, 5],
  7: [6],
  8: [5],
  9: [8]
}

/* the graph:

    4-5-8-9
   /   \
1-2-3---6-7

*/

var readParents = function(id, cb) {
  cb(null, nodes[id])
}

var tests = [
  {from: 7, to: 9, expected: [9, 8]},
  {from: 6, to: 7, expected: [7]}
]

describe('tree-difference', function() {
  tests.forEach(function(each, i) {
    it('should run test ' + i, function(done) {
      treeDiff(each.from, each.to, readParents, function(err, res) {
        assert.deepEqual(res, each.expected)
        done()
      })
    })
  })
})
<|endoftext|>


<commit_before>/* jshint node: true */
/* jshint jquery: true */
/* jshint sub: true */
/* global window,document, $,alert,history */
'use strict';
var log = function(msg)
{
  console.log('TEST:', msg);
};

//----------

var _ = require('./spacetime').lazy();
var __ = require('./spacetime').timeline();

log('test start');

var _e = _([2, 7, 1, 8, 2, 8]);
_e.take(5).compute(function(x)
{
  log(x)
});
//wrap a recursive function to memoize
// must be at the definition in the same scope
var fib = _(function(n)
{
  if (n <= 1)
    return 1; // as the Fib definition in Math
  else
    return fib(n - 2) + fib(n - 1); // as the Fib definition in Math
});

//var _fib = _().generator(fib); //fib inginite sequence, won't actually calc
var _fib = _(fib);

var fib10 = _fib
  .take(10)
  .compute(function(x)
  {
    log(x);
  });

var increment = function(x)
{
  return x + 1;
};

var add = function(a, b)
{
  return a + b;
};

var multiply = function(a, b)
{
  return a * b;
};

var _d = _([1, 2, 3, 4])
  .map(increment)
  .take(3)
  .reduce(add);

_d
  .compute(function(x)
  {
    log(x);
  });

//===========================

var customTL = function(tl)
{
  var interval = setInterval(function()
  {
    tl.next();
  }, 100);

  tl.stop = function()
  {
    clearInterval(interval);
  };
};

var __a =
  __(customTL)
  .map(function()
  {
    return 0;
  })
  .take(5);

__a
  .compute(function(x)
  {
    log(x);
  });

var natural = _(function(n)
{
  return n;
});
var _natural = _(natural);
var _pi = _([3, 1, 4, 1, 5, 9, 2]);

//var it = _natural.it();
var it = _pi.it();

var __b = __().interval(3000)
  .map(function()
  {
    return it.next();
  })
  .take(2);

__b
  .compute(function(x)
  {
    log(x);
  });
<commit_msg>commit<commit_after>/* jshint node: true */
/* jshint jquery: true */
/* jshint sub: true */
/* global window,document, $,alert,history */
'use strict';
var log = function(msg)
{
  console.log('TEST:', msg);
};

//----------

var _ = require('./spacetime').lazy();
var __ = require('./spacetime').timeline();

log('test start');

var _e = _([2, 7, 1, 8, 2, 8]);

_e.take(5).compute(function(x)
{
  log(x);
});
//wrap a recursive function to memoize
// must be at the definition in the same scope
var fib = _(function(n)
{
  if (n <= 1)
    return 1; // as the Fib definition in Math
  else
    return fib(n - 2) + fib(n - 1); // as the Fib definition in Math
});

//var _fib = _().generator(fib); //fib inginite sequence, won't actually calc
var _fib = _(fib);

var fib10 = _fib
  .take(10)
  .compute(function(x)
  {
    log(x);
  });

var increment = function(x)
{
  return x + 1;
};

var add = function(a, b)
{
  return a + b;
};

var multiply = function(a, b)
{
  return a * b;
};

var _d = _([1, 2, 3, 4])
  .map(increment)
  .take(3)
  .reduce(add);

_d
  .compute(function(x)
  {
    log(x);
  });

//===========================

var customTL = function(tl)
{
  var interval = setInterval(function()
  {
    tl.next();
  }, 100);

  tl.stop = function()
  {
    clearInterval(interval);
  };
};

var __a =
  __(customTL)
  .map(function()
  {
    return 0;
  })
  .take(5);

__a
  .compute(function(x)
  {
    log(x);
  });

var natural = _(function(n)
{
  return n;
});
var _natural = _(natural);
var _pi = _([3, 1, 4, 1, 5, 9, 2]);

//var it = _natural.it();
var it = _pi.it();

var __b = __().interval(3000)
  .map(function()
  {
    return it.next();
  })
  .take(2);

__b
  .compute(function(x)
  {
    log(x);
  });
<|endoftext|>