Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(505)

Side by Side Diff: pkg/polymer/test/build/common.dart

Issue 794473002: Delete polymer from the Dart repo (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 6 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2013, 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 polymer.test.build.common;
6
7 import 'dart:async';
8
9 import 'package:barback/barback.dart';
10 import 'package:code_transformers/messages/build_logger.dart'
11 show LOG_EXTENSION;
12 import 'package:polymer/src/build/common.dart';
13 import 'package:stack_trace/stack_trace.dart';
14 import 'package:unittest/unittest.dart';
15
16 String idToString(AssetId id) => '${id.package}|${id.path}';
17 AssetId idFromString(String s) {
18 int index = s.indexOf('|');
19 return new AssetId(s.substring(0, index), s.substring(index + 1));
20 }
21
22 String _removeTrailingWhitespace(String str) =>
23 str.splitMapJoin('\n',
24 onNonMatch: (s) => s.replaceAll(new RegExp(r'\s+$'), ''));
25
26 /// A helper package provider that has files stored in memory, also wraps
27 /// [Barback] to simply our tests.
28 class TestHelper implements PackageProvider {
29 /// Maps from an asset string identifier of the form 'package|path' to the
30 /// file contents.
31 final Map<String, String> files;
32 final Iterable<String> packages;
33 final List<String> messages;
34 int messagesSeen = 0;
35 bool errorSeen = false;
36
37 Barback barback;
38 var errorSubscription;
39 var resultSubscription;
40 var logSubscription;
41
42 Future<Asset> getAsset(AssetId id) {
43 var content = files[idToString(id)];
44 if (content == null) fail('error: requested $id, but $id is not available');
45 return new Future.value(new Asset.fromString(id, content));
46 }
47
48 TestHelper(List<List<Transformer>> transformers, Map<String, String> files,
49 this.messages)
50 : files = files,
51 packages = files.keys.map((s) => idFromString(s).package) {
52 barback = new Barback(this);
53 for (var p in packages) {
54 barback.updateTransformers(p, transformers);
55 }
56
57 errorSubscription = barback.errors.listen((e) {
58 var trace = null;
59 if (e is Error) trace = e.stackTrace;
60 if (trace != null) {
61 print(Trace.format(trace));
62 }
63 fail('error running barback: $e');
64 });
65
66 resultSubscription = barback.results.listen((result) {
67 expect(result.succeeded, !errorSeen, reason: "${result.errors}");
68 });
69
70 logSubscription = barback.log.listen((entry) {
71 // Ignore info messages.
72 if (entry.level == LogLevel.INFO || entry.level == LogLevel.FINE) return;
73 if (entry.level == LogLevel.ERROR) errorSeen = true;
74 // We only check messages when an expectation is provided.
75 if (messages == null) return;
76
77 var errorLink = new RegExp(
78 ' See http://goo.gl/5HPeuP#polymer_[0-9]* for details.');
79 var text = entry.message;
80 var newText = text.replaceFirst(errorLink, '');
81 expect(text != newText, isTrue);
82 var msg = '${entry.level.name.toLowerCase()}: ${newText}';
83 var span = entry.span;
84 var spanInfo = span == null ? '' :
85 ' (${span.sourceUrl} ${span.start.line} ${span.start.column})';
86 var index = messagesSeen++;
87 expect(messagesSeen, lessThanOrEqualTo(messages.length),
88 reason: 'more messages than expected.\nMessage seen: $msg$spanInfo');
89 expect('$msg$spanInfo', messages[index]);
90 });
91 }
92
93 void tearDown() {
94 errorSubscription.cancel();
95 resultSubscription.cancel();
96 logSubscription.cancel();
97 }
98
99 /// Tells barback which files have changed, and thus anything that depends on
100 /// it on should be computed. By default mark all the input files.
101 void run([Iterable<String> paths]) {
102 if (paths == null) paths = files.keys;
103 barback.updateSources(paths.map(idFromString));
104 }
105
106 Future<String> operator [](String assetString){
107 return barback.getAssetById(idFromString(assetString))
108 .then((asset) => asset.readAsString());
109 }
110
111 Future check(String assetIdString, String content) {
112 return this[assetIdString].then((value) {
113 value = _removeTrailingWhitespace(value);
114 content = _removeTrailingWhitespace(content);
115 expect(value, content, reason: 'Final output of $assetIdString differs.');
116 });
117 }
118
119 Future checkAll(Map<String, String> files) {
120 return barback.results.first.then((_) {
121 if (files == null) return null;
122 var futures = [];
123 files.forEach((k, v) {
124 futures.add(check(k, v));
125 });
126 return Future.wait(futures);
127 }).then((_) {
128 // We only check messages when an expectation is provided.
129 if (messages == null) return;
130 expect(messagesSeen, messages.length,
131 reason: 'less messages than expected');
132 });
133 }
134 }
135
136 testPhases(String testName, List<List<Transformer>> phases,
137 Map<String, String> inputFiles, Map<String, String> expectedFiles,
138 [List<String> expectedMessages, bool solo = false]) {
139 // Include mock versions of the polymer library that can be used to test
140 // resolver-based code generation.
141 POLYMER_MOCKS.forEach((file, contents) { inputFiles[file] = contents; });
142 (solo ? solo_test : test)(testName, () {
143 var helper = new TestHelper(phases, inputFiles, expectedMessages)..run();
144 return helper.checkAll(expectedFiles).whenComplete(() => helper.tearDown());
145 });
146 }
147
148 solo_testPhases(String testName, List<List<Transformer>> phases,
149 Map<String, String> inputFiles, Map<String, String> expectedFiles,
150 [List<String> expectedMessages]) =>
151 testPhases(testName, phases, inputFiles, expectedFiles, expectedMessages,
152 true);
153
154
155 // Similar to testPhases, but tests all the cases around log behaviour in
156 // different modes. Any expectedFiles with [LOG_EXTENSION] will be removed from
157 // the expectation as appropriate, and any error logs will be changed to expect
158 // warning logs as appropriate.
159 testLogOutput(Function buildPhase, String testName,
160 Map<String, String> inputFiles, Map<String, String> expectedFiles,
161 [List<String> expectedMessages, bool solo = false]) {
162
163 final transformOptions = [
164 new TransformOptions(injectBuildLogsInOutput: false, releaseMode: false),
165 new TransformOptions(injectBuildLogsInOutput: false, releaseMode: true),
166 new TransformOptions(injectBuildLogsInOutput: true, releaseMode: false),
167 new TransformOptions(injectBuildLogsInOutput: true, releaseMode: true),
168 ];
169
170 for (var options in transformOptions) {
171 var phase = buildPhase(options);
172 var actualExpectedFiles = {};
173 expectedFiles.forEach((file, content) {
174 if (file.contains(LOG_EXTENSION)
175 && (!options.injectBuildLogsInOutput || options.releaseMode)) {
176 return;
177 }
178 actualExpectedFiles[file] = content;
179 });
180 var fullTestName = '$testName: '
181 'injectLogs=${options.injectBuildLogsInOutput} '
182 'releaseMode=${options.releaseMode}';
183 testPhases(
184 fullTestName, [[phase]], inputFiles,
185 actualExpectedFiles,
186 expectedMessages.map((m) =>
187 options.releaseMode ? m : m.replaceFirst('error:', 'warning:'))
188 .toList(),
189 solo);
190 }
191 }
192
193 /// Generate an expected ._data file, where all files are assumed to be in the
194 /// same [package].
195 String expectedData(List<String> urls, {package: 'a', experimental: false}) {
196 var ids = urls.map((e) => '["$package","$e"]').join(',');
197 return '{"experimental_bootstrap":$experimental,"script_ids":[$ids]}';
198 }
199
200 const EMPTY_DATA = '{"experimental_bootstrap":false,"script_ids":[]}';
201
202 const DART_SUPPORT_TAG =
203 '<script src="packages/web_components/dart_support.js"></script>\n';
204 const WEB_COMPONENTS_JS_TAG =
205 '<script src="packages/web_components/webcomponents.min.js"></script>\n';
206 const COMPATIBILITY_JS_TAGS =
207 '$WEB_COMPONENTS_JS_TAG$DART_SUPPORT_TAG';
208 const PLATFORM_JS_TAG =
209 '<script src="packages/web_components/platform.js"></script>\n';
210
211 const INTEROP_TAG = '<script src="packages/browser/interop.js"></script>\n';
212 const DART_JS_TAG = '<script src="packages/browser/dart.js"></script>';
213
214 const POLYMER_MOCKS = const {
215 'polymer|lib/src/js/polymer/polymer.html': '<!DOCTYPE html><html>',
216 'polymer|lib/polymer.html': '<!DOCTYPE html><html>'
217 '<link rel="import" href="src/js/polymer/polymer.html">',
218 'polymer|lib/polymer_experimental.html':
219 '<!DOCTYPE html><html>'
220 '<link rel="import" href="polymer.html">',
221 'polymer|lib/polymer.dart':
222 'library polymer;\n'
223 'import "dart:html";\n'
224 'export "package:observe/observe.dart";\n' // for @observable
225 'part "src/loader.dart";\n' // for @CustomTag and @initMethod
226 'part "src/instance.dart";\n', // for @published and @ObserveProperty
227
228 'polymer|lib/src/loader.dart':
229 'part of polymer;\n'
230 'class CustomTag {\n'
231 ' final String tagName;\n'
232 ' const CustomTag(this.tagName);'
233 '}\n'
234 'class InitMethodAnnotation { const InitMethodAnnotation(); }\n'
235 'const initMethod = const InitMethodAnnotation();\n',
236
237 'polymer|lib/src/instance.dart':
238 'part of polymer;\n'
239 'class PublishedProperty { const PublishedProperty(); }\n'
240 'const published = const PublishedProperty();\n'
241 'class ComputedProperty {'
242 ' final String expression;\n'
243 ' const ComputedProperty();'
244 '}\n'
245 'class ObserveProperty { const ObserveProperty(); }\n'
246 'abstract class Polymer {}\n'
247 'class PolymerElement extends HtmlElement with Polymer {}\n',
248
249 'polymer|lib/init.dart':
250 'library polymer.init;\n'
251 'import "package:polymer/polymer.dart";\n'
252 'main() {};\n',
253
254 'observe|lib/observe.dart':
255 'library observe;\n'
256 'export "src/metadata.dart";',
257
258 'observe|lib/src/metadata.dart':
259 'library observe.src.metadata;\n'
260 'class ObservableProperty { const ObservableProperty(); }\n'
261 'const observable = const ObservableProperty();\n',
262 };
OLDNEW
« no previous file with comments | « pkg/polymer/test/build/code_extractor.dart ('k') | pkg/polymer/test/build/import_inliner_test.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698