OLD | NEW |
| (Empty) |
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 library matcher.core_matchers; | |
6 | |
7 import 'description.dart'; | |
8 import 'interfaces.dart'; | |
9 import 'util.dart'; | |
10 | |
11 /// Returns a matcher that matches the isEmpty property. | |
12 const Matcher isEmpty = const _Empty(); | |
13 | |
14 class _Empty extends Matcher { | |
15 const _Empty(); | |
16 | |
17 bool matches(item, Map matchState) => item.isEmpty; | |
18 | |
19 Description describe(Description description) => description.add('empty'); | |
20 } | |
21 | |
22 /// Returns a matcher that matches the isNotEmpty property. | |
23 const Matcher isNotEmpty = const _NotEmpty(); | |
24 | |
25 class _NotEmpty extends Matcher { | |
26 const _NotEmpty(); | |
27 | |
28 bool matches(item, Map matchState) => item.isNotEmpty; | |
29 | |
30 Description describe(Description description) => description.add('non-empty'); | |
31 } | |
32 | |
33 /// A matcher that matches any null value. | |
34 const Matcher isNull = const _IsNull(); | |
35 | |
36 /// A matcher that matches any non-null value. | |
37 const Matcher isNotNull = const _IsNotNull(); | |
38 | |
39 class _IsNull extends Matcher { | |
40 const _IsNull(); | |
41 bool matches(item, Map matchState) => item == null; | |
42 Description describe(Description description) => description.add('null'); | |
43 } | |
44 | |
45 class _IsNotNull extends Matcher { | |
46 const _IsNotNull(); | |
47 bool matches(item, Map matchState) => item != null; | |
48 Description describe(Description description) => description.add('not null'); | |
49 } | |
50 | |
51 /// A matcher that matches the Boolean value true. | |
52 const Matcher isTrue = const _IsTrue(); | |
53 | |
54 /// A matcher that matches anything except the Boolean value true. | |
55 const Matcher isFalse = const _IsFalse(); | |
56 | |
57 class _IsTrue extends Matcher { | |
58 const _IsTrue(); | |
59 bool matches(item, Map matchState) => item == true; | |
60 Description describe(Description description) => description.add('true'); | |
61 } | |
62 | |
63 class _IsFalse extends Matcher { | |
64 const _IsFalse(); | |
65 bool matches(item, Map matchState) => item == false; | |
66 Description describe(Description description) => description.add('false'); | |
67 } | |
68 | |
69 /// A matcher that matches the numeric value NaN. | |
70 const Matcher isNaN = const _IsNaN(); | |
71 | |
72 /// A matcher that matches any non-NaN value. | |
73 const Matcher isNotNaN = const _IsNotNaN(); | |
74 | |
75 class _IsNaN extends Matcher { | |
76 const _IsNaN(); | |
77 bool matches(item, Map matchState) => double.NAN.compareTo(item) == 0; | |
78 Description describe(Description description) => description.add('NaN'); | |
79 } | |
80 | |
81 class _IsNotNaN extends Matcher { | |
82 const _IsNotNaN(); | |
83 bool matches(item, Map matchState) => double.NAN.compareTo(item) != 0; | |
84 Description describe(Description description) => description.add('not NaN'); | |
85 } | |
86 | |
87 /// Returns a matches that matches if the value is the same instance | |
88 /// as [expected], using [identical]. | |
89 Matcher same(expected) => new _IsSameAs(expected); | |
90 | |
91 class _IsSameAs extends Matcher { | |
92 final _expected; | |
93 const _IsSameAs(this._expected); | |
94 bool matches(item, Map matchState) => identical(item, _expected); | |
95 // If all types were hashable we could show a hash here. | |
96 Description describe(Description description) => | |
97 description.add('same instance as ').addDescriptionOf(_expected); | |
98 } | |
99 | |
100 /// Returns a matcher that matches if the value is structurally equal to | |
101 /// [expected]. | |
102 /// | |
103 /// If [expected] is a [Matcher], then it matches using that. Otherwise it tests | |
104 /// for equality using `==` on the expected value. | |
105 /// | |
106 /// For [Iterable]s and [Map]s, this will recursively match the elements. To | |
107 /// handle cyclic structures a recursion depth [limit] can be provided. The | |
108 /// default limit is 100. [Set]s will be compared order-independently. | |
109 Matcher equals(expected, [int limit = 100]) => expected is String | |
110 ? new _StringEqualsMatcher(expected) | |
111 : new _DeepMatcher(expected, limit); | |
112 | |
113 class _DeepMatcher extends Matcher { | |
114 final _expected; | |
115 final int _limit; | |
116 var count; | |
117 | |
118 _DeepMatcher(this._expected, [int limit = 1000]) : this._limit = limit; | |
119 | |
120 // Returns a pair (reason, location) | |
121 List _compareIterables(expected, actual, matcher, depth, location) { | |
122 if (actual is! Iterable) return ['is not Iterable', location]; | |
123 | |
124 var expectedIterator = expected.iterator; | |
125 var actualIterator = actual.iterator; | |
126 for (var index = 0; ; index++) { | |
127 // Advance in lockstep. | |
128 var expectedNext = expectedIterator.moveNext(); | |
129 var actualNext = actualIterator.moveNext(); | |
130 | |
131 // If we reached the end of both, we succeeded. | |
132 if (!expectedNext && !actualNext) return null; | |
133 | |
134 // Fail if their lengths are different. | |
135 var newLocation = '${location}[${index}]'; | |
136 if (!expectedNext) return ['longer than expected', newLocation]; | |
137 if (!actualNext) return ['shorter than expected', newLocation]; | |
138 | |
139 // Match the elements. | |
140 var rp = matcher( | |
141 expectedIterator.current, actualIterator.current, newLocation, depth); | |
142 if (rp != null) return rp; | |
143 } | |
144 } | |
145 | |
146 List _compareSets(Set expected, actual, matcher, depth, location) { | |
147 if (actual is! Iterable) return ['is not Iterable', location]; | |
148 actual = actual.toSet(); | |
149 | |
150 for (var expectedElement in expected) { | |
151 if (actual.every((actualElement) => | |
152 matcher(expectedElement, actualElement, location, depth) != null)) { | |
153 return ['does not contain $expectedElement', location]; | |
154 } | |
155 } | |
156 | |
157 if (actual.length > expected.length) { | |
158 return ['larger than expected', location]; | |
159 } else if (actual.length < expected.length) { | |
160 return ['smaller than expected', location]; | |
161 } else { | |
162 return null; | |
163 } | |
164 } | |
165 | |
166 List _recursiveMatch(expected, actual, String location, int depth) { | |
167 // If the expected value is a matcher, try to match it. | |
168 if (expected is Matcher) { | |
169 var matchState = {}; | |
170 if (expected.matches(actual, matchState)) return null; | |
171 | |
172 var description = new StringDescription(); | |
173 expected.describe(description); | |
174 return ['does not match $description', location]; | |
175 } else { | |
176 // Otherwise, test for equality. | |
177 try { | |
178 if (expected == actual) return null; | |
179 } catch (e) { | |
180 // TODO(gram): Add a test for this case. | |
181 return ['== threw "$e"', location]; | |
182 } | |
183 } | |
184 | |
185 if (depth > _limit) return ['recursion depth limit exceeded', location]; | |
186 | |
187 // If _limit is 1 we can only recurse one level into object. | |
188 if (depth == 0 || _limit > 1) { | |
189 if (expected is Set) { | |
190 return _compareSets( | |
191 expected, actual, _recursiveMatch, depth + 1, location); | |
192 } else if (expected is Iterable) { | |
193 return _compareIterables( | |
194 expected, actual, _recursiveMatch, depth + 1, location); | |
195 } else if (expected is Map) { | |
196 if (actual is! Map) return ['expected a map', location]; | |
197 | |
198 var err = (expected.length == actual.length) | |
199 ? '' | |
200 : 'has different length and '; | |
201 for (var key in expected.keys) { | |
202 if (!actual.containsKey(key)) { | |
203 return ["${err}is missing map key '$key'", location]; | |
204 } | |
205 } | |
206 | |
207 for (var key in actual.keys) { | |
208 if (!expected.containsKey(key)) { | |
209 return ["${err}has extra map key '$key'", location]; | |
210 } | |
211 } | |
212 | |
213 for (var key in expected.keys) { | |
214 var rp = _recursiveMatch( | |
215 expected[key], actual[key], "${location}['${key}']", depth + 1); | |
216 if (rp != null) return rp; | |
217 } | |
218 | |
219 return null; | |
220 } | |
221 } | |
222 | |
223 var description = new StringDescription(); | |
224 | |
225 // If we have recursed, show the expected value too; if not, expect() will | |
226 // show it for us. | |
227 if (depth > 0) { | |
228 description | |
229 .add('was ') | |
230 .addDescriptionOf(actual) | |
231 .add(' instead of ') | |
232 .addDescriptionOf(expected); | |
233 return [description.toString(), location]; | |
234 } | |
235 | |
236 // We're not adding any value to the actual value. | |
237 return ["", location]; | |
238 } | |
239 | |
240 String _match(expected, actual, Map matchState) { | |
241 var rp = _recursiveMatch(expected, actual, '', 0); | |
242 if (rp == null) return null; | |
243 var reason; | |
244 if (rp[0].length > 0) { | |
245 if (rp[1].length > 0) { | |
246 reason = "${rp[0]} at location ${rp[1]}"; | |
247 } else { | |
248 reason = rp[0]; | |
249 } | |
250 } else { | |
251 reason = ''; | |
252 } | |
253 // Cache the failure reason in the matchState. | |
254 addStateInfo(matchState, {'reason': reason}); | |
255 return reason; | |
256 } | |
257 | |
258 bool matches(item, Map matchState) => | |
259 _match(_expected, item, matchState) == null; | |
260 | |
261 Description describe(Description description) => | |
262 description.addDescriptionOf(_expected); | |
263 | |
264 Description describeMismatch( | |
265 item, Description mismatchDescription, Map matchState, bool verbose) { | |
266 var reason = matchState['reason']; | |
267 // If we didn't get a good reason, that would normally be a | |
268 // simple 'is <value>' message. We only add that if the mismatch | |
269 // description is non empty (so we are supplementing the mismatch | |
270 // description). | |
271 if (reason.length == 0 && mismatchDescription.length > 0) { | |
272 mismatchDescription.add('is ').addDescriptionOf(item); | |
273 } else { | |
274 mismatchDescription.add(reason); | |
275 } | |
276 return mismatchDescription; | |
277 } | |
278 } | |
279 | |
280 /// A special equality matcher for strings. | |
281 class _StringEqualsMatcher extends Matcher { | |
282 final String _value; | |
283 | |
284 _StringEqualsMatcher(this._value); | |
285 | |
286 bool get showActualValue => true; | |
287 | |
288 bool matches(item, Map matchState) => _value == item; | |
289 | |
290 Description describe(Description description) => | |
291 description.addDescriptionOf(_value); | |
292 | |
293 Description describeMismatch( | |
294 item, Description mismatchDescription, Map matchState, bool verbose) { | |
295 if (item is! String) { | |
296 return mismatchDescription.addDescriptionOf(item).add('is not a string'); | |
297 } else { | |
298 var buff = new StringBuffer(); | |
299 buff.write('is different.'); | |
300 var escapedItem = escape(item); | |
301 var escapedValue = escape(_value); | |
302 int minLength = escapedItem.length < escapedValue.length | |
303 ? escapedItem.length | |
304 : escapedValue.length; | |
305 var start = 0; | |
306 for (; start < minLength; start++) { | |
307 if (escapedValue.codeUnitAt(start) != escapedItem.codeUnitAt(start)) { | |
308 break; | |
309 } | |
310 } | |
311 if (start == minLength) { | |
312 if (escapedValue.length < escapedItem.length) { | |
313 buff.write(' Both strings start the same, but the given value also' | |
314 ' has the following trailing characters: '); | |
315 _writeTrailing(buff, escapedItem, escapedValue.length); | |
316 } else { | |
317 buff.write(' Both strings start the same, but the given value is' | |
318 ' missing the following trailing characters: '); | |
319 _writeTrailing(buff, escapedValue, escapedItem.length); | |
320 } | |
321 } else { | |
322 buff.write('\nExpected: '); | |
323 _writeLeading(buff, escapedValue, start); | |
324 _writeTrailing(buff, escapedValue, start); | |
325 buff.write('\n Actual: '); | |
326 _writeLeading(buff, escapedItem, start); | |
327 _writeTrailing(buff, escapedItem, start); | |
328 buff.write('\n '); | |
329 for (int i = (start > 10 ? 14 : start); i > 0; i--) buff.write(' '); | |
330 buff.write('^\n Differ at offset $start'); | |
331 } | |
332 | |
333 return mismatchDescription.replace(buff.toString()); | |
334 } | |
335 } | |
336 | |
337 static void _writeLeading(StringBuffer buff, String s, int start) { | |
338 if (start > 10) { | |
339 buff.write('... '); | |
340 buff.write(s.substring(start - 10, start)); | |
341 } else { | |
342 buff.write(s.substring(0, start)); | |
343 } | |
344 } | |
345 | |
346 static void _writeTrailing(StringBuffer buff, String s, int start) { | |
347 if (start + 10 > s.length) { | |
348 buff.write(s.substring(start)); | |
349 } else { | |
350 buff.write(s.substring(start, start + 10)); | |
351 buff.write(' ...'); | |
352 } | |
353 } | |
354 } | |
355 | |
356 /// A matcher that matches any value. | |
357 const Matcher anything = const _IsAnything(); | |
358 | |
359 class _IsAnything extends Matcher { | |
360 const _IsAnything(); | |
361 bool matches(item, Map matchState) => true; | |
362 Description describe(Description description) => description.add('anything'); | |
363 } | |
364 | |
365 /// Returns a matcher that matches if an object is an instance | |
366 /// of [type] (or a subtype). | |
367 /// | |
368 /// As types are not first class objects in Dart we can only | |
369 /// approximate this test by using a generic wrapper class. | |
370 /// | |
371 /// For example, to test whether 'bar' is an instance of type | |
372 /// 'Foo', we would write: | |
373 /// | |
374 /// expect(bar, new isInstanceOf<Foo>()); | |
375 class isInstanceOf<T> extends Matcher { | |
376 const isInstanceOf(); | |
377 | |
378 bool matches(obj, Map matchState) => obj is T; | |
379 | |
380 Description describe(Description description) => | |
381 description.add('an instance of $T'); | |
382 } | |
383 | |
384 /// A matcher that matches a function call against no exception. | |
385 /// | |
386 /// The function will be called once. Any exceptions will be silently swallowed. | |
387 /// The value passed to expect() should be a reference to the function. | |
388 /// Note that the function cannot take arguments; to handle this | |
389 /// a wrapper will have to be created. | |
390 const Matcher returnsNormally = const _ReturnsNormally(); | |
391 | |
392 class _ReturnsNormally extends Matcher { | |
393 const _ReturnsNormally(); | |
394 | |
395 bool matches(f, Map matchState) { | |
396 try { | |
397 f(); | |
398 return true; | |
399 } catch (e, s) { | |
400 addStateInfo(matchState, {'exception': e, 'stack': s}); | |
401 return false; | |
402 } | |
403 } | |
404 | |
405 Description describe(Description description) => | |
406 description.add("return normally"); | |
407 | |
408 Description describeMismatch( | |
409 item, Description mismatchDescription, Map matchState, bool verbose) { | |
410 mismatchDescription.add('threw ').addDescriptionOf(matchState['exception']); | |
411 if (verbose) { | |
412 mismatchDescription.add(' at ').add(matchState['stack'].toString()); | |
413 } | |
414 return mismatchDescription; | |
415 } | |
416 } | |
417 | |
418 /* | |
419 * Matchers for different exception types. Ideally we should just be able to | |
420 * use something like: | |
421 * | |
422 * final Matcher throwsException = | |
423 * const _Throws(const isInstanceOf<Exception>()); | |
424 * | |
425 * Unfortunately instanceOf is not working with dart2js. | |
426 * | |
427 * Alternatively, if static functions could be used in const expressions, | |
428 * we could use: | |
429 * | |
430 * bool _isException(x) => x is Exception; | |
431 * final Matcher isException = const _Predicate(_isException, "Exception"); | |
432 * final Matcher throwsException = const _Throws(isException); | |
433 * | |
434 * But currently using static functions in const expressions is not supported. | |
435 * For now the only solution for all platforms seems to be separate classes | |
436 * for each exception type. | |
437 */ | |
438 | |
439 abstract class TypeMatcher extends Matcher { | |
440 final String _name; | |
441 const TypeMatcher(this._name); | |
442 Description describe(Description description) => description.add(_name); | |
443 } | |
444 | |
445 /// A matcher for Map types. | |
446 const Matcher isMap = const _IsMap(); | |
447 | |
448 class _IsMap extends TypeMatcher { | |
449 const _IsMap() : super("Map"); | |
450 bool matches(item, Map matchState) => item is Map; | |
451 } | |
452 | |
453 /// A matcher for List types. | |
454 const Matcher isList = const _IsList(); | |
455 | |
456 class _IsList extends TypeMatcher { | |
457 const _IsList() : super("List"); | |
458 bool matches(item, Map matchState) => item is List; | |
459 } | |
460 | |
461 /// Returns a matcher that matches if an object has a length property | |
462 /// that matches [matcher]. | |
463 Matcher hasLength(matcher) => new _HasLength(wrapMatcher(matcher)); | |
464 | |
465 class _HasLength extends Matcher { | |
466 final Matcher _matcher; | |
467 const _HasLength([Matcher matcher = null]) : this._matcher = matcher; | |
468 | |
469 bool matches(item, Map matchState) { | |
470 try { | |
471 // This is harmless code that will throw if no length property | |
472 // but subtle enough that an optimizer shouldn't strip it out. | |
473 if (item.length * item.length >= 0) { | |
474 return _matcher.matches(item.length, matchState); | |
475 } | |
476 } catch (e) {} | |
477 return false; | |
478 } | |
479 | |
480 Description describe(Description description) => | |
481 description.add('an object with length of ').addDescriptionOf(_matcher); | |
482 | |
483 Description describeMismatch( | |
484 item, Description mismatchDescription, Map matchState, bool verbose) { | |
485 try { | |
486 // We want to generate a different description if there is no length | |
487 // property; we use the same trick as in matches(). | |
488 if (item.length * item.length >= 0) { | |
489 return mismatchDescription | |
490 .add('has length of ') | |
491 .addDescriptionOf(item.length); | |
492 } | |
493 } catch (e) {} | |
494 return mismatchDescription.add('has no length property'); | |
495 } | |
496 } | |
497 | |
498 /// Returns a matcher that matches if the match argument contains the expected | |
499 /// value. | |
500 /// | |
501 /// For [String]s this means substring matching; | |
502 /// for [Map]s it means the map has the key, and for [Iterable]s | |
503 /// it means the iterable has a matching element. In the case of iterables, | |
504 /// [expected] can itself be a matcher. | |
505 Matcher contains(expected) => new _Contains(expected); | |
506 | |
507 class _Contains extends Matcher { | |
508 final _expected; | |
509 | |
510 const _Contains(this._expected); | |
511 | |
512 bool matches(item, Map matchState) { | |
513 if (item is String) { | |
514 return item.indexOf(_expected) >= 0; | |
515 } else if (item is Iterable) { | |
516 if (_expected is Matcher) { | |
517 return item.any((e) => _expected.matches(e, matchState)); | |
518 } else { | |
519 return item.contains(_expected); | |
520 } | |
521 } else if (item is Map) { | |
522 return item.containsKey(_expected); | |
523 } | |
524 return false; | |
525 } | |
526 | |
527 Description describe(Description description) => | |
528 description.add('contains ').addDescriptionOf(_expected); | |
529 | |
530 Description describeMismatch( | |
531 item, Description mismatchDescription, Map matchState, bool verbose) { | |
532 if (item is String || item is Iterable || item is Map) { | |
533 return super.describeMismatch( | |
534 item, mismatchDescription, matchState, verbose); | |
535 } else { | |
536 return mismatchDescription.add('is not a string, map or iterable'); | |
537 } | |
538 } | |
539 } | |
540 | |
541 /// Returns a matcher that matches if the match argument is in | |
542 /// the expected value. This is the converse of [contains]. | |
543 Matcher isIn(expected) => new _In(expected); | |
544 | |
545 class _In extends Matcher { | |
546 final _expected; | |
547 | |
548 const _In(this._expected); | |
549 | |
550 bool matches(item, Map matchState) { | |
551 if (_expected is String) { | |
552 return _expected.indexOf(item) >= 0; | |
553 } else if (_expected is Iterable) { | |
554 return _expected.any((e) => e == item); | |
555 } else if (_expected is Map) { | |
556 return _expected.containsKey(item); | |
557 } | |
558 return false; | |
559 } | |
560 | |
561 Description describe(Description description) => | |
562 description.add('is in ').addDescriptionOf(_expected); | |
563 } | |
564 | |
565 /// Returns a matcher that uses an arbitrary function that returns | |
566 /// true or false for the actual value. | |
567 /// | |
568 /// For example: | |
569 /// | |
570 /// expect(v, predicate((x) => ((x % 2) == 0), "is even")) | |
571 Matcher predicate(bool f(value), [String description = 'satisfies function']) => | |
572 new _Predicate(f, description); | |
573 | |
574 typedef bool _PredicateFunction(value); | |
575 | |
576 class _Predicate extends Matcher { | |
577 final _PredicateFunction _matcher; | |
578 final String _description; | |
579 | |
580 const _Predicate(this._matcher, this._description); | |
581 | |
582 bool matches(item, Map matchState) => _matcher(item); | |
583 | |
584 Description describe(Description description) => | |
585 description.add(_description); | |
586 } | |
587 | |
588 /// A useful utility class for implementing other matchers through inheritance. | |
589 /// Derived classes should call the base constructor with a feature name and | |
590 /// description, and an instance matcher, and should implement the | |
591 /// [featureValueOf] abstract method. | |
592 /// | |
593 /// The feature description will typically describe the item and the feature, | |
594 /// while the feature name will just name the feature. For example, we may | |
595 /// have a Widget class where each Widget has a price; we could make a | |
596 /// [CustomMatcher] that can make assertions about prices with: | |
597 /// | |
598 /// class HasPrice extends CustomMatcher { | |
599 /// const HasPrice(matcher) : | |
600 /// super("Widget with price that is", "price", matcher); | |
601 /// featureValueOf(actual) => actual.price; | |
602 /// } | |
603 /// | |
604 /// and then use this for example like: | |
605 /// | |
606 /// expect(inventoryItem, new HasPrice(greaterThan(0))); | |
607 class CustomMatcher extends Matcher { | |
608 final String _featureDescription; | |
609 final String _featureName; | |
610 final Matcher _matcher; | |
611 | |
612 CustomMatcher(this._featureDescription, this._featureName, matcher) | |
613 : this._matcher = wrapMatcher(matcher); | |
614 | |
615 /// Override this to extract the interesting feature. | |
616 featureValueOf(actual) => actual; | |
617 | |
618 bool matches(item, Map matchState) { | |
619 var f = featureValueOf(item); | |
620 if (_matcher.matches(f, matchState)) return true; | |
621 addStateInfo(matchState, {'feature': f}); | |
622 return false; | |
623 } | |
624 | |
625 Description describe(Description description) => | |
626 description.add(_featureDescription).add(' ').addDescriptionOf(_matcher); | |
627 | |
628 Description describeMismatch( | |
629 item, Description mismatchDescription, Map matchState, bool verbose) { | |
630 mismatchDescription | |
631 .add('has ') | |
632 .add(_featureName) | |
633 .add(' with value ') | |
634 .addDescriptionOf(matchState['feature']); | |
635 var innerDescription = new StringDescription(); | |
636 _matcher.describeMismatch( | |
637 matchState['feature'], innerDescription, matchState['state'], verbose); | |
638 if (innerDescription.length > 0) { | |
639 mismatchDescription.add(' which ').add(innerDescription.toString()); | |
640 } | |
641 return mismatchDescription; | |
642 } | |
643 } | |
OLD | NEW |