refactor with unittest
R=nweiz@google.com
Review URL: https://codereview.chromium.org//867133002
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e9e16d..1f71fae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,16 @@
+## 0.12.0
+
+* Moved a number of members to the
+ [`unittest`](https://pub.dartlang.org/packages/unittest) package.
+ * `TestFailure`, `ErrorFormatter`, `expect`, `fail`, and 'wrapAsync'.
+ * `completes`, `completion`, `throws`, and `throwsA` Matchers.
+ * The `Throws` class.
+ * All of the `throws...Error` Matchers.
+
+* Removed `FailureHandler`, `DefaultFailureHandler`,
+ `configureExpectFailureHandler`, and `getOrCreateExpectFailureHandler`.
+ Now that `expect` is in the `unittest` package, these are no longer needed.
+
## 0.11.4+1
* Correctly match and print `String`s containing characters that must be
diff --git a/lib/matcher.dart b/lib/matcher.dart
index c7790c9..c719fb1 100644
--- a/lib/matcher.dart
+++ b/lib/matcher.dart
@@ -8,15 +8,10 @@
export 'src/core_matchers.dart';
export 'src/description.dart';
export 'src/error_matchers.dart';
-export 'src/expect.dart';
-export 'src/future_matchers.dart';
export 'src/interfaces.dart';
export 'src/iterable_matchers.dart';
export 'src/map_matchers.dart';
export 'src/numeric_matchers.dart';
export 'src/operator_matchers.dart';
-export 'src/prints_matcher.dart';
export 'src/string_matchers.dart';
-export 'src/throws_matcher.dart';
-export 'src/throws_matchers.dart';
export 'src/util.dart';
diff --git a/lib/src/expect.dart b/lib/src/expect.dart
deleted file mode 100644
index 08eb68e..0000000
--- a/lib/src/expect.dart
+++ /dev/null
@@ -1,177 +0,0 @@
-// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library matcher.expect;
-
-import 'core_matchers.dart';
-import 'description.dart';
-import 'interfaces.dart';
-import 'util.dart';
-
-/// The objects thrown by the default failure handler.
-class TestFailure extends Error {
- final String message;
-
- TestFailure(this.message);
-
- String toString() => message;
-}
-
-/// Failed matches are reported using a default IFailureHandler.
-/// The default implementation simply throws [TestFailure]s;
-/// this can be replaced by some other implementation of
-/// IFailureHandler by calling configureExpectHandler.
-abstract class FailureHandler {
- /// This handles failures given a textual decription
- void fail(String reason);
-
- /// This handles failures given the actual [value], the [matcher]
- /// the [reason] (argument from [expect]), some additonal [matchState]
- /// generated by the [matcher], and a verbose flag which controls in
- /// some cases how much [matchState] information is used. It will use
- /// these to create a detailed error message (typically by calling
- /// an [ErrorFormatter]) and then call [fail] with this message.
- void failMatch(
- actual, Matcher matcher, String reason, Map matchState, bool verbose);
-}
-
-/// The ErrorFormatter type is used for functions that
-/// can be used to build up error reports upon [expect] failures.
-/// There is one built-in implementation ([defaultErrorFormatter])
-/// which is used by the default failure handler. If the failure handler
-/// is replaced it may be desirable to replace the [stringDescription]
-/// error formatter with another.
-typedef String ErrorFormatter(
- actual, Matcher matcher, String reason, Map matchState, bool verbose);
-
-/// This Function is used by certain Matchers to catch certain exceptions.
-///
-/// Some matchers, like those for Futures and exception testing,
-/// can fail in asynchronous sections, and throw exceptions.
-/// A user of this library will typically want to catch and handle
-/// such exceptions. The [wrapAsync] property is a function that
-/// can wrap callbacks used by these Matchers so that they can be
-/// used safely. For example, the unittest library will set this
-/// to be `expectAsync`. By default this is an identity function.
-Function wrapAsync = (Function f, [id]) => f;
-
-/// Assert that [actual] matches [matcher].
-///
-/// This is the main assertion function. [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 a
-/// [TestFailure], 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 = {};
- 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);
- }
-}
-
-void fail(String message, {FailureHandler failureHandler}) {
- if (failureHandler == null) {
- failureHandler = getOrCreateExpectFailureHandler();
- }
- failureHandler.fail(message);
-}
-
-// The handler for failed asserts.
-FailureHandler _assertFailureHandler = null;
-
-// The default failure handler that throws [TestFailure]s.
-class DefaultFailureHandler implements FailureHandler {
- DefaultFailureHandler() {
- if (_assertErrorFormatter == null) {
- _assertErrorFormatter = _defaultErrorFormatter;
- }
- }
- void fail(String reason) {
- throw new TestFailure(reason);
- }
- void failMatch(
- actual, Matcher matcher, String reason, Map matchState, bool verbose) {
- fail(_assertErrorFormatter(actual, matcher, reason, matchState, verbose));
- }
-}
-
-/// Changes the default 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 [TestFailure]s on [expect] assertion failures.
-void configureExpectFailureHandler([FailureHandler handler = null]) {
- if (handler == null) {
- handler = new DefaultFailureHandler();
- }
- _assertFailureHandler = handler;
-}
-
-FailureHandler getOrCreateExpectFailureHandler() {
- if (_assertFailureHandler == null) {
- configureExpectFailureHandler();
- }
- return _assertFailureHandler;
-}
-
-// The error message formatter for failed asserts.
-ErrorFormatter _assertErrorFormatter = null;
-
-// The default error formatter implementation.
-String _defaultErrorFormatter(
- actual, Matcher matcher, String reason, Map matchState, bool verbose) {
- var description = new StringDescription();
- description.add('Expected: ').addDescriptionOf(matcher).add('\n');
- description.add(' Actual: ').addDescriptionOf(actual).add('\n');
-
- var mismatchDescription = new StringDescription();
- matcher.describeMismatch(actual, mismatchDescription, matchState, verbose);
-
- if (mismatchDescription.length > 0) {
- description.add(' Which: ${mismatchDescription}\n');
- }
- if (reason != null) {
- description.add(reason).add('\n');
- }
- return description.toString();
-}
-
-/// Changes 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;
-}
diff --git a/lib/src/future_matchers.dart b/lib/src/future_matchers.dart
deleted file mode 100644
index bdbd62f..0000000
--- a/lib/src/future_matchers.dart
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library matcher.future_matchers;
-
-import 'dart:async';
-
-import 'expect.dart';
-import 'interfaces.dart';
-import 'util.dart';
-
-/// Matches a [Future] that completes successfully with a value.
-///
-/// 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].
-final Matcher completes = const _Completes(null, '');
-
-/// 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].
-///
-/// [id] is an optional tag that can be used to identify the completion matcher
-/// in error messages.
-Matcher completion(matcher, [String id = '']) =>
- new _Completes(wrapMatcher(matcher), id);
-
-class _Completes extends Matcher {
- final Matcher _matcher;
- final String _id;
-
- const _Completes(this._matcher, this._id);
-
- bool matches(item, Map matchState) {
- if (item is! Future) return false;
- var done = wrapAsync((fn) => fn(), _id);
-
- item.then((value) {
- done(() {
- if (_matcher != null) expect(value, _matcher);
- });
- }, onError: (error, trace) {
- var id = _id == '' ? '' : '${_id} ';
- var reason = 'Expected future ${id}to complete successfully, '
- 'but it failed with ${error}';
- if (trace != null) {
- var stackTrace = trace.toString();
- stackTrace = ' ${stackTrace.replaceAll('\n', '\n ')}';
- reason = '$reason\nStack trace:\n$stackTrace';
- }
- done(() => fail(reason));
- });
-
- return true;
- }
-
- Description describe(Description description) {
- if (_matcher == null) {
- description.add('completes successfully');
- } else {
- description.add('completes to a value that ').addDescriptionOf(_matcher);
- }
- return description;
- }
-}
diff --git a/lib/src/prints_matcher.dart b/lib/src/prints_matcher.dart
deleted file mode 100644
index be6abe3..0000000
--- a/lib/src/prints_matcher.dart
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library matcher.prints_matcher;
-
-import 'dart:async';
-
-import 'description.dart';
-import 'expect.dart';
-import 'interfaces.dart';
-import 'future_matchers.dart';
-import 'util.dart';
-
-/// Matches a [Function] that prints text that matches [matcher].
-///
-/// [matcher] may be a String or a [Matcher].
-///
-/// If the function this runs against returns a [Future], all text printed by
-/// the function (using [Zone] scoping) until that Future completes is matched.
-///
-/// This only tracks text printed using the [print] function.
-Matcher prints(matcher) => new _Prints(wrapMatcher(matcher));
-
-class _Prints extends Matcher {
- final Matcher _matcher;
-
- _Prints(this._matcher);
-
- bool matches(item, Map matchState) {
- if (item is! Function) return false;
-
- var buffer = new StringBuffer();
- var result = runZoned(item,
- zoneSpecification: new ZoneSpecification(print: (_, __, ____, line) {
- buffer.writeln(line);
- }));
-
- if (result is! Future) {
- var actual = buffer.toString();
- matchState['prints.actual'] = actual;
- return _matcher.matches(actual, matchState);
- }
-
- return completes.matches(result.then(wrapAsync((_) {
- expect(buffer.toString(), _matcher);
- }, 'prints')), matchState);
- }
-
- Description describe(Description description) =>
- description.add('prints ').addDescriptionOf(_matcher);
-
- Description describeMismatch(
- item, Description description, Map matchState, bool verbose) {
- var actual = matchState.remove('prints.actual');
- if (actual == null) return description;
- if (actual.isEmpty) return description.add("printed nothing.");
-
- description.add('printed ').addDescriptionOf(actual);
-
- // Create a new description for the matcher because at least
- // [_StringEqualsMatcher] replaces the previous contents of the description.
- var innerMismatch = _matcher
- .describeMismatch(actual, new StringDescription(), matchState, verbose)
- .toString();
-
- if (innerMismatch.isNotEmpty) {
- description.add('\n Which: ').add(innerMismatch.toString());
- }
-
- return description;
- }
-}
diff --git a/lib/src/throws_matcher.dart b/lib/src/throws_matcher.dart
deleted file mode 100644
index 461c585..0000000
--- a/lib/src/throws_matcher.dart
+++ /dev/null
@@ -1,112 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library matcher.throws_matcher;
-
-import 'dart:async';
-
-import 'expect.dart';
-import 'interfaces.dart';
-import 'util.dart';
-
-/// 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 to `expect()` that includes this will
-/// return immediately and execution will continue. Later, when the future
-/// completes, the actual expectation will run.
-const Matcher throws = const Throws();
-
-/// 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 to `expect()` 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));
-
-class Throws extends Matcher {
- final Matcher _matcher;
-
- const Throws([Matcher matcher]) : this._matcher = matcher;
-
- bool matches(item, Map matchState) {
- if (item is! Function && item is! Future) return false;
- if (item is Future) {
- var done = wrapAsync((fn) => fn());
-
- // Queue up an asynchronous expectation that validates when the future
- // completes.
- item.then((value) {
- done(() {
- fail("Expected future to fail, but succeeded with '$value'.");
- });
- }, onError: (error, trace) {
- done(() {
- if (_matcher == null) return;
- var reason;
- if (trace != null) {
- var stackTrace = trace.toString();
- stackTrace = " ${stackTrace.replaceAll("\n", "\n ")}";
- reason = "Actual exception trace:\n$stackTrace";
- }
- expect(error, _matcher, reason: reason);
- });
- });
- // It hasn't failed yet.
- return true;
- }
-
- try {
- item();
- return false;
- } catch (e, s) {
- if (_matcher == null || _matcher.matches(e, matchState)) {
- return true;
- } else {
- addStateInfo(matchState, {'exception': e, 'stack': s});
- return false;
- }
- }
- }
-
- Description describe(Description description) {
- if (_matcher == null) {
- return description.add("throws");
- } else {
- return description.add('throws ').addDescriptionOf(_matcher);
- }
- }
-
- Description describeMismatch(
- item, Description mismatchDescription, Map matchState, bool verbose) {
- if (item is! Function && item is! Future) {
- return mismatchDescription.add('is not a Function or Future');
- } else if (_matcher == null || matchState['exception'] == null) {
- return mismatchDescription.add('did not throw');
- } else {
- mismatchDescription
- .add('threw ')
- .addDescriptionOf(matchState['exception']);
- if (verbose) {
- mismatchDescription.add(' at ').add(matchState['stack'].toString());
- }
- return mismatchDescription;
- }
- }
-}
diff --git a/lib/src/throws_matchers.dart b/lib/src/throws_matchers.dart
deleted file mode 100644
index 35dfb39..0000000
--- a/lib/src/throws_matchers.dart
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library matcher.throws_matchers;
-
-import 'error_matchers.dart';
-import 'interfaces.dart';
-import 'throws_matcher.dart';
-
-/// A matcher for functions that throw ArgumentError.
-const Matcher throwsArgumentError = const Throws(isArgumentError);
-
-/// A matcher for functions that throw ConcurrentModificationError.
-const Matcher throwsConcurrentModificationError =
- const Throws(isConcurrentModificationError);
-
-/// A matcher for functions that throw CyclicInitializationError.
-const Matcher throwsCyclicInitializationError =
- const Throws(isCyclicInitializationError);
-
-/// A matcher for functions that throw Exception.
-const Matcher throwsException = const Throws(isException);
-
-/// A matcher for functions that throw FormatException.
-const Matcher throwsFormatException = const Throws(isFormatException);
-
-/// A matcher for functions that throw NoSuchMethodError.
-const Matcher throwsNoSuchMethodError = const Throws(isNoSuchMethodError);
-
-/// A matcher for functions that throw NullThrownError.
-const Matcher throwsNullThrownError = const Throws(isNullThrownError);
-
-/// A matcher for functions that throw RangeError.
-const Matcher throwsRangeError = const Throws(isRangeError);
-
-/// A matcher for functions that throw StateError.
-const Matcher throwsStateError = const Throws(isStateError);
-
-/// A matcher for functions that throw Exception.
-const Matcher throwsUnimplementedError = const Throws(isUnimplementedError);
-
-/// A matcher for functions that throw UnsupportedError.
-const Matcher throwsUnsupportedError = const Throws(isUnsupportedError);
diff --git a/pubspec.yaml b/pubspec.yaml
index 3988f16..aabf395 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,9 +1,14 @@
name: matcher
-version: 0.11.4+1
+version: 0.12.0-dev
author: Dart Team <misc@dartlang.org>
description: Support for specifying test expectations
homepage: https://github.com/dart-lang/matcher
environment:
sdk: '>=1.0.0 <2.0.0'
dev_dependencies:
- unittest: '>=0.10.0 <0.12.0'
+ # Using a git dependency to align with the unreleased version of unittest
+ # that is compatible with matcher 0.12.0
+ unittest:
+ git:
+ ref: master
+ url: https://github.com/dart-lang/unittest
diff --git a/test/core_matchers_test.dart b/test/core_matchers_test.dart
index 7024894..3213455 100644
--- a/test/core_matchers_test.dart
+++ b/test/core_matchers_test.dart
@@ -10,8 +10,6 @@
import 'test_utils.dart';
void main() {
- initUtils();
-
test('isTrue', () {
shouldPass(true, isTrue);
shouldFail(false, isTrue, "Expected: true Actual: <false>");
@@ -117,10 +115,10 @@
shouldPass(a, hasLength(0));
shouldPass(b, hasLength(0));
shouldPass('a', hasLength(1));
- shouldFail(0, hasLength(0), new PrefixMatcher(
+ shouldFail(0, hasLength(0),
"Expected: an object with length of <0> "
"Actual: <0> "
- "Which: has no length property"));
+ "Which: has no length property");
b.add(0);
shouldPass(b, hasLength(1));
diff --git a/test/future_matchers_test.dart b/test/future_matchers_test.dart
deleted file mode 100644
index 4e21ea2..0000000
--- a/test/future_matchers_test.dart
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library matcher.future_matchers_test;
-
-import 'dart:async';
-
-import 'package:matcher/matcher.dart';
-import 'package:unittest/unittest.dart' show test, group;
-
-import 'test_utils.dart';
-
-void main() {
- initUtils();
-
- test('completes - unexpected error', () {
- var completer = new Completer();
- completer.completeError('X');
- shouldFail(completer.future, completes, contains(
- 'Expected future to complete successfully, '
- 'but it failed with X'), isAsync: true);
- });
-
- test('completes - successfully', () {
- var completer = new Completer();
- completer.complete('1');
- shouldPass(completer.future, completes, isAsync: true);
- });
-
- test('throws - unexpected to see normal completion', () {
- var completer = new Completer();
- completer.complete('1');
- shouldFail(completer.future, throws,
- contains("Expected future to fail, but succeeded with '1'"),
- isAsync: true);
- });
-
- test('throws - expected to see exception', () {
- var completer = new Completer();
- completer.completeError('X');
- shouldPass(completer.future, throws, isAsync: true);
- });
-
- test('throws - expected to see exception thrown later on', () {
- var completer = new Completer();
- var chained = completer.future.then((_) {
- throw 'X';
- });
- shouldPass(chained, throws, isAsync: true);
- completer.complete('1');
- });
-
- test('throwsA - unexpected normal completion', () {
- var completer = new Completer();
- completer.complete('1');
- shouldFail(completer.future, throwsA(equals('X')),
- contains("Expected future to fail, but succeeded with '1'"),
- isAsync: true);
- });
-
- test('throwsA - correct error', () {
- var completer = new Completer();
- completer.completeError('X');
- shouldPass(completer.future, throwsA(equals('X')), isAsync: true);
- });
-
- test('throwsA - wrong error', () {
- var completer = new Completer();
- completer.completeError('X');
- shouldFail(completer.future, throwsA(equals('Y')),
- "Expected: 'Y' Actual: 'X' "
- "Which: is different. "
- "Expected: Y Actual: X ^ Differ at offset 0", isAsync: true);
- });
-}
diff --git a/test/iterable_matchers_test.dart b/test/iterable_matchers_test.dart
index da454fb..ed15da7 100644
--- a/test/iterable_matchers_test.dart
+++ b/test/iterable_matchers_test.dart
@@ -10,8 +10,6 @@
import 'test_utils.dart';
void main() {
- initUtils();
-
test('isEmpty', () {
shouldPass([], isEmpty);
shouldFail([1], isEmpty, "Expected: empty Actual: [1]");
diff --git a/test/matchers_minified_test.dart b/test/matchers_minified_test.dart
deleted file mode 100644
index d9ee582..0000000
--- a/test/matchers_minified_test.dart
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-// This file is for matcher tests that rely on the names of various Dart types.
-// These tests normally fail when run in minified dart2js, since the names will
-// be mangled. This version of the file is modified to expect minified names.
-
-library matcher.minified_test;
-
-import 'package:matcher/matcher.dart';
-import 'package:unittest/unittest.dart' show test, group;
-
-import 'test_common.dart';
-import 'test_utils.dart';
-
-// A regexp fragment matching a minified name.
-const _MINIFIED_NAME = r"[A-Za-z0-9]{1,3}";
-
-void main() {
- initUtils();
-
- group('Core matchers', () {
- test('throwsFormatException', () {
- shouldPass(() {
- throw new FormatException('');
- }, throwsFormatException);
- shouldFail(() {
- throw new Exception();
- }, throwsFormatException, matches(r"Expected: throws FormatException +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw " + _MINIFIED_NAME + r":<Exception>"));
- });
-
- test('throwsArgumentError', () {
- shouldPass(() {
- throw new ArgumentError('');
- }, throwsArgumentError);
- shouldFail(() {
- throw new Exception();
- }, throwsArgumentError, matches(r"Expected: throws ArgumentError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw " + _MINIFIED_NAME + r":<Exception>"));
- });
-
- test('throwsRangeError', () {
- shouldPass(() {
- throw new RangeError(0);
- }, throwsRangeError);
- shouldFail(() {
- throw new Exception();
- }, throwsRangeError, matches(r"Expected: throws RangeError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw " + _MINIFIED_NAME + r":<Exception>"));
- });
-
- test('throwsNoSuchMethodError', () {
- shouldPass(() {
- throw new NoSuchMethodError(null, const Symbol(''), null, null);
- }, throwsNoSuchMethodError);
- shouldFail(() {
- throw new Exception();
- }, throwsNoSuchMethodError, matches(
- r"Expected: throws NoSuchMethodError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw " + _MINIFIED_NAME + r":<Exception>"));
- });
-
- test('throwsUnimplementedError', () {
- shouldPass(() {
- throw new UnimplementedError('');
- }, throwsUnimplementedError);
- shouldFail(() {
- throw new Exception();
- }, throwsUnimplementedError, matches(
- r"Expected: throws UnimplementedError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw " + _MINIFIED_NAME + r":<Exception>"));
- });
-
- test('throwsUnsupportedError', () {
- shouldPass(() {
- throw new UnsupportedError('');
- }, throwsUnsupportedError);
- shouldFail(() {
- throw new Exception();
- }, throwsUnsupportedError, matches(r"Expected: throws UnsupportedError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw " + _MINIFIED_NAME + r":<Exception>"));
- });
-
- test('throwsStateError', () {
- shouldPass(() {
- throw new StateError('');
- }, throwsStateError);
- shouldFail(() {
- throw new Exception();
- }, throwsStateError, matches(r"Expected: throws StateError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw " + _MINIFIED_NAME + r":<Exception>"));
- });
- });
-
- group('Iterable Matchers', () {
- test('isEmpty', () {
- var d = new SimpleIterable(0);
- var e = new SimpleIterable(1);
- shouldPass(d, isEmpty);
- shouldFail(e, isEmpty,
- matches(r"Expected: empty +Actual: " + _MINIFIED_NAME + r":\[1\]"));
- });
-
- test('isNotEmpty', () {
- var d = new SimpleIterable(0);
- var e = new SimpleIterable(1);
- shouldPass(e, isNotEmpty);
- shouldFail(d, isNotEmpty, matches(
- r"Expected: non-empty +Actual: " + _MINIFIED_NAME + r":\[\]"));
- });
-
- test('contains', () {
- var d = new SimpleIterable(3);
- shouldPass(d, contains(2));
- shouldFail(d, contains(5), matches(r"Expected: contains <5> +"
- r"Actual: " + _MINIFIED_NAME + r":\[3, 2, 1\]"));
- });
- });
-
- group('Feature Matchers', () {
- test("Feature Matcher", () {
- var w = new Widget();
- w.price = 10;
- shouldPass(w, new HasPrice(10));
- shouldPass(w, new HasPrice(greaterThan(0)));
- shouldFail(w, new HasPrice(greaterThan(10)), matches(
- r"Expected: Widget with a price that is a value greater than "
- r"<10> +"
- r"Actual: <Instance of '" + _MINIFIED_NAME + r"'> +"
- r"Which: has price with value <10> which is not "
- r"a value greater than <10>"));
- });
- });
-}
diff --git a/test/matchers_unminified_test.dart b/test/matchers_unminified_test.dart
deleted file mode 100644
index b9ea535..0000000
--- a/test/matchers_unminified_test.dart
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-// This file is for matcher tests that rely on the names of various Dart types.
-// These tests will fail when run in minified dart2js, since the names will be
-// mangled. A version of this file that works in minified dart2js is in
-// matchers_minified_test.dart.
-
-library matcher.unminified_test;
-
-import 'package:matcher/matcher.dart';
-import 'package:unittest/unittest.dart' show group, test;
-
-import 'test_common.dart';
-import 'test_utils.dart';
-
-void main() {
- initUtils();
-
- group('Core matchers', () {
- test('throwsFormatException', () {
- shouldPass(() {
- throw new FormatException('');
- }, throwsFormatException);
- shouldFail(() {
- throw new Exception();
- }, throwsFormatException, matches(r"Expected: throws FormatException +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw \?:<Exception>"));
- });
-
- test('throwsArgumentError', () {
- shouldPass(() {
- throw new ArgumentError('');
- }, throwsArgumentError);
- shouldFail(() {
- throw new Exception();
- }, throwsArgumentError, matches(r"Expected: throws ArgumentError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw \?:<Exception>"));
- });
-
- test('throwsRangeError', () {
- shouldPass(() {
- throw new RangeError(0);
- }, throwsRangeError);
- shouldFail(() {
- throw new Exception();
- }, throwsRangeError, matches(r"Expected: throws RangeError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw \?:<Exception>"));
- });
-
- test('throwsNoSuchMethodError', () {
- shouldPass(() {
- throw new NoSuchMethodError(null, const Symbol(''), null, null);
- }, throwsNoSuchMethodError);
- shouldFail(() {
- throw new Exception();
- }, throwsNoSuchMethodError, matches(
- r"Expected: throws NoSuchMethodError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw \?:<Exception>"));
- });
-
- test('throwsUnimplementedError', () {
- shouldPass(() {
- throw new UnimplementedError('');
- }, throwsUnimplementedError);
- shouldFail(() {
- throw new Exception();
- }, throwsUnimplementedError, matches(
- r"Expected: throws UnimplementedError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw \?:<Exception>"));
- });
-
- test('throwsUnsupportedError', () {
- shouldPass(() {
- throw new UnsupportedError('');
- }, throwsUnsupportedError);
- shouldFail(() {
- throw new Exception();
- }, throwsUnsupportedError, matches(r"Expected: throws UnsupportedError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw \?:<Exception>"));
- });
-
- test('throwsStateError', () {
- shouldPass(() {
- throw new StateError('');
- }, throwsStateError);
- shouldFail(() {
- throw new Exception();
- }, throwsStateError, matches(r"Expected: throws StateError +"
- r"Actual: <Closure(: \(\) => dynamic)?> +"
- r"Which: threw \?:<Exception>"));
- });
- });
-
- group('Iterable Matchers', () {
- test('isEmpty', () {
- var d = new SimpleIterable(0);
- var e = new SimpleIterable(1);
- shouldPass(d, isEmpty);
- shouldFail(e, isEmpty, "Expected: empty "
- "Actual: SimpleIterable:[1]");
- });
-
- test('isNotEmpty', () {
- var d = new SimpleIterable(0);
- var e = new SimpleIterable(1);
- shouldPass(e, isNotEmpty);
- shouldFail(d, isNotEmpty, "Expected: non-empty "
- "Actual: SimpleIterable:[]");
- });
-
- test('contains', () {
- var d = new SimpleIterable(3);
- shouldPass(d, contains(2));
- shouldFail(d, contains(5), "Expected: contains <5> "
- "Actual: SimpleIterable:[3, 2, 1]");
- });
- });
-
- group('Feature Matchers', () {
- test("Feature Matcher", () {
- var w = new Widget();
- w.price = 10;
- shouldPass(w, new HasPrice(10));
- shouldPass(w, new HasPrice(greaterThan(0)));
- shouldFail(w, new HasPrice(greaterThan(10)),
- "Expected: Widget with a price that is a value greater than <10> "
- "Actual: <Instance of 'Widget'> "
- "Which: has price with value <10> which is not "
- "a value greater than <10>");
- });
- });
-}
diff --git a/test/mirror_matchers_test.dart b/test/mirror_matchers_test.dart
index 90d7c46..3e2a4ed 100644
--- a/test/mirror_matchers_test.dart
+++ b/test/mirror_matchers_test.dart
@@ -17,8 +17,6 @@
}
void main() {
- initUtils();
-
test('hasProperty', () {
var foo = [3];
shouldPass(foo, hasProperty('length', 1));
diff --git a/test/numeric_matchers_test.dart b/test/numeric_matchers_test.dart
index 7ced6b4..af0f634 100644
--- a/test/numeric_matchers_test.dart
+++ b/test/numeric_matchers_test.dart
@@ -10,8 +10,6 @@
import 'test_utils.dart';
void main() {
- initUtils();
-
test('greaterThan', () {
shouldPass(10, greaterThan(9));
shouldFail(9, greaterThan(10), "Expected: a value greater than <10> "
diff --git a/test/operator_matchers_test.dart b/test/operator_matchers_test.dart
index b92986c..7cf0d59 100644
--- a/test/operator_matchers_test.dart
+++ b/test/operator_matchers_test.dart
@@ -5,13 +5,12 @@
library matcher.operator_matchers_test;
import 'package:matcher/matcher.dart';
-import 'package:unittest/unittest.dart' show test, group;
+import 'package:unittest/unittest.dart'
+ show test, group, expect, throwsArgumentError;
import 'test_utils.dart';
void main() {
- initUtils();
-
test('anyOf', () {
// with a list
shouldFail(
diff --git a/test/pretty_print_minified_test.dart b/test/pretty_print_minified_test.dart
index f1107f7..9eb6d76 100644
--- a/test/pretty_print_minified_test.dart
+++ b/test/pretty_print_minified_test.dart
@@ -13,7 +13,7 @@
import 'package:matcher/matcher.dart';
import 'package:matcher/src/pretty_print.dart';
-import 'package:unittest/unittest.dart' show test, group;
+import 'package:unittest/unittest.dart' show test, group, expect;
class DefaultToString {}
diff --git a/test/pretty_print_test.dart b/test/pretty_print_test.dart
index 6d443b5..1e3704f 100644
--- a/test/pretty_print_test.dart
+++ b/test/pretty_print_test.dart
@@ -6,7 +6,7 @@
import 'package:matcher/matcher.dart';
import 'package:matcher/src/pretty_print.dart';
-import 'package:unittest/unittest.dart' show group, test;
+import 'package:unittest/unittest.dart' show group, test, expect;
void main() {
test('with primitive objects', () {
diff --git a/test/pretty_print_unminified_test.dart b/test/pretty_print_unminified_test.dart
index c8b2035..f14dfb8 100644
--- a/test/pretty_print_unminified_test.dart
+++ b/test/pretty_print_unminified_test.dart
@@ -13,7 +13,7 @@
import 'package:matcher/matcher.dart';
import 'package:matcher/src/pretty_print.dart';
-import 'package:unittest/unittest.dart' show test, group;
+import 'package:unittest/unittest.dart' show test, group, expect;
class DefaultToString {}
diff --git a/test/prints_matcher_test.dart b/test/prints_matcher_test.dart
deleted file mode 100644
index 7680953..0000000
--- a/test/prints_matcher_test.dart
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library matcher.prints_matchers_test;
-
-import 'dart:async';
-
-import 'package:matcher/matcher.dart';
-import 'package:unittest/unittest.dart';
-
-import 'test_utils.dart';
-
-/// The VM and dart2js have different toStrings for closures.
-final closureToString = (() {}).toString();
-
-void main() {
- initUtils();
-
- group('synchronous', () {
- test("passes with an expected print", () {
- shouldPass(() => print("Hello, world!"), prints("Hello, world!\n"));
- });
-
- test("combines multiple prints", () {
- shouldPass(() {
- print("Hello");
- print("World!");
- }, prints("Hello\nWorld!\n"));
- });
-
- test("works with a Matcher", () {
- shouldPass(() => print("Hello, world!"), prints(contains("Hello")));
- });
-
- test("describes a failure nicely", () {
- shouldFail(() => print("Hello, world!"), prints("Goodbye, world!\n"),
- "Expected: prints 'Goodbye, world!\\n' ''"
- " Actual: <$closureToString> "
- " Which: printed 'Hello, world!\\n' ''"
- " Which: is different. "
- "Expected: Goodbye, w ... "
- " Actual: Hello, wor ... "
- " ^ Differ at offset 0");
- });
-
- test("describes a failure with a non-descriptive Matcher nicely", () {
- shouldFail(() => print("Hello, world!"), prints(contains("Goodbye")),
- "Expected: prints contains 'Goodbye'"
- " Actual: <$closureToString> "
- " Which: printed 'Hello, world!\\n' ''");
- });
-
- test("describes a failure with no text nicely", () {
- shouldFail(() {}, prints(contains("Goodbye")),
- "Expected: prints contains 'Goodbye'"
- " Actual: <$closureToString> "
- " Which: printed nothing.");
- });
- });
-
- group('asynchronous', () {
- test("passes with an expected print", () {
- shouldPass(() => new Future(() => print("Hello, world!")),
- prints("Hello, world!\n"));
- });
-
- test("combines multiple prints", () {
- shouldPass(() => new Future(() {
- print("Hello");
- print("World!");
- }), prints("Hello\nWorld!\n"));
- });
-
- test("works with a Matcher", () {
- shouldPass(() => new Future(() => print("Hello, world!")),
- prints(contains("Hello")));
- });
-
- test("describes a failure nicely", () {
- shouldFail(() => new Future(() => print("Hello, world!")),
- prints("Goodbye, world!\n"), "Expected: 'Goodbye, world!\\n' ''"
- " Actual: 'Hello, world!\\n' ''"
- " Which: is different. "
- "Expected: Goodbye, w ... "
- " Actual: Hello, wor ... "
- " ^ Differ at offset 0", isAsync: true);
- });
-
- test("describes a failure with a non-descriptive Matcher nicely", () {
- shouldFail(() => new Future(() => print("Hello, world!")),
- prints(contains("Goodbye")), "Expected: contains 'Goodbye'"
- " Actual: 'Hello, world!\\n' ''", isAsync: true);
- });
-
- test("describes a failure with no text nicely", () {
- shouldFail(() => new Future.value(), prints(contains("Goodbye")),
- "Expected: contains 'Goodbye'"
- " Actual: ''", isAsync: true);
- });
- });
-}
diff --git a/test/string_matchers_test.dart b/test/string_matchers_test.dart
index 4cebd58..cb34a70 100644
--- a/test/string_matchers_test.dart
+++ b/test/string_matchers_test.dart
@@ -5,13 +5,11 @@
library matcher.string_matchers_test;
import 'package:matcher/matcher.dart';
-import 'package:unittest/unittest.dart' show test, group;
+import 'package:unittest/unittest.dart' show test, group, expect;
import 'test_utils.dart';
void main() {
- initUtils();
-
test('Reports mismatches in whitespace and escape sequences', () {
shouldFail('before\nafter', equals('before\\nafter'),
contains('Differ at offset 7'));
diff --git a/test/test_common.dart b/test/test_common.dart
deleted file mode 100644
index c360fe7..0000000
--- a/test/test_common.dart
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library matcher.test_common;
-
-import 'dart:collection';
-
-import 'package:matcher/matcher.dart';
-
-class Widget {
- int price;
-}
-
-class HasPrice extends CustomMatcher {
- HasPrice(matcher) : super("Widget with a price that is", "price", matcher);
- featureValueOf(actual) => actual.price;
-}
-
-class SimpleIterable extends IterableBase<int> {
- final int count;
-
- SimpleIterable(this.count);
-
- bool contains(int val) => count < val ? false : true;
-
- bool any(bool f(element)) {
- for (var i = 0; i <= count; i++) {
- if (f(i)) return true;
- }
- return false;
- }
-
- String toString() => "<[$count]>";
-
- Iterator get iterator {
- return new _SimpleIterator(count);
- }
-}
-
-class _SimpleIterator implements Iterator<int> {
- int _count;
- int _current;
-
- _SimpleIterator(this._count);
-
- bool moveNext() {
- if (_count > 0) {
- _current = _count;
- _count--;
- return true;
- }
- _current = null;
- return false;
- }
-
- int get current => _current;
-}
diff --git a/test/test_utils.dart b/test/test_utils.dart
index 4df8e2e..fb342a4 100644
--- a/test/test_utils.dart
+++ b/test/test_utils.dart
@@ -4,36 +4,17 @@
library matcher.test_utils;
-import 'dart:async';
+import 'package:unittest/unittest.dart';
-import 'package:matcher/matcher.dart';
-import 'package:unittest/unittest.dart' show test, expectAsync;
+void shouldFail(value, Matcher matcher, expected) {
+ var failed = false;
+ try {
+ expect(value, matcher);
+ } on TestFailure catch (err) {
+ failed = true;
-int _errorCount;
-String _errorString;
-FailureHandler _testHandler = null;
+ var _errorString = err.message;
-class MyFailureHandler extends DefaultFailureHandler {
- void fail(String reason) {
- ++_errorCount;
- _errorString = reason;
- }
-}
-
-void initUtils() {
- if (_testHandler == null) {
- _testHandler = new MyFailureHandler();
- }
-}
-
-void shouldFail(value, Matcher matcher, expected, {bool isAsync: false}) {
- configureExpectFailureHandler(_testHandler);
- _errorCount = 0;
- _errorString = '';
- expect(value, matcher);
- afterTest() {
- configureExpectFailureHandler(null);
- expect(_errorCount, equals(1));
if (expected is String) {
expect(_errorString, equalsIgnoringWhitespace(expected));
} else {
@@ -41,44 +22,14 @@
}
}
- if (isAsync) {
- Timer.run(expectAsync(afterTest));
- } else {
- afterTest();
- }
+ expect(failed, isTrue, reason: 'Expected to fail.');
}
-void shouldPass(value, Matcher matcher, {bool isAsync: false}) {
- configureExpectFailureHandler(_testHandler);
- _errorCount = 0;
- _errorString = '';
+void shouldPass(value, Matcher matcher) {
expect(value, matcher);
- afterTest() {
- configureExpectFailureHandler(null);
- expect(_errorCount, equals(0));
- }
- if (isAsync) {
- Timer.run(expectAsync(afterTest));
- } else {
- afterTest();
- }
}
doesNotThrow() {}
doesThrow() {
throw 'X';
}
-
-class PrefixMatcher extends Matcher {
- final String _prefix;
- const PrefixMatcher(this._prefix);
- bool matches(item, Map matchState) {
- return item is String &&
- (collapseWhitespace(item)).startsWith(collapseWhitespace(_prefix));
- }
-
- Description describe(Description description) => description
- .add('a string starting with ')
- .addDescriptionOf(collapseWhitespace(_prefix))
- .add(' ignoring whitespace');
-}
diff --git a/test/throws_matchers_test.dart b/test/throws_matchers_test.dart
deleted file mode 100644
index f766002..0000000
--- a/test/throws_matchers_test.dart
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library matcher.core_matchers_test;
-
-import 'package:matcher/matcher.dart';
-import 'package:unittest/unittest.dart' show test, group;
-
-import 'test_utils.dart';
-
-void main() {
- initUtils();
-
- test('throws', () {
- shouldFail(doesNotThrow, throws, matches(r"Expected: throws"
- r" Actual: <Closure(: \(\) => dynamic "
- r"from Function 'doesNotThrow': static\.)?>"
- r" Which: did not throw"));
- shouldPass(doesThrow, throws);
- shouldFail(true, throws, "Expected: throws"
- " Actual: <true>"
- " Which: is not a Function or Future");
- });
-
- test('throwsA', () {
- shouldPass(doesThrow, throwsA(equals('X')));
- shouldFail(doesThrow, throwsA(equals('Y')), matches(r"Expected: throws 'Y'"
- r" Actual: <Closure(: \(\) => dynamic "
- r"from Function 'doesThrow': static\.)?>"
- r" Which: threw 'X'"));
- });
-
- test('throwsA', () {
- shouldPass(doesThrow, throwsA(equals('X')));
- shouldFail(doesThrow, throwsA(equals('Y')), matches("Expected: throws 'Y'.*"
- "Actual: <Closure.*"
- "Which: threw 'X'"));
- });
-
- group('exception/error matchers', () {
- test('throwsCyclicInitializationError', () {
- expect(() => _Bicycle.foo, throwsCyclicInitializationError);
- });
-
- test('throwsConcurrentModificationError', () {
- expect(() {
- var a = {'foo': 'bar'};
- for (var k in a.keys) {
- a.remove(k);
- }
- }, throwsConcurrentModificationError);
- });
-
- test('throwsNullThrownError', () {
- expect(() => throw null, throwsNullThrownError);
- });
- });
-}
-
-class _Bicycle {
- static final foo = bar();
-
- static bar() {
- return foo + 1;
- }
-}