85 lines
2.3 KiB
Dart
85 lines
2.3 KiB
Dart
|
|
import 'dart:io';
|
||
|
|
import 'dart:typed_data';
|
||
|
|
|
||
|
|
import 'package:http/http.dart' as http;
|
||
|
|
import 'package:http/testing.dart';
|
||
|
|
import 'package:swarm/swarm.dart';
|
||
|
|
import 'package:test/test.dart';
|
||
|
|
|
||
|
|
void main() {
|
||
|
|
late Directory tmpDir;
|
||
|
|
|
||
|
|
setUp(() async {
|
||
|
|
tmpDir = await Directory.systemTemp.createTemp('file_download_test_');
|
||
|
|
});
|
||
|
|
|
||
|
|
tearDown(() async {
|
||
|
|
await tmpDir.delete(recursive: true);
|
||
|
|
});
|
||
|
|
|
||
|
|
FileDownloadActor makeActor(http.Client client) => FileDownloadActor(
|
||
|
|
fileActor: FileActor(),
|
||
|
|
httpClient: client,
|
||
|
|
);
|
||
|
|
|
||
|
|
test('returns FileDownloaded with correct savePath', () async {
|
||
|
|
final client = MockClient(
|
||
|
|
(_) async => http.Response.bytes([1, 2, 3], 200),
|
||
|
|
);
|
||
|
|
final path = '${tmpDir.path}/output.bin';
|
||
|
|
final result = await makeActor(client).handle(
|
||
|
|
DownloadFile(url: 'https://example.com/file', savePath: path),
|
||
|
|
);
|
||
|
|
expect(result, isA<FileDownloaded>());
|
||
|
|
expect((result as FileDownloaded).savePath, equals(path));
|
||
|
|
});
|
||
|
|
|
||
|
|
test('saves correct bytes to disk', () async {
|
||
|
|
final bytes = Uint8List.fromList([0xDE, 0xAD, 0xBE, 0xEF]);
|
||
|
|
final client = MockClient(
|
||
|
|
(_) async => http.Response.bytes(bytes, 200),
|
||
|
|
);
|
||
|
|
final path = '${tmpDir.path}/data.bin';
|
||
|
|
await makeActor(client).handle(
|
||
|
|
DownloadFile(url: 'https://example.com/file', savePath: path),
|
||
|
|
);
|
||
|
|
expect(await File(path).readAsBytes(), equals(bytes));
|
||
|
|
});
|
||
|
|
|
||
|
|
test('sends GET request to the correct URL', () async {
|
||
|
|
http.Request? captured;
|
||
|
|
final client = MockClient((request) async {
|
||
|
|
captured = request;
|
||
|
|
return http.Response.bytes([0], 200);
|
||
|
|
});
|
||
|
|
await makeActor(client).handle(
|
||
|
|
DownloadFile(
|
||
|
|
url: 'https://example.com/assets/image.png',
|
||
|
|
savePath: '${tmpDir.path}/image.png',
|
||
|
|
),
|
||
|
|
);
|
||
|
|
expect(captured!.method, equals('GET'));
|
||
|
|
expect(
|
||
|
|
captured!.url.toString(),
|
||
|
|
equals('https://example.com/assets/image.png'),
|
||
|
|
);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('non-2xx response throws', () async {
|
||
|
|
for (final status in [400, 403, 404, 500]) {
|
||
|
|
final client = MockClient(
|
||
|
|
(_) async => http.Response.bytes([], status),
|
||
|
|
);
|
||
|
|
await expectLater(
|
||
|
|
makeActor(client).handle(
|
||
|
|
DownloadFile(
|
||
|
|
url: 'https://example.com/file',
|
||
|
|
savePath: '${tmpDir.path}/out.bin',
|
||
|
|
),
|
||
|
|
),
|
||
|
|
throwsA(isA<Exception>()),
|
||
|
|
);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|