2
This commit is contained in:
1 parent
b49e096355
commit
63e1fe3861
48 files changed
+5817
-556
No files matched your search
@@ -0,0 +1,186 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:code_editor/services/archive_compressor.dart';
|
||||
import 'package:code_editor/services/archive_extractor.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() {
|
||||
late Directory tempTestDir;
|
||||
|
||||
setUp(() {
|
||||
tempTestDir = Directory.systemTemp.createTempSync('archive_compressor_test_');
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
if (tempTestDir.existsSync()) {
|
||||
try {
|
||||
tempTestDir.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
});
|
||||
|
||||
group('ArchiveCompressor CRC-32 Tests', () {
|
||||
test('standard test vector "123456789" produces 0xCBF43926', () {
|
||||
final input = utf8.encode('123456789');
|
||||
final crc = computeCrc32(input);
|
||||
expect(crc, equals(0xCBF43926));
|
||||
});
|
||||
|
||||
test('empty byte array produces 0', () {
|
||||
final crc = computeCrc32(<int>[]);
|
||||
expect(crc, equals(0));
|
||||
});
|
||||
|
||||
test('incremental chunked calculation matches one-shot calculation', () {
|
||||
final data = Uint8List.fromList(List<int>.generate(20000, (i) => i % 256));
|
||||
final oneShotCrc = computeCrc32(data);
|
||||
|
||||
var chunkedCrc = 0;
|
||||
const chunkSize = 1024;
|
||||
for (var i = 0; i < data.length; i += chunkSize) {
|
||||
final end = (i + chunkSize < data.length) ? i + chunkSize : data.length;
|
||||
chunkedCrc = computeCrc32(data.sublist(i, end), chunkedCrc);
|
||||
}
|
||||
|
||||
expect(chunkedCrc, equals(oneShotCrc));
|
||||
});
|
||||
});
|
||||
|
||||
group('ArchiveCompressor Streaming ZIP Compression Tests', () {
|
||||
test('compresses nested files, empty files, empty dirs and utf-8 names cleanly', () async {
|
||||
final srcDir = Directory(p.join(tempTestDir.path, 'source_project'))..createSync();
|
||||
|
||||
// 1. 普通文件
|
||||
final fileA = File(p.join(srcDir.path, 'main.dart'))..writeAsStringSync('void main() => print("hello");');
|
||||
|
||||
// 2. 多级子目录与文件
|
||||
final subDir = Directory(p.join(srcDir.path, 'src', 'utils'))..createSync(recursive: true);
|
||||
final fileB = File(p.join(subDir.path, 'helper.dart'))..writeAsStringSync('class Helper {}');
|
||||
|
||||
// 3. 空目录
|
||||
Directory(p.join(srcDir.path, 'assets', 'empty_folder')).createSync(recursive: true);
|
||||
|
||||
// 4. 空文件
|
||||
File(p.join(srcDir.path, 'EMPTY.txt')).writeAsStringSync('');
|
||||
|
||||
// 5. 中文与表情等 UTF-8 文件名
|
||||
final fileUtf8 = File(p.join(srcDir.path, '测试项目_说明.md'))..writeAsStringSync('# 中文测试文档\n内容丰富');
|
||||
|
||||
// 6. 大文件 (> 128KB 验证 64KB 多分块流式压缩与 CRC 回填)
|
||||
final largeContent = 'Line of large content for streaming test 1234567890\n' * 3000;
|
||||
final fileLarge = File(p.join(srcDir.path, 'large_file.txt'))..writeAsStringSync(largeContent);
|
||||
|
||||
final zipFile = File(p.join(tempTestDir.path, 'output.zip'));
|
||||
final progressList = <double>[];
|
||||
|
||||
await ArchiveCompressor.zipDirectory(
|
||||
sourceDir: srcDir,
|
||||
targetZipFile: zipFile,
|
||||
onProgress: (p, msg) {
|
||||
progressList.add(p);
|
||||
},
|
||||
);
|
||||
|
||||
expect(zipFile.existsSync(), isTrue);
|
||||
expect(zipFile.lengthSync(), greaterThan(100));
|
||||
expect(progressList, isNotEmpty);
|
||||
expect(progressList.last, equals(1.0));
|
||||
|
||||
// 使用 ArchiveExtractor 解压验证 ZIP 完整性与正确性
|
||||
final extractDir = Directory(p.join(tempTestDir.path, 'extracted'))..createSync();
|
||||
await ArchiveExtractor.extract(
|
||||
archiveFile: zipFile,
|
||||
targetDir: extractDir,
|
||||
);
|
||||
|
||||
// 校验解压出的各个文件及内容
|
||||
expect(File(p.join(extractDir.path, 'main.dart')).existsSync(), isTrue);
|
||||
expect(File(p.join(extractDir.path, 'main.dart')).readAsStringSync(), equals(fileA.readAsStringSync()));
|
||||
|
||||
expect(File(p.join(extractDir.path, 'src', 'utils', 'helper.dart')).existsSync(), isTrue);
|
||||
expect(File(p.join(extractDir.path, 'src', 'utils', 'helper.dart')).readAsStringSync(), equals(fileB.readAsStringSync()));
|
||||
|
||||
expect(Directory(p.join(extractDir.path, 'assets', 'empty_folder')).existsSync(), isTrue);
|
||||
|
||||
expect(File(p.join(extractDir.path, 'EMPTY.txt')).existsSync(), isTrue);
|
||||
expect(File(p.join(extractDir.path, 'EMPTY.txt')).readAsStringSync(), isEmpty);
|
||||
|
||||
expect(File(p.join(extractDir.path, '测试项目_说明.md')).existsSync(), isTrue);
|
||||
expect(File(p.join(extractDir.path, '测试项目_说明.md')).readAsStringSync(), equals(fileUtf8.readAsStringSync()));
|
||||
|
||||
expect(File(p.join(extractDir.path, 'large_file.txt')).existsSync(), isTrue);
|
||||
expect(File(p.join(extractDir.path, 'large_file.txt')).readAsStringSync(), equals(fileLarge.readAsStringSync()));
|
||||
});
|
||||
|
||||
test('cancellation aborts compression and cleans up target zip file', () async {
|
||||
final srcDir = Directory(p.join(tempTestDir.path, 'cancel_src'))..createSync();
|
||||
for (var i = 0; i < 50; i++) {
|
||||
File(p.join(srcDir.path, 'file_$i.txt')).writeAsStringSync('Content $i ' * 500);
|
||||
}
|
||||
|
||||
final zipFile = File(p.join(tempTestDir.path, 'cancel_target.zip'));
|
||||
|
||||
expect(
|
||||
() async {
|
||||
await ArchiveCompressor.zipDirectory(
|
||||
sourceDir: srcDir,
|
||||
targetZipFile: zipFile,
|
||||
isCancelled: () => true,
|
||||
);
|
||||
},
|
||||
throwsA(isA<ArchiveCompressCancelledException>()),
|
||||
);
|
||||
|
||||
// 验证未完成的临时或目标 zip 文件被及时清理
|
||||
expect(zipFile.existsSync(), isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group('InternalProjectService Export & Import End-to-End Tests', () {
|
||||
test('exports project to zip and re-imports back with perfect fidelity', () async {
|
||||
final service = InternalProjectService.instance;
|
||||
final customProjectsDir = Directory(p.join(tempTestDir.path, 'projects'))..createSync(recursive: true);
|
||||
service.customProjectsDir = customProjectsDir;
|
||||
|
||||
// 1. 创建待导出的项目
|
||||
final projectDir = await service.createProject('MyExportApp');
|
||||
File(p.join(projectDir.path, 'pubspec.yaml')).writeAsStringSync('name: my_export_app\nversion: 1.0.0\n');
|
||||
final libDir = Directory(p.join(projectDir.path, 'lib'))..createSync();
|
||||
File(p.join(libDir.path, 'main.dart')).writeAsStringSync('void main() {}');
|
||||
File(p.join(libDir.path, 'calc.dart')).writeAsStringSync('int add(int a, int b) => a + b;');
|
||||
|
||||
// 2. 导出到外部目标目录
|
||||
final exportDir = Directory(p.join(tempTestDir.path, 'user_exports'))..createSync(recursive: true);
|
||||
final targetZipPath = p.join(exportDir.path, 'MyExportApp.zip');
|
||||
|
||||
final exportedFile = await service.exportProjectToZip(projectDir, targetZipPath);
|
||||
expect(exportedFile.existsSync(), isTrue);
|
||||
expect(exportedFile.path, equals(targetZipPath));
|
||||
|
||||
// 3. 从导出的 ZIP 重新导入为新项目
|
||||
final importedProjectDir = await service.importProjectFromArchive(
|
||||
targetZipPath,
|
||||
'MyExportApp_Restored',
|
||||
);
|
||||
|
||||
expect(importedProjectDir.existsSync(), isTrue);
|
||||
expect(p.basename(importedProjectDir.path), equals('MyExportApp_Restored'));
|
||||
|
||||
// 4. 校验所有导入的文件及内容无损还原
|
||||
final pubspec = File(p.join(importedProjectDir.path, 'pubspec.yaml'));
|
||||
expect(pubspec.existsSync(), isTrue);
|
||||
expect(pubspec.readAsStringSync(), contains('name: my_export_app'));
|
||||
|
||||
final restoredMain = File(p.join(importedProjectDir.path, 'lib', 'main.dart'));
|
||||
expect(restoredMain.existsSync(), isTrue);
|
||||
expect(restoredMain.readAsStringSync(), equals('void main() {}'));
|
||||
|
||||
final restoredCalc = File(p.join(importedProjectDir.path, 'lib', 'calc.dart'));
|
||||
expect(restoredCalc.existsSync(), isTrue);
|
||||
expect(restoredCalc.readAsStringSync(), equals('int add(int a, int b) => a + b;'));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:archive/archive_io.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:code_editor/services/archive_extractor.dart';
|
||||
import 'package:code_editor/services/internal_project_service.dart';
|
||||
|
||||
import 'distro_image_resolver_test.dart'; // 借用 encodeValidXz
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late Directory tempBaseDir;
|
||||
|
||||
setUp(() {
|
||||
tempBaseDir = Directory.systemTemp.createTempSync('archive_extractor_test_');
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
try {
|
||||
if (tempBaseDir.existsSync()) {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
}
|
||||
} catch (_) {}
|
||||
});
|
||||
|
||||
group('ArchiveExtractor Format Detection Tests', () {
|
||||
test('detectFormat correctly identifies format from magic bytes or extension', () {
|
||||
final zipFile = File(p.join(tempBaseDir.path, 'test.zip'));
|
||||
zipFile.writeAsBytesSync(ZipEncoder().encode(Archive()..addFile(ArchiveFile('a.txt', 1, [65])))!);
|
||||
expect(ArchiveExtractor.detectFormat(zipFile), ArchiveFormat.zip);
|
||||
|
||||
final tarGzFile = File(p.join(tempBaseDir.path, 'test.tar.gz'));
|
||||
final tarBytes = TarEncoder().encode(Archive()..addFile(ArchiveFile('b.txt', 1, [66])));
|
||||
tarGzFile.writeAsBytesSync(GZipEncoder().encode(tarBytes)!);
|
||||
expect(ArchiveExtractor.detectFormat(tarGzFile), ArchiveFormat.tarGz);
|
||||
|
||||
final xzBytes = encodeValidXz(tarBytes);
|
||||
final tarXzFile = File(p.join(tempBaseDir.path, 'test.tar.xz'));
|
||||
tarXzFile.writeAsBytesSync(xzBytes);
|
||||
expect(ArchiveExtractor.detectFormat(tarXzFile), ArchiveFormat.tarXz);
|
||||
});
|
||||
});
|
||||
|
||||
group('ArchiveExtractor Extraction Tests', () {
|
||||
test('extracts ZIP archive with subdirectories and verifies content', () async {
|
||||
final zipFile = File(p.join(tempBaseDir.path, 'project.zip'));
|
||||
final encoder = ZipFileEncoder();
|
||||
encoder.create(zipFile.path);
|
||||
|
||||
final file1 = File(p.join(tempBaseDir.path, 'pubspec.yaml'));
|
||||
file1.writeAsStringSync('name: test_project\nversion: 1.0.0\n');
|
||||
encoder.addFile(file1);
|
||||
|
||||
final file2 = File(p.join(tempBaseDir.path, 'main.dart'));
|
||||
file2.writeAsStringSync('void main() { print("hello world"); }');
|
||||
encoder.addFile(file2);
|
||||
|
||||
encoder.close();
|
||||
|
||||
final targetDir = Directory(p.join(tempBaseDir.path, 'extracted_zip'));
|
||||
final progressList = <double>[];
|
||||
|
||||
await ArchiveExtractor.extract(
|
||||
archiveFile: zipFile,
|
||||
targetDir: targetDir,
|
||||
onProgress: (prog, msg) {
|
||||
progressList.add(prog);
|
||||
},
|
||||
);
|
||||
|
||||
expect(targetDir.existsSync(), isTrue);
|
||||
expect(File(p.join(targetDir.path, 'pubspec.yaml')).existsSync(), isTrue);
|
||||
expect(File(p.join(targetDir.path, 'pubspec.yaml')).readAsStringSync(), contains('name: test_project'));
|
||||
expect(File(p.join(targetDir.path, 'main.dart')).existsSync(), isTrue);
|
||||
expect(File(p.join(targetDir.path, 'main.dart')).readAsStringSync(), contains('hello world'));
|
||||
expect(progressList.isNotEmpty, isTrue);
|
||||
expect(progressList.last, 1.0);
|
||||
});
|
||||
|
||||
test('extracts TAR.GZ archive with low-memory streaming', () async {
|
||||
final archive = Archive();
|
||||
archive.addFile(ArchiveFile('src/index.js', 25, utf8.encode('console.log("hello node");')));
|
||||
archive.addFile(ArchiveFile('package.json', 16, utf8.encode('{"name":"demo"}')));
|
||||
final tarBytes = TarEncoder().encode(archive);
|
||||
final gzBytes = GZipEncoder().encode(tarBytes)!;
|
||||
|
||||
final gzFile = File(p.join(tempBaseDir.path, 'project.tar.gz'));
|
||||
gzFile.writeAsBytesSync(gzBytes);
|
||||
|
||||
final targetDir = Directory(p.join(tempBaseDir.path, 'extracted_targz'));
|
||||
await ArchiveExtractor.extract(
|
||||
archiveFile: gzFile,
|
||||
targetDir: targetDir,
|
||||
);
|
||||
|
||||
expect(targetDir.existsSync(), isTrue);
|
||||
expect(File(p.join(targetDir.path, 'src', 'index.js')).existsSync(), isTrue);
|
||||
expect(File(p.join(targetDir.path, 'src', 'index.js')).readAsStringSync(), contains('hello node'));
|
||||
expect(File(p.join(targetDir.path, 'package.json')).existsSync(), isTrue);
|
||||
});
|
||||
|
||||
test('extracts TAR.XZ archive using LowMemoryXZDecoder', () async {
|
||||
final archive = Archive();
|
||||
archive.addFile(ArchiveFile('CMakeLists.txt', 25, utf8.encode('cmake_minimum_required()')));
|
||||
archive.addFile(ArchiveFile('main.cpp', 20, utf8.encode('int main(){return 0;}')));
|
||||
final tarBytes = TarEncoder().encode(archive);
|
||||
final xzBytes = encodeValidXz(tarBytes);
|
||||
|
||||
final xzFile = File(p.join(tempBaseDir.path, 'project.tar.xz'));
|
||||
xzFile.writeAsBytesSync(xzBytes);
|
||||
|
||||
final targetDir = Directory(p.join(tempBaseDir.path, 'extracted_tarxz'));
|
||||
await ArchiveExtractor.extract(
|
||||
archiveFile: xzFile,
|
||||
targetDir: targetDir,
|
||||
);
|
||||
|
||||
expect(targetDir.existsSync(), isTrue);
|
||||
expect(File(p.join(targetDir.path, 'CMakeLists.txt')).existsSync(), isTrue);
|
||||
expect(File(p.join(targetDir.path, 'CMakeLists.txt')).readAsStringSync(), 'cmake_minimum_required()');
|
||||
expect(File(p.join(targetDir.path, 'main.cpp')).existsSync(), isTrue);
|
||||
});
|
||||
|
||||
test('cancellation aborts extraction and cleans up target directory', () async {
|
||||
final archive = Archive();
|
||||
archive.addFile(ArchiveFile('file1.txt', 10, utf8.encode('1234567890')));
|
||||
final tarBytes = TarEncoder().encode(archive);
|
||||
final gzBytes = GZipEncoder().encode(tarBytes)!;
|
||||
|
||||
final gzFile = File(p.join(tempBaseDir.path, 'cancel_test.tar.gz'));
|
||||
gzFile.writeAsBytesSync(gzBytes);
|
||||
|
||||
final targetDir = Directory(p.join(tempBaseDir.path, 'cancelled_target'));
|
||||
|
||||
expect(
|
||||
() => ArchiveExtractor.extract(
|
||||
archiveFile: gzFile,
|
||||
targetDir: targetDir,
|
||||
isCancelled: () => true,
|
||||
),
|
||||
throwsA(isA<ArchiveExtractCancelledException>()),
|
||||
);
|
||||
|
||||
expect(targetDir.existsSync(), isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group('InternalProjectService with ArchiveExtractor Tests', () {
|
||||
test('importProjectFromArchive uses ArchiveExtractor and imports project successfully', () async {
|
||||
final service = InternalProjectService.instance;
|
||||
service.customProjectsDir = Directory(p.join(tempBaseDir.path, 'files', 'projects'));
|
||||
|
||||
final zipFile = File(p.join(tempBaseDir.path, 'sample_repo.zip'));
|
||||
final encoder = ZipFileEncoder();
|
||||
encoder.create(zipFile.path);
|
||||
final dummyFile = File(p.join(tempBaseDir.path, 'app.py'));
|
||||
dummyFile.writeAsStringSync('print("python app")');
|
||||
encoder.addFile(dummyFile);
|
||||
encoder.close();
|
||||
|
||||
final importedDir = await service.importProjectFromArchive(zipFile.path, 'sample_repo');
|
||||
expect(importedDir.existsSync(), isTrue);
|
||||
expect(File(p.join(importedDir.path, 'app.py')).existsSync(), isTrue);
|
||||
expect(File(p.join(importedDir.path, 'app.py')).readAsStringSync(), 'print("python app")');
|
||||
|
||||
service.customProjectsDir = null;
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/widgets/code_editor_menu.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('CodeEditorToolbarController 选区菜单定位与恢复测试', () {
|
||||
test('拖动 End Handle 时,锚点严格位于末尾手柄位置,绝不跳跃至顶端', () {
|
||||
// 模拟 re_editor 传递的 End Handle 拖拽锚点:primary 为 -10000,secondary 为末尾坐标 (180, 450)
|
||||
const inputAnchors = TextSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(-10000, -10000),
|
||||
secondaryAnchor: Offset(180, 450),
|
||||
);
|
||||
|
||||
// 验证 End Handle 拖拽锚点规则
|
||||
final target = inputAnchors.primaryAnchor.dx < 0 && inputAnchors.secondaryAnchor != null
|
||||
? inputAnchors.secondaryAnchor!
|
||||
: inputAnchors.primaryAnchor;
|
||||
|
||||
expect(target.dy, equals(450));
|
||||
expect(target.dx, equals(180));
|
||||
});
|
||||
|
||||
test('拖动 Start Handle 时,锚点严格位于起始手柄位置', () {
|
||||
const inputAnchors = TextSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(150, 120),
|
||||
secondaryAnchor: Offset(180, 450),
|
||||
);
|
||||
|
||||
final target = inputAnchors.primaryAnchor.dx < 0 && inputAnchors.secondaryAnchor != null
|
||||
? inputAnchors.secondaryAnchor!
|
||||
: inputAnchors.primaryAnchor;
|
||||
|
||||
expect(target.dy, equals(120));
|
||||
expect(target.dx, equals(150));
|
||||
});
|
||||
|
||||
testWidgets('reshowLastToolbar 在选区折叠时安全跳过,在有选区时可重新唤起', (tester) async {
|
||||
final controller = CodeEditorToolbarController();
|
||||
final codeController = CodeLineEditingController.fromText('Hello World\nSecond Line\nThird Line');
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (context) {
|
||||
return ElevatedButton(
|
||||
onPressed: () {
|
||||
controller.reshowLastToolbar(context);
|
||||
},
|
||||
child: const Text('Reshow'),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 无选区(折叠)时点击 Reshow 不抛异常且无崩溃
|
||||
await tester.tap(find.text('Reshow'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 设置选区
|
||||
codeController.selection = const CodeLineSelection(
|
||||
baseIndex: 0,
|
||||
baseOffset: 0,
|
||||
extentIndex: 0,
|
||||
extentOffset: 5,
|
||||
);
|
||||
|
||||
// 模拟 show 记录上下文
|
||||
final layerLink = LayerLink();
|
||||
final visibility = ValueNotifier<bool>(true);
|
||||
final element = tester.element(find.text('Reshow'));
|
||||
|
||||
controller.show(
|
||||
context: element,
|
||||
controller: codeController,
|
||||
anchors: const TextSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(100, 200),
|
||||
),
|
||||
renderRect: const Rect.fromLTWH(0, 0, 400, 600),
|
||||
layerLink: layerLink,
|
||||
visibility: visibility,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 隐藏后再 reshow
|
||||
controller.hide(element);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
controller.reshowLastToolbar(element);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 验证无异常并正常处理
|
||||
expect(codeController.selection.isCollapsed, isFalse);
|
||||
});
|
||||
|
||||
testWidgets('验证中英文本地化字符串正确无硬编码', (tester) async {
|
||||
late AppLocalizations zhL10n;
|
||||
late AppLocalizations enL10n;
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
locale: const Locale('zh'),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Builder(
|
||||
builder: (context) {
|
||||
zhL10n = AppLocalizations.of(context)!;
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(zhL10n.copy, equals('复制'));
|
||||
expect(zhL10n.cut, equals('剪切'));
|
||||
expect(zhL10n.paste, equals('粘贴'));
|
||||
expect(zhL10n.selectAll, equals('全选'));
|
||||
expect(zhL10n.copiedToClipboard, equals('已复制到剪贴板'));
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
locale: const Locale('en'),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Builder(
|
||||
builder: (context) {
|
||||
enL10n = AppLocalizations.of(context)!;
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(enL10n.copy, equals('Copy'));
|
||||
expect(enL10n.cut, equals('Cut'));
|
||||
expect(enL10n.paste, equals('Paste'));
|
||||
expect(enL10n.selectAll, equals('Select All'));
|
||||
expect(enL10n.copiedToClipboard, equals('Copied to clipboard'));
|
||||
});
|
||||
|
||||
testWidgets('CodeEditor 选区手柄在有选区时正常展现并支持鼠标交互', (tester) async {
|
||||
final codeController = CodeLineEditingController.fromText('Hello Flutter Code Editor\nSecond line text');
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 500,
|
||||
height: 400,
|
||||
child: CodeEditor(
|
||||
controller: codeController,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
codeController.selection = const CodeLineSelection(
|
||||
baseIndex: 0,
|
||||
baseOffset: 0,
|
||||
extentIndex: 0,
|
||||
extentOffset: 5,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(codeController.selection.isCollapsed, isFalse);
|
||||
});
|
||||
|
||||
testWidgets('智能定位算法测试: aboveStart/belowEnd/center/top/bottom 与空间避让翻转', (tester) async {
|
||||
final controller = CodeEditorToolbarController();
|
||||
final codeController = CodeLineEditingController.fromText('Test line 1\nTest line 2\nTest line 3');
|
||||
codeController.selection = const CodeLineSelection(
|
||||
baseIndex: 0,
|
||||
baseOffset: 0,
|
||||
extentIndex: 0,
|
||||
extentOffset: 4,
|
||||
);
|
||||
|
||||
late BuildContext buildCtx;
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (context) {
|
||||
buildCtx = context;
|
||||
return const SizedBox(width: 400, height: 600);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final layerLink = LayerLink();
|
||||
final visibility = ValueNotifier<bool>(true);
|
||||
|
||||
// 1. aboveStart: 空间充裕时显示在目标上方
|
||||
controller.show(
|
||||
context: buildCtx,
|
||||
controller: codeController,
|
||||
anchors: const EditorSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(200, 300),
|
||||
placement: EditorToolbarPlacement.aboveStart,
|
||||
targetOffset: Offset(200, 300),
|
||||
visibleEditorRect: Rect.fromLTWH(0, 50, 400, 500),
|
||||
),
|
||||
renderRect: const Rect.fromLTWH(0, 50, 400, 500),
|
||||
layerLink: layerLink,
|
||||
visibility: visibility,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final abovePos = tester.getTopLeft(find.byType(Material).last);
|
||||
expect(abovePos.dy, lessThan(300));
|
||||
|
||||
// 2. aboveStart: 空间狭小(靠近顶部)时翻转到下方
|
||||
controller.show(
|
||||
context: buildCtx,
|
||||
controller: codeController,
|
||||
anchors: const EditorSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(200, 60),
|
||||
placement: EditorToolbarPlacement.aboveStart,
|
||||
targetOffset: Offset(200, 60),
|
||||
visibleEditorRect: Rect.fromLTWH(0, 50, 400, 500),
|
||||
),
|
||||
renderRect: const Rect.fromLTWH(0, 50, 400, 500),
|
||||
layerLink: layerLink,
|
||||
visibility: visibility,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final flippedBelowPos = tester.getTopLeft(find.byType(Material).last);
|
||||
expect(flippedBelowPos.dy, greaterThan(60));
|
||||
|
||||
// 3. belowEnd: 空间充裕时显示在目标下方
|
||||
controller.show(
|
||||
context: buildCtx,
|
||||
controller: codeController,
|
||||
anchors: const EditorSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(200, 200),
|
||||
placement: EditorToolbarPlacement.belowEnd,
|
||||
targetOffset: Offset(200, 200),
|
||||
visibleEditorRect: Rect.fromLTWH(0, 50, 400, 500),
|
||||
),
|
||||
renderRect: const Rect.fromLTWH(0, 50, 400, 500),
|
||||
layerLink: layerLink,
|
||||
visibility: visibility,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final belowPos = tester.getTopLeft(find.byType(Material).last);
|
||||
expect(belowPos.dy, greaterThan(200));
|
||||
|
||||
// 4. belowEnd: 空间狭小(靠近底部)时翻转到上方
|
||||
controller.show(
|
||||
context: buildCtx,
|
||||
controller: codeController,
|
||||
anchors: const EditorSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(200, 530),
|
||||
placement: EditorToolbarPlacement.belowEnd,
|
||||
targetOffset: Offset(200, 530),
|
||||
visibleEditorRect: Rect.fromLTWH(0, 50, 400, 500),
|
||||
),
|
||||
renderRect: const Rect.fromLTWH(0, 50, 400, 500),
|
||||
layerLink: layerLink,
|
||||
visibility: visibility,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final flippedAbovePos = tester.getTopLeft(find.byType(Material).last);
|
||||
expect(flippedAbovePos.dy, lessThan(530));
|
||||
|
||||
// 5. center: 居中显示
|
||||
controller.show(
|
||||
context: buildCtx,
|
||||
controller: codeController,
|
||||
anchors: const EditorSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(200, 300),
|
||||
placement: EditorToolbarPlacement.center,
|
||||
targetOffset: Offset(200, 300),
|
||||
visibleEditorRect: Rect.fromLTWH(0, 100, 400, 400),
|
||||
),
|
||||
renderRect: const Rect.fromLTWH(0, 100, 400, 400),
|
||||
layerLink: layerLink,
|
||||
visibility: visibility,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final centerPos = tester.getCenter(find.byType(Material).last);
|
||||
expect((centerPos.dy - 300).abs(), lessThan(30));
|
||||
|
||||
// 6. top: 顶部贴边
|
||||
controller.show(
|
||||
context: buildCtx,
|
||||
controller: codeController,
|
||||
anchors: const EditorSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(200, 100),
|
||||
placement: EditorToolbarPlacement.top,
|
||||
targetOffset: Offset(200, 100),
|
||||
visibleEditorRect: Rect.fromLTWH(0, 100, 400, 400),
|
||||
),
|
||||
renderRect: const Rect.fromLTWH(0, 100, 400, 400),
|
||||
layerLink: layerLink,
|
||||
visibility: visibility,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final topPos = tester.getTopLeft(find.byType(Material).last);
|
||||
expect(topPos.dy, closeTo(110, 10));
|
||||
|
||||
// 7. bottom: 底部贴边
|
||||
controller.show(
|
||||
context: buildCtx,
|
||||
controller: codeController,
|
||||
anchors: const EditorSelectionToolbarAnchors(
|
||||
primaryAnchor: Offset(200, 500),
|
||||
placement: EditorToolbarPlacement.bottom,
|
||||
targetOffset: Offset(200, 500),
|
||||
visibleEditorRect: Rect.fromLTWH(0, 100, 400, 400),
|
||||
),
|
||||
renderRect: const Rect.fromLTWH(0, 100, 400, 400),
|
||||
layerLink: layerLink,
|
||||
visibility: visibility,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final bottomPos = tester.getBottomLeft(find.byType(Material).last);
|
||||
expect(bottomPos.dy, closeTo(490, 20));
|
||||
|
||||
controller.hide(buildCtx);
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
|
||||
testWidgets('存在框选区域时,点击框选区域不取消框选,点击外部则取消框选', (tester) async {
|
||||
final codeController = CodeLineEditingController.fromText('Hello Flutter Code Editor\nSecond line text');
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 500,
|
||||
height: 400,
|
||||
child: CodeEditor(
|
||||
controller: codeController,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 设置选区为 "Hello" (offset 0 到 5)
|
||||
codeController.selection = const CodeLineSelection(
|
||||
baseIndex: 0,
|
||||
baseOffset: 0,
|
||||
extentIndex: 0,
|
||||
extentOffset: 5,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(codeController.selection.isCollapsed, isFalse);
|
||||
|
||||
// 点击首行 "Hello" 内部
|
||||
final editorFinder = find.byType(CodeEditor);
|
||||
final editorTopLeft = tester.getTopLeft(editorFinder);
|
||||
await tester.tapAt(editorTopLeft + const Offset(20, 10));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 选区不被取消!
|
||||
expect(codeController.selection.isCollapsed, isFalse);
|
||||
|
||||
// 点击第 2 行(选区外部)
|
||||
await tester.tapAt(editorTopLeft + const Offset(20, 60));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 选区在点击外部后被取消
|
||||
expect(codeController.selection.isCollapsed, isTrue);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -62,9 +62,12 @@ void main() {
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
if (tempBaseDir.existsSync()) {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
}
|
||||
manager.customSdcardPath = null;
|
||||
try {
|
||||
if (tempBaseDir.existsSync()) {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
}
|
||||
} catch (_) {}
|
||||
});
|
||||
|
||||
Uint8List createMockRootfsTarGz() {
|
||||
@@ -246,6 +249,28 @@ void main() {
|
||||
expect(hushFile.existsSync(), isTrue);
|
||||
});
|
||||
|
||||
test('buildLaunchConfig 自动挂载 sdcard 目录到 /sdcard 与 /root/sdcard', () async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'sdcard_cfg.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
|
||||
await manager.importFromCustomTarGz(systemName: 'sdcard_env', tarGzFile: tempGzFile);
|
||||
|
||||
final fakeSdcard = Directory(p.join(tempBaseDir.path, 'fake_sdcard'))..createSync();
|
||||
manager.customSdcardPath = fakeSdcard.path;
|
||||
|
||||
final launchConfig = await manager.buildLaunchConfig(
|
||||
systemName: 'sdcard_env',
|
||||
workspacePath: tempBaseDir.path,
|
||||
);
|
||||
|
||||
expect(launchConfig.arguments, contains('${fakeSdcard.path}:/sdcard'));
|
||||
expect(launchConfig.arguments, contains('${fakeSdcard.path}:/root/sdcard'));
|
||||
|
||||
final rootDir = await manager.getSystemRootDir('sdcard_env');
|
||||
expect(Directory(p.join(rootDir.path, 'sdcard')).existsSync(), isTrue);
|
||||
expect(Directory(p.join(rootDir.path, 'root', 'sdcard')).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);
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:code_editor/models/run_task.dart';
|
||||
import 'package:code_editor/providers/run_provider.dart';
|
||||
import 'package:code_editor/services/project_modules/gradle_project_module.dart';
|
||||
import 'package:code_editor/services/project_task_dispatcher.dart';
|
||||
import 'package:code_editor/services/run_task_storage_service.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('GradleProjectModule Parser Tests', () {
|
||||
test('parseGradleTasksOutput parses single project tasks, groups, and descriptions', () {
|
||||
const output = '''
|
||||
------------------------------------------------------------
|
||||
Tasks runnable from root project 'my-app'
|
||||
------------------------------------------------------------
|
||||
|
||||
Application tasks
|
||||
-----------------
|
||||
run - Runs this project as a JVM application
|
||||
|
||||
Build tasks
|
||||
-----------
|
||||
assemble - Assembles the outputs of this project.
|
||||
build - Assembles and tests this project.
|
||||
clean - Deletes the build directory.
|
||||
|
||||
Verification tasks
|
||||
------------------
|
||||
check - Runs all checks.
|
||||
test - Runs the test suite.
|
||||
|
||||
Other tasks
|
||||
-----------
|
||||
customTask - Executes a custom task
|
||||
''';
|
||||
|
||||
final tasks = GradleProjectModule.parseGradleTasksOutput(output, 'sh ./gradlew');
|
||||
expect(tasks, isNotEmpty);
|
||||
|
||||
// 验证任务名称与命令
|
||||
final runTask = tasks.firstWhere((t) => t.name == 'run');
|
||||
expect(runTask.command, 'sh ./gradlew run');
|
||||
expect(runTask.group, 'application');
|
||||
expect(runTask.moduleId, 'gradle');
|
||||
expect(runTask.source, TaskSource.detected);
|
||||
expect(runTask.description, 'Runs this project as a JVM application');
|
||||
|
||||
final assembleTask = tasks.firstWhere((t) => t.name == 'assemble');
|
||||
expect(assembleTask.command, 'sh ./gradlew assemble');
|
||||
expect(assembleTask.group, 'build');
|
||||
expect(assembleTask.moduleId, 'gradle');
|
||||
|
||||
final buildTask = tasks.firstWhere((t) => t.name == 'build');
|
||||
expect(buildTask.command, 'sh ./gradlew build');
|
||||
expect(buildTask.group, 'build');
|
||||
|
||||
final testTask = tasks.firstWhere((t) => t.name == 'test');
|
||||
expect(testTask.command, 'sh ./gradlew test');
|
||||
expect(testTask.group, 'verification');
|
||||
|
||||
final customTask = tasks.firstWhere((t) => t.name == 'customTask');
|
||||
expect(customTask.command, 'sh ./gradlew customTask');
|
||||
expect(customTask.group, 'other');
|
||||
expect(customTask.description, 'Executes a custom task');
|
||||
|
||||
// 优先级排序验证:application -> build -> verification -> other
|
||||
final groupsInOrder = tasks.map((t) => t.group).toList();
|
||||
final appIdx = groupsInOrder.indexOf('application');
|
||||
final buildIdx = groupsInOrder.indexOf('build');
|
||||
final verifIdx = groupsInOrder.indexOf('verification');
|
||||
final otherIdx = groupsInOrder.indexOf('other');
|
||||
|
||||
expect(appIdx, lessThan(buildIdx));
|
||||
expect(buildIdx, lessThan(verifIdx));
|
||||
expect(verifIdx, lessThan(otherIdx));
|
||||
});
|
||||
|
||||
test('parseGradleTasksOutput parses multi-module projects with prefixes (:app:xxx)', () {
|
||||
const output = '''
|
||||
------------------------------------------------------------
|
||||
Tasks runnable from project ':app'
|
||||
------------------------------------------------------------
|
||||
|
||||
Build tasks
|
||||
-----------
|
||||
assembleDebug - Assembles all Debug builds.
|
||||
assembleRelease - Assembles all Release builds.
|
||||
|
||||
Tasks runnable from project ':core'
|
||||
------------------------------------------------------------
|
||||
|
||||
Build tasks
|
||||
-----------
|
||||
compileJava - Compiles Java sources.
|
||||
''';
|
||||
|
||||
final tasks = GradleProjectModule.parseGradleTasksOutput(output, 'sh ./gradlew');
|
||||
expect(tasks.length, 3);
|
||||
|
||||
final assembleDebugTask = tasks.firstWhere((t) => t.name == ':app:assembleDebug');
|
||||
expect(assembleDebugTask.command, 'sh ./gradlew :app:assembleDebug');
|
||||
expect(assembleDebugTask.id, 'gradle__app_assembleDebug');
|
||||
expect(assembleDebugTask.group, 'build');
|
||||
expect(assembleDebugTask.moduleId, 'gradle');
|
||||
|
||||
final compileJavaTask = tasks.firstWhere((t) => t.name == ':core:compileJava');
|
||||
expect(compileJavaTask.command, 'sh ./gradlew :core:compileJava');
|
||||
expect(compileJavaTask.id, 'gradle__core_compileJava');
|
||||
});
|
||||
});
|
||||
|
||||
group('Gradle Module Cache & Storage Tests', () {
|
||||
late Directory tempDir;
|
||||
late RunTaskStorageService storageService;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('gradle_module_test_');
|
||||
storageService = RunTaskStorageService();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
if (await tempDir.exists()) {
|
||||
await tempDir.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
test('saveModuleTasks writes to .code_editor/gradle_tasks.json and loadModuleTasks reads it back', () async {
|
||||
final initial = await storageService.loadModuleTasks(tempDir.path, 'gradle');
|
||||
expect(initial.tasks, isEmpty);
|
||||
expect(initial.hash, isNull);
|
||||
|
||||
const tasksToSave = [
|
||||
RunTask(
|
||||
id: 'gradle_assembleDebug',
|
||||
name: 'assembleDebug',
|
||||
command: 'sh ./gradlew assembleDebug',
|
||||
source: TaskSource.detected,
|
||||
group: 'build',
|
||||
moduleId: 'gradle',
|
||||
description: 'Build debug package',
|
||||
),
|
||||
RunTask(
|
||||
id: 'gradle_run',
|
||||
name: 'run',
|
||||
command: 'sh ./gradlew run',
|
||||
source: TaskSource.detected,
|
||||
group: 'application',
|
||||
moduleId: 'gradle',
|
||||
description: 'Run project',
|
||||
),
|
||||
];
|
||||
|
||||
await storageService.saveModuleTasks(
|
||||
projectRoot: tempDir.path,
|
||||
moduleName: 'gradle',
|
||||
tasks: tasksToSave,
|
||||
hash: 'test_hash_12345',
|
||||
);
|
||||
|
||||
// 验证独立持久化文件存在:.code_editor/gradle_tasks.json
|
||||
final cacheFile = File('${tempDir.path}/.code_editor/gradle_tasks.json');
|
||||
expect(cacheFile.existsSync(), isTrue);
|
||||
|
||||
// 读取并校验
|
||||
final loaded = await storageService.loadModuleTasks(tempDir.path, 'gradle');
|
||||
expect(loaded.hash, 'test_hash_12345');
|
||||
expect(loaded.tasks.length, 2);
|
||||
expect(loaded.tasks.first.name, 'assembleDebug');
|
||||
expect(loaded.tasks.first.group, 'build');
|
||||
expect(loaded.tasks.first.moduleId, 'gradle');
|
||||
expect(loaded.tasks.last.name, 'run');
|
||||
|
||||
// 验证 run_tasks.json(用户任务)完全不受影响且相互隔离
|
||||
final userConfig = await storageService.loadConfig(tempDir.path);
|
||||
expect(userConfig.tasks, isEmpty);
|
||||
});
|
||||
|
||||
test('computeBuildScriptHash changes when build.gradle is modified', () async {
|
||||
final buildGradle = File('${tempDir.path}/build.gradle');
|
||||
await buildGradle.writeAsString('plugins { id "java" }\n');
|
||||
|
||||
final hash1 = GradleProjectModule.computeBuildScriptHash(tempDir);
|
||||
expect(hash1.isNotEmpty, isTrue);
|
||||
|
||||
// 稍微休眠并修改内容
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
await buildGradle.writeAsString('plugins { id "application" }\n');
|
||||
|
||||
final hash2 = GradleProjectModule.computeBuildScriptHash(tempDir);
|
||||
expect(hash2, isNot(equals(hash1)));
|
||||
});
|
||||
});
|
||||
|
||||
group('ProjectTaskDispatcher & RunProvider Modular Tests', () {
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('dispatcher_test_');
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
if (await tempDir.exists()) {
|
||||
await tempDir.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
test('ProjectTaskDispatcher activates modules correctly', () async {
|
||||
final dispatcher = ProjectTaskDispatcher();
|
||||
|
||||
// 空目录,不激活任何模块
|
||||
expect(dispatcher.getActiveModules(tempDir), isEmpty);
|
||||
|
||||
// 写入 build.gradle
|
||||
await File('${tempDir.path}/build.gradle').writeAsString('// gradle build');
|
||||
final active = dispatcher.getActiveModules(tempDir);
|
||||
expect(active.length, 1);
|
||||
expect(active.first.id, 'gradle');
|
||||
|
||||
// 再写入 CMakeLists.txt
|
||||
await File('${tempDir.path}/CMakeLists.txt').writeAsString('project(test)');
|
||||
final active2 = dispatcher.getActiveModules(tempDir);
|
||||
expect(active2.length, 2);
|
||||
expect(active2.any((m) => m.id == 'cmake'), isTrue);
|
||||
expect(active2.any((m) => m.id == 'gradle'), isTrue);
|
||||
});
|
||||
|
||||
test('GradleProjectModule returns cached tasks when hash matches without executing command', () async {
|
||||
final buildGradle = File('${tempDir.path}/build.gradle');
|
||||
await buildGradle.writeAsString('plugins { id "java" }\n');
|
||||
|
||||
final storageService = RunTaskStorageService();
|
||||
final currentHash = GradleProjectModule.computeBuildScriptHash(tempDir);
|
||||
|
||||
const cachedTasks = [
|
||||
RunTask(
|
||||
id: 'gradle_cached_task',
|
||||
name: 'cachedTask',
|
||||
command: 'sh ./gradlew cachedTask',
|
||||
source: TaskSource.detected,
|
||||
group: 'build',
|
||||
moduleId: 'gradle',
|
||||
),
|
||||
];
|
||||
|
||||
await storageService.saveModuleTasks(
|
||||
projectRoot: tempDir.path,
|
||||
moduleName: 'gradle',
|
||||
tasks: cachedTasks,
|
||||
hash: currentHash,
|
||||
);
|
||||
|
||||
final dispatcher = ProjectTaskDispatcher();
|
||||
final tasks = await dispatcher.detect(
|
||||
projectRoot: tempDir.path,
|
||||
storageService: storageService,
|
||||
);
|
||||
|
||||
expect(tasks.any((t) => t.id == 'gradle_cached_task'), isTrue);
|
||||
expect(tasks.firstWhere((t) => t.id == 'gradle_cached_task').name, 'cachedTask');
|
||||
});
|
||||
|
||||
test('RunProvider integrates with modular task system and maintains customTasks', () async {
|
||||
final storageService = RunTaskStorageService();
|
||||
final runProvider = RunProvider(storageService: storageService);
|
||||
|
||||
// 准备工程与一个已缓存的 Gradle 任务
|
||||
await File('${tempDir.path}/build.gradle').writeAsString('plugins { id "java" }\n');
|
||||
final currentHash = GradleProjectModule.computeBuildScriptHash(tempDir);
|
||||
const initialGradleTask = RunTask(
|
||||
id: 'gradle_assemble',
|
||||
name: 'assemble',
|
||||
command: 'sh ./gradlew assemble',
|
||||
source: TaskSource.detected,
|
||||
group: 'build',
|
||||
moduleId: 'gradle',
|
||||
);
|
||||
await storageService.saveModuleTasks(
|
||||
projectRoot: tempDir.path,
|
||||
moduleName: 'gradle',
|
||||
tasks: [initialGradleTask],
|
||||
hash: currentHash,
|
||||
);
|
||||
|
||||
// 打开工程
|
||||
await runProvider.onProjectOpened(tempDir.path);
|
||||
expect(runProvider.detectedTasks.any((t) => t.id == 'gradle_assemble'), isTrue);
|
||||
|
||||
// 添加用户自定义任务
|
||||
const customTask = RunTask(
|
||||
id: 'user_custom_1',
|
||||
name: 'My Custom Run',
|
||||
command: 'echo "custom"',
|
||||
source: TaskSource.custom,
|
||||
);
|
||||
await runProvider.addCustomTask(customTask);
|
||||
|
||||
expect(runProvider.customTasks.length, 1);
|
||||
// allTasks 自定义置顶
|
||||
expect(runProvider.allTasks.first.id, 'user_custom_1');
|
||||
expect(runProvider.allTasks.any((t) => t.id == 'gradle_assemble'), isTrue);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class MockFilePicker extends FilePicker {
|
||||
String? pickedPath;
|
||||
String? pickedDirectory;
|
||||
|
||||
@override
|
||||
Future<FilePickerResult?> pickFiles({
|
||||
@@ -50,7 +51,7 @@ class MockFilePicker extends FilePicker {
|
||||
String? dialogTitle,
|
||||
bool lockParentWindow = false,
|
||||
String? initialDirectory,
|
||||
}) async => null;
|
||||
}) async => pickedDirectory;
|
||||
|
||||
@override
|
||||
Future<String?> saveFile({
|
||||
@@ -529,5 +530,109 @@ void main() {
|
||||
final projects = await projectService.listProjects();
|
||||
expect(projects, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('Export button is placed next to edit button and exports project as zip', (tester) async {
|
||||
final projDir = await projectService.createProject('my_export_app');
|
||||
File(p.join(projDir.path, 'main.dart')).writeAsStringSync('void main() {}');
|
||||
|
||||
final exportDir = Directory(p.join(tempBaseDir.path, 'exports'))..createSync();
|
||||
mockFilePicker.pickedDirectory = exportDir.path;
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
locale: const Locale('zh'),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('my_export_app'), findsOneWidget);
|
||||
|
||||
// Verify buttons in order: Edit, Export, Delete
|
||||
expect(find.byIcon(Icons.edit_outlined), findsOneWidget);
|
||||
expect(find.byIcon(Icons.drive_folder_upload_outlined), findsOneWidget);
|
||||
expect(find.byTooltip('导出为 ZIP 压缩包'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.delete_outline), findsOneWidget);
|
||||
|
||||
final targetZip = File(p.join(exportDir.path, 'my_export_app.zip'));
|
||||
|
||||
// Tap export button inside runAsync so Isolate compression can complete
|
||||
await tester.runAsync(() async {
|
||||
await tester.tap(find.byIcon(Icons.drive_folder_upload_outlined));
|
||||
for (var i = 0; i < 50; i++) {
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
if (targetZip.existsSync()) break;
|
||||
}
|
||||
});
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 4));
|
||||
|
||||
// Verify exported file exists on disk
|
||||
expect(targetZip.existsSync(), isTrue);
|
||||
expect(targetZip.lengthSync(), greaterThan(0));
|
||||
});
|
||||
|
||||
testWidgets('Exporting when target zip exists prompts for overwrite confirmation', (tester) async {
|
||||
final projDir = await projectService.createProject('app_conflict');
|
||||
File(p.join(projDir.path, 'code.dart')).writeAsStringSync('int a = 1;');
|
||||
|
||||
final exportDir = Directory(p.join(tempBaseDir.path, 'exports_conflict'))..createSync();
|
||||
final existingZip = File(p.join(exportDir.path, 'app_conflict.zip'))..writeAsStringSync('old zip content');
|
||||
mockFilePicker.pickedDirectory = exportDir.path;
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
locale: const Locale('zh'),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Tap export button
|
||||
await tester.tap(find.byIcon(Icons.drive_folder_upload_outlined));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Overwrite confirmation dialog should appear
|
||||
expect(find.text('目标文件 "app_conflict.zip" 已存在,是否覆盖?'), findsOneWidget);
|
||||
expect(find.text('覆盖'), findsOneWidget);
|
||||
expect(find.text('取消'), findsOneWidget);
|
||||
|
||||
// Cancel first
|
||||
await tester.tap(find.text('取消'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(existingZip.readAsStringSync(), equals('old zip content'));
|
||||
|
||||
// Tap export again and confirm overwrite
|
||||
await tester.tap(find.byIcon(Icons.drive_folder_upload_outlined));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.runAsync(() async {
|
||||
await tester.tap(find.text('覆盖'));
|
||||
for (var i = 0; i < 50; i++) {
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
if (existingZip.existsSync() && existingZip.lengthSync() > 15) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 4));
|
||||
|
||||
expect(existingZip.existsSync(), isTrue);
|
||||
expect(existingZip.lengthSync(), greaterThan(15));
|
||||
final bytes = existingZip.readAsBytesSync();
|
||||
expect(bytes[0], equals(0x50));
|
||||
expect(bytes[1], equals(0x4B));
|
||||
});
|
||||
|
||||
testWidgets('Export button tooltips follow English locale', (tester) async {
|
||||
await projectService.createProject('en_project');
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const ProjectManagementView(),
|
||||
locale: const Locale('en'),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byTooltip('Export as ZIP archive'), findsOneWidget);
|
||||
expect(find.byTooltip('Rename Project'), findsOneWidget);
|
||||
expect(find.byTooltip('Delete Project'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import 'dart:io';
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/providers/distro_provider.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/providers/terminal_provider.dart';
|
||||
import 'package:code_editor/services/internal_project_service.dart';
|
||||
import 'package:code_editor/services/permission_service.dart';
|
||||
import 'package:code_editor/services/project_history_service.dart';
|
||||
import 'package:code_editor/views/terminal_view.dart';
|
||||
import 'package:code_editor/widgets/code_editor_app_bar.dart';
|
||||
import 'package:code_editor/widgets/project_history_widget.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 InternalProjectService projectService;
|
||||
late ProjectProvider projectProvider;
|
||||
late TabProvider tabProvider;
|
||||
late SettingsProvider settingsProvider;
|
||||
late TerminalProvider terminalProvider;
|
||||
late DistroProvider distroProvider;
|
||||
late RunProvider runProvider;
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
tempBaseDir = Directory.systemTemp.createTempSync('term_batt_test_');
|
||||
projectService = InternalProjectService.instance;
|
||||
projectService.customProjectsDir = Directory(p.join(tempBaseDir.path, 'files', 'projects'));
|
||||
|
||||
projectProvider = ProjectProvider();
|
||||
tabProvider = TabProvider()..bindProjectProvider(projectProvider);
|
||||
settingsProvider = SettingsProvider();
|
||||
terminalProvider = TerminalProvider();
|
||||
distroProvider = DistroProvider();
|
||||
runProvider = RunProvider();
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
projectService.customProjectsDir = null;
|
||||
if (tempBaseDir.existsSync()) {
|
||||
try {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
});
|
||||
|
||||
Widget buildTestApp({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<TerminalProvider>.value(value: terminalProvider),
|
||||
ChangeNotifierProvider<DistroProvider>.value(value: distroProvider),
|
||||
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('ProjectHistoryWidget 内部与外部项目展示测试', () {
|
||||
testWidgets('内部项目副标题显示项目名称,外部项目副标题显示绝对路径', (tester) async {
|
||||
// 创建一个内部项目路径
|
||||
final internalProjectsDir = projectService.customProjectsDir!;
|
||||
final internalDir = Directory(p.join(internalProjectsDir.path, 'my_internal_app'))..createSync(recursive: true);
|
||||
final internalFile = File(p.join(internalDir.path, 'lib', 'main.dart'))..createSync(recursive: true);
|
||||
|
||||
// 创建一个外部项目路径
|
||||
final externalDir = Directory(p.join(tempBaseDir.path, 'outside', 'external_proj'))..createSync(recursive: true);
|
||||
final externalFile = File(p.join(externalDir.path, 'app.py'))..createSync(recursive: true);
|
||||
|
||||
// 录入历史
|
||||
await ProjectHistoryService.instance.recordHistory(
|
||||
rootPath: internalDir.path,
|
||||
lastOpenedFilePath: internalFile.path,
|
||||
);
|
||||
await ProjectHistoryService.instance.recordHistory(
|
||||
rootPath: externalDir.path,
|
||||
lastOpenedFilePath: externalFile.path,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(buildTestApp(
|
||||
child: const Scaffold(
|
||||
body: ProjectHistoryWidget(),
|
||||
),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 验证内部项目:显示项目名 "my_internal_app",而不显示绝对路径
|
||||
expect(find.text('my_internal_app'), findsOneWidget);
|
||||
expect(find.text(internalDir.path), findsNothing);
|
||||
|
||||
// 验证外部项目:显示完整绝对路径
|
||||
expect(find.text(externalDir.path), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
group('TerminalView AppBar 副标题展示测试', () {
|
||||
testWidgets('内部项目工作区副标题显示项目名,外部项目工作区副标题显示完整路径', (tester) async {
|
||||
final internalProjectsDir = projectService.customProjectsDir!;
|
||||
final internalDir = Directory(p.join(internalProjectsDir.path, 'term_internal_proj'))..createSync(recursive: true);
|
||||
|
||||
// 会话 1:绑定内部项目工作区
|
||||
terminalProvider.createSession(
|
||||
name: '会话1',
|
||||
distroId: 'ubuntu',
|
||||
workspacePath: internalDir.path,
|
||||
activate: true,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(buildTestApp(
|
||||
child: const TerminalView(),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// AppBar 标题与副标题
|
||||
expect(find.text('会话1'), findsOneWidget);
|
||||
// 内部项目:副标题应为项目名称 "term_internal_proj",而不是绝对路径
|
||||
expect(find.text('term_internal_proj'), findsOneWidget);
|
||||
expect(find.text(internalDir.path), findsNothing);
|
||||
|
||||
// 切换为外部项目工作区会话
|
||||
final externalPath = p.normalize('C:/workspace/my_ext_work');
|
||||
terminalProvider.createSession(
|
||||
name: '会话2',
|
||||
distroId: 'ubuntu',
|
||||
workspacePath: externalPath,
|
||||
activate: true,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('会话2'), findsOneWidget);
|
||||
// 外部项目:副标题应为完整路径
|
||||
expect(find.text(externalPath), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
group('进入终端前的电池优化检测与导航测试', () {
|
||||
testWidgets('点击 AppBar 更多菜单中的终端按钮触发进入终端', (tester) async {
|
||||
await tester.pumpWidget(buildTestApp(
|
||||
child: const Scaffold(
|
||||
appBar: CodeEditorAppBar(filePath: null),
|
||||
body: Center(child: Text('Editor')),
|
||||
),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 点击右上角更多按钮
|
||||
final moreButton = find.byIcon(Icons.more_vert);
|
||||
expect(moreButton, findsOneWidget);
|
||||
await tester.tap(moreButton);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 菜单弹出,找到“终端”选项
|
||||
final terminalItem = find.text('终端');
|
||||
expect(terminalItem, findsOneWidget);
|
||||
|
||||
// 点击终端
|
||||
await tester.tap(terminalItem);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 验证进入终端视图 TerminalView
|
||||
expect(find.byType(TerminalView), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('非 Android 平台下 promptBatteryOptimizationIfNeeded 静默返回 false 且无弹窗', (tester) async {
|
||||
await tester.pumpWidget(buildTestApp(
|
||||
child: Builder(
|
||||
builder: (context) => ElevatedButton(
|
||||
onPressed: () async {
|
||||
final res = await PermissionService.instance.promptBatteryOptimizationIfNeeded(context);
|
||||
expect(res, isFalse);
|
||||
},
|
||||
child: const Text('Test'),
|
||||
),
|
||||
),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('Test'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(AlertDialog), findsNothing);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
import 'dart:ui';
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/widgets/terminal_selection_overlay.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:xterm/xterm.dart' as xterm;
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('TerminalSelectionOverlay 终端框选与菜单测试', () {
|
||||
late xterm.Terminal terminal;
|
||||
late xterm.TerminalController controller;
|
||||
late FocusNode focusNode;
|
||||
late GlobalKey<xterm.TerminalViewState> terminalViewKey;
|
||||
|
||||
String? clipboardContent;
|
||||
|
||||
setUp(() {
|
||||
terminal = xterm.Terminal(maxLines: 100);
|
||||
controller = xterm.TerminalController();
|
||||
focusNode = FocusNode();
|
||||
terminalViewKey = GlobalKey<xterm.TerminalViewState>();
|
||||
clipboardContent = null;
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
(MethodCall methodCall) async {
|
||||
if (methodCall.method == 'Clipboard.setData') {
|
||||
clipboardContent = (methodCall.arguments as Map<dynamic, dynamic>)['text'] as String?;
|
||||
return null;
|
||||
}
|
||||
if (methodCall.method == 'Clipboard.getData') {
|
||||
return <String, dynamic>{'text': clipboardContent};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
controller.dispose();
|
||||
focusNode.dispose();
|
||||
});
|
||||
|
||||
Widget buildTestWidget({Locale locale = const Locale('zh')}) {
|
||||
return MaterialApp(
|
||||
locale: locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 400,
|
||||
height: 600,
|
||||
child: TerminalSelectionOverlay(
|
||||
terminal: terminal,
|
||||
controller: controller,
|
||||
terminalViewKey: terminalViewKey,
|
||||
focusNode: focusNode,
|
||||
child: xterm.TerminalView(
|
||||
terminal,
|
||||
key: terminalViewKey,
|
||||
controller: controller,
|
||||
focusNode: focusNode,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('无选区时不显示拖动手柄与弹出菜单', (tester) async {
|
||||
terminal.write('Hello Terminal\r\n');
|
||||
await tester.pumpWidget(buildTestWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(CustomPaint), findsWidgets);
|
||||
// 没有任何选区手柄或菜单
|
||||
expect(find.text('复制'), findsNothing);
|
||||
expect(find.text('粘贴'), findsNothing);
|
||||
expect(find.text('全选'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('选中文本后自动展示两个拖动手柄以及浮动菜单', (tester) async {
|
||||
terminal.write('Hello Terminal World\r\n');
|
||||
await tester.pumpWidget(buildTestWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 设置选区覆盖 "Hello"
|
||||
controller.setSelection(
|
||||
terminal.buffer.createAnchor(0, 0),
|
||||
terminal.buffer.createAnchor(5, 0),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 菜单弹出:包含复制、粘贴、全选
|
||||
expect(find.text('复制'), findsOneWidget);
|
||||
expect(find.text('粘贴'), findsOneWidget);
|
||||
expect(find.text('全选'), findsOneWidget);
|
||||
|
||||
// 选区存在手柄
|
||||
expect(controller.selection, isNotNull);
|
||||
expect(controller.selection!.isCollapsed, isFalse);
|
||||
});
|
||||
|
||||
testWidgets('英文环境下菜单显示 Copy, Paste, Select All', (tester) async {
|
||||
terminal.write('Hello Terminal World\r\n');
|
||||
await tester.pumpWidget(buildTestWidget(locale: const Locale('en')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
controller.setSelection(
|
||||
terminal.buffer.createAnchor(0, 0),
|
||||
terminal.buffer.createAnchor(5, 0),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Copy'), findsOneWidget);
|
||||
expect(find.text('Paste'), findsOneWidget);
|
||||
expect(find.text('Select All'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('点击菜单中的“复制”将选区文本写入剪贴板并清空选区与关闭菜单', (tester) async {
|
||||
terminal.write('TestText\r\n');
|
||||
await tester.pumpWidget(buildTestWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 清空初始系统剪贴板
|
||||
await Clipboard.setData(const ClipboardData(text: ''));
|
||||
|
||||
controller.setSelection(
|
||||
terminal.buffer.createAnchor(0, 0),
|
||||
terminal.buffer.createAnchor(8, 0),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('复制'), findsOneWidget);
|
||||
await tester.tap(find.text('复制'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 验证剪贴板
|
||||
final clipData = await Clipboard.getData(Clipboard.kTextPlain);
|
||||
expect(clipData?.text, equals('TestText'));
|
||||
|
||||
// 选区已清空,菜单已隐藏
|
||||
expect(controller.selection, isNull);
|
||||
expect(find.text('复制'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('点击菜单中的“粘贴”将剪贴板内容输入到终端', (tester) async {
|
||||
String? outputData;
|
||||
terminal.onOutput = (data) {
|
||||
outputData = data;
|
||||
terminal.write(data);
|
||||
};
|
||||
|
||||
terminal.write('Prompt\$ ');
|
||||
await tester.pumpWidget(buildTestWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
clipboardContent = 'ls -la';
|
||||
|
||||
controller.setSelection(
|
||||
terminal.buffer.createAnchor(0, 0),
|
||||
terminal.buffer.createAnchor(6, 0),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('粘贴'), findsOneWidget);
|
||||
await tester.tap(find.text('粘贴'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 验证终端输出被粘贴
|
||||
expect(outputData, equals('ls -la'));
|
||||
expect(terminal.buffer.getText(), contains('ls -la'));
|
||||
expect(controller.selection, isNull);
|
||||
expect(find.text('粘贴'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('点击菜单中的“全选”选择终端所有可见字符', (tester) async {
|
||||
terminal.write('Line 1\r\nLine 2\r\nLine 3\r\n');
|
||||
await tester.pumpWidget(buildTestWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
controller.setSelection(
|
||||
terminal.buffer.createAnchor(0, 0),
|
||||
terminal.buffer.createAnchor(4, 0),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('全选'), findsOneWidget);
|
||||
await tester.tap(find.text('全选'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 选区扩展
|
||||
expect(controller.selection, isNotNull);
|
||||
expect(controller.selection!.begin.x, equals(0));
|
||||
expect(controller.selection!.begin.y, equals(0));
|
||||
});
|
||||
|
||||
testWidgets('拖动手柄时隐藏弹出菜单,拖动结束后重新展示', (tester) async {
|
||||
terminal.write('Hello World from Terminal\r\n');
|
||||
await tester.pumpWidget(buildTestWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
controller.setSelection(
|
||||
terminal.buffer.createAnchor(0, 0),
|
||||
terminal.buffer.createAnchor(11, 0),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('复制'), findsOneWidget);
|
||||
|
||||
final handleFinder = find.byWidgetPredicate(
|
||||
(w) => w.runtimeType.toString() == '_TerminalSelectionHandle',
|
||||
);
|
||||
expect(handleFinder, findsNWidgets(2));
|
||||
|
||||
// 模拟拖拽结束手柄
|
||||
final handleCenter = tester.getCenter(handleFinder.last);
|
||||
final gesture = await tester.startGesture(handleCenter);
|
||||
await tester.pump();
|
||||
await gesture.moveBy(const Offset(30, 0));
|
||||
await tester.pump();
|
||||
|
||||
// 移动过程中菜单隐藏
|
||||
expect(find.text('复制'), findsNothing);
|
||||
|
||||
await gesture.up();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 松手后菜单恢复
|
||||
expect(find.text('复制'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('鼠标直接拖动框选文本后松开弹出菜单', (tester) async {
|
||||
terminal.write('Hello Terminal World\r\n');
|
||||
await tester.pumpWidget(buildTestWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final terminalTopLeft = tester.getTopLeft(find.byType(xterm.TerminalView));
|
||||
// 在文本区域内拖动
|
||||
final gesture = await tester.startGesture(
|
||||
terminalTopLeft + const Offset(15, 15),
|
||||
kind: PointerDeviceKind.mouse,
|
||||
);
|
||||
await tester.pump();
|
||||
await gesture.moveBy(const Offset(60, 0));
|
||||
await tester.pump();
|
||||
await gesture.up();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 验证是否已选中文本
|
||||
expect(controller.selection, isNotNull);
|
||||
expect(controller.selection!.isCollapsed, isFalse);
|
||||
// 验证菜单是否弹出
|
||||
expect(find.text('复制'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user