Skip to content

Commit f075c79

Browse files
committed
1 parent 975fbfd commit f075c79

5 files changed

Lines changed: 336 additions & 0 deletions

File tree

‎lib/src/dart.dart‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
library unittest.dart;
6+
7+
import 'dart:async';
8+
import 'dart:io';
9+
import 'dart:isolate';
10+
11+
import 'package:path/path.dart' as p;
12+
13+
import 'io.dart';
14+
import 'remote_exception.dart';
15+
16+
/// Runs [code] in an isolate.
17+
///
18+
/// [code] should be the contents of a Dart entrypoint. It may contain imports;
19+
/// they will be resolved in the same context as the host isolate. [message] is
20+
/// passed to the [main] method of the code being run; the caller is responsible
21+
/// for using this to establish communication with the isolate.
22+
///
23+
/// [packageRoot] controls the package root of the isolate. It may be either a
24+
/// [String] or a [Uri].
25+
Future<Isolate> runInIsolate(String code, message, {packageRoot}) {
26+
// TODO(nweiz): load code from a local server rather than from a file.
27+
return withTempDir((dir) {
28+
var dartPath = p.join(dir, 'runInIsolate.dart');
29+
new File(dartPath).writeAsStringSync(code);
30+
var port = new ReceivePort();
31+
return Isolate.spawn(_isolateBuffer, {
32+
'replyTo': port.sendPort,
33+
'uri': p.toUri(dartPath).toString(),
34+
'packageRoot': packageRoot == null ? null : packageRoot.toString(),
35+
'message': message
36+
}).then((isolate) {
37+
return port.first.then((response) {
38+
if (response['type'] != 'error') return isolate;
39+
isolate.kill();
40+
var asyncError = RemoteException.deserialize(response['error']);
41+
return new Future.error(asyncError.error, asyncError.stackTrace);
42+
});
43+
});
44+
});
45+
}
46+
47+
// TODO(nweiz): remove this when issue 12617 is fixed.
48+
/// A function used as a buffer between the host isolate and [spawnUri].
49+
///
50+
/// [spawnUri] synchronously loads the file and its imports, which can deadlock
51+
/// the host isolate if there's an HTTP import pointing at a server in the host.
52+
/// Adding an additional isolate in the middle works around this.
53+
void _isolateBuffer(message) {
54+
var replyTo = message['replyTo'];
55+
var packageRoot = message['packageRoot'];
56+
if (packageRoot != null) packageRoot = Uri.parse(packageRoot);
57+
Isolate.spawnUri(Uri.parse(message['uri']), [], message['message'],
58+
packageRoot: packageRoot)
59+
.then((_) => replyTo.send({'type': 'success'}))
60+
.catchError((error, stackTrace) {
61+
replyTo.send({
62+
'type': 'error',
63+
'error': RemoteException.serialize(error, stackTrace)
64+
});
65+
});
66+
}

‎lib/src/io.dart‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
library unittest.io;
66

7+
import 'dart:async';
78
import 'dart:io';
89

910
/// Whether "special" strings such as Unicode characters or color escapes are
@@ -21,3 +22,21 @@ bool get canUseSpecialChars =>
2122
/// those aren't supported.
2223
String getSpecial(String special, [String onWindows = '']) =>
2324
canUseSpecialChars ? special : onWindows;
25+
26+
/// Creates a temporary directory and passes its path to [fn].
27+
///
28+
/// Once the [Future] returned by [fn] completes, the temporary directory and
29+
/// all its contents are deleted. [fn] can also return `null`, in which case
30+
/// the temporary directory is deleted immediately afterwards.
31+
///
32+
/// Returns a future that completes to the value that the future returned from
33+
/// [fn] completes to.
34+
Future withTempDir(Future fn(String path)) {
35+
return new Future.sync(() {
36+
// TODO(nweiz): Empirically test whether sync or async functions perform
37+
// better here when starting a bunch of isolates.
38+
var tempDir = Directory.systemTemp.createTempSync('unittest_');
39+
return new Future.sync(() => fn(tempDir.path))
40+
.whenComplete(() => tempDir.deleteSync(recursive: true));
41+
});
42+
}

‎lib/src/loader.dart‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
library unittest.loader;
6+
7+
import 'dart:async';
8+
import 'dart:io';
9+
import 'dart:isolate';
10+
11+
import 'package:path/path.dart' as p;
12+
13+
import 'dart.dart';
14+
import 'isolate_test.dart';
15+
import 'suite.dart';
16+
17+
/// A class for finding test files and loading them into a runnable form.
18+
class Loader {
19+
/// The package root to use for loading tests, or `null` to use the automatic
20+
/// root.
21+
final String _packageRoot;
22+
23+
/// All isolates that have been spun up by the loader.
24+
final _isolates = new Set<Isolate>();
25+
26+
/// Creates a new loader.
27+
///
28+
/// If [packageRoot] is passed, it's used as the package root for all loaded
29+
/// tests. Otherwise, the `packages/` directories next to the test entrypoints
30+
/// will be used.
31+
Loader({String packageRoot})
32+
: _packageRoot = packageRoot;
33+
34+
/// Loads all test suites in [dir].
35+
///
36+
/// This will load tests from files that end in "_test.dart".
37+
Future<Set<Suite>> loadDir(String dir) {
38+
return Future.wait(new Directory(dir).listSync(recursive: true)
39+
.map((entry) {
40+
if (entry is! File) return new Future.value();
41+
if (!entry.path.endsWith("_test.dart")) return new Future.value();
42+
if (p.split(entry.path).contains('packages')) return new Future.value();
43+
44+
// TODO(nweiz): Provide a way for the caller to gracefully handle some
45+
// isolates failing to load without stopping the rest.
46+
return loadFile(entry.path);
47+
})).then((suites) => suites.toSet()..remove(null));
48+
}
49+
50+
/// Loads a test suite from the file at [path].
51+
///
52+
/// This wil throw a [FileSystemException] if there's no `packages/` directory
53+
/// available for [path]. Any other load error will cause an
54+
/// [IsolateSpawnException] or a [RemoteException].
55+
Future<Suite> loadFile(String path) {
56+
// TODO(nweiz): Support browser tests.
57+
var packageRoot = _packageRoot == null
58+
? p.join(p.dirname(path), 'packages')
59+
: _packageRoot;
60+
61+
if (!new Directory(packageRoot).existsSync()) {
62+
throw new FileSystemException("Directory $packageRoot does not exist.");
63+
}
64+
65+
var receivePort = new ReceivePort();
66+
return runInIsolate('''
67+
import "package:unittest/src/vm_listener.dart";
68+
69+
import "${p.toUri(p.absolute(path))}" as test;
70+
71+
void main(_, Map message) {
72+
var sendPort = message['reply'];
73+
VmListener.start(sendPort, test.main);
74+
}
75+
''', {
76+
'reply': receivePort.sendPort
77+
}, packageRoot: packageRoot).then((isolate) {
78+
_isolates.add(isolate);
79+
return receivePort.first;
80+
}).then((tests) {
81+
return new Suite(path, tests.map((test) {
82+
return new IsolateTest(test['name'], test['sendPort']);
83+
}));
84+
});
85+
}
86+
87+
/// Closes the loader and releases all resources allocated by it.
88+
Future close() {
89+
for (var isolate in _isolates) {
90+
isolate.kill();
91+
}
92+
_isolates.clear();
93+
return new Future.value();
94+
}
95+
}

‎test/loader_test.dart‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
library unittest.loader;
6+
7+
import 'dart:io';
8+
9+
import 'package:path/path.dart' as p;
10+
import 'package:unittest/src/loader.dart';
11+
import 'package:unittest/src/state.dart';
12+
import 'package:unittest/unittest.dart';
13+
14+
import 'utils.dart';
15+
16+
Loader _loader;
17+
String _sandbox;
18+
19+
final _tests = """
20+
import 'dart:async';
21+
22+
import 'package:unittest/unittest.dart';
23+
24+
void main() {
25+
var declarer = Zone.current[#unittest.declarer];
26+
declarer.test("success", () {});
27+
declarer.test("failure", () => throw new TestFailure('oh no'));
28+
declarer.test("error", () => throw 'oh no');
29+
}
30+
""";
31+
32+
void main() {
33+
setUp(() {
34+
_loader = new Loader(packageRoot: p.join(packageDir, 'packages'));
35+
_sandbox = Directory.systemTemp.createTempSync('unittest_').path;
36+
});
37+
38+
tearDown(() {
39+
new Directory(_sandbox).deleteSync(recursive: true);
40+
return _loader.close();
41+
});
42+
43+
group(".loadFile()", () {
44+
var suite;
45+
setUp(() {
46+
/// TODO(nweiz): Use scheduled_test for this once it's compatible with
47+
/// this version of unittest.
48+
new File(p.join(_sandbox, 'a_test.dart')).writeAsStringSync(_tests);
49+
return _loader.loadFile(p.join(_sandbox, 'a_test.dart'))
50+
.then((suite_) => suite = suite_);
51+
});
52+
53+
test("returns a suite with a name matching the file path", () {
54+
expect(suite.name, equals(p.join(_sandbox, 'a_test.dart')));
55+
});
56+
57+
test("returns tests with the correct names", () {
58+
expect(suite.tests, hasLength(3));
59+
expect(suite.tests[0].name, equals("success"));
60+
expect(suite.tests[1].name, equals("failure"));
61+
expect(suite.tests[2].name, equals("error"));
62+
});
63+
64+
test("can load and run a successful test", () {
65+
var liveTest = suite.tests[0].load(suite);
66+
67+
expectStates(liveTest, [
68+
const State(Status.running, Result.success),
69+
const State(Status.complete, Result.success)
70+
]);
71+
expectErrors(liveTest, []);
72+
73+
return liveTest.run().whenComplete(() => liveTest.close());
74+
});
75+
76+
test("can load and run a failing test", () {
77+
var liveTest = suite.tests[1].load(suite);
78+
expectSingleFailure(liveTest);
79+
return liveTest.run().whenComplete(() => liveTest.close());
80+
});
81+
82+
test("throws a nice error if the package root doesn't exist", () {
83+
var loader = new Loader();
84+
expect(() => loader.loadFile(p.join(_sandbox, 'a_test.dart')),
85+
throwsA(isFileSystemException(
86+
"Directory ${p.join(_sandbox, 'packages')} does not exist.")));
87+
});
88+
});
89+
90+
group(".loadDir()", () {
91+
test("ignores non-Dart files", () {
92+
new File(p.join(_sandbox, 'a_test.txt')).writeAsStringSync(_tests);
93+
expect(_loader.loadDir(_sandbox), completion(isEmpty));
94+
});
95+
96+
test("ignores files in packages/ directories", () {
97+
var dir = p.join(_sandbox, 'packages');
98+
new Directory(dir).createSync();
99+
new File(p.join(dir, 'a_test.dart')).writeAsStringSync(_tests);
100+
expect(_loader.loadDir(_sandbox), completion(isEmpty));
101+
});
102+
103+
test("ignores files that don't end in _test.dart", () {
104+
new File(p.join(_sandbox, 'test.dart')).writeAsStringSync(_tests);
105+
expect(_loader.loadDir(_sandbox), completion(isEmpty));
106+
});
107+
108+
group("with suites loaded from a directory", () {
109+
var suites;
110+
setUp(() {
111+
/// TODO(nweiz): Use scheduled_test for this once it's compatible with
112+
/// this version of unittest.
113+
new File(p.join(_sandbox, 'a_test.dart')).writeAsStringSync(_tests);
114+
new File(p.join(_sandbox, 'another_test.dart'))
115+
.writeAsStringSync(_tests);
116+
new Directory(p.join(_sandbox, 'dir')).createSync();
117+
new File(p.join(_sandbox, 'dir/sub_test.dart'))
118+
.writeAsStringSync(_tests);
119+
120+
return _loader.loadDir(_sandbox).then((suites_) => suites = suites_);
121+
});
122+
123+
test("names those suites after their files", () {
124+
expect(suites.map((suite) => suite.name), unorderedEquals([
125+
p.join(_sandbox, 'a_test.dart'),
126+
p.join(_sandbox, 'another_test.dart'),
127+
p.join(_sandbox, 'dir/sub_test.dart')
128+
]));
129+
});
130+
131+
test("can run tests in those suites", () {
132+
var suite = suites.firstWhere((suite) => suite.name.contains("a_test"));
133+
var liveTest = suite.tests[1].load(suite);
134+
expectSingleFailure(liveTest);
135+
return liveTest.run().whenComplete(() => liveTest.close());
136+
});
137+
});
138+
});
139+
}

‎test/utils.dart‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ library unittest.test.utils;
66

77
import 'dart:async';
88
import 'dart:collection';
9+
import 'dart:io';
10+
11+
import 'package:path/path.dart' as p;
12+
import 'package:stack_trace/stack_trace.dart';
913

1014
import 'package:unittest/src/live_test.dart';
1115
import 'package:unittest/src/remote_exception.dart';
@@ -15,6 +19,13 @@ import 'package:unittest/unittest.dart';
1519
// The last state change detected via [expectStates].
1620
State lastState;
1721

22+
final String packageDir = _computePackageDir();
23+
24+
String _computePackageDir() {
25+
var trace = new Trace.current();
26+
return p.dirname(p.dirname(p.fromUri(trace.frames.first.uri)));
27+
}
28+
1829
/// Asserts that exactly [states] will be emitted via [liveTest.onStateChange].
1930
///
2031
/// The most recent emitted state is stored in [_lastState].
@@ -71,6 +82,12 @@ Matcher isRemoteException(String message) => predicate(
7182
(error) => error is RemoteException && error.message == message,
7283
'is a RemoteException with message "$message"');
7384

85+
/// Returns a matcher that matches a [FileSystemException] with the given
86+
/// [message].
87+
Matcher isFileSystemException(String message) => predicate(
88+
(error) => error is FileSystemException && error.message == message,
89+
'is a FileSystemException with message "$message"');
90+
7491
/// Returns a [Future] that completes after pumping the event queue [times]
7592
/// times.
7693
///

0 commit comments

Comments
 (0)