feat(rtts_assert): avoid deep recursion in prettyPrint

This commit is contained in:
Victor Berchet 2015-02-24 16:24:58 +01:00
parent 908a0aa7dc
commit e05079f4a8
2 changed files with 44 additions and 4 deletions

View File

@ -74,7 +74,15 @@ function assertArgumentTypes(...params) {
} }
} }
function prettyPrint(value) { function prettyPrint(value, depth) {
if (typeof(depth) === 'undefined') {
depth = 0;
}
if (depth++ > 3) {
return '[...]';
}
if (typeof value === 'undefined') { if (typeof value === 'undefined') {
return 'undefined'; return 'undefined';
} }
@ -96,12 +104,17 @@ function prettyPrint(value) {
return value.__assertName; return value.__assertName;
} }
if (value.map) { if (value.map && typeof value.map === 'function') {
return '[' + value.map(prettyPrint).join(', ') + ']'; return '[' + value.map((v) => prettyPrint(v, depth)).join(', ') + ']';
} }
var properties = Object.keys(value); var properties = Object.keys(value);
return '{' + properties.map((p) => p + ': ' + prettyPrint(value[p])).join(', ') + '}'; var suffix = '}';
if (properties.length > 20) {
properties.length = 20;
suffix = ', ... }';
}
return '{' + properties.map((p) => p + ': ' + prettyPrint(value[p], depth)).join(', ') + suffix;
} }
return value.__assertName || value.name || value.toString(); return value.__assertName || value.name || value.toString();

View File

@ -14,6 +14,33 @@
export function main() { export function main() {
describe('prettyPrint', () => {
class Type {};
it('should limit the number of printed properties', () => {
var o = {};
for (var i = 0; i < 100; i++) {
o['p_' + i] = i;
}
try {
assert.type(o, Type);
throw 'fail!';
} catch (e) {
expect(e.message.indexOf('p_0')).toBeGreaterThan(-1);
expect(e.message.indexOf('...')).toBeGreaterThan(-1);
expect(e.message.indexOf('p_20')).toBe(-1);
}
});
it('should limit the depth of printed properties', () => {
var o = {l1: {l2: {l3: {l4: {l5: {l6: 'deep'}}}}}};
expect(() => {
assert.type(o, Type);
}).toThrowError('Expected an instance of Type, got {l1: {l2: {l3: {l4: [...]}}}}!');
});
});
// ## Basic Type Check // ## Basic Type Check
// By default, `instanceof` is used to check the type. // By default, `instanceof` is used to check the type.
// //