2
This commit is contained in:
1 parent
cce34e7960
commit
b49e096355
56 files changed
+8343
-296
No files matched your search
@@ -0,0 +1,401 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:archive/archive.dart';
|
||||
import 'package:code_editor/models/distro_manifest.dart';
|
||||
import 'package:code_editor/services/distro_image_resolver.dart';
|
||||
import 'package:code_editor/services/distro_installer.dart';
|
||||
import 'package:code_editor/services/low_memory_xz_decoder.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
const sampleIndexSystem = '''
|
||||
# LXC Images Mirror index
|
||||
debian;bookworm;arm64;default;20260912_05:24;/images/debian/bookworm/arm64/default/20260912_05:24/
|
||||
debian;bookworm;arm64;default;20260913_05:24;/images/debian/bookworm/arm64/default/20260913_05:24/
|
||||
debian;bookworm;amd64;default;20260913_05:24;/images/debian/bookworm/amd64/default/20260913_05:24/
|
||||
archlinux;current;arm64;default;20260913_04:18;/images/archlinux/current/arm64/default/20260913_04:18/
|
||||
archlinux;current;amd64;default;20260913_04:18;/images/archlinux/current/amd64/default/20260913_04:18/
|
||||
fedora;43;arm64;default;20260913_20:33;/images/fedora/43/arm64/default/20260913_20:33/
|
||||
fedora;43;amd64;default;20260913_20:33;/images/fedora/43/amd64/default/20260913_20:33/
|
||||
''';
|
||||
|
||||
group('DistroIndexEntry & DistroImageResolver Tests', () {
|
||||
late DistroImageResolver resolver;
|
||||
|
||||
setUp(() {
|
||||
resolver = DistroImageResolver();
|
||||
resolver.invalidateCache();
|
||||
resolver.customIndexContent = sampleIndexSystem;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
resolver.customIndexContent = null;
|
||||
resolver.invalidateCache();
|
||||
});
|
||||
|
||||
test('parseIndex extracts all valid entries', () {
|
||||
final entries = DistroImageResolver.parseIndex(sampleIndexSystem);
|
||||
expect(entries.length, 7);
|
||||
expect(entries.first.distribution, 'debian');
|
||||
expect(entries.first.release, 'bookworm');
|
||||
expect(entries.first.arch, 'arm64');
|
||||
expect(entries.first.variant, 'default');
|
||||
expect(entries.first.buildDate, '20260912_05:24');
|
||||
expect(entries.first.path, '/images/debian/bookworm/arm64/default/20260912_05:24/');
|
||||
});
|
||||
|
||||
test('toLxcArch maps arm64 and x86_64 correctly', () {
|
||||
expect(DistroImageResolver.toLxcArch(DistroArch.arm64), 'arm64');
|
||||
expect(DistroImageResolver.toLxcArch(DistroArch.x86_64), 'amd64');
|
||||
});
|
||||
|
||||
test('resolveDownloadUrl picks latest build date for debian arm64', () async {
|
||||
final debian = DistroRepository.getById('debian')!;
|
||||
final tsinghua = DistroRepository.getMirrorById('tsinghua');
|
||||
|
||||
final url = await resolver.resolveDownloadUrl(
|
||||
item: debian,
|
||||
arch: DistroArch.arm64,
|
||||
mirror: tsinghua,
|
||||
);
|
||||
|
||||
// 应该选择 20260913_05:24 而不是旧的 20260912_05:24
|
||||
expect(
|
||||
url,
|
||||
'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/bookworm/arm64/default/20260913_05:24/rootfs.tar.xz',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveDownloadUrl resolves archlinux on different mirrors', () async {
|
||||
final arch = DistroRepository.getById('arch')!;
|
||||
final bfsu = DistroRepository.getMirrorById('bfsu');
|
||||
|
||||
final url = await resolver.resolveDownloadUrl(
|
||||
item: arch,
|
||||
arch: DistroArch.x86_64,
|
||||
mirror: bfsu,
|
||||
);
|
||||
|
||||
expect(
|
||||
url,
|
||||
'https://mirrors.bfsu.edu.cn/lxc-images/images/archlinux/current/amd64/default/20260913_04:18/rootfs.tar.xz',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveDownloadUrl resolves fedora 43 arm64', () async {
|
||||
final fedora = DistroRepository.getById('fedora')!;
|
||||
final iscas = DistroRepository.getMirrorById('iscas');
|
||||
|
||||
final url = await resolver.resolveDownloadUrl(
|
||||
item: fedora,
|
||||
arch: DistroArch.arm64,
|
||||
mirror: iscas,
|
||||
);
|
||||
|
||||
expect(
|
||||
url,
|
||||
'https://mirror.iscas.ac.cn/lxc-images/images/fedora/43/arm64/default/20260913_20:33/rootfs.tar.xz',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveDownloadUrl throws HttpException when image is not in index', () async {
|
||||
const emptyIndex = '# Empty index\n';
|
||||
resolver.customIndexContent = emptyIndex;
|
||||
|
||||
final debian = DistroRepository.getById('debian')!;
|
||||
final tsinghua = DistroRepository.getMirrorById('tsinghua');
|
||||
|
||||
expect(
|
||||
() => resolver.resolveDownloadUrl(
|
||||
item: debian,
|
||||
arch: DistroArch.arm64,
|
||||
mirror: tsinghua,
|
||||
),
|
||||
throwsA(isA<HttpException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveDownloadUrl returns builtin asset path directly for builtin distro', () async {
|
||||
final alpine = DistroRepository.getById('alpine')!;
|
||||
final tsinghua = DistroRepository.getMirrorById('tsinghua');
|
||||
|
||||
final url = await resolver.resolveDownloadUrl(
|
||||
item: alpine,
|
||||
arch: DistroArch.arm64,
|
||||
mirror: tsinghua,
|
||||
);
|
||||
|
||||
expect(url, 'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz');
|
||||
});
|
||||
});
|
||||
|
||||
group('DistroInstaller Archive Decoding Tests', () {
|
||||
test('installFromBytes succeeds with valid TarGz archive bytes', () async {
|
||||
// 创建包含一个测试文件的 TarGz 内存包
|
||||
final archive = Archive();
|
||||
archive.addFile(ArchiveFile('test.txt', 5, utf8.encode('hello')));
|
||||
final tarBytes = TarEncoder().encode(archive);
|
||||
final gzBytes = Uint8List.fromList(GZipEncoder().encode(tarBytes)!);
|
||||
|
||||
final tempDir = Directory.systemTemp.createTempSync('installer_test_');
|
||||
try {
|
||||
await DistroInstaller.installFromBytes(
|
||||
tarGzBytes: gzBytes,
|
||||
targetDir: tempDir,
|
||||
);
|
||||
|
||||
final testFile = File('${tempDir.path}/test.txt');
|
||||
expect(testFile.existsSync(), isTrue);
|
||||
expect(testFile.readAsStringSync(), 'hello');
|
||||
} finally {
|
||||
if (tempDir.existsSync()) {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('installFromBytes succeeds with valid TarXZ archive bytes', () async {
|
||||
// 创建包含一个测试文件的 TarXZ 内存包
|
||||
final archive = Archive();
|
||||
archive.addFile(ArchiveFile('greet.txt', 5, utf8.encode('world')));
|
||||
final tarBytes = TarEncoder().encode(archive);
|
||||
final xzBytes = encodeValidXz(tarBytes);
|
||||
|
||||
final tempDir = Directory.systemTemp.createTempSync('installer_xz_test_');
|
||||
try {
|
||||
await DistroInstaller.installFromBytes(
|
||||
tarGzBytes: xzBytes,
|
||||
targetDir: tempDir,
|
||||
);
|
||||
|
||||
final testFile = File('${tempDir.path}/greet.txt');
|
||||
expect(testFile.existsSync(), isTrue);
|
||||
expect(testFile.readAsStringSync(), 'world');
|
||||
} finally {
|
||||
if (tempDir.existsSync()) {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('installFromFile directly extracts TarXZ file on disk', () async {
|
||||
final archive = Archive();
|
||||
archive.addFile(ArchiveFile('direct.txt', 6, utf8.encode('direct')));
|
||||
final tarBytes = TarEncoder().encode(archive);
|
||||
final xzBytes = encodeValidXz(tarBytes);
|
||||
|
||||
final tempDir = Directory.systemTemp.createTempSync('installer_file_test_');
|
||||
final archiveFile = File('${tempDir.path}/test.tar.xz');
|
||||
archiveFile.writeAsBytesSync(xzBytes);
|
||||
|
||||
final outDir = Directory('${tempDir.path}/rootfs');
|
||||
try {
|
||||
await DistroInstaller.installFromFile(
|
||||
archiveFile: archiveFile,
|
||||
targetDir: outDir,
|
||||
);
|
||||
|
||||
final testFile = File('${outDir.path}/direct.txt');
|
||||
expect(testFile.existsSync(), isTrue);
|
||||
expect(testFile.readAsStringSync(), 'direct');
|
||||
} finally {
|
||||
if (tempDir.existsSync()) {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('installFromFile cancellation throws DistroInstallCancelledException and rolls back targetDir', () async {
|
||||
final archive = Archive();
|
||||
archive.addFile(ArchiveFile('cancel.txt', 6, utf8.encode('cancel')));
|
||||
final tarBytes = TarEncoder().encode(archive);
|
||||
final xzBytes = encodeValidXz(tarBytes);
|
||||
|
||||
final tempDir = Directory.systemTemp.createTempSync('installer_cancel_test_');
|
||||
final archiveFile = File('${tempDir.path}/test.tar.xz');
|
||||
archiveFile.writeAsBytesSync(xzBytes);
|
||||
|
||||
final outDir = Directory('${tempDir.path}/rootfs');
|
||||
try {
|
||||
expect(
|
||||
() => DistroInstaller.installFromFile(
|
||||
archiveFile: archiveFile,
|
||||
targetDir: outDir,
|
||||
isCancelled: () => true,
|
||||
),
|
||||
throwsA(isA<DistroInstallCancelledException>()),
|
||||
);
|
||||
|
||||
// 验证回滚:目标目录不残留
|
||||
expect(outDir.existsSync(), isFalse);
|
||||
} finally {
|
||||
if (tempDir.existsSync()) {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('LowMemoryXZDecoder decodes valid XZ stream directly to sink', () async {
|
||||
final inputBytes = utf8.encode('Low memory streaming XZ decoding test string! 1234567890');
|
||||
final xzBytes = encodeValidXz(inputBytes);
|
||||
|
||||
final tempDir = Directory.systemTemp.createTempSync('low_mem_xz_test_');
|
||||
final outFile = File('${tempDir.path}/out.bin');
|
||||
final outSink = outFile.openWrite();
|
||||
|
||||
final decoder = LowMemoryXZDecoder();
|
||||
var progressFired = false;
|
||||
try {
|
||||
decoder.decodeToSink(
|
||||
InputStream(xzBytes),
|
||||
outSink,
|
||||
onProgress: (decompressed, compPos) {
|
||||
progressFired = true;
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
await outSink.flush();
|
||||
await outSink.close();
|
||||
}
|
||||
|
||||
expect(outFile.existsSync(), isTrue);
|
||||
expect(outFile.readAsBytesSync(), inputBytes);
|
||||
expect(progressFired, isTrue);
|
||||
|
||||
tempDir.deleteSync(recursive: true);
|
||||
});
|
||||
|
||||
test('installFromFile extracts multiple files, subdirectories and reports progress', () async {
|
||||
final archive = Archive();
|
||||
archive.addFile(ArchiveFile('sub/dir/one.txt', 5, utf8.encode('one..')));
|
||||
archive.addFile(ArchiveFile('sub/dir/two.txt', 5, utf8.encode('two..')));
|
||||
archive.addFile(ArchiveFile('root.txt', 4, utf8.encode('root')));
|
||||
final tarBytes = TarEncoder().encode(archive);
|
||||
final xzBytes = encodeValidXz(tarBytes);
|
||||
|
||||
final tempDir = Directory.systemTemp.createTempSync('installer_multi_test_');
|
||||
final archiveFile = File('${tempDir.path}/distro.tar.xz');
|
||||
archiveFile.writeAsBytesSync(xzBytes);
|
||||
|
||||
final outDir = Directory('${tempDir.path}/rootfs');
|
||||
final progressList = <double>[];
|
||||
|
||||
try {
|
||||
await DistroInstaller.installFromFile(
|
||||
archiveFile: archiveFile,
|
||||
targetDir: outDir,
|
||||
onProgress: (prog, msg) {
|
||||
progressList.add(prog);
|
||||
},
|
||||
);
|
||||
|
||||
expect(File('${outDir.path}/sub/dir/one.txt').readAsStringSync(), 'one..');
|
||||
expect(File('${outDir.path}/sub/dir/two.txt').readAsStringSync(), 'two..');
|
||||
expect(File('${outDir.path}/root.txt').readAsStringSync(), 'root');
|
||||
expect(progressList.isNotEmpty, isTrue);
|
||||
expect(progressList.last, 1.0);
|
||||
} finally {
|
||||
if (tempDir.existsSync()) {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// 遵循标准 LEB128 与 XZ 格式的纯 Dart 辅助编码器(避免 archive 包中 XZEncoder 的多字节大端序 bug)
|
||||
Uint8List encodeValidXz(List<int> data) {
|
||||
void writeLeb128(BytesBuilder out, int value) {
|
||||
while (value >= 0x80) {
|
||||
out.addByte((value & 0x7f) | 0x80);
|
||||
value >>= 7;
|
||||
}
|
||||
out.addByte(value & 0x7f);
|
||||
}
|
||||
|
||||
final out = BytesBuilder();
|
||||
out.add([253, 55, 122, 88, 90, 0]); // Header magic
|
||||
final headerFlags = [0, 0];
|
||||
out.add(headerFlags);
|
||||
final headerCrc = getCrc32(headerFlags);
|
||||
out.add([headerCrc & 0xff, (headerCrc >> 8) & 0xff, (headerCrc >> 16) & 0xff, (headerCrc >> 24) & 0xff]);
|
||||
|
||||
final lzma2 = BytesBuilder();
|
||||
var offset = 0;
|
||||
var isFirst = true;
|
||||
while (offset < data.length) {
|
||||
final chunkLen = (data.length - offset).clamp(1, 65536);
|
||||
lzma2.addByte(isFirst ? 1 : 2);
|
||||
isFirst = false;
|
||||
final lenMinusOne = chunkLen - 1;
|
||||
lzma2.addByte((lenMinusOne >> 8) & 0xff);
|
||||
lzma2.addByte(lenMinusOne & 0xff);
|
||||
lzma2.add(data.sublist(offset, offset + chunkLen));
|
||||
offset += chunkLen;
|
||||
}
|
||||
lzma2.addByte(0); // end marker
|
||||
|
||||
final lzma2Bytes = lzma2.toBytes();
|
||||
|
||||
final filter = BytesBuilder();
|
||||
writeLeb128(filter, 0x21); // LZMA2
|
||||
writeLeb128(filter, 1);
|
||||
filter.addByte(0); // dict size
|
||||
|
||||
final filterBytes = filter.toBytes();
|
||||
final headerSizeWithoutCrc = 1 + 1 + filterBytes.length;
|
||||
final paddingHeader = (4 - ((headerSizeWithoutCrc + 4) % 4)) % 4;
|
||||
final totalHeaderSize = headerSizeWithoutCrc + paddingHeader + 4;
|
||||
|
||||
final blockHeader = BytesBuilder();
|
||||
blockHeader.addByte((totalHeaderSize ~/ 4) - 1);
|
||||
blockHeader.addByte(0); // flags
|
||||
blockHeader.add(filterBytes);
|
||||
for (var i = 0; i < paddingHeader; i++) {
|
||||
blockHeader.addByte(0);
|
||||
}
|
||||
final bhBytes = blockHeader.toBytes();
|
||||
final bhCrc = getCrc32(bhBytes);
|
||||
|
||||
final blockStart = out.length;
|
||||
out.add(bhBytes);
|
||||
out.add([bhCrc & 0xff, (bhCrc >> 8) & 0xff, (bhCrc >> 16) & 0xff, (bhCrc >> 24) & 0xff]);
|
||||
out.add(lzma2Bytes);
|
||||
|
||||
final paddingBlock = (4 - (out.length % 4)) % 4;
|
||||
for (var i = 0; i < paddingBlock; i++) {
|
||||
out.addByte(0);
|
||||
}
|
||||
|
||||
final unpaddedLength = out.length - blockStart - paddingBlock;
|
||||
|
||||
final indexStart = out.length;
|
||||
final index = BytesBuilder();
|
||||
index.addByte(0); // indicator
|
||||
writeLeb128(index, 1);
|
||||
writeLeb128(index, unpaddedLength);
|
||||
writeLeb128(index, data.length);
|
||||
while (index.length % 4 != 0) {
|
||||
index.addByte(0);
|
||||
}
|
||||
final indexBytes = index.toBytes();
|
||||
final indexCrc = getCrc32(indexBytes);
|
||||
out.add(indexBytes);
|
||||
out.add([indexCrc & 0xff, (indexCrc >> 8) & 0xff, (indexCrc >> 16) & 0xff, (indexCrc >> 24) & 0xff]);
|
||||
final indexTotalSize = out.length - indexStart;
|
||||
|
||||
final footer = BytesBuilder();
|
||||
final indexSizeField = (indexTotalSize ~/ 4) - 1;
|
||||
footer.add([indexSizeField & 0xff, (indexSizeField >> 8) & 0xff, (indexSizeField >> 16) & 0xff, (indexSizeField >> 24) & 0xff]);
|
||||
footer.add([0, 0]);
|
||||
final footerBytes = footer.toBytes();
|
||||
final footerCrc = getCrc32(footerBytes);
|
||||
out.add([footerCrc & 0xff, (footerCrc >> 8) & 0xff, (footerCrc >> 16) & 0xff, (footerCrc >> 24) & 0xff]);
|
||||
out.add(footerBytes);
|
||||
out.add([89, 90]); // 'YZ'
|
||||
|
||||
return out.toBytes();
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/distro_manifest.dart';
|
||||
import 'package:code_editor/providers/distro_provider.dart';
|
||||
import 'package:code_editor/providers/settings_provider.dart';
|
||||
import 'package:code_editor/providers/terminal_provider.dart';
|
||||
import 'package:code_editor/services/distro_download_manager.dart';
|
||||
import 'package:code_editor/services/distro_manager.dart';
|
||||
import 'package:code_editor/views/distro_management_view.dart';
|
||||
import 'package:code_editor/views/settings_view.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late Directory tempBaseDir;
|
||||
late DistroManager manager;
|
||||
late DistroProvider distroProvider;
|
||||
late DistroDownloadManager downloadManager;
|
||||
late SettingsProvider settingsProvider;
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
tempBaseDir = Directory.systemTemp.createTempSync('distro_mgmt_test_');
|
||||
manager = DistroManager();
|
||||
manager.customBaseDir = tempBaseDir;
|
||||
distroProvider = DistroProvider();
|
||||
settingsProvider = SettingsProvider();
|
||||
|
||||
downloadManager = DistroDownloadManager();
|
||||
downloadManager.customPackagesDir = tempBaseDir;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
manager.customBaseDir = null;
|
||||
downloadManager.customPackagesDir = null;
|
||||
if (tempBaseDir.existsSync()) {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
Widget buildTestableWidget({
|
||||
required Widget child,
|
||||
Locale locale = const Locale('zh'),
|
||||
}) {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<SettingsProvider>.value(value: settingsProvider),
|
||||
ChangeNotifierProvider<DistroProvider>.value(value: distroProvider),
|
||||
ChangeNotifierProvider<TerminalProvider>(create: (_) => TerminalProvider()),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: const [
|
||||
AppLocalizations.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: const [
|
||||
Locale('zh'),
|
||||
Locale('en'),
|
||||
],
|
||||
locale: locale,
|
||||
home: child,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
group('DistroManifest & Repository Tests', () {
|
||||
test('currentArchDistros only returns systems supported by current arch', () {
|
||||
final items = DistroRepository.currentArchDistros;
|
||||
expect(items, isNotEmpty);
|
||||
|
||||
// 验证每个条目在当前架构下都有有效的包源
|
||||
for (final item in items) {
|
||||
expect(item.currentPackageSource, isNotNull);
|
||||
expect(item.currentPackageSource!.isNotEmpty, isTrue);
|
||||
}
|
||||
|
||||
// 验证内置系统的 isBuiltin 标识
|
||||
final ubuntu = items.firstWhere((e) => e.id == 'ubuntu');
|
||||
expect(ubuntu.isBuiltin, isTrue);
|
||||
expect(ubuntu.isRecommended, isTrue);
|
||||
|
||||
final alpine = items.firstWhere((e) => e.id == 'alpine');
|
||||
expect(alpine.isBuiltin, isTrue);
|
||||
});
|
||||
|
||||
test('currentArch returns arm64 or x86_64 correctly', () {
|
||||
final arch = DistroManifestItem.currentArch;
|
||||
expect(arch == DistroArch.arm64 || arch == DistroArch.x86_64, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('DistroDownloadManager Tests', () {
|
||||
test('initial state has no active downloads', () {
|
||||
final dm = DistroDownloadManager();
|
||||
expect(dm.isDownloading('unknown_distro'), isFalse);
|
||||
expect(dm.getProgress('unknown_distro'), isNull);
|
||||
});
|
||||
|
||||
test('package file detection and deletion', () async {
|
||||
final dm = DistroDownloadManager();
|
||||
const distroId = 'debian';
|
||||
const fakeUrl = 'https://example.com/debian.tar.xz';
|
||||
|
||||
expect(await dm.isPackageDownloaded(distroId, fakeUrl), isFalse);
|
||||
|
||||
final file = await dm.getPackageFile(distroId, fakeUrl);
|
||||
file.writeAsStringSync('fake tar data');
|
||||
|
||||
expect(await dm.isPackageDownloaded(distroId, fakeUrl), isTrue);
|
||||
|
||||
await dm.deletePackage(distroId, fakeUrl);
|
||||
expect(await dm.isPackageDownloaded(distroId, fakeUrl), isFalse);
|
||||
});
|
||||
|
||||
test('cancelDownload immediately stops background streaming, closes file sinks, and cleans up .part file', () async {
|
||||
await HttpOverrides.runWithHttpOverrides(() async {
|
||||
final dm = DistroDownloadManager();
|
||||
const distroId = 'test_cancel_distro';
|
||||
|
||||
// 启动一个本地 HTTP 服务器模拟网络流式下载
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final serverUrl = 'http://${server.address.address}:${server.port}/test_image.tar.xz';
|
||||
|
||||
final serverCompleter = Completer<void>();
|
||||
|
||||
server.listen((HttpRequest request) async {
|
||||
request.response.bufferOutput = false;
|
||||
request.response.statusCode = HttpStatus.ok;
|
||||
request.response.contentLength = 1000000;
|
||||
request.response.add(List.filled(1024, 42));
|
||||
await request.response.flush();
|
||||
|
||||
// 挂起等待客户端取消
|
||||
await serverCompleter.future;
|
||||
try {
|
||||
await request.response.close();
|
||||
} catch (_) {}
|
||||
});
|
||||
|
||||
final downloadFuture = dm.startDownload(
|
||||
distroId: distroId,
|
||||
downloadUrl: serverUrl,
|
||||
);
|
||||
|
||||
while ((dm.getProgress(distroId)?.receivedBytes ?? 0) == 0) {
|
||||
await Future.delayed(const Duration(milliseconds: 10));
|
||||
}
|
||||
expect(dm.isDownloading(distroId), isTrue);
|
||||
|
||||
final partFile = File(p.join(tempBaseDir.path, '${distroId}_rootfs.tar.xz.part'));
|
||||
expect(partFile.existsSync(), isTrue);
|
||||
|
||||
await dm.cancelDownload(distroId);
|
||||
|
||||
// 验证取消后:
|
||||
// 1. isDownloading 为 false
|
||||
expect(dm.isDownloading(distroId), isFalse);
|
||||
// 2. 进度映射已被重置清理
|
||||
expect(dm.getProgress(distroId), isNull);
|
||||
// 3. .part 临时文件被立即安全删除(Windows 上句柄已完全释放)
|
||||
expect(partFile.existsSync(), isFalse);
|
||||
|
||||
// 唤醒服务端
|
||||
if (!serverCompleter.isCompleted) {
|
||||
serverCompleter.complete();
|
||||
}
|
||||
|
||||
// 等待 startDownload Future 完成,并验证返回值必须为 null 且未生成最终文件
|
||||
final resultFile = await downloadFuture;
|
||||
expect(resultFile, isNull);
|
||||
|
||||
final finalFile = File(p.join(tempBaseDir.path, '${distroId}_rootfs.tar.xz'));
|
||||
expect(finalFile.existsSync(), isFalse);
|
||||
|
||||
await server.close(force: true);
|
||||
}, _TestHttpOverrides());
|
||||
});
|
||||
|
||||
test('re-download after cancellation succeeds cleanly', () async {
|
||||
await HttpOverrides.runWithHttpOverrides(() async {
|
||||
final dm = DistroDownloadManager();
|
||||
const distroId = 'test_redownload_distro';
|
||||
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final serverUrl = 'http://${server.address.address}:${server.port}/test_image.tar.xz';
|
||||
|
||||
server.listen((HttpRequest request) async {
|
||||
request.response.statusCode = HttpStatus.ok;
|
||||
request.response.contentLength = 50;
|
||||
request.response.add(List.filled(50, 99));
|
||||
await request.response.close();
|
||||
});
|
||||
|
||||
// 下载能成功完成
|
||||
final resultFile = await dm.startDownload(
|
||||
distroId: distroId,
|
||||
downloadUrl: serverUrl,
|
||||
);
|
||||
|
||||
expect(resultFile, isNotNull);
|
||||
expect(resultFile!.existsSync(), isTrue);
|
||||
expect(resultFile.lengthSync(), 50);
|
||||
expect(dm.getProgress(distroId)?.state, DistroDownloadState.completed);
|
||||
|
||||
await server.close(force: true);
|
||||
}, _TestHttpOverrides());
|
||||
});
|
||||
|
||||
test('startDownload refuses duplicate download and returns existing file when package already exists', () async {
|
||||
final dm = DistroDownloadManager();
|
||||
const distroId = 'test_existing_distro';
|
||||
const fakeUrl = 'https://example.com/test_image.tar.xz';
|
||||
|
||||
final file = await dm.getPackageFile(distroId, fakeUrl);
|
||||
file.writeAsStringSync('existing package content');
|
||||
|
||||
expect(await dm.isPackageDownloaded(distroId, fakeUrl), isTrue);
|
||||
|
||||
// 再次调用 startDownload,应立即返回已有文件,且不发起网络请求
|
||||
final returnedFile = await dm.startDownload(
|
||||
distroId: distroId,
|
||||
downloadUrl: fakeUrl,
|
||||
);
|
||||
|
||||
expect(returnedFile, isNotNull);
|
||||
expect(returnedFile!.path, file.path);
|
||||
expect(dm.getProgress(distroId)?.state, DistroDownloadState.completed);
|
||||
expect(returnedFile.readAsStringSync(), 'existing package content');
|
||||
});
|
||||
});
|
||||
|
||||
group('DistroManagementView Requirements Tests', () {
|
||||
testWidgets('1. 内置字样完全移除,2. 安装按钮和已安装文本去掉', (tester) async {
|
||||
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 验证返回按键与标题
|
||||
expect(find.byIcon(Icons.arrow_back), findsOneWidget);
|
||||
expect(find.text('系统管理'), findsOneWidget);
|
||||
|
||||
// 验证品牌图标存在
|
||||
expect(find.byType(Image), findsWidgets);
|
||||
|
||||
// 1. 验证“内置”字样完全不存在
|
||||
expect(find.text('内置'), findsNothing);
|
||||
expect(find.text('Built-in'), findsNothing);
|
||||
|
||||
// 2. 验证“安装”按键与“已安装”文本完全不存在
|
||||
expect(find.text('安装'), findsNothing);
|
||||
expect(find.text('Install'), findsNothing);
|
||||
expect(find.text('已安装'), findsNothing);
|
||||
expect(find.text('Installed'), findsNothing);
|
||||
|
||||
// 3. 验证推荐标签保留
|
||||
expect(find.text('推荐'), findsWidgets);
|
||||
});
|
||||
|
||||
testWidgets('3. 选中后无高亮边框 (border 无突出 primary 高亮)', (tester) async {
|
||||
// 预置默认选中 ubuntu
|
||||
await distroProvider.refreshSystems();
|
||||
|
||||
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 获取第一个 Card
|
||||
final cardFinder = find.byType(Card).first;
|
||||
final cardWidget = tester.widget<Card>(cardFinder);
|
||||
final shape = cardWidget.shape as RoundedRectangleBorder;
|
||||
final side = shape.side;
|
||||
|
||||
// 边框宽度为普通 1.0,颜色不是 primary 高亮
|
||||
expect(side.width, 1.0);
|
||||
});
|
||||
|
||||
testWidgets('4. 内置系统 (ubuntu / alpine) 无法删除,右侧无按键', (tester) async {
|
||||
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 在初始未下载任何外部系统的状态下,内置系统右侧没有任何删除按键
|
||||
expect(find.byIcon(Icons.delete_outline), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('4. 点击已就绪的 item 本身直接返回 DistroManifestItem', (tester) async {
|
||||
DistroManifestItem? selectedItem;
|
||||
await tester.pumpWidget(buildTestableWidget(
|
||||
child: Builder(
|
||||
builder: (context) => ElevatedButton(
|
||||
onPressed: () async {
|
||||
selectedItem = await Navigator.of(context).push<DistroManifestItem>(
|
||||
MaterialPageRoute(builder: (_) => const DistroManagementView()),
|
||||
);
|
||||
},
|
||||
child: const Text('Open'),
|
||||
),
|
||||
),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 打开页面
|
||||
await tester.tap(find.text('Open'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 点击已就绪的 Alpine Linux 条目本身
|
||||
await tester.tap(find.text('Alpine Linux'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 确认返回了 DistroManifestItem
|
||||
expect(selectedItem, isNotNull);
|
||||
expect(selectedItem!.id, 'alpine');
|
||||
});
|
||||
|
||||
testWidgets('4. 下载完成的系统右侧显示红色删除按钮,点击弹出删除安装包确认框', (tester) async {
|
||||
// 模拟 debian 安装包已存在于本地目录
|
||||
final debianFile = File(p.join(tempBaseDir.path, 'debian_rootfs.tar.xz'));
|
||||
debianFile.writeAsStringSync('dummy content');
|
||||
|
||||
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// debian 应出现红色删除按钮
|
||||
final deleteBtn = find.byIcon(Icons.delete_outline);
|
||||
expect(deleteBtn, findsOneWidget);
|
||||
|
||||
// 点击删除按钮弹出“确认删除安装包”对话框
|
||||
await tester.tap(deleteBtn);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('确认删除安装包'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('下载完成后页面立即响应更新为就绪状态,无需退出重新进入', (tester) async {
|
||||
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 此时 debian 处于未下载状态,显示“下载”按钮
|
||||
expect(find.text('下载'), findsWidgets);
|
||||
|
||||
// 模拟下载管理器写入完成包
|
||||
final debianFile = await downloadManager.getPackageFile('debian', 'https://example.com/debian.tar.xz');
|
||||
debianFile.writeAsStringSync('debian package content');
|
||||
|
||||
// 触发 startDownload,由于本地文件已完备,会直接更新状态并通知监听器
|
||||
await downloadManager.startDownload(distroId: 'debian', downloadUrl: 'https://example.com/debian.tar.xz');
|
||||
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// debian 的卡片立即就绪,出现红色删除按钮
|
||||
expect(find.byIcon(Icons.delete_outline), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
group('SettingsView Download Mirror Tests', () {
|
||||
testWidgets('设置页面项目下方展示“下载”分组,默认显示清华源', (tester) async {
|
||||
await tester.pumpWidget(buildTestableWidget(child: const SettingsView()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 滚动到“下载”分组可见
|
||||
await tester.scrollUntilVisible(
|
||||
find.text('下载'),
|
||||
300,
|
||||
scrollable: find.byType(Scrollable).first,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 验证“下载”分组标题与“下载源”
|
||||
expect(find.text('下载'), findsOneWidget);
|
||||
expect(find.text('下载源'), findsOneWidget);
|
||||
expect(find.text('清华大学开源软件镜像站 (推荐)'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('点击下载源弹出底部选择菜单,可自由切换至北外源', (tester) async {
|
||||
await tester.pumpWidget(buildTestableWidget(child: const SettingsView()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 滚动到“下载源”可见
|
||||
await tester.scrollUntilVisible(
|
||||
find.text('下载源'),
|
||||
300,
|
||||
scrollable: find.byType(Scrollable).first,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 点击下载源条目弹出 BottomSheet
|
||||
await tester.tap(find.text('下载源'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('选择下载源'), findsOneWidget);
|
||||
expect(find.text('北京外国语大学开源软件镜像站'), findsOneWidget);
|
||||
expect(find.text('中国科学院软件研究所开源镜像站'), findsOneWidget);
|
||||
expect(find.text('LinuxContainers 官方镜像源'), findsOneWidget);
|
||||
|
||||
// 选中北外源
|
||||
await tester.tap(find.text('北京外国语大学开源软件镜像站'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 验证 SettingsProvider 状态更新
|
||||
expect(settingsProvider.downloadMirrorId, 'bfsu');
|
||||
expect(find.text('北京外国语大学开源软件镜像站'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
class _TestHttpOverrides extends HttpOverrides {}
|
||||
|
||||
@@ -7,12 +7,47 @@ import 'package:code_editor/providers/terminal_provider.dart';
|
||||
import 'package:code_editor/services/distro_installer.dart';
|
||||
import 'package:code_editor/services/distro_manager.dart';
|
||||
import 'package:code_editor/widgets/distro_selector_dialog.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class MockDistroFilePicker extends FilePicker {
|
||||
String? pickedPath;
|
||||
|
||||
@override
|
||||
Future<FilePickerResult?> pickFiles({
|
||||
String? dialogTitle,
|
||||
String? initialDirectory,
|
||||
FileType type = FileType.any,
|
||||
List<String>? allowedExtensions,
|
||||
Function(FilePickerStatus)? onFileLoading,
|
||||
bool allowCompression = false,
|
||||
int compressionQuality = 30,
|
||||
bool allowMultiple = false,
|
||||
bool withData = false,
|
||||
bool withReadStream = false,
|
||||
bool lockParentWindow = false,
|
||||
bool readSequential = false,
|
||||
}) async {
|
||||
if (pickedPath == null) return null;
|
||||
return FilePickerResult([
|
||||
PlatformFile(name: p.basename(pickedPath!), size: 10, path: pickedPath),
|
||||
]);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool?> clearTemporaryFiles() async => true;
|
||||
|
||||
@override
|
||||
Future<String?> getDirectoryPath({String? dialogTitle, bool lockParentWindow = false, String? initialDirectory}) async => null;
|
||||
|
||||
@override
|
||||
Future<String?> saveFile({String? dialogTitle, String? fileName, String? initialDirectory, FileType type = FileType.any, List<String>? allowedExtensions, Uint8List? bytes, bool lockParentWindow = false}) async => null;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
@@ -171,6 +206,92 @@ void main() {
|
||||
expect(launchConfig.arguments, contains('-k'));
|
||||
expect(launchConfig.arguments, contains('5.4.0-proot'));
|
||||
expect(launchConfig.environment['PROOT_L2S_DIR'], isNotNull);
|
||||
expect(launchConfig.environment['SHELL'], equals('/bin/sh'));
|
||||
expect(launchConfig.arguments, contains('SHELL=/bin/sh'));
|
||||
expect(launchConfig.arguments, contains('-l'));
|
||||
expect(launchConfig.arguments, contains('-i'));
|
||||
});
|
||||
|
||||
test('buildLaunchConfig 自动检测 rootfs 中的 /bin/bash 并设置为交互式登录 Shell', () async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'bash_cfg.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
|
||||
await manager.importFromCustomTarGz(systemName: 'ubuntu_env', tarGzFile: tempGzFile);
|
||||
final rootDir = await manager.getSystemRootDir('ubuntu_env');
|
||||
|
||||
// 模拟 Ubuntu 根文件系统中自带的 bash
|
||||
final bashFile = File(p.join(rootDir.path, 'bin', 'bash'));
|
||||
await bashFile.create(recursive: true);
|
||||
|
||||
final launchConfig = await manager.buildLaunchConfig(
|
||||
systemName: 'ubuntu_env',
|
||||
workspacePath: tempBaseDir.path,
|
||||
);
|
||||
|
||||
expect(launchConfig.environment['SHELL'], equals('/bin/bash'));
|
||||
expect(launchConfig.arguments, contains('SHELL=/bin/bash'));
|
||||
expect(launchConfig.arguments, contains('/bin/bash'));
|
||||
expect(launchConfig.arguments, contains('-l'));
|
||||
expect(launchConfig.arguments, contains('-i'));
|
||||
|
||||
// 验证 Android 宿主特权/辅助组自动写入 /etc/group 与 .hushlogin 生成
|
||||
final groupFile = File(p.join(rootDir.path, 'etc', 'group'));
|
||||
expect(groupFile.existsSync(), isTrue);
|
||||
final groupContent = groupFile.readAsStringSync();
|
||||
expect(groupContent, contains('aid_inet:x:3003:'));
|
||||
expect(groupContent, contains('aid_ext_data_rw:x:1077:'));
|
||||
expect(groupContent, contains('aid_everybody:x:9997:'));
|
||||
|
||||
final hushFile = File(p.join(rootDir.path, 'root', '.hushlogin'));
|
||||
expect(hushFile.existsSync(), isTrue);
|
||||
});
|
||||
|
||||
test('buildLaunchConfig 针对不同发行版(Alpine ash vs passwd 自定义 shell)自适应启动参数', () async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'alpine_cfg.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
|
||||
await manager.importFromCustomTarGz(systemName: 'alpine_env', tarGzFile: tempGzFile);
|
||||
final rootDir = await manager.getSystemRootDir('alpine_env');
|
||||
|
||||
// 1. 模拟 Alpine(无 bash,自带 ash,/etc/passwd 中 root 为 /bin/ash)
|
||||
final ashFile = File(p.join(rootDir.path, 'bin', 'ash'));
|
||||
await ashFile.create(recursive: true);
|
||||
final passwdFile = File(p.join(rootDir.path, 'etc', 'passwd'));
|
||||
await passwdFile.writeAsString('root:x:0:0:root:/root:/bin/ash\n');
|
||||
|
||||
final alpineConfig = await manager.buildLaunchConfig(
|
||||
systemName: 'alpine_env',
|
||||
workspacePath: tempBaseDir.path,
|
||||
);
|
||||
expect(alpineConfig.environment['SHELL'], equals('/bin/ash'));
|
||||
expect(alpineConfig.arguments, contains('/bin/ash'));
|
||||
expect(alpineConfig.arguments, contains('-l'));
|
||||
expect(alpineConfig.arguments, contains('-i'));
|
||||
|
||||
// 2. 模拟用户安装并切换为 /bin/zsh
|
||||
final zshFile = File(p.join(rootDir.path, 'bin', 'zsh'));
|
||||
await zshFile.create(recursive: true);
|
||||
await passwdFile.writeAsString('root:x:0:0:root:/root:/bin/zsh\n');
|
||||
|
||||
final zshConfig = await manager.buildLaunchConfig(
|
||||
systemName: 'alpine_env',
|
||||
workspacePath: tempBaseDir.path,
|
||||
);
|
||||
expect(zshConfig.environment['SHELL'], equals('/bin/zsh'));
|
||||
expect(zshConfig.arguments, contains('/bin/zsh'));
|
||||
expect(zshConfig.arguments, contains('-l'));
|
||||
expect(zshConfig.arguments, contains('-i'));
|
||||
});
|
||||
|
||||
test('buildLaunchConfig 在 host 模式下正确配置 SHELL 与 -i 交互模式', () async {
|
||||
final hostConfig = await manager.buildLaunchConfig(
|
||||
systemName: 'host',
|
||||
workspacePath: tempBaseDir.path,
|
||||
);
|
||||
|
||||
expect(hostConfig.executable, equals('/system/bin/sh'));
|
||||
expect(hostConfig.arguments, contains('-i'));
|
||||
expect(hostConfig.environment['SHELL'], equals('/system/bin/sh'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -294,5 +415,59 @@ void main() {
|
||||
// 验证存在高危删除按钮
|
||||
expect(find.byIcon(Icons.delete_outline), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('DistroSelectorDialog 导入外部系统选择不支持的格式时显示错误 Toast 并中止流程', (tester) async {
|
||||
final mockPicker = MockDistroFilePicker();
|
||||
FilePicker.platform = mockPicker;
|
||||
|
||||
// 设置选中的文件为不受支持的格式(如 .zip 或 .txt)
|
||||
final unsupportedFile = File(p.join(tempBaseDir.path, 'rootfs_image.zip'))..writeAsStringSync('zip content');
|
||||
mockPicker.pickedPath = unsupportedFile.path;
|
||||
|
||||
final distroProvider = DistroProvider();
|
||||
await tester.runAsync(() async {
|
||||
await distroProvider.init();
|
||||
});
|
||||
|
||||
await tester.pumpWidget(
|
||||
MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<DistroProvider>.value(value: distroProvider),
|
||||
ChangeNotifierProvider<TerminalProvider>(create: (_) => TerminalProvider()),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: const Locale('zh'),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: const Scaffold(
|
||||
body: DistroSelectorDialog(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 点击导入按钮打开 PopupMenu
|
||||
final importButton = find.byIcon(Icons.add_circle_outline);
|
||||
expect(importButton, findsOneWidget);
|
||||
await tester.tap(importButton);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 点击“从外部导入 (.tar.gz)”
|
||||
final externalItem = find.text('从外部导入 (.tar.gz)');
|
||||
expect(externalItem, findsOneWidget);
|
||||
await tester.tap(externalItem);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
|
||||
// 验证不应弹出系统名称输入弹窗
|
||||
expect(find.text('导入外部系统'), findsNothing);
|
||||
|
||||
// 验证弹出指定格式错误 Toast
|
||||
expect(find.text('不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)'), findsOneWidget);
|
||||
|
||||
// 等待 Toast 定时器安全结束
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import 'dart:io';
|
||||
import 'package:archive/archive_io.dart';
|
||||
import 'package:code_editor/services/internal_project_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late Directory tempBaseDir;
|
||||
late InternalProjectService service;
|
||||
|
||||
setUp(() {
|
||||
tempBaseDir = Directory.systemTemp.createTempSync('internal_project_test_');
|
||||
service = InternalProjectService.instance;
|
||||
service.customProjectsDir = Directory(p.join(tempBaseDir.path, 'files', 'projects'));
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
service.customProjectsDir = null;
|
||||
if (tempBaseDir.existsSync()) {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
group('InternalProjectService Unit Tests', () {
|
||||
test('getProjectsDirectory creates directory if it does not exist', () async {
|
||||
final dir = await service.getProjectsDirectory();
|
||||
expect(dir.existsSync(), isTrue);
|
||||
expect(p.split(dir.path), containsAll(['files', 'projects']));
|
||||
});
|
||||
|
||||
test('createProject successfully creates new project folder', () async {
|
||||
final projectDir = await service.createProject('my_cool_project');
|
||||
expect(projectDir.existsSync(), isTrue);
|
||||
expect(p.basename(projectDir.path), 'my_cool_project');
|
||||
|
||||
final exists = await service.projectExists('my_cool_project');
|
||||
expect(exists, isTrue);
|
||||
});
|
||||
|
||||
test('createProject throws when name is empty or already exists', () async {
|
||||
expect(() => service.createProject(' '), throwsA(isA<FileSystemException>()));
|
||||
|
||||
await service.createProject('unique_project');
|
||||
expect(() => service.createProject('unique_project'), throwsA(isA<FileSystemException>()));
|
||||
});
|
||||
|
||||
test('listProjects returns sorted directories', () async {
|
||||
await service.createProject('project_c');
|
||||
await service.createProject('project_a');
|
||||
await service.createProject('project_b');
|
||||
|
||||
final list = await service.listProjects();
|
||||
expect(list.length, 3);
|
||||
expect(p.basename(list[0].path), 'project_a');
|
||||
expect(p.basename(list[1].path), 'project_b');
|
||||
expect(p.basename(list[2].path), 'project_c');
|
||||
});
|
||||
|
||||
test('renameProject successfully renames project folder', () async {
|
||||
final original = await service.createProject('old_name');
|
||||
expect(original.existsSync(), isTrue);
|
||||
|
||||
final renamed = await service.renameProject(original, 'new_name');
|
||||
expect(original.existsSync(), isFalse);
|
||||
expect(renamed.existsSync(), isTrue);
|
||||
expect(p.basename(renamed.path), 'new_name');
|
||||
|
||||
final list = await service.listProjects();
|
||||
expect(list.length, 1);
|
||||
expect(p.basename(list[0].path), 'new_name');
|
||||
});
|
||||
|
||||
test('renameProject throws if target name already exists or is empty', () async {
|
||||
final p1 = await service.createProject('p1');
|
||||
await service.createProject('p2');
|
||||
|
||||
expect(() => service.renameProject(p1, ' '), throwsA(isA<FileSystemException>()));
|
||||
expect(() => service.renameProject(p1, 'p2'), throwsA(isA<FileSystemException>()));
|
||||
});
|
||||
|
||||
test('deleteProject recursively deletes project folder', () async {
|
||||
final projectDir = await service.createProject('to_delete');
|
||||
// Create subfile inside project
|
||||
final subFile = File(p.join(projectDir.path, 'main.dart'));
|
||||
await subFile.writeAsString('void main() {}');
|
||||
expect(subFile.existsSync(), isTrue);
|
||||
|
||||
await service.deleteProject(projectDir);
|
||||
expect(projectDir.existsSync(), isFalse);
|
||||
expect(await service.projectExists('to_delete'), isFalse);
|
||||
});
|
||||
|
||||
test('isInternalProject correctly identifies internal vs external paths', () async {
|
||||
final proj = await service.createProject('my_app');
|
||||
expect(service.isInternalProject(proj.path), isTrue);
|
||||
|
||||
expect(service.isInternalProject(null), isFalse);
|
||||
expect(service.isInternalProject(''), isFalse);
|
||||
expect(service.isInternalProject(' '), isFalse);
|
||||
expect(service.isInternalProject('C:/Users/SomeUser/Desktop/other_project'), isFalse);
|
||||
expect(service.isInternalProject('/storage/emulated/0/Download/some_proj'), isFalse);
|
||||
});
|
||||
|
||||
test('importProjectFromArchive extracts archive into new project directory', () async {
|
||||
// Create a test zip file
|
||||
final zipFilePath = p.join(tempBaseDir.path, 'sample_project.zip');
|
||||
final encoder = ZipFileEncoder();
|
||||
encoder.create(zipFilePath);
|
||||
final dummyFile = File(p.join(tempBaseDir.path, 'readme.md'));
|
||||
dummyFile.writeAsStringSync('# Test Project');
|
||||
encoder.addFile(dummyFile);
|
||||
encoder.close();
|
||||
|
||||
final importedDir = await service.importProjectFromArchive(zipFilePath, 'sample_project');
|
||||
expect(importedDir.existsSync(), isTrue);
|
||||
expect(p.basename(importedDir.path), 'sample_project');
|
||||
|
||||
final extractedReadme = File(p.join(importedDir.path, 'readme.md'));
|
||||
expect(extractedReadme.existsSync(), isTrue);
|
||||
expect(extractedReadme.readAsStringSync(), '# Test Project');
|
||||
|
||||
// Verify listing includes imported project
|
||||
final list = await service.listProjects();
|
||||
expect(list.any((d) => p.basename(d.path) == 'sample_project'), isTrue);
|
||||
});
|
||||
|
||||
test('importProjectFromArchive throws when target project already exists or archive missing', () async {
|
||||
await service.createProject('existing_project');
|
||||
|
||||
final zipFilePath = p.join(tempBaseDir.path, 'dummy.zip');
|
||||
expect(
|
||||
() => service.importProjectFromArchive(zipFilePath, 'existing_project'),
|
||||
throwsA(isA<FileSystemException>()),
|
||||
);
|
||||
|
||||
expect(
|
||||
() => service.importProjectFromArchive(zipFilePath, 'non_existent_zip_proj'),
|
||||
throwsA(isA<FileSystemException>()),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,533 @@
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:archive/archive_io.dart';
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/project_history.dart';
|
||||
import 'package:code_editor/providers/project_provider.dart';
|
||||
import 'package:code_editor/providers/run_provider.dart';
|
||||
import 'package:code_editor/providers/settings_provider.dart';
|
||||
import 'package:code_editor/providers/tab_provider.dart';
|
||||
import 'package:code_editor/services/internal_project_service.dart';
|
||||
import 'package:code_editor/views/project_management_view.dart';
|
||||
import 'package:code_editor/widgets/code_editor_drawer.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class MockFilePicker extends FilePicker {
|
||||
String? pickedPath;
|
||||
|
||||
@override
|
||||
Future<FilePickerResult?> pickFiles({
|
||||
String? dialogTitle,
|
||||
String? initialDirectory,
|
||||
FileType type = FileType.any,
|
||||
List<String>? allowedExtensions,
|
||||
Function(FilePickerStatus)? onFileLoading,
|
||||
bool allowCompression = false,
|
||||
int compressionQuality = 30,
|
||||
bool allowMultiple = false,
|
||||
bool withData = false,
|
||||
bool withReadStream = false,
|
||||
bool lockParentWindow = false,
|
||||
bool readSequential = false,
|
||||
}) async {
|
||||
if (pickedPath == null) return null;
|
||||
return FilePickerResult([
|
||||
PlatformFile(name: p.basename(pickedPath!), size: 10, path: pickedPath),
|
||||
]);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool?> clearTemporaryFiles() async => true;
|
||||
|
||||
@override
|
||||
Future<String?> getDirectoryPath({
|
||||
String? dialogTitle,
|
||||
bool lockParentWindow = false,
|
||||
String? initialDirectory,
|
||||
}) async => null;
|
||||
|
||||
@override
|
||||
Future<String?> saveFile({
|
||||
String? dialogTitle,
|
||||
String? fileName,
|
||||
String? initialDirectory,
|
||||
FileType type = FileType.any,
|
||||
List<String>? allowedExtensions,
|
||||
Uint8List? bytes,
|
||||
bool lockParentWindow = false,
|
||||
}) async => null;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late Directory tempBaseDir;
|
||||
late InternalProjectService projectService;
|
||||
late ProjectProvider projectProvider;
|
||||
late TabProvider tabProvider;
|
||||
late SettingsProvider settingsProvider;
|
||||
late RunProvider runProvider;
|
||||
late MockFilePicker mockFilePicker;
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
tempBaseDir = Directory.systemTemp.createTempSync('project_mgmt_widget_test_');
|
||||
projectService = InternalProjectService.instance;
|
||||
projectService.customProjectsDir = Directory(p.join(tempBaseDir.path, 'files', 'projects'));
|
||||
|
||||
projectProvider = ProjectProvider();
|
||||
tabProvider = TabProvider()..bindProjectProvider(projectProvider);
|
||||
settingsProvider = SettingsProvider();
|
||||
runProvider = RunProvider();
|
||||
|
||||
mockFilePicker = MockFilePicker();
|
||||
FilePicker.platform = mockFilePicker;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
projectService.customProjectsDir = null;
|
||||
if (tempBaseDir.existsSync()) {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
Widget buildTestWidget({
|
||||
required Widget child,
|
||||
Locale locale = const Locale('zh'),
|
||||
}) {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<ProjectProvider>.value(value: projectProvider),
|
||||
ChangeNotifierProvider<TabProvider>.value(value: tabProvider),
|
||||
ChangeNotifierProvider<SettingsProvider>.value(value: settingsProvider),
|
||||
ChangeNotifierProvider<RunProvider>.value(value: runProvider),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: const [
|
||||
AppLocalizations.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: const [
|
||||
Locale('zh'),
|
||||
Locale('en'),
|
||||
],
|
||||
locale: locale,
|
||||
home: child,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
group('Drawer Open Project Menu Tests', () {
|
||||
testWidgets('Clicking open project button pops up menu with two options (zh & en)', (tester) async {
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const Scaffold(
|
||||
drawer: CodeEditorDrawer(),
|
||||
body: Center(child: Text('Main')),
|
||||
),
|
||||
locale: const Locale('zh'),
|
||||
));
|
||||
|
||||
// Open drawer
|
||||
final scaffoldState = tester.state<ScaffoldState>(find.byType(Scaffold));
|
||||
scaffoldState.openDrawer();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Find the folder_open popup menu button
|
||||
final openButton = find.byIcon(Icons.folder_open);
|
||||
expect(openButton, findsOneWidget);
|
||||
|
||||
await tester.tap(openButton);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Check popup menu items
|
||||
expect(find.text('从软件内打开'), findsOneWidget);
|
||||
expect(find.text('从外部打开'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Clicking open from app navigates to ProjectManagementView', (tester) async {
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const Scaffold(
|
||||
drawer: CodeEditorDrawer(),
|
||||
body: Center(child: Text('Main')),
|
||||
),
|
||||
));
|
||||
|
||||
final scaffoldState = tester.state<ScaffoldState>(find.byType(Scaffold));
|
||||
scaffoldState.openDrawer();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byIcon(Icons.folder_open));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('从软件内打开'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Should now be on ProjectManagementView
|
||||
expect(find.byType(ProjectManagementView), findsOneWidget);
|
||||
expect(find.text('项目'), findsOneWidget);
|
||||
expect(find.byTooltip('新建项目'), findsOneWidget);
|
||||
expect(find.byTooltip('从外部导入'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Drawer header subtitle shows project name for internal projects, root path for external projects', (tester) async {
|
||||
final internalProj = await projectService.createProject('my_internal_app');
|
||||
|
||||
// 1. 设置内部项目
|
||||
projectProvider.setHistoryForTesting(ProjectHistory(
|
||||
rootPath: internalProj.path,
|
||||
lastOpenedFilePath: null,
|
||||
));
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const Scaffold(
|
||||
drawer: CodeEditorDrawer(),
|
||||
body: Center(child: Text('Main')),
|
||||
),
|
||||
));
|
||||
|
||||
final scaffoldState = tester.state<ScaffoldState>(find.byType(Scaffold));
|
||||
scaffoldState.openDrawer();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 内部项目应当只显示项目名称,而非完整根路径
|
||||
expect(find.text('my_internal_app'), findsOneWidget);
|
||||
expect(find.text(internalProj.path), findsNothing);
|
||||
|
||||
// 2. 切换为外部项目
|
||||
final externalPath = p.normalize('C:/outside/external_project');
|
||||
projectProvider.setHistoryForTesting(ProjectHistory(
|
||||
rootPath: externalPath,
|
||||
lastOpenedFilePath: null,
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 外部项目应显示完整根路径
|
||||
expect(find.text(externalPath), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
group('ProjectManagementView Feature Tests', () {
|
||||
testWidgets('Empty state displays placeholder icon and text', (tester) async {
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('暂无项目,点击右上角新建项目'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.folder_open_outlined), findsOneWidget);
|
||||
expect(find.text('项目'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.arrow_back), findsOneWidget);
|
||||
expect(find.byIcon(Icons.file_upload_outlined), findsOneWidget);
|
||||
expect(find.byTooltip('从外部导入'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.add), findsOneWidget);
|
||||
expect(find.byTooltip('新建项目'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Creating a new project via dialog adds item to the list', (tester) async {
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Tap "新建项目" button (IconButton with tooltip '新建项目')
|
||||
await tester.tap(find.byTooltip('新建项目'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Dialog should appear
|
||||
expect(find.text('请输入项目名称'), findsOneWidget);
|
||||
|
||||
// Enter project name
|
||||
await tester.enterText(find.byType(TextFormField), 'my_flutter_app');
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Tap confirm button ("确定")
|
||||
await tester.tap(find.text('确定'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
|
||||
// Project item should now exist in list
|
||||
expect(find.text('my_flutter_app'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.edit_outlined), findsOneWidget);
|
||||
expect(find.byIcon(Icons.delete_outline), findsOneWidget);
|
||||
|
||||
// Verify directory was actually created
|
||||
final projects = await projectService.listProjects();
|
||||
expect(projects.length, 1);
|
||||
expect(p.basename(projects.first.path), 'my_flutter_app');
|
||||
});
|
||||
|
||||
testWidgets('Renaming a project updates folder and UI', (tester) async {
|
||||
await projectService.createProject('initial_proj');
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('initial_proj'), findsOneWidget);
|
||||
|
||||
// Tap edit button
|
||||
await tester.tap(find.byIcon(Icons.edit_outlined));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Dialog should appear with 'initial_proj'
|
||||
expect(find.text('重命名项目'), findsOneWidget);
|
||||
expect(find.text('initial_proj'), findsWidgets);
|
||||
|
||||
// Enter new name
|
||||
await tester.enterText(find.byType(TextFormField), 'renamed_proj');
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('确定'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
|
||||
// Check UI updated
|
||||
expect(find.text('renamed_proj'), findsOneWidget);
|
||||
expect(find.text('initial_proj'), findsNothing);
|
||||
|
||||
// Verify on disk
|
||||
final projects = await projectService.listProjects();
|
||||
expect(projects.length, 1);
|
||||
expect(p.basename(projects.first.path), 'renamed_proj');
|
||||
});
|
||||
|
||||
testWidgets('Deleting a project pops confirmation dialog and deletes folder on confirm', (tester) async {
|
||||
await projectService.createProject('project_to_remove');
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('project_to_remove'), findsOneWidget);
|
||||
|
||||
// Tap delete button
|
||||
await tester.tap(find.byIcon(Icons.delete_outline));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Confirmation dialog should appear
|
||||
expect(find.byType(AlertDialog), findsOneWidget);
|
||||
expect(find.text('删除项目'), findsOneWidget);
|
||||
expect(find.text('确定要删除项目 "project_to_remove" 吗?此操作不可逆。'), findsOneWidget);
|
||||
|
||||
// Tap cancel first
|
||||
await tester.tap(find.text('取消'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Item should still be there
|
||||
expect(find.text('project_to_remove'), findsOneWidget);
|
||||
|
||||
// Tap delete again and confirm
|
||||
await tester.tap(find.byIcon(Icons.delete_outline));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('删除'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
|
||||
// Should now be empty
|
||||
expect(find.text('project_to_remove'), findsNothing);
|
||||
expect(find.text('暂无项目,点击右上角新建项目'), findsOneWidget);
|
||||
|
||||
// Verify on disk
|
||||
final projects = await projectService.listProjects();
|
||||
expect(projects, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('Tapping project item opens project and returns to main view', (tester) async {
|
||||
final projDir = await projectService.createProject('opened_project');
|
||||
// Create a dummy file in the project
|
||||
File(p.join(projDir.path, 'hello.txt')).writeAsStringSync('world');
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: Builder(
|
||||
builder: (context) => Scaffold(
|
||||
body: ElevatedButton(
|
||||
onPressed: () => Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => const ProjectManagementView()),
|
||||
),
|
||||
child: const Text('Go to PM'),
|
||||
),
|
||||
),
|
||||
),
|
||||
));
|
||||
|
||||
// Navigate to ProjectManagementView
|
||||
await tester.tap(find.text('Go to PM'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(ProjectManagementView), findsOneWidget);
|
||||
expect(find.text('opened_project'), findsOneWidget);
|
||||
|
||||
// Tap the project item inside runAsync so FileService buildTree stream can complete
|
||||
await tester.runAsync(() async {
|
||||
await tester.tap(find.text('opened_project'));
|
||||
await Future.delayed(const Duration(milliseconds: 200));
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Should have popped back to previous view
|
||||
expect(find.byType(ProjectManagementView), findsNothing);
|
||||
expect(find.text('Go to PM'), findsOneWidget);
|
||||
|
||||
// Verify ProjectProvider opened the project
|
||||
expect(projectProvider.rootPath, p.normalize(projDir.path));
|
||||
});
|
||||
|
||||
testWidgets('Full English locale validation (no hardcoded Chinese)', (tester) async {
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
locale: const Locale('en'),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// English texts in AppBar and empty state
|
||||
expect(find.text('Projects'), findsOneWidget);
|
||||
expect(find.byTooltip('New Project'), findsOneWidget);
|
||||
expect(find.byTooltip('Import from External'), findsOneWidget);
|
||||
expect(find.text('No projects yet, click top right to create one'), findsOneWidget);
|
||||
|
||||
// Tap New Project
|
||||
await tester.tap(find.byTooltip('New Project'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Enter project name'), findsOneWidget);
|
||||
expect(find.text('Cancel'), findsOneWidget);
|
||||
expect(find.text('Confirm'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Importing project from external archive prompts for name and extracts upon confirmation', (tester) async {
|
||||
// Create a test zip
|
||||
final zipFilePath = p.join(tempBaseDir.path, 'imported_pkg.zip');
|
||||
final encoder = ZipFileEncoder();
|
||||
encoder.create(zipFilePath);
|
||||
final dummyFile = File(p.join(tempBaseDir.path, 'info.txt'));
|
||||
dummyFile.writeAsStringSync('package contents');
|
||||
encoder.addFile(dummyFile);
|
||||
encoder.close();
|
||||
|
||||
mockFilePicker.pickedPath = zipFilePath;
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Tap import button
|
||||
await tester.tap(find.byTooltip('从外部导入'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Dialog should appear with default name from filename "imported_pkg"
|
||||
expect(find.text('确认项目名称'), findsOneWidget);
|
||||
expect(find.text('imported_pkg'), findsOneWidget);
|
||||
|
||||
// Confirm project name inside runAsync so extractFileToDisk file streams can complete
|
||||
await tester.runAsync(() async {
|
||||
await tester.tap(find.text('确定'));
|
||||
await tester.pump();
|
||||
for (int i = 0; i < 20; i++) {
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
if (await projectService.projectExists('imported_pkg')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
|
||||
// Should now show in list
|
||||
expect(find.text('imported_pkg'), findsOneWidget);
|
||||
|
||||
// Verify directory on disk
|
||||
final projects = await projectService.listProjects();
|
||||
expect(projects.length, 1);
|
||||
expect(p.basename(projects.first.path), 'imported_pkg');
|
||||
expect(File(p.join(projects.first.path, 'info.txt')).existsSync(), isTrue);
|
||||
});
|
||||
|
||||
testWidgets('Canceling import dialog does not import or create project', (tester) async {
|
||||
final zipFilePath = p.join(tempBaseDir.path, 'cancel_test.zip');
|
||||
final encoder = ZipFileEncoder();
|
||||
encoder.create(zipFilePath);
|
||||
encoder.close();
|
||||
|
||||
mockFilePicker.pickedPath = zipFilePath;
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byTooltip('从外部导入'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('确认项目名称'), findsOneWidget);
|
||||
|
||||
// Tap Cancel
|
||||
await tester.tap(find.text('取消'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// No projects created
|
||||
expect(find.text('cancel_test'), findsNothing);
|
||||
expect(find.text('暂无项目,点击右上角新建项目'), findsOneWidget);
|
||||
final projects = await projectService.listProjects();
|
||||
expect(projects, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('Project items do not have Divider separators', (tester) async {
|
||||
await projectService.createProject('project_1');
|
||||
await projectService.createProject('project_2');
|
||||
await projectService.createProject('project_3');
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('project_1'), findsOneWidget);
|
||||
expect(find.text('project_2'), findsOneWidget);
|
||||
expect(find.text('project_3'), findsOneWidget);
|
||||
|
||||
// Verify no Divider widgets exist between items
|
||||
expect(find.byType(Divider), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('Selecting unsupported file format shows error toast and aborts import', (tester) async {
|
||||
final invalidFile = File(p.join(tempBaseDir.path, 'unsupported.pdf'));
|
||||
invalidFile.writeAsStringSync('not an archive');
|
||||
mockFilePicker.pickedPath = invalidFile.path;
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Tap import button
|
||||
await tester.tap(find.byTooltip('从外部导入'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
|
||||
// Confirmation dialog should NOT appear
|
||||
expect(find.text('确认项目名称'), findsNothing);
|
||||
|
||||
// Error toast should appear
|
||||
expect(find.text('不支持的文件格式,仅支持压缩包格式 (.zip, .tar.gz, .tar.xz, .tar 等)'), findsOneWidget);
|
||||
|
||||
// Wait for toast to dismiss
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
|
||||
// Verify no project created
|
||||
final projects = await projectService.listProjects();
|
||||
expect(projects, isEmpty);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/run_task.dart';
|
||||
import 'package:code_editor/providers/run_provider.dart';
|
||||
import 'package:code_editor/services/run_task_storage_service.dart';
|
||||
import 'package:code_editor/services/project_task_detector.dart';
|
||||
import 'package:code_editor/widgets/run_tasks_dialog.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
@@ -78,5 +83,330 @@ void main() {
|
||||
expect(tasks.any((t) => t.id == 'detected_cmake_build_run'), isTrue);
|
||||
expect(tasks.any((t) => t.id == 'detected_cmake_clean'), isTrue);
|
||||
});
|
||||
|
||||
test('ProjectTaskDetector detects Makefile, Gradle, Cargo, NPM, Dart and source files', () async {
|
||||
final makefile = File('${tempDir.path}/Makefile');
|
||||
await makefile.writeAsString('all:\n\tgcc main.c\n');
|
||||
|
||||
final cargoToml = File('${tempDir.path}/Cargo.toml');
|
||||
await cargoToml.writeAsString('[package]\nname = "demo"\n');
|
||||
|
||||
final packageJson = File('${tempDir.path}/package.json');
|
||||
await packageJson.writeAsString('{"name": "demo"}');
|
||||
|
||||
final pubspec = File('${tempDir.path}/pubspec.yaml');
|
||||
await pubspec.writeAsString('name: demo\n');
|
||||
|
||||
final gradlew = File('${tempDir.path}/gradlew');
|
||||
await gradlew.writeAsString('#!/bin/sh\n');
|
||||
|
||||
final cppFile = File('${tempDir.path}/main.cpp');
|
||||
await cppFile.writeAsString('int main() { return 0; }');
|
||||
|
||||
final tasks = await ProjectTaskDetector.detect(
|
||||
projectRoot: tempDir.path,
|
||||
currentFilePath: cppFile.path,
|
||||
);
|
||||
|
||||
expect(tasks.any((t) => t.id == 'detected_single_cpp'), isTrue);
|
||||
expect(tasks.first.command, contains('g++'));
|
||||
expect(tasks.any((t) => t.id == 'detected_make_default'), isTrue);
|
||||
expect(tasks.any((t) => t.id == 'detected_cargo_run'), isTrue);
|
||||
expect(tasks.any((t) => t.id == 'detected_npm_start'), isTrue);
|
||||
expect(tasks.any((t) => t.id == 'detected_dart_run'), isTrue);
|
||||
expect(tasks.any((t) => t.id == 'detected_gradle_run'), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('RunTask Localization Tests', () {
|
||||
testWidgets('getLocalizedDescription returns correct localized text in zh and en for all detected tasks', (tester) async {
|
||||
late AppLocalizations l10nZh;
|
||||
late AppLocalizations l10nEn;
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: const [
|
||||
AppLocalizations.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: const [Locale('zh'), Locale('en')],
|
||||
locale: const Locale('zh'),
|
||||
home: Builder(builder: (ctx) {
|
||||
l10nZh = AppLocalizations.of(ctx)!;
|
||||
return const SizedBox();
|
||||
}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: const [
|
||||
AppLocalizations.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: const [Locale('zh'), Locale('en')],
|
||||
locale: const Locale('en'),
|
||||
home: Builder(builder: (ctx) {
|
||||
l10nEn = AppLocalizations.of(ctx)!;
|
||||
return const SizedBox();
|
||||
}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
const gradleRunTask = RunTask(
|
||||
id: 'detected_gradle_run',
|
||||
name: 'Gradle: Run',
|
||||
command: 'sh ./gradlew run',
|
||||
source: TaskSource.detected,
|
||||
);
|
||||
expect(gradleRunTask.getLocalizedDescription(l10nZh), '执行应用程序主入口');
|
||||
expect(gradleRunTask.getLocalizedDescription(l10nEn), 'Execute application main entrypoint');
|
||||
|
||||
const gradleAssembleTask = RunTask(
|
||||
id: 'detected_gradle_assemble',
|
||||
name: 'Gradle: Assemble Debug',
|
||||
command: 'sh ./gradlew assembleDebug',
|
||||
source: TaskSource.detected,
|
||||
);
|
||||
expect(gradleAssembleTask.getLocalizedDescription(l10nZh), '构建调试输出包');
|
||||
expect(gradleAssembleTask.getLocalizedDescription(l10nEn), 'Build debug output package');
|
||||
|
||||
const gradleBuildTask = RunTask(
|
||||
id: 'detected_gradle_build',
|
||||
name: 'Gradle: Build',
|
||||
command: 'sh ./gradlew build',
|
||||
source: TaskSource.detected,
|
||||
);
|
||||
expect(gradleBuildTask.getLocalizedDescription(l10nZh), '执行完整构建与测试');
|
||||
expect(gradleBuildTask.getLocalizedDescription(l10nEn), 'Execute full build and tests');
|
||||
|
||||
const cmakeBuildRunTask = RunTask(
|
||||
id: 'detected_cmake_build_run',
|
||||
name: 'CMake: Build & Run',
|
||||
command: 'cmake -B build',
|
||||
source: TaskSource.detected,
|
||||
);
|
||||
expect(cmakeBuildRunTask.getLocalizedDescription(l10nZh), '配置、编译并尝试启动生成的目标程序');
|
||||
expect(cmakeBuildRunTask.getLocalizedDescription(l10nEn), 'Configure, build, and try launching the target executable');
|
||||
});
|
||||
|
||||
testWidgets('RunTasksDialog displays English descriptions when locale is en', (tester) async {
|
||||
const detectedTasks = [
|
||||
RunTask(
|
||||
id: 'detected_gradle_run',
|
||||
name: 'Gradle: Run',
|
||||
command: 'sh ./gradlew run',
|
||||
source: TaskSource.detected,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_gradle_assemble',
|
||||
name: 'Gradle: Assemble Debug',
|
||||
command: 'sh ./gradlew assembleDebug',
|
||||
source: TaskSource.detected,
|
||||
),
|
||||
RunTask(
|
||||
id: 'detected_gradle_build',
|
||||
name: 'Gradle: Build',
|
||||
command: 'sh ./gradlew build',
|
||||
source: TaskSource.detected,
|
||||
),
|
||||
];
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: const [
|
||||
AppLocalizations.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: const [Locale('zh'), Locale('en')],
|
||||
locale: const Locale('en'),
|
||||
home: Scaffold(
|
||||
body: RunTasksDialog(
|
||||
customTasks: const [],
|
||||
detectedTasks: detectedTasks,
|
||||
onTaskSelected: (_) {},
|
||||
onEditCustomTasks: () {},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// In English, subtitles should be in English
|
||||
expect(find.text('Execute application main entrypoint'), findsOneWidget);
|
||||
expect(find.text('Build debug output package'), findsOneWidget);
|
||||
expect(find.text('Execute full build and tests'), findsOneWidget);
|
||||
|
||||
// Chinese text should NOT appear
|
||||
expect(find.text('执行应用程序主入口'), findsNothing);
|
||||
expect(find.text('构建调试输出包'), findsNothing);
|
||||
expect(find.text('执行完整构建与测试'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('RunTasksDialog displays Chinese descriptions when locale is zh', (tester) async {
|
||||
const detectedTasks = [
|
||||
RunTask(
|
||||
id: 'detected_gradle_run',
|
||||
name: 'Gradle: Run',
|
||||
command: 'sh ./gradlew run',
|
||||
source: TaskSource.detected,
|
||||
),
|
||||
];
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: const [
|
||||
AppLocalizations.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: const [Locale('zh'), Locale('en')],
|
||||
locale: const Locale('zh'),
|
||||
home: Scaffold(
|
||||
body: RunTasksDialog(
|
||||
customTasks: const [],
|
||||
detectedTasks: detectedTasks,
|
||||
onTaskSelected: (_) {},
|
||||
onEditCustomTasks: () {},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// In Chinese, subtitles should be in Chinese
|
||||
expect(find.text('执行应用程序主入口'), findsOneWidget);
|
||||
expect(find.text('Execute application main entrypoint'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('Missing distro dialog renders without overflow in English on narrow screen', (tester) async {
|
||||
tester.view.physicalSize = const Size(320, 640);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: const [
|
||||
AppLocalizations.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: const [Locale('zh'), Locale('en')],
|
||||
locale: const Locale('en'),
|
||||
home: Builder(
|
||||
builder: (context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return Scaffold(
|
||||
body: AlertDialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
title: Row(
|
||||
children: [
|
||||
const Icon(Icons.warning_amber_rounded, color: Colors.orange, size: 24),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.missingDistroTitle,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: Text(l10n.noDistroAvailableContent),
|
||||
actions: [
|
||||
TextButton(onPressed: () {}, child: Text(l10n.cancel)),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () {},
|
||||
icon: const Icon(Icons.dns_outlined, size: 18),
|
||||
label: Text(l10n.systemManagement),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.text('System Environment Not Ready'), findsOneWidget);
|
||||
expect(find.text('No available Linux execution environment detected.\n\nProject tasks need to run inside a Linux container. Please install or download a Linux system first (e.g. Ubuntu or Alpine).'), findsOneWidget);
|
||||
});
|
||||
|
||||
test('RunProvider 切换项目时运行任务完全隔离,不发生上一个项目的任务污染', () async {
|
||||
final projectADir = await Directory.systemTemp.createTemp('project_a_');
|
||||
final projectBDir = await Directory.systemTemp.createTemp('project_b_');
|
||||
addTearDown(() async {
|
||||
if (await projectADir.exists()) await projectADir.delete(recursive: true);
|
||||
if (await projectBDir.exists()) await projectBDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
final runProvider = RunProvider();
|
||||
|
||||
// 1. 打开项目 A,并执行并记录一个任务
|
||||
await runProvider.onProjectOpened(projectADir.path);
|
||||
expect(runProvider.currentProjectRoot, equals(projectADir.path));
|
||||
expect(runProvider.lastRunTask, isNull);
|
||||
|
||||
const taskA = RunTask(
|
||||
id: 'task_a_build',
|
||||
name: 'Build Project A',
|
||||
command: 'echo "building A"',
|
||||
source: TaskSource.custom,
|
||||
);
|
||||
await runProvider.addCustomTask(taskA);
|
||||
await runProvider.setLastRunTask(taskA);
|
||||
|
||||
expect(runProvider.lastRunTask?.id, equals('task_a_build'));
|
||||
expect(runProvider.lastRunTaskId, equals('task_a_build'));
|
||||
|
||||
// 2. 切换至项目 B(新项目,无持久化任务)
|
||||
await runProvider.onProjectOpened(projectBDir.path);
|
||||
expect(runProvider.currentProjectRoot, equals(projectBDir.path));
|
||||
|
||||
// 验证:项目 A 的 lastRunTask 与 customTasks 绝不会泄漏到项目 B!
|
||||
expect(runProvider.lastRunTask, isNull);
|
||||
expect(runProvider.lastRunTaskId, isNull);
|
||||
expect(runProvider.customTasks, isEmpty);
|
||||
expect(runProvider.allTasks.any((t) => t.id == 'task_a_build'), isFalse);
|
||||
|
||||
// 3. 在项目 B 添加并执行任务 B
|
||||
const taskB = RunTask(
|
||||
id: 'task_b_test',
|
||||
name: 'Test Project B',
|
||||
command: 'pytest',
|
||||
source: TaskSource.custom,
|
||||
);
|
||||
await runProvider.addCustomTask(taskB);
|
||||
await runProvider.setLastRunTask(taskB);
|
||||
expect(runProvider.lastRunTask?.id, equals('task_b_test'));
|
||||
|
||||
// 4. 切回项目 A,应该恢复项目 A 自身的历史任务
|
||||
await runProvider.onProjectOpened(projectADir.path);
|
||||
expect(runProvider.currentProjectRoot, equals(projectADir.path));
|
||||
expect(runProvider.lastRunTask?.id, equals('task_a_build'));
|
||||
expect(runProvider.lastRunTaskId, equals('task_a_build'));
|
||||
expect(runProvider.customTasks.any((t) => t.id == 'task_a_build'), isTrue);
|
||||
expect(runProvider.customTasks.any((t) => t.id == 'task_b_test'), isFalse);
|
||||
|
||||
// 5. 关闭项目
|
||||
runProvider.onProjectClosed();
|
||||
expect(runProvider.currentProjectRoot, isNull);
|
||||
expect(runProvider.lastRunTask, isNull);
|
||||
expect(runProvider.lastRunTaskId, isNull);
|
||||
expect(runProvider.allTasks, isEmpty);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
import 'dart:io';
|
||||
import 'package:code_editor/models/terminal_session.dart';
|
||||
import 'package:code_editor/services/distro_manager.dart';
|
||||
import 'package:code_editor/services/toolchain_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
group('ToolchainService Tool Detection Tests', () {
|
||||
test('detectRequiredTools extracts compiler and runtime tools correctly', () {
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('make').map((r) => r.checkBinary),
|
||||
contains('make'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('cmake -B build && cmake --build build').map((r) => r.checkBinary),
|
||||
contains('cmake'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('gcc "./main.c" -o /tmp/a.out && /tmp/a.out').map((r) => r.checkBinary),
|
||||
contains('gcc'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('g++ "./main.cpp" -o /tmp/a.out').map((r) => r.checkBinary),
|
||||
contains('g++'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('python3 "./script.py"').map((r) => r.checkBinary),
|
||||
contains('python3'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('npm start').map((r) => r.checkBinary),
|
||||
contains('npm'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('node app.js').map((r) => r.checkBinary),
|
||||
contains('node'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('cargo run').map((r) => r.checkBinary),
|
||||
contains('cargo'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('rustc main.rs').map((r) => r.checkBinary),
|
||||
contains('rustc'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('go run main.go').map((r) => r.checkBinary),
|
||||
contains('go'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('./gradlew assembleDebug').map((r) => r.checkBinary),
|
||||
contains('java'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('sh ./gradlew run').map((r) => r.checkBinary),
|
||||
contains('java'),
|
||||
);
|
||||
|
||||
expect(
|
||||
ToolchainService.detectRequiredTools('echo "hello world" && ls -la'),
|
||||
isEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
test('detectRequiredTools deduplicates multiple calls to the same tool', () {
|
||||
final reqs = ToolchainService.detectRequiredTools('cmake -B build && cmake --build build');
|
||||
expect(reqs.length, equals(1));
|
||||
expect(reqs.first.checkBinary, equals('cmake'));
|
||||
});
|
||||
});
|
||||
|
||||
group('ToolchainService Command Resolution Tests', () {
|
||||
test('unknown distro returns raw command directly without modification', () {
|
||||
const cmd = 'make';
|
||||
final resolved = ToolchainService.resolveCommand(cmd, DistroFamily.unknown);
|
||||
expect(resolved, equals('make'));
|
||||
});
|
||||
|
||||
test('non-toolchain command returns raw command directly', () {
|
||||
const cmd = 'echo "test" && ls -la';
|
||||
final resolved = ToolchainService.resolveCommand(cmd, DistroFamily.ubuntu);
|
||||
expect(resolved, equals('echo "test" && ls -la'));
|
||||
});
|
||||
|
||||
test('Alpine generates apk install preamble for make', () {
|
||||
final resolved = ToolchainService.resolveCommand('make', DistroFamily.alpine);
|
||||
expect(resolved, contains('command -v make'));
|
||||
expect(resolved, contains('apk update && apk add --no-cache make build-base'));
|
||||
expect(resolved, contains('make 编译构建工具'));
|
||||
expect(resolved, endsWith('&& (make)'));
|
||||
});
|
||||
|
||||
test('Ubuntu generates apt-get install preamble for make', () {
|
||||
final resolved = ToolchainService.resolveCommand('make', DistroFamily.ubuntu);
|
||||
expect(resolved, contains('command -v make'));
|
||||
expect(resolved, contains('apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential'));
|
||||
expect(resolved, contains('make 编译构建工具'));
|
||||
expect(resolved, endsWith('&& (make)'));
|
||||
});
|
||||
|
||||
test('Debian generates apt-get install preamble for cmake', () {
|
||||
final resolved = ToolchainService.resolveCommand('cmake -B build', DistroFamily.debian);
|
||||
expect(resolved, contains('command -v cmake'));
|
||||
expect(resolved, contains('apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential'));
|
||||
expect(resolved, endsWith('&& (cmake -B build)'));
|
||||
});
|
||||
|
||||
test('Arch generates pacman install preamble for gcc', () {
|
||||
final resolved = ToolchainService.resolveCommand('gcc main.c', DistroFamily.arch);
|
||||
expect(resolved, contains('command -v gcc'));
|
||||
expect(resolved, contains('pacman -Sy --noconfirm base-devel'));
|
||||
expect(resolved, endsWith('&& (gcc main.c)'));
|
||||
});
|
||||
|
||||
test('Fedora generates dnf install preamble for python3', () {
|
||||
final resolved = ToolchainService.resolveCommand('python3 app.py', DistroFamily.fedora);
|
||||
expect(resolved, contains('command -v python3'));
|
||||
expect(resolved, contains('dnf install -y python3 python3-pip'));
|
||||
expect(resolved, endsWith('&& (python3 app.py)'));
|
||||
});
|
||||
|
||||
test('Multiple tools generate multiple chained checks', () {
|
||||
final resolved = ToolchainService.resolveCommand('gcc main.c && python3 test.py', DistroFamily.ubuntu);
|
||||
expect(resolved, contains('command -v gcc'));
|
||||
expect(resolved, contains('command -v python3'));
|
||||
expect(resolved, contains('apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential'));
|
||||
expect(resolved, contains('apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip'));
|
||||
expect(resolved, endsWith('&& (gcc main.c && python3 test.py)'));
|
||||
});
|
||||
|
||||
test('When tool is already physically installed in rootfs, resolveCommand returns raw command without any preamble', () {
|
||||
final tempRootfs = Directory.systemTemp.createTempSync('rootfs_installed_test_');
|
||||
try {
|
||||
final usrBin = Directory(p.join(tempRootfs.path, 'usr', 'bin'))..createSync(recursive: true);
|
||||
File(p.join(usrBin.path, 'make')).writeAsStringSync('#!/bin/sh\n');
|
||||
|
||||
// make 已物理存在于 /usr/bin/make
|
||||
final resolved = ToolchainService.resolveCommand(
|
||||
'make',
|
||||
DistroFamily.debian,
|
||||
rootDir: tempRootfs,
|
||||
);
|
||||
|
||||
// 核心断言:直接返回原命令 "make",绝不包含任何多余脚本或回显!
|
||||
expect(resolved, equals('make'));
|
||||
} finally {
|
||||
if (tempRootfs.existsSync()) {
|
||||
try {
|
||||
tempRootfs.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('When tool is missing in rootfs, resolveCommand writes /root/.ce_setup.sh and executes it cleanly', () {
|
||||
final tempRootfs = Directory.systemTemp.createTempSync('rootfs_missing_test_');
|
||||
try {
|
||||
final resolved = ToolchainService.resolveCommand(
|
||||
'make',
|
||||
DistroFamily.debian,
|
||||
rootDir: tempRootfs,
|
||||
);
|
||||
|
||||
// 生成了 /root/.ce_setup.sh
|
||||
final setupFile = File(p.join(tempRootfs.path, 'root', '.ce_setup.sh'));
|
||||
expect(setupFile.existsSync(), isTrue);
|
||||
expect(setupFile.readAsStringSync(), contains('build-essential'));
|
||||
|
||||
// 终端仅执行简洁命令
|
||||
expect(resolved, equals('sh /root/.ce_setup.sh && (make)'));
|
||||
} finally {
|
||||
if (tempRootfs.existsSync()) {
|
||||
try {
|
||||
tempRootfs.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('When command is a multiline script, resolveCommand writes /root/.ce_task.sh and returns sh /root/.ce_task.sh', () {
|
||||
final tempRootfs = Directory.systemTemp.createTempSync('rootfs_multiline_test_');
|
||||
try {
|
||||
const multilineScript = '''
|
||||
echo "Step 1: start"
|
||||
mkdir -p output
|
||||
echo "done" > output/result.txt
|
||||
''';
|
||||
|
||||
final resolved = ToolchainService.resolveCommand(
|
||||
multilineScript,
|
||||
DistroFamily.alpine,
|
||||
rootDir: tempRootfs,
|
||||
);
|
||||
|
||||
expect(resolved, equals('sh /root/.ce_task.sh'));
|
||||
final taskFile = File(p.join(tempRootfs.path, 'root', '.ce_task.sh'));
|
||||
expect(taskFile.existsSync(), isTrue);
|
||||
final content = taskFile.readAsStringSync();
|
||||
expect(content, contains('#!/bin/sh'));
|
||||
expect(content, contains('set -e'));
|
||||
expect(content, contains('echo "Step 1: start"'));
|
||||
expect(content, contains('echo "done" > output/result.txt'));
|
||||
// 确保没有 Windows \r\n
|
||||
expect(content.contains('\r'), isFalse);
|
||||
} finally {
|
||||
if (tempRootfs.existsSync()) {
|
||||
try {
|
||||
tempRootfs.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('Multiline script with missing tools injects installer before script in .ce_task.sh', () {
|
||||
final tempRootfs = Directory.systemTemp.createTempSync('rootfs_multiline_tool_test_');
|
||||
try {
|
||||
const multilineScript = '''
|
||||
gcc main.c -o app
|
||||
./app
|
||||
''';
|
||||
|
||||
final resolved = ToolchainService.resolveCommand(
|
||||
multilineScript,
|
||||
DistroFamily.debian,
|
||||
rootDir: tempRootfs,
|
||||
);
|
||||
|
||||
expect(resolved, equals('sh /root/.ce_task.sh'));
|
||||
final taskFile = File(p.join(tempRootfs.path, 'root', '.ce_task.sh'));
|
||||
expect(taskFile.existsSync(), isTrue);
|
||||
final content = taskFile.readAsStringSync();
|
||||
// 验证同时包含了安装引导与用户脚本
|
||||
expect(content, contains('build-essential'));
|
||||
expect(content, contains('gcc main.c -o app'));
|
||||
} finally {
|
||||
if (tempRootfs.existsSync()) {
|
||||
try {
|
||||
tempRootfs.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
group('DistroManager detectDistroFamily Tests', () {
|
||||
late Directory tempBaseDir;
|
||||
late DistroManager manager;
|
||||
|
||||
setUp(() {
|
||||
tempBaseDir = Directory.systemTemp.createTempSync('distro_detect_test_');
|
||||
manager = DistroManager();
|
||||
manager.customBaseDir = tempBaseDir;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
if (tempBaseDir.existsSync()) {
|
||||
try {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
manager.customBaseDir = null;
|
||||
});
|
||||
|
||||
test('detects Alpine correctly from apk directory and release file', () async {
|
||||
final rootfs = Directory(p.join(tempBaseDir.path, 'my_alpine', 'rootfs'));
|
||||
Directory(p.join(rootfs.path, 'etc', 'apk')).createSync(recursive: true);
|
||||
File(p.join(rootfs.path, 'etc', 'alpine-release')).writeAsStringSync('3.20.3\n');
|
||||
|
||||
final family = await manager.detectDistroFamily('my_alpine');
|
||||
expect(family, equals(DistroFamily.alpine));
|
||||
});
|
||||
|
||||
test('detects Ubuntu correctly from os-release and apt directory', () async {
|
||||
final rootfs = Directory(p.join(tempBaseDir.path, 'ubuntu_dev', 'rootfs'));
|
||||
Directory(p.join(rootfs.path, 'etc', 'apt')).createSync(recursive: true);
|
||||
File(p.join(rootfs.path, 'etc', 'os-release')).writeAsStringSync('NAME="Ubuntu"\nID=ubuntu\nVERSION_ID="24.04"\n');
|
||||
|
||||
final family = await manager.detectDistroFamily('ubuntu_dev');
|
||||
expect(family, equals(DistroFamily.ubuntu));
|
||||
});
|
||||
|
||||
test('detects Debian correctly when apt is present without ubuntu markers', () async {
|
||||
final rootfs = Directory(p.join(tempBaseDir.path, 'debian_sys', 'rootfs'));
|
||||
Directory(p.join(rootfs.path, 'etc', 'apt')).createSync(recursive: true);
|
||||
File(p.join(rootfs.path, 'etc', 'os-release')).writeAsStringSync('NAME="Debian GNU/Linux"\nID=debian\n');
|
||||
|
||||
final family = await manager.detectDistroFamily('debian_sys');
|
||||
expect(family, equals(DistroFamily.debian));
|
||||
});
|
||||
|
||||
test('detects Arch Linux correctly from pacman.d directory', () async {
|
||||
final rootfs = Directory(p.join(tempBaseDir.path, 'arch_sys', 'rootfs'));
|
||||
Directory(p.join(rootfs.path, 'etc', 'pacman.d')).createSync(recursive: true);
|
||||
|
||||
final family = await manager.detectDistroFamily('arch_sys');
|
||||
expect(family, equals(DistroFamily.arch));
|
||||
});
|
||||
|
||||
test('detects Fedora correctly from yum.repos.d directory', () async {
|
||||
final rootfs = Directory(p.join(tempBaseDir.path, 'fedora_sys', 'rootfs'));
|
||||
Directory(p.join(rootfs.path, 'etc', 'yum.repos.d')).createSync(recursive: true);
|
||||
|
||||
final family = await manager.detectDistroFamily('fedora_sys');
|
||||
expect(family, equals(DistroFamily.fedora));
|
||||
});
|
||||
|
||||
test('returns unknown for host system or unrecognized custom distro', () async {
|
||||
expect(await manager.detectDistroFamily('host'), equals(DistroFamily.unknown));
|
||||
|
||||
final rootfs = Directory(p.join(tempBaseDir.path, 'custom_sys', 'rootfs'));
|
||||
Directory(p.join(rootfs.path, 'etc')).createSync(recursive: true);
|
||||
expect(await manager.detectDistroFamily('custom_sys'), equals(DistroFamily.unknown));
|
||||
|
||||
expect(await manager.detectDistroFamily('non_existent'), equals(DistroFamily.unknown));
|
||||
});
|
||||
});
|
||||
|
||||
group('TerminalSession executeCommand Tests', () {
|
||||
test('executeCommand reports unstarted when PTY launch fails or is unstarted', () async {
|
||||
final session = TerminalSession(
|
||||
id: 'test_session',
|
||||
autoStartProcess: false,
|
||||
);
|
||||
|
||||
await session.executeCommand('echo test');
|
||||
expect(session.bufferText, contains('无法执行命令:终端环境未启动或启动失败'));
|
||||
|
||||
session.dispose();
|
||||
});
|
||||
|
||||
test('clear resets terminal screen', () {
|
||||
final session = TerminalSession(
|
||||
id: 'test_clear_session',
|
||||
autoStartProcess: false,
|
||||
);
|
||||
session.write('Some previous output');
|
||||
session.clear();
|
||||
// clear emits VT100 ANSI sequences
|
||||
expect(session.bufferText.trim(), isEmpty);
|
||||
session.dispose();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -2103,9 +2103,6 @@ void main() {
|
||||
await tester.scrollUntilVisible(find.text('终端小键盘'), 200);
|
||||
expect(find.text('终端小键盘'), findsOneWidget);
|
||||
|
||||
await tester.scrollUntilVisible(find.text('编辑终端键盘配置'), 200);
|
||||
expect(find.text('编辑终端键盘配置'), findsOneWidget);
|
||||
|
||||
// 关闭终端小键盘后,配置入口被禁用但编辑区的仍可用
|
||||
final terminalSwitch = find.descendant(
|
||||
of: find.widgetWithText(SwitchListTile, '终端小键盘'),
|
||||
@@ -2119,6 +2116,9 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
expect(settingsProvider.keyboardEnabledFor(KeyboardScope.terminal), isTrue);
|
||||
|
||||
await tester.scrollUntilVisible(find.text('编辑终端键盘配置'), 200);
|
||||
expect(find.text('编辑终端键盘配置'), findsOneWidget);
|
||||
|
||||
// 进入终端键盘配置页:副标题显示“终端”
|
||||
final editorJsonBefore = settingsProvider.keyboardConfigJsonFor(KeyboardScope.editor);
|
||||
await tester.tap(find.text('编辑终端键盘配置'));
|
||||
|
||||
Reference in new issue
Block a user