OLD | NEW |
| (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.future_matchers; | |
6 | |
7 import 'dart:async'; | |
8 | |
9 import 'expect.dart'; | |
10 import 'interfaces.dart'; | |
11 import 'util.dart'; | |
12 | |
13 /// Matches a [Future] that completes successfully with a value. | |
14 /// | |
15 /// Note that this creates an asynchronous expectation. The call to `expect()` | |
16 /// that includes this will return immediately and execution will continue. | |
17 /// Later, when the future completes, the actual expectation will run. | |
18 /// | |
19 /// To test that a Future completes with an exception, you can use [throws] and | |
20 /// [throwsA]. | |
21 final Matcher completes = const _Completes(null, ''); | |
22 | |
23 /// Matches a [Future] that completes succesfully with a value that matches | |
24 /// [matcher]. | |
25 /// | |
26 /// Note that this creates an asynchronous expectation. The call to | |
27 /// `expect()` that includes this will return immediately and execution will | |
28 /// continue. Later, when the future completes, the actual expectation will run. | |
29 /// | |
30 /// To test that a Future completes with an exception, you can use [throws] and | |
31 /// [throwsA]. | |
32 /// | |
33 /// [id] is an optional tag that can be used to identify the completion matcher | |
34 /// in error messages. | |
35 Matcher completion(matcher, [String id = '']) => | |
36 new _Completes(wrapMatcher(matcher), id); | |
37 | |
38 class _Completes extends Matcher { | |
39 final Matcher _matcher; | |
40 final String _id; | |
41 | |
42 const _Completes(this._matcher, this._id); | |
43 | |
44 bool matches(item, Map matchState) { | |
45 if (item is! Future) return false; | |
46 var done = wrapAsync((fn) => fn(), _id); | |
47 | |
48 item.then((value) { | |
49 done(() { if (_matcher != null) expect(value, _matcher); }); | |
50 }, onError: (error, trace) { | |
51 var id = _id == '' ? '' : '${_id} '; | |
52 var reason = 'Expected future ${id}to complete successfully, ' | |
53 'but it failed with ${error}'; | |
54 if (trace != null) { | |
55 var stackTrace = trace.toString(); | |
56 stackTrace = ' ${stackTrace.replaceAll('\n', '\n ')}'; | |
57 reason = '$reason\nStack trace:\n$stackTrace'; | |
58 } | |
59 done(() => fail(reason)); | |
60 }); | |
61 | |
62 return true; | |
63 } | |
64 | |
65 Description describe(Description description) { | |
66 if (_matcher == null) { | |
67 description.add('completes successfully'); | |
68 } else { | |
69 description.add('completes to a value that ').addDescriptionOf(_matcher); | |
70 } | |
71 return description; | |
72 } | |
73 } | |
OLD | NEW |