2
This commit is contained in:
1 parent
5ac164b407
commit
f93f6095af
94 files changed
+7877
-4018
No files matched your search
@@ -6,7 +6,12 @@ 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
|
||||
/// 构造包含合法 XZ 头的字节流用于测试
|
||||
List<int> encodeValidXz(List<int> payload) {
|
||||
// 最小合法 XZ 流结构 (Stream Header + Filter Flags + Data + Footer)
|
||||
final xzEncoded = XZEncoder().encode(payload);
|
||||
return xzEncoded;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:code_editor/models/notice_item.dart';
|
||||
import 'package:code_editor/providers/notice_center.dart';
|
||||
import 'package:code_editor/services/background_task/background_task.dart';
|
||||
import 'package:code_editor/services/background_task/background_task_scheduler.dart';
|
||||
import 'package:code_editor/services/background_task/generic_background_task.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('BackgroundTaskScheduler Tests', () {
|
||||
late NoticeCenter noticeCenter;
|
||||
late BackgroundTaskScheduler scheduler;
|
||||
|
||||
setUp(() {
|
||||
noticeCenter = NoticeCenter();
|
||||
scheduler = BackgroundTaskScheduler.instance;
|
||||
scheduler.attachNoticeCenter(noticeCenter);
|
||||
});
|
||||
|
||||
test('packageManager scope tasks are executed sequentially without race conditions', () async {
|
||||
final executionOrder = <String>[];
|
||||
final activePackageManagerTasks = <String>[];
|
||||
var maxConcurrentPackageManager = 0;
|
||||
|
||||
Future<bool> runTask(String id, Duration duration) async {
|
||||
activePackageManagerTasks.add(id);
|
||||
if (activePackageManagerTasks.length > maxConcurrentPackageManager) {
|
||||
maxConcurrentPackageManager = activePackageManagerTasks.length;
|
||||
}
|
||||
await Future.delayed(duration);
|
||||
executionOrder.add(id);
|
||||
activePackageManagerTasks.remove(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
final task1 = GenericBackgroundTask<bool>(
|
||||
id: 'pkg1',
|
||||
scope: TaskExecutionScope.packageManager,
|
||||
priority: TaskPriority.projectLifecycle,
|
||||
runner: (_) => runTask('pkg1', const Duration(milliseconds: 50)),
|
||||
);
|
||||
|
||||
final task2 = GenericBackgroundTask<bool>(
|
||||
id: 'pkg2',
|
||||
scope: TaskExecutionScope.packageManager,
|
||||
priority: TaskPriority.projectLifecycle,
|
||||
runner: (_) => runTask('pkg2', const Duration(milliseconds: 20)),
|
||||
);
|
||||
|
||||
final future1 = scheduler.submit(task1);
|
||||
final future2 = scheduler.submit(task2);
|
||||
|
||||
await Future.wait([future1, future2]);
|
||||
|
||||
expect(maxConcurrentPackageManager, 1);
|
||||
expect(executionOrder, ['pkg1', 'pkg2']);
|
||||
});
|
||||
|
||||
test('Higher priority task jumps queue ahead of lower priority queued tasks', () async {
|
||||
final executionOrder = <String>[];
|
||||
|
||||
// 先占住 packageManager 锁
|
||||
final blocker = GenericBackgroundTask<bool>(
|
||||
id: 'blocker',
|
||||
scope: TaskExecutionScope.packageManager,
|
||||
priority: TaskPriority.projectLifecycle,
|
||||
runner: (_) async {
|
||||
await Future.delayed(const Duration(milliseconds: 60));
|
||||
executionOrder.add('blocker');
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
final lowPriority = GenericBackgroundTask<bool>(
|
||||
id: 'low',
|
||||
scope: TaskExecutionScope.packageManager,
|
||||
priority: TaskPriority.projectLifecycle,
|
||||
runner: (_) async {
|
||||
executionOrder.add('low');
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
final highPriority = GenericBackgroundTask<bool>(
|
||||
id: 'high',
|
||||
scope: TaskExecutionScope.packageManager,
|
||||
priority: TaskPriority.userInitiated,
|
||||
runner: (_) async {
|
||||
executionOrder.add('high');
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
final fBlocker = scheduler.submit(blocker);
|
||||
// 两个在 blocker 执行期间进入排队
|
||||
final fLow = scheduler.submit(lowPriority);
|
||||
final fHigh = scheduler.submit(highPriority);
|
||||
|
||||
await Future.wait([fBlocker, fLow, fHigh]);
|
||||
|
||||
expect(executionOrder, ['blocker', 'high', 'low']);
|
||||
});
|
||||
|
||||
test('Task cancellation removes queued task and notifies NoticeCenter', () async {
|
||||
// blocker
|
||||
final blocker = GenericBackgroundTask<bool>(
|
||||
id: 'blocker2',
|
||||
scope: TaskExecutionScope.packageManager,
|
||||
priority: TaskPriority.projectLifecycle,
|
||||
runner: (_) => Future.delayed(const Duration(milliseconds: 50), () => true),
|
||||
);
|
||||
|
||||
final target = GenericBackgroundTask<bool>(
|
||||
id: 'to_cancel',
|
||||
scope: TaskExecutionScope.packageManager,
|
||||
priority: TaskPriority.projectLifecycle,
|
||||
showNotice: true,
|
||||
noticeTextBuilder: (state, {detail, error}) => const ComponentInstallPhaseText(
|
||||
componentName: 'test',
|
||||
isQueued: true,
|
||||
),
|
||||
runner: (_) async => true,
|
||||
);
|
||||
|
||||
final fBlocker = scheduler.submit(blocker);
|
||||
final fTarget = scheduler.submit(target);
|
||||
|
||||
expect(noticeCenter.visible.any((e) => e.id == 'to_cancel'), isTrue);
|
||||
|
||||
scheduler.cancel('to_cancel');
|
||||
|
||||
expect(fTarget, throwsA(isA<CancellationException>()));
|
||||
// dismiss 后卡片被标记为 removing(等待 UI 播放退场动画)
|
||||
expect(noticeCenter.removingIds.contains('to_cancel'), isTrue);
|
||||
noticeCenter.finalizeDismiss('to_cancel');
|
||||
expect(noticeCenter.visible.any((e) => e.id == 'to_cancel'), isFalse);
|
||||
|
||||
await fBlocker;
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:code_editor/widgets/code_autocomplete_view.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
void main() {
|
||||
group('CodeAutocomplete Adaptive Height and Scrolling Tests', () {
|
||||
test('CodeAutocompleteView preferredSize dynamically adapts to prompt count', () {
|
||||
final notifier = ValueNotifier<CodeAutocompleteEditingValue>(
|
||||
const CodeAutocompleteEditingValue(
|
||||
input: '',
|
||||
prompts: [
|
||||
CodeKeywordPrompt(word: 'first'),
|
||||
],
|
||||
index: 0,
|
||||
),
|
||||
);
|
||||
|
||||
final view1 = CodeAutocompleteView(
|
||||
notifier: notifier,
|
||||
onSelected: (_) {},
|
||||
);
|
||||
|
||||
// 1 item: 1 * 36.0 + 8.0 + 2.0 = 46.0
|
||||
expect(view1.preferredSize.height, equals(46.0));
|
||||
|
||||
// 2 items: 2 * 36.0 + 10.0 = 82.0
|
||||
notifier.value = const CodeAutocompleteEditingValue(
|
||||
input: '',
|
||||
prompts: [
|
||||
CodeKeywordPrompt(word: 'first'),
|
||||
CodeKeywordPrompt(word: 'second'),
|
||||
],
|
||||
index: 0,
|
||||
);
|
||||
final view2 = CodeAutocompleteView(
|
||||
notifier: notifier,
|
||||
onSelected: (_) {},
|
||||
);
|
||||
expect(view2.preferredSize.height, equals(82.0));
|
||||
|
||||
// 3 items: 3 * 36.0 + 10.0 = 118.0
|
||||
notifier.value = const CodeAutocompleteEditingValue(
|
||||
input: '',
|
||||
prompts: [
|
||||
CodeKeywordPrompt(word: 'first'),
|
||||
CodeKeywordPrompt(word: 'second'),
|
||||
CodeKeywordPrompt(word: 'third'),
|
||||
],
|
||||
index: 0,
|
||||
);
|
||||
final view3 = CodeAutocompleteView(
|
||||
notifier: notifier,
|
||||
onSelected: (_) {},
|
||||
);
|
||||
expect(view3.preferredSize.height, equals(118.0));
|
||||
|
||||
// 10 items capped at default max height 196.0
|
||||
notifier.value = CodeAutocompleteEditingValue(
|
||||
input: '',
|
||||
prompts: List.generate(10, (i) => CodeKeywordPrompt(word: 'item_$i')),
|
||||
index: 0,
|
||||
);
|
||||
final view10 = CodeAutocompleteView(
|
||||
notifier: notifier,
|
||||
onSelected: (_) {},
|
||||
);
|
||||
expect(view10.preferredSize.height, equals(196.0));
|
||||
|
||||
notifier.dispose();
|
||||
});
|
||||
|
||||
testWidgets('CodeAutocompleteView scrolls smoothly when constrained in limited height', (tester) async {
|
||||
final notifier = ValueNotifier<CodeAutocompleteEditingValue>(
|
||||
const CodeAutocompleteEditingValue(
|
||||
input: '',
|
||||
prompts: [
|
||||
CodeKeywordPrompt(word: 'option_1'),
|
||||
CodeKeywordPrompt(word: 'option_2'),
|
||||
CodeKeywordPrompt(word: 'option_3'),
|
||||
],
|
||||
index: 0,
|
||||
),
|
||||
);
|
||||
|
||||
String? selectedWord;
|
||||
|
||||
// 空间不足:强制限制高度为 80.0(只能完整显示约 2 项,第 3 项需要滑动)
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: SizedBox(
|
||||
width: 270.0,
|
||||
height: 80.0,
|
||||
child: CodeAutocompleteView(
|
||||
notifier: notifier,
|
||||
onSelected: (result) {
|
||||
selectedWord = (result as dynamic).word as String?;
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(find.text('option_1'), findsOneWidget);
|
||||
expect(find.text('option_2'), findsOneWidget);
|
||||
|
||||
// 模拟选择第 3 个项目,触发自动滚动
|
||||
notifier.value = notifier.value.copyWith(index: 2);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 滑动或选择后,第 3 项可见且可点击
|
||||
expect(find.text('option_3'), findsOneWidget);
|
||||
await tester.tap(find.text('option_3'));
|
||||
await tester.pump();
|
||||
|
||||
expect(selectedWord, equals('option_3'));
|
||||
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
notifier.dispose();
|
||||
});
|
||||
|
||||
testWidgets('Autocomplete does not dismiss on scrolling or operating virtual keyboard, only on tapping editor outside menu', (tester) async {
|
||||
final controller = CodeLineEditingController.fromText('foo\nbar\nbaz');
|
||||
final promptsBuilder = DefaultCodeAutocompletePromptsBuilder(
|
||||
directPrompts: [
|
||||
const CodeKeywordPrompt(word: 'foo_item1'),
|
||||
const CodeKeywordPrompt(word: 'foo_item2'),
|
||||
],
|
||||
);
|
||||
|
||||
bool virtualKeyPressed = false;
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: CodeAutocomplete(
|
||||
viewBuilder: (context, notifier, onSelected) {
|
||||
return CodeAutocompleteView(
|
||||
notifier: notifier,
|
||||
onSelected: onSelected,
|
||||
);
|
||||
},
|
||||
promptsBuilder: promptsBuilder,
|
||||
child: CodeEditor(
|
||||
controller: controller,
|
||||
),
|
||||
),
|
||||
),
|
||||
GestureDetector(
|
||||
key: const ValueKey('mock_virtual_keyboard'),
|
||||
onTap: () {
|
||||
virtualKeyPressed = true;
|
||||
},
|
||||
child: Container(
|
||||
height: 50,
|
||||
width: double.infinity,
|
||||
color: Colors.grey,
|
||||
child: const Text('Virtual Keyboard Key'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// 输入触发补全
|
||||
controller.text = 'fo';
|
||||
controller.selection = const CodeLineSelection.collapsed(index: 0, offset: 2);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
|
||||
expect(find.byType(CodeAutocompleteView), findsOneWidget);
|
||||
|
||||
// 1. 操作小键盘控件:不应关闭菜单
|
||||
await tester.tap(find.byKey(const ValueKey('mock_virtual_keyboard')));
|
||||
await tester.pump();
|
||||
expect(virtualKeyPressed, isTrue);
|
||||
expect(find.byType(CodeAutocompleteView), findsOneWidget);
|
||||
|
||||
// 2. 滑动编辑区:上下滑动拖动代码,不应关闭菜单
|
||||
final editorFinder = find.byType(CodeEditor);
|
||||
await tester.drag(editorFinder, const Offset(0, -60));
|
||||
await tester.pump();
|
||||
expect(find.byType(CodeAutocompleteView), findsOneWidget);
|
||||
|
||||
// 3. 只有点击到菜单区域外的编辑区,才关闭菜单
|
||||
final editorTopLeft = tester.getTopLeft(editorFinder);
|
||||
await tester.tapAt(editorTopLeft + const Offset(50, 150));
|
||||
await tester.pump();
|
||||
expect(find.byType(CodeAutocompleteView), findsNothing);
|
||||
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump(const Duration(milliseconds: 600));
|
||||
controller.dispose();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import 'package:code_editor/providers/settings_provider.dart';
|
||||
import 'package:code_editor/services/code_completion/smart_prompts_builder.dart';
|
||||
import 'package:code_editor/services/lsp/lsp_protocol.dart';
|
||||
import 'package:code_editor/widgets/editor/editor_diagnostic_controller.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class _MockAsyncProvider implements CompletionProvider {
|
||||
final List<SmartPrompt> results;
|
||||
_MockAsyncProvider(this.results);
|
||||
|
||||
@override
|
||||
String get id => 'mock_async';
|
||||
|
||||
@override
|
||||
bool get isAsync => true;
|
||||
|
||||
@override
|
||||
Future<List<SmartPrompt>> provideCompletions(CompletionContext context) async {
|
||||
await Future.delayed(const Duration(milliseconds: 10));
|
||||
return results;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('Completion Pipeline Architecture Tests', () {
|
||||
test('LspCompletionProvider.fromLspItem maps kinds and details correctly', () {
|
||||
final lspItem = LspCompletionItem(
|
||||
label: 'printf',
|
||||
kind: 3, // Function
|
||||
detail: 'int printf(const char *format, ...)',
|
||||
insertText: 'printf',
|
||||
);
|
||||
|
||||
final prompt = LspCompletionProvider.fromLspItem(lspItem);
|
||||
expect(prompt.word, equals('printf'));
|
||||
expect(prompt.kind, equals(SmartPromptKind.function));
|
||||
expect(prompt.type, equals('int printf(const char *format, ...)'));
|
||||
});
|
||||
|
||||
test('CompletionEngine.requestCompletionsAsync directly resolves LSP completions with fuzzy score & sorting', () async {
|
||||
final asyncLsp = _MockAsyncProvider([
|
||||
SmartPrompt(
|
||||
word: 'printf',
|
||||
kind: SmartPromptKind.function,
|
||||
type: 'int printf(const char *format, ...)',
|
||||
sortText: '0001',
|
||||
),
|
||||
SmartPrompt(
|
||||
word: 'print_custom',
|
||||
kind: SmartPromptKind.function,
|
||||
sortText: '0002',
|
||||
),
|
||||
]);
|
||||
|
||||
final engine = CompletionEngine(providers: [asyncLsp]);
|
||||
|
||||
final ctx = CompletionContext(
|
||||
input: 'pri',
|
||||
lineIndex: 0,
|
||||
characterOffset: 3,
|
||||
codeLine: const CodeLine('pri'),
|
||||
selection: const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3),
|
||||
);
|
||||
|
||||
final result = await engine.requestCompletionsAsync(ctx);
|
||||
expect(result, isNotNull);
|
||||
expect(result!.prompts, isNotEmpty);
|
||||
expect(result.prompts.first.word, equals('printf'));
|
||||
expect((result.prompts.first as SmartPrompt).type, equals('int printf(const char *format, ...)'));
|
||||
expect(result.prompts.map((p) => p.word), contains('print_custom'));
|
||||
});
|
||||
|
||||
test('CompletionEngine drops stale request when new request is initiated', () async {
|
||||
final asyncLsp = _MockAsyncProvider([
|
||||
SmartPrompt(
|
||||
word: 'printf',
|
||||
kind: SmartPromptKind.function,
|
||||
),
|
||||
]);
|
||||
|
||||
final engine = CompletionEngine(providers: [asyncLsp]);
|
||||
|
||||
final ctx1 = CompletionContext(
|
||||
input: 'p',
|
||||
lineIndex: 0,
|
||||
characterOffset: 1,
|
||||
codeLine: const CodeLine('p'),
|
||||
selection: const CodeLineSelection(baseIndex: 0, baseOffset: 1, extentIndex: 0, extentOffset: 1),
|
||||
);
|
||||
|
||||
final ctx2 = CompletionContext(
|
||||
input: 'pr',
|
||||
lineIndex: 0,
|
||||
characterOffset: 2,
|
||||
codeLine: const CodeLine('pr'),
|
||||
selection: const CodeLineSelection(baseIndex: 0, baseOffset: 2, extentIndex: 0, extentOffset: 2),
|
||||
);
|
||||
|
||||
// 发起两次连续请求,前一次会被后一次作为陈旧请求丢弃
|
||||
final future1 = engine.requestCompletionsAsync(ctx1);
|
||||
final future2 = engine.requestCompletionsAsync(ctx2);
|
||||
|
||||
final res1 = await future1;
|
||||
final res2 = await future2;
|
||||
|
||||
expect(res1, isNull); // 过期响应返回 null
|
||||
expect(res2, isNotNull); // 最新响应正常返回
|
||||
});
|
||||
});
|
||||
|
||||
group('EditorDiagnosticController Tests', () {
|
||||
testWidgets('EditorDiagnosticController returns base span when no diagnostics exist', (tester) async {
|
||||
late BuildContext ctx;
|
||||
await tester.pumpWidget(
|
||||
Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: Builder(
|
||||
builder: (c) {
|
||||
ctx = c;
|
||||
return const SizedBox();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const controller = EditorDiagnosticController();
|
||||
const baseSpan = TextSpan(text: 'int main() {}');
|
||||
final result = controller.buildDiagnosticSpans(
|
||||
context: ctx,
|
||||
filePath: 'test.c',
|
||||
index: 0,
|
||||
codeLine: const CodeLine('int main() {}'),
|
||||
textSpan: baseSpan,
|
||||
style: const TextStyle(),
|
||||
);
|
||||
|
||||
expect(result.text, equals('int main() {}'));
|
||||
});
|
||||
});
|
||||
|
||||
group('Completion Switch & Isolation Tests', () {
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
});
|
||||
|
||||
test('SettingsProvider lsp completion flag persists properly', () async {
|
||||
final provider = SettingsProvider();
|
||||
await provider.init();
|
||||
|
||||
expect(provider.enableLspCompletion, isTrue);
|
||||
|
||||
await provider.setEnableLspCompletion(false);
|
||||
expect(provider.enableLspCompletion, isFalse);
|
||||
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
expect(prefs.getBool('enable_lsp_completion'), isFalse);
|
||||
|
||||
// 重新实例化验证从持久化中正确恢复
|
||||
final restoredProvider = SettingsProvider();
|
||||
await restoredProvider.init();
|
||||
expect(restoredProvider.enableLspCompletion, isFalse);
|
||||
});
|
||||
|
||||
test('SmartCodeAutocompletePromptsBuilder provider filtering by flag', () {
|
||||
// 1. 默认开启:仅 1 个 LspCompletionProvider
|
||||
final builderDefault = SmartCodeAutocompletePromptsBuilder();
|
||||
expect(builderDefault.engine.providers.length, equals(1));
|
||||
expect(builderDefault.engine.providers.first, isA<LspCompletionProvider>());
|
||||
|
||||
// 2. 关闭 LSP:providers 为空
|
||||
final builderDisabled = SmartCodeAutocompletePromptsBuilder(
|
||||
enableLspCompletion: false,
|
||||
);
|
||||
expect(builderDisabled.engine.providers.isEmpty, isTrue);
|
||||
});
|
||||
|
||||
test('Pure Backend Mode: SmartCodeAutocompletePromptsBuilder.build returns Future that resolves LSP completions', () async {
|
||||
final asyncLsp = _MockAsyncProvider([
|
||||
SmartPrompt(
|
||||
word: 'printf',
|
||||
kind: SmartPromptKind.function,
|
||||
type: 'int printf(const char *format, ...)',
|
||||
),
|
||||
]);
|
||||
|
||||
final builder = SmartCodeAutocompletePromptsBuilder(
|
||||
customProviders: [asyncLsp],
|
||||
);
|
||||
|
||||
final result = builder.build(
|
||||
_FakeBuildContext(),
|
||||
const CodeLine('pri'),
|
||||
const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3),
|
||||
);
|
||||
|
||||
expect(result, isA<Future<CodeAutocompleteEditingValue?>>());
|
||||
final resolved = await (result as Future<CodeAutocompleteEditingValue?>);
|
||||
expect(resolved, isNotNull);
|
||||
expect(resolved!.prompts.length, equals(1));
|
||||
final prompt = resolved.prompts.first as SmartPrompt;
|
||||
expect(prompt.word, equals('printf'));
|
||||
expect(prompt.type, equals('int printf(const char *format, ...)'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
class _FakeBuildContext extends Fake implements BuildContext {}
|
||||
@@ -1,401 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,413 +0,0 @@
|
||||
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 {}
|
||||
|
||||
@@ -1,525 +0,0 @@
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:archive/archive.dart';
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/providers/distro_provider.dart';
|
||||
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();
|
||||
|
||||
late Directory tempBaseDir;
|
||||
late DistroManager manager;
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
tempBaseDir = Directory.systemTemp.createTempSync('distro_multi_test_');
|
||||
manager = DistroManager();
|
||||
manager.customBaseDir = tempBaseDir;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
manager.customSdcardPath = null;
|
||||
try {
|
||||
if (tempBaseDir.existsSync()) {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
}
|
||||
} catch (_) {}
|
||||
});
|
||||
|
||||
Uint8List createMockRootfsTarGz() {
|
||||
final archive = Archive();
|
||||
archive.addFile(ArchiveFile('bin/sh', 11, 'echo "sh"'.codeUnits));
|
||||
archive.addFile(ArchiveFile('etc/os-release', 18, 'NAME="Alpine Linux"'.codeUnits));
|
||||
final tarData = TarEncoder().encode(archive);
|
||||
final gzData = GZipEncoder().encode(tarData);
|
||||
return Uint8List.fromList(gzData!);
|
||||
}
|
||||
|
||||
group('DistroManager 多系统实例管理测试', () {
|
||||
test('初始状态系统列表为空', () async {
|
||||
final systems = await manager.listInstalledSystems();
|
||||
expect(systems, isEmpty);
|
||||
expect(await manager.hasAnySystem(), isFalse);
|
||||
});
|
||||
|
||||
test('空壳 rootfs(只有 etc 缺少 bin)不被视为已安装系统,也不会出现在列表里', () async {
|
||||
// 复现历史缺陷遗留物:探测流程的 ensure* 会在未安装的系统名下造出 rootfs/etc
|
||||
final ghostEtc = Directory(p.join(tempBaseDir.path, 'ghost', 'rootfs', 'etc'));
|
||||
ghostEtc.createSync(recursive: true);
|
||||
File(p.join(ghostEtc.path, 'resolv.conf')).writeAsStringSync('nameserver 1.1.1.1\n');
|
||||
|
||||
// 一个真正可用的系统实例
|
||||
final realRootfs = Directory(p.join(tempBaseDir.path, 'real', 'rootfs'));
|
||||
Directory(p.join(realRootfs.path, 'etc')).createSync(recursive: true);
|
||||
Directory(p.join(realRootfs.path, 'bin')).createSync(recursive: true);
|
||||
|
||||
expect(await manager.listInstalledSystems(), equals(<String>['real']));
|
||||
expect(await manager.isSystemInstalled('ghost'), isFalse);
|
||||
expect(await manager.isSystemInstalled('real'), isTrue);
|
||||
});
|
||||
|
||||
test('buildLaunchConfig 对未安装的系统直接抛错,且不在磁盘上创建任何目录', () async {
|
||||
await expectLater(
|
||||
manager.buildLaunchConfig(
|
||||
systemName: 'not_installed',
|
||||
workspacePath: tempBaseDir.path,
|
||||
),
|
||||
throwsA(isA<StateError>()),
|
||||
);
|
||||
expect(Directory(p.join(tempBaseDir.path, 'not_installed')).existsSync(), isFalse);
|
||||
});
|
||||
|
||||
test('同一 Rootfs 包支持导入并创建多个独立系统实例', () async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'source_rootfs.tar.gz'));
|
||||
tempGzFile.writeAsBytesSync(gzBytes);
|
||||
|
||||
// 导入系统 1: alpine
|
||||
await manager.importFromCustomTarGz(
|
||||
systemName: 'alpine',
|
||||
tarGzFile: tempGzFile,
|
||||
);
|
||||
|
||||
// 导入系统 2: alpine_dev
|
||||
await manager.importFromCustomTarGz(
|
||||
systemName: 'alpine_dev',
|
||||
tarGzFile: tempGzFile,
|
||||
);
|
||||
|
||||
final systems = await manager.listInstalledSystems();
|
||||
expect(systems.length, equals(2));
|
||||
expect(systems, containsAll(['alpine', 'alpine_dev']));
|
||||
|
||||
// 验证各自根目录独立存在
|
||||
final alpineRootDir = await manager.getSystemRootDir('alpine');
|
||||
final devRootDir = await manager.getSystemRootDir('alpine_dev');
|
||||
expect(File(p.join(alpineRootDir.path, 'bin', 'sh')).existsSync(), isTrue);
|
||||
expect(File(p.join(devRootDir.path, 'bin', 'sh')).existsSync(), isTrue);
|
||||
expect(alpineRootDir.path != devRootDir.path, isTrue);
|
||||
|
||||
// 验证网络配置 (resolv.conf / hosts) 与挂载点 (/workspace, /tmp)
|
||||
final resolvFile = File(p.join(alpineRootDir.path, 'etc', 'resolv.conf'));
|
||||
expect(resolvFile.existsSync(), isTrue);
|
||||
expect(resolvFile.readAsStringSync(), contains('1.1.1.1'));
|
||||
|
||||
final hostsFile = File(p.join(alpineRootDir.path, 'etc', 'hosts'));
|
||||
expect(hostsFile.existsSync(), isTrue);
|
||||
expect(hostsFile.readAsStringSync(), contains('127.0.0.1 localhost'));
|
||||
|
||||
expect(Directory(p.join(alpineRootDir.path, 'workspace')).existsSync(), isTrue);
|
||||
expect(Directory(p.join(alpineRootDir.path, 'tmp')).existsSync(), isTrue);
|
||||
|
||||
// 验证已就绪状态检测
|
||||
expect(await manager.isSystemInstalled('alpine'), isTrue);
|
||||
});
|
||||
|
||||
test('系统名称校验:非法字符与同名防重', () async {
|
||||
expect(
|
||||
() => manager.validateSystemName(''),
|
||||
throwsArgumentError,
|
||||
);
|
||||
|
||||
expect(
|
||||
() => manager.validateSystemName('bad/name*here'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
|
||||
// 创建一个系统后,同名抛出异常
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'temp.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
await manager.importFromCustomTarGz(systemName: 'my_sys', tarGzFile: tempGzFile);
|
||||
|
||||
expect(
|
||||
() => manager.validateSystemName('my_sys'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
});
|
||||
|
||||
test('解压取消时抛出异常并自动回滚清理残余目录', () async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'cancel_test.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
|
||||
bool cancelTriggered = false;
|
||||
|
||||
try {
|
||||
await manager.importFromCustomTarGz(
|
||||
systemName: 'cancelled_sys',
|
||||
tarGzFile: tempGzFile,
|
||||
onProgress: (prog, msg) {
|
||||
cancelTriggered = true;
|
||||
},
|
||||
isCancelled: () => cancelTriggered, // 模拟用户在解压循环中点击了取消
|
||||
);
|
||||
fail('应当抛出 DistroInstallCancelledException');
|
||||
} catch (e) {
|
||||
expect(e, isA<DistroInstallCancelledException>());
|
||||
}
|
||||
|
||||
// 验证未导入成功的脏目录被清理
|
||||
final sysRootDir = await manager.getSystemRootDir('cancelled_sys');
|
||||
expect(sysRootDir.existsSync(), isFalse);
|
||||
expect((await manager.listInstalledSystems()).contains('cancelled_sys'), isFalse);
|
||||
});
|
||||
|
||||
test('高危删除系统实例物理清除文件', () async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'del_test.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
|
||||
await manager.importFromCustomTarGz(systemName: 'to_delete', tarGzFile: tempGzFile);
|
||||
expect((await manager.listInstalledSystems()).contains('to_delete'), isTrue);
|
||||
|
||||
await manager.deleteSystem('to_delete');
|
||||
expect((await manager.listInstalledSystems()).contains('to_delete'), isFalse);
|
||||
|
||||
final sysDir = Directory(p.join(tempBaseDir.path, 'to_delete'));
|
||||
expect(sysDir.existsSync(), isFalse);
|
||||
});
|
||||
|
||||
test('buildLaunchConfig 准确指向对应系统根目录', () async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'cfg.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
|
||||
await manager.importFromCustomTarGz(systemName: 'prod_env', tarGzFile: tempGzFile);
|
||||
|
||||
final launchConfig = await manager.buildLaunchConfig(
|
||||
systemName: 'prod_env',
|
||||
workspacePath: tempBaseDir.path,
|
||||
);
|
||||
|
||||
expect(launchConfig.arguments, contains('-r'));
|
||||
final rootDir = await manager.getSystemRootDir('prod_env');
|
||||
expect(launchConfig.arguments, contains(rootDir.path));
|
||||
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 自动挂载 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);
|
||||
|
||||
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'));
|
||||
});
|
||||
});
|
||||
|
||||
group('DistroProvider 状态持久化与系统切换测试', () {
|
||||
test('默认系统自动选取与持久化切换', () async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'provider_test.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
|
||||
final provider = DistroProvider();
|
||||
await provider.init();
|
||||
expect(provider.selectedSystem, isNull);
|
||||
|
||||
// 导入首个系统,自动选为当前系统
|
||||
await provider.importFromCustomTarGz(systemName: 'sys_a', tarGzFile: tempGzFile);
|
||||
expect(provider.selectedSystem, equals('sys_a'));
|
||||
expect(provider.installedSystems, contains('sys_a'));
|
||||
|
||||
// 导入第二个系统,自动切换到新系统
|
||||
await provider.importFromCustomTarGz(systemName: 'sys_b', tarGzFile: tempGzFile);
|
||||
expect(provider.selectedSystem, equals('sys_b'));
|
||||
|
||||
// 手动切换回 sys_a 并持久化
|
||||
await provider.selectSystem('sys_a');
|
||||
expect(provider.selectedSystem, equals('sys_a'));
|
||||
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
expect(prefs.getString('terminal_default_system'), equals('sys_a'));
|
||||
|
||||
// 删除当前选中的系统,自动平滑退回到另一个系统
|
||||
await provider.deleteSystem('sys_a');
|
||||
expect(provider.installedSystems, equals(['sys_b']));
|
||||
expect(provider.selectedSystem, equals('sys_b'));
|
||||
|
||||
// 删除仅剩的系统,回到 null
|
||||
await provider.deleteSystem('sys_b');
|
||||
expect(provider.installedSystems, isEmpty);
|
||||
expect(provider.selectedSystem, isNull);
|
||||
});
|
||||
|
||||
test('删除系统实例时联动清理对应系统的全部终端会话', () async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'session_clean_test.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
|
||||
final distroProvider = DistroProvider();
|
||||
await distroProvider.init();
|
||||
|
||||
await distroProvider.importFromCustomTarGz(systemName: 'sys_1', tarGzFile: tempGzFile);
|
||||
await distroProvider.importFromCustomTarGz(systemName: 'sys_2', tarGzFile: tempGzFile);
|
||||
|
||||
final terminalProvider = TerminalProvider();
|
||||
distroProvider.onSystemDeleted = (deleted) {
|
||||
terminalProvider.removeSessionsForDistro(deleted);
|
||||
if (!distroProvider.hasAnySystem) {
|
||||
terminalProvider.clearAllSessions();
|
||||
}
|
||||
};
|
||||
|
||||
// 创建 sys_1 的两个会话,sys_2 的一个会话
|
||||
final s1 = terminalProvider.createSession(name: '会话1', distroId: 'sys_1');
|
||||
final s2 = terminalProvider.createSession(name: '会话2', distroId: 'sys_1');
|
||||
final s3 = terminalProvider.createSession(name: '会话3', distroId: 'sys_2');
|
||||
|
||||
expect(terminalProvider.sessions.length, equals(3));
|
||||
|
||||
// 删除 sys_1:应当仅删除 s1 与 s2,保留 s3
|
||||
await distroProvider.deleteSystem('sys_1');
|
||||
|
||||
expect(terminalProvider.sessions.length, equals(1));
|
||||
expect(terminalProvider.sessions.first.id, equals(s3.id));
|
||||
expect(terminalProvider.sessions.first.distroId, equals('sys_2'));
|
||||
expect(terminalProvider.sessions.any((s) => s.id == s1.id), isFalse);
|
||||
expect(terminalProvider.sessions.any((s) => s.id == s2.id), isFalse);
|
||||
|
||||
// 删除最后一个系统 sys_2:所有会话均被清理清空
|
||||
await distroProvider.deleteSystem('sys_2');
|
||||
expect(terminalProvider.sessions, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('DistroSelectorDialog 列表项仅显示名称,无副标题与前置勾选图标', (tester) async {
|
||||
final gzBytes = createMockRootfsTarGz();
|
||||
final tempGzFile = File(p.join(tempBaseDir.path, 'dialog_ui_test.tar.gz'))..writeAsBytesSync(gzBytes);
|
||||
|
||||
final distroProvider = DistroProvider();
|
||||
await tester.runAsync(() async {
|
||||
await distroProvider.init();
|
||||
await distroProvider.importFromCustomTarGz(systemName: 'my_alpine', tarGzFile: tempGzFile);
|
||||
});
|
||||
|
||||
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();
|
||||
|
||||
// 验证系统管理标题来自 l10n
|
||||
expect(find.text('系统管理'), findsOneWidget);
|
||||
|
||||
// 验证系统名称正常显示
|
||||
expect(find.text('my_alpine'), findsOneWidget);
|
||||
|
||||
// 验证无旧版副标题文字(如“当前默认系统”、“点击切换为默认”)
|
||||
expect(find.text('当前默认系统'), findsNothing);
|
||||
expect(find.text('点击切换为默认'), findsNothing);
|
||||
|
||||
// 验证无前置勾选图标
|
||||
expect(find.byIcon(Icons.check_circle), findsNothing);
|
||||
expect(find.byIcon(Icons.radio_button_unchecked), findsNothing);
|
||||
|
||||
// 验证存在高危删除按钮
|
||||
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,80 @@
|
||||
import 'package:code_editor/services/code_completion/smart_prompts_builder.dart';
|
||||
import 'package:code_editor/widgets/code_autocomplete_view.dart';
|
||||
import 'package:code_editor/widgets/editor/editor_overlay_scope.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
void main() {
|
||||
group('Editor Overlay Hierarchy Tests', () {
|
||||
testWidgets('CodeAutocomplete uses local EditorOverlayScope instead of root overlay', (tester) async {
|
||||
final controller = CodeLineEditingController.fromText('pri');
|
||||
final promptsBuilder = SmartCodeAutocompletePromptsBuilder(
|
||||
controller: controller,
|
||||
directPrompts: [
|
||||
CodeKeywordPrompt(word: 'printf'),
|
||||
],
|
||||
);
|
||||
|
||||
bool tappedBottomButton = false;
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: EditorOverlayScope(
|
||||
child: CodeAutocomplete(
|
||||
viewBuilder: (context, notifier, onSelected) {
|
||||
promptsBuilder.activeNotifier = notifier;
|
||||
return CodeAutocompleteView(
|
||||
notifier: notifier,
|
||||
onSelected: onSelected,
|
||||
);
|
||||
},
|
||||
promptsBuilder: promptsBuilder,
|
||||
child: CodeEditor(
|
||||
autofocus: false,
|
||||
controller: controller,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// 模拟小键盘(在 Column 中位于 Editor 下方)
|
||||
GestureDetector(
|
||||
key: const ValueKey('virtual_keyboard_btn'),
|
||||
onTap: () {
|
||||
tappedBottomButton = true;
|
||||
},
|
||||
child: Container(
|
||||
height: 50,
|
||||
width: double.infinity,
|
||||
color: Colors.blue,
|
||||
child: const Text('Virtual Key ;'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// 获取当前所有的 Overlay
|
||||
final overlays = tester.widgetList<Overlay>(find.byType(Overlay)).toList();
|
||||
// 至少应该有 2 个 Overlay:1 个是 MaterialApp/Navigator 的 root overlay,1 个是 EditorOverlayScope 的 local overlay
|
||||
expect(overlays.length, greaterThanOrEqualTo(2));
|
||||
|
||||
// 验证底部的模拟小键盘正常渲染
|
||||
expect(find.byKey(const ValueKey('virtual_keyboard_btn')), findsOneWidget);
|
||||
|
||||
// 点击虚拟小键盘,验证点击事件正常响应且不受干扰
|
||||
await tester.tap(find.byKey(const ValueKey('virtual_keyboard_btn')));
|
||||
expect(tappedBottomButton, isTrue);
|
||||
|
||||
// 清理测试组件树
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
controller.dispose();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/lsp_language_config.dart';
|
||||
import 'package:code_editor/models/run_task.dart';
|
||||
import 'package:code_editor/services/project_modules/maven_project_module.dart';
|
||||
import 'package:code_editor/services/project_modules/project_probe.dart';
|
||||
import 'package:code_editor/services/project_modules/python_project_module.dart';
|
||||
import 'package:code_editor/services/project_modules/single_file_task_detector.dart';
|
||||
import 'package:code_editor/services/project_task_dispatcher.dart';
|
||||
import 'package:code_editor/services/toolchain_service.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;
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() {
|
||||
tempDir = Directory.systemTemp.createTempSync('extended_modules_test_');
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
if (tempDir.existsSync()) {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
group('SingleFileTaskDetector Extended Tests', () {
|
||||
test('Detects Java single file', () {
|
||||
final javaFile = File(p.join(tempDir.path, 'Hello.java'))..writeAsStringSync('public class Hello {}');
|
||||
expect(SingleFileTaskDetector.isSupported(javaFile.path), isTrue);
|
||||
|
||||
final task = SingleFileTaskDetector.detect(tempDir.path, javaFile.path);
|
||||
expect(task, isNotNull);
|
||||
expect(task!.id, equals('detected_single_java'));
|
||||
expect(task.name, equals('Java: Hello.java'));
|
||||
expect(task.command, contains('java '));
|
||||
});
|
||||
|
||||
test('Detects TypeScript single file', () {
|
||||
final tsFile = File(p.join(tempDir.path, 'index.ts'))..writeAsStringSync('console.log(42);');
|
||||
expect(SingleFileTaskDetector.isSupported(tsFile.path), isTrue);
|
||||
|
||||
final task = SingleFileTaskDetector.detect(tempDir.path, tsFile.path);
|
||||
expect(task, isNotNull);
|
||||
expect(task!.id, equals('detected_single_ts'));
|
||||
expect(task.command, contains('npx -y tsx'));
|
||||
});
|
||||
|
||||
test('Detects Lua, Perl, PHP single files', () {
|
||||
final luaFile = File(p.join(tempDir.path, 'script.lua'))..writeAsStringSync('print("hi")');
|
||||
final plFile = File(p.join(tempDir.path, 'script.pl'))..writeAsStringSync('print "hi";');
|
||||
final phpFile = File(p.join(tempDir.path, 'index.php'))..writeAsStringSync('<?php echo "hi";');
|
||||
|
||||
final luaTask = SingleFileTaskDetector.detect(tempDir.path, luaFile.path);
|
||||
expect(luaTask, isNotNull);
|
||||
expect(luaTask!.id, equals('detected_single_lua'));
|
||||
expect(luaTask.command, contains('lua '));
|
||||
|
||||
final plTask = SingleFileTaskDetector.detect(tempDir.path, plFile.path);
|
||||
expect(plTask, isNotNull);
|
||||
expect(plTask!.id, equals('detected_single_perl'));
|
||||
expect(plTask.command, contains('perl '));
|
||||
|
||||
final phpTask = SingleFileTaskDetector.detect(tempDir.path, phpFile.path);
|
||||
expect(phpTask, isNotNull);
|
||||
expect(phpTask!.id, equals('detected_single_php'));
|
||||
expect(phpTask.command, contains('php '));
|
||||
});
|
||||
});
|
||||
|
||||
group('PythonProjectModule Tests', () {
|
||||
test('Activates on requirements.txt and generates pip, run and pytest tasks', () async {
|
||||
File(p.join(tempDir.path, 'requirements.txt')).writeAsStringSync('flask\npytest');
|
||||
File(p.join(tempDir.path, 'main.py')).writeAsStringSync('print("app")');
|
||||
Directory(p.join(tempDir.path, 'tests')).createSync();
|
||||
|
||||
final module = PythonProjectModule();
|
||||
expect(module.shouldActivate(tempDir), isTrue);
|
||||
|
||||
final dispatcher = ProjectTaskDispatcher();
|
||||
final probe = dispatcher.createProbe(
|
||||
projectRoot: tempDir.path,
|
||||
systemName: 'ubuntu',
|
||||
);
|
||||
|
||||
final result = await module.probe(probe);
|
||||
expect(result.status, equals(ModuleProbeStatus.ok));
|
||||
final taskIds = result.tasks.map((t) => t.id).toList();
|
||||
expect(taskIds, contains('detected_python_pip_install'));
|
||||
expect(taskIds, contains('detected_python_run_main'));
|
||||
expect(taskIds, contains('detected_python_pytest'));
|
||||
});
|
||||
});
|
||||
|
||||
group('MavenProjectModule Tests', () {
|
||||
test('Activates on pom.xml and supports mvnw wrapper', () async {
|
||||
File(p.join(tempDir.path, 'pom.xml')).writeAsStringSync('<project></project>');
|
||||
File(p.join(tempDir.path, 'mvnw')).writeAsStringSync('#!/bin/sh');
|
||||
|
||||
final module = MavenProjectModule();
|
||||
expect(module.shouldActivate(tempDir), isTrue);
|
||||
|
||||
final dispatcher = ProjectTaskDispatcher();
|
||||
final probe = dispatcher.createProbe(
|
||||
projectRoot: tempDir.path,
|
||||
systemName: 'ubuntu',
|
||||
);
|
||||
|
||||
final result = await module.probe(probe);
|
||||
expect(result.status, equals(ModuleProbeStatus.ok));
|
||||
final taskIds = result.tasks.map((t) => t.id).toList();
|
||||
expect(taskIds, contains('detected_maven_package'));
|
||||
expect(taskIds, contains('detected_maven_compile'));
|
||||
expect(taskIds, contains('detected_maven_test'));
|
||||
expect(taskIds, contains('detected_maven_clean'));
|
||||
|
||||
// Verifies ./mvnw was used because wrapper exists
|
||||
final pkgTask = result.tasks.firstWhere((t) => t.id == 'detected_maven_package');
|
||||
expect(pkgTask.command, equals('./mvnw package'));
|
||||
});
|
||||
});
|
||||
|
||||
group('ToolchainService Extended Tests', () {
|
||||
test('Supported tools contain java, maven, lua, perl, php', () {
|
||||
expect(ToolchainService.supportedTools.containsKey('java'), isTrue);
|
||||
expect(ToolchainService.supportedTools.containsKey('maven'), isTrue);
|
||||
expect(ToolchainService.supportedTools.containsKey('mvn'), isTrue);
|
||||
expect(ToolchainService.supportedTools.containsKey('lua'), isTrue);
|
||||
expect(ToolchainService.supportedTools.containsKey('perl'), isTrue);
|
||||
expect(ToolchainService.supportedTools.containsKey('php'), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('LspLanguageConfig Presets Extended Tests', () {
|
||||
test('Builtin presets contain Java, TypeScript, Lua', () {
|
||||
final javaPreset = LspLanguageConfig.findBuiltinByExtension('.java');
|
||||
expect(javaPreset, isNotNull);
|
||||
expect(javaPreset!.id, equals('java'));
|
||||
|
||||
final tsPreset = LspLanguageConfig.findBuiltinByExtension('.ts');
|
||||
expect(tsPreset, isNotNull);
|
||||
expect(tsPreset!.id, equals('typescript'));
|
||||
|
||||
final luaPreset = LspLanguageConfig.findBuiltinByExtension('.lua');
|
||||
expect(luaPreset, isNotNull);
|
||||
expect(luaPreset!.id, equals('lua'));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
group('Localization Coverage Tests', () {
|
||||
testWidgets('Localized descriptions exist for all new tasks in zh and en without throwing', (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 newTaskIds = [
|
||||
'detected_single_java',
|
||||
'detected_single_ts',
|
||||
'detected_single_lua',
|
||||
'detected_single_perl',
|
||||
'detected_single_php',
|
||||
'detected_python_pip_install',
|
||||
'detected_python_run_main',
|
||||
'detected_python_pytest',
|
||||
'detected_maven_package',
|
||||
'detected_maven_compile',
|
||||
'detected_maven_test',
|
||||
'detected_maven_clean',
|
||||
];
|
||||
|
||||
for (final id in newTaskIds) {
|
||||
final task = RunTask(
|
||||
id: id,
|
||||
name: id,
|
||||
command: 'echo 1',
|
||||
source: TaskSource.detected,
|
||||
);
|
||||
final descZh = task.getLocalizedDescription(l10nZh);
|
||||
final descEn = task.getLocalizedDescription(l10nEn);
|
||||
|
||||
expect(descZh.isNotEmpty, isTrue, reason: '$id zh description should not be empty');
|
||||
expect(descEn.isNotEmpty, isTrue, reason: '$id en description should not be empty');
|
||||
expect(descZh != descEn, isTrue, reason: '$id zh and en descriptions should be distinct');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'package:code_editor/services/code_completion/fuzzy_matcher.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
group('FuzzyMatcher Tests', () {
|
||||
test('Exact match gives highest score', () {
|
||||
final res = FuzzyMatcher.match('print', 'print');
|
||||
expect(res.isMatch, isTrue);
|
||||
expect(res.score, greaterThanOrEqualTo(2000));
|
||||
});
|
||||
|
||||
test('Case-sensitive prefix match', () {
|
||||
final res = FuzzyMatcher.match('pri', 'print');
|
||||
expect(res.isMatch, isTrue);
|
||||
expect(res.score, greaterThanOrEqualTo(1500));
|
||||
});
|
||||
|
||||
test('Case-insensitive prefix match', () {
|
||||
final res = FuzzyMatcher.match('pri', 'PrintStream');
|
||||
expect(res.isMatch, isTrue);
|
||||
expect(res.score, greaterThanOrEqualTo(1000));
|
||||
});
|
||||
|
||||
test('CamelCase match (e.g. fb -> FloatingActionButton)', () {
|
||||
final res = FuzzyMatcher.match('fab', 'FloatingActionButton');
|
||||
expect(res.isMatch, isTrue);
|
||||
expect(res.score, greaterThanOrEqualTo(500));
|
||||
expect(res.matchedIndices, equals([0, 8, 14]));
|
||||
});
|
||||
|
||||
test('Snake_case match (e.g. tf -> text_field)', () {
|
||||
final res = FuzzyMatcher.match('tf', 'text_field');
|
||||
expect(res.isMatch, isTrue);
|
||||
expect(res.score, greaterThanOrEqualTo(500));
|
||||
expect(res.matchedIndices, equals([0, 5]));
|
||||
});
|
||||
|
||||
test('Subsequence match', () {
|
||||
final res = FuzzyMatcher.match('pnt', 'print');
|
||||
expect(res.isMatch, isTrue);
|
||||
expect(res.score, greaterThan(400));
|
||||
});
|
||||
|
||||
test('Typo tolerance / error correction (e.g. prnt -> print)', () {
|
||||
final res = FuzzyMatcher.match('prnt', 'print');
|
||||
expect(res.isMatch, isTrue);
|
||||
});
|
||||
|
||||
test('Typo tolerance with 1 char mistake (e.g. prib -> print)', () {
|
||||
final res = FuzzyMatcher.match('prib', 'print');
|
||||
expect(res.isMatch, isTrue);
|
||||
expect(res.score, greaterThan(100));
|
||||
});
|
||||
|
||||
test('Typo tolerance for length mistake (e.g. lenght -> length)', () {
|
||||
final res = FuzzyMatcher.match('lenght', 'length');
|
||||
expect(res.isMatch, isTrue);
|
||||
expect(res.score, greaterThan(100));
|
||||
});
|
||||
|
||||
test('Completely unrelated word does not match', () {
|
||||
final res = FuzzyMatcher.match('xyz', 'print');
|
||||
expect(res.isMatch, isFalse);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:code_editor/l10n/app_localizations.dart';
|
||||
import 'package:code_editor/models/lsp_language_config.dart';
|
||||
import 'package:code_editor/services/internal_engine_service.dart';
|
||||
import 'package:code_editor/services/lsp_config_service.dart';
|
||||
import 'package:code_editor/views/code_completion_management_view.dart';
|
||||
@@ -57,20 +58,18 @@ void main() {
|
||||
}
|
||||
|
||||
group('LspConfigService Tests', () {
|
||||
test('Initial load creates default presets and writes to disk', () async {
|
||||
test('Initial load returns empty list and writes empty json to disk', () async {
|
||||
final configs = await lspConfigService.loadConfigs(forceReload: true);
|
||||
expect(configs.isNotEmpty, isTrue);
|
||||
expect(configs.any((c) => c.id == 'c_cpp'), isTrue);
|
||||
expect(configs.any((c) => c.id == 'rust'), isTrue);
|
||||
expect(configs.isEmpty, isTrue);
|
||||
|
||||
final file = await lspConfigService.getConfigFile();
|
||||
expect(file.existsSync(), isTrue);
|
||||
|
||||
final content = jsonDecode(file.readAsStringSync()) as List;
|
||||
expect(content.length, equals(configs.length));
|
||||
expect(content.isEmpty, isTrue);
|
||||
});
|
||||
|
||||
test('Incremental merge appends missing default presets without overwriting user configs', () async {
|
||||
test('Loads pre-existing custom configs from disk without auto-injecting uninstalled presets', () async {
|
||||
final file = await lspConfigService.getConfigFile();
|
||||
// Write only custom Python config
|
||||
const customConfig = [
|
||||
@@ -81,61 +80,99 @@ void main() {
|
||||
'fileExtensions': ['.py', '.pyw'],
|
||||
'serverCommand': 'my_pylsp',
|
||||
'serverArgs': ['--verbose'],
|
||||
'apkPackage': 'py3-lsp-server',
|
||||
'package': 'python3-pylsp',
|
||||
'enabled': true,
|
||||
}
|
||||
];
|
||||
file.writeAsStringSync(jsonEncode(customConfig));
|
||||
|
||||
final configs = await lspConfigService.loadConfigs(forceReload: true);
|
||||
// User's custom python must be preserved
|
||||
final pyConfig = configs.firstWhere((c) => c.id == 'python');
|
||||
expect(configs.length, equals(1));
|
||||
final pyConfig = configs.first;
|
||||
expect(pyConfig.id, equals('python'));
|
||||
expect(pyConfig.name, equals('My Custom Python'));
|
||||
expect(pyConfig.serverCommand, equals('my_pylsp'));
|
||||
|
||||
// Missing presets like c_cpp, rust must be incrementally added
|
||||
expect(configs.any((c) => c.id == 'c_cpp'), isTrue);
|
||||
expect(configs.any((c) => c.id == 'rust'), isTrue);
|
||||
expect(configs.any((c) => c.id == 'go'), isTrue);
|
||||
// Missing presets like c_cpp, rust are NOT automatically added to installed list
|
||||
expect(configs.any((c) => c.id == 'c_cpp'), isFalse);
|
||||
expect(configs.any((c) => c.id == 'rust'), isFalse);
|
||||
expect(configs.any((c) => c.id == 'go'), isFalse);
|
||||
});
|
||||
|
||||
test('findByExtension resolves language config correctly', () async {
|
||||
test('LspLanguageConfig.findBuiltinByExtension resolves builtin templates correctly', () {
|
||||
final cPreset = LspLanguageConfig.findBuiltinByExtension('.c');
|
||||
expect(cPreset, isNotNull);
|
||||
expect(cPreset!.id, equals('c_cpp'));
|
||||
|
||||
final cppPreset = LspLanguageConfig.findBuiltinByExtension('cpp');
|
||||
expect(cppPreset, isNotNull);
|
||||
expect(cppPreset!.id, equals('c_cpp'));
|
||||
|
||||
final pyPreset = LspLanguageConfig.findBuiltinByExtension('.py');
|
||||
expect(pyPreset, isNotNull);
|
||||
expect(pyPreset!.id, equals('python'));
|
||||
|
||||
final unknown = LspLanguageConfig.findBuiltinByExtension('.unknown');
|
||||
expect(unknown, isNull);
|
||||
});
|
||||
|
||||
test('LspConfigService.findByExtension only returns installed and enabled configs', () async {
|
||||
await lspConfigService.loadConfigs(forceReload: true);
|
||||
|
||||
final cConfig = lspConfigService.findByExtension('.c');
|
||||
expect(cConfig, isNotNull);
|
||||
expect(cConfig!.id, equals('c_cpp'));
|
||||
// When no configs are installed, findByExtension must return null (not builtin preset)
|
||||
expect(lspConfigService.findByExtension('.cpp'), isNull);
|
||||
expect(lspConfigService.findByExtension('cpp'), isNull);
|
||||
expect(lspConfigService.findByExtension('.py'), isNull);
|
||||
|
||||
final cppConfig = lspConfigService.findByExtension('cpp');
|
||||
expect(cppConfig, isNotNull);
|
||||
expect(cppConfig!.id, equals('c_cpp'));
|
||||
// Install C/C++ config
|
||||
const sample = LspLanguageConfig(
|
||||
id: 'c_cpp',
|
||||
name: 'C / C++',
|
||||
languageId: 'cpp',
|
||||
fileExtensions: ['.c', '.cpp', '.h'],
|
||||
serverCommand: 'clangd',
|
||||
package: 'clangd',
|
||||
);
|
||||
await lspConfigService.updateConfig(sample);
|
||||
|
||||
final pyConfig = lspConfigService.findByExtension('.py');
|
||||
expect(pyConfig, isNotNull);
|
||||
expect(pyConfig!.id, equals('python'));
|
||||
// Now it should resolve
|
||||
expect(lspConfigService.findByExtension('.cpp'), isNotNull);
|
||||
expect(lspConfigService.findByExtension('cpp')!.id, equals('c_cpp'));
|
||||
|
||||
final unknown = lspConfigService.findByExtension('.unknown');
|
||||
expect(unknown, isNull);
|
||||
// If disabled, it should return null
|
||||
final disabledSample = sample.copyWith(enabled: false);
|
||||
await lspConfigService.updateConfig(disabledSample);
|
||||
expect(lspConfigService.findByExtension('.cpp'), isNull);
|
||||
});
|
||||
|
||||
test('updateConfig, deleteConfig and resetToDefaults work and persist to disk', () async {
|
||||
await lspConfigService.loadConfigs(forceReload: true);
|
||||
|
||||
// 1. Update config
|
||||
final originalC = lspConfigService.configs.firstWhere((c) => c.id == 'c_cpp');
|
||||
final modifiedC = originalC.copyWith(serverCommand: 'clangd-18');
|
||||
await lspConfigService.updateConfig(modifiedC);
|
||||
// 1. Add / Update config
|
||||
const sample = LspLanguageConfig(
|
||||
id: 'c_cpp',
|
||||
name: 'C / C++',
|
||||
languageId: 'cpp',
|
||||
fileExtensions: ['.c', '.cpp', '.h'],
|
||||
serverCommand: 'clangd',
|
||||
package: 'clangd',
|
||||
);
|
||||
await lspConfigService.updateConfig(sample);
|
||||
expect(lspConfigService.configs.any((c) => c.id == 'c_cpp'), isTrue);
|
||||
|
||||
final modifiedC = sample.copyWith(serverCommand: 'clangd-18');
|
||||
await lspConfigService.updateConfig(modifiedC);
|
||||
expect(lspConfigService.configs.firstWhere((c) => c.id == 'c_cpp').serverCommand, equals('clangd-18'));
|
||||
|
||||
// 2. Delete config
|
||||
await lspConfigService.deleteConfig('shell');
|
||||
expect(lspConfigService.configs.any((c) => c.id == 'shell'), isFalse);
|
||||
await lspConfigService.deleteConfig('c_cpp');
|
||||
expect(lspConfigService.configs.any((c) => c.id == 'c_cpp'), isFalse);
|
||||
|
||||
// 3. Reset to defaults
|
||||
// 3. Reset to defaults (clears configs)
|
||||
await lspConfigService.updateConfig(sample);
|
||||
expect(lspConfigService.configs.isNotEmpty, isTrue);
|
||||
await lspConfigService.resetToDefaults();
|
||||
expect(lspConfigService.configs.any((c) => c.id == 'shell'), isTrue);
|
||||
expect(lspConfigService.configs.firstWhere((c) => c.id == 'c_cpp').serverCommand, equals('clangd'));
|
||||
expect(lspConfigService.configs.isEmpty, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -158,7 +195,7 @@ void main() {
|
||||
});
|
||||
|
||||
group('CodeCompletionManagementView & LspLanguageEditDialog Widget Tests', () {
|
||||
testWidgets('Management view renders all language items and engine card in Chinese', (tester) async {
|
||||
testWidgets('Management view renders empty placeholder when no language is installed', (tester) async {
|
||||
await lspConfigService.loadConfigs(forceReload: true);
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
@@ -168,11 +205,39 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('代码补全管理'), findsOneWidget);
|
||||
expect(find.text('内部代码智能引擎 (Alpine)'), findsOneWidget);
|
||||
expect(find.text('引擎未启动'), findsOneWidget);
|
||||
expect(find.text('暂无已安装的代码智能组件'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Management view renders installed language items in Chinese', (tester) async {
|
||||
await lspConfigService.loadConfigs(forceReload: true);
|
||||
await lspConfigService.updateConfig(const LspLanguageConfig(
|
||||
id: 'c_cpp',
|
||||
name: 'C / C++',
|
||||
languageId: 'cpp',
|
||||
fileExtensions: ['.c', '.cpp', '.h'],
|
||||
serverCommand: 'clangd',
|
||||
package: 'clangd',
|
||||
));
|
||||
await lspConfigService.updateConfig(const LspLanguageConfig(
|
||||
id: 'python',
|
||||
name: 'Python',
|
||||
languageId: 'python',
|
||||
fileExtensions: ['.py'],
|
||||
serverCommand: 'pylsp',
|
||||
package: 'python3-pylsp',
|
||||
));
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const CodeCompletionManagementView(),
|
||||
locale: const Locale('zh'),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('代码补全管理'), findsOneWidget);
|
||||
expect(find.text('引擎未启动'), findsOneWidget);
|
||||
expect(find.text('C / C++'), findsOneWidget);
|
||||
expect(find.text('Python'), findsOneWidget);
|
||||
expect(find.text('Rust'), findsOneWidget);
|
||||
expect(find.text('Go'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Management view renders without hardcoded text in English', (tester) async {
|
||||
@@ -185,13 +250,21 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Code Completion Management'), findsOneWidget);
|
||||
expect(find.text('Internal Code Intelligence Engine (Alpine)'), findsOneWidget);
|
||||
expect(find.byTooltip('Reset to Defaults'), findsOneWidget);
|
||||
expect(find.text('Engine Not Started'), findsOneWidget);
|
||||
expect(find.byTooltip('Add Language Configuration'), findsOneWidget);
|
||||
expect(find.text('No code intelligence components installed'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Edit button pops LspLanguageEditDialog and saves modifications', (tester) async {
|
||||
await lspConfigService.loadConfigs(forceReload: true);
|
||||
await lspConfigService.updateConfig(const LspLanguageConfig(
|
||||
id: 'c_cpp',
|
||||
name: 'C / C++',
|
||||
languageId: 'cpp',
|
||||
fileExtensions: ['.c', '.cpp', '.h'],
|
||||
serverCommand: 'clangd',
|
||||
package: 'clangd',
|
||||
));
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const CodeCompletionManagementView(),
|
||||
@@ -199,9 +272,13 @@ void main() {
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Tap first edit icon
|
||||
// Click C / C++ card to expand it
|
||||
await tester.tap(find.text('C / C++'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Tap edit button in the expanded menu
|
||||
final editButtons = find.byIcon(Icons.edit_outlined);
|
||||
expect(editButtons, findsWidgets);
|
||||
expect(editButtons, findsOneWidget);
|
||||
|
||||
await tester.tap(editButtons.first);
|
||||
await tester.pumpAndSettle();
|
||||
@@ -228,6 +305,14 @@ void main() {
|
||||
|
||||
testWidgets('Delete button prompts confirmation and removes language', (tester) async {
|
||||
await lspConfigService.loadConfigs(forceReload: true);
|
||||
await lspConfigService.updateConfig(const LspLanguageConfig(
|
||||
id: 'python',
|
||||
name: 'Python',
|
||||
languageId: 'python',
|
||||
fileExtensions: ['.py'],
|
||||
serverCommand: 'pylsp',
|
||||
package: 'python3-pylsp',
|
||||
));
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const CodeCompletionManagementView(),
|
||||
@@ -237,16 +322,20 @@ void main() {
|
||||
|
||||
expect(find.text('Python'), findsOneWidget);
|
||||
|
||||
// Find delete button for Python (index 1)
|
||||
// Click Python card to expand it
|
||||
await tester.tap(find.text('Python'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Find delete button in the expanded Python card
|
||||
final deleteButtons = find.byIcon(Icons.delete_outline);
|
||||
await tester.tap(deleteButtons.at(1));
|
||||
await tester.tap(deleteButtons.first);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('删除语言配置'), findsOneWidget);
|
||||
expect(find.text('确定要删除 Python 的代码补全配置吗?'), findsOneWidget);
|
||||
|
||||
// Confirm delete
|
||||
await tester.tap(find.text('删除'));
|
||||
// Confirm delete in dialog
|
||||
await tester.tap(find.widgetWithText(FilledButton, '删除'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Python should now be gone
|
||||
@@ -256,5 +345,21 @@ void main() {
|
||||
// Settle SnackBar timer
|
||||
await tester.pump(const Duration(seconds: 4));
|
||||
});
|
||||
|
||||
testWidgets('CodeCompletionManagementView renders without overflow on narrow device (320px width)', (tester) async {
|
||||
await lspConfigService.loadConfigs(forceReload: true);
|
||||
tester.view.physicalSize = const Size(320 * 2.0, 640 * 2.0);
|
||||
tester.view.devicePixelRatio = 2.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
|
||||
await tester.pumpWidget(buildTestWidget(
|
||||
child: const CodeCompletionManagementView(),
|
||||
locale: const Locale('en'),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(tester.takeException(), isNull, reason: 'Narrow layout in English should not have any RenderFlex overflow');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
import 'package:code_editor/services/lsp/lsp_diagnostics_store.dart';
|
||||
import 'package:code_editor/services/lsp/lsp_protocol.dart';
|
||||
import 'package:code_editor/services/lsp/lsp_workspace_edit_applier.dart';
|
||||
import 'package:code_editor/widgets/editor/editor_lsp_coordinator.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
void main() {
|
||||
group('LSP 协议与数据模型测试', () {
|
||||
test('LspPosition 与 LspRange 范围包含与行交集判断', () {
|
||||
const pos1 = LspPosition(line: 2, character: 4);
|
||||
const pos2 = LspPosition(line: 2, character: 10);
|
||||
const range = LspRange(start: pos1, end: pos2);
|
||||
|
||||
expect(range.contains(2, 4), isTrue);
|
||||
expect(range.contains(2, 7), isTrue);
|
||||
expect(range.contains(2, 10), isTrue);
|
||||
expect(range.contains(2, 3), isFalse);
|
||||
expect(range.contains(2, 11), isFalse);
|
||||
expect(range.contains(1, 4), isFalse);
|
||||
expect(range.contains(3, 4), isFalse);
|
||||
|
||||
expect(range.overlapsLine(2), isTrue);
|
||||
expect(range.overlapsLine(1), isFalse);
|
||||
expect(range.overlapsLine(3), isFalse);
|
||||
|
||||
const multiLineRange = LspRange(
|
||||
start: LspPosition(line: 1, character: 5),
|
||||
end: LspPosition(line: 3, character: 2),
|
||||
);
|
||||
expect(multiLineRange.overlapsLine(1), isTrue);
|
||||
expect(multiLineRange.overlapsLine(2), isTrue);
|
||||
expect(multiLineRange.overlapsLine(3), isTrue);
|
||||
expect(multiLineRange.overlapsLine(0), isFalse);
|
||||
expect(multiLineRange.overlapsLine(4), isFalse);
|
||||
});
|
||||
|
||||
test('LspDiagnostic 序列化与严重等级解析', () {
|
||||
final json = {
|
||||
'range': {
|
||||
'start': {'line': 5, 'character': 2},
|
||||
'end': {'line': 5, 'character': 8},
|
||||
},
|
||||
'severity': 1,
|
||||
'message': "Use of undeclared identifier 'foo'",
|
||||
'source': 'clangd',
|
||||
};
|
||||
|
||||
final diag = LspDiagnostic.fromJson(json);
|
||||
expect(diag.isError, isTrue);
|
||||
expect(diag.isWarning, isFalse);
|
||||
expect(diag.message, "Use of undeclared identifier 'foo'");
|
||||
expect(diag.source, 'clangd');
|
||||
expect(diag.range.start.line, 5);
|
||||
expect(diag.range.start.character, 2);
|
||||
});
|
||||
|
||||
test('LspCompletionItem 解析与文本插入兼容', () {
|
||||
final json = {
|
||||
'label': 'printf',
|
||||
'kind': 3, // Function
|
||||
'detail': 'int printf(const char *format, ...)',
|
||||
'documentation': 'Formatted output conversion.',
|
||||
'insertText': 'printf',
|
||||
};
|
||||
|
||||
final item = LspCompletionItem.fromJson(json);
|
||||
expect(item.label, 'printf');
|
||||
expect(item.effectiveInsertText, 'printf');
|
||||
expect(item.detail, contains('int printf'));
|
||||
expect(item.documentation, contains('Formatted output'));
|
||||
});
|
||||
|
||||
test('LspCodeAction 与 LspWorkspaceEdit 解析', () {
|
||||
final json = {
|
||||
'title': "Include <stdio.h>",
|
||||
'kind': 'quickfix',
|
||||
'isPreferred': true,
|
||||
'edit': {
|
||||
'changes': {
|
||||
'file:///workspace/main.c': [
|
||||
{
|
||||
'range': {
|
||||
'start': {'line': 0, 'character': 0},
|
||||
'end': {'line': 0, 'character': 0},
|
||||
},
|
||||
'newText': '#include <stdio.h>\n',
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
final action = LspCodeAction.fromJson(json);
|
||||
expect(action.title, 'Include <stdio.h>');
|
||||
expect(action.isPreferred, isTrue);
|
||||
expect(action.edit, isNotNull);
|
||||
expect(action.edit!.changes.containsKey('file:///workspace/main.c'), isTrue);
|
||||
expect(action.edit!.changes['file:///workspace/main.c']!.first.newText, '#include <stdio.h>\n');
|
||||
});
|
||||
});
|
||||
|
||||
group('LspDiagnosticsStore 存储与路径统一测试', () {
|
||||
final store = LspDiagnosticsStore.instance;
|
||||
|
||||
setUp(() {
|
||||
store.clear();
|
||||
});
|
||||
|
||||
test('多文件诊断隔离与跨平台路径匹配', () {
|
||||
const diag1 = LspDiagnostic(
|
||||
range: LspRange(
|
||||
start: LspPosition(line: 0, character: 0),
|
||||
end: LspPosition(line: 0, character: 5),
|
||||
),
|
||||
severity: LspDiagnosticSeverity.error,
|
||||
message: 'Syntax error',
|
||||
);
|
||||
|
||||
store.updateDiagnostics('D:/Project/src/main.c', [diag1]);
|
||||
|
||||
// 各种变体路径均能精确匹配
|
||||
expect(store.getDiagnosticsForFile('d:/Project/src/main.c'), hasLength(1));
|
||||
expect(store.getDiagnosticsForFile('file:///D:/Project/src/main.c'), hasLength(1));
|
||||
expect(store.getDiagnosticsForFile(r'D:\Project\src\main.c'), hasLength(1));
|
||||
expect(store.getDiagnosticsForFile('D:/Project/src/other.c'), isEmpty);
|
||||
|
||||
final line0Diags = store.getDiagnosticsForLine('D:/Project/src/main.c', 0);
|
||||
expect(line0Diags, hasLength(1));
|
||||
expect(line0Diags.first.message, 'Syntax error');
|
||||
|
||||
final line1Diags = store.getDiagnosticsForLine('D:/Project/src/main.c', 1);
|
||||
expect(line1Diags, isEmpty);
|
||||
});
|
||||
|
||||
test('getDiagnosticAt 精准定位与就近容错', () {
|
||||
const diag = LspDiagnostic(
|
||||
range: LspRange(
|
||||
start: LspPosition(line: 3, character: 5),
|
||||
end: LspPosition(line: 3, character: 10),
|
||||
),
|
||||
severity: LspDiagnosticSeverity.warning,
|
||||
message: 'Unused variable',
|
||||
);
|
||||
|
||||
store.updateDiagnostics('/workspace/test.c', [diag]);
|
||||
|
||||
// 精准命中区间 [5, 10]
|
||||
expect(store.getDiagnosticAt('/workspace/test.c', 3, 6)?.message, 'Unused variable');
|
||||
// 同行就近返回
|
||||
expect(store.getDiagnosticAt('/workspace/test.c', 3, 2)?.message, 'Unused variable');
|
||||
// 不同行返回 null
|
||||
expect(store.getDiagnosticAt('/workspace/test.c', 4, 6), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
group('LspWorkspaceEditApplier 逆向安全应用测试', () {
|
||||
test('单行局部替换', () {
|
||||
final controller = CodeLineEditingController.fromText(
|
||||
'int main() {\n int val = foo();\n return 0;\n}',
|
||||
);
|
||||
|
||||
final edit = LspWorkspaceEdit(
|
||||
changes: {
|
||||
'file:///src/main.c': [
|
||||
const LspTextEdit(
|
||||
range: LspRange(
|
||||
start: LspPosition(line: 1, character: 12),
|
||||
end: LspPosition(line: 1, character: 15),
|
||||
),
|
||||
newText: 'bar',
|
||||
),
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
LspWorkspaceEditApplier.applyWorkspaceEdit(controller, edit, currentFilePath: '/src/main.c');
|
||||
expect(controller.codeLines[1].text, ' int val = bar();');
|
||||
});
|
||||
|
||||
test('同一行多处编辑自动逆序应用,不破坏列号偏移', () {
|
||||
final controller = CodeLineEditingController.fromText(
|
||||
'AAA BBB CCC',
|
||||
);
|
||||
|
||||
// 顺序为正向传入:先改 AAA 为 12345,再改 CCC 为 9
|
||||
final edits = [
|
||||
const LspTextEdit(
|
||||
range: LspRange(
|
||||
start: LspPosition(line: 0, character: 0),
|
||||
end: LspPosition(line: 0, character: 3),
|
||||
),
|
||||
newText: '12345',
|
||||
),
|
||||
const LspTextEdit(
|
||||
range: LspRange(
|
||||
start: LspPosition(line: 0, character: 8),
|
||||
end: LspPosition(line: 0, character: 11),
|
||||
),
|
||||
newText: '9',
|
||||
),
|
||||
];
|
||||
|
||||
LspWorkspaceEditApplier.applyTextEdits(controller, edits);
|
||||
// CCC 变成了 9,AAA 变成了 12345,中间 BBB 完整无损
|
||||
expect(controller.codeLines[0].text, '12345 BBB 9');
|
||||
});
|
||||
|
||||
test('跨行插入与头部插入', () {
|
||||
final controller = CodeLineEditingController.fromText(
|
||||
'int x = 1;\nint y = 2;',
|
||||
);
|
||||
|
||||
final edit = LspWorkspaceEdit(
|
||||
changes: {
|
||||
'file:///test.c': [
|
||||
const LspTextEdit(
|
||||
range: LspRange(
|
||||
start: LspPosition(line: 0, character: 0),
|
||||
end: LspPosition(line: 0, character: 0),
|
||||
),
|
||||
newText: '// header\n',
|
||||
),
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
LspWorkspaceEditApplier.applyWorkspaceEdit(controller, edit, currentFilePath: 'test.c');
|
||||
expect(controller.codeLines[0].text, '// header');
|
||||
expect(controller.codeLines[1].text, 'int x = 1;');
|
||||
expect(controller.codeLines[2].text, 'int y = 2;');
|
||||
});
|
||||
});
|
||||
|
||||
group('CodeLineSpanBuilder 波浪下划线扩展测试', () {
|
||||
testWidgets('控制器支持注入 spanBuilder 并不破坏基础文本', (tester) async {
|
||||
late BuildContext testContext;
|
||||
await tester.pumpWidget(
|
||||
Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: Builder(
|
||||
builder: (ctx) {
|
||||
testContext = ctx;
|
||||
return const SizedBox();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
bool spanBuilderCalled = false;
|
||||
final controller = CodeLineEditingController.fromText(
|
||||
'int a = 10;\nfloat b = 20.0;',
|
||||
const CodeLineOptions(),
|
||||
({
|
||||
required BuildContext context,
|
||||
required int index,
|
||||
required CodeLine codeLine,
|
||||
required TextSpan textSpan,
|
||||
required TextStyle style,
|
||||
}) {
|
||||
spanBuilderCalled = true;
|
||||
return TextSpan(
|
||||
text: codeLine.text,
|
||||
style: style.copyWith(
|
||||
decoration: TextDecoration.underline,
|
||||
decorationStyle: TextDecorationStyle.wavy,
|
||||
decorationColor: Colors.redAccent,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
expect(controller.codeLines.length, 2);
|
||||
expect(controller.codeLines[0].text, 'int a = 10;');
|
||||
expect(controller.codeLines[1].text, 'float b = 20.0;');
|
||||
|
||||
final span = controller.buildTextSpan(
|
||||
context: testContext,
|
||||
index: 0,
|
||||
textSpan: const TextSpan(text: 'int a = 10;'),
|
||||
style: const TextStyle(),
|
||||
);
|
||||
expect(spanBuilderCalled, isTrue);
|
||||
expect(span.style?.decoration, equals(TextDecoration.underline));
|
||||
});
|
||||
});
|
||||
|
||||
group('EditorLspCoordinator 纯 LSP 协调与诊断生命周期测试', () {
|
||||
test('无 LSP 服务时打开或修改文件绝不注入任何本地伪诊断', () {
|
||||
const coordinator = EditorLspCoordinator();
|
||||
const testPath = '/test/unsupported/main.fake';
|
||||
final codeLines = CodeLines.fromText('int a = 10\nprintf("ok");');
|
||||
|
||||
// 确保初始状态干净
|
||||
LspDiagnosticsStore.instance.removeForFile(testPath);
|
||||
expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isEmpty);
|
||||
|
||||
// 打开文件
|
||||
coordinator.onFileOpened(testPath, 'int a = 10\nprintf("ok");', codeLines);
|
||||
expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isEmpty);
|
||||
|
||||
// 修改文件
|
||||
coordinator.onFileChanged(testPath, 'int a = 10', codeLines);
|
||||
expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isEmpty);
|
||||
});
|
||||
|
||||
test('文件关闭时自动清理该文件的 LSP 诊断', () {
|
||||
const coordinator = EditorLspCoordinator();
|
||||
const testPath = '/test/project/main.c';
|
||||
|
||||
// 模拟 LSP 写入了诊断
|
||||
LspDiagnosticsStore.instance.updateDiagnostics(testPath, const [
|
||||
LspDiagnostic(
|
||||
range: LspRange(
|
||||
start: LspPosition(line: 0, character: 0),
|
||||
end: LspPosition(line: 0, character: 5),
|
||||
),
|
||||
message: 'LSP compile error',
|
||||
),
|
||||
]);
|
||||
expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isNotEmpty);
|
||||
|
||||
// 关闭文件
|
||||
coordinator.onFileClosed(testPath);
|
||||
expect(LspDiagnosticsStore.instance.getDiagnosticsForFile(testPath), isEmpty);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:code_editor/services/lsp/lsp_manager.dart';
|
||||
import 'package:code_editor/views/main_view.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('LSP Lifecycle & Uninstall Tests', () {
|
||||
test('LspManager.stopSession handles nonexistent session gracefully', () async {
|
||||
final manager = LspManager.instance;
|
||||
// 停止一个未启动的 session 不抛出异常
|
||||
await expectLater(manager.stopSession('nonexistent_id'), completes);
|
||||
});
|
||||
|
||||
test('MainView.clearPromptedLanguage removes record and allows re-prompting', () {
|
||||
// 首次清除
|
||||
MainView.clearPromptedLanguage('c_cpp');
|
||||
MainView.clearPromptedLanguage(null);
|
||||
// 清空全部后不抛异常
|
||||
expect(() => MainView.clearPromptedLanguage(null), returnsNormally);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -301,6 +301,26 @@ void main() {
|
||||
final txtFile = File(p.join(projectA.path, 'notes.txt'))..writeAsStringSync('hi');
|
||||
provider.refreshSingleFileTask(currentFilePath: txtFile.path);
|
||||
expect(provider.taskTable.tasksOf(RunTaskType.singleFile), isEmpty);
|
||||
|
||||
// 上一次运行单文件任务时的联动测试:
|
||||
// 1. 在 cpp 文件设置单文件任务为 lastRunTask
|
||||
provider.refreshSingleFileTask(currentFilePath: cppFile.path);
|
||||
final cppTask = provider.taskTable.tasksOf(RunTaskType.singleFile).first;
|
||||
await provider.setLastRunTask(cppTask);
|
||||
expect(provider.lastRunTask?.id, 'detected_single_cpp');
|
||||
|
||||
// 2. 切换到 python 文件 -> lastRunTask 自动联动为当前 py 文件的任务
|
||||
provider.refreshSingleFileTask(currentFilePath: pyFile.path);
|
||||
expect(provider.lastRunTask?.id, 'detected_single_python');
|
||||
expect(provider.lastRunTask?.name, 'Python: main.py');
|
||||
|
||||
// 3. 切换到不可运行文件(txt)-> lastRunTask 安全置空,不误跑切走的文件
|
||||
provider.refreshSingleFileTask(currentFilePath: txtFile.path);
|
||||
expect(provider.lastRunTask, isNull);
|
||||
|
||||
// 4. 再切回 cpp 文件 -> 重新恢复为 cpp 单文件任务
|
||||
provider.refreshSingleFileTask(currentFilePath: cppFile.path);
|
||||
expect(provider.lastRunTask?.id, 'detected_single_cpp');
|
||||
});
|
||||
|
||||
test('未映射到内置类型的自定义模块:任务归入 other,不能丢', () async {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import 'dart:io';
|
||||
import 'package:code_editor/services/lsp/cpp_project_helper.dart';
|
||||
import 'package:code_editor/services/lsp/proot_path_mapper.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
group('PRootPathMapper Tests', () {
|
||||
test('toGuestUri maps subpath within workspaceRoot to file:///workspace/...', () {
|
||||
final guestUri = PRootPathMapper.toGuestUri(
|
||||
'/data/data/com.example/files/workspace/src/main.c',
|
||||
'/data/data/com.example/files/workspace',
|
||||
);
|
||||
expect(guestUri, equals('file:///workspace/src/main.c'));
|
||||
});
|
||||
|
||||
test('toGuestUri maps root directory itself to file:///workspace', () {
|
||||
final guestUri = PRootPathMapper.toGuestUri(
|
||||
'/data/data/com.example/files/workspace',
|
||||
'/data/data/com.example/files/workspace',
|
||||
);
|
||||
expect(guestUri, equals('file:///workspace'));
|
||||
});
|
||||
|
||||
test('toGuestUri leaves path outside workspaceRoot with file:/// scheme', () {
|
||||
final guestUri = PRootPathMapper.toGuestUri(
|
||||
'/system/etc/hosts',
|
||||
'/data/data/com.example/files/workspace',
|
||||
);
|
||||
expect(guestUri, equals('file:///system/etc/hosts'));
|
||||
});
|
||||
|
||||
test('fromGuestUriToHostPath restores guest URI to host absolute path', () {
|
||||
final hostPath = PRootPathMapper.fromGuestUriToHostPath(
|
||||
'file:///workspace/src/main.c',
|
||||
'/data/data/com.example/files/workspace',
|
||||
);
|
||||
expect(hostPath.replaceAll('\\', '/'), equals('/data/data/com.example/files/workspace/src/main.c'));
|
||||
});
|
||||
|
||||
test('fromGuestUriToHostPath restores root /workspace', () {
|
||||
final hostPath = PRootPathMapper.fromGuestUriToHostPath(
|
||||
'file:///workspace',
|
||||
'/data/data/com.example/files/workspace',
|
||||
);
|
||||
expect(hostPath.replaceAll('\\', '/'), equals('/data/data/com.example/files/workspace'));
|
||||
});
|
||||
|
||||
test('fromGuestUriToHostPath handles external file:/// URIs', () {
|
||||
final hostPath = PRootPathMapper.fromGuestUriToHostPath(
|
||||
'file:///system/etc/hosts',
|
||||
'/data/data/com.example/files/workspace',
|
||||
);
|
||||
expect(hostPath.replaceAll('\\', '/'), equals('/system/etc/hosts'));
|
||||
});
|
||||
|
||||
test('toGuestPath maps host workspace and subpath to container absolute path', () {
|
||||
final guestPath = PRootPathMapper.toGuestPath(
|
||||
'/data/data/com.example/files/workspace/src/main.c',
|
||||
'/data/data/com.example/files/workspace',
|
||||
);
|
||||
expect(guestPath, equals('/workspace/src/main.c'));
|
||||
|
||||
final guestRoot = PRootPathMapper.toGuestPath(
|
||||
'/data/data/com.example/files/workspace',
|
||||
'/data/data/com.example/files/workspace',
|
||||
);
|
||||
expect(guestRoot, equals('/workspace'));
|
||||
});
|
||||
});
|
||||
|
||||
group('CppProjectHelper Tests', () {
|
||||
late Directory tempProjectDir;
|
||||
|
||||
setUp(() {
|
||||
tempProjectDir = Directory.systemTemp.createTempSync('cpp_helper_test_');
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
if (tempProjectDir.existsSync()) {
|
||||
tempProjectDir.deleteSync(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
test('Do nothing if compile_commands.json already exists in root', () async {
|
||||
final existing = File(p.join(tempProjectDir.path, 'compile_commands.json'));
|
||||
existing.writeAsStringSync('[]');
|
||||
|
||||
await CppProjectHelper.ensureCompileFlags(tempProjectDir.path);
|
||||
|
||||
final flagsFile = File(p.join(tempProjectDir.path, 'compile_flags.txt'));
|
||||
expect(flagsFile.existsSync(), isFalse);
|
||||
});
|
||||
|
||||
test('Generates .clangd when build/compile_commands.json exists', () async {
|
||||
final buildDir = Directory(p.join(tempProjectDir.path, 'build'))..createSync();
|
||||
File(p.join(buildDir.path, 'compile_commands.json')).writeAsStringSync('[]');
|
||||
|
||||
await CppProjectHelper.ensureCompileFlags(tempProjectDir.path);
|
||||
|
||||
final clangdFile = File(p.join(tempProjectDir.path, '.clangd'));
|
||||
expect(clangdFile.existsSync(), isTrue);
|
||||
expect(clangdFile.readAsStringSync(), contains('CompilationDatabase: build'));
|
||||
});
|
||||
|
||||
test('Auto scans header directories and generates compile_flags.txt with -I and -std=c++17', () async {
|
||||
// Create include/, src/, and ggml/include/
|
||||
final incDir = Directory(p.join(tempProjectDir.path, 'include'))..createSync();
|
||||
final srcDir = Directory(p.join(tempProjectDir.path, 'src'))..createSync();
|
||||
final ggmlIncDir = Directory(p.join(tempProjectDir.path, 'ggml', 'include'))..createSync(recursive: true);
|
||||
|
||||
// Add dummy headers
|
||||
File(p.join(incDir.path, 'llama.h')).writeAsStringSync('#pragma once');
|
||||
File(p.join(srcDir.path, 'llama-impl.h')).writeAsStringSync('#pragma once');
|
||||
File(p.join(ggmlIncDir.path, 'ggml.h')).writeAsStringSync('#pragma once');
|
||||
|
||||
await CppProjectHelper.ensureCompileFlags(tempProjectDir.path);
|
||||
|
||||
final flagsFile = File(p.join(tempProjectDir.path, 'compile_flags.txt'));
|
||||
expect(flagsFile.existsSync(), isTrue);
|
||||
|
||||
final content = flagsFile.readAsStringSync();
|
||||
expect(content, contains('-Iinclude'));
|
||||
expect(content, contains('-Isrc'));
|
||||
expect(content, contains('-Iggml/include'));
|
||||
expect(content, contains('-xc++'));
|
||||
expect(content, contains('-std=c++17'));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import 'dart:io';
|
||||
import 'package:code_editor/services/distro_installer.dart';
|
||||
import 'package:code_editor/services/distro_manager.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late Directory tempBaseDir;
|
||||
late Directory tempRootDir;
|
||||
|
||||
setUp(() {
|
||||
tempBaseDir = Directory.systemTemp.createTempSync('proot_perl_fix_test_');
|
||||
tempRootDir = Directory(p.join(tempBaseDir.path, 'debian', 'rootfs'))..createSync(recursive: true);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
if (tempBaseDir.existsSync()) {
|
||||
tempBaseDir.deleteSync(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
group('PRoot Perl Fix Tests', () {
|
||||
test('ensureDpkgConfiguration creates /etc/dpkg/dpkg.cfg.d/01_proot with force-unsafe-io', () async {
|
||||
// 1. Initially without /etc/dpkg, should do nothing
|
||||
await DistroInstaller.ensureDpkgConfiguration(tempRootDir);
|
||||
expect(Directory(p.join(tempRootDir.path, 'etc', 'dpkg')).existsSync(), isFalse);
|
||||
|
||||
// 2. With /etc/dpkg present, should create 01_proot
|
||||
final dpkgDir = Directory(p.join(tempRootDir.path, 'etc', 'dpkg'))..createSync(recursive: true);
|
||||
await DistroInstaller.ensureDpkgConfiguration(tempRootDir);
|
||||
|
||||
final prootCfg = File(p.join(dpkgDir.path, 'dpkg.cfg.d', '01_proot'));
|
||||
expect(prootCfg.existsSync(), isTrue);
|
||||
expect(prootCfg.readAsStringSync(), equals('force-unsafe-io\n'));
|
||||
});
|
||||
|
||||
test('buildLaunchConfig places .l2s inside rootDir and migrates legacy .l2s', () async {
|
||||
// Setup legacy external .l2s directory
|
||||
final legacyL2sDir = Directory(p.join(tempBaseDir.path, 'debian', '.l2s'))..createSync(recursive: true);
|
||||
File(p.join(legacyL2sDir.path, 'meta_link_1')).writeAsStringSync('stand-in-content');
|
||||
|
||||
// Setup /bin/sh inside rootDir so targetShell resolves cleanly
|
||||
final binDir = Directory(p.join(tempRootDir.path, 'bin'))..createSync(recursive: true);
|
||||
File(p.join(binDir.path, 'sh')).writeAsStringSync('#!/bin/sh');
|
||||
|
||||
final launchConfig = await DistroManager().buildLaunchConfig(
|
||||
systemName: 'debian',
|
||||
customRootDir: tempRootDir,
|
||||
);
|
||||
|
||||
// Verify guest environment has PROOT_L2S_DIR=/.l2s
|
||||
expect(launchConfig.arguments, contains('PROOT_L2S_DIR=/.l2s'));
|
||||
|
||||
// Verify host environment PROOT_L2S_DIR points to rootDir/.l2s
|
||||
final targetL2sDir = Directory(p.join(tempRootDir.path, '.l2s'));
|
||||
expect(targetL2sDir.existsSync(), isTrue);
|
||||
expect(launchConfig.environment['PROOT_L2S_DIR'], equals(targetL2sDir.path));
|
||||
|
||||
// Verify legacy file was migrated
|
||||
final migratedFile = File(p.join(targetL2sDir.path, 'meta_link_1'));
|
||||
expect(migratedFile.existsSync(), isTrue);
|
||||
expect(migratedFile.readAsStringSync(), equals('stand-in-content'));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import 'package:code_editor/services/code_completion/smart_prompts_builder.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
|
||||
class _MockLspCompletionProvider implements CompletionProvider {
|
||||
final List<SmartPrompt> mockPrompts;
|
||||
_MockLspCompletionProvider(this.mockPrompts);
|
||||
|
||||
@override
|
||||
String get id => 'mock_lsp';
|
||||
|
||||
@override
|
||||
bool get isAsync => true;
|
||||
|
||||
@override
|
||||
Future<List<SmartPrompt>> provideCompletions(CompletionContext context) async {
|
||||
return mockPrompts;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('SmartCodeAutocompletePromptsBuilder LSP Tests', () {
|
||||
testWidgets('SmartCodeAutocompletePromptsBuilder requests LSP asynchronously and applies fuzzy filter', (tester) async {
|
||||
late BuildContext testContext;
|
||||
await tester.pumpWidget(
|
||||
Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: Builder(
|
||||
builder: (ctx) {
|
||||
testContext = ctx;
|
||||
return const SizedBox();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final provider = _MockLspCompletionProvider([
|
||||
SmartPrompt(word: 'print', kind: SmartPromptKind.function),
|
||||
SmartPrompt(word: 'printf', kind: SmartPromptKind.function, type: 'int printf(const char *format, ...)'),
|
||||
SmartPrompt(word: 'length', kind: SmartPromptKind.field),
|
||||
SmartPrompt(word: 'FloatingActionButton', kind: SmartPromptKind.type),
|
||||
]);
|
||||
|
||||
final builder = SmartCodeAutocompletePromptsBuilder(
|
||||
customProviders: [provider],
|
||||
);
|
||||
|
||||
// 1. Normal prefix 'pri'
|
||||
final res1Future = builder.build(
|
||||
testContext,
|
||||
const CodeLine('pri'),
|
||||
const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3),
|
||||
);
|
||||
expect(res1Future, isA<Future<CodeAutocompleteEditingValue?>>());
|
||||
final res1 = await (res1Future as Future<CodeAutocompleteEditingValue?>);
|
||||
expect(res1, isNotNull);
|
||||
expect(res1!.prompts.map((p) => p.word), containsAll(['print', 'printf']));
|
||||
|
||||
// 2. Typo correction: 'prnt' -> matches 'print'
|
||||
final res2 = await (builder.build(
|
||||
testContext,
|
||||
const CodeLine('prnt'),
|
||||
const CodeLineSelection(baseIndex: 0, baseOffset: 4, extentIndex: 0, extentOffset: 4),
|
||||
) as Future<CodeAutocompleteEditingValue?>);
|
||||
expect(res2, isNotNull);
|
||||
expect(res2!.prompts.map((p) => p.word), contains('print'));
|
||||
|
||||
// 3. Typo correction: 'lenght' -> matches 'length'
|
||||
final res3 = await (builder.build(
|
||||
testContext,
|
||||
const CodeLine('lenght'),
|
||||
const CodeLineSelection(baseIndex: 0, baseOffset: 6, extentIndex: 0, extentOffset: 6),
|
||||
) as Future<CodeAutocompleteEditingValue?>);
|
||||
expect(res3, isNotNull);
|
||||
expect(res3!.prompts.map((p) => p.word), contains('length'));
|
||||
|
||||
// 4. CamelCase: 'fab' -> matches 'FloatingActionButton'
|
||||
final res4 = await (builder.build(
|
||||
testContext,
|
||||
const CodeLine('fab'),
|
||||
const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3),
|
||||
) as Future<CodeAutocompleteEditingValue?>);
|
||||
expect(res4, isNotNull);
|
||||
expect(res4!.prompts.first.word, equals('FloatingActionButton'));
|
||||
});
|
||||
|
||||
testWidgets('字符串字面量内部不触发补全', (tester) async {
|
||||
late BuildContext testContext;
|
||||
await tester.pumpWidget(
|
||||
Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: Builder(
|
||||
builder: (ctx) {
|
||||
testContext = ctx;
|
||||
return const SizedBox();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final provider = _MockLspCompletionProvider([
|
||||
SmartPrompt(word: 'printf', kind: SmartPromptKind.function),
|
||||
]);
|
||||
|
||||
final builder = SmartCodeAutocompletePromptsBuilder(
|
||||
customProviders: [provider],
|
||||
);
|
||||
|
||||
// 光标处于 "hello pri" 内部
|
||||
final res = builder.build(
|
||||
testContext,
|
||||
const CodeLine('"hello pri"'),
|
||||
const CodeLineSelection(baseIndex: 0, baseOffset: 10, extentIndex: 0, extentOffset: 10),
|
||||
);
|
||||
expect(res, isNull);
|
||||
});
|
||||
|
||||
testWidgets('输入点 . 触发符能正确触发异步补全', (tester) async {
|
||||
late BuildContext testContext;
|
||||
await tester.pumpWidget(
|
||||
Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: Builder(
|
||||
builder: (ctx) {
|
||||
testContext = ctx;
|
||||
return const SizedBox();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final provider = _MockLspCompletionProvider([
|
||||
SmartPrompt(word: 'size', kind: SmartPromptKind.field),
|
||||
SmartPrompt(word: 'clear', kind: SmartPromptKind.function),
|
||||
]);
|
||||
|
||||
final builder = SmartCodeAutocompletePromptsBuilder(
|
||||
customProviders: [provider],
|
||||
);
|
||||
|
||||
final res = await (builder.build(
|
||||
testContext,
|
||||
const CodeLine('list.'),
|
||||
const CodeLineSelection(baseIndex: 0, baseOffset: 5, extentIndex: 0, extentOffset: 5),
|
||||
) as Future<CodeAutocompleteEditingValue?>);
|
||||
|
||||
expect(res, isNotNull);
|
||||
expect(res!.prompts.map((p) => p.word), containsAll(['size', 'clear']));
|
||||
});
|
||||
|
||||
testWidgets('当禁用 LSP 补全时直接返回 null 不打扰输入', (tester) async {
|
||||
late BuildContext testContext;
|
||||
await tester.pumpWidget(
|
||||
Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: Builder(
|
||||
builder: (ctx) {
|
||||
testContext = ctx;
|
||||
return const SizedBox();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final builder = SmartCodeAutocompletePromptsBuilder(
|
||||
enableLspCompletion: false,
|
||||
);
|
||||
|
||||
final res = builder.build(
|
||||
testContext,
|
||||
const CodeLine('pri'),
|
||||
const CodeLineSelection(baseIndex: 0, baseOffset: 3, extentIndex: 0, extentOffset: 3),
|
||||
);
|
||||
|
||||
// 未装配任何 provider,直接返回 null
|
||||
expect(res, isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
+2
-23
@@ -45,29 +45,8 @@ class FakeDistroProvider extends DistroProvider {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> deleteSystem(String systemName) async {
|
||||
_systems.remove(systemName);
|
||||
if (_selected == systemName) {
|
||||
_selected = _systems.isNotEmpty ? _systems.first : null;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> importBuiltinAlpine({
|
||||
required String systemName,
|
||||
dynamic onProgress,
|
||||
bool Function()? isCancelled,
|
||||
}) async {
|
||||
_systems.add(systemName);
|
||||
_selected = systemName;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> importFromCustomTarGz({
|
||||
required String systemName,
|
||||
required dynamic tarGzFile,
|
||||
Future<void> importBuiltinUbuntu({
|
||||
String systemName = 'ubuntu',
|
||||
dynamic onProgress,
|
||||
bool Function()? isCancelled,
|
||||
}) async {
|
||||
|
||||
@@ -94,14 +94,6 @@ void main() {
|
||||
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'));
|
||||
@@ -110,24 +102,10 @@ void main() {
|
||||
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);
|
||||
test('All toolchain resolutions map to Ubuntu apt-get command', () {
|
||||
final resolved = ToolchainService.resolveCommand('python3 app.py', DistroFamily.ubuntu);
|
||||
expect(resolved, contains('command -v python3'));
|
||||
expect(resolved, contains('dnf install -y python3 python3-pip'));
|
||||
expect(resolved, contains('apt-get install -y python3 python3-pip'));
|
||||
expect(resolved, endsWith('&& (python3 app.py)'));
|
||||
});
|
||||
|
||||
@@ -391,15 +369,13 @@ gcc main.c -o app
|
||||
}
|
||||
});
|
||||
|
||||
test('ToolchainRequirement getInstallCommand automatically adds dpkg self-healing for Ubuntu and Debian', () {
|
||||
test('ToolchainRequirement getInstallCommand automatically adds dpkg self-healing', () {
|
||||
final makeReq = ToolchainService.supportedTools['make']!;
|
||||
final ubuntuCmd = makeReq.getInstallCommand(DistroFamily.ubuntu);
|
||||
final debianCmd = makeReq.getInstallCommand(DistroFamily.debian);
|
||||
final alpineCmd = makeReq.getInstallCommand(DistroFamily.alpine);
|
||||
final defaultCmd = makeReq.effectiveInstallCommand;
|
||||
|
||||
expect(ubuntuCmd, contains('dpkg --configure -a'));
|
||||
expect(debianCmd, contains('dpkg --configure -a'));
|
||||
expect(alpineCmd, isNot(contains('dpkg --configure -a')));
|
||||
expect(defaultCmd, contains('dpkg --configure -a'));
|
||||
});
|
||||
});
|
||||
}
|
||||
+39
-23
@@ -40,8 +40,6 @@ import 'package:code_editor/widgets/virtual_keyboard_page_drawer.dart';
|
||||
import 'package:code_editor/widgets/terminal_session_item_widget.dart';
|
||||
import 'package:code_editor/models/terminal_session.dart';
|
||||
import 'package:code_editor/providers/terminal_provider.dart';
|
||||
import 'package:code_editor/providers/distro_provider.dart';
|
||||
import 'package:code_editor/widgets/distro_selector_dialog.dart';
|
||||
import 'package:code_editor/widgets/code_editor_app_bar.dart';
|
||||
import 'package:code_editor/widgets/code_editor_drawer.dart';
|
||||
import 'package:code_editor/utils/dialog_utils.dart';
|
||||
@@ -3114,6 +3112,45 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('CodeEditorAppBar disables run button and runTasks menu item when isDetecting is true', (tester) async {
|
||||
bool runCalled = false;
|
||||
bool runTasksCalled = false;
|
||||
|
||||
await tester.pumpWidget(
|
||||
localizedApp(
|
||||
Scaffold(
|
||||
appBar: CodeEditorAppBar(
|
||||
filePath: '/test/main.dart',
|
||||
isDetecting: true,
|
||||
onRun: () => runCalled = true,
|
||||
onRunTasks: () => runTasksCalled = true,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 1. 运行按钮 (Play) 处于禁用状态
|
||||
final playBtnFinder = find.widgetWithIcon(IconButton, Icons.play_arrow);
|
||||
expect(playBtnFinder, findsOneWidget);
|
||||
final playBtn = tester.widget<IconButton>(playBtnFinder);
|
||||
expect(playBtn.onPressed, isNull);
|
||||
|
||||
// 2. 打开右上角更多菜单
|
||||
final moreBtnFinder = find.byIcon(Icons.more_vert);
|
||||
expect(moreBtnFinder, findsOneWidget);
|
||||
await tester.tap(moreBtnFinder);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 3. 点击运行任务菜单项,验证不会触发回调
|
||||
final runTasksItemFinder = find.byIcon(Icons.playlist_play);
|
||||
expect(runTasksItemFinder, findsOneWidget);
|
||||
await tester.tap(runTasksItemFinder);
|
||||
await tester.pumpAndSettle();
|
||||
expect(runTasksCalled, isFalse);
|
||||
expect(runCalled, isFalse);
|
||||
});
|
||||
|
||||
testWidgets('VirtualKeyboardConfigView', (tester) async {
|
||||
await pumpNarrow(
|
||||
tester,
|
||||
@@ -3261,27 +3298,6 @@ void main() {
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('DistroSelectorDialog import popup (en)', (tester) async {
|
||||
await pumpNarrow(
|
||||
tester,
|
||||
MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<DistroProvider>.value(value: DistroProvider()),
|
||||
ChangeNotifierProvider<TerminalProvider>.value(value: TerminalProvider()),
|
||||
],
|
||||
child: localizedApp(
|
||||
const Scaffold(body: DistroSelectorDialog()),
|
||||
locale: const Locale('en'),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// 展开“导入系统”弹出菜单
|
||||
await tester.tap(find.byIcon(Icons.add_circle_outline));
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.takeException(), isNull, reason: '导入菜单展开后不应溢出');
|
||||
});
|
||||
|
||||
testWidgets('CodeEditorTabBar with many modified tabs', (tester) async {
|
||||
final tabProvider = TabProvider();
|
||||
for (int i = 0; i < 12; i++) {
|
||||
|
||||
Reference in new issue
Block a user