OLD | NEW |
| (Empty) |
1 // Copyright (c) 2014, 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.prints_matcher; | |
6 | |
7 import 'dart:async'; | |
8 | |
9 import 'description.dart'; | |
10 import 'expect.dart'; | |
11 import 'interfaces.dart'; | |
12 import 'future_matchers.dart'; | |
13 import 'util.dart'; | |
14 | |
15 /// Matches a [Function] that prints text that matches [matcher]. | |
16 /// | |
17 /// [matcher] may be a String or a [Matcher]. | |
18 /// | |
19 /// If the function this runs against returns a [Future], all text printed by | |
20 /// the function (using [Zone] scoping) until that Future completes is matched. | |
21 /// | |
22 /// This only tracks text printed using the [print] function. | |
23 Matcher prints(matcher) => new _Prints(wrapMatcher(matcher)); | |
24 | |
25 class _Prints extends Matcher { | |
26 final Matcher _matcher; | |
27 | |
28 _Prints(this._matcher); | |
29 | |
30 bool matches(item, Map matchState) { | |
31 if (item is! Function) return false; | |
32 | |
33 var buffer = new StringBuffer(); | |
34 var result = runZoned(item, zoneSpecification: | |
35 new ZoneSpecification(print: (_, __, ____, line) { | |
36 buffer.writeln(line); | |
37 })); | |
38 | |
39 if (result is! Future) { | |
40 var actual = buffer.toString(); | |
41 matchState['prints.actual'] = actual; | |
42 return _matcher.matches(actual, matchState); | |
43 } | |
44 | |
45 return completes.matches(result.then(wrapAsync((_) { | |
46 expect(buffer.toString(), _matcher); | |
47 }, 'prints')), matchState); | |
48 } | |
49 | |
50 Description describe(Description description) => | |
51 description.add('prints ').addDescriptionOf(_matcher); | |
52 | |
53 Description describeMismatch(item, Description description, Map matchState, | |
54 bool verbose) { | |
55 var actual = matchState.remove('prints.actual'); | |
56 if (actual == null) return description; | |
57 if (actual.isEmpty) return description.add("printed nothing."); | |
58 | |
59 description.add('printed ').addDescriptionOf(actual); | |
60 | |
61 // Create a new description for the matcher because at least | |
62 // [_StringEqualsMatcher] replaces the previous contents of the description. | |
63 var innerMismatch = _matcher.describeMismatch( | |
64 actual, new StringDescription(), matchState, verbose).toString(); | |
65 | |
66 if (innerMismatch.isNotEmpty) { | |
67 description.add('\n Which: ').add(innerMismatch.toString()); | |
68 } | |
69 | |
70 return description; | |
71 } | |
72 } | |
OLD | NEW |