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; | |
nweiz
2015/05/07 23:06:58
Namespace these library tags or dart2js will compl
kevmoo
2015/05/07 23:11:38
Done.
| |
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 int start; | |
306 for (start = 0; 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 /// The [name] parameter does nothing; it's deprecated and will be removed in | |
377 /// future version of [matcher]. | |
378 const isInstanceOf([@deprecated String name]); | |
379 | |
380 bool matches(obj, Map matchState) => obj is T; | |
381 | |
382 Description describe(Description description) => | |
383 description.add('an instance of $T'); | |
384 } | |
385 | |
386 /// A matcher that matches a function call against no exception. | |
387 /// | |
388 /// The function will be called once. Any exceptions will be silently swallowed. | |
389 /// The value passed to expect() should be a reference to the function. | |
390 /// Note that the function cannot take arguments; to handle this | |
391 /// a wrapper will have to be created. | |
392 const Matcher returnsNormally = const _ReturnsNormally(); | |
393 | |
394 class _ReturnsNormally extends Matcher { | |
395 const _ReturnsNormally(); | |
396 | |
397 bool matches(f, Map matchState) { | |
398 try { | |
399 f(); | |
400 return true; | |
401 } catch (e, s) { | |
402 addStateInfo(matchState, {'exception': e, 'stack': s}); | |
403 return false; | |
404 } | |
405 } | |
406 | |
407 Description describe(Description description) => | |
408 description.add("return normally"); | |
409 | |
410 Description describeMismatch( | |
411 item, Description mismatchDescription, Map matchState, bool verbose) { | |
412 mismatchDescription.add('threw ').addDescriptionOf(matchState['exception']); | |
413 if (verbose) { | |
414 mismatchDescription.add(' at ').add(matchState['stack'].toString()); | |
415 } | |
416 return mismatchDescription; | |
417 } | |
418 } | |
419 | |
420 /* | |
421 * Matchers for different exception types. Ideally we should just be able to | |
422 * use something like: | |
423 * | |
424 * final Matcher throwsException = | |
425 * const _Throws(const isInstanceOf<Exception>()); | |
426 * | |
427 * Unfortunately instanceOf is not working with dart2js. | |
428 * | |
429 * Alternatively, if static functions could be used in const expressions, | |
430 * we could use: | |
431 * | |
432 * bool _isException(x) => x is Exception; | |
433 * final Matcher isException = const _Predicate(_isException, "Exception"); | |
434 * final Matcher throwsException = const _Throws(isException); | |
435 * | |
436 * But currently using static functions in const expressions is not supported. | |
437 * For now the only solution for all platforms seems to be separate classes | |
438 * for each exception type. | |
439 */ | |
440 | |
441 abstract class TypeMatcher extends Matcher { | |
442 final String _name; | |
443 const TypeMatcher(this._name); | |
444 Description describe(Description description) => description.add(_name); | |
445 } | |
446 | |
447 /// A matcher for Map types. | |
448 const Matcher isMap = const _IsMap(); | |
449 | |
450 class _IsMap extends TypeMatcher { | |
451 const _IsMap() : super("Map"); | |
452 bool matches(item, Map matchState) => item is Map; | |
453 } | |
454 | |
455 /// A matcher for List types. | |
456 const Matcher isList = const _IsList(); | |
457 | |
458 class _IsList extends TypeMatcher { | |
459 const _IsList() : super("List"); | |
460 bool matches(item, Map matchState) => item is List; | |
461 } | |
462 | |
463 /// Returns a matcher that matches if an object has a length property | |
464 /// that matches [matcher]. | |
465 Matcher hasLength(matcher) => new _HasLength(wrapMatcher(matcher)); | |
466 | |
467 class _HasLength extends Matcher { | |
468 final Matcher _matcher; | |
469 const _HasLength([Matcher matcher = null]) : this._matcher = matcher; | |
470 | |
471 bool matches(item, Map matchState) { | |
472 try { | |
473 // This is harmless code that will throw if no length property | |
474 // but subtle enough that an optimizer shouldn't strip it out. | |
475 if (item.length * item.length >= 0) { | |
476 return _matcher.matches(item.length, matchState); | |
477 } | |
478 } catch (e) {} | |
479 return false; | |
480 } | |
481 | |
482 Description describe(Description description) => | |
483 description.add('an object with length of ').addDescriptionOf(_matcher); | |
484 | |
485 Description describeMismatch( | |
486 item, Description mismatchDescription, Map matchState, bool verbose) { | |
487 try { | |
488 // We want to generate a different description if there is no length | |
489 // property; we use the same trick as in matches(). | |
490 if (item.length * item.length >= 0) { | |
491 return mismatchDescription | |
492 .add('has length of ') | |
493 .addDescriptionOf(item.length); | |
494 } | |
495 } catch (e) {} | |
496 return mismatchDescription.add('has no length property'); | |
497 } | |
498 } | |
499 | |
500 /// Returns a matcher that matches if the match argument contains the expected | |
501 /// value. | |
502 /// | |
503 /// For [String]s this means substring matching; | |
504 /// for [Map]s it means the map has the key, and for [Iterable]s | |
505 /// it means the iterable has a matching element. In the case of iterables, | |
506 /// [expected] can itself be a matcher. | |
507 Matcher contains(expected) => new _Contains(expected); | |
508 | |
509 class _Contains extends Matcher { | |
510 final _expected; | |
511 | |
512 const _Contains(this._expected); | |
513 | |
514 bool matches(item, Map matchState) { | |
515 if (item is String) { | |
516 return item.indexOf(_expected) >= 0; | |
517 } else if (item is Iterable) { | |
518 if (_expected is Matcher) { | |
519 return item.any((e) => _expected.matches(e, matchState)); | |
520 } else { | |
521 return item.contains(_expected); | |
522 } | |
523 } else if (item is Map) { | |
524 return item.containsKey(_expected); | |
525 } | |
526 return false; | |
527 } | |
528 | |
529 Description describe(Description description) => | |
530 description.add('contains ').addDescriptionOf(_expected); | |
531 | |
532 Description describeMismatch( | |
533 item, Description mismatchDescription, Map matchState, bool verbose) { | |
534 if (item is String || item is Iterable || item is Map) { | |
535 return super.describeMismatch( | |
536 item, mismatchDescription, matchState, verbose); | |
537 } else { | |
538 return mismatchDescription.add('is not a string, map or iterable'); | |
539 } | |
540 } | |
541 } | |
542 | |
543 /// Returns a matcher that matches if the match argument is in | |
544 /// the expected value. This is the converse of [contains]. | |
545 Matcher isIn(expected) => new _In(expected); | |
546 | |
547 class _In extends Matcher { | |
548 final _expected; | |
549 | |
550 const _In(this._expected); | |
551 | |
552 bool matches(item, Map matchState) { | |
553 if (_expected is String) { | |
554 return _expected.indexOf(item) >= 0; | |
555 } else if (_expected is Iterable) { | |
556 return _expected.any((e) => e == item); | |
557 } else if (_expected is Map) { | |
558 return _expected.containsKey(item); | |
559 } | |
560 return false; | |
561 } | |
562 | |
563 Description describe(Description description) => | |
564 description.add('is in ').addDescriptionOf(_expected); | |
565 } | |
566 | |
567 /// Returns a matcher that uses an arbitrary function that returns | |
568 /// true or false for the actual value. | |
569 /// | |
570 /// For example: | |
571 /// | |
572 /// expect(v, predicate((x) => ((x % 2) == 0), "is even")) | |
573 Matcher predicate(bool f(value), [String description = 'satisfies function']) => | |
574 new _Predicate(f, description); | |
575 | |
576 typedef bool _PredicateFunction(value); | |
577 | |
578 class _Predicate extends Matcher { | |
579 final _PredicateFunction _matcher; | |
580 final String _description; | |
581 | |
582 const _Predicate(this._matcher, this._description); | |
583 | |
584 bool matches(item, Map matchState) => _matcher(item); | |
585 | |
586 Description describe(Description description) => | |
587 description.add(_description); | |
588 } | |
589 | |
590 /// A useful utility class for implementing other matchers through inheritance. | |
591 /// Derived classes should call the base constructor with a feature name and | |
592 /// description, and an instance matcher, and should implement the | |
593 /// [featureValueOf] abstract method. | |
594 /// | |
595 /// The feature description will typically describe the item and the feature, | |
596 /// while the feature name will just name the feature. For example, we may | |
597 /// have a Widget class where each Widget has a price; we could make a | |
598 /// [CustomMatcher] that can make assertions about prices with: | |
599 /// | |
600 /// class HasPrice extends CustomMatcher { | |
601 /// const HasPrice(matcher) : | |
602 /// super("Widget with price that is", "price", matcher); | |
603 /// featureValueOf(actual) => actual.price; | |
604 /// } | |
605 /// | |
606 /// and then use this for example like: | |
607 /// | |
608 /// expect(inventoryItem, new HasPrice(greaterThan(0))); | |
609 class CustomMatcher extends Matcher { | |
610 final String _featureDescription; | |
611 final String _featureName; | |
612 final Matcher _matcher; | |
613 | |
614 CustomMatcher(this._featureDescription, this._featureName, matcher) | |
615 : this._matcher = wrapMatcher(matcher); | |
616 | |
617 /// Override this to extract the interesting feature. | |
618 featureValueOf(actual) => actual; | |
619 | |
620 bool matches(item, Map matchState) { | |
621 var f = featureValueOf(item); | |
622 if (_matcher.matches(f, matchState)) return true; | |
623 addStateInfo(matchState, {'feature': f}); | |
624 return false; | |
625 } | |
626 | |
627 Description describe(Description description) => | |
628 description.add(_featureDescription).add(' ').addDescriptionOf(_matcher); | |
629 | |
630 Description describeMismatch( | |
631 item, Description mismatchDescription, Map matchState, bool verbose) { | |
632 mismatchDescription | |
633 .add('has ') | |
634 .add(_featureName) | |
635 .add(' with value ') | |
636 .addDescriptionOf(matchState['feature']); | |
637 var innerDescription = new StringDescription(); | |
638 _matcher.describeMismatch( | |
639 matchState['feature'], innerDescription, matchState['state'], verbose); | |
640 if (innerDescription.length > 0) { | |
641 mismatchDescription.add(' which ').add(innerDescription.toString()); | |
642 } | |
643 return mismatchDescription; | |
644 } | |
645 } | |
OLD | NEW |