How to use createType method in storybook-root

Best JavaScript code snippet using storybook-root

test_schemas.js

Source:test_schemas.js Github

copy

Full Screen

...60 }61 ];62 testType(types.IntType, data);63 test('toBuffer int', function () {64 var type = createType('int');65 assert.equal(type.fromBuffer(new Buffer([0x80, 0x01])), 64);66 assert(new Buffer([0]).equals(type.toBuffer(0)));67 });68 test('resolve int > long', function () {69 var intType = createType('int');70 var longType = createType('long');71 var buf = intType.toBuffer(123);72 assert.equal(73 longType.fromBuffer(buf, longType.createResolver(intType)),74 12375 );76 });77 test('resolve int > [null, int]', function () {78 var wt = createType('int');79 var rt = createType(['null', 'int']);80 var buf = wt.toBuffer(123);81 assert.deepEqual(82 rt.fromBuffer(buf, rt.createResolver(wt)),83 {'int': 123}84 );85 });86 test('resolve int > float', function () {87 var wt = createType('int');88 var rt = createType('float');89 var buf = wt.toBuffer(123);90 assert.deepEqual(rt.fromBuffer(buf, rt.createResolver(wt)), 123);91 });92 test('resolve int > double', function () {93 var wt = createType('int');94 var rt = createType('double');95 var n = Math.pow(2, 30) + 1;96 var buf = wt.toBuffer(n);97 assert.deepEqual(rt.fromBuffer(buf, rt.createResolver(wt)), n);98 });99 test('toString', function () {100 assert.equal(createType('int').toString(), '"int"');101 });102 test('clone', function () {103 var t = createType('int');104 assert.equal(t.clone(123), 123);105 assert.throws(function () { t.clone(''); });106 });107 test('resolve invalid', function () {108 assert.throws(function () { getResolver('int', 'long'); });109 });110 });111 suite('LongType', function () {112 var data = [113 {114 valid: [1, -3, 12314, 9007199254740990, 900719925474090],115 invalid: [null, 'hi', undefined, 9007199254740991, 1.3, 1e67]116 }117 ];118 testType(types.LongType, data);119 test('resolve invalid', function () {120 assert.throws(function () { getResolver('long', 'double'); });121 });122 test('resolve long > float', function () {123 var t1 = createType('long');124 var t2 = createType('float');125 var n = 9007199254740990; // Number.MAX_SAFE_INTEGER - 1126 var buf = t1.toBuffer(n);127 var f = t2.fromBuffer(buf, t2.createResolver(t1));128 assert(Math.abs(f - n) / n < 1e-7);129 assert(t2.isValid(f));130 });131 test('precision loss', function () {132 var type = createType('long');133 var buf = new Buffer([0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x20]);134 assert.throws(function () { type.fromBuffer(buf); });135 });136 test('using missing methods', function () {137 assert.throws(function () { types.LongType.using(); });138 });139 });140 suite('StringType', function () {141 var data = [142 {143 valid: ['', 'hi'],144 invalid: [null, undefined, 1, 0]145 }146 ];147 testType(types.StringType, data);148 test('fromBuffer string', function () {149 var type = createType('string');150 var buf = new Buffer([0x06, 0x68, 0x69, 0x21]);151 var s = 'hi!';152 assert.equal(type.fromBuffer(buf), s);153 assert(buf.equals(type.toBuffer(s)));154 });155 test('toBuffer string', function () {156 var type = createType('string');157 var buf = new Buffer([0x06, 0x68, 0x69, 0x21]);158 assert(buf.equals(type.toBuffer('hi!', 1)));159 });160 test('resolve string > bytes', function () {161 var stringT = createType('string');162 var bytesT = createType('bytes');163 var buf = stringT.toBuffer('\x00\x01');164 assert.deepEqual(165 bytesT.fromBuffer(buf, bytesT.createResolver(stringT)),166 new Buffer([0, 1])167 );168 });169 test('encode resize', function () {170 var t = createType('string');171 var s = 'hello';172 var b, pos;173 b = new Buffer(2);174 pos = t.encode(s, b);175 assert(pos < 0);176 b = new Buffer(2 - pos);177 pos = t.encode(s, b);178 assert(pos >= 0);179 assert.equal(s, t.fromBuffer(b)); // Also checks exact length match.180 });181 });182 suite('NullType', function () {183 var data = [184 {185 schema: 'null',186 valid: [null],187 invalid: [0, 1, 'hi', undefined]188 }189 ];190 testType(types.NullType, data);191 });192 suite('FloatType', function () {193 var data = [194 {195 valid: [1, -3, 123e7],196 invalid: [null, 'hi', undefined],197 check: function (a, b) { assert(floatEquals(a, b)); }198 }199 ];200 testType(types.FloatType, data);201 test('compare buffer', function () {202 var t = createType('float');203 var b1 = t.toBuffer(0.5);204 assert.equal(t.compareBuffers(b1, b1), 0);205 var b2 = t.toBuffer(-0.75);206 assert.equal(t.compareBuffers(b1, b2), 1);207 var b3 = t.toBuffer(175);208 assert.equal(t.compareBuffers(b1, b3), -1);209 });210 test('resolver double > float', function () {211 assert.throws(function () { getResolver('float', 'double'); });212 });213 test('fromString', function () {214 var t = createType('float');215 var f = t.fromString('3.1');216 assert(t.isValid(f));217 });218 test('clone from double', function () {219 var t = createType('float');220 var d = 3.1;221 var f;222 f = t.clone(d);223 assert(t.isValid(f));224 });225 });226 suite('DoubleType', function () {227 var data = [228 {229 valid: [1, -3.4, 12314e31, 5e37],230 invalid: [null, 'hi', undefined],231 check: function (a, b) { assert(floatEquals(a, b), '' + [a, b]); }232 }233 ];234 testType(types.DoubleType, data);235 test('resolver string > double', function () {236 assert.throws(function () { getResolver('double', 'string'); });237 });238 test('compare buffer', function () {239 var t = createType('double');240 var b1 = t.toBuffer(0.5);241 assert.equal(t.compareBuffers(b1, b1), 0);242 var b2 = t.toBuffer(-0.75);243 assert.equal(t.compareBuffers(b1, b2), 1);244 var b3 = t.toBuffer(175);245 assert.equal(t.compareBuffers(b1, b3), -1);246 });247 });248 suite('BytesType', function () {249 var data = [250 {251 valid: [new Buffer(1), new Buffer('abc')],252 invalid: [null, 'hi', undefined, 1, 0, -3.5]253 }254 ];255 testType(types.BytesType, data);256 test('clone', function () {257 var t = createType('bytes');258 var s = '\x01\x02';259 var buf = new Buffer(s);260 var clone;261 clone = t.clone(buf);262 assert.deepEqual(clone, buf);263 clone[0] = 0;264 assert.equal(buf[0], 1);265 assert.throws(function () { t.clone(s); });266 clone = t.clone(buf.toJSON(), {coerceBuffers: true});267 assert.deepEqual(clone, buf);268 assert.throws(function () { t.clone(1, {coerceBuffers: true}); });269 });270 test('fromString', function () {271 var t = createType('bytes');272 var s = '\x01\x02';273 var buf = new Buffer(s);274 var clone = t.fromString(JSON.stringify(s));275 assert.deepEqual(clone, buf);276 });277 test('compare', function () {278 var t = createType('bytes');279 var b1 = t.toBuffer(new Buffer([0, 2]));280 assert.equal(t.compareBuffers(b1, b1), 0);281 var b2 = t.toBuffer(new Buffer([0, 2, 3]));282 assert.equal(t.compareBuffers(b1, b2), -1);283 var b3 = t.toBuffer(new Buffer([1]));284 assert.equal(t.compareBuffers(b3, b1), 1);285 });286 });287 suite('UnionType', function () {288 var data = [289 {290 name: 'null & string',291 schema: ['null', 'string'],292 valid: [null, {string: 'hi'}],293 invalid: ['null', undefined, {string: 1}],294 check: assert.deepEqual295 },296 {297 name: 'qualified name',298 schema: ['null', {type: 'fixed', name: 'a.B', size: 2}],299 valid: [null, {'a.B': new Buffer(2)}],300 invalid: [new Buffer(2)],301 check: assert.deepEqual302 },303 {304 name: 'array int',305 schema: ['int', {type: 'array', items: 'int'}],306 valid: [{'int': 1}, {array: [1,3]}],307 invalid: [null, 2, {array: ['a']}, [4], 2],308 check: assert.deepEqual309 },310 {311 name: 'null',312 schema: ['null'],313 valid: [null],314 invalid: [{array: ['a']}, [4], 'null'],315 check: assert.deepEqual316 }317 ];318 var schemas = [319 {},320 [],321 ['null', 'null'],322 ['null', {type: 'map', values: 'int'}, {type: 'map', values: 'long'}],323 ['null', ['int', 'string']]324 ];325 testType(types.UnionType, data, schemas);326 test('getTypes', function () {327 var t = createType(['null', 'int']);328 assert.deepEqual(t.getTypes(), [createType('null'), createType('int')]);329 });330 test('instanceof Union', function () {331 var type = new types.UnionType(['null', 'int']);332 assert(type instanceof types.UnionType);333 });334 test('missing name write', function () {335 var type = new types.UnionType(['null', 'int']);336 assert.throws(function () {337 type.toBuffer({b: 'a'});338 });339 });340 test('read invalid index', function () {341 var type = new types.UnionType(['null', 'int']);342 var buf = new Buffer([1, 0]);343 assert.throws(function () { type.fromBuffer(buf); });344 });345 test('non wrapped write', function () {346 var type = new types.UnionType(['null', 'int']);347 assert.throws(function () {348 type.toBuffer(1, true);349 }, Error);350 });351 test('to JSON', function () {352 var type = new types.UnionType(['null', 'int']);353 assert.equal(JSON.stringify(type), '["null","int"]');354 });355 test('resolve int to [long, int]', function () {356 var t1 = createType('int');357 var t2 = createType(['long', 'int']);358 var a = t2.createResolver(t1);359 var buf = t1.toBuffer(23);360 assert.deepEqual(t2.fromBuffer(buf, a), {'long': 23});361 });362 test('resolve null to [null, int]', function () {363 var t1 = createType('null');364 var t2 = createType(['null', 'int']);365 var a = t2.createResolver(t1);366 assert.deepEqual(t2.fromBuffer(new Buffer(0), a), null);367 });368 test('resolve [string, int] to [long, string]', function () {369 var t1 = createType(['string', 'int']);370 var t2 = createType(['int', 'bytes']);371 var a = t2.createResolver(t1);372 var buf;373 buf = t1.toBuffer({string: 'hi'});374 assert.deepEqual(t2.fromBuffer(buf, a), {'bytes': new Buffer('hi')});375 buf = t1.toBuffer({'int': 1});376 assert.deepEqual(t2.fromBuffer(buf, a), {'int': 1});377 });378 test('clone', function () {379 var t = new types.UnionType(['null', 'int']);380 var o = {'int': 1};381 assert.strictEqual(t.clone(null), null);382 var c = t.clone(o);383 assert.deepEqual(c, o);384 c.int = 2;385 assert.equal(o.int, 1);386 assert.throws(function () { t.clone([]); });387 assert.throws(function () { t.clone(undefined); });388 });389 test('clone and wrap', function () {390 var t = createType(['string', 'int']);391 var o;392 o = t.clone('hi', {wrapUnions: true});393 assert.deepEqual(o, {'string': 'hi'});394 o = t.clone(3, {wrapUnions: true});395 assert.deepEqual(o, {'int': 3});396 assert.throws(function () { t.clone(null, {wrapUnions: 2}); });397 });398 test('invalid multiple keys', function () {399 var t = createType(['null', 'int']);400 var o = {'int': 2};401 assert(t.isValid(o));402 o.foo = 3;403 assert(!t.isValid(o));404 });405 test('clone multiple keys', function () {406 var t = createType(['null', 'int']);407 var o = {'int': 2, foo: 3};408 assert.throws(function () { t.clone(o); });409 });410 test('clone unqualified names', function () {411 var t = createType({412 name: 'Person',413 type: 'record',414 fields: [415 {name: 'id1', type: {name: 'an.Id', type: 'fixed', size: 1}},416 {name: 'id2', type: ['null', 'an.Id']}417 ]418 });419 var b = new Buffer([0]);420 var o = {id1: b, id2: {Id: b}};421 assert.deepEqual(t.clone(o), {id1: b, id2: {'an.Id': b}});422 });423 test('clone unqualified names', function () {424 var t = createType({425 name: 'Person',426 type: 'record',427 fields: [428 {name: 'id1', type: {name: 'Id', type: 'fixed', size: 1}},429 {name: 'id2', type: ['null', 'Id']}430 ]431 });432 var b = new Buffer([0]);433 var o = {id1: b, id2: {'an.Id': b}};434 assert.throws(function () { t.clone(o); });435 });436 test('compare buffers', function () {437 var t = createType(['null', 'double']);438 var b1 = t.toBuffer(null);439 assert.equal(t.compareBuffers(b1, b1), 0);440 var b2 = t.toBuffer({'double': 4});441 assert.equal(t.compareBuffers(b2, b1), 1);442 assert.equal(t.compareBuffers(b1, b2), -1);443 var b3 = t.toBuffer({'double': 6});444 assert.equal(t.compareBuffers(b3, b2), 1);445 });446 test('compare', function () {447 var t;448 t = createType(['null', 'int']);449 assert.equal(t.compare(null, {'int': 3}), -1);450 assert.equal(t.compare(null, null), 0);451 t = createType(['int', 'float']);452 assert.equal(t.compare({'int': 2}, {'float': 0.5}), -1);453 assert.equal(t.compare({'int': 20}, {'int': 5}), 1);454 });455 });456 suite('EnumType', function () {457 var data = [458 {459 name: 'single symbol',460 schema: {name: 'Foo', symbols: ['HI']},461 valid: ['HI'],462 invalid: ['HEY', null, undefined, 0]463 },464 {465 name: 'number-ish as symbol',466 schema: {name: 'Foo', symbols: ['HI', 'A0']},467 valid: ['HI', 'A0'],468 invalid: ['HEY', null, undefined, 0, 'a0']469 }470 ];471 var schemas = [472 {name: 'Foo', symbols: []},473 {name: 'Foo'},474 {symbols: ['hi']},475 {name: 'G', symbols: ['0']}476 ];477 testType(types.EnumType, data, schemas);478 test('get full name', function () {479 var t = createType({480 type: 'enum',481 symbols: ['A', 'B'],482 name: 'Letter',483 namespace: 'latin'484 });485 assert.equal(t.getName(), 'latin.Letter');486 });487 test('get aliases', function () {488 var t = createType({489 type: 'enum',490 symbols: ['A', 'B'],491 name: 'Letter',492 namespace: 'latin',493 aliases: ['Character', 'alphabet.Letter']494 });495 var aliases = t.getAliases();496 assert.deepEqual(aliases, ['latin.Character', 'alphabet.Letter']);497 aliases.push('Char');498 assert.equal(t.getAliases().length, 3);499 });500 test('get symbols', function () {501 var t = createType({type: 'enum', symbols: ['A', 'B'], name: 'Letter'});502 var symbols = t.getSymbols();503 assert.deepEqual(symbols, ['A', 'B']);504 symbols.push('Char');505 assert.equal(t.getSymbols().length, 2);506 });507 test('duplicate symbol', function () {508 assert.throws(function () {509 createType({type: 'enum', symbols: ['A', 'B', 'A'], name: 'B'});510 });511 });512 test('write invalid', function () {513 var type = createType({type: 'enum', symbols: ['A'], name: 'a'});514 assert.throws(function () {515 type.toBuffer('B');516 });517 });518 test('read invalid index', function () {519 var type = new types.EnumType({type: 'enum', symbols: ['A'], name: 'a'});520 var buf = new Buffer([2]);521 assert.throws(function () { type.fromBuffer(buf); });522 });523 test('resolve', function () {524 var t1, t2, buf, resolver;525 t1 = newEnum('Foo', ['bar', 'baz']);526 t2 = newEnum('Foo', ['bar', 'baz']);527 resolver = t1.createResolver(t2);528 buf = t2.toBuffer('bar');529 assert.equal(t1.fromBuffer(buf, resolver), 'bar');530 t2 = newEnum('Foo', ['baz', 'bar']);531 buf = t2.toBuffer('bar');532 resolver = t1.createResolver(t2);533 assert.notEqual(t1.fromBuffer(buf), 'bar');534 assert.equal(t1.fromBuffer(buf, resolver), 'bar');535 t1 = newEnum('Foo2', ['foo', 'baz', 'bar'], ['Foo']);536 resolver = t1.createResolver(t2);537 assert.equal(t1.fromBuffer(buf, resolver), 'bar');538 t2 = newEnum('Foo', ['bar', 'bax']);539 assert.throws(function () { t1.createResolver(t2); });540 assert.throws(function () {541 t1.createResolver(createType('int'));542 });543 function newEnum(name, symbols, aliases, namespace) {544 var obj = {type: 'enum', name: name, symbols: symbols};545 if (aliases !== undefined) {546 obj.aliases = aliases;547 }548 if (namespace !== undefined) {549 obj.namespace = namespace;550 }551 return new types.EnumType(obj);552 }553 });554 test('clone', function () {555 var t = createType({type: 'enum', name: 'Foo', symbols: ['bar', 'baz']});556 assert.equal(t.clone('bar'), 'bar');557 assert.throws(function () { t.clone('BAR'); });558 assert.throws(function () { t.clone(null); });559 });560 test('compare buffers', function () {561 var t = createType({type: 'enum', name: 'Foo', symbols: ['bar', 'baz']});562 var b1 = t.toBuffer('bar');563 var b2 = t.toBuffer('baz');564 assert.equal(t.compareBuffers(b1, b1), 0);565 assert.equal(t.compareBuffers(b2, b1), 1);566 });567 test('compare', function () {568 var t = createType({type: 'enum', name: 'Foo', symbols: ['b', 'a']});569 assert.equal(t.compare('b', 'a'), -1);570 assert.equal(t.compare('a', 'a'), 0);571 });572 });573 suite('FixedType', function () {574 var data = [575 {576 name: 'size 1',577 schema: {name: 'Foo', size: 2},578 valid: [new Buffer([1, 2]), new Buffer([2, 3])],579 invalid: ['HEY', null, undefined, 0, new Buffer(1), new Buffer(3)],580 check: function (a, b) { assert(a.equals(b)); }581 }582 ];583 var schemas = [584 {name: 'Foo', size: 0},585 {name: 'Foo', size: -2},586 {size: 2},587 {name: 'Foo'},588 {}589 ];590 testType(types.FixedType, data, schemas);591 test('get full name', function () {592 var t = createType({593 type: 'fixed',594 size: 2,595 name: 'Id',596 namespace: 'id'597 });598 assert.equal(t.getName(), 'id.Id');599 });600 test('get aliases', function () {601 var t = createType({602 type: 'fixed',603 size: 3,604 name: 'Id'605 });606 var aliases = t.getAliases();607 assert.deepEqual(aliases, []);608 aliases.push('ID');609 assert.equal(t.getAliases().length, 1);610 });611 test('get size', function () {612 var t = createType({type: 'fixed', size: 5, name: 'Id'});613 assert.equal(t.getSize(), 5);614 });615 test('resolve', function () {616 var t1 = new types.FixedType({name: 'Id', size: 4});617 var t2 = new types.FixedType({name: 'Id', size: 4});618 assert.doesNotThrow(function () { t2.createResolver(t1); });619 t2 = new types.FixedType({name: 'Id2', size: 4});620 assert.throws(function () { t2.createResolver(t1); });621 t2 = new types.FixedType({name: 'Id2', size: 4, aliases: ['Id']});622 assert.doesNotThrow(function () { t2.createResolver(t1); });623 t2 = new types.FixedType({name: 'Id2', size: 5, aliases: ['Id']});624 assert.throws(function () { t2.createResolver(t1); });625 });626 test('clone', function () {627 var t = new types.FixedType({name: 'Id', size: 2});628 var s = '\x01\x02';629 var buf = new Buffer(s);630 var clone;631 clone = t.clone(buf);632 assert.deepEqual(clone, buf);633 clone[0] = 0;634 assert.equal(buf[0], 1);635 assert.throws(function () { t.clone(s); });636 clone = t.clone(buf.toJSON(), {coerceBuffers: true});637 assert.deepEqual(clone, buf);638 assert.throws(function () { t.clone(1, {coerceBuffers: true}); });639 assert.throws(function () { t.clone(new Buffer([2])); });640 });641 test('getSchema with extra fields', function () {642 var t = createType({type: 'fixed', name: 'Id', size: 2, three: 3});643 t.one = 1;644 assert.equal(t.getSchema(), '{"name":"Id","type":"fixed","size":2}');645 assert.equal(t.getSchema(true), '"Id"');646 });647 test('fromString', function () {648 var t = new types.FixedType({name: 'Id', size: 2});649 var s = '\x01\x02';650 var buf = new Buffer(s);651 var clone = t.fromString(JSON.stringify(s));652 assert.deepEqual(clone, buf);653 });654 test('compare buffers', function () {655 var t = createType({type: 'fixed', name: 'Id', size: 2});656 var b1 = new Buffer([1, 2]);657 assert.equal(t.compareBuffers(b1, b1), 0);658 var b2 = new Buffer([2, 2]);659 assert.equal(t.compareBuffers(b1, b2), -1);660 });661 });662 suite('MapType', function () {663 var data = [664 {665 name: 'int',666 schema: {values: 'int'},667 valid: [{one: 1}, {two: 2, o: 0}],668 invalid: [1, {o: null}, [], undefined, {o: 'hi'}, {1: '', 2: 3}, ''],669 check: assert.deepEqual670 },671 {672 name: 'enum',673 schema: {values: {type: 'enum', name: 'a', symbols: ['A', 'B']}},674 valid: [{a: 'A'}, {a: 'A', b: 'B'}, {}],675 invalid: [{o: 'a'}, {1: 'A', 2: 'b'}, {a: 3}],676 check: assert.deepEqual677 },678 {679 name: 'array of string',680 schema: {values: {type: 'array', items: 'string'}},681 valid: [{a: []}, {a: ['A'], b: ['B', '']}, {}],682 invalid: [{o: 'a', b: []}, {a: [1, 2]}, {a: {b: ''}}],683 check: assert.deepEqual684 }685 ];686 var schemas = [687 {},688 {values: ''},689 {values: {type: 'array'}}690 ];691 testType(types.MapType, data, schemas);692 test('get values type', function () {693 var t = new types.MapType({type: 'map', values: 'int'});694 assert.deepEqual(t.getValuesType(), createType('int'));695 });696 test('write int', function () {697 var t = new types.MapType({type: 'map', values: 'int'});698 var buf = t.toBuffer({'\x01': 3, '\x02': 4});699 assert.deepEqual(buf, new Buffer([4, 2, 1, 6, 2, 2, 8, 0]));700 });701 test('read long', function () {702 var t = new types.MapType({type: 'map', values: 'long'});703 var buf = new Buffer([4, 2, 1, 6, 2, 2, 8, 0]);704 assert.deepEqual(t.fromBuffer(buf), {'\x01': 3, '\x02': 4});705 });706 test('read with sizes', function () {707 var t = new types.MapType({type: 'map', values: 'int'});708 var buf = new Buffer([1,6,2,97,2,0]);709 assert.deepEqual(t.fromBuffer(buf), {a: 1});710 });711 test('skip', function () {712 var v1 = createType({713 name: 'Foo',714 type: 'record',715 fields: [716 {name: 'map', type: {type: 'map', values: 'int'}},717 {name: 'val', type: 'int'}718 ]719 });720 var v2 = createType({721 name: 'Foo',722 type: 'record',723 fields: [{name: 'val', type: 'int'}]724 });725 var b1 = new Buffer([2,2,97,2,0,6]); // Without sizes.726 var b2 = new Buffer([1,6,2,97,2,0,6]); // With sizes.727 var resolver = v2.createResolver(v1);728 assert.deepEqual(v2.fromBuffer(b1, resolver), {val: 3});729 assert.deepEqual(v2.fromBuffer(b2, resolver), {val: 3});730 });731 test('resolve int > long', function () {732 var t1 = new types.MapType({type: 'map', values: 'int'});733 var t2 = new types.MapType({type: 'map', values: 'long'});734 var resolver = t2.createResolver(t1);735 var obj = {one: 1, two: 2};736 var buf = t1.toBuffer(obj);737 assert.deepEqual(t2.fromBuffer(buf, resolver), obj);738 });739 test('resolve double > double', function () {740 var t = new types.MapType({type: 'map', values: 'double'});741 var resolver = t.createResolver(t);742 var obj = {one: 1, two: 2};743 var buf = t.toBuffer(obj);744 assert.deepEqual(t.fromBuffer(buf, resolver), obj);745 });746 test('resolve invalid', function () {747 var t1 = new types.MapType({type: 'map', values: 'int'});748 var t2 = new types.MapType({type: 'map', values: 'string'});749 assert.throws(function () { t2.createResolver(t1); });750 t2 = new types.ArrayType({type: 'array', items: 'string'});751 assert.throws(function () { t2.createResolver(t1); });752 });753 test('resolve fixed', function () {754 var t1 = createType({755 type: 'map', values: {name: 'Id', type: 'fixed', size: 2}756 });757 var t2 = createType({758 type: 'map', values: {759 name: 'Id2', aliases: ['Id'], type: 'fixed', size: 2760 }761 });762 var resolver = t2.createResolver(t1);763 var obj = {one: new Buffer([1, 2])};764 var buf = t1.toBuffer(obj);765 assert.deepEqual(t2.fromBuffer(buf, resolver), obj);766 });767 test('clone', function () {768 var t = new types.MapType({type: 'map', values: 'int'});769 var o = {one: 1, two: 2};770 var c = t.clone(o);771 assert.deepEqual(c, o);772 c.one = 3;773 assert.equal(o.one, 1);774 assert.throws(function () { t.clone(undefined); });775 });776 test('clone coerce buffers', function () {777 var t = new types.MapType({type: 'map', values: 'bytes'});778 var o = {one: {type: 'Buffer', data: [1]}};779 assert.throws(function () { t.clone(o); });780 var c = t.clone(o, {coerceBuffers: true});781 assert.deepEqual(c, {one: new Buffer([1])});782 });783 test('compare buffers', function () {784 var t = new types.MapType({type: 'map', values: 'bytes'});785 var b1 = t.toBuffer({});786 assert.throws(function () { t.compareBuffers(b1, b1); });787 });788 test('isValid hook', function () {789 var t = new types.MapType({type: 'map', values: 'int'});790 var o = {one: 1, two: 'deux', three: null, four: 4};791 var errs = {};792 assert(!t.isValid(o, {errorHook: hook}));793 assert.deepEqual(errs, {two: 'deux', three: null});794 function hook(path, obj, type) {795 assert.strictEqual(type, t.getValuesType());796 assert.equal(path.length, 1);797 errs[path[0]] = obj;798 }799 });800 test('getName', function () {801 var t = new types.MapType({type: 'map', values: 'int'});802 assert.strictEqual(t.getName(), undefined);803 });804 });805 suite('ArrayType', function () {806 var data = [807 {808 name: 'int',809 schema: {items: 'int'},810 valid: [[1,3,4], []],811 invalid: [1, {o: null}, undefined, ['a'], [true]],812 check: assert.deepEqual813 }814 ];815 var schemas = [816 {},817 {items: ''},818 ];819 testType(types.ArrayType, data, schemas);820 test('get items type', function () {821 var t = new types.ArrayType({type: 'array', items: 'int'});822 assert.deepEqual(t.getItemsType(), createType('int'));823 });824 test('read with sizes', function () {825 var t = new types.ArrayType({type: 'array', items: 'int'});826 var buf = new Buffer([1,2,2,0]);827 assert.deepEqual(t.fromBuffer(buf), [1]);828 });829 test('skip', function () {830 var v1 = createType({831 name: 'Foo',832 type: 'record',833 fields: [834 {name: 'array', type: {type: 'array', items: 'int'}},835 {name: 'val', type: 'int'}836 ]837 });838 var v2 = createType({839 name: 'Foo',840 type: 'record',841 fields: [{name: 'val', type: 'int'}]842 });843 var b1 = new Buffer([2,2,0,6]); // Without sizes.844 var b2 = new Buffer([1,2,2,0,6]); // With sizes.845 var resolver = v2.createResolver(v1);846 assert.deepEqual(v2.fromBuffer(b1, resolver), {val: 3});847 assert.deepEqual(v2.fromBuffer(b2, resolver), {val: 3});848 });849 test('resolve string items to bytes items', function () {850 var t1 = new types.ArrayType({type: 'array', items: 'string'});851 var t2 = new types.ArrayType({type: 'array', items: 'bytes'});852 var resolver = t2.createResolver(t1);853 var obj = ['\x01\x02'];854 var buf = t1.toBuffer(obj);855 assert.deepEqual(t2.fromBuffer(buf, resolver), [new Buffer([1, 2])]);856 });857 test('resolve invalid', function () {858 var t1 = new types.ArrayType({type: 'array', items: 'string'});859 var t2 = new types.ArrayType({type: 'array', items: 'long'});860 assert.throws(function () { t2.createResolver(t1); });861 t2 = new types.MapType({type: 'map', values: 'string'});862 assert.throws(function () { t2.createResolver(t1); });863 });864 test('clone', function () {865 var t = new types.ArrayType({type: 'array', items: 'int'});866 var o = [1, 2];867 var c = t.clone(o);868 assert.deepEqual(c, o);869 c.one = 3;870 assert.equal(o[0], 1);871 assert.throws(function () { t.clone({}); });872 });873 test('clone coerce buffers', function () {874 var t = createType({875 type: 'array',876 items: {type: 'fixed', name: 'Id', size: 2}877 });878 var o = [{type: 'Buffer', data: [1, 2]}];879 assert.throws(function () { t.clone(o); });880 var c = t.clone(o, {coerceBuffers: true});881 assert.deepEqual(c, [new Buffer([1, 2])]);882 });883 test('compare buffers', function () {884 var t = createType({type: 'array', items: 'int'});885 assert.equal(t.compareBuffers(t.toBuffer([]), t.toBuffer([])), 0);886 assert.equal(t.compareBuffers(t.toBuffer([1, 2]), t.toBuffer([])), 1);887 assert.equal(t.compareBuffers(t.toBuffer([1]), t.toBuffer([1, -1])), -1);888 assert.equal(t.compareBuffers(t.toBuffer([1]), t.toBuffer([2])), -1);889 assert.equal(t.compareBuffers(t.toBuffer([1, 2]), t.toBuffer([1])), 1);890 });891 test('compare', function () {892 var t = createType({type: 'array', items: 'int'});893 assert.equal(t.compare([], []), 0);894 assert.equal(t.compare([], [-1]), -1);895 assert.equal(t.compare([1], [1]), 0);896 assert.equal(t.compare([2], [1, 2]), 1);897 });898 test('isValid hook invalid array', function () {899 var t = createType({type: 'array', items: 'int'});900 var hookCalled = false;901 assert(!t.isValid({}, {errorHook: hook}));902 assert(hookCalled);903 function hook(path, obj, type) {904 assert.strictEqual(type, t);905 assert.deepEqual(path, []);906 hookCalled = true;907 }908 });909 test('isValid hook invalid elems', function () {910 var t = createType({type: 'array', items: 'int'});911 var paths = [];912 assert(!t.isValid([0, 3, 'hi', 5, 'hey'], {errorHook: hook}));913 assert.deepEqual(paths, [['2'], ['4']]);914 function hook(path, obj, type) {915 assert.strictEqual(type, t.getItemsType());916 assert.equal(typeof obj, 'string');917 paths.push(path);918 }919 });920 });921 suite('RecordType', function () {922 var data = [923 {924 name: 'union field null and string with default',925 schema: {926 type: 'record',927 name: 'a',928 fields: [{name: 'b', type: ['null', 'string'], 'default': null}]929 },930 valid: [],931 invalid: [],932 check: assert.deepEqual933 }934 ];935 var schemas = [936 {type: 'record', name: 'a', fields: ['null', 'string']},937 {type: 'record', name: 'a', fields: [{type: ['null', 'string']}]},938 {939 type: 'record',940 name: 'a',941 fields: [{name: 'b', type: ['null', 'string'], 'default': 'a'}]942 },943 {type: 'record', name: 'a', fields: {type: 'int', name: 'age'}}944 ];945 testType(types.RecordType, data, schemas);946 test('duplicate field names', function () {947 assert.throws(function () {948 createType({949 type: 'record',950 name: 'Person',951 fields: [{name: 'age', type: 'int'}, {name: 'age', type: 'float'}]952 });953 });954 });955 test('default constructor', function () {956 var type = createType({957 type: 'record',958 name: 'Person',959 fields: [{name: 'age', type: 'int', 'default': 25}]960 });961 var Person = type.getRecordConstructor();962 var p = new Person();963 assert.equal(p.age, 25);964 assert.strictEqual(p.constructor, Person);965 });966 test('default check & write', function () {967 var type = createType({968 type: 'record',969 name: 'Person',970 fields: [971 {name: 'age', type: 'int', 'default': 25},972 {name: 'name', type: 'string', 'default': '\x01'}973 ]974 });975 assert.deepEqual(type.toBuffer({}), new Buffer([50, 2, 1]));976 });977 test('fixed string default', function () {978 var s = '\x01\x04';979 var b = new Buffer(s);980 var type = createType({981 type: 'record',982 name: 'Object',983 fields: [984 {985 name: 'id',986 type: {type: 'fixed', size: 2, name: 'Id'},987 'default': s988 }989 ]990 });991 var obj = new (type.getRecordConstructor())();992 assert.deepEqual(obj.id, new Buffer([1, 4]));993 assert.deepEqual(type.toBuffer({}), b);994 });995 test('fixed buffer invalid default', function () {996 assert.throws(function () {997 createType({998 type: 'record',999 name: 'Object',1000 fields: [1001 {1002 name: 'id',1003 type: {type: 'fixed', size: 2, name: 'Id'},1004 'default': new Buffer([0])1005 }1006 ]1007 });1008 });1009 });1010 test('union invalid default', function () {1011 assert.throws(function () {1012 createType({1013 type: 'record',1014 name: 'Person',1015 fields: [{name: 'name', type: ['null', 'string'], 'default': ''}]1016 });1017 });1018 });1019 test('record default', function () {1020 var d = {street: null, zip: 123};1021 var Person = createType({1022 name: 'Person',1023 type: 'record',1024 fields: [1025 {1026 name: 'address',1027 type: {1028 name: 'Address',1029 type: 'record',1030 fields: [1031 {name: 'street', type: ['null', 'string']},1032 {name: 'zip', type: ['int', 'string']}1033 ]1034 },1035 'default': d1036 }1037 ]1038 }).getRecordConstructor();1039 var p = new Person();1040 assert.deepEqual(p.address, {street: null, zip: {'int': 123}});1041 });1042 test('record keyword field name', function () {1043 var type = createType({1044 type: 'record',1045 name: 'Person',1046 fields: [{name: 'null', type: 'int'}]1047 });1048 var Person = type.getRecordConstructor();1049 assert.deepEqual(new Person(2), {'null': 2});1050 });1051 test('record isValid', function () {1052 var type = createType({1053 type: 'record',1054 name: 'Person',1055 fields: [{name: 'age', type: 'int'}]1056 });1057 var Person = type.getRecordConstructor();1058 assert((new Person(20)).$isValid());1059 assert(!(new Person()).$isValid());1060 assert(!(new Person('a')).$isValid());1061 });1062 test('record toBuffer', function () {1063 var type = createType({1064 type: 'record',1065 name: 'Person',1066 fields: [{name: 'age', type: 'int'}]1067 });1068 var Person = type.getRecordConstructor();1069 assert.deepEqual((new Person(48)).$toBuffer(), new Buffer([96]));1070 assert.throws(function () { (new Person()).$toBuffer(); });1071 });1072 test('record compare', function () {1073 var P = createType({1074 type: 'record',1075 name: 'Person',1076 fields: [1077 {name: 'data', type: {type: 'map', values: 'int'}, order:'ignore'},1078 {name: 'age', type: 'int'}1079 ]1080 }).getRecordConstructor();1081 var p1 = new P({}, 1);1082 var p2 = new P({}, 2);1083 assert.equal(p1.$compare(p2), -1);1084 assert.equal(p2.$compare(p2), 0);1085 assert.equal(p2.$compare(p1), 1);1086 });1087 test('Record type', function () {1088 var type = createType({1089 type: 'record',1090 name: 'Person',1091 fields: [{name: 'age', type: 'int'}]1092 });1093 var Person = type.getRecordConstructor();1094 assert.strictEqual(Person.getType(), type);1095 });1096 test('mutable defaults', function () {1097 var Person = createType({1098 type: 'record',1099 name: 'Person',1100 fields: [1101 {1102 name: 'friends',1103 type: {type: 'array', items: 'string'},1104 'default': []1105 }1106 ]1107 }).getRecordConstructor();1108 var p1 = new Person(undefined);1109 assert.deepEqual(p1.friends, []);1110 p1.friends.push('ann');1111 var p2 = new Person(undefined);1112 assert.deepEqual(p2.friends, []);1113 });1114 test('resolve alias', function () {1115 var v1 = createType({1116 type: 'record',1117 name: 'Person',1118 fields: [{name: 'name', type: 'string'}]1119 });1120 var p = v1.random();1121 var buf = v1.toBuffer(p);1122 var v2 = createType({1123 type: 'record',1124 name: 'Human',1125 aliases: ['Person'],1126 fields: [{name: 'name', type: 'string'}]1127 });1128 var resolver = v2.createResolver(v1);1129 assert.deepEqual(v2.fromBuffer(buf, resolver), p);1130 var v3 = createType({1131 type: 'record',1132 name: 'Human',1133 fields: [{name: 'name', type: 'string'}]1134 });1135 assert.throws(function () { v3.createResolver(v1); });1136 });1137 test('resolve alias with namespace', function () {1138 var v1 = createType({1139 type: 'record',1140 name: 'Person',1141 namespace: 'earth',1142 fields: [{name: 'name', type: 'string'}]1143 });1144 var v2 = createType({1145 type: 'record',1146 name: 'Human',1147 aliases: ['Person'],1148 fields: [{name: 'name', type: 'string'}]1149 });1150 assert.throws(function () { v2.createResolver(v1); });1151 var v3 = createType({1152 type: 'record',1153 name: 'Human',1154 aliases: ['earth.Person'],1155 fields: [{name: 'name', type: 'string'}]1156 });1157 assert.doesNotThrow(function () { v3.createResolver(v1); });1158 });1159 test('resolve skip field', function () {1160 var v1 = createType({1161 type: 'record',1162 name: 'Person',1163 fields: [1164 {name: 'age', type: 'int'},1165 {name: 'name', type: 'string'}1166 ]1167 });1168 var p = {age: 25, name: 'Ann'};1169 var buf = v1.toBuffer(p);1170 var v2 = createType({1171 type: 'record',1172 name: 'Person',1173 fields: [{name: 'name', type: 'string'}]1174 });1175 var resolver = v2.createResolver(v1);1176 assert.deepEqual(v2.fromBuffer(buf, resolver), {name: 'Ann'});1177 });1178 test('resolve new field', function () {1179 var v1 = createType({1180 type: 'record',1181 name: 'Person',1182 fields: [{name: 'name', type: 'string'}]1183 });1184 var p = {name: 'Ann'};1185 var buf = v1.toBuffer(p);1186 var v2 = createType({1187 type: 'record',1188 name: 'Person',1189 fields: [1190 {name: 'age', type: 'int', 'default': 25},1191 {name: 'name', type: 'string'}1192 ]1193 });1194 var resolver = v2.createResolver(v1);1195 assert.deepEqual(v2.fromBuffer(buf, resolver), {name: 'Ann', age: 25});1196 });1197 test('resolve new field no default', function () {1198 var v1 = createType({1199 type: 'record',1200 name: 'Person',1201 fields: [{name: 'name', type: 'string'}]1202 });1203 var v2 = createType({1204 type: 'record',1205 name: 'Person',1206 fields: [1207 {name: 'age', type: 'int'},1208 {name: 'name', type: 'string'}1209 ]1210 });1211 assert.throws(function () { v2.createResolver(v1); });1212 });1213 test('resolve from recursive schema', function () {1214 var v1 = createType({1215 type: 'record',1216 name: 'Person',1217 fields: [{name: 'friends', type: {type: 'array', items: 'Person'}}]1218 });1219 var v2 = createType({1220 type: 'record',1221 name: 'Person',1222 fields: [{name: 'age', type: 'int', 'default': -1}]1223 });1224 var resolver = v2.createResolver(v1);1225 var p1 = {friends: [{friends: []}]};1226 var p2 = v2.fromBuffer(v1.toBuffer(p1), resolver);1227 assert.deepEqual(p2, {age: -1});1228 });1229 test('resolve to recursive schema', function () {1230 var v1 = createType({1231 type: 'record',1232 name: 'Person',1233 fields: [{name: 'age', type: 'int', 'default': -1}]1234 });1235 var v2 = createType({1236 type: 'record',1237 name: 'Person',1238 fields: [1239 {1240 name: 'friends',1241 type: {type: 'array', items: 'Person'},1242 'default': []1243 }1244 ]1245 });1246 var resolver = v2.createResolver(v1);1247 var p1 = {age: 25};1248 var p2 = v2.fromBuffer(v1.toBuffer(p1), resolver);1249 assert.deepEqual(p2, {friends: []});1250 });1251 test('resolve from both recursive schema', function () {1252 var v1 = createType({1253 type: 'record',1254 name: 'Person',1255 fields: [1256 {name: 'friends', type: {type: 'array', items: 'Person'}},1257 {name: 'age', type: 'int'}1258 ]1259 });1260 var v2 = createType({1261 type: 'record',1262 name: 'Person',1263 fields: [{name: 'friends', type: {type: 'array', items: 'Person'}}]1264 });1265 var resolver = v2.createResolver(v1);1266 var p1 = {friends: [{age: 1, friends: []}], age: 10};1267 var p2 = v2.fromBuffer(v1.toBuffer(p1), resolver);1268 assert.deepEqual(p2, {friends: [{friends: []}]});1269 });1270 test('resolve multiple matching aliases', function () {1271 var v1 = createType({1272 type: 'record',1273 name: 'Person',1274 fields: [1275 {name: 'phone', type: 'string'},1276 {name: 'number', type: 'string'}1277 ]1278 });1279 var v2 = createType({1280 type: 'record',1281 name: 'Person',1282 fields: [{name: 'number', type: 'string', aliases: ['phone']}]1283 });1284 assert.throws(function () { v2.createResolver(v1); });1285 });1286 test('getName', function () {1287 var t = createType({1288 type: 'record',1289 name: 'Person',1290 doc: 'Hi!',1291 namespace: 'earth',1292 aliases: ['Human'],1293 fields: [1294 {name: 'friends', type: {type: 'array', items: 'string'}},1295 {name: 'age', aliases: ['years'], type: {type: 'int'}}1296 ]1297 });1298 assert.strictEqual(t.getName(), 'earth.Person');1299 assert.equal(t.getName(true), 'record');1300 });1301 test('getSchema', function () {1302 var t = createType({1303 type: 'record',1304 name: 'Person',1305 doc: 'Hi!',1306 namespace: 'earth',1307 aliases: ['Human'],1308 fields: [1309 {name: 'friends', type: {type: 'array', items: 'string'}},1310 {name: 'age', aliases: ['years'], type: {type: 'int'}}1311 ]1312 });1313 assert.equal(1314 t.getSchema(),1315 '{"name":"earth.Person","type":"record","fields":[{"name":"friends","type":{"type":"array","items":"string"}},{"name":"age","type":"int"}]}'1316 );1317 assert.equal(t.getSchema(true), '"earth.Person"');1318 });1319 test('getSchema recursive schema', function () {1320 var t = createType({1321 type: 'record',1322 name: 'Person',1323 namespace: 'earth',1324 fields: [1325 {name: 'friends', type: {type: 'array', items: 'Person'}},1326 ]1327 });1328 assert.equal(1329 t.getSchema(),1330 '{"name":"earth.Person","type":"record","fields":[{"name":"friends","type":{"type":"array","items":"earth.Person"}}]}'1331 );1332 assert.equal(t.getSchema(true), '"earth.Person"');1333 });1334 test('toString record', function () {1335 var T = createType({1336 type: 'record',1337 name: 'Person',1338 fields: [{name: 'pwd', type: 'bytes'}]1339 }).getRecordConstructor();1340 var r = new T(new Buffer([1, 2]));1341 assert.equal(r.$toString(), T.getType().toString(r));1342 });1343 test('clone', function () {1344 var t = createType({1345 type: 'record',1346 name: 'Person',1347 fields: [{name: 'age', type: 'int'}, {name: 'name', type: 'string'}]1348 });1349 var Person = t.getRecordConstructor();1350 var o = {age: 25, name: 'Ann'};1351 var c = t.clone(o);1352 assert.deepEqual(c, o);1353 assert(c instanceof Person);1354 c.age = 26;1355 assert.equal(o.age, 25);1356 assert.strictEqual(c.$getType(), t);1357 assert.deepEqual(c.$clone(), c);1358 });1359 test('clone field hook', function () {1360 var t = createType({1361 type: 'record',1362 name: 'Person',1363 fields: [{name: 'age', type: 'int'}, {name: 'name', type: 'string'}]1364 });1365 var o = {name: 'Ann', age: 25};1366 var c = t.clone(o, {fieldHook: function (f, o, r) {1367 assert.strictEqual(r, t);1368 return f._type instanceof types.StringType ? o.toUpperCase() : o;1369 }});1370 assert.deepEqual(c, {name: 'ANN', age: 25});1371 });1372 test('get full name & aliases', function () {1373 var t = createType({1374 type: 'record',1375 name: 'Person',1376 namespace: 'a',1377 fields: [{name: 'age', type: 'int'}, {name: 'name', type: 'string'}]1378 });1379 assert.equal(t.getName(), 'a.Person');1380 assert.deepEqual(t.getAliases(), []);1381 });1382 test('field getters', function () {1383 var t = createType({1384 type: 'record',1385 name: 'Person',1386 namespace: 'a',1387 fields: [1388 {name: 'age', type: 'int'},1389 {name: 'name', type: 'string', aliases: ['word'], namespace: 'b'}1390 ]1391 });1392 var fields = t.getFields();1393 assert.deepEqual(fields[0].getAliases(), []);1394 assert.deepEqual(fields[1].getAliases(), ['word']);1395 assert.equal(fields[1].getName(), 'name'); // Namespaces are ignored.1396 assert.deepEqual(fields[1].getType(), createType('string'));1397 fields.push('null');1398 assert.equal(t.getFields().length, 2); // No change.1399 });1400 test('field order', function () {1401 var t = createType({1402 type: 'record',1403 name: 'Person',1404 fields: [{name: 'age', type: 'int'}]1405 });1406 var field = t.getFields()[0];1407 assert.equal(field.getOrder(), 'ascending'); // Default.1408 });1409 test('compare buffers default order', function () {1410 var t = createType({1411 type: 'record',1412 name: 'Person',1413 fields: [1414 {name: 'age', type: 'long'},1415 {name: 'name', type: 'string'},1416 {name: 'weight', type: 'float'},1417 ]1418 });1419 var b1 = t.toBuffer({age: 20, name: 'Ann', weight: 0.5});1420 assert.equal(t.compareBuffers(b1, b1), 0);1421 var b2 = t.toBuffer({age: 20, name: 'Bob', weight: 0});1422 assert.equal(t.compareBuffers(b1, b2), -1);1423 var b3 = t.toBuffer({age: 19, name: 'Carrie', weight: 0});1424 assert.equal(t.compareBuffers(b1, b3), 1);1425 });1426 test('compare buffers custom order', function () {1427 var t = createType({1428 type: 'record',1429 name: 'Person',1430 fields: [1431 {name: 'meta', type: {type: 'map', values: 'int'}, order: 'ignore'},1432 {name: 'name', type: 'string', order: 'descending'}1433 ]1434 });1435 var b1 = t.toBuffer({meta: {}, name: 'Ann'});1436 assert.equal(t.compareBuffers(b1, b1), 0);1437 var b2 = t.toBuffer({meta: {foo: 1}, name: 'Bob'});1438 assert.equal(t.compareBuffers(b1, b2), 1);1439 var b3 = t.toBuffer({meta: {foo: 0}, name: 'Alex'});1440 assert.equal(t.compareBuffers(b1, b3), -1);1441 });1442 test('compare buffers invalid order', function () {1443 assert.throws(function () { createType({1444 type: 'record',1445 name: 'Person',1446 fields: [{name: 'age', type: 'int', order: 'up'}]1447 }); });1448 });1449 test('error type', function () {1450 var t = createType({1451 type: 'error',1452 name: 'Ouch',1453 fields: [{name: 'name', type: 'string'}]1454 });1455 var E = t.getRecordConstructor();1456 var err = new E('MyError');1457 assert(err instanceof Error);1458 });1459 test('isValid hook', function () {1460 var t = createType({1461 type: 'record',1462 name: 'Person',1463 fields: [1464 {name: 'age', type: 'int'},1465 {name: 'names', type: {type: 'array', items: 'string'}}1466 ]1467 });1468 var hasErr = false;1469 try {1470 assert(!t.isValid({age: 23, names: ['ann', null]}, {errorHook: hook}));1471 } catch (err) {1472 hasErr = true;1473 }1474 assert(hasErr);1475 hasErr = false;1476 try {1477 // Again to make sure `PATH` was correctly reset.1478 assert(!t.isValid({age: 23, names: ['ann', null]}, {errorHook: hook}));1479 } catch (err) {1480 hasErr = true;1481 }1482 assert(hasErr);1483 function hook(path, obj, type) {1484 assert.strictEqual(type, t.getFields()[1].getType().getItemsType());1485 assert.deepEqual(path, ['names', '1']);1486 throw new Error();1487 }1488 });1489 test('isValid empty record', function () {1490 var t = createType({type: 'record', name: 'Person', fields: []});1491 assert(t.isValid({}));1492 });1493 });1494 suite('AbstractLongType', function () {1495 var fastLongType = new types.LongType();1496 suite('unpacked', function () {1497 var slowLongType = types.LongType.using({1498 fromBuffer: function (buf) {1499 var neg = buf[7] >> 7;1500 if (neg) { // Negative number.1501 invert(buf);1502 }1503 var n = buf.readInt32LE() + Math.pow(2, 32) * buf.readInt32LE(4);1504 if (neg) {1505 invert(buf);1506 n = -n - 1;1507 }1508 return n;1509 },1510 toBuffer: function (n) {1511 var buf = new Buffer(8);1512 var neg = n < 0;1513 if (neg) {1514 invert(buf);1515 n = -n - 1;1516 }1517 buf.writeInt32LE(n | 0);1518 var h = n / Math.pow(2, 32) | 0;1519 buf.writeInt32LE(h ? h : (n >= 0 ? 0 : -1), 4);1520 if (neg) {1521 invert(buf);1522 }1523 return buf;1524 },1525 isValid: function (n) {1526 return typeof n == 'number' && n % 1 === 0;1527 },1528 fromJSON: function (n) { return n; },1529 toJSON: function (n) { return n; },1530 compare: function (n1, n2) {1531 return n1 === n2 ? 0 : (n1 < n2 ? -1 : 1);1532 }1533 });1534 test('encode', function () {1535 [123, -1, 321414, 900719925474090].forEach(function (n) {1536 assert.deepEqual(slowLongType.toBuffer(n), fastLongType.toBuffer(n));1537 });1538 });1539 test('decode', function () {1540 [123, -1, 321414, 900719925474090].forEach(function (n) {1541 var buf = fastLongType.toBuffer(n);1542 assert.deepEqual(slowLongType.fromBuffer(buf), n);1543 });1544 });1545 test('clone', function () {1546 assert.equal(slowLongType.clone(123), 123);1547 assert.equal(slowLongType.fromString('-1'), -1);1548 assert.equal(slowLongType.toString(-1), '-1');1549 });1550 test('random', function () {1551 assert(slowLongType.isValid(slowLongType.random()));1552 });1553 test('isValid hook', function () {1554 var s = 'hi';1555 var errs = [];1556 assert(!slowLongType.isValid(s, {errorHook: hook}));1557 assert.deepEqual(errs, [s]);1558 assert.throws(function () { slowLongType.toBuffer(s); });1559 function hook(path, obj, type) {1560 assert.strictEqual(type, slowLongType);1561 assert.equal(path.length, 0);1562 errs.push(obj);1563 }1564 });1565 });1566 suite('packed', function () {1567 var slowLongType = types.LongType.using({1568 fromBuffer: function (buf) {1569 var tap = new Tap(buf);1570 return tap.readLong();1571 },1572 toBuffer: function (n) {1573 var buf = new Buffer(10);1574 var tap = new Tap(buf);1575 tap.writeLong(n);1576 return buf.slice(0, tap.pos);1577 },1578 fromJSON: function (n) { return n; },1579 toJSON: function (n) { return n; },1580 isValid: function (n) { return typeof n == 'number' && n % 1 === 0; },1581 compare: function (n1, n2) {1582 return n1 === n2 ? 0 : (n1 < n2 ? -1 : 1);1583 }1584 }, true);1585 test('encode', function () {1586 [123, -1, 321414, 900719925474090].forEach(function (n) {1587 assert.deepEqual(slowLongType.toBuffer(n), fastLongType.toBuffer(n));1588 });1589 });1590 test('decode', function () {1591 [123, -1, 321414, 900719925474090].forEach(function (n) {1592 var buf = fastLongType.toBuffer(n);1593 assert.deepEqual(slowLongType.fromBuffer(buf), n);1594 });1595 });1596 test('clone', function () {1597 assert.equal(slowLongType.clone(123), 123);1598 assert.equal(slowLongType.fromString('-1'), -1);1599 assert.equal(slowLongType.toString(-1), '-1');1600 });1601 test('random', function () {1602 assert(slowLongType.isValid(slowLongType.random()));1603 });1604 });1605 test('incomplete buffer', function () {1606 // Check that `fromBuffer` doesn't get called.1607 var slowLongType = new types.LongType.using({1608 fromBuffer: function () { throw new Error('no'); },1609 toBuffer: null,1610 fromJSON: null,1611 toJSON: null,1612 isValid: null,1613 compare: null1614 });1615 var buf = fastLongType.toBuffer(12314);1616 assert.deepEqual(1617 slowLongType.decode(buf.slice(0, 1)),1618 {value: undefined, offset: -1}1619 );1620 });1621 });1622 suite('LogicalType', function () {1623 function DateType(attrs, opts) {1624 types.LogicalType.call(this, attrs, opts, [types.LongType]);1625 }1626 util.inherits(DateType, types.LogicalType);1627 DateType.prototype._fromValue = function (val) { return new Date(val); };1628 DateType.prototype._toValue = function (date) { return +date; };1629 DateType.prototype._resolve = function (type) {1630 if (type instanceof types.StringType) {1631 return function (str) { return new Date(Date.parse(str)); };1632 } else if (type instanceof types.LongType) {1633 return this.fromValue;1634 }1635 };1636 function AgeType(attrs, opts) {1637 types.LogicalType.call(this, attrs, opts, [types.IntType]);1638 }1639 util.inherits(AgeType, types.LogicalType);1640 AgeType.prototype._fromValue = function (val) {1641 if (val < 0) { throw new Error('invalid age'); }1642 return val;1643 };1644 AgeType.prototype._toValue = AgeType.prototype._fromValue;1645 var logicalTypes = {age: AgeType, date: DateType};1646 test('valid type', function () {1647 var t = createType({1648 type: 'long',1649 logicalType: 'date'1650 }, {logicalTypes: logicalTypes});1651 assert(t instanceof DateType);1652 assert(t.getUnderlyingType() instanceof types.LongType);1653 assert(t.isValid(t.random()));1654 var d = new Date(123);1655 assert.equal(t.toString(d), '123');1656 assert.deepEqual(t.fromString('123'), d);1657 assert.deepEqual(t.clone(d), d);1658 assert.equal(t.compare(d, d), 0);1659 assert.equal(t.getSchema(), '"long"');1660 });1661 test('invalid type', function () {1662 var attrs = {1663 type: 'int',1664 logicalType: 'date'1665 };1666 var t;1667 t = createType(attrs); // Missing.1668 assert(t instanceof types.IntType);1669 t = createType(attrs, {logicalTypes: logicalTypes}); // Invalid.1670 assert(t instanceof types.IntType);1671 assert.throws(function () {1672 createType(attrs, {1673 logicalTypes: logicalTypes,1674 assertLogicalTypes: true1675 });1676 });1677 });1678 test('nested types', function () {1679 var attrs = {1680 name: 'Person',1681 type: 'record',1682 fields: [1683 {name: 'age', type: {type: 'int', logicalType: 'age'}},1684 {name: 'time', type: {type: 'long', logicalType: 'date'}}1685 ]1686 };1687 var base = createType(attrs);1688 var derived = createType(attrs, {logicalTypes: logicalTypes});1689 var fields = derived.getFields();1690 assert(fields[0].getType() instanceof AgeType);1691 assert(fields[1].getType() instanceof DateType);1692 var date = new Date(Date.now());1693 var buf = base.toBuffer({age: 12, time: +date});1694 var person = derived.fromBuffer(buf);1695 assert.deepEqual(person.age, 12);1696 assert.deepEqual(person.time, date);1697 assert.throws(function () { derived.toBuffer({age: -1, date: date}); });1698 var invalid = {age: -1, time: date};1699 assert.throws(function () { derived.toBuffer(invalid); });1700 var hasError = false;1701 derived.isValid(invalid, {errorHook: function (path, any, type) {1702 hasError = true;1703 assert.deepEqual(path, ['age']);1704 assert.equal(any, -1);1705 assert(type instanceof AgeType);1706 }});1707 assert(hasError);1708 });1709 test('recursive', function () {1710 function Person(friends) { this.friends = friends || []; }1711 function PersonType(attrs, opts) {1712 types.LogicalType.call(this, attrs, opts);1713 }1714 util.inherits(PersonType, types.LogicalType);1715 PersonType.prototype._fromValue = function (val) {1716 return new Person(val.friends);1717 };1718 PersonType.prototype._toValue = function (val) { return val; };1719 var t = createType({1720 type: 'record',1721 name: 'Person',1722 namespace: 'earth',1723 logicalType: 'person',1724 fields: [1725 {name: 'friends', type: {type: 'array', items: 'Person'}},1726 ]1727 }, {logicalTypes: {'person': PersonType}});1728 var p1 = new Person([new Person()]);1729 var buf = t.toBuffer(p1);1730 var p2 = t.fromBuffer(buf);1731 assert(p2 instanceof Person);1732 assert(p2.friends[0] instanceof Person);1733 assert.deepEqual(p2, p1);1734 });1735 test('resolve underlying > logical', function () {1736 var t1 = createType({type: 'string'});1737 var t2 = createType({1738 type: 'long',1739 logicalType: 'date'1740 }, {logicalTypes: logicalTypes});1741 var d1 = new Date(Date.now());1742 var buf = t1.toBuffer('' + d1);1743 var res = t2.createResolver(t1);1744 assert.throws(function () { t2.createResolver(createType('float')); });1745 var d2 = t2.fromBuffer(buf, res);1746 assert.deepEqual('' + d2, '' + d1); // Rounding error on date objects.1747 });1748 test('resolve logical > underlying', function () {1749 var t1 = createType({1750 type: 'long',1751 logicalType: 'date'1752 }, {logicalTypes: logicalTypes});1753 var t2 = createType({type: 'double'}); // Note long > double too.1754 var d = new Date(Date.now());1755 var buf = t1.toBuffer(d);1756 var res = t2.createResolver(t1);1757 assert.throws(function () { createType('int').createResolver(t1); });1758 assert.equal(t2.fromBuffer(buf, res), +d);1759 });1760 suite('union logical types', function () {1761 // Unions are slightly tricky to override with logical types since their1762 // schemas aren't represented as objects.1763 var schema = [1764 'null',1765 {1766 name: 'Person',1767 type: 'record',1768 fields: [1769 {name: 'name', type: 'string'},1770 {name: 'age', type: ['null', 'int'], 'default': null}1771 ]1772 }1773 ];1774 function createUnionTypeHook(Type) {1775 var visited = [];1776 return function(attrs, opts) {1777 if (attrs instanceof Array && !~visited.indexOf(attrs)) {1778 visited.push(attrs);1779 return new Type(attrs, opts);1780 }1781 };1782 }1783 test('unwrapped', function () {1784 /**1785 * A generic union type which exposes its values directly.1786 *1787 * This implementation is pretty minimal, we could optimize it by caching1788 * the underlying union's type names for example.1789 *1790 */1791 function UnwrappedUnionType(attrs, opts) {1792 types.LogicalType.call(this, attrs, opts);1793 }1794 util.inherits(UnwrappedUnionType, types.LogicalType);1795 UnwrappedUnionType.prototype._fromValue = function (val) {1796 return val === null ? null : val[Object.keys(val)[0]];1797 };1798 UnwrappedUnionType.prototype._toValue = function (any) {1799 return this.getUnderlyingType().clone(any, {wrapUnions: true});1800 };1801 var t1 = createType(1802 schema,1803 {typeHook: createUnionTypeHook(UnwrappedUnionType)}1804 );1805 var obj = {name: 'Ann', age: 23};1806 assert(t1.isValid(obj));1807 var buf = t1.toBuffer(obj);1808 var t2 = createType(schema);1809 assert.deepEqual(1810 t2.fromBuffer(buf),1811 {Person: {name: 'Ann', age: {'int': 23}}}1812 );1813 });1814 test('optional', function () {1815 /**1816 * A basic optional type.1817 *1818 * It assumes an underlying union of the form `["null", ???]`.1819 *1820 * Enhancements include:1821 *1822 * + Performing a check in the constructor on the underlying type (i.e.1823 * union with the correct form).1824 * + Code-generating the conversion methods (especially a constructor1825 * for `_toValue`).1826 *1827 */1828 function OptionalType(attrs, opts) {1829 types.LogicalType.call(this, attrs, opts);1830 var type = this.getUnderlyingType().getTypes()[1];1831 this._name = type.getName() || type.getName(true);1832 }1833 util.inherits(OptionalType, types.LogicalType);1834 OptionalType.prototype._fromValue = function (val) {1835 return val === null ? null : val[this._name];1836 };1837 OptionalType.prototype._toValue = function (any) {1838 if (any === null) {1839 return null;1840 }1841 var obj = {};1842 obj[this._name] = any;1843 return obj;1844 };1845 var t1 = createType(1846 schema,1847 {typeHook: createUnionTypeHook(OptionalType)}1848 );1849 var obj = {name: 'Ann', age: 23};1850 assert(t1.isValid(obj));1851 var buf = t1.toBuffer(obj);1852 var t2 = createType(schema);1853 assert.deepEqual(1854 t2.fromBuffer(buf),1855 {Person: {name: 'Ann', age: {'int': 23}}}1856 );1857 });1858 });1859 test('even integer', function () {1860 function EvenIntType(attrs, opts) {1861 types.LogicalType.call(this, attrs, opts, [types.IntType]);1862 }1863 util.inherits(EvenIntType, types.LogicalType);1864 EvenIntType.prototype._fromValue = function (val) {1865 this._assertValid(val);1866 return val;1867 };1868 EvenIntType.prototype._toValue = EvenIntType.prototype._fromValue;1869 EvenIntType.prototype._assertValid = function (any) {1870 if (any !== (any | 0) || any % 2) {1871 throw new Error('invalid');1872 }1873 };1874 var opts = {logicalTypes: {'even-integer': EvenIntType}};1875 var t = createType({type: 'int', logicalType: 'even-integer'}, opts);1876 assert(t.isValid(2));1877 assert(!t.isValid(3));1878 assert(!t.isValid('abc'));1879 assert.equal(t.fromBuffer(new Buffer([4])), 2);1880 assert.equal(t.clone(4), 4);1881 assert.equal(t.fromString('6'), 6);1882 assert.throws(function () { t.clone(3); });1883 assert.throws(function () { t.fromString('5'); });1884 assert.throws(function () { t.toBuffer(3); });1885 assert.throws(function () { t.fromBuffer(new Buffer([2])); });1886 });1887 });1888 suite('createType', function () {1889 test('null type', function () {1890 assert.throws(function () { createType(null); });1891 });1892 test('unknown types', function () {1893 assert.throws(function () { createType('a'); });1894 assert.throws(function () { createType({type: 'b'}); });1895 });1896 test('namespaced type', function () {1897 var type = createType({1898 type: 'record',1899 name: 'Human',1900 namespace: 'earth',1901 fields: [1902 {1903 name: 'id',1904 type: {type: 'fixed', name: 'Id', size: 2, namespace: 'all'}1905 },1906 {1907 name: 'alien',1908 type: {1909 type: 'record',1910 name: 'Alien',1911 namespace: 'all',1912 fields: [1913 {name: 'friend', type: 'earth.Human'},1914 {name: 'id', type: 'Id'},1915 ]1916 }1917 }1918 ]1919 });1920 assert.equal(type._name, 'earth.Human');1921 assert.equal(type._fields[0]._type._name, 'all.Id');1922 assert.equal(type._fields[1]._type._name, 'all.Alien');1923 });1924 test('wrapped primitive', function () {1925 var type = createType({1926 type: 'record',1927 name: 'Person',1928 fields: [{name: 'nothing', type: {type: 'null'}}]1929 });1930 assert.strictEqual(type._fields[0]._type.constructor, types.NullType);1931 });1932 test('fromBuffer truncated', function () {1933 var type = createType('int');1934 assert.throws(function () {1935 type.fromBuffer(new Buffer([128]));1936 });1937 });1938 test('fromBuffer bad resolver', function () {1939 var type = createType('int');1940 assert.throws(function () {1941 type.fromBuffer(new Buffer([0]), 123, {});1942 });1943 });1944 test('fromBuffer trailing', function () {1945 var type = createType('int');1946 assert.throws(function () {1947 type.fromBuffer(new Buffer([0, 2]));1948 });1949 });1950 test('fromBuffer trailing with resolver', function () {1951 var type = createType('int');1952 var resolver = type.createResolver(createType(['int']));1953 assert.equal(type.fromBuffer(new Buffer([0, 2]), resolver), 1);1954 });1955 test('toBuffer', function () {1956 var type = createType('int');1957 assert.throws(function () { type.toBuffer('abc'); });1958 assert.doesNotThrow(function () { type.toBuffer(123); });1959 });1960 test('toBuffer and resize', function () {1961 var type = createType('string');1962 assert.deepEqual(type.toBuffer('\x01', 1), new Buffer([2, 1]));1963 });1964 test('type hook', function () {1965 var refs = [];1966 var ts = [];1967 var o = {1968 type: 'record',1969 name: 'Human',1970 fields: [1971 {name: 'age', type: 'int'},1972 {name: 'name', type: {type: 'string'}}1973 ]1974 };1975 createType(o, {typeHook: hook});1976 assert.equal(ts.length, 1);1977 assert.equal(ts[0].getName(), 'Human');1978 function hook(schema, opts) {1979 if (~refs.indexOf(schema)) {1980 // Already seen this schema.1981 return;1982 }1983 refs.push(schema);1984 var type = createType(schema, opts);1985 if (type instanceof types.RecordType) {1986 ts.push(type);1987 }1988 return type;1989 }1990 });1991 test('type hook invalid return value', function () {1992 assert.throws(function () {1993 createType({type: 'int'}, {typeHook: hook});1994 });1995 function hook() { return 'int'; }1996 });1997 test('fingerprint', function () {1998 var t = createType('int');1999 var buf = new Buffer('ef524ea1b91e73173d938ade36c1db32', 'hex');2000 assert.deepEqual(t.getFingerprint('md5'), buf);2001 assert.deepEqual(t.getFingerprint(), buf);2002 });2003 test('getSchema default', function () {2004 var type = createType({2005 type: 'record',2006 name: 'Human',2007 fields: [2008 {name: 'id1', type: ['string', 'null'], 'default': ''},2009 {name: 'id2', type: ['null', 'string'], 'default': null}2010 ]2011 });2012 assert.deepEqual(2013 JSON.parse(type.getSchema()),2014 {2015 type: 'record',2016 name: 'Human',2017 fields: [2018 {name: 'id1', type: ['string', 'null']}, // Stripped defaults.2019 {name: 'id2', type: ['null', 'string']}2020 ]2021 }2022 );2023 });2024 });2025 suite('fromString', function () {2026 test('int', function () {2027 var t = createType('int');2028 assert.equal(t.fromString('2'), 2);2029 assert.throws(function () { t.fromString('"a"'); });2030 });2031 test('string', function () {2032 var t = createType('string');2033 assert.equal(t.fromString('"2"'), '2');2034 assert.throws(function () { t.fromString('a'); });2035 });2036 test('coerce buffers', function () {2037 var t = createType({2038 name: 'Ids',2039 type: 'record',2040 fields: [{name: 'id1', type: {name: 'Id1', type: 'fixed', size: 2}}]2041 });2042 var o = {id1: new Buffer([0, 1])};2043 var s = '{"id1": "\\u0000\\u0001"}';2044 var c = t.fromString(s);2045 assert.deepEqual(c, o);2046 assert(c instanceof t.getRecordConstructor());2047 });2048 });2049 suite('toString', function () {2050 test('int', function () {2051 var t = createType('int');2052 assert.equal(t.toString(2), '2');2053 assert.throws(function () { t.toString('a'); });2054 });2055 });2056 suite('resolve', function () {2057 test('non type', function () {2058 var t = createType({type: 'map', values: 'int'});2059 var obj = {type: 'map', values: 'int'};2060 assert.throws(function () { t.createResolver(obj); });2061 });2062 test('union to valid union', function () {2063 var t1 = createType(['int', 'string']);2064 var t2 = createType(['null', 'string', 'long']);2065 var resolver = t2.createResolver(t1);2066 var buf = t1.toBuffer({'int': 12});2067 assert.deepEqual(t2.fromBuffer(buf, resolver), {'long': 12});2068 });2069 test('union to invalid union', function () {2070 var t1 = createType(['int', 'string']);2071 var t2 = createType(['null', 'long']);2072 assert.throws(function () { t2.createResolver(t1); });2073 });2074 test('union to non union', function () {2075 var t1 = createType(['int', 'long']);2076 var t2 = createType('long');2077 var resolver = t2.createResolver(t1);2078 var buf = t1.toBuffer({'int': 12});2079 assert.equal(t2.fromBuffer(buf, resolver), 12);2080 buf = new Buffer([4, 0]);2081 assert.throws(function () { t2.fromBuffer(buf, resolver); });2082 });2083 test('union to invalid non union', function () {2084 var t1 = createType(['int', 'long']);2085 var t2 = createType('int');2086 assert.throws(function() { t2.createResolver(t1); });2087 });2088 });2089 suite('type references', function () {2090 test('existing', function () {2091 var type = createType({2092 type: 'record',2093 name: 'Person',2094 fields: [{name: 'so', type: 'Person'}]2095 });2096 assert.strictEqual(type, type._fields[0]._type);2097 });2098 test('namespaced', function () {2099 var type = createType({2100 type: 'record',2101 name: 'Person',2102 fields: [2103 {2104 name: 'so',2105 type: {2106 type: 'record',2107 name: 'Person',2108 fields: [{name: 'age', type: 'int'}],2109 namespace: 'a'2110 }2111 }2112 ]2113 });2114 assert.equal(type._name, 'Person');2115 assert.equal(type._fields[0]._type._name, 'a.Person');2116 });2117 test('redefining', function () {2118 assert.throws(function () {2119 createType({2120 type: 'record',2121 name: 'Person',2122 fields: [2123 {2124 name: 'so',2125 type: {2126 type: 'record',2127 name: 'Person',2128 fields: [{name: 'age', type: 'int'}]2129 }2130 }2131 ]2132 });2133 });2134 });2135 test('missing', function () {2136 assert.throws(function () {2137 createType({2138 type: 'record',2139 name: 'Person',2140 fields: [{name: 'so', type: 'Friend'}]2141 });2142 });2143 });2144 test('redefining primitive', function () {2145 assert.throws( // Unqualified.2146 function () { createType({type: 'fixed', name: 'int', size: 2}); }2147 );2148 assert.throws( // Qualified.2149 function () {2150 createType({type: 'fixed', name: 'int', size: 2, namespace: 'a'});2151 }2152 );2153 });2154 test('aliases', function () {2155 var type = createType({2156 type: 'record',2157 name: 'Person',2158 namespace: 'a',2159 aliases: ['Human', 'b.Being'],2160 fields: [{name: 'age', type: 'int'}]2161 });2162 assert.deepEqual(type._aliases, ['a.Human', 'b.Being']);2163 });2164 test('invalid', function () {2165 // Name.2166 assert.throws(function () {2167 createType({type: 'fixed', name: 'ID$', size: 3});2168 });2169 // Namespace.2170 assert.throws(function () {2171 createType({type: 'fixed', name: 'ID', size: 3, namespace: '1a'});2172 });2173 // Qualified.2174 assert.throws(function () {2175 createType({type: 'fixed', name: 'a.2.ID', size: 3});2176 });2177 });2178 });2179 suite('decode', function () {2180 test('long valid', function () {2181 var t = createType('long');2182 var buf = new Buffer([0, 128, 2, 0]);2183 var res = t.decode(buf, 1);2184 assert.deepEqual(res, {value: 128, offset: 3});2185 });2186 test('bytes invalid', function () {2187 var t = createType('bytes');2188 var buf = new Buffer([4, 1]);2189 var res = t.decode(buf, 0);2190 assert.deepEqual(res, {value: undefined, offset: -1});2191 });2192 });2193 suite('encode', function () {2194 test('int valid', function () {2195 var t = createType('int');2196 var buf = new Buffer(2);2197 buf.fill(0);2198 var n = t.encode(5, buf, 1);2199 assert.equal(n, 2);2200 assert.deepEqual(buf, new Buffer([0, 10]));2201 });2202 test('string invalid', function () {2203 var t = createType('string');2204 var buf = new Buffer(1);2205 var n = t.encode('\x01\x02', buf, 0);2206 assert.equal(n, -2);2207 });2208 test('invalid', function () {2209 var t = createType('float');2210 var buf = new Buffer(2);2211 assert.throws(function () { t.encode('hi', buf, 0); });2212 });2213 });2214 suite('inspect', function () {2215 test('type', function () {2216 assert.equal(createType('int').inspect(), '<IntType>');2217 assert.equal(2218 createType({type: 'map', values: 'string'}).inspect(),2219 '<MapType {"values":"string"}>'2220 );2221 assert.equal(2222 createType({type: 'fixed', name: 'Id', size: 2}).inspect(),2223 '<FixedType "Id">'2224 );2225 });2226 test('field', function () {2227 var type = createType({2228 type: 'record',2229 name: 'Person',2230 fields: [{name: 'age', type: 'int'}]2231 });2232 var field = type.getFields()[0];2233 assert.equal(field.inspect(), '<Field "age">');2234 });2235 test('resolver', function () {2236 var t1 = createType('int');2237 var t2 = createType('double');2238 var resolver = t2.createResolver(t1);2239 assert.equal(resolver.inspect(), '<Resolver>');2240 });2241 });2242 test('reset', function () {2243 types.Type.__reset(0);2244 var t = createType('string');2245 var buf = t.toBuffer('\x01');2246 assert.deepEqual(buf, new Buffer([2, 1]));2247 });2248});2249function testType(Type, data, invalidSchemas) {2250 data.forEach(function (elem) {2251 test('roundtrip', function () {2252 var type = new Type(elem.schema);2253 elem.valid.forEach(function (v) {2254 assert(type.isValid(v), '' + v);2255 var fn = elem.check || assert.deepEqual;2256 fn(type.fromBuffer(type.toBuffer(v)), v);2257 fn(type.fromString(type.toString(v), {coerceBuffers: true}), v);2258 });2259 elem.invalid.forEach(function (v) {2260 assert(!type.isValid(v), '' + v);2261 assert.throws(function () { type.isValid(v, {errorHook: hook}); });2262 assert.throws(function () { type.toBuffer(v); });2263 function hook() { throw new Error(); }2264 });2265 var n = 50;2266 while (n--) {2267 // Run a few times to make sure we cover any branches.2268 assert(type.isValid(type.random()));2269 }2270 });2271 });2272 test('skip', function () {2273 data.forEach(function (elem) {2274 var fn = elem.check || assert.deepEqual;2275 var items = elem.valid;2276 if (items.length > 1) {2277 var type = new Type(elem.schema);2278 var buf = new Buffer(1024);2279 var tap = new Tap(buf);2280 type._write(tap, items[0]);2281 type._write(tap, items[1]);2282 tap.pos = 0;2283 type._skip(tap);2284 fn(type._read(tap), items[1]);2285 }2286 });2287 });2288 if (invalidSchemas) {2289 test('invalid', function () {2290 invalidSchemas.forEach(function (schema) {2291 assert.throws(function () { new Type(schema); });2292 });2293 });2294 }2295}2296function getResolver(reader, writer) {2297 return createType(reader).createResolver(createType(writer));2298}2299function floatEquals(a, b) {2300 return Math.abs((a - b) / Math.min(a, b)) < 1e-7;2301}2302function invert(buf) {2303 var len = buf.length;2304 while (len--) {2305 buf[len] = ~buf[len];2306 }...

Full Screen

Full Screen

saved_objects_type_registry.test.ts

Source:saved_objects_type_registry.test.ts Github

copy

Full Screen

...31 beforeEach(() => {32 registry = new SavedObjectTypeRegistry();33 });34 it('allows to register types', () => {35 registry.registerType(createType({ name: 'typeA' }));36 registry.registerType(createType({ name: 'typeB' }));37 registry.registerType(createType({ name: 'typeC' }));38 expect(39 registry40 .getAllTypes()41 .map((type) => type.name)42 .sort()43 ).toEqual(['typeA', 'typeB', 'typeC']);44 });45 it('throws when trying to register the same type twice', () => {46 registry.registerType(createType({ name: 'typeA' }));47 registry.registerType(createType({ name: 'typeB' }));48 expect(() => {49 registry.registerType(createType({ name: 'typeA' }));50 }).toThrowErrorMatchingInlineSnapshot(`"Type 'typeA' is already registered"`);51 });52 describe('#getType', () => {53 it(`retrieve a type by it's name`, () => {54 const typeA = createType({ name: 'typeA' });55 const typeB = createType({ name: 'typeB' });56 registry.registerType(typeA);57 registry.registerType(typeB);58 registry.registerType(createType({ name: 'typeC' }));59 expect(registry.getType('typeA')).toEqual(typeA);60 expect(registry.getType('typeB')).toEqual(typeB);61 expect(registry.getType('unknownType')).toBeUndefined();62 });63 it('forbids to mutate the registered types', () => {64 registry.registerType(65 createType({66 name: 'typeA',67 mappings: {68 properties: {69 someField: { type: 'text' },70 },71 },72 })73 );74 const typeA = registry.getType('typeA')!;75 expect(() => {76 typeA.migrations = {};77 }).toThrow();78 expect(() => {79 typeA.name = 'foo';80 }).toThrow();81 expect(() => {82 typeA.mappings.properties = {};83 }).toThrow();84 expect(() => {85 typeA.indexPattern = '.overrided';86 }).toThrow();87 });88 });89 describe('#getAllTypes', () => {90 it('returns all registered types', () => {91 const typeA = createType({ name: 'typeA' });92 const typeB = createType({ name: 'typeB' });93 const typeC = createType({ name: 'typeC' });94 registry.registerType(typeA);95 registry.registerType(typeB);96 const registered = registry.getAllTypes();97 expect(registered.length).toEqual(2);98 expect(registered).toContainEqual(typeA);99 expect(registered).toContainEqual(typeB);100 expect(registered).not.toContainEqual(typeC);101 });102 it('forbids to mutate the registered types', () => {103 registry.registerType(104 createType({105 name: 'typeA',106 mappings: {107 properties: {108 someField: { type: 'text' },109 },110 },111 })112 );113 registry.registerType(114 createType({115 name: 'typeB',116 migrations: {117 '1.0.0': jest.fn(),118 },119 })120 );121 const typeA = registry.getType('typeA')!;122 const typeB = registry.getType('typeB')!;123 expect(() => {124 typeA.migrations = {};125 }).toThrow();126 expect(() => {127 typeA.name = 'foo';128 }).toThrow();129 expect(() => {130 typeB.mappings.properties = {};131 }).toThrow();132 expect(() => {133 typeB.indexPattern = '.overrided';134 }).toThrow();135 });136 it('does not mutate the registered types when altering the list', () => {137 registry.registerType(createType({ name: 'typeA' }));138 registry.registerType(createType({ name: 'typeB' }));139 registry.registerType(createType({ name: 'typeC' }));140 const types = registry.getAllTypes();141 types.splice(0, 3);142 expect(registry.getAllTypes().length).toEqual(3);143 });144 });145 describe('#isNamespaceAgnostic', () => {146 const expectResult = (expected: boolean, schemaDefinition?: Partial<SavedObjectsType>) => {147 registry = new SavedObjectTypeRegistry();148 registry.registerType(createType({ name: 'foo', ...schemaDefinition }));149 expect(registry.isNamespaceAgnostic('foo')).toBe(expected);150 };151 it(`returns false when the type is not registered`, () => {152 expect(registry.isNamespaceAgnostic('unknownType')).toEqual(false);153 });154 it(`returns true for namespaceType 'agnostic'`, () => {155 expectResult(true, { namespaceType: 'agnostic' });156 });157 it(`returns false for other namespaceType`, () => {158 expectResult(false, { namespaceType: 'multiple' });159 expectResult(false, { namespaceType: 'single' });160 expectResult(false, { namespaceType: undefined });161 });162 });163 describe('#isSingleNamespace', () => {164 const expectResult = (expected: boolean, schemaDefinition?: Partial<SavedObjectsType>) => {165 registry = new SavedObjectTypeRegistry();166 registry.registerType(createType({ name: 'foo', ...schemaDefinition }));167 expect(registry.isSingleNamespace('foo')).toBe(expected);168 };169 it(`returns true when the type is not registered`, () => {170 expect(registry.isSingleNamespace('unknownType')).toEqual(true);171 });172 it(`returns true for namespaceType 'single'`, () => {173 expectResult(true, { namespaceType: 'single' });174 expectResult(true, { namespaceType: undefined });175 });176 it(`returns false for other namespaceType`, () => {177 expectResult(false, { namespaceType: 'agnostic' });178 expectResult(false, { namespaceType: 'multiple' });179 });180 });181 describe('#isMultiNamespace', () => {182 const expectResult = (expected: boolean, schemaDefinition?: Partial<SavedObjectsType>) => {183 registry = new SavedObjectTypeRegistry();184 registry.registerType(createType({ name: 'foo', ...schemaDefinition }));185 expect(registry.isMultiNamespace('foo')).toBe(expected);186 };187 it(`returns false when the type is not registered`, () => {188 expect(registry.isMultiNamespace('unknownType')).toEqual(false);189 });190 it(`returns true for namespaceType 'multiple'`, () => {191 expectResult(true, { namespaceType: 'multiple' });192 });193 it(`returns false for other namespaceType`, () => {194 expectResult(false, { namespaceType: 'agnostic' });195 expectResult(false, { namespaceType: 'single' });196 expectResult(false, { namespaceType: undefined });197 });198 });199 describe('#isHidden', () => {200 it('returns correct value for the type', () => {201 registry.registerType(createType({ name: 'typeA', hidden: true }));202 registry.registerType(createType({ name: 'typeB', hidden: false }));203 expect(registry.isHidden('typeA')).toEqual(true);204 expect(registry.isHidden('typeB')).toEqual(false);205 });206 it('returns false when the type is not registered', () => {207 registry.registerType(createType({ name: 'typeA', hidden: true }));208 registry.registerType(createType({ name: 'typeB', hidden: false }));209 expect(registry.isHidden('unknownType')).toEqual(false);210 });211 });212 describe('#getIndex', () => {213 it('returns correct value for the type', () => {214 registry.registerType(createType({ name: 'typeA', indexPattern: '.custom-index' }));215 registry.registerType(createType({ name: 'typeB', indexPattern: '.another-index' }));216 registry.registerType(createType({ name: 'typeWithNoIndex' }));217 expect(registry.getIndex('typeA')).toEqual('.custom-index');218 expect(registry.getIndex('typeB')).toEqual('.another-index');219 expect(registry.getIndex('typeWithNoIndex')).toBeUndefined();220 });221 it('returns undefined when the type is not registered', () => {222 registry.registerType(createType({ name: 'typeA', namespaceType: 'agnostic' }));223 registry.registerType(createType({ name: 'typeB', namespaceType: 'single' }));224 expect(registry.getIndex('unknownType')).toBeUndefined();225 });226 });227 describe('#isImportableAndExportable', () => {228 it('returns correct value for the type', () => {229 registry.registerType(230 createType({ name: 'typeA', management: { importableAndExportable: true } })231 );232 registry.registerType(233 createType({ name: 'typeB', management: { importableAndExportable: false } })234 );235 expect(registry.isImportableAndExportable('typeA')).toBe(true);236 expect(registry.isImportableAndExportable('typeB')).toBe(false);237 });238 it('returns false when the type is not registered', () => {239 registry.registerType(createType({ name: 'typeA', management: {} }));240 registry.registerType(createType({ name: 'typeB', management: {} }));241 expect(registry.isImportableAndExportable('typeA')).toBe(false);242 });243 it('returns false when management is not defined for the type', () => {244 registry.registerType(createType({ name: 'typeA' }));245 expect(registry.isImportableAndExportable('unknownType')).toBe(false);246 });247 });248 describe('#getImportableAndExportableTypes', () => {249 it('returns all registered types that are importable/exportable', () => {250 const typeA = createType({ name: 'typeA', management: { importableAndExportable: true } });251 const typeB = createType({ name: 'typeB' });252 const typeC = createType({ name: 'typeC', management: { importableAndExportable: false } });253 const typeD = createType({ name: 'typeD', management: { importableAndExportable: true } });254 registry.registerType(typeA);255 registry.registerType(typeB);256 registry.registerType(typeC);257 registry.registerType(typeD);258 const types = registry.getImportableAndExportableTypes();259 expect(types.length).toEqual(2);260 expect(types.map((t) => t.name)).toEqual(['typeA', 'typeD']);261 });262 });...

Full Screen

Full Screen

sendXcm.js

Source:sendXcm.js Github

copy

Full Screen

...7 api, fromLocation='PHA30', toParaId=100, amount=100,8 toAddr='45R2pfjQUW2s9PQRHU48HQKLKHVMaDja7N3wpBtmF28UYDs2'9) {10 const bnAmount = bn1e12.muln(amount);11 return api.createType('Xcm', {12 WithdrawAsset: api.createType('WithdrawAsset', {13 assets: [14 api.createType('MultiAsset', {15 ConcreteFungible: api.createType('ConcreteFungible', {16 id: api.createType('MultiLocation', {17 X1: api.createType('Junction', {18 'GeneralKey': fromLocation19 })20 }),21 amount: api.createType('Compact<U128>', bnAmount),22 })23 }),24 ],25 effects: [26 api.createType('Order', {27 DepositReserveAsset: api.createType('DepositReserveAsset', {28 assets: [api.createType('MultiAsset', 'All')],29 dest: api.createType('MultiLocation', {30 X2: [31 api.createType('Junction', 'Parent'),32 api.createType('Junction', {33 Parachain: api.createType('Compact<U32>', toParaId),34 }),35 ]36 }),37 effects: [38 api.createType('Order', {39 DepositAsset: api.createType('DepositAsset', {40 assets: [41 api.createType('MultiAsset', 'All'),42 ],43 dest: api.createType('MultiLocation', {44 X1: api.createType('Junction', {45 AccountId32: api.createType('AccountId32Junction', {46 network: api.createType('NetworkId', 'Any'),47 id: toAddr,48 })49 })50 })51 })52 }),53 ]54 })55 })56 ],57 })58 });59}60async function main () {...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { createType } from 'storybook-root-elements';3import { storiesOf } from '@storybook/react';4import { withInfo } from '@storybook/addon-info';5import { withKnobs, text, boolean } from '@storybook/addon-knobs/react';6import { Button } from '../src/components/Button';7const stories = storiesOf('Button', module);8stories.addDecorator(withKnobs);9stories.add(10 withInfo()(() => {11 const label = text('Label', 'Click me');12 const disabled = boolean('Disabled', false);13 const type = createType('button', {14 onClick: () => alert('clicked'),15 });16 return <Button type={type} />;17 }),18);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { createType } from "storybook-root";2import { storiesOf } from "@storybook/react";3import React from "react";4import { withInfo } from "@storybook/addon-info";5import { withKnobs, text, boolean, number } from "@storybook/addon-knobs";6import { action } from "@storybook/addon-actions";7const stories = storiesOf("Test", module);8stories.addDecorator(withInfo).addDecorator(withKnobs);9stories.add("Test", () => {10 const name = text("name", "David");11 const age = number("age", 21);12 const isMale = boolean("isMale", true);13 const onClick = action("onClick");14 return (15 name: {name}, age: {age}, isMale: {isMale ? "true" : "false"}16 <button onClick={onClick}>Click Me!</button>17 );18});19stories.add("Test2", () => {20 const name = text("name", "David");21 const age = number("age", 21);22 const isMale = boolean("isMale", true);23 const onClick = action("onClick");24 return (25 name: {name}, age: {age}, isMale: {isMale ? "true" : "false"}26 <button onClick={onClick}>Click Me!</button>27 );28});29import { storiesOf } from "@storybook/react";30import React from "react";31import { withInfo } from "@storybook/addon-info";32import { withKnobs, text, boolean, number } from "@storybook/addon-knobs";33import { action } from "@storybook/addon-actions";34export const createType = (type) => {35 const stories = storiesOf(type, module);36 stories.addDecorator(withInfo).addDecorator(withKnobs);37 return stories;38};39import { configure } from "@storybook/react";40import { setOptions } from "@storybook/addon-options";41import { setDefaults } from "@storybook/addon-info";42setOptions({

Full Screen

Using AI Code Generation

copy

Full Screen

1import { createType } from 'storybook-root';2const type = createType('test');3export default type;4import React from 'react';5import { storiesOf } from '@storybook/react';6import { action } from '@storybook/addon-actions';7import { boolean, withKnobs } from '@storybook/addon-knobs';8import type from './test';9storiesOf('Test', module)10 .addDecorator(withKnobs)11 .add('Test', () => (12 ));13import React from 'react';14import { storiesOf } from '@storybook/react';15import { action } from '@storybook/addon-actions';16import { boolean, withKnobs } from '@storybook/addon-knobs';17import type from './test';18storiesOf(type, module)19 .addDecorator(withKnobs)20 .add('Test', () => (21 ));22import { configure, addDecorator } from '@storybook/react';23import { withKnobs } from '@storybook/addon-knobs';24import { createType } from 'storybook-root';25addDecorator(withKnobs);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { createType } from "storybook-root";2const myType = createType({3 fields: {4 },5});6export default myType;7import { createType } from "storybook-root";8const myType = createType({9 fields: {10 },11});12export default myType;13import { createType } from "storybook-root";14const myType = createType({15 fields: {16 },17});18export default myType;19import { createType } from "storybook-root";20const myType = createType({21 fields: {22 },23});24export default myType;25import { createType } from "storybook-root";26const myType = createType({27 fields: {28 },29});30export default myType;31import { createType } from "storybook-root";32const myType = createType({33 fields: {34 },35});36export default myType;37import { createType } from "storybook-root";38const myType = createType({39 fields: {40 },41});42export default myType;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { createType } from 'storybook-root-cause';2const type = createType('test');3type.log('test');4import { createType } from 'storybook-root-cause';5const type = createType('test');6type.log('test');7import { createType } from 'storybook-root-cause';8const type = createType('test');9type.log('test');10import { createType } from 'storybook-root-cause';11const type = createType('test');12type.log('test');13import { createType } from 'storybook-root-cause';14const type = createType('test');15type.log('test');16import { createType } from 'storybook-root-cause';17const type = createType('test');18type.log('test');19import { createType } from 'storybook-root-cause';20const type = createType('test');21type.log('test');22import { createType } from 'storybook-root-cause';23const type = createType('test');24type.log('test');25import { createType } from 'storybook-root-cause';26const type = createType('test');27type.log('test');28import { createType } from 'storybook-root-cause';29const type = createType('test');30type.log('test');31import { createType } from 'storybook-root-cause';32const type = createType('test');33type.log('test');34import { createType } from 'storybook-root-cause';35const type = createType('test');36type.log('test');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { createType } from 'storybook-root'2const Type = createType({3 props: {4 },5})6import Type from 'test.js'7export default {8 components: { Type },9 props: {10 name: {11 },12 color: {13 },14 },15}16import Type from 'storybook/components/Type'17export default {18 argTypes: {19 name: {20 control: {21 },22 },23 color: {24 control: {25 },26 },27 },28}29const Template = (args, { argTypes }) => ({30 props: Object.keys(argTypes),31 components: { Type },32})33export const TypeStory = Template.bind({})34TypeStory.args = {35}36import TypeStory from 'storybook/stories/Type'37import { Meta, Story, Preview, Props } from '@storybook/addon-docs/blocks'38<Meta title="Type" component={Type} />39<Props of={Type} />40import TypeStory from 'storybook/stories/Type'41import TypeStory from 'storybook/stories/Type'42export default {43 components: { TypeStory },44}45import Type from 'storybook/components

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createType } = require('storybook-root');2const { Type } = require('js-data');3const { createType } = require('storybook-root');4const { Type } = require('js-data');5const Post = createType({6 schema: {7 properties: {8 id: { type: 'number' },9 title: { type: 'string' }10 }11 }12});13module.exports = Post;14const { createType } = require('storybook-root');15const { Type } = require('js-data');16const { createType } = require('storybook-root');17const { Type } = require('js-data');18const Post = createType({19 schema: {20 properties: {21 id: { type: 'number' },22 title: { type: 'string' }23 }24 }25});26module.exports = Post;

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createType } = require('storybook-root');2const { string, number, bool, array, object } = createType('MyComponent');3const { createType } = require('storybook-root');4const { string, number, bool, array, object } = createType('MyComponent');5const { createType } = require('storybook-root');6const { string, number, bool, array, object } = createType('MyComponent');7const { createType } = require('storybook-root');8const { string, number, bool, array, object } = createType('MyComponent');9const { createType } = require('storybook-root');10const { string, number, bool, array, object } = createType('MyComponent');11const { createType } = require('storybook-root');12const { string, number, bool, array, object } = createType('MyComponent');13const { createType } = require('storybook-root');14const { string, number, bool, array, object } = createType('MyComponent');15const { createType } = require('storybook-root');16const { string, number, bool, array, object } = createType('MyComponent');17const { createType } = require('storybook-root');18const { string, number, bool, array, object } = createType('MyComponent');19const { createType } = require('storybook-root');20const { string, number, bool, array, object } = createType('MyComponent');21const { createType } = require('storybook-root');22const { string, number, bool, array, object } = createType('MyComponent');23const { createType } = require('storybook-root');24const { string, number, bool, array, object } = createType('MyComponent');

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful