Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a | 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. | 3 // BSD-style license that can be found in the LICENSE file. |
| 4 | 4 |
| 5 /** | 5 /** |
| 6 * Test infrastructure for testing pub. Unlike typical unit tests, most pub | 6 * Test infrastructure for testing pub. Unlike typical unit tests, most pub |
| 7 * tests are integration tests that stage some stuff on the file system, run | 7 * tests are integration tests that stage some stuff on the file system, run |
| 8 * pub, and then validate the results. This library provides an API to build | 8 * pub, and then validate the results. This library provides an API to build |
| 9 * tests like that. | 9 * tests like that. |
| 10 */ | 10 */ |
| 11 library test_pub; | 11 library test_pub; |
| 12 | 12 |
| 13 import 'dart:io'; | 13 import 'dart:io'; |
| 14 import 'dart:isolate'; | 14 import 'dart:isolate'; |
| 15 import 'dart:json'; | 15 import 'dart:json'; |
| 16 import 'dart:math'; | 16 import 'dart:math'; |
| 17 import 'dart:uri'; | 17 import 'dart:uri'; |
| 18 | 18 |
| 19 import '../../../pkg/oauth2/lib/oauth2.dart' as oauth2; | |
| 19 import '../../../pkg/unittest/lib/unittest.dart'; | 20 import '../../../pkg/unittest/lib/unittest.dart'; |
| 20 import '../../lib/file_system.dart' as fs; | 21 import '../../lib/file_system.dart' as fs; |
| 21 import '../../pub/git_source.dart'; | 22 import '../../pub/git_source.dart'; |
| 22 import '../../pub/hosted_source.dart'; | 23 import '../../pub/hosted_source.dart'; |
| 23 import '../../pub/io.dart'; | 24 import '../../pub/io.dart'; |
| 24 import '../../pub/sdk_source.dart'; | 25 import '../../pub/sdk_source.dart'; |
| 25 import '../../pub/utils.dart'; | 26 import '../../pub/utils.dart'; |
| 26 import '../../pub/yaml/yaml.dart'; | 27 import '../../pub/yaml/yaml.dart'; |
| 27 | 28 |
| 28 /** | 29 /** |
| (...skipping 328 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 357 contents.add(packageCacheDir(name, version)); | 358 contents.add(packageCacheDir(name, version)); |
| 358 } | 359 } |
| 359 }); | 360 }); |
| 360 return dir(cachePath, [ | 361 return dir(cachePath, [ |
| 361 dir('hosted', [ | 362 dir('hosted', [ |
| 362 async(port.transform((p) => dir('localhost%58$p', contents))) | 363 async(port.transform((p) => dir('localhost%58$p', contents))) |
| 363 ]) | 364 ]) |
| 364 ]); | 365 ]); |
| 365 } | 366 } |
| 366 | 367 |
| 368 /// Describes the file in the system cache that contains the client's OAuth2 | |
| 369 /// credentials. The URL "/token" on [server] will be used as the token | |
| 370 /// endpoint for refreshing the access token. | |
| 371 Descriptor credentialsFile( | |
| 372 ScheduledServer server, | |
| 373 String accessToken, | |
| 374 {String refreshToken, | |
| 375 Date expiration}) { | |
| 376 return async(server.url.transform((url) { | |
| 377 return dir(cachePath, [ | |
| 378 file('credentials.json', new oauth2.Credentials( | |
| 379 accessToken, | |
| 380 refreshToken, | |
| 381 url.resolve('/token'), | |
| 382 ['https://www.googleapis.com/auth/userinfo.email'], | |
| 383 expiration).toJson()) | |
| 384 ]); | |
| 385 })); | |
| 386 } | |
| 387 | |
| 367 /** | 388 /** |
| 368 * Describes the application directory, containing only a pubspec specifying the | 389 * Describes the application directory, containing only a pubspec specifying the |
| 369 * given [dependencies]. | 390 * given [dependencies]. |
| 370 */ | 391 */ |
| 371 DirectoryDescriptor appDir(List dependencies) => | 392 DirectoryDescriptor appDir(List dependencies) => |
| 372 dir(appPath, [appPubspec(dependencies)]); | 393 dir(appPath, [appPubspec(dependencies)]); |
| 373 | 394 |
| 374 /** | 395 /** |
| 375 * Converts a list of dependencies as passed to [package] into a hash as used in | 396 * Converts a list of dependencies as passed to [package] into a hash as used in |
| 376 * a pubspec. | 397 * a pubspec. |
| (...skipping 76 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 453 * The list of events that are scheduled to run as part of the test case. | 474 * The list of events that are scheduled to run as part of the test case. |
| 454 */ | 475 */ |
| 455 List<_ScheduledEvent> _scheduled; | 476 List<_ScheduledEvent> _scheduled; |
| 456 | 477 |
| 457 /** | 478 /** |
| 458 * The list of events that are scheduled to run after the test case, even if it | 479 * The list of events that are scheduled to run after the test case, even if it |
| 459 * failed. | 480 * failed. |
| 460 */ | 481 */ |
| 461 List<_ScheduledEvent> _scheduledCleanup; | 482 List<_ScheduledEvent> _scheduledCleanup; |
| 462 | 483 |
| 484 /// The list of events that are scheduled to run after the test case only if it | |
| 485 /// failed. | |
| 486 List<_ScheduledEvent> _scheduledOnException; | |
| 487 | |
| 463 /** | 488 /** |
| 464 * Set to true when the current batch of scheduled events should be aborted. | 489 * Set to true when the current batch of scheduled events should be aborted. |
| 465 */ | 490 */ |
| 466 bool _abortScheduled = false; | 491 bool _abortScheduled = false; |
| 467 | 492 |
| 468 /** | 493 /** |
| 469 * Runs all the scheduled events for a test case. This should only be called | 494 * Runs all the scheduled events for a test case. This should only be called |
| 470 * once per test case. | 495 * once per test case. |
| 471 */ | 496 */ |
| 472 void run() { | 497 void run() { |
| 473 var createdSandboxDir; | 498 var createdSandboxDir; |
| 474 | 499 |
| 475 var asyncDone = expectAsync0(() {}); | 500 var asyncDone = expectAsync0(() {}); |
| 476 | 501 |
| 477 Future cleanup() { | 502 Future cleanup() { |
| 478 return _runScheduled(createdSandboxDir, _scheduledCleanup).chain((_) { | 503 return _runScheduled(createdSandboxDir, _scheduledCleanup).chain((_) { |
| 479 _scheduled = null; | 504 _scheduled = null; |
| 505 _scheduledCleanup = null; | |
| 506 _scheduledOnException = null; | |
| 480 if (createdSandboxDir != null) return deleteDir(createdSandboxDir); | 507 if (createdSandboxDir != null) return deleteDir(createdSandboxDir); |
| 481 return new Future.immediate(null); | 508 return new Future.immediate(null); |
| 482 }); | 509 }); |
| 483 } | 510 } |
| 484 | 511 |
| 485 final future = _setUpSandbox().chain((sandboxDir) { | 512 final future = _setUpSandbox().chain((sandboxDir) { |
| 486 createdSandboxDir = sandboxDir; | 513 createdSandboxDir = sandboxDir; |
| 487 return _runScheduled(sandboxDir, _scheduled); | 514 return _runScheduled(sandboxDir, _scheduled); |
| 488 }); | 515 }); |
| 489 | 516 |
| 490 future.handleException((error) { | 517 future.handleException((error) { |
| 491 // If an error occurs during testing, delete the sandbox, throw the error so | 518 // If an error occurs during testing, delete the sandbox, throw the error so |
| 492 // that the test framework sees it, then finally call asyncDone so that the | 519 // that the test framework sees it, then finally call asyncDone so that the |
| 493 // test framework knows we're done doing asynchronous stuff. | 520 // test framework knows we're done doing asynchronous stuff. |
| 494 cleanup().then((_) => registerException(error, future.stackTrace)); | 521 var future = _runScheduled(createdSandboxDir, _scheduledOnException) |
| 522 .chain((_) => cleanup()); | |
| 523 future.handleException((e) { | |
| 524 print("Exception while cleaning up: $e"); | |
| 525 print(future.stackTrace); | |
| 526 registerException(error, future.stackTrace); | |
| 527 return true; | |
| 528 }); | |
| 529 future.then((_) => registerException(error, future.stackTrace)); | |
| 495 return true; | 530 return true; |
| 496 }); | 531 }); |
| 497 | 532 |
| 498 future.chain((_) => cleanup()).then((_) { | 533 future.chain((_) => cleanup()).then((_) { |
| 499 asyncDone(); | 534 asyncDone(); |
| 500 }); | 535 }); |
| 501 } | 536 } |
| 502 | 537 |
| 503 /// Get the path to the root "util/test/pub" directory containing the pub tests. | 538 /// Get the path to the root "util/test/pub" directory containing the pub tests. |
| 504 String get testDirectory { | 539 String get testDirectory { |
| 505 var dir = new Path.fromNative(new Options().script); | 540 var dir = new Path.fromNative(new Options().script); |
| 506 while (dir.filename != 'pub') dir = dir.directoryPath; | 541 while (dir.filename != 'pub') dir = dir.directoryPath; |
| 507 | 542 |
| 508 return new File(dir.toNativePath()).fullPathSync(); | 543 return new File(dir.toNativePath()).fullPathSync(); |
| 509 } | 544 } |
| 510 | 545 |
| 511 /** | 546 /** |
| 512 * Schedules a call to the Pub command-line utility. Runs Pub with [args] and | 547 * Schedules a call to the Pub command-line utility. Runs Pub with [args] and |
| 513 * validates that its results match [output], [error], and [exitCode]. | 548 * validates that its results match [output], [error], and [exitCode]. |
| 514 */ | 549 */ |
| 515 void schedulePub({List<String> args, Pattern output, Pattern error, | 550 void schedulePub({List<String> args, Pattern output, Pattern error, |
| 516 int exitCode: 0}) { | 551 Future<Uri> tokenEndpoint, int exitCode: 0}) { |
| 517 _schedule((sandboxDir) { | 552 _schedule((sandboxDir) { |
| 518 String pathInSandbox(path) => join(getFullPath(sandboxDir), path); | 553 return _doPub(runProcess, sandboxDir, args, tokenEndpoint) |
| 519 | 554 .transform((result) { |
| 520 return ensureDir(pathInSandbox(appPath)).chain((_) { | |
| 521 // Find a Dart executable we can use to spawn. Use the same one that was | |
| 522 // used to run this script itself. | |
| 523 var dartBin = new Options().executable; | |
| 524 | |
| 525 // If the executable looks like a path, get its full path. That way we | |
| 526 // can still find it when we spawn it with a different working directory. | |
| 527 if (dartBin.contains(Platform.pathSeparator)) { | |
| 528 dartBin = new File(dartBin).fullPathSync(); | |
| 529 } | |
| 530 | |
| 531 // Find the main pub entrypoint. | |
| 532 var pubPath = fs.joinPaths(testDirectory, '../../pub/pub.dart'); | |
| 533 | |
| 534 var dartArgs = | |
| 535 ['--enable-type-checks', '--enable-asserts', pubPath, '--trace']; | |
| 536 dartArgs.addAll(args); | |
| 537 | |
| 538 var environment = { | |
| 539 'PUB_CACHE': pathInSandbox(cachePath), | |
| 540 'DART_SDK': pathInSandbox(sdkPath) | |
| 541 }; | |
| 542 | |
| 543 return runProcess(dartBin, dartArgs, workingDir: pathInSandbox(appPath), | |
| 544 environment: environment); | |
| 545 }).transform((result) { | |
| 546 var failures = []; | 555 var failures = []; |
| 547 | 556 |
| 548 _validateOutput(failures, 'stdout', output, result.stdout); | 557 _validateOutput(failures, 'stdout', output, result.stdout); |
| 549 _validateOutput(failures, 'stderr', error, result.stderr); | 558 _validateOutput(failures, 'stderr', error, result.stderr); |
| 550 | 559 |
| 551 if (result.exitCode != exitCode) { | 560 if (result.exitCode != exitCode) { |
| 552 failures.add( | 561 failures.add( |
| 553 'Pub returned exit code ${result.exitCode}, expected $exitCode.'); | 562 'Pub returned exit code ${result.exitCode}, expected $exitCode.'); |
| 554 } | 563 } |
| 555 | 564 |
| (...skipping 15 matching lines...) Expand all Loading... | |
| 571 /** | 580 /** |
| 572 * A shorthand for [schedulePub] and [run] when no validation needs to be done | 581 * A shorthand for [schedulePub] and [run] when no validation needs to be done |
| 573 * after Pub has been run. | 582 * after Pub has been run. |
| 574 */ | 583 */ |
| 575 void runPub({List<String> args, Pattern output, Pattern error, | 584 void runPub({List<String> args, Pattern output, Pattern error, |
| 576 int exitCode: 0}) { | 585 int exitCode: 0}) { |
| 577 schedulePub(args: args, output: output, error: error, exitCode: exitCode); | 586 schedulePub(args: args, output: output, error: error, exitCode: exitCode); |
| 578 run(); | 587 run(); |
| 579 } | 588 } |
| 580 | 589 |
| 590 /// Starts a Pub process and returns a [ScheduledProcess] that supports | |
| 591 /// interaction with that process. | |
| 592 ScheduledProcess startPub({List<String> args}) { | |
| 593 var process = _scheduleValue((sandboxDir) => | |
| 594 _doPub(startProcess, sandboxDir, args)); | |
| 595 return new ScheduledProcess("pub", process); | |
| 596 } | |
| 597 | |
| 598 /// Like [startPub], but runs `pub lish` in particular with [server] used both | |
| 599 /// as the OAuth2 server (with "/token" as the token endpoint) and as the | |
| 600 /// package server. | |
| 601 ScheduledProcess startPubLish(ScheduledServer server, {List<String> args}) { | |
| 602 var process = _scheduleValue((sandboxDir) { | |
| 603 return server.url.chain((url) { | |
| 604 var tokenEndpoint = url.resolve('/token'); | |
| 605 if (args == null) args = []; | |
| 606 args = flatten(['lish', '--server', url.toString(), args]); | |
| 607 return _doPub(startProcess, sandboxDir, args, tokenEndpoint); | |
| 608 }); | |
| 609 }); | |
| 610 return new ScheduledProcess("pub lish", process); | |
| 611 } | |
| 612 | |
| 613 /// Calls [fn] with appropriately modified arguments to run a pub process. [fn] | |
| 614 /// should have the same signature as [startProcess], except that the returned | |
| 615 /// [Future] may have a type other than [Process]. | |
| 616 Future _doPub(Function fn, sandboxDir, List<String> args, Uri tokenEndpoint) { | |
| 617 String pathInSandbox(path) => join(getFullPath(sandboxDir), path); | |
| 618 | |
| 619 return ensureDir(pathInSandbox(appPath)).chain((_) { | |
| 620 // Find a Dart executable we can use to spawn. Use the same one that was | |
| 621 // used to run this script itself. | |
| 622 var dartBin = new Options().executable; | |
| 623 | |
| 624 // If the executable looks like a path, get its full path. That way we | |
| 625 // can still find it when we spawn it with a different working directory. | |
| 626 if (dartBin.contains(Platform.pathSeparator)) { | |
| 627 dartBin = new File(dartBin).fullPathSync(); | |
| 628 } | |
| 629 | |
| 630 // Find the main pub entrypoint. | |
| 631 var pubPath = fs.joinPaths(testDirectory, '../../pub/pub.dart'); | |
| 632 | |
| 633 var dartArgs = | |
| 634 ['--enable-type-checks', '--enable-asserts', pubPath, '--trace']; | |
| 635 dartArgs.addAll(args); | |
| 636 | |
| 637 var environment = { | |
| 638 'PUB_CACHE': pathInSandbox(cachePath), | |
| 639 'DART_SDK': pathInSandbox(sdkPath) | |
| 640 }; | |
| 641 if (tokenEndpoint != null) { | |
| 642 environment['_PUB_TEST_TOKEN_ENDPOINT'] = tokenEndpoint.toString(); | |
| 643 } | |
| 644 | |
| 645 return fn(dartBin, dartArgs, workingDir: pathInSandbox(appPath), | |
| 646 environment: environment); | |
| 647 }); | |
| 648 } | |
| 649 | |
| 581 /** | 650 /** |
| 582 * Skips the current test if Git is not installed. This validates that the | 651 * Skips the current test if Git is not installed. This validates that the |
| 583 * current test is running on a buildbot in which case we expect git to be | 652 * current test is running on a buildbot in which case we expect git to be |
| 584 * installed. If we are not running on the buildbot, we will instead see if git | 653 * installed. If we are not running on the buildbot, we will instead see if git |
| 585 * is installed and skip the test if not. This way, users don't need to have git | 654 * is installed and skip the test if not. This way, users don't need to have git |
| 586 * installed to run the tests locally (unless they actually care about the pub | 655 * installed to run the tests locally (unless they actually care about the pub |
| 587 * git tests). | 656 * git tests). |
| 588 */ | 657 */ |
| 589 void ensureGit() { | 658 void ensureGit() { |
| 590 _schedule((_) { | 659 _schedule((_) { |
| (...skipping 421 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 1012 /** | 1081 /** |
| 1013 * Schedules changes to be committed to the Git repository. | 1082 * Schedules changes to be committed to the Git repository. |
| 1014 */ | 1083 */ |
| 1015 void scheduleCommit() => _schedule((dir) => this.commit(dir)); | 1084 void scheduleCommit() => _schedule((dir) => this.commit(dir)); |
| 1016 | 1085 |
| 1017 /** | 1086 /** |
| 1018 * Return a Future that completes to the commit in the git repository referred | 1087 * Return a Future that completes to the commit in the git repository referred |
| 1019 * to by [ref] at the current point in the scheduled test run. | 1088 * to by [ref] at the current point in the scheduled test run. |
| 1020 */ | 1089 */ |
| 1021 Future<String> revParse(String ref) { | 1090 Future<String> revParse(String ref) { |
| 1022 var completer = new Completer<String>(); | 1091 return _scheduleValue((parentDir) { |
| 1023 _schedule((parentDir) { | |
| 1024 return super.create(parentDir).chain((rootDir) { | 1092 return super.create(parentDir).chain((rootDir) { |
| 1025 return _runGit(['rev-parse', ref], rootDir); | 1093 return _runGit(['rev-parse', ref], rootDir); |
| 1026 }).transform((output) { | 1094 }).transform((output) => output[0]); |
| 1027 completer.complete(output[0]); | |
| 1028 return null; | |
| 1029 }); | |
| 1030 }); | 1095 }); |
| 1031 return completer.future; | |
| 1032 } | 1096 } |
| 1033 | 1097 |
| 1034 /// Schedule a Git command to run in this repository. | 1098 /// Schedule a Git command to run in this repository. |
| 1035 void scheduleGit(List<String> args) { | 1099 void scheduleGit(List<String> args) { |
| 1036 _schedule((parentDir) { | 1100 _schedule((parentDir) { |
| 1037 var gitDir = new Directory(join(parentDir, name)); | 1101 var gitDir = new Directory(join(parentDir, name)); |
| 1038 return _runGit(args, gitDir); | 1102 return _runGit(args, gitDir); |
| 1039 }); | 1103 }); |
| 1040 } | 1104 } |
| 1041 | 1105 |
| (...skipping 140 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 1182 InputStream load(List<String> path) { | 1246 InputStream load(List<String> path) { |
| 1183 if (path.isEmpty) { | 1247 if (path.isEmpty) { |
| 1184 throw "Can't load the contents of $name: it doesn't exist."; | 1248 throw "Can't load the contents of $name: it doesn't exist."; |
| 1185 } else { | 1249 } else { |
| 1186 throw "Can't load ${Strings.join(path, '/')} from within $name: $name " | 1250 throw "Can't load ${Strings.join(path, '/')} from within $name: $name " |
| 1187 "doesn't exist."; | 1251 "doesn't exist."; |
| 1188 } | 1252 } |
| 1189 } | 1253 } |
| 1190 } | 1254 } |
| 1191 | 1255 |
| 1256 /// A class representing a [Process] that is scheduled to run in the course of | |
| 1257 /// the test. This class allows actions on the process to be scheduled | |
| 1258 /// synchronously. All operations on this class are scheduled. | |
| 1259 /// | |
| 1260 /// Before running the test, either [shouldExit] or [kill] must be called on | |
| 1261 /// this to ensure that the process terminates when expected. | |
| 1262 /// | |
| 1263 /// If the test fails, this will automatically print out any remaining stdout | |
| 1264 /// and stderr from the process to aid debugging. | |
| 1265 class ScheduledProcess { | |
| 1266 /// The name of the process. Used for error reporting. | |
| 1267 final String name; | |
| 1268 | |
| 1269 /// The process that's scheduled to run. | |
| 1270 final Future<Process> _process; | |
| 1271 | |
| 1272 /// A [StringInputStream] wrapping the stdout of the process that's scheduled | |
| 1273 /// to run. | |
| 1274 final Future<StringInputStream> _stdout; | |
| 1275 | |
| 1276 /// A [StringInputStream] wrapping the stderr of the process that's scheduled | |
| 1277 /// to run. | |
| 1278 final Future<StringInputStream> _stderr; | |
| 1279 | |
| 1280 /// The exit code of the process that's scheduled to run. This will naturally | |
| 1281 /// only complete once the process has terminated. | |
| 1282 Future<int> get _exitCode => _exitCodeCompleter.future; | |
| 1283 | |
| 1284 /// The completer for [_exitCode]. | |
| 1285 final Completer<int> _exitCodeCompleter = new Completer(); | |
| 1286 | |
| 1287 /// Whether the user has scheduled the end of this process by calling either | |
| 1288 /// [shouldExit] or [kill]. | |
| 1289 bool _endScheduled = false; | |
| 1290 | |
| 1291 /// Whether the process is expected to terminate at this point. | |
| 1292 bool _endExpected = false; | |
| 1293 | |
| 1294 /// Wraps a [Process] [Future] in a scheduled process. | |
| 1295 ScheduledProcess(this.name, Future<Process> process) | |
| 1296 : _process = process, | |
| 1297 _stdout = process.transform((p) => new StringInputStream(p.stdout)), | |
| 1298 _stderr = process.transform((p) => new StringInputStream(p.stderr)) { | |
| 1299 | |
| 1300 _schedule((_) { | |
| 1301 if (!_endScheduled) { | |
| 1302 throw new StateError("Scheduled process $name must have shouldExit() " | |
| 1303 "or kill() called before the test is run."); | |
| 1304 } | |
| 1305 | |
| 1306 return _process.transform((p) { | |
| 1307 p.onExit = (c) { | |
| 1308 if (_endExpected) { | |
| 1309 _exitCodeCompleter.complete(c); | |
| 1310 return; | |
| 1311 } | |
| 1312 | |
| 1313 // Sleep for half a second in case _endExpected is set in the next | |
|
Bob Nystrom
2012/11/27 21:00:53
Why 500ms?
nweiz
2012/11/27 22:07:34
It seemed like a time increment that would be larg
| |
| 1314 // scheduled event. | |
| 1315 sleep(500).then((_) { | |
| 1316 if (_endExpected) { | |
| 1317 _exitCodeCompleter.complete(c); | |
| 1318 return; | |
| 1319 } | |
| 1320 | |
| 1321 _printStreams().then((_) { | |
| 1322 registerException(new ExpectException("Process $name ended " | |
| 1323 "earlier than scheduled with exit code $c")); | |
| 1324 }); | |
| 1325 }); | |
| 1326 }; | |
| 1327 }); | |
| 1328 }); | |
| 1329 | |
| 1330 _scheduleOnException((_) { | |
| 1331 if (!_process.hasValue) return; | |
| 1332 | |
| 1333 if (!_exitCode.hasValue) { | |
| 1334 print("\nKilling process $name prematurely."); | |
| 1335 _endExpected = true; | |
| 1336 _process.value.kill(); | |
| 1337 } | |
| 1338 | |
| 1339 return _printStreams(); | |
| 1340 }); | |
| 1341 | |
| 1342 _scheduleCleanup((_) { | |
| 1343 if (!_process.hasValue) return; | |
| 1344 // Ensure that the process is dead and we aren't waiting on any IO. | |
| 1345 var process = _process.value; | |
| 1346 process.kill(); | |
| 1347 process.stdout.close(); | |
| 1348 process.stderr.close(); | |
| 1349 }); | |
| 1350 } | |
| 1351 | |
| 1352 /// Reads the next line of stdout from the process. | |
| 1353 Future<String> nextLine() { | |
| 1354 return _scheduleValue((_) { | |
| 1355 return timeout(_stdout.chain(readLine), 5000, | |
| 1356 "waiting for the next stdout line from process $name"); | |
| 1357 }); | |
| 1358 } | |
| 1359 | |
| 1360 /// Reads the next line of stderr from the process. | |
| 1361 Future<String> nextErrLine() { | |
| 1362 return _scheduleValue((_) { | |
| 1363 return timeout(_stderr.chain(readLine), 5000, | |
| 1364 "waiting for the next stderr line from process $name"); | |
| 1365 }); | |
| 1366 } | |
| 1367 | |
| 1368 /// Writes [line] to the process as stdin. | |
| 1369 void writeLine(String line) { | |
| 1370 _schedule((_) => _process.transform((p) => p.stdin.writeString('$line\n'))); | |
| 1371 } | |
| 1372 | |
| 1373 /// Kills the process, and waits until it's dead. | |
| 1374 void kill() { | |
| 1375 _endScheduled = true; | |
| 1376 _schedule((_) { | |
| 1377 _endExpected = true; | |
| 1378 return _process.chain((p) { | |
| 1379 p.kill(); | |
| 1380 return timeout(_exitCode, 5000, "waiting for process $name to die"); | |
| 1381 }); | |
| 1382 }); | |
| 1383 } | |
| 1384 | |
| 1385 /// Waits for the process to exit, and verifies that the exit code matches | |
| 1386 /// [expectedExitCode] (if given). | |
| 1387 void shouldExit([int expectedExitCode]) { | |
| 1388 _endScheduled = true; | |
| 1389 _schedule((_) { | |
| 1390 _endExpected = true; | |
| 1391 return timeout(_exitCode, 5000, "waiting for process $name to exit") | |
| 1392 .transform((exitCode) { | |
| 1393 if (expectedExitCode != null) expect(exitCode, equals(expectedExitCode)) ; | |
|
Bob Nystrom
2012/11/27 21:00:53
Long line.
nweiz
2012/11/27 22:07:34
Done.
| |
| 1394 }); | |
| 1395 }); | |
| 1396 } | |
| 1397 | |
| 1398 /// Prints the remaining data in the process's stdout and stderr streams. | |
| 1399 /// Prints nothing if the straems are empty. | |
| 1400 Future _printStreams() { | |
| 1401 Future printStream(String streamName, StringInputStream stream) { | |
| 1402 return consumeStringInputStream(stream).transform((output) { | |
| 1403 if (output.isEmpty) return; | |
| 1404 | |
| 1405 print('\nProcess $name $streamName:'); | |
| 1406 for (var line in output.trim().split("\n")) { | |
| 1407 print('| $line'); | |
| 1408 } | |
| 1409 return; | |
| 1410 }); | |
| 1411 } | |
| 1412 | |
| 1413 return printStream('stdout', _stdout.value) | |
| 1414 .chain((_) => printStream('stderr', _stderr.value)); | |
| 1415 } | |
| 1416 } | |
| 1417 | |
| 1418 /// A class representing an [HttpServer] that's scheduled to run in the course | |
| 1419 /// of the test. This class allows the server's request handling to be scheduled | |
| 1420 /// synchronously. All operations on this class are scheduled. | |
| 1421 class ScheduledServer { | |
| 1422 /// The wrapped server. | |
| 1423 final Future<HttpServer> _server; | |
| 1424 | |
| 1425 ScheduledServer._(this._server); | |
| 1426 | |
| 1427 /// Creates a new server listening on an automatically-allocated port on | |
| 1428 /// localhost. | |
| 1429 factory ScheduledServer() { | |
| 1430 return new ScheduledServer._(_scheduleValue((_) { | |
| 1431 var server = new HttpServer(); | |
| 1432 server.defaultRequestHandler = _unexpectedRequest; | |
| 1433 server.listen("127.0.0.1", 0); | |
| 1434 _scheduleCleanup((_) => server.close()); | |
| 1435 return new Future.immediate(server); | |
| 1436 })); | |
| 1437 } | |
| 1438 | |
| 1439 /// The port on which the server is listening. | |
| 1440 Future<int> get port => _server.transform((s) => s.port); | |
| 1441 | |
| 1442 /// The base URL of the server, including its port. | |
| 1443 Future<Uri> get url => | |
| 1444 port.transform((p) => new Uri.fromString("http://localhost:$p")); | |
| 1445 | |
| 1446 /// Assert that the next request has the given [method] and [path], and pass | |
| 1447 /// it to [handler] to handle. If [handler] returns a [Future], wait until | |
| 1448 /// it's completed to continue the schedule. | |
| 1449 void handle(String method, String path, | |
| 1450 Future handler(HttpRequest request, HttpResponse response)) { | |
| 1451 _schedule((_) { | |
|
Bob Nystrom
2012/11/27 21:00:53
Could do:
_schedule((_) => timeout(...));
And ge
nweiz
2012/11/27 22:07:34
That's allowed? :o
| |
| 1452 return timeout(_server.chain((server) { | |
| 1453 var completer = new Completer(); | |
| 1454 server.defaultRequestHandler = (request, response) { | |
| 1455 server.defaultRequestHandler = _unexpectedRequest; | |
| 1456 expect(request.method, equals(method)); | |
| 1457 expect(request.path, equals(path)); | |
| 1458 | |
| 1459 var future = handler(request, response); | |
| 1460 if (future == null) future = new Future.immediate(null); | |
| 1461 chainToCompleter(future, completer); | |
| 1462 }; | |
| 1463 return completer.future; | |
| 1464 }), 5000, "waiting for $method $path"); | |
| 1465 }); | |
| 1466 } | |
| 1467 | |
| 1468 /// Raises an error complaining of an unexpected request. | |
| 1469 static void _unexpectedRequest(HttpRequest request, HttpResponse response) { | |
| 1470 fail('Unexpected ${request.method} request to ${request.path}.'); | |
| 1471 } | |
| 1472 } | |
| 1473 | |
| 1192 /** | 1474 /** |
| 1193 * Takes a simple data structure (composed of [Map]s, [List]s, scalar objects, | 1475 * Takes a simple data structure (composed of [Map]s, [List]s, scalar objects, |
| 1194 * and [Future]s) and recursively resolves all the [Future]s contained within. | 1476 * and [Future]s) and recursively resolves all the [Future]s contained within. |
| 1195 * Completes with the fully resolved structure. | 1477 * Completes with the fully resolved structure. |
| 1196 */ | 1478 */ |
| 1197 Future _awaitObject(object) { | 1479 Future _awaitObject(object) { |
| 1198 // Unroll nested futures. | 1480 // Unroll nested futures. |
| 1199 if (object is Future) return object.chain(_awaitObject); | 1481 if (object is Future) return object.chain(_awaitObject); |
| 1200 if (object is Collection) return Futures.wait(object.map(_awaitObject)); | 1482 if (object is Collection) return Futures.wait(object.map(_awaitObject)); |
| 1201 if (object is! Map) return new Future.immediate(object); | 1483 if (object is! Map) return new Future.immediate(object); |
| (...skipping 13 matching lines...) Expand all Loading... | |
| 1215 } | 1497 } |
| 1216 | 1498 |
| 1217 /** | 1499 /** |
| 1218 * Schedules a callback to be called as part of the test case. | 1500 * Schedules a callback to be called as part of the test case. |
| 1219 */ | 1501 */ |
| 1220 void _schedule(_ScheduledEvent event) { | 1502 void _schedule(_ScheduledEvent event) { |
| 1221 if (_scheduled == null) _scheduled = []; | 1503 if (_scheduled == null) _scheduled = []; |
| 1222 _scheduled.add(event); | 1504 _scheduled.add(event); |
| 1223 } | 1505 } |
| 1224 | 1506 |
| 1225 /** | 1507 /// Like [_schedule], but pipes the return value of [event] to a returned |
| 1226 * Schedules a callback to be called after Pub is run with [runPub], even if it | 1508 /// [Future]. |
| 1227 * fails. | 1509 Future _scheduleValue(_ScheduledEvent event) { |
| 1228 */ | 1510 var completer = new Completer(); |
| 1511 _schedule((parentDir) { | |
|
Bob Nystrom
2012/11/27 21:00:53
"parentDir" -> "value".
nweiz
2012/11/27 22:07:34
This isn't the value that's being returned. It act
| |
| 1512 chainToCompleter(event(parentDir), completer); | |
| 1513 return completer.future; | |
| 1514 }); | |
| 1515 return completer.future; | |
| 1516 } | |
| 1517 | |
| 1518 /// Schedules a callback to be called after the test case has completed, even if | |
| 1519 /// it failed. | |
| 1229 void _scheduleCleanup(_ScheduledEvent event) { | 1520 void _scheduleCleanup(_ScheduledEvent event) { |
| 1230 if (_scheduledCleanup == null) _scheduledCleanup = []; | 1521 if (_scheduledCleanup == null) _scheduledCleanup = []; |
| 1231 _scheduledCleanup.add(event); | 1522 _scheduledCleanup.add(event); |
| 1232 } | 1523 } |
| 1524 | |
| 1525 /// Schedules a callback to be called after the test case has completed, but | |
| 1526 /// only if it failed. | |
| 1527 void _scheduleOnException(_ScheduledEvent event) { | |
| 1528 if (_scheduledOnException == null) _scheduledOnException = []; | |
| 1529 _scheduledOnException.add(event); | |
| 1530 } | |
| 1531 | |
| 1532 /// Like [expect], but for [Future]s that complete as part of the scheduled | |
| 1533 /// test. This is necessary to ensure that the exception thrown by the | |
| 1534 /// expectation failing is handled by the scheduler. | |
| 1535 /// | |
| 1536 /// Note that [matcher] matches against the completed value of [actual], so | |
| 1537 /// calling [completion] is unnecessary. | |
| 1538 Matcher expectLater(Future actual, matcher, {String reason, | |
| 1539 FailureHandler failureHandler, bool verbose: false}) { | |
| 1540 _schedule((_) { | |
| 1541 return actual.transform((value) { | |
| 1542 expect(value, matcher, reason: reason, failureHandler: failureHandler, | |
| 1543 verbose: false); | |
| 1544 }); | |
| 1545 }); | |
| 1546 } | |
| OLD | NEW |