matcher library
The matcher library provides a 3rd generation assertion mechanism, drawing
inspiration from Hamcrest
and Ladislav Thon's dart-matchers
library.
See Hamcrest
http://en.wikipedia.org/wiki/Hamcrest
[Hamcrest] http://code.google.com/p/hamcrest/ [dart-matchers] https://github.com/Ladicek/dart-matchers
Properties
const isArgumentError #
isArgumentError = const _ArgumentError()
const isException #
isException = const _Exception()
const isFormatException #
isFormatException = const _FormatException()
const isIllegalJSRegExpException #
isIllegalJSRegExpException = const _IllegalJSRegExpException()
const isList #
isList = const _IsList()
const isMap #
isMap = const _IsMap()
const Matcher isNegative #
isNegative = const _OrderingComparison(0, false, true, false, 'a negative value', false)
const Matcher isNonNegative #
isNonNegative = const _OrderingComparison(0, true, false, true, 'a non-negative value', false)
const Matcher isNonPositive #
isNonPositive = const _OrderingComparison(0, true, true, false, 'a non-positive value', false)
const Matcher isNonZero #
isNonZero = const _OrderingComparison(0, false, true, true, 'a value not equal to')
const isNoSuchMethodError #
isNoSuchMethodError = const _NoSuchMethodError()
const Matcher isPositive #
isPositive = const _OrderingComparison(0, false, false, true, 'a positive value', false)
const isRangeError #
isRangeError = const _RangeError()
const isStateError #
isStateError = const _StateError()
const isUnimplementedError #
isUnimplementedError = const _UnimplementedError()
const isUnsupportedError #
isUnsupportedError = const _UnsupportedError()
const Matcher isZero #
isZero = const _OrderingComparison(0, true, false, false, 'a value equal to')
const Matcher throwsIllegalJSRegExpException #
throwsIllegalJSRegExpException = const Throws(isIllegalJSRegExpException)
const Matcher throwsUnimplementedError #
throwsUnimplementedError = const Throws(isUnimplementedError)
Function wrapAsync #
wrapAsync = (f) => f
Functions
Matcher matches(re) #
Returns a matcher that matches if the match argument is a string and matches the regular expression given by re. re can be a RegExp instance or a string; in the latter case it will be used to create a RegExp instance.
Matcher matches(re) => new _MatchesRegExp(re);
Matcher stringContainsInOrder(substrings) #
Returns a matcher that matches if the match argument is a string and contains a given list of substrings in relative order.
For example, stringContainsInOrder(["a", "e", "i", "o", "u"])
will match
"abcdefghijklmnopqrstuvwxyz".
Matcher stringContainsInOrder(substrings) => new _StringContainsInOrder(substrings);
Matcher endsWith(String suffixString) #
Returns a matcher that matches if the match argument is a string and ends with suffixString.
Matcher endsWith(String suffixString) => new _StringEndsWith(suffixString);
Matcher startsWith(String prefixString) #
Returns a matcher that matches if the match argument is a string and starts with prefixString.
Matcher startsWith(String prefixString) => new _StringStartsWith(prefixString);
String collapseWhitespace(_string) #
Utility function to collapse whitespace runs to single spaces and strip leading/trailing whitespace.
String collapseWhitespace(_string) { bool isWhitespace(String ch) => (' \n\r\t'.indexOf(ch) >= 0); StringBuffer result = new StringBuffer(); bool skipSpace = true; for (var i = 0; i < _string.length; i++) { var character = _string[i]; if (isWhitespace(character)) { if (!skipSpace) { result.add(' '); skipSpace = true; } } else { result.add(character); skipSpace = false; } } return result.toString().trim(); }
Matcher equalsIgnoringWhitespace(_string) #
Returns a matcher which matches if the match argument is a string and
is equal to value
when compared with all runs of whitespace
collapsed to single spaces and leading and trailing whitespace removed.
For example, equalsIgnoringCase("hello world")
will match
"hello world", " hello world" and "hello world ".
Matcher equalsIgnoringWhitespace(_string) => new _IsEqualIgnoringWhitespace(_string);
Matcher equalsIgnoringCase(String value) #
Returns a matcher which matches if the match argument is a string and is equal to value when compared case-insensitively.
Matcher equalsIgnoringCase(String value) => new _IsEqualIgnoringCase(value);
Matcher anyOf(arg0, [arg1 = null, arg2 = null, arg3 = null, arg4 = null, arg5 = null, arg6 = null]) #
Matches if any of the given matchers evaluate to true. The arguments can be a set of matchers as separate parameters (up to 7), or a List of matchers.
The matchers are evaluated from left to right using short-circuit evaluation, so evaluation stops as soon as a matcher returns true.
Any argument that is not a matcher is implicitly wrapped in a Matcher to check for equality.
Matcher anyOf(arg0, [arg1 = null, arg2 = null, arg3 = null, arg4 = null, arg5 = null, arg6 = null]) { if (arg0 is List) { expect(arg1, isNull); expect(arg2, isNull); expect(arg3, isNull); expect(arg4, isNull); expect(arg5, isNull); expect(arg6, isNull); for (int i = 0; i < arg0.length; i++) { arg0[i] = wrapMatcher(arg0[i]); } return new _AnyOf(arg0); } else { List matchers = new List(); if (arg0 != null) { matchers.add(wrapMatcher(arg0)); } if (arg1 != null) { matchers.add(wrapMatcher(arg1)); } if (arg2 != null) { matchers.add(wrapMatcher(arg2)); } if (arg3 != null) { matchers.add(wrapMatcher(arg3)); } if (arg4 != null) { matchers.add(wrapMatcher(arg4)); } if (arg5 != null) { matchers.add(wrapMatcher(arg5)); } if (arg6 != null) { matchers.add(wrapMatcher(arg6)); } return new _AnyOf(matchers); } }
Matcher allOf(arg0, [arg1 = null, arg2 = null, arg3 = null, arg4 = null, arg5 = null, arg6 = null]) #
This returns a matcher that matches if all of the matchers passed as arguments (up to 7) match. Instead of passing the matchers separately they can be passed as a single List argument. Any argument that is not a matcher is implicitly wrapped in a Matcher to check for equality.
Matcher allOf(arg0, [arg1 = null, arg2 = null, arg3 = null, arg4 = null, arg5 = null, arg6 = null]) { if (arg0 is List) { expect(arg1, isNull); expect(arg2, isNull); expect(arg3, isNull); expect(arg4, isNull); expect(arg5, isNull); expect(arg6, isNull); for (int i = 0; i < arg0.length; i++) { arg0[i] = wrapMatcher(arg0[i]); } return new _AllOf(arg0); } else { List matchers = new List(); if (arg0 != null) { matchers.add(wrapMatcher(arg0)); } if (arg1 != null) { matchers.add(wrapMatcher(arg1)); } if (arg2 != null) { matchers.add(wrapMatcher(arg2)); } if (arg3 != null) { matchers.add(wrapMatcher(arg3)); } if (arg4 != null) { matchers.add(wrapMatcher(arg4)); } if (arg5 != null) { matchers.add(wrapMatcher(arg5)); } if (arg6 != null) { matchers.add(wrapMatcher(arg6)); } return new _AllOf(matchers); } }
Matcher isNot(matcher) #
This returns a matcher that inverts matcher to its logical negation.
Matcher isNot(matcher) => new _IsNot(wrapMatcher(matcher));
Matcher inClosedOpenRange(low, high) #
Returns a matcher which matches if the match argument is greater than or equal to a low and less than high.
Matcher inClosedOpenRange(low, high) => new _InRange(low, high, true, false);
Matcher inOpenClosedRange(low, high) #
Returns a matcher which matches if the match argument is greater than low and less than or equal to high.
Matcher inOpenClosedRange(low, high) => new _InRange(low, high, false, true);
Matcher inExclusiveRange(low, high) #
Returns a matcher which matches if the match argument is greater than low and less than high.
Matcher inExclusiveRange(low, high) => new _InRange(low, high, false, false);
Matcher inInclusiveRange(low, high) #
Returns a matcher which matches if the match argument is greater than or equal to low and less than or equal to high.
Matcher inInclusiveRange(low, high) => new _InRange(low, high, true, true);
Matcher closeTo(value, delta) #
Returns a matcher which matches if the match argument is within delta of some value; i.e. if the match argument is greater than than or equal value- delta and less than or equal to value+ delta.
Matcher closeTo(value, delta) => new _IsCloseTo(value, delta);
Matcher lessThanOrEqualTo(value) #
Returns a matcher which matches if the match argument is less than or equal to the given value.
Matcher lessThanOrEqualTo(value) => new _OrderingComparison(value, true, true, false, 'a value less than or equal to');
Matcher lessThan(value) #
Returns a matcher which matches if the match argument is less than the given value.
Matcher lessThan(value) => new _OrderingComparison(value, false, true, false, 'a value less than');
Matcher greaterThanOrEqualTo(value) #
Returns a matcher which matches if the match argument is greater than or equal to the given value.
Matcher greaterThanOrEqualTo(value) => new _OrderingComparison(value, true, false, true, 'a value greater than or equal to');
Matcher greaterThan(value) #
Returns a matcher which matches if the match argument is greater than the given value.
Matcher greaterThan(value) => new _OrderingComparison(value, false, false, true, 'a value greater than');
Matcher containsPair(key, value) #
Returns a matcher which matches maps containing the key-value pair with key => value.
Matcher containsPair(key, value) => new _ContainsMapping(key, wrapMatcher(value));
Matcher containsValue(value) #
Returns a matcher which matches maps containing the given value.
Matcher containsValue(value) => new _ContainsValue(value);
Matcher completion(matcher) #
Matches a Future
that completes succesfully with a value that matches
matcher. Note that this creates an asynchronous expectation. The call to
expect()
that includes this will return immediately and execution will
continue. Later, when the future completes, the actual expectation will run.
To test that a Future completes with an exception, you can use throws and throwsA.
Matcher completion(matcher) => new _Completes(wrapMatcher(matcher));
ErrorFormatter configureExpectFormatter([ErrorFormatter formatter = null]) #
Changes or resets to default the failure message formatter for expect(). formatter is a reference to the new formatter; if this is omitted or null then the failure formatter is reset to the default. The new formatter is returned; this allows custom expect handlers to easily get a reference to the default formatter.
ErrorFormatter configureExpectFormatter([ErrorFormatter formatter = null]) { if (formatter == null) { formatter = _defaultErrorFormatter; } return _assertErrorFormatter = formatter; }
FailureHandler getOrCreateExpectFailureHandler() #
FailureHandler getOrCreateExpectFailureHandler() { if (_assertFailureHandler == null) { configureExpectFailureHandler(); } return _assertFailureHandler; }
void configureExpectFailureHandler([FailureHandler handler = null]) #
Changes or resets to the default the failure handler for expect()
handler is a reference to the new handler; if this is omitted
or null then the failure handler is reset to the default, which
throws ExpectExceptions
on expect assertion failures.
void configureExpectFailureHandler([FailureHandler handler = null]) { if (handler == null) { handler = new DefaultFailureHandler(); } _assertFailureHandler = handler; }
Matcher wrapMatcher(x) #
Takes an argument and returns an equivalent matcher. If the argument is already a matcher this does nothing, else if the argument is a function, it generates a predicate function matcher, else it generates an equals matcher.
Matcher wrapMatcher(x) { if (x is Matcher) { return x; } else if (x is Function) { return predicate(x); } else { return equals(x); } }
void expect(actual, matcher, {String reason, FailureHandler failureHandler, bool verbose: false}) #
This is the main assertion function. It asserts that actual matches the matcher. reason is optional and is typically not supplied, as a reason is generated from the matcher; if reason is included it is appended to the reason generated by the matcher.
matcher can be a value in which case it will be wrapped in an equals matcher.
If the assertion fails, then the default behavior is to throw an
ExpectException
, but this behavior can be changed by calling
configureExpectFailureHandler and providing an alternative handler that
implements the IFailureHandler
interface. It is also possible to
pass a
failureHandler to expect as a final parameter for fine-
grained control.
In some cases extra diagnostic info can be produced on failure (for example, stack traces on mismatched exceptions). To enable these, verbose should be specified as true;
void expect(actual, matcher, {String reason, FailureHandler failureHandler, bool verbose : false}) { matcher = wrapMatcher(matcher); bool doesMatch; var matchState = new MatchState(); try { doesMatch = matcher.matches(actual, matchState); } catch (e, trace) { doesMatch = false; if (reason == null) { reason = '${(e is String) ? e : e.toString()} at $trace'; } } if (!doesMatch) { if (failureHandler == null) { failureHandler = getOrCreateExpectFailureHandler(); } failureHandler.failMatch(actual, matcher, reason, matchState, verbose); } }
Matcher predicate(Function f, [description = 'satisfies function']) #
Returns a matcher that uses an arbitrary function that returns true or false for the actual value. For example:
expect(v, predicate((x) => ((x % 2) == 0), "is even"))
Matcher predicate(Function f, [description ='satisfies function']) => new _Predicate(f, description);
Matcher isIn(expected) #
Returns a matcher that matches if the match argument is in the expected value. This is the converse of contains.
Matcher isIn(expected) => new _In(expected);
Matcher contains(expected) #
Returns a matcher that matches if the match argument contains
the expected value. For String
s this means substring matching;
for Map
s it means the map has the key, and for Iterable
s
(including Collection
s) it means the iterable has a matching
element. In the case of iterables,
expected can itself be a
matcher.
Matcher contains(expected) => new _Contains(expected);
Matcher hasLength(matcher) #
Returns a matcher that matches if an object has a length property that matches matcher.
Matcher hasLength(matcher) => new _HasLength(wrapMatcher(matcher));
Matcher throwsA(matcher) #
This can be used to match two kinds of objects:
-
A
Function
that throws an exception when called. The function cannot take any arguments. If you want to test that a function expecting arguments throws, wrap it in another zero-argument function that calls the one you want to test. -
A
Future
that completes with an exception. Note that this creates an asynchronous expectation. The call toexpect()
that includes this will return immediately and execution will continue. Later, when the future completes, the actual expectation will run.
In both cases, when an exception is thrown, this will test that the exception
object matches
matcher. If
matcher is not an instance of Matcher, it
will implicitly be treated as equals(matcher)
.
Matcher throwsA(matcher) => new Throws(wrapMatcher(matcher));
Matcher equals(expected, [limit = 100]) #
Returns a matcher that does a deep recursive match. This only works with scalars, Maps and Iterables. To handle cyclic structures a recursion depth limit can be provided. The default limit is 100.
Matcher equals(expected, [limit=100]) => new _DeepMatcher(expected, limit);
Matcher same(expected) #
Returns a matches that matches if the value is the same instance as object.
Matcher same(expected) => new _IsSameAs(expected);
Matcher unorderedEquals(Iterable expected) #
Returns a matcher which matches Iterable
s that have the same
length and the same elements as
expected, but not necessarily in
the same order. Note that this is O(n^2) so should only be used on
small objects.
Matcher unorderedEquals(Iterable expected) => new _UnorderedEquals(expected);
Matcher orderedEquals(Iterable expected) #
Returns a matcher which matches Iterable
s that have the same
length and the same elements as
expected, and in the same order.
This is equivalent to equals but does not recurse.
Matcher orderedEquals(Iterable expected) => new _OrderedEquals(expected);