-
Notifications
You must be signed in to change notification settings - Fork 29
/
createTopLevelExpect.js
1940 lines (1781 loc) · 52.1 KB
/
createTopLevelExpect.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const createStandardErrorMessage = require('./createStandardErrorMessage');
const utils = require('./utils');
const magicpen = require('magicpen');
const extend = utils.extend;
const ukkonen = require('ukkonen');
const makePromise = require('./makePromise');
const addAdditionalPromiseMethods = require('./addAdditionalPromiseMethods');
const wrapPromiseIfNecessary = require('./wrapPromiseIfNecessary');
const oathbreaker = require('./oathbreaker');
const UnexpectedError = require('./UnexpectedError');
const notifyPendingPromise = require('./notifyPendingPromise');
const defaultDepth = require('./defaultDepth');
const AssertionString = require('./AssertionString');
const Context = require('./Context');
const throwIfNonUnexpectedError = require('./throwIfNonUnexpectedError');
const ensureValidUseOfParenthesesOrBrackets = require('./ensureValidUseOfParenthesesOrBrackets');
const expandAssertion = require('./expandAssertion');
const nodeJsCustomInspect = require('./nodeJsCustomInspect');
function isAssertionArg({ type }) {
return type.is('assertion');
}
const anyType = {
_unexpectedType: true,
name: 'any',
level: 0,
identify() {
return true;
},
equal: utils.objectIs,
inspect(value, depth, output) {
if (output && output.isMagicPen) {
return output.text(value);
} else {
// Guard against node.js' require('util').inspect eagerly calling .inspect() on objects
return `type: ${this.name}`;
}
},
diff(actual, expected, output, diff, inspect) {
return null;
},
typeEqualityCache: {},
is(typeOrTypeName) {
let typeName;
if (typeof typeOrTypeName === 'string') {
typeName = typeOrTypeName;
} else {
typeName = typeOrTypeName.name;
}
const cachedValue = this.typeEqualityCache[typeName];
if (typeof cachedValue !== 'undefined') {
return cachedValue;
}
let result = false;
if (this.name === typeName) {
result = true;
} else if (this.baseType) {
result = this.baseType.is(typeName);
}
this.typeEqualityCache[typeName] = result;
return result;
},
};
if (nodeJsCustomInspect !== 'inspect') {
anyType[nodeJsCustomInspect] = function () {
return `type: ${this.name}`;
};
}
const OR = {};
function getOrGroups(expectations) {
const orGroups = [[]];
expectations.forEach((expectation) => {
if (expectation === OR) {
orGroups.push([]);
} else {
orGroups[orGroups.length - 1].push(expectation);
}
});
return orGroups;
}
function evaluateGroup(expect, context, subject, orGroup, forwardedFlags) {
return orGroup.map((expectation) => {
const args = Array.prototype.slice.call(expectation);
args.unshift(subject);
return {
expectation: args,
promise: makePromise(() => {
if (typeof args[1] === 'function') {
if (args.length > 2) {
throw new Error(
'expect.it(<function>) does not accept additional arguments'
);
} else {
// expect.it(function (value) { ... })
return args[1](args[0]);
}
} else {
return expect._expect(context.child(), args, forwardedFlags);
}
}),
};
});
}
function writeGroupEvaluationsToOutput(output, groupEvaluations) {
const hasOrClauses = groupEvaluations.length > 1;
const hasAndClauses = groupEvaluations.some(({ length }) => length > 1);
groupEvaluations.forEach((groupEvaluation, i) => {
if (i > 0) {
if (hasAndClauses) {
output.nl();
} else {
output.sp();
}
output.jsComment('or').nl();
}
let groupFailed = false;
groupEvaluation.forEach((evaluation, j) => {
if (j > 0) {
output.jsComment(' and').nl();
}
const isRejected = evaluation.promise.isRejected();
if (isRejected && !groupFailed) {
groupFailed = true;
const err = evaluation.promise.reason();
if (hasAndClauses || hasOrClauses) {
output.error('⨯ ');
}
output.block((output) => {
output.append(err.getErrorMessage(output));
});
} else {
if (isRejected) {
output.error('⨯ ');
} else {
output.success('✓ ');
}
const expectation = evaluation.expectation;
output.block((output) => {
const subject = expectation[0];
const subjectOutput = (output) => {
output.appendInspected(subject);
};
const args = expectation.slice(2);
const argsOutput = args.map((arg) => (output) => {
output.appendInspected(arg);
});
const testDescription = expectation[1];
createStandardErrorMessage(
output,
subjectOutput,
testDescription,
argsOutput,
{
subject,
}
);
});
}
});
});
}
function createExpectIt(expect, expectations, forwardedFlags) {
const orGroups = getOrGroups(expectations);
function expectIt(subject, context) {
context =
context && typeof context === 'object' && context instanceof Context
? context
: new Context();
if (
orGroups.length === 1 &&
orGroups[0].length === 1 &&
orGroups[0][0].length === 1 &&
typeof orGroups[0][0][0] === 'function'
) {
// expect.it(subject => ...)
return oathbreaker(orGroups[0][0][0](subject));
}
const groupEvaluations = [];
const promises = [];
orGroups.forEach((orGroup) => {
const evaluations = evaluateGroup(
expect,
context,
subject,
orGroup,
forwardedFlags
);
evaluations.forEach(({ promise }) => {
promises.push(promise);
});
groupEvaluations.push(evaluations);
});
return oathbreaker(
makePromise.settle(promises).then(() => {
groupEvaluations.forEach((groupEvaluation) => {
groupEvaluation.forEach(({ promise }) => {
if (
promise.isRejected() &&
promise.reason().errorMode === 'bubbleThrough'
) {
throw promise.reason();
}
});
});
if (
!groupEvaluations.some((groupEvaluation) =>
groupEvaluation.every(({ promise }) => promise.isFulfilled())
)
) {
expect.fail((output) => {
writeGroupEvaluationsToOutput(output, groupEvaluations);
});
}
})
);
}
expectIt._expectIt = true;
expectIt._expectations = expectations;
expectIt._OR = OR;
expectIt.and = function (...args) {
const copiedExpectations = expectations.slice();
copiedExpectations.push(args);
return createExpectIt(expect, copiedExpectations, forwardedFlags);
};
expectIt.or = function (...args) {
const copiedExpectations = expectations.slice();
copiedExpectations.push(OR, args);
return createExpectIt(expect, copiedExpectations, forwardedFlags);
};
return expectIt;
}
const expectPrototype = {
promise: makePromise,
notifyPendingPromise,
errorMode: 'default',
};
utils.setPrototypeOfOrExtend(expectPrototype, Function.prototype);
expectPrototype.it = function (...args) {
return createExpectIt(this._topLevelExpect, [args], this.flags);
};
expectPrototype.equal = function (actual, expected, depth, seen) {
depth = typeof depth === 'number' ? depth : 100;
if (depth <= 0) {
// detect recursive loops in the structure
seen = seen || [];
if (seen.indexOf(actual) !== -1) {
throw new Error('Cannot compare circular structures');
}
seen.push(actual);
}
return this.findCommonType(actual, expected).equal(actual, expected, (a, b) =>
this.equal(a, b, depth - 1, seen)
);
};
expectPrototype.inspect = function (obj, depth, outputOrFormat) {
let seen = [];
const printOutput = (obj, currentDepth, output) => {
const objType = this.findTypeOf(obj);
if (currentDepth <= 0 && objType.is('object') && !objType.is('expect.it')) {
return output.text('...');
}
seen = seen || [];
if (seen.indexOf(obj) !== -1) {
return output.text('[Circular]');
}
return objType.inspect(obj, currentDepth, output, (v, childDepth) => {
output = output.clone();
seen.push(obj);
if (typeof childDepth === 'undefined') {
childDepth = currentDepth - 1;
}
output = printOutput(v, childDepth, output) || output;
seen.pop();
return output;
});
};
let output =
typeof outputOrFormat === 'string'
? this.createOutput(outputOrFormat)
: outputOrFormat;
output = output || this.createOutput();
return (
printOutput(
obj,
typeof depth === 'number' ? depth : defaultDepth,
output
) || output
);
};
if (nodeJsCustomInspect !== 'inspect') {
expectPrototype[nodeJsCustomInspect] = expectPrototype.inspect;
}
expectPrototype.expandTypeAlternations = function (assertion) {
const createPermutations = (args, i) => {
if (i === args.length) {
return [];
}
const result = [];
args[i].forEach((arg) => {
const tails = createPermutations(args, i + 1);
if (tails.length) {
tails.forEach((tail) => {
result.push([arg].concat(tail));
});
} else if (arg.type.is('assertion')) {
result.push([
{ type: arg.type, minimum: 1, maximum: 1 },
{ type: this.getType('any'), minimum: 0, maximum: Infinity },
]);
result.push([
{ type: this.getType('expect.it'), minimum: 1, maximum: 1 },
]);
if (arg.minimum === 0) {
// <assertion?>
result.push([]);
}
} else {
result.push([arg]);
}
});
return result;
};
const result = [];
assertion.subject.forEach((subjectRequirement) => {
if (assertion.args.length) {
createPermutations(assertion.args, 0).forEach((args) => {
result.push(
extend({}, assertion, {
subject: subjectRequirement,
args,
})
);
});
} else {
result.push(
extend({}, assertion, {
subject: subjectRequirement,
args: [],
})
);
}
});
return result;
};
expectPrototype.parseAssertion = function (assertionString) {
const tokens = [];
let nextIndex = 0;
const parseTypeToken = (typeToken) => {
return typeToken.split('|').map((typeDeclaration) => {
const matchNameAndOperator = typeDeclaration.match(
/^([a-z_](?:|[a-z0-9_.-]*[_a-z0-9]))([+*?]|)$/i
);
if (!matchNameAndOperator) {
throw new SyntaxError(
`Cannot parse type declaration:${typeDeclaration}`
);
}
const type = this.getType(matchNameAndOperator[1]);
if (!type) {
throw new Error(
`Unknown type: ${matchNameAndOperator[1]} in ${assertionString}`
);
}
const operator = matchNameAndOperator[2];
return {
minimum: !operator || operator === '+' ? 1 : 0,
maximum: operator === '*' || operator === '+' ? Infinity : 1,
type,
};
});
};
function hasVarargs(types) {
return types.some(({ minimum, maximum }) => minimum !== 1 || maximum !== 1);
}
assertionString.replace(
/\s*<((?:[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])[?*+]?)(?:\|(?:[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])[?*+]?))*)>|\s*([^<]+)/gi,
({ length }, $1, $2, index) => {
if (index !== nextIndex) {
throw new SyntaxError(
`Cannot parse token at index ${nextIndex} in ${assertionString}`
);
}
if ($1) {
tokens.push(parseTypeToken($1));
} else {
tokens.push($2.trim());
}
nextIndex += length;
}
);
let assertion;
if (tokens.length === 1 && typeof tokens[0] === 'string') {
if (!this._legacyTypelessAssertionWarned) {
console.warn(
'The typeless expect.addAssertion syntax is deprecated and will be removed in a future update\n' +
'Please refer to http://unexpected.js.org/api/addAssertion/'
);
this._legacyTypelessAssertionWarned = true;
}
assertion = {
subject: parseTypeToken('any'),
assertion: tokens[0],
args: [parseTypeToken('any*')],
};
} else {
assertion = {
subject: tokens[0],
assertion: tokens[1],
args: tokens.slice(2),
};
}
if (!Array.isArray(assertion.subject)) {
throw new SyntaxError(`Missing subject type in ${assertionString}`);
}
if (typeof assertion.assertion !== 'string') {
throw new SyntaxError(`Missing assertion in ${assertionString}`);
}
if (hasVarargs(assertion.subject)) {
throw new SyntaxError(
`The subject type cannot have varargs: ${assertionString}`
);
}
if (assertion.args.some((arg) => typeof arg === 'string')) {
throw new SyntaxError('Only one assertion string is supported (see #225)');
}
if (assertion.args.slice(0, -1).some(hasVarargs)) {
throw new SyntaxError(
`Only the last argument type can have varargs: ${assertionString}`
);
}
if (
[assertion.subject]
.concat(assertion.args.slice(0, -1))
.some((argRequirements) =>
argRequirements.some(({ type }) => type.is('assertion'))
)
) {
throw new SyntaxError(
`Only the last argument type can be <assertion>: ${assertionString}`
);
}
const lastArgRequirements = assertion.args[assertion.args.length - 1] || [];
const assertionRequirements = lastArgRequirements.filter(({ type }) =>
type.is('assertion')
);
if (assertionRequirements.length > 0 && lastArgRequirements.length > 1) {
throw new SyntaxError(
`<assertion> cannot be alternated with other types: ${assertionString}`
);
}
if (assertionRequirements.some(({ maximum }) => maximum !== 1)) {
throw new SyntaxError(
`<assertion+> and <assertion*> are not allowed: ${assertionString}`
);
}
return this.expandTypeAlternations(assertion);
};
const placeholderSplitRegexp = /(\{(?:\d+)\})/g;
const placeholderRegexp = /\{(\d+)\}/;
expectPrototype._fail = function (arg) {
if (arg instanceof UnexpectedError) {
arg._hasSerializedErrorMessage = false;
throw arg;
}
if (utils.isError(arg)) {
throw arg;
}
const error = new UnexpectedError(this);
if (typeof arg === 'function') {
error.errorMode = 'bubble';
error.output = arg;
} else if (arg && typeof arg === 'object') {
if (typeof arg.message !== 'undefined') {
error.errorMode = 'bubble';
}
error.output = (output) => {
if (typeof arg.message !== 'undefined') {
if (arg.message.isMagicPen) {
output.append(arg.message);
} else if (typeof arg.message === 'function') {
arg.message.call(output, output);
} else {
output.text(String(arg.message));
}
} else {
output.error('Explicit failure');
}
};
Object.keys(arg).forEach(function (key) {
const value = arg[key];
if (key === 'diff') {
if (typeof value === 'function' && this.parent) {
error.createDiff = (output, diff, inspect, equal) => {
const childOutput = this.createOutput(output.format);
childOutput.inline = output.inline;
childOutput.output = output.output;
return value(
childOutput,
(actual, expected) => {
return this.diff(actual, expected, childOutput.clone());
},
(v, depth) =>
childOutput
.clone()
.appendInspected(v, (depth || defaultDepth) - 1),
(actual, expected) => this.equal(actual, expected)
);
};
} else {
error.createDiff = value;
}
} else if (key !== 'message') {
error[key] = value;
}
}, this);
} else {
let placeholderArgs;
if (arguments.length > 0) {
placeholderArgs = new Array(arguments.length - 1);
for (let i = 1; i < arguments.length; i += 1) {
placeholderArgs[i - 1] = arguments[i];
}
}
error.errorMode = 'bubble';
error.output = (output) => {
const message = arg ? String(arg) : 'Explicit failure';
const tokens = message.split(placeholderSplitRegexp);
tokens.forEach((token) => {
const match = placeholderRegexp.exec(token);
if (match) {
const index = match[1];
if (index in placeholderArgs) {
const placeholderArg = placeholderArgs[index];
if (placeholderArg && placeholderArg.isMagicPen) {
output.append(placeholderArg);
} else {
output.appendInspected(placeholderArg);
}
} else {
output.text(match[0]);
}
} else {
output.error(token);
}
});
};
}
throw error;
};
function compareSpecificities(a, b) {
for (let i = 0; i < Math.min(a.length, b.length); i += 1) {
const c = b[i] - a[i];
if (c !== 0) {
return c;
}
}
return b.length - a.length;
}
function calculateAssertionSpecificity({ subject, args }) {
return [subject.type.level].concat(
args.map(({ minimum, maximum, type }) => {
const bonus = minimum === 1 && maximum === 1 ? 0.5 : 0;
return bonus + type.level;
})
);
}
function calculateLimits(items) {
let minimum = 0;
let maximum = 0;
items.forEach((item) => {
minimum += item.minimum;
maximum += item.maximum;
});
return {
minimum,
maximum,
};
}
expectPrototype.addAssertion = function (
patternOrPatterns,
handler,
childExpect
) {
if (this._frozen) {
throw new Error(
'Cannot add an assertion to a frozen instance, please run .clone() first'
);
}
let maxArguments;
if (typeof childExpect === 'function') {
maxArguments = 3;
} else {
maxArguments = 2;
}
if (
arguments.length > maxArguments ||
typeof handler !== 'function' ||
(typeof patternOrPatterns !== 'string' && !Array.isArray(patternOrPatterns))
) {
let errorMessage =
'Syntax: expect.addAssertion(<string|array[string]>, function (expect, subject, ...) { ... });';
if (
(typeof handler === 'string' || Array.isArray(handler)) &&
typeof arguments[2] === 'function'
) {
errorMessage +=
'\nAs of Unexpected 10, the syntax for adding assertions that apply only to specific\n' +
'types has changed. See http://unexpected.js.org/api/addAssertion/';
}
throw new Error(errorMessage);
}
const patterns = Array.isArray(patternOrPatterns)
? patternOrPatterns
: [patternOrPatterns];
patterns.forEach((pattern) => {
if (typeof pattern !== 'string' || pattern === '') {
throw new Error('Assertion patterns must be a non-empty string');
} else {
if (pattern !== pattern.trim()) {
throw new Error(
`Assertion patterns can't start or end with whitespace:\n\n ${JSON.stringify(
pattern
)}`
);
}
}
});
const assertions = this.assertions;
const defaultValueByFlag = {};
const assertionHandlers = [];
let maxNumberOfArgs = 0;
patterns.forEach((pattern) => {
const assertionDeclarations = this.parseAssertion(pattern);
assertionDeclarations.forEach(({ assertion, args, subject }) => {
ensureValidUseOfParenthesesOrBrackets(assertion);
const expandedAssertions = expandAssertion(assertion);
expandedAssertions.forEach(({ flags, alternations, text }) => {
Object.keys(flags).forEach((flag) => {
defaultValueByFlag[flag] = false;
});
maxNumberOfArgs = Math.max(
maxNumberOfArgs,
args.reduce(
(previous, { maximum }) =>
previous + (maximum === null ? Infinity : maximum),
0
)
);
const limits = calculateLimits(args);
assertionHandlers.push({
handler,
alternations,
flags,
subject,
args,
testDescriptionString: text,
declaration: pattern,
expect: childExpect,
minimum: limits.minimum,
maximum: limits.maximum,
});
});
});
});
if (handler.length - 2 > maxNumberOfArgs) {
throw new Error(
`The provided assertion handler takes ${
handler.length - 2
} parameters, but the type signature specifies a maximum of ${maxNumberOfArgs}:\n\n ${JSON.stringify(
patterns
)}`
);
}
assertionHandlers.forEach((handler) => {
// Make sure that all flags are defined.
handler.flags = extend({}, defaultValueByFlag, handler.flags);
const assertionHandlers = assertions[handler.testDescriptionString];
handler.specificity = calculateAssertionSpecificity(handler);
if (!assertionHandlers) {
assertions[handler.testDescriptionString] = [handler];
} else {
let i = 0;
while (
i < assertionHandlers.length &&
compareSpecificities(
handler.specificity,
assertionHandlers[i].specificity
) > 0
) {
i += 1;
}
assertionHandlers.splice(i, 0, handler);
}
});
return this; // for chaining
};
expectPrototype.addType = function (type, childExpect) {
if (this._frozen) {
throw new Error(
'Cannot add a type to a frozen instance, please run .clone() first'
);
}
let baseType;
if (
typeof type.name !== 'string' ||
!/^[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])$/i.test(type.name)
) {
throw new Error(
'A type must be given a non-empty name and must match ^[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])$'
);
}
if (typeof type.identify !== 'function' && type.identify !== false) {
throw new Error(
`Type ${type.name} must specify an identify function or be declared abstract by setting identify to false`
);
}
if (this.typeByName[type.name]) {
throw new Error(`The type with the name ${type.name} already exists`);
}
if (type.base) {
baseType = this.getType(type.base);
if (!baseType) {
throw new Error(`Unknown base type: ${type.base}`);
}
} else {
baseType = anyType;
}
const extendedBaseType = Object.create(baseType);
extendedBaseType.inspect = (value, depth, output) => {
if (!output || !output.isMagicPen) {
throw new Error(
'You need to pass the output to baseType.inspect() as the third parameter'
);
}
return baseType.inspect(value, depth, output, (value, depth) =>
output.clone().appendInspected(value, depth)
);
};
if (nodeJsCustomInspect !== 'inspect') {
extendedBaseType[nodeJsCustomInspect] = extendedBaseType.inspect;
}
extendedBaseType.diff = (actual, expected, output) => {
if (!output || !output.isMagicPen) {
throw new Error(
'You need to pass the output to baseType.diff() as the third parameter'
);
}
return baseType.diff(
actual,
expected,
output.clone(),
(actual, expected) => this.diff(actual, expected, output.clone()),
(value, depth) => output.clone().appendInspected(value, depth),
this.equal.bind(this)
);
};
extendedBaseType.equal = (actual, expected) =>
baseType.equal(actual, expected, this.equal.bind(this));
const extendedType = extend({}, baseType, type, {
baseType: extendedBaseType,
});
const originalInspect = extendedType.inspect;
// Prevent node.js' util.inspect from complaining about our inspect method:
if (nodeJsCustomInspect !== 'inspect') {
extendedType[nodeJsCustomInspect] = function () {
return `type: ${type.name}`;
};
}
extendedType.inspect = function (obj, depth, output, inspect) {
if (arguments.length < 2 || !output || !output.isMagicPen) {
return `type: ${type.name}`;
} else if (childExpect) {
const childOutput = childExpect.createOutput(output.format);
return (
originalInspect.call(this, obj, depth, childOutput, inspect) ||
childOutput
);
} else {
return originalInspect.call(this, obj, depth, output, inspect) || output;
}
};
if (childExpect) {
extendedType.childExpect = childExpect;
const originalDiff = extendedType.diff;
extendedType.diff = function (
actual,
expected,
output,
inspect,
diff,
equal
) {
const childOutput = childExpect.createOutput(output.format);
// Make sure that already buffered up output is preserved:
childOutput.output = output.output;
return (
originalDiff.call(
this,
actual,
expected,
childOutput,
inspect,
diff,
equal
) || output
);
};
}
if (extendedType.identify === false) {
this.types.push(extendedType);
} else {
this.types.unshift(extendedType);
}
extendedType.level = baseType.level + 1;
extendedType.typeEqualityCache = {};
this.typeByName[extendedType.name] = extendedType;
return this;
};
expectPrototype.getType = function (typeName) {
return (
this.typeByName[typeName] || (this.parent && this.parent.getType(typeName))
);
};
expectPrototype.findTypeOf = function (obj) {
return (
utils.findFirst(
this.types || [],
(type) => type.identify && type.identify(obj)
) ||
(this.parent && this.parent.findTypeOf(obj))
);
};
expectPrototype.findTypeOfWithParentType = function (obj, requiredParentType) {
return (
utils.findFirst(
this.types || [],
(type) =>
type.identify &&
type.identify(obj) &&
(!requiredParentType || type.is(requiredParentType))
) ||
(this.parent &&
this.parent.findTypeOfWithParentType(obj, requiredParentType))
);
};
expectPrototype.findCommonType = function (a, b) {
const aAncestorIndex = {};
let current = this.findTypeOf(a);
while (current) {
aAncestorIndex[current.name] = current;
current = current.baseType;
}
current = this.findTypeOf(b);
while (current) {
if (aAncestorIndex[current.name]) {
return current;
}
current = current.baseType;
}
};
expectPrototype.addStyle = function (...args) {
if (this._frozen) {
throw new Error(
'Cannot add a style to a frozen instance, please run .clone() first'
);
}
this.output.addStyle(...args);
return this;
};
expectPrototype.installTheme = function (...args) {
if (this._frozen) {
throw new Error(
'Cannot install a theme into a frozen instance, please run .clone() first'
);
}
this.output.installTheme(...args);
return this;
};
function getPluginName(plugin) {
if (typeof plugin === 'function') {
return utils.getFunctionName(plugin);
} else {
return plugin.name;
}
}
expectPrototype.use = function (plugin) {
this._assertTopLevelExpect();
if (this._frozen) {
throw new Error(
'Cannot install a plugin into a frozen instance, please run .clone() first'
);
}
if (
(typeof plugin !== 'function' &&
(typeof plugin !== 'object' ||
typeof plugin.installInto !== 'function')) ||
(typeof plugin.name !== 'undefined' && typeof plugin.name !== 'string')
) {
throw new Error(
'Plugins must be functions or adhere to the following interface\n' +
'{\n' +
' name: <an optional plugin name>,\n' +
' version: <an optional semver version string>,\n' +
' installInto: <a function that will update the given expect instance>\n' +
'}'
);
}
const pluginName = getPluginName(plugin);
const existingPlugin = utils.findFirst(
this.installedPlugins,
(installedPlugin) => {
if (installedPlugin === plugin) {
return true;
} else {
return pluginName && pluginName === getPluginName(installedPlugin);
}
}
);
if (existingPlugin) {
if (