Add support for attachRequest in DAP, running "flutter attach" (#97652)

* Add support for attachRequest in DAP, which runs "flutter attach"

* Update DAP docs for attachRequest

* Improve doc comments

* Fix comments

* Remove noDebug from attach + create a getter for `debug`

* Fix indent
This commit is contained in:
Danny Tuppeny
2022-02-07 18:54:07 +00:00
committed by GitHub
parent ba01ec8faa
commit c659ad6ace
6 changed files with 554 additions and 241 deletions

View File

@@ -4,9 +4,11 @@
import 'dart:async';
import 'package:dds/dap.dart';
import 'package:dds/src/dap/protocol_generated.dart';
import 'package:file/file.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import '../../src/common.dart';
import '../test_data/basic_project.dart';
@@ -34,236 +36,324 @@ void main() {
tryToDelete(tempDir);
});
testWithoutContext('can run and terminate a Flutter app in debug mode', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
group('launch', () {
testWithoutContext('can run and terminate a Flutter app in debug mode', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
// Once the "topLevelFunction" output arrives, we can terminate the app.
unawaited(
dap.client.output
.firstWhere((String output) => output.startsWith('topLevelFunction'))
.whenComplete(() => dap.client.terminate()),
);
// Once the "topLevelFunction" output arrives, we can terminate the app.
unawaited(
dap.client.output
.firstWhere((String output) => output.startsWith('topLevelFunction'))
.whenComplete(() => dap.client.terminate()),
);
final List<OutputEventBody> outputEvents = await dap.client.collectAllOutput(
launch: () => dap.client
.launch(
cwd: project.dir.path,
toolArgs: <String>['-d', 'flutter-tester'],
),
);
final List<OutputEventBody> outputEvents = await dap.client.collectAllOutput(
launch: () => dap.client
.launch(
cwd: project.dir.path,
toolArgs: <String>['-d', 'flutter-tester'],
),
);
final String output = _uniqueOutputLines(outputEvents);
final String output = _uniqueOutputLines(outputEvents);
expectLines(output, <Object>[
'Launching $relativeMainPath on Flutter test device in debug mode...',
startsWith('Connecting to VM Service at'),
'topLevelFunction',
'',
startsWith('Exited'),
]);
});
expectLines(output, <Object>[
'Launching $relativeMainPath on Flutter test device in debug mode...',
startsWith('Connecting to VM Service at'),
'topLevelFunction',
'',
startsWith('Exited'),
]);
});
testWithoutContext('can run and terminate a Flutter app in noDebug mode', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
testWithoutContext('can run and terminate a Flutter app in noDebug mode', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
// Once the "topLevelFunction" output arrives, we can terminate the app.
unawaited(
dap.client.stdoutOutput
.firstWhere((String output) => output.startsWith('topLevelFunction'))
.whenComplete(() => dap.client.terminate()),
);
// Once the "topLevelFunction" output arrives, we can terminate the app.
unawaited(
dap.client.stdoutOutput
.firstWhere((String output) => output.startsWith('topLevelFunction'))
.whenComplete(() => dap.client.terminate()),
);
final List<OutputEventBody> outputEvents = await dap.client.collectAllOutput(
launch: () => dap.client
.launch(
final List<OutputEventBody> outputEvents = await dap.client.collectAllOutput(
launch: () => dap.client
.launch(
cwd: project.dir.path,
noDebug: true,
toolArgs: <String>['-d', 'flutter-tester'],
),
);
final String output = _uniqueOutputLines(outputEvents);
expectLines(output, <Object>[
'Launching $relativeMainPath on Flutter test device in debug mode...',
'topLevelFunction',
'',
startsWith('Exited'),
]);
});
testWithoutContext('correctly outputs launch errors and terminates', () async {
final CompileErrorProject project = CompileErrorProject();
await project.setUpIn(tempDir);
final List<OutputEventBody> outputEvents = await dap.client.collectAllOutput(
launch: () => dap.client
.launch(
cwd: project.dir.path,
toolArgs: <String>['-d', 'flutter-tester'],
),
);
final String output = _uniqueOutputLines(outputEvents);
expect(output, contains('this code does not compile'));
expect(output, contains('Exception: Failed to build'));
expect(output, contains('Exited (1)'));
});
testWithoutContext('can hot reload', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
// Launch the app and wait for it to print "topLevelFunction".
await Future.wait(<Future<void>>[
dap.client.stdoutOutput.firstWhere((String output) => output.startsWith('topLevelFunction')),
dap.client.start(
launch: () => dap.client.launch(
cwd: project.dir.path,
noDebug: true,
toolArgs: <String>['-d', 'flutter-tester'],
),
);
),
], eagerError: true);
final String output = _uniqueOutputLines(outputEvents);
// Capture the next two output events that we expect to be the Reload
// notification and then topLevelFunction being printed again.
final Future<List<String>> outputEventsFuture = dap.client.stdoutOutput
// But skip any topLevelFunctions that come before the reload.
.skipWhile((String output) => output.startsWith('topLevelFunction'))
.take(2)
.toList();
expectLines(output, <Object>[
'Launching $relativeMainPath on Flutter test device in debug mode...',
'topLevelFunction',
'',
startsWith('Exited'),
]);
});
await dap.client.hotReload();
testWithoutContext('correctly outputs launch errors and terminates', () async {
final CompileErrorProject project = CompileErrorProject();
await project.setUpIn(tempDir);
expectLines(
(await outputEventsFuture).join(),
<Object>[
startsWith('Reloaded'),
'topLevelFunction',
],
);
final List<OutputEventBody> outputEvents = await dap.client.collectAllOutput(
launch: () => dap.client
.launch(
await dap.client.terminate();
});
testWithoutContext('can hot restart', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
// Launch the app and wait for it to print "topLevelFunction".
await Future.wait(<Future<void>>[
dap.client.stdoutOutput.firstWhere((String output) => output.startsWith('topLevelFunction')),
dap.client.start(
launch: () => dap.client.launch(
cwd: project.dir.path,
noDebug: true,
toolArgs: <String>['-d', 'flutter-tester'],
),
),
], eagerError: true);
// Capture the next two output events that we expect to be the Restart
// notification and then topLevelFunction being printed again.
final Future<List<String>> outputEventsFuture = dap.client.stdoutOutput
// But skip any topLevelFunctions that come before the restart.
.skipWhile((String output) => output.startsWith('topLevelFunction'))
.take(2)
.toList();
await dap.client.hotRestart();
expectLines(
(await outputEventsFuture).join(),
<Object>[
startsWith('Restarted application'),
'topLevelFunction',
],
);
await dap.client.terminate();
});
testWithoutContext('can hot restart when exceptions occur on outgoing isolates', () async {
final BasicProjectThatThrows project = BasicProjectThatThrows();
await project.setUpIn(tempDir);
// Launch the app and wait for it to stop at an exception.
late int originalThreadId, newThreadId;
await Future.wait(<Future<void>>[
// Capture the thread ID of the stopped thread.
dap.client.stoppedEvents.first.then((StoppedEventBody event) => originalThreadId = event.threadId!),
dap.client.start(
exceptionPauseMode: 'All', // Ensure we stop on all exceptions
launch: () => dap.client.launch(
cwd: project.dir.path,
toolArgs: <String>['-d', 'flutter-tester'],
),
);
final String output = _uniqueOutputLines(outputEvents);
expect(output, contains('this code does not compile'));
expect(output, contains('Exception: Failed to build'));
expect(output, contains('Exited (1)'));
});
testWithoutContext('can hot reload', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
// Launch the app and wait for it to print "topLevelFunction".
await Future.wait(<Future<void>>[
dap.client.stdoutOutput.firstWhere((String output) => output.startsWith('topLevelFunction')),
dap.client.start(
launch: () => dap.client.launch(
cwd: project.dir.path,
noDebug: true,
toolArgs: <String>['-d', 'flutter-tester'],
),
),
], eagerError: true);
], eagerError: true);
// Capture the next two output events that we expect to be the Reload
// notification and then topLevelFunction being printed again.
final Future<List<String>> outputEventsFuture = dap.client.stdoutOutput
// But skip any topLevelFunctions that come before the reload.
.skipWhile((String output) => output.startsWith('topLevelFunction'))
.take(2)
.toList();
// Hot restart, ensuring it completes and capturing the ID of the new thread
// to pause.
await Future.wait(<Future<void>>[
// Capture the thread ID of the newly stopped thread.
dap.client.stoppedEvents.first.then((StoppedEventBody event) => newThreadId = event.threadId!),
dap.client.hotRestart(),
], eagerError: true);
await dap.client.hotReload();
// We should not have stopped on the original thread, but the new thread
// from after the restart.
expect(newThreadId, isNot(equals(originalThreadId)));
expectLines(
(await outputEventsFuture).join(),
<Object>[
startsWith('Reloaded'),
'topLevelFunction',
],
);
await dap.client.terminate();
});
await dap.client.terminate();
});
testWithoutContext('sends events for extension state updates', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
const String debugPaintRpc = 'ext.flutter.debugPaint';
testWithoutContext('can hot restart', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
// Create a future to capture the isolate ID when the debug paint service
// extension loads, as we'll need that to call it later.
final Future<String> isolateIdForDebugPaint = dap.client
.serviceExtensionAdded(debugPaintRpc)
.then((Map<String, Object?> body) => body['isolateId']! as String);
// Launch the app and wait for it to print "topLevelFunction".
await Future.wait(<Future<void>>[
dap.client.stdoutOutput.firstWhere((String output) => output.startsWith('topLevelFunction')),
dap.client.start(
launch: () => dap.client.launch(
cwd: project.dir.path,
noDebug: true,
toolArgs: <String>['-d', 'flutter-tester'],
// Launch the app and wait for it to print "topLevelFunction" so we know
// it's up and running.
await Future.wait(<Future<void>>[
dap.client.stdoutOutput.firstWhere((String output) => output.startsWith('topLevelFunction')),
dap.client.start(
launch: () => dap.client.launch(
cwd: project.dir.path,
toolArgs: <String>['-d', 'flutter-tester'],
),
),
),
], eagerError: true);
], eagerError: true);
// Capture the next two output events that we expect to be the Restart
// notification and then topLevelFunction being printed again.
final Future<List<String>> outputEventsFuture = dap.client.stdoutOutput
// But skip any topLevelFunctions that come before the restart.
.skipWhile((String output) => output.startsWith('topLevelFunction'))
.take(2)
.toList();
// Capture the next relevant state-change event (which should occur as a
// result of the call below).
final Future<Map<String, Object?>> stateChangeEventFuture =
dap.client.serviceExtensionStateChanged(debugPaintRpc);
await dap.client.hotRestart();
expectLines(
(await outputEventsFuture).join(),
<Object>[
startsWith('Restarted application'),
'topLevelFunction',
],
);
await dap.client.terminate();
});
testWithoutContext('can hot restart when exceptions occur on outgoing isolates', () async {
final BasicProjectThatThrows project = BasicProjectThatThrows();
await project.setUpIn(tempDir);
// Launch the app and wait for it to stop at an exception.
late int originalThreadId, newThreadId;
await Future.wait(<Future<void>>[
// Capture the thread ID of the stopped thread.
dap.client.stoppedEvents.first.then((StoppedEventBody event) => originalThreadId = event.threadId!),
dap.client.start(
exceptionPauseMode: 'All', // Ensure we stop on all exceptions
launch: () => dap.client.launch(
cwd: project.dir.path,
toolArgs: <String>['-d', 'flutter-tester'],
),
),
], eagerError: true);
// Hot restart, ensuring it completes and capturing the ID of the new thread
// to pause.
await Future.wait(<Future<void>>[
// Capture the thread ID of the newly stopped thread.
dap.client.stoppedEvents.first.then((StoppedEventBody event) => newThreadId = event.threadId!),
dap.client.hotRestart(),
], eagerError: true);
// We should not have stopped on the original thread, but the new thread
// from after the restart.
expect(newThreadId, isNot(equals(originalThreadId)));
await dap.client.terminate();
});
testWithoutContext('sends events for extension state updates', () async {
final BasicProject project = BasicProject();
await project.setUpIn(tempDir);
const String debugPaintRpc = 'ext.flutter.debugPaint';
// Create a future to capture the isolate ID when the debug paint service
// extension loads, as we'll need that to call it later.
final Future<String> isolateIdForDebugPaint = dap.client
.serviceExtensionAdded(debugPaintRpc)
.then((Map<String, Object?> body) => body['isolateId']! as String);
// Launch the app and wait for it to print "topLevelFunction" so we know
// it's up and running.
await Future.wait(<Future<void>>[
dap.client.stdoutOutput.firstWhere((String output) => output.startsWith('topLevelFunction')),
dap.client.start(
launch: () => dap.client.launch(
cwd: project.dir.path,
toolArgs: <String>['-d', 'flutter-tester'],
),
),
], eagerError: true);
// Capture the next relevant state-change event (which should occur as a
// result of the call below).
final Future<Map<String, Object?>> stateChangeEventFuture =
dap.client.serviceExtensionStateChanged(debugPaintRpc);
// Enable debug paint to trigger the state change.
await dap.client.custom(
'callService',
<String, Object?>{
'method': debugPaintRpc,
'params': <String, Object?>{
'enabled': true,
'isolateId': await isolateIdForDebugPaint,
// Enable debug paint to trigger the state change.
await dap.client.custom(
'callService',
<String, Object?>{
'method': debugPaintRpc,
'params': <String, Object?>{
'enabled': true,
'isolateId': await isolateIdForDebugPaint,
},
},
},
);
);
// Ensure the event occurred, and its value was as expected.
final Map<String, Object?> stateChangeEvent = await stateChangeEventFuture;
expect(stateChangeEvent['value'], 'true'); // extension state change values are always strings
// Ensure the event occurred, and its value was as expected.
final Map<String, Object?> stateChangeEvent = await stateChangeEventFuture;
expect(stateChangeEvent['value'], 'true'); // extension state change values are always strings
await dap.client.terminate();
await dap.client.terminate();
});
});
group('attach', () {
late SimpleFlutterRunner testProcess;
late BasicProject project;
late String breakpointFilePath;
late int breakpointLine;
setUp(() async {
project = BasicProject();
await project.setUpIn(tempDir);
testProcess = await SimpleFlutterRunner.start(tempDir);
breakpointFilePath = globals.fs.path.join(project.dir.path, 'lib', 'main.dart');
breakpointLine = project.buildMethodBreakpointLine;
});
tearDown(() async {
testProcess.process.kill();
await testProcess.process.exitCode;
});
testWithoutContext('can attach to an already-running Flutter app and reload', () async {
final Uri vmServiceUri = await testProcess.vmServiceUri;
// Launch the app and wait for it to print "topLevelFunction".
await Future.wait(<Future<void>>[
dap.client.stdoutOutput.firstWhere((String output) => output.startsWith('topLevelFunction')),
dap.client.start(
launch: () => dap.client.attach(
cwd: project.dir.path,
toolArgs: <String>['-d', 'flutter-tester'],
vmServiceUri: vmServiceUri.toString(),
),
),
], eagerError: true);
// Capture the "Reloaded" output and events immediately after.
final Future<List<String>> outputEventsFuture = dap.client.stdoutOutput
.skipWhile((String output) => !output.startsWith('Reloaded'))
.take(4)
.toList();
// Perform the reload, and expect we get the Reloaded output followed
// by printed output, to ensure the app is running again.
await dap.client.hotReload();
expectLines(
(await outputEventsFuture).join(),
<Object>[
startsWith('Reloaded'),
'topLevelFunction',
],
allowExtras: true,
);
await dap.client.terminate();
});
testWithoutContext('can attach to an already-running Flutter app and hit breakpoints', () async {
final Uri vmServiceUri = await testProcess.vmServiceUri;
// Launch the app and wait for it to print "topLevelFunction".
await Future.wait(<Future<void>>[
dap.client.stdoutOutput.firstWhere((String output) => output.startsWith('topLevelFunction')),
dap.client.start(
launch: () => dap.client.attach(
cwd: project.dir.path,
toolArgs: <String>['-d', 'flutter-tester'],
vmServiceUri: vmServiceUri.toString(),
),
),
], eagerError: true);
// Set a breakpoint and expect to hit it.
final Future<StoppedEventBody> stoppedFuture = dap.client.stoppedEvents.firstWhere((StoppedEventBody e) => e.reason == 'breakpoint');
await Future.wait(<Future<void>>[
stoppedFuture,
dap.client.setBreakpoint(breakpointFilePath, breakpointLine),
], eagerError: true);
final int threadId = (await stoppedFuture).threadId!;
// Remove the breakpoint and resume.
await dap.client.clearBreakpoints(breakpointFilePath);
await dap.client.continue_(threadId);
await dap.client.terminate();
});
});
}

View File

@@ -133,7 +133,7 @@ class DapTestClient {
return responses[1] as Response; // Return the initialize response.
}
/// Send a launchRequest to the server, asking it to start a Dart program.
/// Send a launchRequest to the server, asking it to start a Flutter app.
Future<Response> launch({
String? program,
List<String>? args,
@@ -141,7 +141,6 @@ class DapTestClient {
String? cwd,
bool? noDebug,
List<String>? additionalProjectPaths,
String? console,
bool? debugSdkLibraries,
bool? debugExternalPackageLibraries,
bool? evaluateGettersInDebugViews,
@@ -165,11 +164,43 @@ class DapTestClient {
sendLogsToClient: captureVmServiceTraffic,
),
// We can't automatically pick the command when using a custom type
// (DartLaunchRequestArguments).
// (FlutterLaunchRequestArguments).
overrideCommand: 'launch',
);
}
/// Send an attachRequest to the server, asking it to attach to an already-running Flutter app.
Future<Response> attach({
List<String>? toolArgs,
String? vmServiceUri,
String? cwd,
List<String>? additionalProjectPaths,
bool? debugSdkLibraries,
bool? debugExternalPackageLibraries,
bool? evaluateGettersInDebugViews,
bool? evaluateToStringInDebugViews,
}) {
return sendRequest(
FlutterAttachRequestArguments(
cwd: cwd,
toolArgs: toolArgs,
vmServiceUri: vmServiceUri,
additionalProjectPaths: additionalProjectPaths,
debugSdkLibraries: debugSdkLibraries,
debugExternalPackageLibraries: debugExternalPackageLibraries,
evaluateGettersInDebugViews: evaluateGettersInDebugViews,
evaluateToStringInDebugViews: evaluateToStringInDebugViews,
// When running out of process, VM Service traffic won't be available
// to the client-side logger, so force logging on which sends VM Service
// traffic in a custom event.
sendLogsToClient: captureVmServiceTraffic,
),
// We can't automatically pick the command when using a custom type
// (FlutterAttachRequestArguments).
overrideCommand: 'attach',
);
}
/// Sends an arbitrary request to the server.
///
/// Returns a Future that completes when the server returns a corresponding
@@ -357,4 +388,33 @@ extension DapTestClientExtension on DapTestClient {
);
}
/// Sets a breakpoint at [line] in [file].
Future<void> setBreakpoint(String filePath, int line) async {
await sendRequest(
SetBreakpointsArguments(
source: Source(path: filePath),
breakpoints: <SourceBreakpoint>[
SourceBreakpoint(line: line),
],
),
);
}
/// Sends a continue request for the given thread.
///
/// Returns a Future that completes when the server returns a corresponding
/// response.
Future<Response> continue_(int threadId) =>
sendRequest(ContinueArguments(threadId: threadId));
/// Clears breakpoints in [file].
Future<void> clearBreakpoints(String filePath) async {
await sendRequest(
SetBreakpointsArguments(
source: Source(path: filePath),
breakpoints: <SourceBreakpoint>[],
),
);
}
}

View File

@@ -5,7 +5,13 @@
import 'dart:async';
import 'dart:io';
import 'package:dds/dap.dart';
import 'package:dds/src/dap/logging.dart';
import 'package:file/file.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:test/test.dart';
import 'test_client.dart';
@@ -47,6 +53,72 @@ void expectLines(
}
}
/// Manages running a simple Flutter app to be used in tests that need to attach
/// to an existing process.
class SimpleFlutterRunner {
SimpleFlutterRunner(this.process) {
process.stdout.transform(ByteToLineTransformer()).listen(_handleStdout);
process.stderr.transform(utf8.decoder).listen(_handleStderr);
unawaited(process.exitCode.then(_handleExitCode));
}
void _handleExitCode(int code) {
if (!_vmServiceUriCompleter.isCompleted) {
_vmServiceUriCompleter.completeError('Flutter process ended without producing a VM Service URI');
}
}
void _handleStderr(String err) {
if (!_vmServiceUriCompleter.isCompleted) {
_vmServiceUriCompleter.completeError(err);
}
}
void _handleStdout(String outputLine) {
try {
final Object? json = jsonDecode(outputLine);
// Flutter --machine output is wrapped in [brackets] so will deserialize
// as a list with one item.
if (json is List && json.length == 1) {
final Object? message = json.single;
// Parse the add.debugPort event which contains our VM Service URI.
if (message is Map<String, Object?> && message['event'] == 'app.debugPort') {
final String vmServiceUri = (message['params']! as Map<String, Object?>)['wsUri']! as String;
if (!_vmServiceUriCompleter.isCompleted) {
_vmServiceUriCompleter.complete(Uri.parse(vmServiceUri));
}
}
}
} on FormatException {
// `flutter run` writes a lot of text to stdout so just ignore anything
// that's not valid JSON.
}
}
final Process process;
final Completer<Uri> _vmServiceUriCompleter = Completer<Uri>();
Future<Uri> get vmServiceUri => _vmServiceUriCompleter.future;
static Future<SimpleFlutterRunner> start(Directory projectDirectory) async {
final String flutterToolPath = globals.fs.path.join(Cache.flutterRoot!, 'bin', globals.platform.isWindows ? 'flutter.bat' : 'flutter');
final List<String> args = <String>[
'run',
'--machine',
'-d',
'flutter-tester',
];
final Process process = await Process.start(
flutterToolPath,
args,
workingDirectory: projectDirectory.path,
);
return SimpleFlutterRunner(process);
}
}
/// A helper class containing the DAP server/client for DAP integration tests.
class DapTestSession {
DapTestSession._(this.server, this.client);