Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(502)

Side by Side Diff: pkg/matcher/lib/src/core_matchers.dart

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

Powered by Google App Engine
This is Rietveld 408576698