<commit_before>var tap = require('../tap');
var buf = require('buffer');

tap.count(75);

// testing vars
var foo1 = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var foo2 = { "a": 2, "b": [false, true, "a"] };
var foo3 = { "a": 3, "b": { "1": false, "x": 54 } };
var foo4 = { "a": { "b": { "c": { "d": 1 } } } };
var foo5 = '{\n "a": {\n  "b": {\n   "c": {\n    "d": 1\n   }\n  }\n }\n}'
var foo6 = { "location": { "city": { "name": "Chattanooga", "population": 167674 }, "state": { "abbreviation": "TN", "name": "Tennessee", "population": 6403000 } }, "name": "Jim Cowart", "company": "appendTo" };
var foo7 = '{"location":{"city":{"name":"Chattanooga","population":167674},"state":{"abbreviation":"TN","name":"Tennessee","population":6403000}},"name":"Jim Cowart","company":"appendTo"}';
var foo8 = { "a": [ { "b": [ { "c": [ [1,2,3], [], [4,5,6] ] }, { "d": { "e": { "f": [7,8,9], "g": [ [9,8,7], [] ] } } } ] }, "g", [ [ [ { "h": [ [ [ [ [6,5,4] ] ] ] ] } ] ] ], { "i": [ { "j": [ { "k": [ [3,2,1] ] } ] } ] } ] };
var foo9 = '{"a":[{"b":[{"c":[[1,2,3],[],[4,5,6]]},{"d":{"e":{"g":[[9,8,7],[]],"f":[7,8,9]}}}]},"g",[[[{"h":[[[[[6,5,4]]]]]}]]],{"i":[{"j":[{"k":[[3,2,1]]}]}]}]}';
var fooA = { "1800": { "name": "Generic Access", "type": "org.bluetooth.service.generic_access" }, "1801": { "name": "Generic Attribute", "type": "org.bluetooth.service.generic_attribute" }, "1802": { "name": "Immediate Alert", "type": "org.bluetooth.service.immediate_alert" } };
var fooB = '{"1800":{"name":"Generic Access","type":"org.bluetooth.service.generic_access"},"1801":{"name":"Generic Attribute","type":"org.bluetooth.service.generic_attribute"},"1802":{"name":"Immediate Alert","type":"org.bluetooth.service.immediate_alert"}}';

// testing replacer array and functions
var censor_arr = ['transport','month'];
function censor(key, value) {
  tap.ok(this[key] == value, '"this" value correct in replacer');
  if (typeof(value) == "string") {
    return undefined;
  }
  return value;
}

//  1:objects                                   2:string                             3:message                       4:replacer         5:spacer
var objs = [
  { 1:null,                                     2:'null',                            3:'non object null',            4:null,            5:null },
  { 1:true,                                     2:'true',                            3:'non object bool',            4:null,            5:null },
  { 1:3,                                        2:'3',                               3:'non object number',          4:null,            5:null },
  { 1:7.42,                                     2:'7.42',                            3:'non object double',          4:null,            5:null },
  { 1:[],                                       2:'[]',                              3:'empty array',                4:null,            5:null },
  { 1:[0, 1, 2],                                2:'[0,1,2]',                         3:'array',                      4:null,            5:null },
  { 1:[3,"a"],                                  2:'[3,"a"]',                         3:'mixed array',                4:null,            5:null },
  { 1:[3,false,3.454,"a","a"],                  2:'[3,false,3.454,"a","a"]',         3:'repeat value array',         4:null,            5:null },
  { 1:[[[],[],[]],[[],[[1,2]]]],                2:'[[[],[],[]],[[],[[1,2]]]]',       3:'super nested arrays',        4:null,            5:null },
  { 1:foo2,                                     2:'{"a":2,"b":[false,true,"a"]}',    3:'sringify lvl 1 array',       4:null,            5:null },
  { 1:{},                                       2:'{}',                              3:'empty object',               4:null,            5:null },
  { 1:Object(),                                 2:'{}',                              3:'empty object constructor',   4:null,            5:null },
  { 1:{"hi":5},                                 2:'{"hi":5}',                        3:'object explicit key',        4:null,            5:null },
  { 1:{hi:5},                                   2:'{"hi":5}',                        3:'object implicit key',        4:null,            5:null },
  { 1:{"a":{}},                                 2:'{"a":{}}',                        3:'lvl 1 empty object',         4:null,            5:null },
  { 1:foo3,                                     2:'{"a":3,"b":{"1":false,"x":54}}',  3:'lvl 1 object',               4:null,            5:null },
  { 1:foo4,                                     2:'{"a":{"b":{"c":{"d":1}}}}',       3:'super nested objects',       4:null,            5:null },
  { 1:foo6,                                     2:foo7,                              3:'realistic object',           4:null,            5:null },
  { 1:{"hi":5},                                 2:'{\n  "hi": 5\n}',                 3:'spacer string',              4:null,            5:'  ' },
  { 1:{"hi":5},                                 2:'{\n   "hi": 5\n}',                3:'spacer number',              4:null,            5:3 },
  { 1:foo4,                                     2:foo5,                              3:'super nested spacer',        4:null,            5:' ' },
  { 1:foo1,                                     2:'{"month":7,"transport":"car"}',   3:'replacer array',             4:censor_arr,      5:null },
  { 1:{a: function () {}, b: 5},                2:'{"b":5}',                         3:'function',                   4:null,            5:null },
  { 1:[1,function(){},2],                       2:'[1,null,2]',                      3:'function in array',          4:null,            5:null },
  { 1:new buf.Buffer([11,22,33,44]),            2:'[11,22,33,44]',                   3:'buffer',                     4:null,            5:null },
  { 1:NaN,                                      2:'null',                            3:'NaN',                        4:null,            5:null },
  { 1:Infinity,                                 2:'null',                            3:'Infinity',                   4:null,            5:null },
  { 1:-Infinity,                                2:'null',                            3:'-Infinity',                  4:null,            5:null },
  { 1:[[],"11"],                                2:'[[],"11"]',                       3:'arr in arr then value',      4:null,            5:null },
  { 1:'hello\n',                                2:'"hello\\n"',                      3:'non object string',          4:null,            5:null },
]

var objs2 = [
  { 1:{"hi":5},                                 2:'{\n123456789A"hi": 5\n}',         3:'spacer string long',         4:null,            5:'123456789AB' },
  { 1:foo1,                                     2:'{"month":45,"week":7}',           3:'replacer function',          4:censor,          5:null },
  { 1:[[], {}, [null], [0], [[{}]], "14121269654077727"], 2:'[[],{},[null],[0],[[{}]],"14121269654077727"]', 3:'complex object', 4:null, 5:null},
  { 1:foo1,                                     2:'{"month":7,"transport":"car"}',   3:'replacer array',             4:censor_arr,      5:null },
  { 1:foo8,                                     2:foo9,                              3:'array object mess',          4:null,            5:null },
  { 1:fooA,                                     2:fooB,                              3:'input file test',            4:null,            5:null },
]

// Simple parsing testing
console.log('# parsing tesing');
tap.ok(JSON.parse("{\"hi\": 5}").hasOwnProperty, 'json object is real object');
tap.ok(JSON.parse("[0, 1, 2]").slice, 'json array is real array');

// string->parse->stringify should equal original string
for (var i in objs) {
  var obj = JSON.parse(objs[i][2])
  var res = JSON.stringify(obj, objs[i][4], objs[i][5]);
  tap.eq(res, objs[i][2], objs[i][3]);

  tap.eq(JSON.stringify(objs[i][1], objs[i][4], objs[i][5]), objs[i][2], objs[i][3]);
}

// stringified object should equal corresponding string
for (var i in objs2) {
  var res = JSON.stringify(objs[i][1], objs[i][4], objs[i][5]);
  tap.eq(res, objs[i][2], objs[i][3]);
}

var d = new Date(42);
tap.eq(JSON.stringify({
  toJSON: function () { return "foo"; }
}), "\"foo\"", 'toJSON called on dates');

var a = { toJSON: function () { return "hello"; }}
tap.eq(JSON.stringify(a), '"hello"', 'toJSON called on objects')

var a = { toJSON: function () { return { toJSON: function () { return 5; }}; }}
tap.eq(JSON.stringify(a), '{}', 'toJSON isnt recursive')

var arr = JSON.parse("[[], {}, [null], [0], [[{}]], \"14121269654077727\"]");
<commit_msg>Corrects JSON test to evaluate all tests.<commit_after>var tap = require('../tap');
var buf = require('buffer');

tap.count(75);

// testing vars
var foo1 = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var foo2 = { "a": 2, "b": [false, true, "a"] };
var foo3 = { "a": 3, "b": { "1": false, "x": 54 } };
var foo4 = { "a": { "b": { "c": { "d": 1 } } } };
var foo5 = '{\n "a": {\n  "b": {\n   "c": {\n    "d": 1\n   }\n  }\n }\n}'
var foo6 = { "location": { "city": { "name": "Chattanooga", "population": 167674 }, "state": { "abbreviation": "TN", "name": "Tennessee", "population": 6403000 } }, "name": "Jim Cowart", "company": "appendTo" };
var foo7 = '{"location":{"city":{"name":"Chattanooga","population":167674},"state":{"abbreviation":"TN","name":"Tennessee","population":6403000}},"name":"Jim Cowart","company":"appendTo"}';
var foo8 = { "a": [ { "b": [ { "c": [ [1,2,3], [], [4,5,6] ] }, { "d": { "e": { "f": [7,8,9], "g": [ [9,8,7], [] ] } } } ] }, "g", [ [ [ { "h": [ [ [ [ [6,5,4] ] ] ] ] } ] ] ], { "i": [ { "j": [ { "k": [ [3,2,1] ] } ] } ] } ] };
var foo9 = '{"a":[{"b":[{"c":[[1,2,3],[],[4,5,6]]},{"d":{"e":{"g":[[9,8,7],[]],"f":[7,8,9]}}}]},"g",[[[{"h":[[[[[6,5,4]]]]]}]]],{"i":[{"j":[{"k":[[3,2,1]]}]}]}]}';
var fooA = { "1800": { "name": "Generic Access", "type": "org.bluetooth.service.generic_access" }, "1801": { "name": "Generic Attribute", "type": "org.bluetooth.service.generic_attribute" }, "1802": { "name": "Immediate Alert", "type": "org.bluetooth.service.immediate_alert" } };
var fooB = '{"1800":{"name":"Generic Access","type":"org.bluetooth.service.generic_access"},"1801":{"name":"Generic Attribute","type":"org.bluetooth.service.generic_attribute"},"1802":{"name":"Immediate Alert","type":"org.bluetooth.service.immediate_alert"}}';

// testing replacer array and functions
var censor_arr = ['transport','month'];
function censor(key, value) {
  tap.ok(this[key] == value, '"this" value correct in replacer');
  if (typeof(value) == "string") {
    return undefined;
  }
  return value;
}

function object_equivalence (a, b) {
  return Object.keys(a).sort().join(',') == Object.keys(b).sort().join(',');
}

//  1:objects                                   2:string                             3:message                       4:replacer         5:spacer
var objs = [
  { 1:null,                                     2:'null',                            3:'non object null',            4:null,            5:null },
  { 1:true,                                     2:'true',                            3:'non object bool',            4:null,            5:null },
  { 1:3,                                        2:'3',                               3:'non object number',          4:null,            5:null },
  { 1:7.42,                                     2:'7.42',                            3:'non object double',          4:null,            5:null },
  { 1:[],                                       2:'[]',                              3:'empty array',                4:null,            5:null },
  { 1:[0, 1, 2],                                2:'[0,1,2]',                         3:'array',                      4:null,            5:null },
  { 1:[3,"a"],                                  2:'[3,"a"]',                         3:'mixed array',                4:null,            5:null },
  { 1:[3,false,3.454,"a","a"],                  2:'[3,false,3.454,"a","a"]',         3:'repeat value array',         4:null,            5:null },
  { 1:[[[],[],[]],[[],[[1,2]]]],                2:'[[[],[],[]],[[],[[1,2]]]]',       3:'super nested arrays',        4:null,            5:null },
  { 1:foo2,                                     2:'{"a":2,"b":[false,true,"a"]}',    3:'sringify lvl 1 array',       4:null,            5:null },
  { 1:{},                                       2:'{}',                              3:'empty object',               4:null,            5:null },
  { 1:Object(),                                 2:'{}',                              3:'empty object constructor',   4:null,            5:null },
  { 1:{"hi":5},                                 2:'{"hi":5}',                        3:'object explicit key',        4:null,            5:null },
  { 1:{hi:5},                                   2:'{"hi":5}',                        3:'object implicit key',        4:null,            5:null },
  { 1:{"a":{}},                                 2:'{"a":{}}',                        3:'lvl 1 empty object',         4:null,            5:null },
  { 1:foo3,                                     2:'{"a":3,"b":{"1":false,"x":54}}',  3:'lvl 1 object',               4:null,            5:null },
  { 1:foo4,                                     2:'{"a":{"b":{"c":{"d":1}}}}',       3:'super nested objects',       4:null,            5:null },
  { 1:foo6,                                     2:foo7,                              3:'realistic object',           4:null,            5:null },
  { 1:{"hi":5},                                 2:'{\n  "hi": 5\n}',                 3:'spacer string',              4:null,            5:'  ' },
  { 1:{"hi":5},                                 2:'{\n   "hi": 5\n}',                3:'spacer number',              4:null,            5:3 },
  { 1:foo4,                                     2:foo5,                              3:'super nested spacer',        4:null,            5:' ' },
  { 1:{a: function () {}, b: 5},                2:'{"b":5}',                         3:'function',                   4:null,            5:null },
  { 1:[1,function(){},2],                       2:'[1,null,2]',                      3:'function in array',          4:null,            5:null },
  { 1:new buf.Buffer([11,22,33,44]),            2:'[11,22,33,44]',                   3:'buffer',                     4:null,            5:null },
  { 1:NaN,                                      2:'null',                            3:'NaN',                        4:null,            5:null },
  { 1:Infinity,                                 2:'null',                            3:'Infinity',                   4:null,            5:null },
  { 1:-Infinity,                                2:'null',                            3:'-Infinity',                  4:null,            5:null },
  { 1:[[],"11"],                                2:'[[],"11"]',                       3:'arr in arr then value',      4:null,            5:null },
  { 1:'hello\n',                                2:'"hello\\n"',                      3:'non object string',          4:null,            5:null },
]

var objs2 = [
  { 1:{"hi":5},                                 2:'{\n123456789A"hi": 5\n}',         3:'spacer string long',         4:null,            5:'123456789AB' },
];

var objs3 = [
  { 1:foo1,                                     2:'{"month":45,"week":7}',           3:'replacer function',          4:censor,          5:null },
  { 1:[[], {}, [null], [0], [[{}]], "14121269654077727"], 2:'[[],{},[null],[0],[[{}]],"14121269654077727"]', 3:'complex object', 4:null, 5:null},
  { 1:foo1,                                     2:'{"month":7,"transport":"car"}',   3:'replacer array',             4:censor_arr,      5:null },
  { 1:foo8,                                     2:foo9,                              3:'array object mess',          4:null,            5:null },
  { 1:fooA,                                     2:fooB,                              3:'input file test',            4:null,            5:null },
]

// Simple parsing testing
console.log('# parsing tesing');
tap.ok(JSON.parse("{\"hi\": 5}").hasOwnProperty, 'json object is real object');
tap.ok(JSON.parse("[0, 1, 2]").slice, 'json array is real array');

// string->parse->stringify should equal original string
for (var i in objs) {
  var obj = JSON.parse(objs[i][2])
  var res = JSON.stringify(obj, objs[i][4], objs[i][5]);
  tap.eq(res, objs[i][2], objs[i][3]);

  tap.eq(JSON.stringify(objs[i][1], objs[i][4], objs[i][5]), objs[i][2], objs[i][3]);
}

// stringified object should equal corresponding string
for (var i in objs2) {
  var res = JSON.stringify(objs2[i][1], objs2[i][4], objs2[i][5]);
  tap.eq(res, objs2[i][2], objs2[i][3]);
}

// object should equal original object when stringified then parsed
for (var i in objs3) {
  var res = JSON.stringify(objs3[i][1], objs3[i][4], objs3[i][5]);
  var obj = JSON.parse(res);
  var obj2 = JSON.parse(objs3[i][2]);
  tap.ok(object_equivalence(obj, obj2), objs3[i][3]);
}

var d = new Date(42);
tap.eq(JSON.stringify({
  toJSON: function () { return "foo"; }
}), "\"foo\"", 'toJSON called on dates');

var a = { toJSON: function () { return "hello"; }}
tap.eq(JSON.stringify(a), '"hello"', 'toJSON called on objects')

var a = { toJSON: function () { return { toJSON: function () { return 5; }}; }}
tap.eq(JSON.stringify(a), '{}', 'toJSON isnt recursive')

var arr = JSON.parse("[[], {}, [null], [0], [[{}]], \"14121269654077727\"]");
<|endoftext|>


<commit_before>

const mongoose = require('mongoose');
const expect = require('chai').expect;

var TestUtils = {

    getObjectId: function() {
        return mongoose.Types.ObjectId();
    },

    expectEqualObjectId: function(got, exp) {
        var msg = 'Object IDs match';
        expect(got.toString(), msg).to.be.equal(exp.toString());
    },

    connectTestDb: function() {
        var testDbURI = 'mongodb://localhost:27017/bookwyrmstest';
        mongoose.Promise = global.Promise;
        mongoose.connect(testDbURI);
    }
};

TestUtils.createTradeReq = function() {
    return {
        from: TestUtils.getObjectId(),
        to: TestUtils.getObjectId(),
        book: TestUtils.getObjectId()
    };
};

module.exports = TestUtils;
<commit_msg>Added a function to clear collection from DB.<commit_after>

const mongoose = require('mongoose');
const expect = require('chai').expect;

var TestUtils = {

    getObjectId: function() {
        return mongoose.Types.ObjectId();
    },

    expectEqualObjectId: function(got, exp) {
        var msg = 'Object IDs match';
        expect(got.toString(), msg).to.be.equal(exp.toString());
    },

    connectTestDb: function() {
        var testDbURI = 'mongodb://localhost:27017/bookwyrmstest';
        mongoose.Promise = global.Promise;
        mongoose.connect(testDbURI);
    },

    clearTestDb: function(coll, cb) {
        mongoose.connection.db.dropCollection(coll, cb);
    }
};

TestUtils.createTradeReq = function() {
    return {
        from: TestUtils.getObjectId(),
        to: TestUtils.getObjectId(),
        book: TestUtils.getObjectId()
    };
};

module.exports = TestUtils;
<|endoftext|>


<commit_before>/* global require, describe, it */
'use strict';

// MODULES //

var chai = require( 'chai' ),
	matrix = require( 'dstructs-matrix' ),
	noop = require( './fixtures/noop.js' ),
	add = require( './fixtures/add.js' ),
	apply = require( './../lib/apply.js' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'apply', function tests() {

	it( 'should export a function', function test() {
		expect( apply ).to.be.a( 'function' );
	});

	it( 'should throw an error if not provided a function', function test() {
		var values = [
			'5',
			5,
			NaN,
			true,
			null,
			undefined,
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				apply( value, matrix([5,5]) );
			};
		}
	});

	it( 'should throw an error if provided an options argument which is not an object', function test() {
		var values = [
			'5',
			true,
			null,
			undefined,
			[],
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				apply( noop, matrix([5,5]), value );
			};
		}
	});

	it( 'should throw an error if provided an invalid option', function test() {
		var values = [
			5,
			NaN,
			true,
			null,
			undefined,
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				apply( noop, matrix([5,5]), {
					'dtype': value
				});
			};
		}
	});

	it( 'should throw an error if not provided input values (matrices or numbers)', function test() {
		expect( foo ).to.throw( Error );
		expect( bar ).to.throw( Error );
		function foo() {
			apply( noop, {
				'out': true
			});
		}
		function bar() {
			apply( noop, 'beep', {
				'out': true
			});
		}
	});

	it( 'should throw an error if not provided at least one matrix', function test() {
		expect( foo ).to.throw( Error );
		function foo() {
			apply( noop, 1, 2, 3 );
		}
	});

	it( 'should throw an error if provided an output argument which is not a matrix', function test() {
		var values = [
			'5',
			5,
			NaN,
			true,
			null,
			undefined,
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				apply( noop, value, matrix([5,5]), {
					'out': true
				});
			};
		}
	});

	it( 'should throw an error if not provided matrix-like or numeric arguments', function test() {
		var values = [
			'5',
			true,
			null,
			undefined,
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue1( values[i] ) ).to.throw( TypeError );
			expect( badValue2( values[i] ) ).to.throw( TypeError );
		}
		function badValue1( value ) {
			return function() {
				apply( noop, matrix([5,5]), value, 5, {} );
			};
		}
		function badValue2( value ) {
			return function() {
				apply( noop, matrix([5,5]), 5, matrix([5,5]), value, {} );
			};
		}
	});

	it( 'should throw an error if provided incompatible matrix-like arguments', function test() {
		var values = [
			matrix([4,4]),
			matrix([0,0]),
			matrix([5,4])
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( Error );
		}
		function badValue( value ) {
			return function() {
				apply( noop, matrix([5,5]), value );
			};
		}
	});

	it( 'should apply a function to a single matrix', function test() {
		var mat,
			out,
			d, i;

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 1;
		}
		mat = matrix( d, [2,2], 'int8' );

		out = apply( add, mat, 1 );
		assert.strictEqual( out.toString(), '2,2;2,2' );
	});

	it( 'should apply a function to multiple matrices', function test() {
		var mat1,
			mat2,
			out,
			d, i;

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 1;
		}
		mat1 = matrix( d, [2,2], 'int8' );

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 2;
		}
		mat2 = matrix( d, [2,2], 'int8' );

		out = apply( add, mat1, 1, mat2 );
		assert.strictEqual( out.toString(), '4,4;4,4' );
	});

	it( 'should apply a function and return a matrix having a specified type', function test() {
		var mat,
			out,
			d, i;

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 1;
		}
		mat = matrix( d, [2,2], 'int8' );

		out = apply( add, mat, 1, {
			'dtype': 'float32'
		});
		assert.strictEqual( out.dtype, 'float32' );
		assert.strictEqual( out.toString(), '2,2;2,2' );
	});

	it( 'should apply a function to a single matrix and use a provided output matrix', function test() {
		var mat,
			out,
			actual,
			d, i;

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 1;
		}
		mat = matrix( d, [2,2], 'int8' );

		out = matrix( [2,2] );
		actual = apply( add, out, 1, mat, {
			'out': true
		});
		assert.strictEqual( out, actual );
		assert.strictEqual( out.toString(), '2,2;2,2' );
	});

});
<commit_msg>[FIX] fix tests to ensure testing for right case.<commit_after>/* global require, describe, it */
'use strict';

// MODULES //

var chai = require( 'chai' ),
	matrix = require( 'dstructs-matrix' ),
	noop = require( './fixtures/noop.js' ),
	add = require( './fixtures/add.js' ),
	apply = require( './../lib/apply.js' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'apply', function tests() {

	it( 'should export a function', function test() {
		expect( apply ).to.be.a( 'function' );
	});

	it( 'should throw an error if not provided a function', function test() {
		var values = [
			'5',
			5,
			NaN,
			true,
			null,
			undefined,
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				apply( value, matrix([5,5]) );
			};
		}
	});

	it( 'should throw an error if provided an options argument which is not an object', function test() {
		var values = [
			'5',
			true,
			null,
			undefined,
			[],
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				apply( noop, matrix([5,5]), value );
			};
		}
	});

	it( 'should throw an error if provided an invalid option', function test() {
		var values = [
			5,
			NaN,
			true,
			null,
			undefined,
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				apply( noop, matrix([5,5]), {
					'dtype': value
				});
			};
		}
	});

	it( 'should throw an error if not provided input values (matrices or numbers)', function test() {
		expect( foo ).to.throw( Error );
		expect( bar ).to.throw( Error );
		function foo() {
			apply( noop );
		}
		function bar() {
			apply( noop, matrix([5,5]), {
				'out': true
			});
		}
	});

	it( 'should throw an error if not provided at least one matrix', function test() {
		expect( foo ).to.throw( Error );
		function foo() {
			apply( noop, 1, 2, 3 );
		}
	});

	it( 'should throw an error if provided an output argument which is not a matrix', function test() {
		var values = [
			'5',
			5,
			NaN,
			true,
			null,
			undefined,
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				apply( noop, value, matrix([5,5]), {
					'out': true
				});
			};
		}
	});

	it( 'should throw an error if not provided matrix-like or numeric arguments', function test() {
		var values = [
			'5',
			true,
			null,
			undefined,
			[],
			{},
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue1( values[i] ) ).to.throw( TypeError );
			expect( badValue2( values[i] ) ).to.throw( TypeError );
		}
		function badValue1( value ) {
			return function() {
				apply( noop, matrix([5,5]), value, 5, {} );
			};
		}
		function badValue2( value ) {
			return function() {
				apply( noop, matrix([5,5]), 5, matrix([5,5]), value, {} );
			};
		}
	});

	it( 'should throw an error if provided incompatible matrix-like arguments', function test() {
		var values = [
			matrix([4,4]),
			matrix([0,0]),
			matrix([5,4])
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( Error );
		}
		function badValue( value ) {
			return function() {
				apply( noop, matrix([5,5]), value );
			};
		}
	});

	it( 'should apply a function to a single matrix', function test() {
		var mat,
			out,
			d, i;

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 1;
		}
		mat = matrix( d, [2,2], 'int8' );

		out = apply( add, mat, 1 );
		assert.strictEqual( out.toString(), '2,2;2,2' );
	});

	it( 'should apply a function to multiple matrices', function test() {
		var mat1,
			mat2,
			out,
			d, i;

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 1;
		}
		mat1 = matrix( d, [2,2], 'int8' );

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 2;
		}
		mat2 = matrix( d, [2,2], 'int8' );

		out = apply( add, mat1, 1, mat2 );
		assert.strictEqual( out.toString(), '4,4;4,4' );
	});

	it( 'should apply a function and return a matrix having a specified type', function test() {
		var mat,
			out,
			d, i;

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 1;
		}
		mat = matrix( d, [2,2], 'int8' );

		out = apply( add, mat, 1, {
			'dtype': 'float32'
		});
		assert.strictEqual( out.dtype, 'float32' );
		assert.strictEqual( out.toString(), '2,2;2,2' );
	});

	it( 'should apply a function to a single matrix and use a provided output matrix', function test() {
		var mat,
			out,
			actual,
			d, i;

		d = new Int8Array( 4 );
		for ( i = 0; i < d.length; i++ ) {
			d[ i ] = 1;
		}
		mat = matrix( d, [2,2], 'int8' );

		out = matrix( [2,2] );
		actual = apply( add, out, 1, mat, {
			'out': true
		});
		assert.strictEqual( out, actual );
		assert.strictEqual( out.toString(), '2,2;2,2' );
	});

});
<|endoftext|>


<commit_before>const jsdom = require('jsdom');

global.document = jsdom.jsdom("<!doctype html>

", {
  url: 'http://localhost',
  skipWindowCheck: true
});
global.window = document.defaultView;
global.navigator = global.window.navigator;

const sinon = require('sinon');
const React = require('react');
const ReactDOM = require('react-dom');
const ReactTestUtils = require('react-addons-test-utils');
const $ = require('jquery');
const _ = require('lodash');
const moment = require('moment');
const momentRecur = require('moment-recur');
const I18n = require('../public/assets/javascripts/i18n.js');
const chai = require('chai');
const sinonChai = require('sinon-chai');

global.$ = $;
global._ = _;
global.sinon = sinon;
global.React = React;
global.ReactDOM = ReactDOM;
global.ReactTestUtils = ReactTestUtils;
global.Simulate = ReactTestUtils.Simulate;
global.moment = moment;
global['moment-recur'] = momentRecur;
global.I18n = I18n;
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;
global.Features = {};

require('../public/assets/javascripts/i18n/en');

chai.use(sinonChai);
<commit_msg>Work around gulp error during i18n asset rebuilding<commit_after>const jsdom = require('jsdom');

global.document = jsdom.jsdom("<!doctype html>

", {
  url: 'http://localhost',
  skipWindowCheck: true
});
global.window = document.defaultView;
global.navigator = global.window.navigator;

const sinon = require('sinon');
const React = require('react');
const ReactDOM = require('react-dom');
const ReactTestUtils = require('react-addons-test-utils');
const $ = require('jquery');
const _ = require('lodash');
const moment = require('moment');
const momentRecur = require('moment-recur');
const I18n = require('../public/assets/javascripts/i18n.js'); // eslint-disable-line import/no-unresolved
const chai = require('chai');
const sinonChai = require('sinon-chai');

global.$ = $;
global._ = _;
global.sinon = sinon;
global.React = React;
global.ReactDOM = ReactDOM;
global.ReactTestUtils = ReactTestUtils;
global.Simulate = ReactTestUtils.Simulate;
global.moment = moment;
global['moment-recur'] = momentRecur;
global.I18n = I18n;
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;
global.Features = {};

require('../public/assets/javascripts/i18n/en'); // eslint-disable-line import/no-unresolved

chai.use(sinonChai);
<|endoftext|>


<commit_before>'use strict'; /*jslint node: true, es5: true, indent: 2, multistr: true */
var fs = require('fs');
var test = require('tap').test;

var sv = require('..');

test('throughput test', function (t) {
  var input = [
    { index: '1', name: 'chris', time: '1:29' },
    { index: '2', name: 'daniel', time: '1:17' },
    { index: '3', name: 'lewis', time: '1:30' },
    { index: '4', name: 'stephen', time: '1:16' },
    { index: '5', name: 'larry', time: '1:31' },
  ];

  var output = [];
  var stringifier = new sv.Stringifier({peek: 2, missing: 'NA'});

  // var parser = new sv.Parser();
  var parser = new sv.Parser({encoding: stringifier.encoding, quotechar: '"'});
  parser.on('data', function(obj) {
    output.push(obj);
  });
  parser.on('end', function() {
    t.similar(output, input, 'Throughput should be transparent.');
    t.end();
  });

  stringifier.pipe(parser);
  input.forEach(function(record) {
    stringifier.write(record);
  });
  stringifier.end();
});

// var input = fs.createReadStream('test/peektest.in', {encoding: 'utf8'});
// var async = require('async');
// async.map(['peektest.in', 'peektest.out'], fs.readFile, function(err, files) {
<commit_msg>Extra line<commit_after>'use strict'; /*jslint node: true, es5: true, indent: 2, multistr: true */
var fs = require('fs');
var test = require('tap').test;

var sv = require('..');

test('throughput test', function (t) {
  var input = [
    { index: '1', name: 'chris', time: '1:29' },
    { index: '2', name: 'daniel', time: '1:17' },
    { index: '3', name: 'lewis', time: '1:30' },
    { index: '4', name: 'stephen', time: '1:16' },
    { index: '5', name: 'larry', time: '1:31' },
  ];

  var output = [];
  var stringifier = new sv.Stringifier({peek: 2, missing: 'NA'});

  var parser = new sv.Parser({encoding: stringifier.encoding, quotechar: '"'});
  parser.on('data', function(obj) {
    output.push(obj);
  });
  parser.on('end', function() {
    t.similar(output, input, 'Throughput should be transparent.');
    t.end();
  });

  stringifier.pipe(parser);
  input.forEach(function(record) {
    stringifier.write(record);
  });
  stringifier.end();
});

// var input = fs.createReadStream('test/peektest.in', {encoding: 'utf8'});
// var async = require('async');
// async.map(['peektest.in', 'peektest.out'], fs.readFile, function(err, files) {
<|endoftext|>


<commit_before>'use strict'

const test = require('tap').test
const fastify = require('..')()

test('Fastify should throw on wrong options', t => {
  t.plan(2)
  try {
    const f = require('..')('lol') // eslint-disable-line
    t.fail()
  } catch (e) {
    t.is(e.message, 'Options must be an object')
    t.pass()
  }
})

test('Fastify should throw on multiple assignment to the same route', t => {
  t.plan(1)
  fastify.get('/', () => {})
  fastify.get('/', () => {})

  fastify.ready(err => {
    t.is(err.message, 'GET already set for /')
  })
})

test('Should throw on unsupported method', t => {
  t.plan(1)
  try {
    fastify.route({
      method: 'TROLL',
      url: '/',
      schema: {},
      handler: function (req, reply) {}
    })
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw on missing handler', t => {
  t.plan(1)
  try {
    fastify.route({
      method: 'GET',
      url: '/'
    })
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw if one method is unsupported', t => {
  t.plan(1)
  try {
    fastify.route({
      method: ['GET', 'TROLL'],
      url: '/',
      schema: {},
      handler: function (req, reply) {}
    })
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw on duplicate content type parser', t => {
  t.plan(1)

  function customParser (req, done) { done(null, '') }

  fastify.addContentTypeParser('application/qq', customParser)
  try {
    fastify.addContentTypeParser('application/qq', customParser)
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw on duplicate decorator', t => {
  t.plan(1)

  const fooObj = {}

  fastify.decorate('foo', fooObj)
  try {
    fastify.decorate('foo', fooObj)
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw on duplicate decorator encapsulation', t => {
  t.plan(1)

  const foo2Obj = {}

  fastify.decorate('foo2', foo2Obj)

  fastify.register(function (fastify, opts, next) {
    try {
      fastify.decorate('foo2', foo2Obj)
      t.fail()
    } catch (e) {
      t.pass()
    }
    next()
  })
})
<commit_msg>Add test - Should throw on duplicate request/reply decorator<commit_after>'use strict'

const test = require('tap').test
const fastify = require('..')()

test('Fastify should throw on wrong options', t => {
  t.plan(2)
  try {
    const f = require('..')('lol') // eslint-disable-line
    t.fail()
  } catch (e) {
    t.is(e.message, 'Options must be an object')
    t.pass()
  }
})

test('Fastify should throw on multiple assignment to the same route', t => {
  t.plan(1)
  fastify.get('/', () => {})
  fastify.get('/', () => {})

  fastify.ready(err => {
    t.is(err.message, 'GET already set for /')
  })
})

test('Should throw on unsupported method', t => {
  t.plan(1)
  try {
    fastify.route({
      method: 'TROLL',
      url: '/',
      schema: {},
      handler: function (req, reply) {}
    })
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw on missing handler', t => {
  t.plan(1)
  try {
    fastify.route({
      method: 'GET',
      url: '/'
    })
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw if one method is unsupported', t => {
  t.plan(1)
  try {
    fastify.route({
      method: ['GET', 'TROLL'],
      url: '/',
      schema: {},
      handler: function (req, reply) {}
    })
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw on duplicate content type parser', t => {
  t.plan(1)

  function customParser (req, done) { done(null, '') }

  fastify.addContentTypeParser('application/qq', customParser)
  try {
    fastify.addContentTypeParser('application/qq', customParser)
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw on duplicate decorator', t => {
  t.plan(1)

  const fooObj = {}

  fastify.decorate('foo', fooObj)
  try {
    fastify.decorate('foo', fooObj)
    t.fail()
  } catch (e) {
    t.pass()
  }
})

test('Should throw on duplicate decorator encapsulation', t => {
  t.plan(1)

  const foo2Obj = {}

  fastify.decorate('foo2', foo2Obj)

  fastify.register(function (fastify, opts, next) {
    try {
      fastify.decorate('foo2', foo2Obj)
      t.fail()
    } catch (e) {
      t.pass()
    }
    next()
  })
})

test('Should throw on duplicate request decorator', t => {
  t.plan(1)

  const fooObj = {}

  fastify.decorateRequest('foo', fooObj)
  try {
    fastify.decorateRequest('foo', fooObj)
    // TODO: this should be t.fail()!
    t.pass()
  } catch (e) {
    t.pass()
  }
})

test('Should throw on duplicate reply decorator', t => {
  t.plan(1)

  const fooObj = {}

  fastify.decorateReply('foo', fooObj)
  try {
    fastify.decorateReply('foo', fooObj)
    // TODO: this should be t.fail()!
    t.pass()
  } catch (e) {
    t.pass()
  }
})
<|endoftext|>


<commit_before>var rewire = require('rewire');
var chai   = require('chai');
var expect = chai.expect;

// setup promise
chai.use(require('chai-as-promised'));

var google = rewire('../src/tts/google');
describe('tts.google', function() {

  before(function () {
    // mock console.log
    google.__set__({
      console: {
        log: function () {}
      }
    });
  });

  it('Hello', function () {
    var word = 'Hello';
    return expect(google(word)).to.eventually.match(/q=hello/);
    return expect(google(word)).to.eventually.match(/textlen=5/);
  });

  it('hello', function () {
    var word = 'hello';
    return expect(google(word)).to.eventually.match(/q=hello/);
    return expect(google(word)).to.eventually.match(/textlen=5/);
  });

  it('hello world', function () {
    var word = 'hello world';
    return expect(google(word)).to.eventually.match(/q=hello%20world/);
    return expect(google(word)).to.eventually.match(/textlen=11/);
  });

  it('Hello_World', function () {
    var word = 'Hello_World';
    return expect(google(word)).to.eventually.match(/q=hello%20world/);
    return expect(google(word)).to.eventually.match(/textlen=11/);
  });

  it('how_are_you', function () {
    var word = 'how_are_you';
    return expect(google(word)).to.eventually.match(/q=how%20are%20you/);
    return expect(google(word)).to.eventually.match(/textlen=11/);
  });

  it('123', function () {
    var word = '123';
    return expect(google(word)).to.eventually.match(/q=123/);
    return expect(google(word)).to.eventually.match(/textlen=3/);
  });

  it('(null)', function () {
    var word = null;
    return expect(google(word)).to.eventually.be.rejectedWith(TypeError);
  });

  it('123 (number)', function () {
    var word = 123;
    return expect(google(word)).to.eventually.be.rejectedWith(TypeError);
  });

  it('(Empty String)', function () {
    var word = '';
    return expect(google(word)).to.eventually.be.rejectedWith(TypeError);
  });

});
<commit_msg>[test] update tts.google by checking http status<commit_after>var fetch  = require('node-fetch');
var rewire = require('rewire');
var chai   = require('chai');
var expect = chai.expect;

// setup promise
chai.use(require('chai-as-promised'));

// mock console.log
var google = rewire('../src/tts/google');
google.__set__({
  console: {
    log: function () {}
  }
});

function checkHttpStatus (word) {
  return expect(
    google(word)
      .then(function (url) { return fetch(url) })
      .then(function (res) { return res.status })
  ).to.eventually.equal(200);
}

describe('tts.google', function() {

  it('Hello', function () {
    var word = 'Hello';
    return checkHttpStatus(word);
  });

  it('hello', function () {
    var word = 'hello';
    return checkHttpStatus(word);
  });

  it('hello world', function () {
    var word = 'hello world';
    return checkHttpStatus(word);
  });

  it('Hello_World', function () {
    var word = 'Hello_World';
    return checkHttpStatus(word);
  });

  it('how_are_you', function () {
    var word = 'how_are_you';
    return checkHttpStatus(word);
  });

  it('123', function () {
    var word = '123';
    return checkHttpStatus(word);
  });

  it('(null)', function () {
    var word = null;
    return expect(google(word)).to.eventually.be.rejectedWith(TypeError);
  });

  it('123 (number)', function () {
    var word = 123;
    return expect(google(word)).to.eventually.be.rejectedWith(TypeError);
  });

  it('(Empty String)', function () {
    var word = '';
    return expect(google(word)).to.eventually.be.rejectedWith(TypeError);
  });

});
<|endoftext|>


<commit_before>import { Selector } from 'testcafe';

const pageDomain = "http://localhost";
const pagePort = "3000";
const pageRoute = "/patina"

const startPage = `${pageDomain}:${pagePort}${pageRoute}`;

fixture('Lite Mode - Landing')
    .page(startPage);
test('Clicking progression button puts us in progression mode', async t => {
    await t
        .click("#Disease\\ Status")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("Disease Status", `Current header doesn't reflect expected progression page header`);
})
test('Clicking toxicity button puts us in toxicity mode', async t => {
    await t
        .click("#Toxicity")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("Toxicity", `Current header doesn't reflect expected toxicity page header`);
})
test('Clicking clinical trial button puts us in clinical trial mode', async t => {
    await t
        .click("#Clinical\\ Trial")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("Clinical Trial", `Current header doesn't reflect expected toxicity page header`);
})
test('Clicking deceased button puts us in deceased mode', async t => {
    await t
        .click("#Deceased")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("Deceased", `Current header doesn't reflect expected deceased page header` );
})
test('Clicking about button puts us back on landing page', async t => {
    await t
        .click("#Toxicity")
        .click("#About\\ Flux\\ Notes\\ Lite")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("About Flux Notes Lite", `Current header doesn't reflect expected landing page header`);
})

fixture('Lite Mode - Progression')
    .page(startPage)
    .beforeEach( async t => {
        await t.click("#Disease\\ Status");
    });
test('Changing progression status via button updates copy-content', async t => {
    const statusButtons = Selector('.btn-group-status-progression').find("span[class^='MuiButton-label']");
    const numButtons = await statusButtons.count;
    for(let i = 0; i < numButtons; i++) {
        await t
            .click(statusButtons.nth(i))
            .expect(Selector("#copy-content").innerText)
            .contains(await statusButtons.nth(i).innerText);
    }
});
test('Changing progression rationale via button updates copy-content', async t => {
    const rationaleButtons = Selector('.btn-group-reason-progression').find("span[class^='MuiButton-label']");
    const numButtons = await rationaleButtons.count;
    for(let i = 0; i < numButtons; i++) {
        await t
            .click(rationaleButtons.nth(i))
            .expect(Selector("#copy-content").innerText)
            .contains(await rationaleButtons.nth(i).innerText);
    }
});

fixture('Lite Mode - Toxicity')
    .page(startPage)
    .beforeEach( async t => {
        await t.click("#Toxicity");
    });
test('Typing an adverseEvent updates copy-content', async t => {
    const adverseEventInput = Selector('.react-autosuggest__input').nth(0);
    await t
        .typeText(adverseEventInput, "Anemia")
        .pressKey('enter')
        .expect(Selector("#copy-content").innerText)
        .contains(await adverseEventInput.value);
});
test('Selecting adverseEvent, then selecting a valid grade updates copy-content', async t => {
    const adverseEventInput = Selector('.react-autosuggest__input').nth(0);
    const gradeButtons = Selector('#grade-menu').find("div[class='grade-menu-item-name']");
    const numButtons = await gradeButtons.count;
    await t
        .typeText(adverseEventInput, "Anemia")
        .pressKey('enter');

    for(let i = 0; i < numButtons; i++) {
        await t
            .click(gradeButtons.nth(i))
            .expect(Selector("#copy-content").innerText)
            .contains(await gradeButtons.nth(i).innerText);
    }
});
test('Changing attribution via button updates copy-content', async t => {
    const attributionButtons = Selector('.btn-group-attribution').find("span[class^='MuiButton-label']");
    const numButtons = await attributionButtons.count;
    for(let i = 0; i < numButtons; i++) {
        await t
            .click(attributionButtons.nth(i))
            .expect(Selector("#copy-content").innerText)
            .contains(await attributionButtons.nth(i).innerText);
    }
});

fixture('Lite Mode - Clinical Trial')
    .page(startPage)
    .beforeEach( async t => {
        await t.click("#Clinical\\ Trial");
    });
test('Selecting a clinical trial updates copy-content', async t => {
    const trialButtons = Selector('.btn-group-trial-clinical-trial').find("span[class^='MuiButton-label']");
    const numButtons = await trialButtons.count;
    const copyButton = Selector("#copy-content");
    for (let i = 0; i < numButtons; i++) {
        await t
            .click(trialButtons.nth(i))
            .expect(copyButton.innerText)
            .contains(await trialButtons.nth(i).innerText);
    }
});
test('Selecting an enrollment date updates copy-content', async t => {
    const datePicker = Selector("#enrollment-date");
    const copyButton = Selector("#copy-content");
    // Date only appears if a trial is selected
    const firstTrial = Selector('.btn-group-trial-clinical-trial').find("span[class^='MuiButton-label']").nth(0);
    await t
        .click(firstTrial)
        .typeText(datePicker, '2017-10-06')
        .expect(copyButton.innerText)
        .contains(await datePicker.innerText);
});
test('Selecting an end date updates copy-content', async t => {
    const datePicker = Selector("#end-date");
    const copyButton = Selector("#copy-content");
    // Date only appears if a trial is selected
    const firstTrial = Selector('.btn-group-trial-clinical-trial').find("span[class^='MuiButton-label']").nth(0);
    await t
        .click(firstTrial)
        .typeText(datePicker, '2017-10-06')
        .expect(copyButton.innerText)
        .contains(await datePicker.innerText);
});

fixture('Lite Mode - Deceased')
    .page(startPage)
    .beforeEach( async t => {
       await t.click("#Deceased");
    });
test('Selecting a date of death updates copy-content', async t => {
    const datePicker = Selector("#date-of-death");
    const copyButton = Selector("#copy-content");
    await t
        .typeText(datePicker, '2017-10-01')
        .expect(copyButton.innerText)
        .contains(await datePicker.innerText);
});

<commit_msg>Updated enrollment and end date tests to use radio buttons<commit_after>import { Selector } from 'testcafe';

const pageDomain = "http://localhost";
const pagePort = "3000";
const pageRoute = "/patina"

const startPage = `${pageDomain}:${pagePort}${pageRoute}`;

fixture('Lite Mode - Landing')
    .page(startPage);
test('Clicking progression button puts us in progression mode', async t => {
    await t
        .click("#Disease\\ Status")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("Disease Status", `Current header doesn't reflect expected progression page header`);
})
test('Clicking toxicity button puts us in toxicity mode', async t => {
    await t
        .click("#Toxicity")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("Toxicity", `Current header doesn't reflect expected toxicity page header`);
})
test('Clicking clinical trial button puts us in clinical trial mode', async t => {
    await t
        .click("#Clinical\\ Trial")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("Clinical Trial", `Current header doesn't reflect expected toxicity page header`);
})
test('Clicking deceased button puts us in deceased mode', async t => {
    await t
        .click("#Deceased")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("Deceased", `Current header doesn't reflect expected deceased page header` );
})
test('Clicking about button puts us back on landing page', async t => {
    await t
        .click("#Toxicity")
        .click("#About\\ Flux\\ Notes\\ Lite")
        .expect(Selector("#shortcut-viewer").find('h1').innerText)
        .eql("About Flux Notes Lite", `Current header doesn't reflect expected landing page header`);
})

fixture('Lite Mode - Progression')
    .page(startPage)
    .beforeEach( async t => {
        await t.click("#Disease\\ Status");
    });
test('Changing progression status via button updates copy-content', async t => {
    const statusButtons = Selector('.btn-group-status-progression').find("span[class^='MuiButton-label']");
    const numButtons = await statusButtons.count;
    for(let i = 0; i < numButtons; i++) {
        await t
            .click(statusButtons.nth(i))
            .expect(Selector("#copy-content").innerText)
            .contains(await statusButtons.nth(i).innerText);
    }
});
test('Changing progression rationale via button updates copy-content', async t => {
    const rationaleButtons = Selector('.btn-group-reason-progression').find("span[class^='MuiButton-label']");
    const numButtons = await rationaleButtons.count;
    for(let i = 0; i < numButtons; i++) {
        await t
            .click(rationaleButtons.nth(i))
            .expect(Selector("#copy-content").innerText)
            .contains(await rationaleButtons.nth(i).innerText);
    }
});

fixture('Lite Mode - Toxicity')
    .page(startPage)
    .beforeEach( async t => {
        await t.click("#Toxicity");
    });
test('Typing an adverseEvent updates copy-content', async t => {
    const adverseEventInput = Selector('.react-autosuggest__input').nth(0);
    await t
        .typeText(adverseEventInput, "Anemia")
        .pressKey('enter')
        .expect(Selector("#copy-content").innerText)
        .contains(await adverseEventInput.value);
});
test('Selecting adverseEvent, then selecting a valid grade updates copy-content', async t => {
    const adverseEventInput = Selector('.react-autosuggest__input').nth(0);
    const gradeButtons = Selector('#grade-menu').find("div[class='grade-menu-item-name']");
    const numButtons = await gradeButtons.count;
    await t
        .typeText(adverseEventInput, "Anemia")
        .pressKey('enter');

    for(let i = 0; i < numButtons; i++) {
        await t
            .click(gradeButtons.nth(i))
            .expect(Selector("#copy-content").innerText)
            .contains(await gradeButtons.nth(i).innerText);
    }
});
test('Changing attribution via button updates copy-content', async t => {
    const attributionButtons = Selector('.btn-group-attribution').find("span[class^='MuiButton-label']");
    const numButtons = await attributionButtons.count;
    for(let i = 0; i < numButtons; i++) {
        await t
            .click(attributionButtons.nth(i))
            .expect(Selector("#copy-content").innerText)
            .contains(await attributionButtons.nth(i).innerText);
    }
});

fixture('Lite Mode - Clinical Trial')
    .page(startPage)
    .beforeEach( async t => {
        await t.click("#Clinical\\ Trial");
    });
test('Selecting a clinical trial updates copy-content', async t => {
    const trialButtons = Selector('.btn-group-trial-clinical-trial').find("span[class^='MuiButton-label']");
    const numButtons = await trialButtons.count;
    const copyButton = Selector("#copy-content");
    for (let i = 0; i < numButtons; i++) {
        await t
            .click(trialButtons.nth(i))
            .expect(copyButton.innerText)
            .contains(await trialButtons.nth(i).innerText);
    }
});
test('Selecting the enrollment date choice and a date updates copy-content', async t => {
    const enrollmentDateChoice = Selector("#enrollment-date-choice");
    const copyButton = Selector("#copy-content");
    // Date only appears if a trial is selected
    const firstTrial = Selector('.btn-group-trial-clinical-trial').find("span[class^='MuiButton-label']").nth(0);
    await t
        .click(firstTrial)
        .click(enrollmentDateChoice);

    const enrollmentDatePicker = await Selector("#enrollment-date");
    await t
        .typeText(enrollmentDatePicker, '2017-10-06')
        .expect(copyButton.innerText)
        .contains(`#enrolled on ${await enrollmentDatePicker.innerText}`);
});
test('Selecting the end date choice and a date updates copy-content', async t => {
    const endDateChoice = Selector("#end-date-choice");
    const copyButton = Selector("#copy-content");
    // Date only appears if a trial is selected
    const firstTrial = Selector('.btn-group-trial-clinical-trial').find("span[class^='MuiButton-label']").nth(0);
    await t
        .click(firstTrial)
        .click(endDateChoice);

    const endDatePicker = await Selector("#end-date");
    await t
        .typeText(endDatePicker, '2017-10-06')
        .expect(copyButton.innerText)
        .contains(await `#ended on ${await endDatePicker.innerText}`);
});

fixture('Lite Mode - Deceased')
    .page(startPage)
    .beforeEach( async t => {
       await t.click("#Deceased");
    });
test('Selecting a date of death updates copy-content', async t => {
    const datePicker = Selector("#date-of-death");
    const copyButton = Selector("#copy-content");
    await t
        .typeText(datePicker, '2017-10-01')
        .expect(copyButton.innerText)
        .contains(await datePicker.innerText);
});

<|endoftext|>


<commit_before>var grunt = require('grunt');
var jsonlint = require('@prantlf/jsonlint');
var strip = require('strip-json-comments');
var _ = require('lodash');

var expect = require('expect.js');
var sinon = require('sinon');
expect = require('sinon-expect').enhance(expect, sinon, 'was');

var taskFactory = require('../lib/grunt-jsonlint-task');

describe('grunt-jsonlint task', function () {

  before('stub out and spy on grunt logger', function () {
    sinon.stub(grunt.log, 'ok');
    sinon.stub(grunt.log, 'error');
    sinon.stub(grunt.log, 'writeln');
    sinon.stub(grunt.fail, 'warn');
  });

  after('restore grung logger methods', function () {
    grunt.log.ok.restore();
    grunt.log.error.restore();
    grunt.log.writeln.restore();
    grunt.fail.warn.restore();
  });

  afterEach('reset the spy counts', function () {
    grunt.log.ok.reset();
    grunt.log.error.reset();
    grunt.log.writeln.reset();
    grunt.fail.warn.reset();
  });

  // basic pass/fail behaviors

  it('passes a valid JSON file', function () {
    runWithFiles(grunt, jsonlint, [ 'test/valid.json' ]);
    expectSuccess(grunt);
  });

  it('fails an invalid JSON file', function () {
    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ]);
    expectFailure(grunt, 'test/invalid.json', 9);
  });

  it('passes a valid CJSON file', function () {
    runWithFiles(grunt, jsonlint, [ 'test/cjson.json' ], { cjson: true });
    expectSuccess(grunt);
  });

  it('passes a JSON file complying with the schema', function () {
    runWithFiles(grunt, jsonlint, [ 'test/3.json' ], {
      schema: { src: 'test/3.schema.json' }
    });
    expectSuccess(grunt);
  });

  it('fails a JSON file not complying with the schema', function () {
    runWithFiles(grunt, jsonlint, [ 'test/valid.json' ], {
      schema: { src: 'test/3.schema.json' }
    });
    expectFailure(grunt, 'test/valid.json');
  });

  // reporting behaviors

  it('reports a failure for each files which failed to validate', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ]);
    expectFailure(grunt, 'test/invalid.json', 3);
  });

  it('reports the file name and line number for each file that failed validation', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ]);
    expectFailure(grunt, 'test/invalid.json', 3);
  });

  it('fails the build when a JSON file fails to validate', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ]);

    expect(grunt.fail.warn).was.calledOnce();
  });

  it('reports the number of files which validated successfully', function () {
    var jsonlint = createPassingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/valid.json' ]);

    expectSuccess(grunt);
  });

  it('reports the raw jsonlint exception during failure', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ], {
      reporter: 'exception'
    });

    var e = grunt.log.writeln.args[0][0];

    expect(e).to.be.an(Error);
    expect(e.message).to.contain('Invalid JSON');
  });

  it('includes jshint-style details of failure', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ], {
      reporter: 'jshint'
    });

    var message = grunt.log.writeln.args[0][0];

    expect(message).to.contain('"3"');
    expect(message).to.contain('3 | ');
    expect(message).to.contain(grunt.util.linefeed);
    expect(message).to.contain('^ Expected');
    expect(message).to.contain('and instead saw ');
  });

  it('formats validation errors for Visual Studio when the appropriate option is given', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ], {
      formatter: 'msbuild'
    });
    expect(grunt.log.error).was.calledWith('test/invalid.json(3): error: failed JSON validation');
  });

  // formatting of the JSON files.

  it('reformats the input JSON file when configured to do so, using the default indentation level of 2', function () {
    testReformattingFile();
  });

  it('reformats the input JSON file using the specified indentation level', function () {
    testReformattingFile(1);
    testReformattingFile(2);
    testReformattingFile(3);
  });

});

function createPassingJsonlintSpy() {
  return {
    parse: sinon.spy(),
    parser: {
      yy: { }
    }
  };
}

function createFailingJsonlintSpy() {
  var x = {
    parse: function (data) {
      var hash = {
        "text": "\"3\"",
        "token": "STRING",
        "line": 3,
        "loc": {
          "first_line": 3,
          "last_line": 3,
          "first_column": 8,
          "last_column": 11
        },
        "expected": [
          "']'"
        ]
      };
      this.yy.parseError('Invalid JSON', hash);
      throw new Error('Invalid JSON');
    },
    parser: {
      yy: {
        parseError: function stub(msg, hash) { }
      }
    }
  };
  x.parse = x.parse.bind(x.parser);
  return x;
}

function createTaskContext(data) {
  var target = 'unit test';
  var normalizedFiles = grunt.task.normalizeMultiTaskFiles(data, target);

  var filesSrc = normalizedFiles.map(function (f) {
    return f.src;
  }).reduce(function (prev, curr) {
    return prev.concat(curr);
  }, []);

  var optionsFunc = function optionsFunc(options) {
    return function(defaultOptions) {
      return _.extend(defaultOptions, options);
    };
  }(data.options);

  return {
    target: target,
    files: normalizedFiles,
    filesSrc: filesSrc,
    data: data,
    errorCount: 0,
    flags: {},
    nameArgs: '',
    args: [],
    name: 'jsonlint',
    options: optionsFunc
  };
}

function runWithFiles(grunt, jsonlint, files, options) {
  var gruntFiles = files.map(function (file) {
    return {
      src: file
    };
  });

  taskFactory(grunt, jsonlint, strip).bind(createTaskContext({
    files: gruntFiles,
    options: options
  }))();
}

function expectSuccess(gruntSpy) {
  expect(gruntSpy.fail.warn).was.notCalled();
  expect(gruntSpy.log.ok).was.calledOnce();
  expect(gruntSpy.log.ok).was.calledWith('1 file lint free.');
}

function expectFailure(grunt, file, atLine) {
  expect(grunt.log.error).was.calledOnce();
  var message = 'File "' + file + '" failed JSON validation';
  if (atLine != null) {
    message += ' at line ' + atLine;
  }
  message += '.';
  expect(grunt.log.error).was.calledWith(message);
}

function testReformattingFile(indent) {
  var options = {
    format: true
  };

  if (indent !== undefined) {
    options.indent = indent;
  }

  var expectedIndent = '';
  if (indent === undefined) {
    expectedIndent = '  ';
  }
  else {
    for (var i = 0; i < indent; i++) {
      expectedIndent += ' ';
    }
  }

  // Build an unformatted file for testing.
  grunt.file.write(__dirname + '/reformat-this.json', '{"somethingsomething":"something","something":"dark side"}');

  runWithFiles(grunt, createPassingJsonlintSpy(), [ 'test/reformat-this.json' ], options);

  var formatted = grunt.file.read(__dirname + '/reformat-this.json');
  var lines = formatted.split(/\r?\n/);
  expect(lines).to.have.length(5);
  expect(lines[0]).to.be('{');
  expect(lines[1]).to.be(expectedIndent + '"somethingsomething": "something",');
  expect(lines[2]).to.be(expectedIndent + '"something": "dark side"');
  expect(lines[3]).to.be('}');
  expect(lines[4]).to.be.empty();

  grunt.file.delete(__dirname + '/reformat-this.json');
}
<commit_msg>chore: Enable schema validation in unit tests<commit_after>var grunt = require('grunt');
var jsonlint = require('@prantlf/jsonlint');
var strip = require('strip-json-comments');
var validator = require('@prantlf/jsonlint/lib/validator');
var _ = require('lodash');

var expect = require('expect.js');
var sinon = require('sinon');
expect = require('sinon-expect').enhance(expect, sinon, 'was');

var taskFactory = require('../lib/grunt-jsonlint-task');

describe('grunt-jsonlint task', function () {

  before('stub out and spy on grunt logger', function () {
    sinon.stub(grunt.log, 'ok');
    sinon.stub(grunt.log, 'error');
    sinon.stub(grunt.log, 'writeln');
    sinon.stub(grunt.fail, 'warn');
  });

  after('restore grung logger methods', function () {
    grunt.log.ok.restore();
    grunt.log.error.restore();
    grunt.log.writeln.restore();
    grunt.fail.warn.restore();
  });

  afterEach('reset the spy counts', function () {
    grunt.log.ok.reset();
    grunt.log.error.reset();
    grunt.log.writeln.reset();
    grunt.fail.warn.reset();
  });

  // basic pass/fail behaviors

  it('passes a valid JSON file', function () {
    runWithFiles(grunt, jsonlint, [ 'test/valid.json' ]);
    expectSuccess(grunt);
  });

  it('fails an invalid JSON file', function () {
    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ]);
    expectFailure(grunt, 'test/invalid.json', 9);
  });

  it('passes a valid CJSON file', function () {
    runWithFiles(grunt, jsonlint, [ 'test/cjson.json' ], { cjson: true });
    expectSuccess(grunt);
  });

  it('passes a JSON file complying with the schema', function () {
    runWithFiles(grunt, jsonlint, [ 'test/3.json' ], {
      schema: { src: 'test/3.schema.json' }
    });
    expectSuccess(grunt);
  });

  it('fails a JSON file not complying with the schema', function () {
    runWithFiles(grunt, jsonlint, [ 'test/valid.json' ], {
      schema: { src: 'test/3.schema.json' }
    });
    expectFailure(grunt, 'test/valid.json');
  });

  // reporting behaviors

  it('reports a failure for each files which failed to validate', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ]);
    expectFailure(grunt, 'test/invalid.json', 3);
  });

  it('reports the file name and line number for each file that failed validation', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ]);
    expectFailure(grunt, 'test/invalid.json', 3);
  });

  it('fails the build when a JSON file fails to validate', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ]);

    expect(grunt.fail.warn).was.calledOnce();
  });

  it('reports the number of files which validated successfully', function () {
    var jsonlint = createPassingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/valid.json' ]);

    expectSuccess(grunt);
  });

  it('reports the raw jsonlint exception during failure', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ], {
      reporter: 'exception'
    });

    var e = grunt.log.writeln.args[0][0];

    expect(e).to.be.an(Error);
    expect(e.message).to.contain('Invalid JSON');
  });

  it('includes jshint-style details of failure', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ], {
      reporter: 'jshint'
    });

    var message = grunt.log.writeln.args[0][0];

    expect(message).to.contain('"3"');
    expect(message).to.contain('3 | ');
    expect(message).to.contain(grunt.util.linefeed);
    expect(message).to.contain('^ Expected');
    expect(message).to.contain('and instead saw ');
  });

  it('formats validation errors for Visual Studio when the appropriate option is given', function () {
    var jsonlint = createFailingJsonlintSpy();

    runWithFiles(grunt, jsonlint, [ 'test/invalid.json' ], {
      formatter: 'msbuild'
    });
    expect(grunt.log.error).was.calledWith('test/invalid.json(3): error: failed JSON validation');
  });

  // formatting of the JSON files.

  it('reformats the input JSON file when configured to do so, using the default indentation level of 2', function () {
    testReformattingFile();
  });

  it('reformats the input JSON file using the specified indentation level', function () {
    testReformattingFile(1);
    testReformattingFile(2);
    testReformattingFile(3);
  });

});

function createPassingJsonlintSpy() {
  return {
    parse: sinon.spy(),
    parser: {
      yy: { }
    }
  };
}

function createFailingJsonlintSpy() {
  var x = {
    parse: function (data) {
      var hash = {
        "text": "\"3\"",
        "token": "STRING",
        "line": 3,
        "loc": {
          "first_line": 3,
          "last_line": 3,
          "first_column": 8,
          "last_column": 11
        },
        "expected": [
          "']'"
        ]
      };
      this.yy.parseError('Invalid JSON', hash);
      throw new Error('Invalid JSON');
    },
    parser: {
      yy: {
        parseError: function stub(msg, hash) { }
      }
    }
  };
  x.parse = x.parse.bind(x.parser);
  return x;
}

function createTaskContext(data) {
  var target = 'unit test';
  var normalizedFiles = grunt.task.normalizeMultiTaskFiles(data, target);

  var filesSrc = normalizedFiles.map(function (f) {
    return f.src;
  }).reduce(function (prev, curr) {
    return prev.concat(curr);
  }, []);

  var optionsFunc = function optionsFunc(options) {
    return function(defaultOptions) {
      return _.extend(defaultOptions, options);
    };
  }(data.options);

  return {
    target: target,
    files: normalizedFiles,
    filesSrc: filesSrc,
    data: data,
    errorCount: 0,
    flags: {},
    nameArgs: '',
    args: [],
    name: 'jsonlint',
    options: optionsFunc
  };
}

function runWithFiles(grunt, jsonlint, files, options) {
  var gruntFiles = files.map(function (file) {
    return {
      src: file
    };
  });

  taskFactory(grunt, jsonlint, strip, validator).bind(createTaskContext({
    files: gruntFiles,
    options: options
  }))();
}

function expectSuccess(gruntSpy) {
  expect(gruntSpy.fail.warn).was.notCalled();
  expect(gruntSpy.log.ok).was.calledOnce();
  expect(gruntSpy.log.ok).was.calledWith('1 file lint free.');
}

function expectFailure(grunt, file, atLine) {
  expect(grunt.log.error).was.calledOnce();
  var message = 'File "' + file + '" failed JSON validation';
  if (atLine != null) {
    message += ' at line ' + atLine;
  }
  message += '.';
  expect(grunt.log.error).was.calledWith(message);
}

function testReformattingFile(indent) {
  var options = {
    format: true
  };

  if (indent !== undefined) {
    options.indent = indent;
  }

  var expectedIndent = '';
  if (indent === undefined) {
    expectedIndent = '  ';
  }
  else {
    for (var i = 0; i < indent; i++) {
      expectedIndent += ' ';
    }
  }

  // Build an unformatted file for testing.
  grunt.file.write(__dirname + '/reformat-this.json', '{"somethingsomething":"something","something":"dark side"}');

  runWithFiles(grunt, createPassingJsonlintSpy(), [ 'test/reformat-this.json' ], options);

  var formatted = grunt.file.read(__dirname + '/reformat-this.json');
  var lines = formatted.split(/\r?\n/);
  expect(lines).to.have.length(5);
  expect(lines[0]).to.be('{');
  expect(lines[1]).to.be(expectedIndent + '"somethingsomething": "something",');
  expect(lines[2]).to.be(expectedIndent + '"something": "dark side"');
  expect(lines[3]).to.be('}');
  expect(lines[4]).to.be.empty();

  grunt.file.delete(__dirname + '/reformat-this.json');
}
<|endoftext|>


<commit_before>(function() {

  function getAbsolutePath(path) {
    var isAbsolute = /^https?:/.test(path);
    if (isAbsolute) return path;
    var imgEl = _createImageElement();
    imgEl.src = path;
    var src = imgEl.src;
    imgEl = null;
    return src;
  }

  var IMG_SRC     = fabric.isLikelyNode ? (__dirname + '/../fixtures/test_image.gif') : getAbsolutePath('../fixtures/test_image.gif'),
      IMG_WIDTH   = 276,
      IMG_HEIGHT  = 110;

  var REFERENCE_IMG_OBJECT = {
    'type':               'image',
    'originX':            'left',
    'originY':            'top',
    'left':               0,
    'top':                0,
    'width':              IMG_WIDTH, // node-canvas doesn't seem to allow setting width/height on image objects
    'height':             IMG_HEIGHT, // or does it now?
    'fill':               'rgb(0,0,0)',
    'stroke':             null,
    'strokeWidth':        1,
    'strokeDashArray':    null,
    'strokeLineCap':      'butt',
    'strokeLineJoin':     'miter',
    'strokeMiterLimit':   10,
    'scaleX':             1,
    'scaleY':             1,
    'angle':              0,
    'flipX':              false,
    'flipY':              false,
    'opacity':            1,
    'src':                fabric.isLikelyNode ? undefined : IMG_SRC,
    'shadow':             null,
    'visible':            true,
    'backgroundColor':    '',
    'clipTo':             null,
    'filters':            [],
    'crossOrigin':        ''
  };

  function _createImageElement() {
    return fabric.isLikelyNode ? new (require('canvas').Image) : fabric.document.createElement('img');
  }

  function _createImageObject(width, height, callback) {
    var elImage = _createImageElement();
    elImage.width = width;
    elImage.height = height;
    setSrc(elImage, IMG_SRC, function() {
      callback(new fabric.Image(elImage));
    });
  }

  function createImageObject(callback) {
    return _createImageObject(IMG_WIDTH, IMG_HEIGHT, callback)
  }

  function createSmallImageObject(callback) {
    return _createImageObject(IMG_WIDTH / 2, IMG_HEIGHT / 2, callback);
  }

  function setSrc(img, src, callback) {
    if (fabric.isLikelyNode) {
      require('fs').readFile(src, function(err, imgData) {
        if (err) throw err;
        img.src = imgData;
        callback && callback();
      });
    }
    else {
      img.src = src;
      callback && callback();
    }
  }

  QUnit.module('fabric.Image');

  asyncTest('constructor', function() {
    ok(fabric.Image);

    createImageObject(function(image) {
      ok(image instanceof fabric.Image);
      ok(image instanceof fabric.Object);

      equal(image.get('type'), 'image');

      start();
    });
  });

  asyncTest('toObject', function() {
    createImageObject(function(image) {
      ok(typeof image.toObject == 'function');
      var toObject = image.toObject();
      // workaround for node-canvas sometimes producing images with width/height and sometimes not
      if (toObject.width === 0) {
        toObject.width = IMG_WIDTH;
      }
      if (toObject.height === 0) {
        toObject.height = IMG_HEIGHT;
      }
      deepEqual(toObject, REFERENCE_IMG_OBJECT);
      start();
    });
  });

  asyncTest('toString', function() {
    createImageObject(function(image) {
      ok(typeof image.toString == 'function');
      equal(image.toString(), '#<fabric.Image: { src: "' + (fabric.isLikelyNode ? undefined : IMG_SRC) + '" }>');
      start();
    });
  });

  asyncTest('getSrc', function() {
    createImageObject(function(image) {
      ok(typeof image.getSrc == 'function');
      equal(image.getSrc(), fabric.isLikelyNode ? undefined : IMG_SRC);
      start();
    });
  });

  test('getElement', function() {
    var elImage = _createImageElement();
    var image = new fabric.Image(elImage);
    ok(typeof image.getElement == 'function');
    equal(image.getElement(), elImage);
  });

  asyncTest('setElement', function() {
    createImageObject(function(image) {
      ok(typeof image.setElement == 'function');

      var elImage = _createImageElement();
      equal(image.setElement(elImage), image, 'chainable');
      equal(image.getElement(), elImage);
      equal(image._originalElement, elImage);

      start();
    });
  });

  asyncTest('crossOrigin', function() {
    createImageObject(function(image) {
      equal(image.crossOrigin, '', 'initial crossOrigin value should be set');

      start();

      var elImage = _createImageElement();
      elImage.crossOrigin = 'anonymous';
      var image = new fabric.Image(elImage);
      equal(image.crossOrigin, '', 'crossOrigin value on an instance takes precedence');

      var objRepr = image.toObject();
      equal(objRepr.crossOrigin, '', 'toObject should return proper crossOrigin value');

      var elImage2 = _createImageElement();
      image.setElement(elImage2);
      equal(elImage2.crossOrigin, '', 'setElement should set proper crossOrigin on an img element');

      // fromObject doesn't work on Node :/
      if (fabric.isLikelyNode) {
        start();
        return;
      }
      fabric.Image.fromObject(objRepr, function(img) {
        equal(img.crossOrigin, '');
        start();
      });
    });
  });

  // asyncTest('clone', function() {
  //   createImageObject(function(image) {
  //     ok(typeof image.clone == 'function');

  //     var imageClone = null;
  //     image.clone(function(clone) {
  //       imageClone = clone;
  //     });

  //     setTimeout(function() {
  //       ok(imageClone instanceof fabric.Image);
  //       deepEqual(imageClone.toObject(), image.toObject());
  //       start();
  //     }, 1000);
  //   });
  // });

  // asyncTest('cloneWidthHeight', function() {
  //   var image = createSmallImageObject();

  //   var imageClone = null;
  //   image.clone(function(clone) {
  //     imageClone = clone;
  //   });

  //   setTimeout(function() {
  //     equal(imageClone.getElement().width, IMG_WIDTH / 2,
  //       'clone\'s element should have width identical to that of original image');
  //     equal(imageClone.getElement().height, IMG_HEIGHT / 2,
  //       'clone\'s element should have height identical to that of original image');
  //     start();
  //   }, 1000);
  // });

  // asyncTest('fromObject', function() {
  //   ok(typeof fabric.Image.fromObject == 'function');

  //   // should not throw error when no callback is given
  //   var obj = fabric.util.object.extend(fabric.util.object.clone(REFERENCE_IMG_OBJECT), {
  //     src: IMG_SRC
  //   });
  //   fabric.Image.fromObject(obj);

  //   var image;
  //   fabric.Image.fromObject(obj, function(instance){
  //     image = instance;
  //   });

  //   setTimeout(function() {
  //     ok(image instanceof fabric.Image);
  //     start();
  //   }, 1000);
  // });

  // asyncTest('fromURL', function() {
  //   ok(typeof fabric.Image.fromURL == 'function');

  //   // should not throw error when no callback is given
  //   // can't use `assertNothingRaised` due to asynchronous callback
  //   fabric.Image.fromURL(IMG_SRC);

  //   var image;
  //   fabric.Image.fromURL(IMG_SRC, function(instance) {
  //     image = instance;
  //   });

  //   setTimeout(function() {
  //     ok(image instanceof fabric.Image);
  //     deepEqual(REFERENCE_IMG_OBJECT, image.toObject());
  //     start();
  //   }, 1000);
  // });

  // test('toGrayscale', function() {
  //   var image = createImageObject(),
  //       imageEl = _createImageElement();

  //   imageEl.src = IMG_SRC;
  //   image.setElement(imageEl);

  //   ok(typeof image.toGrayscale == 'function');

  //   if (!fabric.Canvas.supports('toDataURL')) {
  //     alert('toDataURL is not supported. Some tests can not be run.');
  //   }
  //   else {
  //     equal(image.toGrayscale(), image, 'chainable');
  //   }
  // });

  // asyncTest('fromElement', function() {

  //   function makeImageElement(attributes) {
  //     var element = _createImageElement();
  //     for (var prop in attributes) {
  //       element.setAttribute(prop, attributes[prop]);
  //     }
  //     return element;
  //   }

  //   var IMAGE_DATA_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAARCAYAAADtyJ2fAAAACXBIWXMAAAsSAAALEgHS3X78AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAVBJREFUeNqMU7tOBDEMtENuy614/QE/gZBOuvJK+Et6CiQ6JP6ExxWI7bhL1vgVExYKLPmsTTIzjieHd+MZZSBIAJwEyJU0EWaum+lNljRux3O6nl70Gx/GUwUeyYcDJWZNhMK1aEXYe95Mz4iP44kDTRUZSWSq1YEHri0/HZxXfGSFBN+qDEJTrNI+QXRBviZ7eWCQgjsg+IHiHYB30MhqUxwcmH1Arc2kFDwkBldeFGJLPqs/AbbF2dWgUym6Z2Tb6RVzYxG1wUnmaNcOonZiU0++l6C7FzoQY42g3+8jz+GZ+dWMr1rRH0OjAFhPO+VJFx/vWDqPmk8H97CGBUYUiqAGW0PVe1+aX8j2Ll0tgHtvLx6AK9Tu1ZTFTQ0ojChqGD4qkOzeAuzVfgzsaTym1ClS+IdwtQCFooQMBTumNun1H6Bfcc9/MUn4R3wJMAAZH6MmA4ht4gAAAABJRU5ErkJggg==";

  //   ok(typeof fabric.Image.fromElement == 'function', 'fromElement should exist');

  //   var imageEl = makeImageElement({
  //     width: "14",
  //     height: "17",
  //     "xlink:href": IMAGE_DATA_URL
  //   });

  //   var imgObject;
  //   fabric.Image.fromElement(imageEl, function(obj) {
  //     imgObject = obj;
  //   });

  //   setTimeout(function() {
  //     ok(imgObject instanceof fabric.Image);
  //     deepEqual(imgObject.get('width'), 14, 'width of an object');
  //     deepEqual(imgObject.get('height'), 17, 'height of an object');
  //     deepEqual(imgObject.getSrc(), IMAGE_DATA_URL, 'src of an object');
  //     start();
  //   }, 500);
  // });

})();
<commit_msg>Update test for fix of #1237<commit_after>(function() {

  function getAbsolutePath(path) {
    var isAbsolute = /^https?:/.test(path);
    if (isAbsolute) return path;
    var imgEl = _createImageElement();
    imgEl.src = path;
    var src = imgEl.src;
    imgEl = null;
    return src;
  }

  var IMG_SRC     = fabric.isLikelyNode ? (__dirname + '/../fixtures/test_image.gif') : getAbsolutePath('../fixtures/test_image.gif'),
      IMG_WIDTH   = 276,
      IMG_HEIGHT  = 110;

  var REFERENCE_IMG_OBJECT = {
    'type':               'image',
    'originX':            'left',
    'originY':            'top',
    'left':               0,
    'top':                0,
    'width':              IMG_WIDTH, // node-canvas doesn't seem to allow setting width/height on image objects
    'height':             IMG_HEIGHT, // or does it now?
    'fill':               'rgb(0,0,0)',
    'stroke':             null,
    'strokeWidth':        1,
    'strokeDashArray':    null,
    'strokeLineCap':      'butt',
    'strokeLineJoin':     'miter',
    'strokeMiterLimit':   10,
    'scaleX':             1,
    'scaleY':             1,
    'angle':              0,
    'flipX':              false,
    'flipY':              false,
    'opacity':            1,
    'src':                fabric.isLikelyNode ? undefined : IMG_SRC,
    'shadow':             null,
    'visible':            true,
    'backgroundColor':    '',
    'clipTo':             null,
    'filters':            [],
    'crossOrigin':        ''
  };

  function _createImageElement() {
    return fabric.isLikelyNode ? new (require('canvas').Image) : fabric.document.createElement('img');
  }

  function _createImageObject(width, height, callback) {
    var elImage = _createImageElement();
    elImage.width = width;
    elImage.height = height;
    setSrc(elImage, IMG_SRC, function() {
      callback(new fabric.Image(elImage));
    });
  }

  function createImageObject(callback) {
    return _createImageObject(IMG_WIDTH, IMG_HEIGHT, callback)
  }

  function createSmallImageObject(callback) {
    return _createImageObject(IMG_WIDTH / 2, IMG_HEIGHT / 2, callback);
  }

  function setSrc(img, src, callback) {
    if (fabric.isLikelyNode) {
      require('fs').readFile(src, function(err, imgData) {
        if (err) throw err;
        img.src = imgData;
        callback && callback();
      });
    }
    else {
      img.src = src;
      callback && callback();
    }
  }

  QUnit.module('fabric.Image');

  asyncTest('constructor', function() {
    ok(fabric.Image);

    createImageObject(function(image) {
      ok(image instanceof fabric.Image);
      ok(image instanceof fabric.Object);

      equal(image.get('type'), 'image');

      start();
    });
  });

  asyncTest('toObject', function() {
    createImageObject(function(image) {
      ok(typeof image.toObject == 'function');
      var toObject = image.toObject();
      // workaround for node-canvas sometimes producing images with width/height and sometimes not
      if (toObject.width === 0) {
        toObject.width = IMG_WIDTH;
      }
      if (toObject.height === 0) {
        toObject.height = IMG_HEIGHT;
      }
      deepEqual(toObject, REFERENCE_IMG_OBJECT);
      start();
    });
  });

  asyncTest('toString', function() {
    createImageObject(function(image) {
      ok(typeof image.toString == 'function');
      equal(image.toString(), '#<fabric.Image: { src: "' + (fabric.isLikelyNode ? undefined : IMG_SRC) + '" }>');
      start();
    });
  });

  asyncTest('getSrc', function() {
    createImageObject(function(image) {
      ok(typeof image.getSrc == 'function');
      equal(image.getSrc(), fabric.isLikelyNode ? undefined : IMG_SRC);
      start();
    });
  });

  test('getElement', function() {
    var elImage = _createImageElement();
    var image = new fabric.Image(elImage);
    ok(typeof image.getElement == 'function');
    equal(image.getElement(), elImage);
  });

  asyncTest('setElement', function() {
    createImageObject(function(image) {
      ok(typeof image.setElement == 'function');

      var elImage = _createImageElement();
      equal(image.setElement(elImage), image, 'chainable');
      equal(image.getElement(), elImage);
      equal(image._originalElement, elImage);

      start();
    });
  });

  asyncTest('crossOrigin', function() {
    createImageObject(function(image) {
      equal(image.crossOrigin, '', 'initial crossOrigin value should be set');

      start();

      var elImage = _createImageElement();
      elImage.crossOrigin = 'anonymous';
      var image = new fabric.Image(elImage);
      equal(image.crossOrigin, '', 'crossOrigin value on an instance takes precedence');

      var objRepr = image.toObject();
      equal(objRepr.crossOrigin, '', 'toObject should return proper crossOrigin value');

      var elImage2 = _createImageElement();
	  elImage2.crossOrigin = 'anonymous';
      image.setElement(elImage2);
      equal(elImage2.crossOrigin, 'anonymous', 'setElement should set proper crossOrigin on an img element');

      // fromObject doesn't work on Node :/
      if (fabric.isLikelyNode) {
        start();
        return;
      }
      fabric.Image.fromObject(objRepr, function(img) {
        equal(img.crossOrigin, '');
        start();
      });
    });
  });

  // asyncTest('clone', function() {
  //   createImageObject(function(image) {
  //     ok(typeof image.clone == 'function');

  //     var imageClone = null;
  //     image.clone(function(clone) {
  //       imageClone = clone;
  //     });

  //     setTimeout(function() {
  //       ok(imageClone instanceof fabric.Image);
  //       deepEqual(imageClone.toObject(), image.toObject());
  //       start();
  //     }, 1000);
  //   });
  // });

  // asyncTest('cloneWidthHeight', function() {
  //   var image = createSmallImageObject();

  //   var imageClone = null;
  //   image.clone(function(clone) {
  //     imageClone = clone;
  //   });

  //   setTimeout(function() {
  //     equal(imageClone.getElement().width, IMG_WIDTH / 2,
  //       'clone\'s element should have width identical to that of original image');
  //     equal(imageClone.getElement().height, IMG_HEIGHT / 2,
  //       'clone\'s element should have height identical to that of original image');
  //     start();
  //   }, 1000);
  // });

  // asyncTest('fromObject', function() {
  //   ok(typeof fabric.Image.fromObject == 'function');

  //   // should not throw error when no callback is given
  //   var obj = fabric.util.object.extend(fabric.util.object.clone(REFERENCE_IMG_OBJECT), {
  //     src: IMG_SRC
  //   });
  //   fabric.Image.fromObject(obj);

  //   var image;
  //   fabric.Image.fromObject(obj, function(instance){
  //     image = instance;
  //   });

  //   setTimeout(function() {
  //     ok(image instanceof fabric.Image);
  //     start();
  //   }, 1000);
  // });

  // asyncTest('fromURL', function() {
  //   ok(typeof fabric.Image.fromURL == 'function');

  //   // should not throw error when no callback is given
  //   // can't use `assertNothingRaised` due to asynchronous callback
  //   fabric.Image.fromURL(IMG_SRC);

  //   var image;
  //   fabric.Image.fromURL(IMG_SRC, function(instance) {
  //     image = instance;
  //   });

  //   setTimeout(function() {
  //     ok(image instanceof fabric.Image);
  //     deepEqual(REFERENCE_IMG_OBJECT, image.toObject());
  //     start();
  //   }, 1000);
  // });

  // test('toGrayscale', function() {
  //   var image = createImageObject(),
  //       imageEl = _createImageElement();

  //   imageEl.src = IMG_SRC;
  //   image.setElement(imageEl);

  //   ok(typeof image.toGrayscale == 'function');

  //   if (!fabric.Canvas.supports('toDataURL')) {
  //     alert('toDataURL is not supported. Some tests can not be run.');
  //   }
  //   else {
  //     equal(image.toGrayscale(), image, 'chainable');
  //   }
  // });

  // asyncTest('fromElement', function() {

  //   function makeImageElement(attributes) {
  //     var element = _createImageElement();
  //     for (var prop in attributes) {
  //       element.setAttribute(prop, attributes[prop]);
  //     }
  //     return element;
  //   }

  //   var IMAGE_DATA_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAARCAYAAADtyJ2fAAAACXBIWXMAAAsSAAALEgHS3X78AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAVBJREFUeNqMU7tOBDEMtENuy614/QE/gZBOuvJK+Et6CiQ6JP6ExxWI7bhL1vgVExYKLPmsTTIzjieHd+MZZSBIAJwEyJU0EWaum+lNljRux3O6nl70Gx/GUwUeyYcDJWZNhMK1aEXYe95Mz4iP44kDTRUZSWSq1YEHri0/HZxXfGSFBN+qDEJTrNI+QXRBviZ7eWCQgjsg+IHiHYB30MhqUxwcmH1Arc2kFDwkBldeFGJLPqs/AbbF2dWgUym6Z2Tb6RVzYxG1wUnmaNcOonZiU0++l6C7FzoQY42g3+8jz+GZ+dWMr1rRH0OjAFhPO+VJFx/vWDqPmk8H97CGBUYUiqAGW0PVe1+aX8j2Ll0tgHtvLx6AK9Tu1ZTFTQ0ojChqGD4qkOzeAuzVfgzsaTym1ClS+IdwtQCFooQMBTumNun1H6Bfcc9/MUn4R3wJMAAZH6MmA4ht4gAAAABJRU5ErkJggg==";

  //   ok(typeof fabric.Image.fromElement == 'function', 'fromElement should exist');

  //   var imageEl = makeImageElement({
  //     width: "14",
  //     height: "17",
  //     "xlink:href": IMAGE_DATA_URL
  //   });

  //   var imgObject;
  //   fabric.Image.fromElement(imageEl, function(obj) {
  //     imgObject = obj;
  //   });

  //   setTimeout(function() {
  //     ok(imgObject instanceof fabric.Image);
  //     deepEqual(imgObject.get('width'), 14, 'width of an object');
  //     deepEqual(imgObject.get('height'), 17, 'height of an object');
  //     deepEqual(imgObject.getSrc(), IMAGE_DATA_URL, 'src of an object');
  //     start();
  //   }, 500);
  // });

})();
<|endoftext|>