OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, 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 unittest.expect; |
| 6 |
| 7 import 'package:matcher/matcher.dart'; |
| 8 |
| 9 /// An exception thrown when a test assertion fails. |
| 10 class TestFailure { |
| 11 final String message; |
| 12 |
| 13 TestFailure(this.message); |
| 14 |
| 15 String toString() => message; |
| 16 } |
| 17 |
| 18 /// The type used for functions that can be used to build up error reports |
| 19 /// upon failures in [expect]. |
| 20 typedef String ErrorFormatter( |
| 21 actual, Matcher matcher, String reason, Map matchState, bool verbose); |
| 22 |
| 23 /// Assert that [actual] matches [matcher]. |
| 24 /// |
| 25 /// This is the main assertion function. [reason] is optional and is typically |
| 26 /// not supplied, as a reason is generated from [matcher]; if [reason] |
| 27 /// is included it is appended to the reason generated by the matcher. |
| 28 /// |
| 29 /// [matcher] can be a value in which case it will be wrapped in an |
| 30 /// [equals] matcher. |
| 31 /// |
| 32 /// If the assertion fails a [TestFailure] is thrown. |
| 33 /// |
| 34 /// In some cases extra diagnostic info can be produced on failure (for |
| 35 /// example, stack traces on mismatched exceptions). To enable these, |
| 36 /// [verbose] should be specified as `true`. |
| 37 void expect(actual, matcher, |
| 38 {String reason, bool verbose: false, ErrorFormatter formatter}) { |
| 39 matcher = wrapMatcher(matcher); |
| 40 var matchState = {}; |
| 41 try { |
| 42 if (matcher.matches(actual, matchState)) return; |
| 43 } catch (e, trace) { |
| 44 if (reason == null) { |
| 45 reason = '${(e is String) ? e : e.toString()} at $trace'; |
| 46 } |
| 47 } |
| 48 if (formatter == null) formatter = _defaultFailFormatter; |
| 49 fail(formatter(actual, matcher, reason, matchState, verbose)); |
| 50 } |
| 51 |
| 52 /// Convenience method for throwing a new [TestFailure] with the provided |
| 53 /// [message]. |
| 54 void fail(String message) => throw new TestFailure(message); |
| 55 |
| 56 // The default error formatter. |
| 57 String _defaultFailFormatter( |
| 58 actual, Matcher matcher, String reason, Map matchState, bool verbose) { |
| 59 var description = new StringDescription(); |
| 60 description.add('Expected: ').addDescriptionOf(matcher).add('\n'); |
| 61 description.add(' Actual: ').addDescriptionOf(actual).add('\n'); |
| 62 |
| 63 var mismatchDescription = new StringDescription(); |
| 64 matcher.describeMismatch(actual, mismatchDescription, matchState, verbose); |
| 65 |
| 66 if (mismatchDescription.length > 0) { |
| 67 description.add(' Which: ${mismatchDescription}\n'); |
| 68 } |
| 69 if (reason != null) description.add(reason).add('\n'); |
| 70 return description.toString(); |
| 71 } |
OLD | NEW |