Add support for running tests through debug-adapter (#92587)

* Add support for running tests through debug-adapter

* Improve comments about stdout + remove pedantic
This commit is contained in:
Danny Tuppeny
2021-10-28 11:34:05 +01:00
committed by GitHub
parent 7cb43e9580
commit 57dbf7f7e7
10 changed files with 504 additions and 19 deletions

View File

@@ -27,7 +27,7 @@ void main() {
});
setUp(() async {
tempDir = createResolvedTempDirectorySync('debug_adapter_test.');
tempDir = createResolvedTempDirectorySync('flutter_adapter_test.');
dap = await DapTestSession.setUp();
});

View File

@@ -0,0 +1,166 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'package:dds/src/dap/protocol_generated.dart';
import 'package:file/file.dart';
import 'package:flutter_tools/src/cache.dart';
import '../../src/common.dart';
import '../test_data/tests_project.dart';
import '../test_utils.dart';
import 'test_client.dart';
import 'test_support.dart';
void main() {
Directory tempDir;
/*late*/ DapTestSession dap;
setUpAll(() {
Cache.flutterRoot = getFlutterRoot();
});
setUp(() async {
tempDir = createResolvedTempDirectorySync('flutter_test_adapter_test.');
dap = await DapTestSession.setUp(additionalArgs: <String>['--test']);
});
tearDown(() async {
await dap.tearDown();
tryToDelete(tempDir);
});
test('can run in debug mode', () async {
final DapTestClient client = dap.client;
final TestsProject project = TestsProject();
await project.setUpIn(tempDir);
// Collect output and test events while running the script.
final TestEvents outputEvents = await client.collectTestOutput(
launch: () => client.launch(
program: project.testFilePath,
cwd: project.dir.path,
),
);
// Check the printed output shows that the run finished, and it's exit
// code (which is 1 due to the failing test).
final String output = outputEvents.output.map((OutputEventBody e) => e.output).join();
expectLines(
output,
<Object>[
startsWith('Connecting to VM Service at'),
..._testsProjectExpectedOutput
],
allowExtras: true, // Allow for printed call stack etc.
);
_expectStandardTestsProjectResults(outputEvents);
});
test('can run in noDebug mode', () async {
final DapTestClient client = dap.client;
final TestsProject project = TestsProject();
await project.setUpIn(tempDir);
// Collect output and test events while running the script.
final TestEvents outputEvents = await client.collectTestOutput(
launch: () => client.launch(
program: project.testFilePath,
noDebug: true,
cwd: project.dir.path,
),
);
// Check the printed output shows that the run finished, and it's exit
// code (which is 1 due to the failing test).
final String output = outputEvents.output.map((OutputEventBody e) => e.output).join();
expectLines(
output,
_testsProjectExpectedOutput,
allowExtras: true, // Allow for printed call stack etc.
);
_expectStandardTestsProjectResults(outputEvents);
});
test('can run a single test', () async {
final DapTestClient client = dap.client;
final TestsProject project = TestsProject();
await project.setUpIn(tempDir);
// Collect output and test events while running the script.
final TestEvents outputEvents = await client.collectTestOutput(
launch: () => client.launch(
program: project.testFilePath,
noDebug: true,
cwd: project.dir.path,
// It's up to the calling IDE to pass the correct args for 'dart test'
// if it wants to run a subset of tests.
args: <String>[
'--plain-name',
'can pass',
],
),
);
final List<Object> testsNames = outputEvents.testNotifications
.where((Map<String, Object>/*?*/ e) => e['type'] == 'testStart')
.map((Map<String, Object>/*?*/ e) => (e['test'] as Map<String, Object/*?*/>)['name'])
.toList();
expect(testsNames, contains('Flutter tests can pass'));
expect(testsNames, isNot(contains('Flutter tests can fail')));
});
}
/// Matchers for the expected console output of [TestsProject].
final List<Object> _testsProjectExpectedOutput = <Object>[
// First test
'✓ Flutter tests can pass',
// Second test
'══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════',
'The following TestFailure object was thrown running a test:',
' Expected: false',
' Actual: <true>',
'',
'The test description was: can fail',
'',
'✖ Flutter tests can fail',
// Exit
'',
'Exited (1).',
];
/// A helper that verifies a full set of expected test results for the
/// [TestsProject] script.
void _expectStandardTestsProjectResults(TestEvents events) {
// Check we recieved all expected test events passed through from
// package:test.
final List<Object> eventNames =
events.testNotifications.map((Map<String, Object/*?*/> e) => e['type']).toList();
// start/done should always be first/last.
expect(eventNames.first, equals('start'));
expect(eventNames.last, equals('done'));
// allSuites should have occurred after start.
expect(
eventNames,
containsAllInOrder(<String>['start', 'allSuites']),
);
// Expect two tests, with the failing one emitting an error.
expect(
eventNames,
containsAllInOrder(<String>[
'testStart',
'testDone',
'testStart',
'error',
'testDone',
]),
);
}

View File

@@ -74,6 +74,12 @@ class DapTestClient {
return _eventController.stream.where((Event e) => e.event == event);
}
/// Returns a stream of 'dart.testNotification' custom events from the
/// package:test JSON reporter.
Stream<Map<String, Object?>> get testNotificationEvents =>
events('dart.testNotification')
.map((Event e) => e.body! as Map<String, Object?>);
/// Sends a custom request to the debug adapter to trigger a Hot Reload.
Future<Response> hotReload() {
return custom('hotReload');
@@ -220,6 +226,17 @@ class DapTestClient {
}
}
/// Useful events produced by the debug adapter during a debug session.
class TestEvents {
TestEvents({
required this.output,
required this.testNotifications,
});
final List<OutputEventBody> output;
final List<Map<String, Object?>> testNotifications;
}
class _OutgoingRequest {
_OutgoingRequest(this.completer, this.name, this.allowFailure);
@@ -273,4 +290,39 @@ extension DapTestClientExtension on DapTestClient {
? output.skipWhile((OutputEventBody output) => output.output.startsWith('Running "flutter pub get"')).toList()
: output;
}
/// Collects all output and test events until the program terminates.
///
/// These results include all events in the order they are recieved, including
/// console, stdout, stderr and test notifications from the test JSON reporter.
///
/// Only one of [start] or [launch] may be provided. Use [start] to customise
/// the whole start of the session (including initialise) or [launch] to only
/// customise the [launchRequest].
Future<TestEvents> collectTestOutput({
String? program,
String? cwd,
Future<Response> Function()? start,
Future<Object?> Function()? launch,
}) async {
assert(
start == null || launch == null,
'Only one of "start" or "launch" may be provided',
);
final Future<List<OutputEventBody>> outputEventsFuture = outputEvents.toList();
final Future<List<Map<String, Object?>>> testNotificationEventsFuture = testNotificationEvents.toList();
if (start != null) {
await start();
} else {
await this.start(program: program, cwd: cwd, launch: launch);
}
return TestEvents(
output: await outputEventsFuture,
testNotifications: await testNotificationEventsFuture,
);
}
}

View File

@@ -29,11 +29,22 @@ final bool verboseLogging = Platform.environment['DAP_TEST_VERBOSE'] == 'true';
/// Expects the lines in [actual] to match the relevant matcher in [expected],
/// ignoring differences in line endings and trailing whitespace.
void expectLines(String actual, List<Object> expected) {
expect(
actual.replaceAll('\r\n', '\n').trim().split('\n'),
equals(expected),
);
void expectLines(
String actual,
List<Object> expected, {
bool allowExtras = false,
}) {
if (allowExtras) {
expect(
actual.replaceAll('\r\n', '\n').trim().split('\n'),
containsAllInOrder(expected),
);
} else {
expect(
actual.replaceAll('\r\n', '\n').trim().split('\n'),
equals(expected),
);
}
}
/// A helper class containing the DAP server/client for DAP integration tests.

View File

@@ -34,8 +34,13 @@ class TestsProject extends Project {
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Hello world test', (WidgetTester tester) async {
expect(true, isTrue); // BREAKPOINT
group('Flutter tests', () {
testWidgets('can pass', (WidgetTester tester) async {
expect(true, isTrue); // BREAKPOINT
});
testWidgets('can fail', (WidgetTester tester) async {
expect(true, isFalse);
});
});
}
''';