Hey Dartisans,
I've just released test 0.12.18, which adds a couple features that I think are pretty neat.
First up is addTearDown(), which allows you to add tear-down callbacks from within a test. Like with tearDown(), they'll run even if the test fails. This is particularly useful for writing testing libraries—for example:
/// Creates a temporary directory that will be deleted when
/// the test finishes running.
String createSandbox([String prefix]) {
prefix ??= 'dart';
var sandbox = Directory.systemTemp
.createTempSync('${prefix}_').path;
// Delete [sandbox] when the test finishes running.
addTearDown(() {
new Directory(sandbox).deleteSync(recursive: true);
});
return sandbox;
}
The second feature is actually a pair of functions:
spawnHybridUri() and
spawnHybridCode(). These allow browser tests to spawn isolates that run on the Dart VM—either from a well-known URI, or from a chunk of inline Dart code. I've personally needed this before for testing packages like
web_socket_channel, who run in the browser and whose whole point is to communicate with a server. It could also be used for running tests against a server-side app, or for something I haven't even dreamed of. For example:
void main() {
int port;
setUp(() async {
var channel = spawnHybridCode(r"""
import 'dart:io';
import 'package:stream_channel/stream_channel.dart';
hybridMain(StreamChannel channel) async {
var server = await HttpServer.bind('localhost', 0);
server.transform(new WebSocketTransformer())
.listen((webSocket) {
webSocket.listen((request) {
webSocket.add(request);
});
});
channel.sink.add(server.port);
}
""", stayAlive: true);
port = await channel.stream.first;
});
test("communicates with the server", () async {
channel = new HtmlWebSocketChannel.connect(
"ws://localhost:$port");
var queue = new StreamQueue(channel.stream);
channel.sink.add("foo");
expect(await queue.next, equals("foo"));
});
}
Download the package, give it a try, and let me know what you think!
- Natalie