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

Side by Side Diff: mojo/public/dart/third_party/analyzer/test/src/context/context_test.dart

Issue 1346773002: Stop running pub get at gclient sync time and fix build bugs (Closed) Base URL: git@github.com:domokit/mojo.git@master
Patch Set: Created 5 years, 3 months 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
OLDNEW
(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 test.src.context.context_test;
6
7 import 'dart:async';
8
9 import 'package:analyzer/file_system/memory_file_system.dart';
10 import 'package:analyzer/src/cancelable_future.dart';
11 import 'package:analyzer/src/context/cache.dart';
12 import 'package:analyzer/src/context/context.dart';
13 import 'package:analyzer/src/generated/ast.dart';
14 import 'package:analyzer/src/generated/element.dart';
15 import 'package:analyzer/src/generated/engine.dart'
16 show
17 AnalysisContext,
18 AnalysisContextStatistics,
19 AnalysisDelta,
20 AnalysisEngine,
21 AnalysisErrorInfo,
22 AnalysisLevel,
23 AnalysisNotScheduledError,
24 AnalysisOptions,
25 AnalysisOptionsImpl,
26 AnalysisResult,
27 CacheState,
28 ChangeNotice,
29 ChangeSet,
30 IncrementalAnalysisCache,
31 TimestampedData;
32 import 'package:analyzer/src/generated/error.dart';
33 import 'package:analyzer/src/generated/java_engine.dart';
34 import 'package:analyzer/src/generated/resolver.dart';
35 import 'package:analyzer/src/generated/scanner.dart';
36 import 'package:analyzer/src/generated/source.dart';
37 import 'package:analyzer/src/task/dart.dart';
38 import 'package:analyzer/src/task/html.dart';
39 import 'package:analyzer/task/dart.dart';
40 import 'package:analyzer/task/model.dart';
41 import 'package:html/dom.dart' show Document;
42 import 'package:unittest/unittest.dart';
43 import 'package:watcher/src/utils.dart';
44
45 import '../../generated/engine_test.dart';
46 import '../../generated/test_support.dart';
47 import '../../reflective_tests.dart';
48 import '../../utils.dart';
49 import 'abstract_context.dart';
50
51 main() {
52 initializeTestEnvironment();
53 runReflectiveTests(AnalysisContextImplTest);
54 runReflectiveTests(LimitedInvalidateTest);
55 }
56
57 @reflectiveTest
58 class AnalysisContextImplTest extends AbstractContextTest {
59 Future fail_implicitAnalysisEvents_removed() async {
60 AnalyzedSourcesListener listener = new AnalyzedSourcesListener();
61 context.implicitAnalysisEvents.listen(listener.onData);
62 //
63 // Create a file that references an file that is not explicitly being
64 // analyzed and fully analyze it. Ensure that the listener is told about
65 // the implicitly analyzed file.
66 //
67 Source sourceA = newSource('/a.dart', "library a; import 'b.dart';");
68 Source sourceB = newSource('/b.dart', "library b;");
69 ChangeSet changeSet = new ChangeSet();
70 changeSet.addedSource(sourceA);
71 context.applyChanges(changeSet);
72 context.computeErrors(sourceA);
73 await pumpEventQueue();
74 listener.expectAnalyzed(sourceB);
75 //
76 // Remove the reference and ensure that the listener is told that we're no
77 // longer implicitly analyzing the file.
78 //
79 context.setContents(sourceA, "library a;");
80 context.computeErrors(sourceA);
81 await pumpEventQueue();
82 listener.expectNotAnalyzed(sourceB);
83 }
84
85 void fail_performAnalysisTask_importedLibraryDelete_html() {
86 // NOTE: This was failing before converting to the new task model.
87 Source htmlSource = addSource(
88 "/page.html",
89 r'''
90 <html><body><script type="application/dart">
91 import 'libB.dart';
92 main() {print('hello dart');}
93 </script></body></html>''');
94 Source libBSource = addSource("/libB.dart", "library libB;");
95 _analyzeAll_assertFinished();
96 context.computeErrors(htmlSource);
97 expect(
98 context.getResolvedCompilationUnit2(libBSource, libBSource), isNotNull,
99 reason: "libB resolved 1");
100 expect(!_hasAnalysisErrorWithErrorSeverity(context.getErrors(htmlSource)),
101 isTrue,
102 reason: "htmlSource doesn't have errors");
103 // remove libB.dart content and analyze
104 context.setContents(libBSource, null);
105 _analyzeAll_assertFinished();
106 context.computeErrors(htmlSource);
107 AnalysisErrorInfo errors = context.getErrors(htmlSource);
108 expect(_hasAnalysisErrorWithErrorSeverity(errors), isTrue,
109 reason: "htmlSource has an error");
110 }
111
112 void fail_recordLibraryElements() {
113 fail("Implement this");
114 }
115
116 @override
117 void tearDown() {
118 context = null;
119 sourceFactory = null;
120 super.tearDown();
121 }
122
123 Future test_applyChanges_add() {
124 SourcesChangedListener listener = new SourcesChangedListener();
125 context.onSourcesChanged.listen(listener.onData);
126 expect(context.sourcesNeedingProcessing, isEmpty);
127 Source source = newSource('/test.dart');
128 ChangeSet changeSet = new ChangeSet();
129 changeSet.addedSource(source);
130 context.applyChanges(changeSet);
131 expect(context.sourcesNeedingProcessing, contains(source));
132 return pumpEventQueue().then((_) {
133 listener.assertEvent(wereSourcesAdded: true);
134 listener.assertNoMoreEvents();
135 });
136 }
137
138 Future test_applyChanges_change() {
139 SourcesChangedListener listener = new SourcesChangedListener();
140 context.onSourcesChanged.listen(listener.onData);
141 expect(context.sourcesNeedingProcessing, isEmpty);
142 Source source = newSource('/test.dart');
143 ChangeSet changeSet1 = new ChangeSet();
144 changeSet1.addedSource(source);
145 context.applyChanges(changeSet1);
146 expect(context.sourcesNeedingProcessing, contains(source));
147 Source source2 = newSource('/test2.dart');
148 ChangeSet changeSet2 = new ChangeSet();
149 changeSet2.addedSource(source2);
150 changeSet2.changedSource(source);
151 context.applyChanges(changeSet2);
152 return pumpEventQueue().then((_) {
153 listener.assertEvent(wereSourcesAdded: true);
154 listener.assertEvent(wereSourcesAdded: true, changedSources: [source]);
155 listener.assertNoMoreEvents();
156 });
157 }
158
159 Future test_applyChanges_change_content() {
160 SourcesChangedListener listener = new SourcesChangedListener();
161 context.onSourcesChanged.listen(listener.onData);
162 expect(context.sourcesNeedingProcessing, isEmpty);
163 Source source = newSource('/test.dart');
164 ChangeSet changeSet1 = new ChangeSet();
165 changeSet1.addedSource(source);
166 context.applyChanges(changeSet1);
167 expect(context.sourcesNeedingProcessing, contains(source));
168 Source source2 = newSource('/test2.dart');
169 ChangeSet changeSet2 = new ChangeSet();
170 changeSet2.addedSource(source2);
171 changeSet2.changedContent(source, 'library test;');
172 context.applyChanges(changeSet2);
173 return pumpEventQueue().then((_) {
174 listener.assertEvent(wereSourcesAdded: true);
175 listener.assertEvent(wereSourcesAdded: true, changedSources: [source]);
176 listener.assertNoMoreEvents();
177 });
178 }
179
180 void test_applyChanges_change_flush_element() {
181 Source librarySource = addSource(
182 "/lib.dart",
183 r'''
184 library lib;
185 int a = 0;''');
186 expect(context.computeLibraryElement(librarySource), isNotNull);
187 context.setContents(
188 librarySource,
189 r'''
190 library lib;
191 int aa = 0;''');
192 expect(context.getLibraryElement(librarySource), isNull);
193 }
194
195 Future test_applyChanges_change_multiple() {
196 SourcesChangedListener listener = new SourcesChangedListener();
197 context.onSourcesChanged.listen(listener.onData);
198 String libraryContents1 = r'''
199 library lib;
200 part 'part.dart';
201 int a = 0;''';
202 Source librarySource = addSource("/lib.dart", libraryContents1);
203 String partContents1 = r'''
204 part of lib;
205 int b = a;''';
206 Source partSource = addSource("/part.dart", partContents1);
207 context.computeLibraryElement(librarySource);
208 String libraryContents2 = r'''
209 library lib;
210 part 'part.dart';
211 int aa = 0;''';
212 context.setContents(librarySource, libraryContents2);
213 String partContents2 = r'''
214 part of lib;
215 int b = aa;''';
216 context.setContents(partSource, partContents2);
217 context.computeLibraryElement(librarySource);
218 CompilationUnit libraryUnit =
219 context.resolveCompilationUnit2(librarySource, librarySource);
220 expect(libraryUnit, isNotNull);
221 CompilationUnit partUnit =
222 context.resolveCompilationUnit2(partSource, librarySource);
223 expect(partUnit, isNotNull);
224 TopLevelVariableDeclaration declaration =
225 libraryUnit.declarations[0] as TopLevelVariableDeclaration;
226 Element declarationElement = declaration.variables.variables[0].element;
227 TopLevelVariableDeclaration use =
228 partUnit.declarations[0] as TopLevelVariableDeclaration;
229 Element useElement = (use.variables.variables[0].initializer
230 as SimpleIdentifier).staticElement;
231 expect((useElement as PropertyAccessorElement).variable,
232 same(declarationElement));
233 return pumpEventQueue().then((_) {
234 listener.assertEvent(wereSourcesAdded: true);
235 listener.assertEvent(wereSourcesAdded: true);
236 listener.assertEvent(changedSources: [librarySource]);
237 listener.assertEvent(changedSources: [partSource]);
238 listener.assertNoMoreEvents();
239 });
240 }
241
242 Future test_applyChanges_change_range() {
243 SourcesChangedListener listener = new SourcesChangedListener();
244 context.onSourcesChanged.listen(listener.onData);
245 expect(context.sourcesNeedingProcessing, isEmpty);
246 Source source = newSource('/test.dart');
247 ChangeSet changeSet1 = new ChangeSet();
248 changeSet1.addedSource(source);
249 context.applyChanges(changeSet1);
250 expect(context.sourcesNeedingProcessing, contains(source));
251 Source source2 = newSource('/test2.dart');
252 ChangeSet changeSet2 = new ChangeSet();
253 changeSet2.addedSource(source2);
254 changeSet2.changedRange(source, 'library test;', 0, 0, 13);
255 context.applyChanges(changeSet2);
256 return pumpEventQueue().then((_) {
257 listener.assertEvent(wereSourcesAdded: true);
258 listener.assertEvent(wereSourcesAdded: true, changedSources: [source]);
259 listener.assertNoMoreEvents();
260 });
261 }
262
263 void test_applyChanges_empty() {
264 context.applyChanges(new ChangeSet());
265 expect(context.performAnalysisTask().changeNotices, isNull);
266 }
267
268 void test_applyChanges_overriddenSource() {
269 // Note: addSource adds the source to the contentCache.
270 Source source = addSource("/test.dart", "library test;");
271 context.computeErrors(source);
272 while (!context.sourcesNeedingProcessing.isEmpty) {
273 context.performAnalysisTask();
274 }
275 // Adding the source as a changedSource should have no effect since
276 // it is already overridden in the content cache.
277 ChangeSet changeSet = new ChangeSet();
278 changeSet.changedSource(source);
279 context.applyChanges(changeSet);
280 expect(context.sourcesNeedingProcessing, hasLength(0));
281 }
282
283 Future test_applyChanges_remove() {
284 SourcesChangedListener listener = new SourcesChangedListener();
285 context.onSourcesChanged.listen(listener.onData);
286 String libAContents = r'''
287 library libA;
288 import 'libB.dart';''';
289 Source libA = addSource("/libA.dart", libAContents);
290 String libBContents = "library libB;";
291 Source libB = addSource("/libB.dart", libBContents);
292 LibraryElement libAElement = context.computeLibraryElement(libA);
293 expect(libAElement, isNotNull);
294 List<LibraryElement> importedLibraries = libAElement.importedLibraries;
295 expect(importedLibraries, hasLength(2));
296 context.computeErrors(libA);
297 context.computeErrors(libB);
298 expect(context.sourcesNeedingProcessing, hasLength(0));
299 context.setContents(libB, null);
300 _removeSource(libB);
301 List<Source> sources = context.sourcesNeedingProcessing;
302 expect(sources, hasLength(1));
303 expect(sources[0], same(libA));
304 libAElement = context.computeLibraryElement(libA);
305 importedLibraries = libAElement.importedLibraries;
306 expect(importedLibraries, hasLength(1));
307 return pumpEventQueue().then((_) {
308 listener.assertEvent(wereSourcesAdded: true);
309 listener.assertEvent(wereSourcesAdded: true);
310 listener.assertEvent(wereSourcesRemovedOrDeleted: true);
311 listener.assertNoMoreEvents();
312 });
313 }
314
315 /**
316 * IDEA uses the following scenario:
317 * 1. Add overlay.
318 * 2. Change overlay.
319 * 3. If the contents of the document buffer is the same as the contents
320 * of the file, remove overlay.
321 * So, we need to try to use incremental resolution for removing overlays too.
322 */
323 void test_applyChanges_remove_incremental() {
324 MemoryResourceProvider resourceProvider = new MemoryResourceProvider();
325 Source source = resourceProvider
326 .newFile(
327 '/test.dart',
328 r'''
329 main() {
330 print(1);
331 }
332 ''')
333 .createSource();
334 context.analysisOptions = new AnalysisOptionsImpl()..incremental = true;
335 context.applyChanges(new ChangeSet()..addedSource(source));
336 // remember compilation unit
337 _analyzeAll_assertFinished();
338 CompilationUnit unit = context.getResolvedCompilationUnit2(source, source);
339 // add overlay
340 context.setContents(
341 source,
342 r'''
343 main() {
344 print(12);
345 }
346 ''');
347 _analyzeAll_assertFinished();
348 expect(context.getResolvedCompilationUnit2(source, source), unit);
349 // remove overlay
350 context.setContents(source, null);
351 context.validateCacheConsistency();
352 _analyzeAll_assertFinished();
353 expect(context.getResolvedCompilationUnit2(source, source), unit);
354 }
355
356 Future test_applyChanges_removeContainer() {
357 SourcesChangedListener listener = new SourcesChangedListener();
358 context.onSourcesChanged.listen(listener.onData);
359 String libAContents = r'''
360 library libA;
361 import 'libB.dart';''';
362 Source libA = addSource("/libA.dart", libAContents);
363 String libBContents = "library libB;";
364 Source libB = addSource("/libB.dart", libBContents);
365 context.computeLibraryElement(libA);
366 context.computeErrors(libA);
367 context.computeErrors(libB);
368 expect(context.sourcesNeedingProcessing, hasLength(0));
369 ChangeSet changeSet = new ChangeSet();
370 SourceContainer removedContainer =
371 new _AnalysisContextImplTest_test_applyChanges_removeContainer(libB);
372 changeSet.removedContainer(removedContainer);
373 context.applyChanges(changeSet);
374 List<Source> sources = context.sourcesNeedingProcessing;
375 expect(sources, hasLength(1));
376 expect(sources[0], same(libA));
377 return pumpEventQueue().then((_) {
378 listener.assertEvent(wereSourcesAdded: true);
379 listener.assertEvent(wereSourcesAdded: true);
380 listener.assertEvent(wereSourcesRemovedOrDeleted: true);
381 listener.assertNoMoreEvents();
382 });
383 }
384
385 void test_computeDocumentationComment_block() {
386 String comment = "/** Comment */";
387 Source source = addSource(
388 "/test.dart",
389 """
390 $comment
391 class A {}""");
392 LibraryElement libraryElement = context.computeLibraryElement(source);
393 expect(libraryElement, isNotNull);
394 ClassElement classElement = libraryElement.definingCompilationUnit.types[0];
395 expect(libraryElement, isNotNull);
396 expect(context.computeDocumentationComment(classElement), comment);
397 }
398
399 void test_computeDocumentationComment_none() {
400 Source source = addSource("/test.dart", "class A {}");
401 LibraryElement libraryElement = context.computeLibraryElement(source);
402 expect(libraryElement, isNotNull);
403 ClassElement classElement = libraryElement.definingCompilationUnit.types[0];
404 expect(libraryElement, isNotNull);
405 expect(context.computeDocumentationComment(classElement), isNull);
406 }
407
408 void test_computeDocumentationComment_null() {
409 expect(context.computeDocumentationComment(null), isNull);
410 }
411
412 void test_computeDocumentationComment_singleLine_multiple_EOL_n() {
413 String comment = "/// line 1\n/// line 2\n/// line 3\n";
414 Source source = addSource("/test.dart", "${comment}class A {}");
415 LibraryElement libraryElement = context.computeLibraryElement(source);
416 expect(libraryElement, isNotNull);
417 ClassElement classElement = libraryElement.definingCompilationUnit.types[0];
418 expect(libraryElement, isNotNull);
419 String actual = context.computeDocumentationComment(classElement);
420 expect(actual, "/// line 1\n/// line 2\n/// line 3");
421 }
422
423 void test_computeDocumentationComment_singleLine_multiple_EOL_rn() {
424 String comment = "/// line 1\r\n/// line 2\r\n/// line 3\r\n";
425 Source source = addSource("/test.dart", "${comment}class A {}");
426 LibraryElement libraryElement = context.computeLibraryElement(source);
427 expect(libraryElement, isNotNull);
428 ClassElement classElement = libraryElement.definingCompilationUnit.types[0];
429 expect(libraryElement, isNotNull);
430 String actual = context.computeDocumentationComment(classElement);
431 expect(actual, "/// line 1\n/// line 2\n/// line 3");
432 }
433
434 void test_computeErrors_dart_none() {
435 Source source = addSource("/lib.dart", "library lib;");
436 List<AnalysisError> errors = context.computeErrors(source);
437 expect(errors, hasLength(0));
438 }
439
440 void test_computeErrors_dart_part() {
441 Source librarySource =
442 addSource("/lib.dart", "library lib; part 'part.dart';");
443 Source partSource = addSource("/part.dart", "part of 'lib';");
444 context.parseCompilationUnit(librarySource);
445 List<AnalysisError> errors = context.computeErrors(partSource);
446 expect(errors, isNotNull);
447 expect(errors.length > 0, isTrue);
448 }
449
450 void test_computeErrors_dart_some() {
451 Source source = addSource("/lib.dart", "library 'lib';");
452 List<AnalysisError> errors = context.computeErrors(source);
453 expect(errors, isNotNull);
454 expect(errors.length > 0, isTrue);
455 }
456
457 void test_computeErrors_html_none() {
458 Source source = addSource("/test.html", "<!DOCTYPE html><html></html>");
459 List<AnalysisError> errors = context.computeErrors(source);
460 expect(errors, hasLength(0));
461 }
462
463 void test_computeExportedLibraries_none() {
464 Source source = addSource("/test.dart", "library test;");
465 expect(context.computeExportedLibraries(source), hasLength(0));
466 }
467
468 void test_computeExportedLibraries_some() {
469 // addSource("/lib1.dart", "library lib1;");
470 // addSource("/lib2.dart", "library lib2;");
471 Source source = addSource(
472 "/test.dart", "library test; export 'lib1.dart'; export 'lib2.dart';");
473 expect(context.computeExportedLibraries(source), hasLength(2));
474 }
475
476 void test_computeImportedLibraries_none() {
477 Source source = addSource("/test.dart", "library test;");
478 expect(context.computeImportedLibraries(source), hasLength(0));
479 }
480
481 void test_computeImportedLibraries_some() {
482 Source source = addSource(
483 "/test.dart", "library test; import 'lib1.dart'; import 'lib2.dart';");
484 expect(context.computeImportedLibraries(source), hasLength(2));
485 }
486
487 void test_computeKindOf_html() {
488 Source source = addSource("/test.html", "");
489 expect(context.computeKindOf(source), same(SourceKind.HTML));
490 }
491
492 void test_computeKindOf_library() {
493 Source source = addSource("/test.dart", "library lib;");
494 expect(context.computeKindOf(source), same(SourceKind.LIBRARY));
495 }
496
497 void test_computeKindOf_libraryAndPart() {
498 Source source = addSource("/test.dart", "library lib; part of lib;");
499 expect(context.computeKindOf(source), same(SourceKind.LIBRARY));
500 }
501
502 void test_computeKindOf_part() {
503 Source source = addSource("/test.dart", "part of lib;");
504 expect(context.computeKindOf(source), same(SourceKind.PART));
505 }
506
507 void test_computeLibraryElement() {
508 Source source = addSource("/test.dart", "library lib;");
509 LibraryElement element = context.computeLibraryElement(source);
510 expect(element, isNotNull);
511 }
512
513 void test_computeLineInfo_dart() {
514 Source source = addSource(
515 "/test.dart",
516 r'''
517 library lib;
518
519 main() {}''');
520 LineInfo info = context.computeLineInfo(source);
521 expect(info, isNotNull);
522 }
523
524 void test_computeLineInfo_html() {
525 Source source = addSource(
526 "/test.html",
527 r'''
528 <html>
529 <body>
530 <h1>A</h1>
531 </body>
532 </html>''');
533 LineInfo info = context.computeLineInfo(source);
534 expect(info, isNotNull);
535 }
536
537 Future test_computeResolvedCompilationUnitAsync() {
538 Source source = addSource("/lib.dart", "library lib;");
539 // Complete all pending analysis tasks and flush the AST so that it won't
540 // be available immediately.
541 _performPendingAnalysisTasks();
542 _flushAst(source);
543 bool completed = false;
544 context
545 .computeResolvedCompilationUnitAsync(source, source)
546 .then((CompilationUnit unit) {
547 expect(unit, isNotNull);
548 completed = true;
549 });
550 return pumpEventQueue().then((_) {
551 expect(completed, isFalse);
552 _performPendingAnalysisTasks();
553 }).then((_) => pumpEventQueue()).then((_) {
554 expect(completed, isTrue);
555 });
556 }
557
558 Future test_computeResolvedCompilationUnitAsync_afterDispose() {
559 Source source = addSource("/lib.dart", "library lib;");
560 // Complete all pending analysis tasks and flush the AST so that it won't
561 // be available immediately.
562 _performPendingAnalysisTasks();
563 _flushAst(source);
564 // Dispose of the context.
565 context.dispose();
566 // Any attempt to start an asynchronous computation should return a future
567 // which completes with error.
568 CancelableFuture<CompilationUnit> future =
569 context.computeResolvedCompilationUnitAsync(source, source);
570 bool completed = false;
571 future.then((CompilationUnit unit) {
572 fail('Future should have completed with error');
573 }, onError: (error) {
574 expect(error, new isInstanceOf<AnalysisNotScheduledError>());
575 completed = true;
576 });
577 return pumpEventQueue().then((_) {
578 expect(completed, isTrue);
579 });
580 }
581
582 Future test_computeResolvedCompilationUnitAsync_cancel() {
583 Source source = addSource("/lib.dart", "library lib;");
584 // Complete all pending analysis tasks and flush the AST so that it won't
585 // be available immediately.
586 _performPendingAnalysisTasks();
587 _flushAst(source);
588 CancelableFuture<CompilationUnit> future =
589 context.computeResolvedCompilationUnitAsync(source, source);
590 bool completed = false;
591 future.then((CompilationUnit unit) {
592 fail('Future should have been canceled');
593 }, onError: (error) {
594 expect(error, new isInstanceOf<FutureCanceledError>());
595 completed = true;
596 });
597 expect(completed, isFalse);
598 expect(context.pendingFutureSources_forTesting, isNotEmpty);
599 future.cancel();
600 expect(context.pendingFutureSources_forTesting, isEmpty);
601 return pumpEventQueue().then((_) {
602 expect(completed, isTrue);
603 expect(context.pendingFutureSources_forTesting, isEmpty);
604 });
605 }
606
607 Future test_computeResolvedCompilationUnitAsync_dispose() {
608 Source source = addSource("/lib.dart", "library lib;");
609 // Complete all pending analysis tasks and flush the AST so that it won't
610 // be available immediately.
611 _performPendingAnalysisTasks();
612 _flushAst(source);
613 bool completed = false;
614 CancelableFuture<CompilationUnit> future =
615 context.computeResolvedCompilationUnitAsync(source, source);
616 future.then((CompilationUnit unit) {
617 fail('Future should have completed with error');
618 }, onError: (error) {
619 expect(error, new isInstanceOf<AnalysisNotScheduledError>());
620 completed = true;
621 });
622 expect(completed, isFalse);
623 expect(context.pendingFutureSources_forTesting, isNotEmpty);
624 // Disposing of the context should cause all pending futures to complete
625 // with AnalysisNotScheduled, so that no clients are left hanging.
626 context.dispose();
627 expect(context.pendingFutureSources_forTesting, isEmpty);
628 return pumpEventQueue().then((_) {
629 expect(completed, isTrue);
630 expect(context.pendingFutureSources_forTesting, isEmpty);
631 });
632 }
633
634 Future test_computeResolvedCompilationUnitAsync_noCacheEntry() {
635 Source librarySource = addSource("/lib.dart", "library lib;");
636 Source partSource = addSource("/part.dart", "part of foo;");
637 bool completed = false;
638 context
639 .computeResolvedCompilationUnitAsync(partSource, librarySource)
640 .then((CompilationUnit unit) {
641 expect(unit, isNotNull);
642 completed = true;
643 });
644 return pumpEventQueue().then((_) {
645 expect(completed, isFalse);
646 _performPendingAnalysisTasks();
647 }).then((_) => pumpEventQueue()).then((_) {
648 expect(completed, isTrue);
649 });
650 }
651
652 void test_dispose() {
653 expect(context.isDisposed, isFalse);
654 context.dispose();
655 expect(context.isDisposed, isTrue);
656 }
657
658 void test_ensureResolvedDartUnits_definingUnit_hasResolved() {
659 Source source = addSource('/test.dart', '');
660 LibrarySpecificUnit libTarget = new LibrarySpecificUnit(source, source);
661 analysisDriver.computeResult(libTarget, RESOLVED_UNIT);
662 CompilationUnit unit =
663 context.getCacheEntry(libTarget).getValue(RESOLVED_UNIT);
664 List<CompilationUnit> units = context.ensureResolvedDartUnits(source);
665 expect(units, unorderedEquals([unit]));
666 }
667
668 void test_ensureResolvedDartUnits_definingUnit_notResolved() {
669 Source source = addSource('/test.dart', '');
670 LibrarySpecificUnit libTarget = new LibrarySpecificUnit(source, source);
671 analysisDriver.computeResult(libTarget, RESOLVED_UNIT);
672 // flush
673 context
674 .getCacheEntry(libTarget)
675 .setState(RESOLVED_UNIT, CacheState.FLUSHED);
676 // schedule recomputing
677 List<CompilationUnit> units = context.ensureResolvedDartUnits(source);
678 expect(units, isNull);
679 // should be the next result to compute
680 TargetedResult nextResult = context.dartWorkManager.getNextResult();
681 expect(nextResult.target, libTarget);
682 expect(nextResult.result, RESOLVED_UNIT);
683 }
684
685 void test_ensureResolvedDartUnits_partUnit_hasResolved() {
686 Source libSource1 = addSource(
687 '/lib1.dart',
688 r'''
689 library lib;
690 part 'part.dart';
691 ''');
692 Source libSource2 = addSource(
693 '/lib2.dart',
694 r'''
695 library lib;
696 part 'part.dart';
697 ''');
698 Source partSource = addSource(
699 '/part.dart',
700 r'''
701 part of lib;
702 ''');
703 LibrarySpecificUnit partTarget1 =
704 new LibrarySpecificUnit(libSource1, partSource);
705 LibrarySpecificUnit partTarget2 =
706 new LibrarySpecificUnit(libSource2, partSource);
707 analysisDriver.computeResult(partTarget1, RESOLVED_UNIT);
708 analysisDriver.computeResult(partTarget2, RESOLVED_UNIT);
709 CompilationUnit unit1 =
710 context.getCacheEntry(partTarget1).getValue(RESOLVED_UNIT);
711 CompilationUnit unit2 =
712 context.getCacheEntry(partTarget2).getValue(RESOLVED_UNIT);
713 List<CompilationUnit> units = context.ensureResolvedDartUnits(partSource);
714 expect(units, unorderedEquals([unit1, unit2]));
715 }
716
717 void test_ensureResolvedDartUnits_partUnit_notResolved() {
718 Source libSource1 = addSource(
719 '/lib1.dart',
720 r'''
721 library lib;
722 part 'part.dart';
723 ''');
724 Source libSource2 = addSource(
725 '/lib2.dart',
726 r'''
727 library lib;
728 part 'part.dart';
729 ''');
730 Source partSource = addSource(
731 '/part.dart',
732 r'''
733 part of lib;
734 ''');
735 LibrarySpecificUnit partTarget1 =
736 new LibrarySpecificUnit(libSource1, partSource);
737 LibrarySpecificUnit partTarget2 =
738 new LibrarySpecificUnit(libSource2, partSource);
739 analysisDriver.computeResult(partTarget1, RESOLVED_UNIT);
740 analysisDriver.computeResult(partTarget2, RESOLVED_UNIT);
741 // flush
742 context
743 .getCacheEntry(partTarget1)
744 .setState(RESOLVED_UNIT, CacheState.FLUSHED);
745 context
746 .getCacheEntry(partTarget2)
747 .setState(RESOLVED_UNIT, CacheState.FLUSHED);
748 // schedule recomputing
749 List<CompilationUnit> units = context.ensureResolvedDartUnits(partSource);
750 expect(units, isNull);
751 // should be the next result to compute
752 TargetedResult nextResult = context.dartWorkManager.getNextResult();
753 expect(nextResult.target, anyOf(partTarget1, partTarget2));
754 expect(nextResult.result, RESOLVED_UNIT);
755 }
756
757 void test_exists_false() {
758 TestSource source = new TestSource();
759 source.exists2 = false;
760 expect(context.exists(source), isFalse);
761 }
762
763 void test_exists_null() {
764 expect(context.exists(null), isFalse);
765 }
766
767 void test_exists_overridden() {
768 Source source = new TestSource();
769 context.setContents(source, "");
770 expect(context.exists(source), isTrue);
771 }
772
773 void test_exists_true() {
774 expect(context.exists(new AnalysisContextImplTest_Source_exists_true()),
775 isTrue);
776 }
777
778 void test_getAnalysisOptions() {
779 expect(context.analysisOptions, isNotNull);
780 }
781
782 void test_getContents_fromSource() {
783 String content = "library lib;";
784 TimestampedData<String> contents =
785 context.getContents(new TestSource('/test.dart', content));
786 expect(contents.data.toString(), content);
787 }
788
789 void test_getContents_overridden() {
790 String content = "library lib;";
791 Source source = new TestSource();
792 context.setContents(source, content);
793 TimestampedData<String> contents = context.getContents(source);
794 expect(contents.data.toString(), content);
795 }
796
797 void test_getContents_unoverridden() {
798 String content = "library lib;";
799 Source source = new TestSource('/test.dart', content);
800 context.setContents(source, "part of lib;");
801 context.setContents(source, null);
802 TimestampedData<String> contents = context.getContents(source);
803 expect(contents.data.toString(), content);
804 }
805
806 void test_getDeclaredVariables() {
807 expect(context.declaredVariables, isNotNull);
808 }
809
810 void test_getElement() {
811 LibraryElement core =
812 context.computeLibraryElement(sourceFactory.forUri("dart:core"));
813 expect(core, isNotNull);
814 ClassElement classObject =
815 _findClass(core.definingCompilationUnit, "Object");
816 expect(classObject, isNotNull);
817 ElementLocation location = classObject.location;
818 Element element = context.getElement(location);
819 expect(element, same(classObject));
820 }
821
822 void test_getElement_constructor_named() {
823 Source source = addSource(
824 "/lib.dart",
825 r'''
826 class A {
827 A.named() {}
828 }''');
829 _analyzeAll_assertFinished();
830 LibraryElement library = context.computeLibraryElement(source);
831 ClassElement classA = _findClass(library.definingCompilationUnit, "A");
832 ConstructorElement constructor = classA.constructors[0];
833 ElementLocation location = constructor.location;
834 Element element = context.getElement(location);
835 expect(element, same(constructor));
836 }
837
838 void test_getElement_constructor_unnamed() {
839 Source source = addSource(
840 "/lib.dart",
841 r'''
842 class A {
843 A() {}
844 }''');
845 _analyzeAll_assertFinished();
846 LibraryElement library = context.computeLibraryElement(source);
847 ClassElement classA = _findClass(library.definingCompilationUnit, "A");
848 ConstructorElement constructor = classA.constructors[0];
849 ElementLocation location = constructor.location;
850 Element element = context.getElement(location);
851 expect(element, same(constructor));
852 }
853
854 void test_getElement_enum() {
855 Source source = addSource('/test.dart', 'enum MyEnum {A, B, C}');
856 _analyzeAll_assertFinished();
857 LibraryElement library = context.computeLibraryElement(source);
858 ClassElement myEnum = library.definingCompilationUnit.getEnum('MyEnum');
859 ElementLocation location = myEnum.location;
860 Element element = context.getElement(location);
861 expect(element, same(myEnum));
862 }
863
864 void test_getErrors_dart_none() {
865 Source source = addSource("/lib.dart", "library lib;");
866 var errorInfo = context.getErrors(source);
867 expect(errorInfo, isNotNull);
868 List<AnalysisError> errors = errorInfo.errors;
869 expect(errors, hasLength(0));
870 context.computeErrors(source);
871 errors = errorInfo.errors;
872 expect(errors, hasLength(0));
873 }
874
875 void test_getErrors_dart_some() {
876 Source source = addSource("/lib.dart", "library 'lib';");
877 var errorInfo = context.getErrors(source);
878 expect(errorInfo, isNotNull);
879 List<AnalysisError> errors = errorInfo.errors;
880 expect(errors, hasLength(0));
881 errors = context.computeErrors(source);
882 expect(errors, hasLength(1));
883 }
884
885 void test_getErrors_html_none() {
886 Source source = addSource("/test.html", "<html></html>");
887 AnalysisErrorInfo errorInfo = context.getErrors(source);
888 expect(errorInfo, isNotNull);
889 List<AnalysisError> errors = errorInfo.errors;
890 expect(errors, hasLength(0));
891 context.computeErrors(source);
892 errors = errorInfo.errors;
893 expect(errors, hasLength(0));
894 }
895
896 void test_getErrors_html_some() {
897 Source source = addSource(
898 "/test.html",
899 r'''
900 <html><head>
901 <script type='application/dart' src='test.dart'/>
902 </head></html>''');
903 AnalysisErrorInfo errorInfo = context.getErrors(source);
904 expect(errorInfo, isNotNull);
905 List<AnalysisError> errors = errorInfo.errors;
906 expect(errors, hasLength(0));
907 errors = context.computeErrors(source);
908 expect(errors, hasLength(3));
909 }
910
911 void test_getHtmlFilesReferencing_html() {
912 Source htmlSource = addSource(
913 "/test.html",
914 r'''
915 <html><head>
916 <script type='application/dart' src='test.dart'/>
917 <script type='application/dart' src='test.js'/>
918 </head></html>''');
919 Source librarySource = addSource("/test.dart", "library lib;");
920 Source secondHtmlSource = addSource("/test.html", "<html></html>");
921 context.computeLibraryElement(librarySource);
922 List<Source> result = context.getHtmlFilesReferencing(secondHtmlSource);
923 expect(result, hasLength(0));
924 context.parseHtmlDocument(htmlSource);
925 result = context.getHtmlFilesReferencing(secondHtmlSource);
926 expect(result, hasLength(0));
927 }
928
929 void test_getHtmlFilesReferencing_library() {
930 Source htmlSource = addSource(
931 "/test.html",
932 r'''
933 <!DOCTYPE html>
934 <html><head>
935 <script type='application/dart' src='test.dart'/>
936 <script type='application/dart' src='test.js'/>
937 </head></html>''');
938 Source librarySource = addSource("/test.dart", "library lib;");
939 context.computeLibraryElement(librarySource);
940 List<Source> result = context.getHtmlFilesReferencing(librarySource);
941 expect(result, hasLength(0));
942 // Indirectly force the data to be computed.
943 context.computeErrors(htmlSource);
944 result = context.getHtmlFilesReferencing(librarySource);
945 expect(result, hasLength(1));
946 expect(result[0], htmlSource);
947 }
948
949 void test_getHtmlFilesReferencing_part() {
950 Source htmlSource = addSource(
951 "/test.html",
952 r'''
953 <!DOCTYPE html>
954 <html><head>
955 <script type='application/dart' src='test.dart'/>
956 <script type='application/dart' src='test.js'/>
957 </head></html>''');
958 Source librarySource =
959 addSource("/test.dart", "library lib; part 'part.dart';");
960 Source partSource = addSource("/part.dart", "part of lib;");
961 context.computeLibraryElement(librarySource);
962 List<Source> result = context.getHtmlFilesReferencing(partSource);
963 expect(result, hasLength(0));
964 // Indirectly force the data to be computed.
965 context.computeErrors(htmlSource);
966 result = context.getHtmlFilesReferencing(partSource);
967 expect(result, hasLength(1));
968 expect(result[0], htmlSource);
969 }
970
971 void test_getHtmlSources() {
972 List<Source> sources = context.htmlSources;
973 expect(sources, hasLength(0));
974 Source source = addSource("/test.html", "");
975 sources = context.htmlSources;
976 expect(sources, hasLength(1));
977 expect(sources[0], source);
978 }
979
980 void test_getKindOf_html() {
981 Source source = addSource("/test.html", "");
982 expect(context.getKindOf(source), same(SourceKind.HTML));
983 }
984
985 void test_getKindOf_library() {
986 Source source = addSource("/test.dart", "library lib;");
987 expect(context.getKindOf(source), same(SourceKind.UNKNOWN));
988 context.computeKindOf(source);
989 expect(context.getKindOf(source), same(SourceKind.LIBRARY));
990 }
991
992 void test_getKindOf_part() {
993 Source source = addSource("/test.dart", "part of lib;");
994 expect(context.getKindOf(source), same(SourceKind.UNKNOWN));
995 context.computeKindOf(source);
996 expect(context.getKindOf(source), same(SourceKind.PART));
997 }
998
999 void test_getKindOf_unknown() {
1000 Source source = addSource("/test.css", "");
1001 expect(context.getKindOf(source), same(SourceKind.UNKNOWN));
1002 }
1003
1004 void test_getLaunchableClientLibrarySources_doesNotImportHtml() {
1005 Source source = addSource(
1006 "/test.dart",
1007 r'''
1008 main() {}''');
1009 context.computeLibraryElement(source);
1010 List<Source> sources = context.launchableClientLibrarySources;
1011 expect(sources, isEmpty);
1012 }
1013
1014 void test_getLaunchableClientLibrarySources_importsHtml_explicitly() {
1015 List<Source> sources = context.launchableClientLibrarySources;
1016 expect(sources, isEmpty);
1017 Source source = addSource(
1018 "/test.dart",
1019 r'''
1020 import 'dart:html';
1021 main() {}''');
1022 context.computeLibraryElement(source);
1023 sources = context.launchableClientLibrarySources;
1024 expect(sources, unorderedEquals([source]));
1025 }
1026
1027 void test_getLaunchableClientLibrarySources_importsHtml_implicitly() {
1028 List<Source> sources = context.launchableClientLibrarySources;
1029 expect(sources, isEmpty);
1030 addSource(
1031 "/a.dart",
1032 r'''
1033 import 'dart:html';
1034 ''');
1035 Source source = addSource(
1036 "/test.dart",
1037 r'''
1038 import 'a.dart';
1039 main() {}''');
1040 context.computeLibraryElement(source);
1041 sources = context.launchableClientLibrarySources;
1042 expect(sources, unorderedEquals([source]));
1043 }
1044
1045 void test_getLaunchableClientLibrarySources_importsHtml_implicitly2() {
1046 List<Source> sources = context.launchableClientLibrarySources;
1047 expect(sources, isEmpty);
1048 addSource(
1049 "/a.dart",
1050 r'''
1051 export 'dart:html';
1052 ''');
1053 Source source = addSource(
1054 "/test.dart",
1055 r'''
1056 import 'a.dart';
1057 main() {}''');
1058 context.computeLibraryElement(source);
1059 sources = context.launchableClientLibrarySources;
1060 expect(sources, unorderedEquals([source]));
1061 }
1062
1063 void test_getLaunchableServerLibrarySources() {
1064 expect(context.launchableServerLibrarySources, isEmpty);
1065 Source source = addSource("/test.dart", "main() {}");
1066 context.computeLibraryElement(source);
1067 expect(context.launchableServerLibrarySources, unorderedEquals([source]));
1068 }
1069
1070 void test_getLaunchableServerLibrarySources_importsHtml_explicitly() {
1071 Source source = addSource(
1072 "/test.dart",
1073 r'''
1074 import 'dart:html';
1075 main() {}
1076 ''');
1077 context.computeLibraryElement(source);
1078 expect(context.launchableServerLibrarySources, isEmpty);
1079 }
1080
1081 void test_getLaunchableServerLibrarySources_importsHtml_implicitly() {
1082 addSource(
1083 "/imports_html.dart",
1084 r'''
1085 import 'dart:html';
1086 ''');
1087 Source source = addSource(
1088 "/test.dart",
1089 r'''
1090 import 'imports_html.dart';
1091 main() {}''');
1092 context.computeLibraryElement(source);
1093 expect(context.launchableServerLibrarySources, isEmpty);
1094 }
1095
1096 void test_getLaunchableServerLibrarySources_noMain() {
1097 Source source = addSource("/test.dart", '');
1098 context.computeLibraryElement(source);
1099 expect(context.launchableServerLibrarySources, isEmpty);
1100 }
1101
1102 void test_getLibrariesContaining() {
1103 Source librarySource = addSource(
1104 "/lib.dart",
1105 r'''
1106 library lib;
1107 part 'part.dart';''');
1108 Source partSource = addSource("/part.dart", "part of lib;");
1109 context.computeLibraryElement(librarySource);
1110 List<Source> result = context.getLibrariesContaining(librarySource);
1111 expect(result, hasLength(1));
1112 expect(result[0], librarySource);
1113 result = context.getLibrariesContaining(partSource);
1114 expect(result, hasLength(1));
1115 expect(result[0], librarySource);
1116 }
1117
1118 void test_getLibrariesDependingOn() {
1119 Source libASource = addSource("/libA.dart", "library libA;");
1120 addSource("/libB.dart", "library libB;");
1121 Source lib1Source = addSource(
1122 "/lib1.dart",
1123 r'''
1124 library lib1;
1125 import 'libA.dart';
1126 export 'libB.dart';''');
1127 Source lib2Source = addSource(
1128 "/lib2.dart",
1129 r'''
1130 library lib2;
1131 import 'libB.dart';
1132 export 'libA.dart';''');
1133 context.computeLibraryElement(lib1Source);
1134 context.computeLibraryElement(lib2Source);
1135 List<Source> result = context.getLibrariesDependingOn(libASource);
1136 expect(result, unorderedEquals([lib1Source, lib2Source]));
1137 }
1138
1139 void test_getLibrariesReferencedFromHtml() {
1140 Source htmlSource = addSource(
1141 "/test.html",
1142 r'''
1143 <!DOCTYPE html>
1144 <html><head>
1145 <script type='application/dart' src='test.dart'/>
1146 <script type='application/dart' src='test.js'/>
1147 </head></html>''');
1148 Source librarySource = addSource("/test.dart", "library lib;");
1149 context.computeLibraryElement(librarySource);
1150 // Indirectly force the data to be computed.
1151 context.computeErrors(htmlSource);
1152 List<Source> result = context.getLibrariesReferencedFromHtml(htmlSource);
1153 expect(result, hasLength(1));
1154 expect(result[0], librarySource);
1155 }
1156
1157 void test_getLibrariesReferencedFromHtml_none() {
1158 Source htmlSource = addSource(
1159 "/test.html",
1160 r'''
1161 <html><head>
1162 <script type='application/dart' src='test.js'/>
1163 </head></html>''');
1164 addSource("/test.dart", "library lib;");
1165 context.parseHtmlDocument(htmlSource);
1166 List<Source> result = context.getLibrariesReferencedFromHtml(htmlSource);
1167 expect(result, hasLength(0));
1168 }
1169
1170 void test_getLibraryElement() {
1171 Source source = addSource("/test.dart", "library lib;");
1172 LibraryElement element = context.getLibraryElement(source);
1173 expect(element, isNull);
1174 context.computeLibraryElement(source);
1175 element = context.getLibraryElement(source);
1176 expect(element, isNotNull);
1177 }
1178
1179 void test_getLibrarySources() {
1180 List<Source> sources = context.librarySources;
1181 int originalLength = sources.length;
1182 Source source = addSource("/test.dart", "library lib;");
1183 context.computeKindOf(source);
1184 sources = context.librarySources;
1185 expect(sources, hasLength(originalLength + 1));
1186 for (Source returnedSource in sources) {
1187 if (returnedSource == source) {
1188 return;
1189 }
1190 }
1191 fail("The added source was not in the list of library sources");
1192 }
1193
1194 void test_getLineInfo() {
1195 Source source = addSource(
1196 "/test.dart",
1197 r'''
1198 library lib;
1199
1200 main() {}''');
1201 LineInfo info = context.getLineInfo(source);
1202 expect(info, isNull);
1203 context.parseCompilationUnit(source);
1204 info = context.getLineInfo(source);
1205 expect(info, isNotNull);
1206 }
1207
1208 void test_getModificationStamp_fromSource() {
1209 int stamp = 42;
1210 expect(
1211 context.getModificationStamp(
1212 new AnalysisContextImplTest_Source_getModificationStamp_fromSource(
1213 stamp)),
1214 stamp);
1215 }
1216
1217 void test_getModificationStamp_overridden() {
1218 int stamp = 42;
1219 Source source =
1220 new AnalysisContextImplTest_Source_getModificationStamp_overridden(
1221 stamp);
1222 context.setContents(source, "");
1223 expect(stamp != context.getModificationStamp(source), isTrue);
1224 }
1225
1226 void test_getPublicNamespace_element() {
1227 Source source = addSource("/test.dart", "class A {}");
1228 LibraryElement library = context.computeLibraryElement(source);
1229 expect(library, isNotNull);
1230 Namespace namespace = context.getPublicNamespace(library);
1231 expect(namespace, isNotNull);
1232 EngineTestCase.assertInstanceOf(
1233 (obj) => obj is ClassElement, ClassElement, namespace.get("A"));
1234 }
1235
1236 void test_getResolvedCompilationUnit_library() {
1237 Source source = addSource("/lib.dart", "library libb;");
1238 LibraryElement library = context.computeLibraryElement(source);
1239 context.computeErrors(source); // Force the resolved unit to be built.
1240 expect(context.getResolvedCompilationUnit(source, library), isNotNull);
1241 context.setContents(source, "library lib;");
1242 expect(context.getResolvedCompilationUnit(source, library), isNull);
1243 }
1244
1245 void test_getResolvedCompilationUnit_library_null() {
1246 Source source = addSource("/lib.dart", "library lib;");
1247 expect(context.getResolvedCompilationUnit(source, null), isNull);
1248 }
1249
1250 void test_getResolvedCompilationUnit_source_dart() {
1251 Source source = addSource("/lib.dart", "library lib;");
1252 expect(context.getResolvedCompilationUnit2(source, source), isNull);
1253 context.resolveCompilationUnit2(source, source);
1254 expect(context.getResolvedCompilationUnit2(source, source), isNotNull);
1255 }
1256
1257 void test_getResolvedCompilationUnit_source_html() {
1258 Source source = addSource("/test.html", "<html></html>");
1259 expect(context.getResolvedCompilationUnit2(source, source), isNull);
1260 expect(context.resolveCompilationUnit2(source, source), isNull);
1261 expect(context.getResolvedCompilationUnit2(source, source), isNull);
1262 }
1263
1264 void test_getSourceFactory() {
1265 expect(context.sourceFactory, same(sourceFactory));
1266 }
1267
1268 void test_getSourcesWithFullName() {
1269 String filePath = '/foo/lib/file.dart';
1270 List<Source> expected = <Source>[];
1271 ChangeSet changeSet = new ChangeSet();
1272
1273 TestSourceWithUri source1 =
1274 new TestSourceWithUri(filePath, Uri.parse('file://$filePath'));
1275 expected.add(source1);
1276 changeSet.addedSource(source1);
1277
1278 TestSourceWithUri source2 =
1279 new TestSourceWithUri(filePath, Uri.parse('package:foo/file.dart'));
1280 expected.add(source2);
1281 changeSet.addedSource(source2);
1282
1283 context.applyChanges(changeSet);
1284 expect(context.getSourcesWithFullName(filePath), unorderedEquals(expected));
1285 }
1286
1287 void test_getStatistics() {
1288 AnalysisContextStatistics statistics = context.statistics;
1289 expect(statistics, isNotNull);
1290 // The following lines are fragile.
1291 // The values depend on the number of libraries in the SDK.
1292 // assertLength(0, statistics.getCacheRows());
1293 // assertLength(0, statistics.getExceptions());
1294 // assertLength(0, statistics.getSources());
1295 }
1296
1297 void test_handleContentsChanged() {
1298 ContentCache contentCache = new ContentCache();
1299 context.contentCache = contentCache;
1300 String oldContents = 'foo() {}';
1301 String newContents = 'bar() {}';
1302 // old contents
1303 Source source = addSource("/test.dart", oldContents);
1304 _analyzeAll_assertFinished();
1305 expect(context.getResolvedCompilationUnit2(source, source), isNotNull);
1306 // new contents
1307 contentCache.setContents(source, newContents);
1308 context.handleContentsChanged(source, oldContents, newContents, true);
1309 // there is some work to do
1310 AnalysisResult analysisResult = context.performAnalysisTask();
1311 expect(analysisResult.changeNotices, isNotNull);
1312 }
1313
1314 Future test_implicitAnalysisEvents_added() async {
1315 AnalyzedSourcesListener listener = new AnalyzedSourcesListener();
1316 context.implicitAnalysisEvents.listen(listener.onData);
1317 //
1318 // Create a file that references an file that is not explicitly being
1319 // analyzed and fully analyze it. Ensure that the listener is told about
1320 // the implicitly analyzed file.
1321 //
1322 Source sourceA = newSource('/a.dart', "library a; import 'b.dart';");
1323 Source sourceB = newSource('/b.dart', "library b;");
1324 ChangeSet changeSet = new ChangeSet();
1325 changeSet.addedSource(sourceA);
1326 context.applyChanges(changeSet);
1327 context.computeErrors(sourceA);
1328 await pumpEventQueue();
1329 listener.expectAnalyzed(sourceB);
1330 }
1331
1332 void test_isClientLibrary_dart() {
1333 Source source = addSource(
1334 "/test.dart",
1335 r'''
1336 import 'dart:html';
1337
1338 main() {}''');
1339 expect(context.isClientLibrary(source), isFalse);
1340 expect(context.isServerLibrary(source), isFalse);
1341 context.computeLibraryElement(source);
1342 expect(context.isClientLibrary(source), isTrue);
1343 expect(context.isServerLibrary(source), isFalse);
1344 }
1345
1346 void test_isClientLibrary_html() {
1347 Source source = addSource("/test.html", "<html></html>");
1348 expect(context.isClientLibrary(source), isFalse);
1349 }
1350
1351 void test_isServerLibrary_dart() {
1352 Source source = addSource(
1353 "/test.dart",
1354 r'''
1355 library lib;
1356
1357 main() {}''');
1358 expect(context.isClientLibrary(source), isFalse);
1359 expect(context.isServerLibrary(source), isFalse);
1360 context.computeLibraryElement(source);
1361 expect(context.isClientLibrary(source), isFalse);
1362 expect(context.isServerLibrary(source), isTrue);
1363 }
1364
1365 void test_isServerLibrary_html() {
1366 Source source = addSource("/test.html", "<html></html>");
1367 expect(context.isServerLibrary(source), isFalse);
1368 }
1369
1370 void test_parseCompilationUnit_errors() {
1371 Source source = addSource("/lib.dart", "library {");
1372 CompilationUnit compilationUnit = context.parseCompilationUnit(source);
1373 expect(compilationUnit, isNotNull);
1374 var errorInfo = context.getErrors(source);
1375 expect(errorInfo, isNotNull);
1376 List<AnalysisError> errors = errorInfo.errors;
1377 expect(errors, isNotNull);
1378 expect(errors.length > 0, isTrue);
1379 }
1380
1381 void test_parseCompilationUnit_exception() {
1382 Source source = _addSourceWithException("/test.dart");
1383 try {
1384 context.parseCompilationUnit(source);
1385 fail("Expected AnalysisException");
1386 } on AnalysisException {
1387 // Expected
1388 }
1389 }
1390
1391 void test_parseCompilationUnit_html() {
1392 Source source = addSource("/test.html", "<html></html>");
1393 expect(context.parseCompilationUnit(source), isNull);
1394 }
1395
1396 void test_parseCompilationUnit_noErrors() {
1397 Source source = addSource("/lib.dart", "library lib;");
1398 CompilationUnit compilationUnit = context.parseCompilationUnit(source);
1399 expect(compilationUnit, isNotNull);
1400 AnalysisErrorInfo errorInfo = context.getErrors(source);
1401 expect(errorInfo, isNotNull);
1402 expect(errorInfo.errors, hasLength(0));
1403 }
1404
1405 void test_parseCompilationUnit_nonExistentSource() {
1406 Source source = newSource('/test.dart');
1407 resourceProvider.deleteFile('/test.dart');
1408 try {
1409 context.parseCompilationUnit(source);
1410 fail("Expected AnalysisException because file does not exist");
1411 } on AnalysisException {
1412 // Expected result
1413 }
1414 }
1415
1416 void test_parseHtmlDocument() {
1417 Source source = addSource("/lib.html", "<!DOCTYPE html><html></html>");
1418 Document document = context.parseHtmlDocument(source);
1419 expect(document, isNotNull);
1420 }
1421
1422 void test_parseHtmlUnit_resolveDirectives() {
1423 Source libSource = addSource(
1424 "/lib.dart",
1425 r'''
1426 library lib;
1427 class ClassA {}''');
1428 Source source = addSource(
1429 "/lib.html",
1430 r'''
1431 <!DOCTYPE html>
1432 <html>
1433 <head>
1434 <script type='application/dart'>
1435 import 'lib.dart';
1436 ClassA v = null;
1437 </script>
1438 </head>
1439 <body>
1440 </body>
1441 </html>''');
1442 Document document = context.parseHtmlDocument(source);
1443 expect(document, isNotNull);
1444 List<DartScript> scripts = context.computeResult(source, DART_SCRIPTS);
1445 expect(scripts, hasLength(1));
1446 CompilationUnit unit = context.computeResult(scripts[0], PARSED_UNIT);
1447 ImportDirective importNode = unit.directives[0] as ImportDirective;
1448 expect(importNode.uriContent, isNotNull);
1449 expect(importNode.source, libSource);
1450 }
1451
1452 void test_performAnalysisTask_addPart() {
1453 Source libSource = addSource(
1454 "/lib.dart",
1455 r'''
1456 library lib;
1457 part 'part.dart';''');
1458 // run all tasks without part
1459 _analyzeAll_assertFinished();
1460 expect(_hasAnalysisErrorWithErrorSeverity(context.getErrors(libSource)),
1461 isTrue,
1462 reason: "lib has errors");
1463 // add part and run all tasks
1464 Source partSource = addSource(
1465 "/part.dart",
1466 r'''
1467 part of lib;
1468 ''');
1469 _analyzeAll_assertFinished();
1470 // "libSource" should be here
1471 List<Source> librariesWithPart = context.getLibrariesContaining(partSource);
1472 expect(librariesWithPart, unorderedEquals([libSource]));
1473 expect(_hasAnalysisErrorWithErrorSeverity(context.getErrors(libSource)),
1474 isFalse,
1475 reason: "lib doesn't have errors");
1476 expect(
1477 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1478 reason: "part resolved");
1479 }
1480
1481 void test_performAnalysisTask_changeLibraryContents() {
1482 Source libSource =
1483 addSource("/test.dart", "library lib; part 'test-part.dart';");
1484 Source partSource = addSource("/test-part.dart", "part of lib;");
1485 _analyzeAll_assertFinished();
1486 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1487 reason: "library resolved 1");
1488 expect(
1489 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1490 reason: "part resolved 1");
1491 // update and analyze #1
1492 context.setContents(libSource, "library lib;");
1493 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNull,
1494 reason: "library changed 2");
1495 expect(context.getResolvedCompilationUnit2(partSource, libSource), isNull,
1496 reason: "part changed 2");
1497 _analyzeAll_assertFinished();
1498 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1499 reason: "library resolved 2");
1500 expect(context.getResolvedCompilationUnit2(partSource, libSource), isNull,
1501 reason: "part resolved 2");
1502 // update and analyze #2
1503 context.setContents(libSource, "library lib; part 'test-part.dart';");
1504 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNull,
1505 reason: "library changed 3");
1506 expect(context.getResolvedCompilationUnit2(partSource, libSource), isNull,
1507 reason: "part changed 3");
1508 _analyzeAll_assertFinished();
1509 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1510 reason: "library resolved 2");
1511 expect(
1512 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1513 reason: "part resolved 3");
1514 }
1515
1516 void test_performAnalysisTask_changeLibraryThenPartContents() {
1517 Source libSource =
1518 addSource("/test.dart", "library lib; part 'test-part.dart';");
1519 Source partSource = addSource("/test-part.dart", "part of lib;");
1520 _analyzeAll_assertFinished();
1521 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1522 reason: "library resolved 1");
1523 expect(
1524 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1525 reason: "part resolved 1");
1526 // update and analyze #1
1527 context.setContents(libSource, "library lib;");
1528 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNull,
1529 reason: "library changed 2");
1530 expect(context.getResolvedCompilationUnit2(partSource, libSource), isNull,
1531 reason: "part changed 2");
1532 _analyzeAll_assertFinished();
1533 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1534 reason: "library resolved 2");
1535 expect(context.getResolvedCompilationUnit2(partSource, libSource), isNull,
1536 reason: "part resolved 2");
1537 // update and analyze #2
1538 context.setContents(partSource, "part of lib; // 1");
1539 // Assert that changing the part's content does not effect the library
1540 // now that it is no longer part of that library
1541 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1542 reason: "library changed 3");
1543 expect(context.getResolvedCompilationUnit2(partSource, libSource), isNull,
1544 reason: "part changed 3");
1545 _analyzeAll_assertFinished();
1546 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1547 reason: "library resolved 3");
1548 expect(context.getResolvedCompilationUnit2(partSource, libSource), isNull,
1549 reason: "part resolved 3");
1550 }
1551
1552 void test_performAnalysisTask_changePartContents_makeItAPart() {
1553 Source libSource = addSource(
1554 "/lib.dart",
1555 r'''
1556 library lib;
1557 part 'part.dart';
1558 void f(x) {}''');
1559 Source partSource = addSource("/part.dart", "void g() { f(null); }");
1560 _analyzeAll_assertFinished();
1561 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1562 reason: "library resolved 1");
1563 expect(
1564 context.getResolvedCompilationUnit2(partSource, partSource), isNotNull,
1565 reason: "part resolved 1");
1566 // update and analyze
1567 context.setContents(
1568 partSource,
1569 r'''
1570 part of lib;
1571 void g() { f(null); }''');
1572 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNull,
1573 reason: "library changed 2");
1574 expect(context.getResolvedCompilationUnit2(partSource, partSource), isNull,
1575 reason: "part changed 2");
1576 _analyzeAll_assertFinished();
1577 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1578 reason: "library resolved 2");
1579 expect(
1580 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1581 reason: "part resolved 2");
1582 expect(context.getErrors(libSource).errors, hasLength(0));
1583 expect(context.getErrors(partSource).errors, hasLength(0));
1584 }
1585
1586 /**
1587 * https://code.google.com/p/dart/issues/detail?id=12424
1588 */
1589 void test_performAnalysisTask_changePartContents_makeItNotPart() {
1590 Source libSource = addSource(
1591 "/lib.dart",
1592 r'''
1593 library lib;
1594 part 'part.dart';
1595 void f(x) {}''');
1596 Source partSource = addSource(
1597 "/part.dart",
1598 r'''
1599 part of lib;
1600 void g() { f(null); }''');
1601 _analyzeAll_assertFinished();
1602 expect(context.getErrors(libSource).errors, hasLength(0));
1603 expect(context.getErrors(partSource).errors, hasLength(0));
1604 // Remove 'part' directive, which should make "f(null)" an error.
1605 context.setContents(
1606 partSource,
1607 r'''
1608 //part of lib;
1609 void g() { f(null); }''');
1610 _analyzeAll_assertFinished();
1611 expect(context.getErrors(libSource).errors.length != 0, isTrue);
1612 }
1613
1614 void test_performAnalysisTask_changePartContents_noSemanticChanges() {
1615 Source libSource =
1616 addSource("/test.dart", "library lib; part 'test-part.dart';");
1617 Source partSource = addSource("/test-part.dart", "part of lib;");
1618 _analyzeAll_assertFinished();
1619 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1620 reason: "library resolved 1");
1621 expect(
1622 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1623 reason: "part resolved 1");
1624 // update and analyze #1
1625 context.setContents(partSource, "part of lib; // 1");
1626 if (AnalysisEngine.instance.limitInvalidationInTaskModel) {
1627 expect(
1628 context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1629 reason: "library changed 2");
1630 expect(
1631 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1632 reason: "part changed 2");
1633 } else {
1634 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNull,
1635 reason: "library changed 2");
1636 expect(context.getResolvedCompilationUnit2(partSource, libSource), isNull,
1637 reason: "part changed 2");
1638 _analyzeAll_assertFinished();
1639 expect(
1640 context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1641 reason: "library resolved 2");
1642 expect(
1643 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1644 reason: "part resolved 2");
1645 }
1646 // update and analyze #2
1647 context.setContents(partSource, "part of lib; // 12");
1648 if (AnalysisEngine.instance.limitInvalidationInTaskModel) {
1649 expect(
1650 context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1651 reason: "library changed 3");
1652 expect(
1653 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1654 reason: "part changed 3");
1655 } else {
1656 expect(context.getResolvedCompilationUnit2(libSource, libSource), isNull,
1657 reason: "library changed 3");
1658 expect(context.getResolvedCompilationUnit2(partSource, libSource), isNull,
1659 reason: "part changed 3");
1660 _analyzeAll_assertFinished();
1661 expect(
1662 context.getResolvedCompilationUnit2(libSource, libSource), isNotNull,
1663 reason: "library resolved 3");
1664 expect(
1665 context.getResolvedCompilationUnit2(partSource, libSource), isNotNull,
1666 reason: "part resolved 3");
1667 }
1668 }
1669
1670 void test_performAnalysisTask_getContentException_dart() {
1671 Source source = _addSourceWithException('test.dart');
1672 // prepare errors
1673 _analyzeAll_assertFinished();
1674 List<AnalysisError> errors = context.getErrors(source).errors;
1675 // validate errors
1676 expect(errors, hasLength(1));
1677 AnalysisError error = errors[0];
1678 expect(error.source, same(source));
1679 expect(error.errorCode, ScannerErrorCode.UNABLE_GET_CONTENT);
1680 }
1681
1682 void test_performAnalysisTask_getContentException_html() {
1683 Source source = _addSourceWithException('test.html');
1684 // prepare errors
1685 _analyzeAll_assertFinished();
1686 List<AnalysisError> errors = context.getErrors(source).errors;
1687 // validate errors
1688 expect(errors, hasLength(1));
1689 AnalysisError error = errors[0];
1690 expect(error.source, same(source));
1691 expect(error.errorCode, ScannerErrorCode.UNABLE_GET_CONTENT);
1692 }
1693
1694 void test_performAnalysisTask_importedLibraryAdd() {
1695 Source libASource =
1696 addSource("/libA.dart", "library libA; import 'libB.dart';");
1697 _analyzeAll_assertFinished();
1698 expect(
1699 context.getResolvedCompilationUnit2(libASource, libASource), isNotNull,
1700 reason: "libA resolved 1");
1701 expect(_hasAnalysisErrorWithErrorSeverity(context.getErrors(libASource)),
1702 isTrue,
1703 reason: "libA has an error");
1704 // add libB.dart and analyze
1705 Source libBSource = addSource("/libB.dart", "library libB;");
1706 _analyzeAll_assertFinished();
1707 expect(
1708 context.getResolvedCompilationUnit2(libASource, libASource), isNotNull,
1709 reason: "libA resolved 2");
1710 expect(
1711 context.getResolvedCompilationUnit2(libBSource, libBSource), isNotNull,
1712 reason: "libB resolved 2");
1713 expect(_hasAnalysisErrorWithErrorSeverity(context.getErrors(libASource)),
1714 isFalse,
1715 reason: "libA doesn't have errors");
1716 }
1717
1718 void test_performAnalysisTask_importedLibraryAdd_html() {
1719 Source htmlSource = addSource(
1720 "/page.html",
1721 r'''
1722 <html><body><script type="application/dart">
1723 import '/libB.dart';
1724 main() {print('hello dart');}
1725 </script></body></html>''');
1726 _analyzeAll_assertFinished();
1727 context.computeErrors(htmlSource);
1728 expect(_hasAnalysisErrorWithErrorSeverity(context.getErrors(htmlSource)),
1729 isTrue,
1730 reason: "htmlSource has an error");
1731 // add libB.dart and analyze
1732 Source libBSource = addSource("/libB.dart", "library libB;");
1733 _analyzeAll_assertFinished();
1734 expect(
1735 context.getResolvedCompilationUnit2(libBSource, libBSource), isNotNull,
1736 reason: "libB resolved 2");
1737 // TODO (danrubel) commented out to fix red bots
1738 // context.computeErrors(htmlSource);
1739 // AnalysisErrorInfo errors = _context.getErrors(htmlSource);
1740 // expect(
1741 // !_hasAnalysisErrorWithErrorSeverity(errors),
1742 // isTrue,
1743 // reason: "htmlSource doesn't have errors");
1744 }
1745
1746 void test_performAnalysisTask_importedLibraryDelete() {
1747 Source libASource =
1748 addSource("/libA.dart", "library libA; import 'libB.dart';");
1749 Source libBSource = addSource("/libB.dart", "library libB;");
1750 _analyzeAll_assertFinished();
1751 expect(
1752 context.getResolvedCompilationUnit2(libASource, libASource), isNotNull,
1753 reason: "libA resolved 1");
1754 expect(
1755 context.getResolvedCompilationUnit2(libBSource, libBSource), isNotNull,
1756 reason: "libB resolved 1");
1757 expect(!_hasAnalysisErrorWithErrorSeverity(context.getErrors(libASource)),
1758 isTrue,
1759 reason: "libA doesn't have errors");
1760 // remove libB.dart and analyze
1761 _removeSource(libBSource);
1762 _analyzeAll_assertFinished();
1763 expect(
1764 context.getResolvedCompilationUnit2(libASource, libASource), isNotNull,
1765 reason: "libA resolved 2");
1766 expect(_hasAnalysisErrorWithErrorSeverity(context.getErrors(libASource)),
1767 isTrue,
1768 reason: "libA has an error");
1769 }
1770
1771 void test_performAnalysisTask_IOException() {
1772 TestSource source = _addSourceWithException2("/test.dart", "library test;");
1773 source.generateExceptionOnRead = false;
1774 _analyzeAll_assertFinished();
1775 expect(source.readCount, 1);
1776 _changeSource(source, "");
1777 source.generateExceptionOnRead = true;
1778 _analyzeAll_assertFinished();
1779 if (AnalysisEngine.instance.limitInvalidationInTaskModel) {
1780 expect(source.readCount, 5);
1781 } else {
1782 expect(source.readCount, 3);
1783 }
1784 }
1785
1786 void test_performAnalysisTask_missingPart() {
1787 Source source =
1788 addSource("/test.dart", "library lib; part 'no-such-file.dart';");
1789 _analyzeAll_assertFinished();
1790 expect(context.getLibraryElement(source), isNotNull,
1791 reason: "performAnalysisTask failed to compute an element model");
1792 }
1793
1794 void test_performAnalysisTask_modifiedAfterParse() {
1795 // TODO(scheglov) no threads in Dart
1796 // Source source = _addSource("/test.dart", "library lib;");
1797 // int initialTime = _context.getModificationStamp(source);
1798 // List<Source> sources = new List<Source>();
1799 // sources.add(source);
1800 // _context.analysisPriorityOrder = sources;
1801 // _context.parseCompilationUnit(source);
1802 // while (initialTime == JavaSystem.currentTimeMillis()) {
1803 // Thread.sleep(1);
1804 // // Force the modification time to be different.
1805 // }
1806 // _context.setContents(source, "library test;");
1807 // JUnitTestCase.assertTrue(initialTime != _context.getModificationStamp(sour ce));
1808 // _analyzeAll_assertFinished();
1809 // JUnitTestCase.assertNotNullMsg("performAnalysisTask failed to compute an e lement model", _context.getLibraryElement(source));
1810 }
1811
1812 void test_performAnalysisTask_onResultComputed() {
1813 Set<String> libraryElementUris = new Set<String>();
1814 Set<String> parsedUnitUris = new Set<String>();
1815 Set<String> resolvedUnitUris = new Set<String>();
1816 // listen
1817 context.onResultComputed(LIBRARY_ELEMENT).listen((event) {
1818 Source librarySource = event.target;
1819 libraryElementUris.add(librarySource.uri.toString());
1820 });
1821 context.onResultComputed(PARSED_UNIT).listen((event) {
1822 Source source = event.target;
1823 parsedUnitUris.add(source.uri.toString());
1824 });
1825 context.onResultComputed(RESOLVED_UNIT).listen((event) {
1826 LibrarySpecificUnit target = event.target;
1827 Source librarySource = target.library;
1828 resolvedUnitUris.add(librarySource.uri.toString());
1829 });
1830 // analyze
1831 addSource('/test.dart', 'main() {}');
1832 _analyzeAll_assertFinished();
1833 // verify
1834 expect(libraryElementUris, contains('dart:core'));
1835 expect(libraryElementUris, contains('file:///test.dart'));
1836 expect(parsedUnitUris, contains('dart:core'));
1837 expect(parsedUnitUris, contains('file:///test.dart'));
1838 expect(resolvedUnitUris, contains('dart:core'));
1839 expect(resolvedUnitUris, contains('file:///test.dart'));
1840 }
1841
1842 void test_resolveCompilationUnit_import_relative() {
1843 Source sourceA =
1844 addSource("/libA.dart", "library libA; import 'libB.dart'; class A{}");
1845 addSource("/libB.dart", "library libB; class B{}");
1846 CompilationUnit compilationUnit =
1847 context.resolveCompilationUnit2(sourceA, sourceA);
1848 expect(compilationUnit, isNotNull);
1849 LibraryElement library = compilationUnit.element.library;
1850 List<LibraryElement> importedLibraries = library.importedLibraries;
1851 assertNamedElements(importedLibraries, ["dart.core", "libB"]);
1852 List<LibraryElement> visibleLibraries = library.visibleLibraries;
1853 assertNamedElements(visibleLibraries,
1854 ["dart.core", "dart.async", "dart.math", "libA", "libB"]);
1855 }
1856
1857 void test_resolveCompilationUnit_import_relative_cyclic() {
1858 Source sourceA =
1859 addSource("/libA.dart", "library libA; import 'libB.dart'; class A{}");
1860 addSource("/libB.dart", "library libB; import 'libA.dart'; class B{}");
1861 CompilationUnit compilationUnit =
1862 context.resolveCompilationUnit2(sourceA, sourceA);
1863 expect(compilationUnit, isNotNull);
1864 LibraryElement library = compilationUnit.element.library;
1865 List<LibraryElement> importedLibraries = library.importedLibraries;
1866 assertNamedElements(importedLibraries, ["dart.core", "libB"]);
1867 List<LibraryElement> visibleLibraries = library.visibleLibraries;
1868 assertNamedElements(visibleLibraries,
1869 ["dart.core", "dart.async", "dart.math", "libA", "libB"]);
1870 }
1871
1872 // void test_resolveCompilationUnit_sourceChangeDuringResolution() {
1873 // _context = new _AnalysisContext_sourceChangeDuringResolution();
1874 // AnalysisContextFactory.initContextWithCore(_context);
1875 // _sourceFactory = _context.sourceFactory;
1876 // Source source = _addSource("/lib.dart", "library lib;");
1877 // CompilationUnit compilationUnit =
1878 // _context.resolveCompilationUnit2(source, source);
1879 // expect(compilationUnit, isNotNull);
1880 // expect(_context.getLineInfo(source), isNotNull);
1881 // }
1882
1883 void test_resolveCompilationUnit_library() {
1884 Source source = addSource("/lib.dart", "library lib;");
1885 LibraryElement library = context.computeLibraryElement(source);
1886 CompilationUnit compilationUnit =
1887 context.resolveCompilationUnit(source, library);
1888 expect(compilationUnit, isNotNull);
1889 expect(compilationUnit.element, isNotNull);
1890 }
1891
1892 void test_resolveCompilationUnit_source() {
1893 Source source = addSource("/lib.dart", "library lib;");
1894 CompilationUnit compilationUnit =
1895 context.resolveCompilationUnit2(source, source);
1896 expect(compilationUnit, isNotNull);
1897 }
1898
1899 void test_setAnalysisOptions() {
1900 AnalysisOptionsImpl options = new AnalysisOptionsImpl();
1901 options.cacheSize = 42;
1902 options.dart2jsHint = false;
1903 options.hint = false;
1904 context.analysisOptions = options;
1905 AnalysisOptions result = context.analysisOptions;
1906 expect(result.cacheSize, options.cacheSize);
1907 expect(result.dart2jsHint, options.dart2jsHint);
1908 expect(result.hint, options.hint);
1909 }
1910
1911 void test_setAnalysisPriorityOrder() {
1912 int priorityCount = 4;
1913 List<Source> sources = new List<Source>();
1914 for (int index = 0; index < priorityCount; index++) {
1915 sources.add(addSource("/lib.dart$index", ""));
1916 }
1917 context.analysisPriorityOrder = sources;
1918 expect(_getPriorityOrder(context).length, priorityCount);
1919 }
1920
1921 void test_setAnalysisPriorityOrder_empty() {
1922 context.analysisPriorityOrder = new List<Source>();
1923 }
1924
1925 void test_setAnalysisPriorityOrder_nonEmpty() {
1926 List<Source> sources = new List<Source>();
1927 sources.add(addSource("/lib.dart", "library lib;"));
1928 context.analysisPriorityOrder = sources;
1929 }
1930
1931 Future test_setChangedContents_libraryWithPart() {
1932 AnalysisOptionsImpl options = new AnalysisOptionsImpl();
1933 options.incremental = true;
1934 context.analysisOptions = options;
1935 SourcesChangedListener listener = new SourcesChangedListener();
1936 context.onSourcesChanged.listen(listener.onData);
1937 String oldCode = r'''
1938 library lib;
1939 part 'part.dart';
1940 int a = 0;''';
1941 Source librarySource = addSource("/lib.dart", oldCode);
1942 String partContents = r'''
1943 part of lib;
1944 int b = a;''';
1945 Source partSource = addSource("/part.dart", partContents);
1946 LibraryElement element = context.computeLibraryElement(librarySource);
1947 CompilationUnit unit =
1948 context.resolveCompilationUnit(librarySource, element);
1949 expect(unit, isNotNull);
1950 int offset = oldCode.indexOf("int a") + 4;
1951 String newCode = r'''
1952 library lib;
1953 part 'part.dart';
1954 int ya = 0;''';
1955 context.setChangedContents(librarySource, newCode, offset, 0, 1);
1956 expect(context.getContents(librarySource).data, newCode);
1957 expect(
1958 context.getResolvedCompilationUnit2(partSource, librarySource), isNull);
1959 return pumpEventQueue().then((_) {
1960 listener.assertEvent(wereSourcesAdded: true);
1961 listener.assertEvent(wereSourcesAdded: true);
1962 listener.assertEvent(changedSources: [librarySource]);
1963 listener.assertNoMoreEvents();
1964 });
1965 }
1966
1967 void test_setChangedContents_notResolved() {
1968 AnalysisOptionsImpl options =
1969 new AnalysisOptionsImpl.from(context.analysisOptions);
1970 options.incremental = true;
1971 context.analysisOptions = options;
1972 String oldCode = r'''
1973 library lib;
1974 int a = 0;''';
1975 Source librarySource = addSource("/lib.dart", oldCode);
1976 int offset = oldCode.indexOf("int a") + 4;
1977 String newCode = r'''
1978 library lib;
1979 int ya = 0;''';
1980 context.setChangedContents(librarySource, newCode, offset, 0, 1);
1981 expect(context.getContents(librarySource).data, newCode);
1982 }
1983
1984 Future test_setContents_libraryWithPart() {
1985 SourcesChangedListener listener = new SourcesChangedListener();
1986 context.onSourcesChanged.listen(listener.onData);
1987 String libraryContents1 = r'''
1988 library lib;
1989 part 'part.dart';
1990 int a = 0;''';
1991 Source librarySource = addSource("/lib.dart", libraryContents1);
1992 String partContents1 = r'''
1993 part of lib;
1994 int b = a;''';
1995 Source partSource = addSource("/part.dart", partContents1);
1996 context.computeLibraryElement(librarySource);
1997 String libraryContents2 = r'''
1998 library lib;
1999 part 'part.dart';
2000 int aa = 0;''';
2001 context.setContents(librarySource, libraryContents2);
2002 expect(
2003 context.getResolvedCompilationUnit2(partSource, librarySource), isNull);
2004 return pumpEventQueue().then((_) {
2005 listener.assertEvent(wereSourcesAdded: true);
2006 listener.assertEvent(wereSourcesAdded: true);
2007 listener.assertEvent(changedSources: [librarySource]);
2008 listener.assertNoMoreEvents();
2009 });
2010 }
2011
2012 void test_setContents_null() {
2013 Source librarySource = addSource(
2014 "/lib.dart",
2015 r'''
2016 library lib;
2017 int a = 0;''');
2018 context.setContents(librarySource, '// different');
2019 context.computeLibraryElement(librarySource);
2020 context.setContents(librarySource, null);
2021 expect(context.getResolvedCompilationUnit2(librarySource, librarySource),
2022 isNull);
2023 }
2024
2025 void test_setContents_unchanged_consistentModificationTime() {
2026 String contents = "// foo";
2027 Source source = addSource("/test.dart", contents);
2028 context.setContents(source, contents);
2029 // do all, no tasks
2030 _analyzeAll_assertFinished();
2031 {
2032 AnalysisResult result = context.performAnalysisTask();
2033 expect(result.changeNotices, isNull);
2034 }
2035 // set the same contents, still no tasks
2036 context.setContents(source, contents);
2037 {
2038 AnalysisResult result = context.performAnalysisTask();
2039 expect(result.changeNotices, isNull);
2040 }
2041 }
2042
2043 void test_setSourceFactory() {
2044 expect(context.sourceFactory, sourceFactory);
2045 SourceFactory factory = new SourceFactory([]);
2046 context.sourceFactory = factory;
2047 expect(context.sourceFactory, factory);
2048 }
2049
2050 void test_updateAnalysis() {
2051 expect(context.sourcesNeedingProcessing, isEmpty);
2052 Source source = newSource('/test.dart');
2053 AnalysisDelta delta = new AnalysisDelta();
2054 delta.setAnalysisLevel(source, AnalysisLevel.ALL);
2055 context.applyAnalysisDelta(delta);
2056 expect(context.sourcesNeedingProcessing, contains(source));
2057 delta = new AnalysisDelta();
2058 delta.setAnalysisLevel(source, AnalysisLevel.NONE);
2059 context.applyAnalysisDelta(delta);
2060 expect(context.sourcesNeedingProcessing.contains(source), isFalse);
2061 }
2062
2063 void xtest_performAnalysisTask_stress() {
2064 int maxCacheSize = 4;
2065 AnalysisOptionsImpl options =
2066 new AnalysisOptionsImpl.from(context.analysisOptions);
2067 options.cacheSize = maxCacheSize;
2068 context.analysisOptions = options;
2069 int sourceCount = maxCacheSize + 2;
2070 List<Source> sources = new List<Source>();
2071 ChangeSet changeSet = new ChangeSet();
2072 for (int i = 0; i < sourceCount; i++) {
2073 Source source = addSource("/lib$i.dart", "library lib$i;");
2074 sources.add(source);
2075 changeSet.addedSource(source);
2076 }
2077 context.applyChanges(changeSet);
2078 context.analysisPriorityOrder = sources;
2079 for (int i = 0; i < 1000; i++) {
2080 List<ChangeNotice> notice = context.performAnalysisTask().changeNotices;
2081 if (notice == null) {
2082 //System.out.println("test_performAnalysisTask_stress: " + i);
2083 break;
2084 }
2085 }
2086 List<ChangeNotice> notice = context.performAnalysisTask().changeNotices;
2087 if (notice != null) {
2088 fail(
2089 "performAnalysisTask failed to terminate after analyzing all sources") ;
2090 }
2091 }
2092
2093 TestSource _addSourceWithException(String fileName) {
2094 return _addSourceWithException2(fileName, "");
2095 }
2096
2097 TestSource _addSourceWithException2(String fileName, String contents) {
2098 TestSource source = new TestSource(fileName, contents);
2099 source.generateExceptionOnRead = true;
2100 ChangeSet changeSet = new ChangeSet();
2101 changeSet.addedSource(source);
2102 context.applyChanges(changeSet);
2103 return source;
2104 }
2105
2106 /**
2107 * Perform analysis tasks up to 512 times and assert that it was enough.
2108 */
2109 void _analyzeAll_assertFinished([int maxIterations = 512]) {
2110 for (int i = 0; i < maxIterations; i++) {
2111 List<ChangeNotice> notice = context.performAnalysisTask().changeNotices;
2112 if (notice == null) {
2113 return;
2114 }
2115 }
2116 fail("performAnalysisTask failed to terminate after analyzing all sources");
2117 }
2118
2119 void _changeSource(TestSource source, String contents) {
2120 source.setContents(contents);
2121 ChangeSet changeSet = new ChangeSet();
2122 changeSet.changedSource(source);
2123 context.applyChanges(changeSet);
2124 }
2125
2126 /**
2127 * Search the given compilation unit for a class with the given name. Return t he class with the
2128 * given name, or `null` if the class cannot be found.
2129 *
2130 * @param unit the compilation unit being searched
2131 * @param className the name of the class being searched for
2132 * @return the class with the given name
2133 */
2134 ClassElement _findClass(CompilationUnitElement unit, String className) {
2135 for (ClassElement classElement in unit.types) {
2136 if (classElement.displayName == className) {
2137 return classElement;
2138 }
2139 }
2140 return null;
2141 }
2142
2143 void _flushAst(Source source) {
2144 CacheEntry entry =
2145 context.getCacheEntry(new LibrarySpecificUnit(source, source));
2146 entry.setState(RESOLVED_UNIT, CacheState.FLUSHED);
2147 }
2148
2149 List<Source> _getPriorityOrder(AnalysisContextImpl context2) {
2150 return context2.test_priorityOrder;
2151 }
2152
2153 void _performPendingAnalysisTasks([int maxTasks = 512]) {
2154 for (int i = 0; context.performAnalysisTask().hasMoreWork; i++) {
2155 if (i > maxTasks) {
2156 fail('Analysis did not terminate.');
2157 }
2158 }
2159 }
2160
2161 void _removeSource(Source source) {
2162 resourceProvider.deleteFile(source.fullName);
2163 ChangeSet changeSet = new ChangeSet();
2164 changeSet.removedSource(source);
2165 context.applyChanges(changeSet);
2166 }
2167
2168 /**
2169 * Returns `true` if there is an [AnalysisError] with [ErrorSeverity.ERROR] in
2170 * the given [AnalysisErrorInfo].
2171 */
2172 static bool _hasAnalysisErrorWithErrorSeverity(AnalysisErrorInfo errorInfo) {
2173 List<AnalysisError> errors = errorInfo.errors;
2174 for (AnalysisError analysisError in errors) {
2175 if (analysisError.errorCode.errorSeverity == ErrorSeverity.ERROR) {
2176 return true;
2177 }
2178 }
2179 return false;
2180 }
2181 }
2182
2183 @reflectiveTest
2184 class LimitedInvalidateTest extends AbstractContextTest {
2185 @override
2186 void setUp() {
2187 AnalysisEngine.instance.limitInvalidationInTaskModel = true;
2188 super.setUp();
2189 AnalysisOptionsImpl options =
2190 new AnalysisOptionsImpl.from(context.analysisOptions);
2191 options.incremental = true;
2192 context.analysisOptions = options;
2193 }
2194
2195 @override
2196 void tearDown() {
2197 AnalysisEngine.instance.limitInvalidationInTaskModel = false;
2198 super.tearDown();
2199 }
2200
2201 void test_noChange_thenChange() {
2202 Source sourceA = addSource(
2203 "/a.dart",
2204 r'''
2205 library lib_a;
2206
2207 class A {
2208 A();
2209 }
2210 class B {
2211 B();
2212 }
2213 ''');
2214 Source sourceB = addSource(
2215 "/b.dart",
2216 r'''
2217 library lib_b;
2218 import 'a.dart';
2219 main() {
2220 new A();
2221 }
2222 ''');
2223 _performPendingAnalysisTasks();
2224 expect(context.getErrors(sourceA).errors, hasLength(0));
2225 expect(context.getErrors(sourceB).errors, hasLength(0));
2226 var unitA = context.getResolvedCompilationUnit2(sourceA, sourceA);
2227 var unitElementA = unitA.element;
2228 var libraryElementA = unitElementA.library;
2229 // Update a.dart, no declaration changes.
2230 context.setContents(
2231 sourceA,
2232 r'''
2233 library lib_a;
2234 class A {
2235 A();
2236 }
2237 class B {
2238 B();
2239 }
2240 ''');
2241 _assertInvalid(sourceA, LIBRARY_ERRORS_READY);
2242 _assertValid(sourceB, LIBRARY_ERRORS_READY);
2243 // The a.dart's unit and element are updated incrementally.
2244 // They are the same instances as initially.
2245 // So, all the references from other units are still valid.
2246 {
2247 LibrarySpecificUnit target = new LibrarySpecificUnit(sourceA, sourceA);
2248 expect(analysisCache.getValue(target, RESOLVED_UNIT1), same(unitA));
2249 expect(unitA.element, same(unitElementA));
2250 expect(unitElementA.library, same(libraryElementA));
2251 }
2252 // Analyze.
2253 _performPendingAnalysisTasks();
2254 expect(context.getErrors(sourceA).errors, hasLength(0));
2255 expect(context.getErrors(sourceB).errors, hasLength(0));
2256 // The a.dart's unit and element are the same.
2257 {
2258 LibrarySpecificUnit target = new LibrarySpecificUnit(sourceA, sourceA);
2259 expect(analysisCache.getValue(target, RESOLVED_UNIT), same(unitA));
2260 expect(unitA.element, same(unitElementA));
2261 expect(unitElementA.library, same(libraryElementA));
2262 }
2263 // Update a.dart, rename A to A2, invalidates b.dart, so
2264 // we know that the previous update did not damage dependencies.
2265 context.setContents(
2266 sourceA,
2267 r'''
2268 library lib_a;
2269 class A {
2270 A();
2271 m() {}
2272 }
2273 class B {
2274 B();
2275 }
2276 ''');
2277 _assertInvalid(sourceA, LIBRARY_ERRORS_READY);
2278 _assertInvalid(sourceB, LIBRARY_ERRORS_READY);
2279 // The a.dart's unit and element are the same.
2280 {
2281 LibrarySpecificUnit target = new LibrarySpecificUnit(sourceA, sourceA);
2282 expect(analysisCache.getValue(target, RESOLVED_UNIT1), same(unitA));
2283 expect(unitA.element, same(unitElementA));
2284 expect(unitElementA.library, same(libraryElementA));
2285 }
2286 // Analyze.
2287 _performPendingAnalysisTasks();
2288 expect(context.getErrors(sourceA).errors, hasLength(0));
2289 expect(context.getErrors(sourceB).errors, hasLength(0));
2290 }
2291
2292 void test_unusedName() {
2293 Source sourceA = addSource(
2294 "/a.dart",
2295 r'''
2296 library lib_a;
2297 class A {}
2298 class B {}
2299 class C {}
2300 ''');
2301 Source sourceB = addSource(
2302 "/b.dart",
2303 r'''
2304 library lib_b;
2305 import 'a.dart';
2306 main() {
2307 new A();
2308 new C();
2309 }
2310 ''');
2311 _performPendingAnalysisTasks();
2312 // Update A.
2313 context.setContents(
2314 sourceA,
2315 r'''
2316 library lib_a;
2317 class A {}
2318 class B2 {}
2319 class C {}
2320 ''');
2321 // Only a.dart is invalidated.
2322 // Because b.dart does not use B, so it is valid.
2323 _assertInvalid(sourceA, LIBRARY_ERRORS_READY);
2324 _assertValid(sourceB, LIBRARY_ERRORS_READY);
2325 }
2326
2327 void test_usedName_directUser() {
2328 Source sourceA = addSource(
2329 "/a.dart",
2330 r'''
2331 library lib_a;
2332 class A {}
2333 class B {}
2334 class C {}
2335 ''');
2336 Source sourceB = addSource(
2337 "/b.dart",
2338 r'''
2339 library lib_b;
2340 import 'a.dart';
2341 main() {
2342 new A();
2343 new C2();
2344 }
2345 ''');
2346 _performPendingAnalysisTasks();
2347 expect(context.getErrors(sourceB).errors, hasLength(1));
2348 // Update a.dart, invalidates b.dart because it references "C2".
2349 context.setContents(
2350 sourceA,
2351 r'''
2352 library lib_a;
2353 class A {}
2354 class B {}
2355 class C2 {}
2356 ''');
2357 _assertInvalid(sourceA, LIBRARY_ERRORS_READY);
2358 _assertInvalid(sourceB, LIBRARY_ERRORS_READY);
2359 // Now b.dart is analyzed and the error is fixed.
2360 _performPendingAnalysisTasks();
2361 expect(context.getErrors(sourceB).errors, hasLength(0));
2362 // Update a.dart, invalidates b.dart because it references "C".
2363 context.setContents(
2364 sourceA,
2365 r'''
2366 library lib_a;
2367 class A {}
2368 class B {}
2369 class C {}
2370 ''');
2371 _assertInvalid(sourceA, LIBRARY_ERRORS_READY);
2372 _assertInvalid(sourceB, LIBRARY_ERRORS_READY);
2373 _performPendingAnalysisTasks();
2374 // Now b.dart is analyzed and it again has the error.
2375 expect(context.getErrors(sourceB).errors, hasLength(1));
2376 }
2377
2378 void test_usedName_directUser_withIncremental() {
2379 Source sourceA = addSource(
2380 "/a.dart",
2381 r'''
2382 library lib_a;
2383 class A {
2384 m() {}
2385 }
2386 ''');
2387 Source sourceB = addSource(
2388 "/b.dart",
2389 r'''
2390 library lib_b;
2391 import 'a.dart';
2392 main() {
2393 A a = new A();
2394 a.m();
2395 }
2396 ''');
2397 _performPendingAnalysisTasks();
2398 // Update A.
2399 context.setContents(
2400 sourceA,
2401 r'''
2402 library lib_a;
2403 class A {
2404 m2() {}
2405 }
2406 ''');
2407 _assertInvalid(sourceA, LIBRARY_ERRORS_READY);
2408 _assertInvalid(sourceB, LIBRARY_ERRORS_READY);
2409 }
2410
2411 void test_usedName_indirectUser() {
2412 Source sourceA = addSource(
2413 "/a.dart",
2414 r'''
2415 library lib_a;
2416 class A {
2417 m() {}
2418 }
2419 ''');
2420 Source sourceB = addSource(
2421 "/b.dart",
2422 r'''
2423 library lib_b;
2424 import 'a.dart';
2425 class B extends A {}
2426 ''');
2427 Source sourceC = addSource(
2428 "/c.dart",
2429 r'''
2430 library lib_c;
2431 import 'b.dart';
2432 class C extends B {
2433 main() {
2434 m();
2435 }
2436 }
2437 ''');
2438 // No errors, "A.m" exists.
2439 _performPendingAnalysisTasks();
2440 expect(context.getErrors(sourceC).errors, hasLength(0));
2441 // Replace "A.m" with "A.m2", invalidate both b.dart and c.dart files.
2442 context.setContents(
2443 sourceA,
2444 r'''
2445 library lib_a;
2446 class A {
2447 m2() {}
2448 }
2449 ''');
2450 _assertInvalid(sourceA, LIBRARY_ERRORS_READY);
2451 _assertInvalid(sourceB, LIBRARY_ERRORS_READY);
2452 _assertInvalid(sourceC, LIBRARY_ERRORS_READY);
2453 // There is an error in c.dart, "A.m" does not exist.
2454 _performPendingAnalysisTasks();
2455 expect(context.getErrors(sourceB).errors, hasLength(0));
2456 expect(context.getErrors(sourceC).errors, hasLength(1));
2457 // Restore "A.m", invalidate both b.dart and c.dart files.
2458 context.setContents(
2459 sourceA,
2460 r'''
2461 library lib_a;
2462 class A {
2463 m() {}
2464 }
2465 ''');
2466 _assertInvalid(sourceA, LIBRARY_ERRORS_READY);
2467 _assertInvalid(sourceB, LIBRARY_ERRORS_READY);
2468 _assertInvalid(sourceC, LIBRARY_ERRORS_READY);
2469 // No errors, "A.m" exists.
2470 _performPendingAnalysisTasks();
2471 expect(context.getErrors(sourceC).errors, hasLength(0));
2472 }
2473
2474 void _assertInvalid(AnalysisTarget target, ResultDescriptor descriptor) {
2475 CacheState state = analysisCache.getState(target, descriptor);
2476 expect(state, CacheState.INVALID);
2477 }
2478
2479 void _assertValid(AnalysisTarget target, ResultDescriptor descriptor) {
2480 CacheState state = analysisCache.getState(target, descriptor);
2481 expect(state, CacheState.VALID);
2482 }
2483
2484 void _performPendingAnalysisTasks([int maxTasks = 512]) {
2485 for (int i = 0; context.performAnalysisTask().hasMoreWork; i++) {
2486 if (i > maxTasks) {
2487 fail('Analysis did not terminate.');
2488 }
2489 }
2490 }
2491 }
2492
2493 class _AnalysisContextImplTest_test_applyChanges_removeContainer
2494 implements SourceContainer {
2495 Source libB;
2496 _AnalysisContextImplTest_test_applyChanges_removeContainer(this.libB);
2497 @override
2498 bool contains(Source source) => source == libB;
2499 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698