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

Side by Side Diff: third_party/dart-packages/matcher/matcher/src/core_matchers.dart

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

Powered by Google App Engine
This is Rietveld 408576698