Chromium Code Reviews

Side by Side Diff: lib/src/runner/console_reporter.dart

Issue 971123002: Add a variant on ConsoleReporter that doesn't import dart:io. (Closed) Base URL: git@github.com:dart-lang/unittest@master
Patch Set: Created 5 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff |
« no previous file with comments | « bin/unittest.dart ('k') | lib/src/runner/reporter/compact.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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.runner.console_reporter;
6
7 import 'dart:async';
8 import 'dart:io';
9
10 import '../backend/live_test.dart';
11 import '../backend/state.dart';
12 import '../backend/suite.dart';
13 import '../utils.dart';
14 import 'engine.dart';
15
16 /// The maximum console line length.
17 ///
18 /// Lines longer than this will be cropped.
19 const _lineLength = 100;
20
21 /// A reporter that prints test results to the console in a single
22 /// continuously-updating line.
23 class ConsoleReporter {
24 /// The terminal escape for green text, or the empty string if this is Windows
25 /// or not outputting to a terminal.
26 final String _green;
27
28 /// The terminal escape for red text, or the empty string if this is Windows
29 /// or not outputting to a terminal.
30 final String _red;
31
32 /// The terminal escape for removing test coloring, or the empty string if
33 /// this is Windows or not outputting to a terminal.
34 final String _noColor;
35
36 /// The engine used to run the tests.
37 final Engine _engine;
38
39 /// Whether multiple test suites are being run.
40 final bool _multipleSuites;
41
42 /// A stopwatch that tracks the duration of the full run.
43 final _stopwatch = new Stopwatch();
44
45 /// The set of tests that have completed and been marked as passing.
46 final _passed = new Set<LiveTest>();
47
48 /// The set of tests that have completed and been marked as failing or error.
49 final _failed = new Set<LiveTest>();
50
51 /// The size of [_passed] last time a progress notification was printed.
52 int _lastProgressPassed;
53
54 /// The size of [_failed] last time a progress notification was printed.
55 int _lastProgressFailed;
56
57 /// The message printed for the last progress notification.
58 String _lastProgressMessage;
59
60 /// Creates a [ConsoleReporter] that will run all tests in [suites].
61 ///
62 /// If [color] is `true`, this will use terminal colors; if it's `false`, it
63 /// won't.
64 ConsoleReporter(Iterable<Suite> suites, {bool color: true})
65 : _multipleSuites = suites.length > 1,
66 _engine = new Engine(suites),
67 _green = color ? '\u001b[32m' : '',
68 _red = color ? '\u001b[31m' : '',
69 _noColor = color ? '\u001b[0m' : '' {
70 _engine.onTestStarted.listen((liveTest) {
71 _progressLine(_description(liveTest));
72 liveTest.onStateChange.listen((state) {
73 if (state.status != Status.complete) return;
74 if (state.result == Result.success) {
75 _passed.add(liveTest);
76 } else {
77 _passed.remove(liveTest);
78 _failed.add(liveTest);
79 }
80 _progressLine(_description(liveTest));
81 });
82
83 liveTest.onError.listen((error) {
84 if (liveTest.state.status != Status.complete) return;
85
86 _progressLine(_description(liveTest));
87 print('');
88 print(indent(error.error.toString()));
89 print(indent(terseChain(error.stackTrace).toString()));
90 });
91 });
92 }
93
94 /// Runs all tests in all provided suites.
95 ///
96 /// This returns `true` if all tests succeed, and `false` otherwise. It will
97 /// only return once all tests have finished running.
98 Future<bool> run() {
99 if (_stopwatch.isRunning) {
100 throw new StateError("ConsoleReporter.run() may not be called more than "
101 "once.");
102 }
103
104 if (_engine.liveTests.isEmpty) {
105 print("No tests ran.");
106 return new Future.value(true);
107 }
108
109 _stopwatch.start();
110 return _engine.run().then((success) {
111 if (success) {
112 _progressLine("All tests passed!");
113 print('');
114 } else {
115 _progressLine('Some tests failed.', color: _red);
116 print('');
117 }
118
119 return success;
120 });
121 }
122
123 /// Signals that the caller is done with any test output and the reporter
124 /// should release any resources it has allocated.
125 Future close() => _engine.close();
126
127 /// Prints a line representing the current state of the tests.
128 ///
129 /// [message] goes after the progress report, and may be truncated to fit the
130 /// entire line within [_lineLength]. If [color] is passed, it's used as the
131 /// color for [message].
132 void _progressLine(String message, {String color}) {
133 // Print nothing if nothing has changed since the last progress line.
134 if (_passed.length == _lastProgressPassed &&
135 _failed.length == _lastProgressFailed &&
136 message == _lastProgressMessage) {
137 return;
138 }
139
140 _lastProgressPassed = _passed.length;
141 _lastProgressFailed = _failed.length;
142 _lastProgressMessage = message;
143
144 if (color == null) color = '';
145 var duration = _stopwatch.elapsed;
146 var buffer = new StringBuffer();
147
148 // \r moves back to the beginning of the current line.
149 buffer.write('\r${_timeString(duration)} ');
150 buffer.write(_green);
151 buffer.write('+');
152 buffer.write(_passed.length);
153 buffer.write(_noColor);
154
155 if (_failed.isNotEmpty) {
156 buffer.write(_red);
157 buffer.write(' -');
158 buffer.write(_failed.length);
159 buffer.write(_noColor);
160 }
161
162 buffer.write(': ');
163 buffer.write(color);
164
165 // Ensure the line fits within [_lineLength]. [buffer] includes the color
166 // escape sequences too. Because these sequences are not visible characters,
167 // we make sure they are not counted towards the limit.
168 var nonVisible = 1 + _green.length + _noColor.length + color.length +
169 (_failed.isEmpty ? 0 : _red.length + _noColor.length);
170 var length = buffer.length - nonVisible;
171 buffer.write(_truncate(message, _lineLength - length));
172 buffer.write(_noColor);
173
174 // Pad the rest of the line so that it looks erased.
175 length = buffer.length - nonVisible - _noColor.length;
176 buffer.write(' ' * (_lineLength - length));
177 stdout.write(buffer.toString());
178 }
179
180 /// Returns a representation of [duration] as `MM:SS`.
181 String _timeString(Duration duration) {
182 return "${duration.inMinutes.toString().padLeft(2, '0')}:"
183 "${(duration.inSeconds % 60).toString().padLeft(2, '0')}";
184 }
185
186 /// Truncates [text] to fit within [maxLength].
187 ///
188 /// This will try to truncate along word boundaries and preserve words both at
189 /// the beginning and the end of [text].
190 String _truncate(String text, int maxLength) {
191 // Return the full message if it fits.
192 if (text.length <= maxLength) return text;
193
194 // If we can fit the first and last three words, do so.
195 var words = text.split(' ');
196 if (words.length > 1) {
197 var i = words.length;
198 var length = words.first.length + 4;
199 do {
200 i--;
201 length += 1 + words[i].length;
202 } while (length <= maxLength && i > 0);
203 if (length > maxLength || i == 0) i++;
204 if (i < words.length - 4) {
205 // Require at least 3 words at the end.
206 var buffer = new StringBuffer();
207 buffer.write(words.first);
208 buffer.write(' ...');
209 for ( ; i < words.length; i++) {
210 buffer.write(' ');
211 buffer.write(words[i]);
212 }
213 return buffer.toString();
214 }
215 }
216
217 // Otherwise truncate to return the trailing text, but attempt to start at
218 // the beginning of a word.
219 var result = text.substring(text.length - maxLength + 4);
220 var firstSpace = result.indexOf(' ');
221 if (firstSpace > 0) {
222 result = result.substring(firstSpace);
223 }
224 return '...$result';
225 }
226
227 /// Returns a description of [liveTest].
228 ///
229 /// This differs from the test's own description in that it may also include
230 /// the suite's name.
231 String _description(LiveTest liveTest) {
232 if (_multipleSuites) return "${liveTest.suite.name}: ${liveTest.test.name}";
233 return liveTest.test.name;
234 }
235 }
OLDNEW
« no previous file with comments | « bin/unittest.dart ('k') | lib/src/runner/reporter/compact.dart » ('j') | no next file with comments »

Powered by Google App Engine