Migrate some tests and test utilities in server

Change-Id: I0a37352c903bf7139af25aab255fe6a5331ce98b
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/194020
Reviewed-by: Konstantin Shcheglov <scheglov@google.com>
Commit-Queue: Brian Wilkerson <brianwilkerson@google.com>
This commit is contained in:
Brian Wilkerson 2021-04-03 19:23:44 +00:00 committed by commit-bot@chromium.org
parent 778c2361c3
commit 0190d20bd6
16 changed files with 124 additions and 142 deletions

View file

@ -2,15 +2,13 @@
// for details. 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.9
import 'package:matcher/matcher.dart';
typedef _Predicate<T> = bool Function(T value);
/// Lightweight expect that can be run outside of a test context.
class ExpectMixin {
void expect(actual, matcher, {String reason}) {
void expect(actual, matcher, {String? reason}) {
matcher = _wrapMatcher(matcher);
var matchState = {};
try {

View file

@ -2,8 +2,6 @@
// for details. 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.9
import 'package:analyzer/error/error.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/analysis_options/analysis_options_provider.dart';
@ -22,10 +20,12 @@ void main() {
@reflectiveTest
class LinterRuleOptionsValidatorTest {
final LinterRuleOptionsValidator validator = LinterRuleOptionsValidator();
final AnalysisOptionsProvider optionsProvider = AnalysisOptionsProvider();
RecordingErrorListener recorder;
ErrorReporter reporter;
late RecordingErrorListener recorder;
late ErrorReporter reporter;
List<AnalysisError> get errors => recorder.errors;

View file

@ -2,8 +2,6 @@
// for details. 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.9
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'linter_test.dart' as linter_test;

View file

@ -2,8 +2,6 @@
// for details. 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.9
import 'dart:convert';
import 'package:analyzer/src/dart/analysis/byte_store.dart';
@ -19,10 +17,10 @@ class CiderServiceTest with ResourceProviderMixin {
final ByteStore byteStore = MemoryByteStore();
final StringBuffer logBuffer = StringBuffer();
PerformanceLog logger;
MockSdk sdk;
late PerformanceLog logger;
late MockSdk sdk;
FileResolver fileResolver;
late FileResolver fileResolver;
String testPath = '/workspace/dart/test/lib/test.dart';
@ -33,7 +31,7 @@ class CiderServiceTest with ResourceProviderMixin {
var workspace = BazelWorkspace.find(
resourceProvider,
convertPath(testPath),
);
)!;
fileResolver = FileResolver(
logger,

View file

@ -2,8 +2,6 @@
// for details. 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.9
import 'package:analysis_server/protocol/protocol_generated.dart' as server;
import 'package:analyzer_plugin/protocol/protocol_common.dart';
import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plugin;
@ -66,7 +64,7 @@ class ProtocolTestUtilities {
/// On return, increment [stringIndex] by 3 (or 4 if no [file] name is
/// provided) and [intIndex] by 4.
AnalysisError analysisError(int stringIndex, int intIndex, {String file}) {
AnalysisError analysisError(int stringIndex, int intIndex, {String? file}) {
return AnalysisError(
AnalysisErrorSeverity.ERROR,
AnalysisErrorType.COMPILE_TIME_ERROR,
@ -78,7 +76,7 @@ class ProtocolTestUtilities {
}
/// On return, increment [stringIndex] by 5 and [intIndex] by 5.
Element element(int stringIndex, int intIndex, {ElementKind kind}) =>
Element element(int stringIndex, int intIndex, {ElementKind? kind}) =>
Element(kind ?? ElementKind.CLASS, strings[stringIndex++], intIndex++,
location: Location(fileName(stringIndex++), intIndex++, intIndex++,
intIndex++, intIndex++, intIndex++, intIndex++),
@ -95,7 +93,7 @@ class ProtocolTestUtilities {
HighlightRegion(HighlightRegionType.FIELD, offset, length);
/// On return, increment [stringIndex] by 1 and [intIndex] by 4.
Location location(int stringIndex, int intIndex, {String file}) => Location(
Location location(int stringIndex, int intIndex, {String? file}) => Location(
file ?? fileName(stringIndex),
intIndex++,
intIndex++,
@ -131,7 +129,7 @@ class ProtocolTestUtilities {
/// On return, increment [stringIndex] by 2 (or 3 if no [file] name is
/// provided) and [intIndex] by 4.
plugin.AnalysisNavigationParams pluginNavigationParams(
int stringIndex, int intIndex, {String file}) =>
int stringIndex, int intIndex, {String? file}) =>
plugin.AnalysisNavigationParams(
file ?? fileName(stringIndex++), <NavigationRegion>[
NavigationRegion(intIndex++, 2, <int>[0])
@ -153,7 +151,7 @@ class ProtocolTestUtilities {
/// On return, increment [stringIndex] by 2 (or 3 if no [file] name is
/// provided) and [intIndex] by 4.
server.AnalysisNavigationParams serverNavigationParams(
int stringIndex, int intIndex, {String file}) =>
int stringIndex, int intIndex, {String? file}) =>
server.AnalysisNavigationParams(
file ?? fileName(stringIndex++), <NavigationRegion>[
NavigationRegion(intIndex++, 2, <int>[0])

View file

@ -2,8 +2,6 @@
// for details. 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.9
final alignmentEditor = '''
"editor": {
"kind": "ENUM_LIKE",

View file

@ -2,8 +2,6 @@
// for details. 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.9
/// Operations to be performed during the simulation.
import '../utilities/server.dart';

View file

@ -2,8 +2,6 @@
// for details. 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.9
/// A stress test for the analysis server.
import 'dart:io';
import 'dart:math' as math;
@ -62,32 +60,32 @@ class Driver {
static String VERBOSE_FLAG_NAME = 'verbose';
/// The style of interaction to use for analysis.updateContent requests.
OverlayStyle overlayStyle;
late OverlayStyle overlayStyle;
/// The absolute path of the repository.
String repositoryPath;
late String repositoryPath;
/// The absolute paths to the analysis roots.
List<String> analysisRoots;
late List<String> analysisRoots;
/// The git repository.
GitRepository repository;
late GitRepository repository;
/// The connection to the analysis server.
Server server;
late Server server;
/// A list of the glob patterns used to identify the files being analyzed by
/// the server.
List<Glob> fileGlobs;
late List<Glob> fileGlobs;
/// An object gathering statistics about the simulation.
Statistics statistics;
late Statistics statistics;
/// A flag indicating whether verbose output should be provided.
bool verbose = false;
/// The logger to which verbose logging data will be written.
Logger logger;
late Logger logger;
/// Initialize a newly created driver.
Driver() {
@ -219,7 +217,7 @@ class Driver {
List<int> _getBreakOffsets(String text) {
var breakOffsets = <int>[];
var featureSet = FeatureSet.forTesting(sdkVersion: '2.2.2');
var scanner = Scanner(null, CharSequenceReader(text),
var scanner = Scanner(_TestSource(), CharSequenceReader(text),
error.AnalysisErrorListener.NULL_LISTENER)
..configureFeatures(
featureSetForOverriding: featureSet,
@ -236,7 +234,7 @@ class Driver {
if (token.type == TokenType.IDENTIFIER && length > 3) {
breakOffsets.add(offset + (length ~/ 2));
}
token = token.next;
token = token.next!;
}
return breakOffsets;
}
@ -315,8 +313,8 @@ class Driver {
// Iterate over the history, applying changes.
//
var firstCheckout = true;
ErrorMap expectedErrors;
Iterable<String> changedPubspecs;
ErrorMap? expectedErrors;
late Iterable<String> changedPubspecs;
while (iterator.moveNext()) {
//
// Checkout the commit on which the changes are based.
@ -416,8 +414,7 @@ class Driver {
/// Run the simulation by starting up a server and sending it requests.
Future<void> _runSimulation() async {
server = Server(logger: logger);
var stopwatch = Stopwatch();
statistics.stopwatch = stopwatch;
var stopwatch = statistics.stopwatch;
stopwatch.start();
await server.start();
server.sendServerSetSubscriptions([ServerService.STATUS]);
@ -443,7 +440,7 @@ class Driver {
}
/// Display usage information, preceded by the [errorMessage] if one is given.
void _showUsage(ArgParser parser, [String errorMessage]) {
void _showUsage(ArgParser parser, [String? errorMessage]) {
if (errorMessage != null) {
stderr.writeln(errorMessage);
stderr.writeln();
@ -474,25 +471,25 @@ class FileEdit {
OverlayStyle overlayStyle;
/// The absolute path of the file to be edited.
String filePath;
late String filePath;
/// The content of the file before any edits have been applied.
String content;
late String content;
/// The line info for the file before any edits have been applied.
LineInfo lineInfo;
late LineInfo lineInfo;
/// The lists of source edits, one list for each hunk being edited.
List<List<SourceEdit>> editLists = <List<SourceEdit>>[];
/// The current content of the file. This field is only used if the overlay
/// style is [OverlayStyle.multipleAdd].
String currentContent;
late String currentContent;
/// Initialize a collection of edits to be associated with the file at the
/// given [filePath].
FileEdit(this.overlayStyle, DiffRecord record) {
filePath = record.srcPath;
filePath = record.srcPath!;
if (record.isAddition) {
content = '';
lineInfo = LineInfo(<int>[0]);
@ -533,9 +530,7 @@ class FileEdit {
} else {
throw StateError('Failed to handle overlay style = $overlayStyle');
}
if (overlay != null) {
addUpdateContent(overlay);
}
addUpdateContent(overlay);
}
}
addUpdateContent(RemoveContentOverlay());
@ -553,10 +548,10 @@ class Statistics {
final Driver driver;
/// The stopwatch being used to time the simulation.
Stopwatch stopwatch;
Stopwatch stopwatch = Stopwatch();
/// The total number of commits in the repository.
int commitCount;
int commitCount = 0;
/// The number of commits in the repository that touched one of the files in
/// one of the analysis roots.
@ -602,3 +597,11 @@ class Statistics {
return '$seconds.$milliseconds';
}
}
class _TestSource implements Source {
@override
String get fullName => '/package/lib/test.dart';
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}

View file

@ -2,8 +2,6 @@
// for details. 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.9
/// Support for interacting with a git repository.
import 'dart:convert';
import 'dart:io';
@ -41,9 +39,9 @@ class BlobDiff {
void _parseLine(String line) {
var currentHunk = hunks.isEmpty ? null : hunks.last;
if (line.startsWith('@@')) {
var match = hunkHeaderRegExp.matchAsPrefix(line);
var srcLine = int.parse(match.group(1));
var dstLine = int.parse(match.group(2));
var match = hunkHeaderRegExp.matchAsPrefix(line)!;
var srcLine = int.parse(match.group(1)!);
var dstLine = int.parse(match.group(2)!);
hunks.add(DiffHunk(srcLine, dstLine));
} else if (currentHunk != null && line.startsWith('+')) {
currentHunk.addLines.add(line.substring(1));
@ -90,7 +88,7 @@ class CommitDelta {
Iterable<String> filesMatching(String fileName) {
return diffRecords
.where((DiffRecord record) => record.isFor(fileName))
.map((DiffRecord record) => record.srcPath);
.map((DiffRecord record) => record.srcPath!);
}
/// Remove any diffs for files that are either (a) outside the given
@ -98,7 +96,7 @@ class CommitDelta {
/// [globPatterns].
void filterDiffs(List<String> inclusionPaths, List<Glob> globPatterns) {
diffRecords.retainWhere((DiffRecord record) {
var filePath = record.srcPath ?? record.dstPath;
var filePath = (record.srcPath ?? record.dstPath)!;
for (var inclusionPath in inclusionPaths) {
if (path.isWithin(inclusionPath, filePath)) {
for (var glob in globPatterns) {
@ -177,7 +175,7 @@ class CommitDelta {
var srcPath = _makeAbsolute(input.substring(startIndex, endIndex));
startIndex = endIndex + 1;
// Parse field 14
String dstPath;
String? dstPath;
if (status.startsWith('C') || status.startsWith('R')) {
endIndex = _findEnd(input, startIndex);
dstPath = _makeAbsolute(input.substring(startIndex, endIndex));
@ -256,10 +254,10 @@ class DiffRecord {
final String status;
/// The path of the src.
final String srcPath;
final String? srcPath;
/// The path of the dst if this was either a copy or a rename operation.
final String dstPath;
final String? dstPath;
/// Initialize a newly created diff record.
DiffRecord(this.repository, this.srcBlob, this.dstBlob, this.status,
@ -288,12 +286,15 @@ class DiffRecord {
BlobDiff getBlobDiff() => repository.getBlobDiff(srcBlob, dstBlob);
/// Return `true` if this diff applies to a file with the given name.
bool isFor(String fileName) =>
(srcPath != null && fileName == path.basename(srcPath)) ||
(dstPath != null && fileName == path.basename(dstPath));
bool isFor(String fileName) {
var srcPath = this.srcPath;
var dstPath = this.dstPath;
return (srcPath != null && fileName == path.basename(srcPath)) ||
(dstPath != null && fileName == path.basename(dstPath));
}
@override
String toString() => srcPath ?? dstPath;
String toString() => srcPath ?? dstPath ?? '<unknown>';
}
/// A representation of a git repository.
@ -303,7 +304,7 @@ class GitRepository {
/// The logger to which git commands should be written, or `null` if the
/// commands should not be written.
final Logger logger;
final Logger? logger;
/// Initialize a newly created repository to represent the git repository at
/// the given [path].
@ -387,7 +388,7 @@ class LinearCommitHistoryIterator {
final LinearCommitHistory history;
/// The index of the current commit in the list of [commitIds].
int currentCommit;
late int currentCommit;
/// Initialize a newly created iterator to iterate over the commits with the
/// given [commitIds];

View file

@ -2,8 +2,6 @@
// for details. 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.9
/// A utility class used to write logging information during a test.
class Logger {
/// The width of the field in which labels are printed.
@ -23,7 +21,7 @@ class Logger {
/// The [label] is used to indicate the kind of information being logged,
/// while the [content] contains the actual information. If a list of
/// [arguments] is provided, then they will be written after the content.
void log(String label, String content, {List<String> arguments}) {
void log(String label, String content, {List<String>? arguments}) {
for (var i = _labelWidth - label.length; i > 0; i--) {
sink.write(' ');
}

View file

@ -2,8 +2,6 @@
// for details. 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.9
/// Support for interacting with an analysis server that is running in a
/// separate process.
import 'dart:async';
@ -50,36 +48,36 @@ class RequestData {
/// The method that was requested.
final String method;
/// The request parameters.
final Map<String, dynamic> params;
/// The request parameters, or `null` if there are no parameters.
final Map<String, dynamic>? params;
/// The time at which the request was sent.
final int requestTime;
/// The time at which the response was received, or `null` if no response has
/// been received.
int responseTime;
int? responseTime;
/// The response that was received.
Response _response;
Response? _response;
/// The completer that will be completed when a response is received.
Completer<Response> _responseCompleter;
Completer<Response>? _responseCompleter;
/// Initialize a newly created set of request data.
RequestData(this.id, this.method, this.params, this.requestTime);
/// Return the number of milliseconds that elapsed between the request and the
/// response. This getter assumes that the response was received.
int get elapsedTime => responseTime - requestTime;
int get elapsedTime => responseTime! - requestTime;
/// Return a future that will complete when a response is received.
Future<Response> get respondedTo {
if (_response != null) {
return Future.value(_response);
}
_responseCompleter ??= Completer<Response>();
return _responseCompleter.future;
var completer = _responseCompleter ??= Completer<Response>();
return completer.future;
}
/// Record that the given [response] was received.
@ -91,8 +89,9 @@ class RequestData {
}
responseTime = currentTime;
_response = response;
if (_responseCompleter != null) {
_responseCompleter.complete(response);
var completer = _responseCompleter;
if (completer != null) {
completer.complete(response);
_responseCompleter = null;
}
}
@ -112,11 +111,11 @@ class Server {
/// The logger to which the communications log should be written, or `null` if
/// the log should not be written.
final Logger logger;
final Logger? logger;
/// The process in which the server is running, or `null` if the server hasn't
/// been started yet.
Process _process;
Process? _process;
/// Number that should be used to compute the 'id' to send in the next command
/// sent to the server.
@ -138,11 +137,11 @@ class Server {
/// The completer that will be completed the next time a 'server.status'
/// notification is received from the server with 'analyzing' set to false.
Completer<void> _analysisFinishedCompleter;
Completer<void>? _analysisFinishedCompleter;
/// The completer that will be completed the next time a 'server.connected'
/// notification is received from the server.
Completer<void> _serverConnectedCompleter;
Completer<void>? _serverConnectedCompleter;
/// A table mapping the ids of requests that have been sent to the server to
/// data about those requests.
@ -167,8 +166,8 @@ class Server {
/// multiple times in one test; each time it is used it will wait afresh for
/// analysis to finish.
Future get analysisFinished {
_analysisFinishedCompleter ??= Completer<void>();
return _analysisFinishedCompleter.future;
var completer = _analysisFinishedCompleter ??= Completer<void>();
return completer.future;
}
/// Return a list of the paths of files that are currently being analyzed.
@ -243,7 +242,7 @@ class Server {
.fold(0, (int count, List<RequestData> list) => count + list.length);
var countWidth = maxCount.toString().length;
for (var key in keys) {
var requests = requestsByMethod[key];
var requests = requestsByMethod[key]!;
var noResponseCount = 0;
var responseCount = 0;
var minTime = -1;
@ -346,7 +345,7 @@ class Server {
void sendAnalysisSetAnalysisRoots(
List<String> included, List<String> excluded,
{Map<String, String> packageRoots}) {
{Map<String, String>? packageRoots}) {
_analysisRootIncludes = included;
var params = AnalysisSetAnalysisRootsParams(included, excluded,
packageRoots: packageRoots)
@ -399,7 +398,7 @@ class Server {
RequestData sendEditFormat(
String file, int selectionOffset, int selectionLength,
{int lineLength}) {
{int? lineLength}) {
var params = EditFormatParams(file, selectionOffset, selectionLength,
lineLength: lineLength)
.toJson();
@ -425,7 +424,7 @@ class Server {
RequestData sendEditGetRefactoring(RefactoringKind kind, String file,
int offset, int length, bool validateOnly,
{RefactoringOptions options}) {
{RefactoringOptions? options}) {
var params = EditGetRefactoringParams(
kind, file, offset, length, validateOnly,
options: options)
@ -453,7 +452,7 @@ class Server {
return _send('execution.deleteContext', params);
}
RequestData sendExecutionMapUri(String id, {String file, String uri}) {
RequestData sendExecutionMapUri(String id, {String? file, String? uri}) {
var params = ExecutionMapUriParams(id, file: file, uri: uri).toJson();
return _send('execution.mapUri', params);
}
@ -487,7 +486,7 @@ class Server {
_send('search.findTopLevelDeclarations', params);
}
void sendSearchGetTypeHierarchy(String file, int offset, {bool superOnly}) {
void sendSearchGetTypeHierarchy(String file, int offset, {bool? superOnly}) {
var params =
SearchGetTypeHierarchyParams(file, offset, superOnly: superOnly)
.toJson();
@ -521,10 +520,10 @@ class Server {
/// highlight APIs.
Future<void> start(
{bool checked = true,
int diagnosticPort,
int? diagnosticPort,
bool profileServer = false,
String sdkPath,
int servicesPort,
String? sdkPath,
int? servicesPort,
bool useAnalysisHighlight2 = false}) async {
if (_process != null) {
throw Exception('Process already started');
@ -573,14 +572,15 @@ class Server {
// stdout.writeln('Launching $serverPath');
// stdout.writeln('$dartBinary ${arguments.join(' ')}');
_process = await Process.start(dartBinary, arguments);
_process.exitCode.then((int code) {
_process!.exitCode.then((int code) {
if (code != 0) {
throw StateError('Server terminated with exit code $code');
}
});
_listenToOutput();
_serverConnectedCompleter = Completer<void>();
return _serverConnectedCompleter.future;
var completer = Completer<void>();
_serverConnectedCompleter = completer;
return completer.future;
}
/// Find the root directory of the analysis_server package by proceeding
@ -601,18 +601,17 @@ class Server {
switch (notification.event) {
case 'server.connected':
// new ServerConnectedParams.fromNotification(notification);
_serverConnectedCompleter.complete(null);
_serverConnectedCompleter!.complete(null);
break;
case 'server.error':
// new ServerErrorParams.fromNotification(notification);
throw StateError('Server error: ${notification.toJson()}');
break;
case 'server.status':
if (_analysisFinishedCompleter != null) {
var params = ServerStatusParams.fromNotification(notification);
var analysis = params.analysis;
if (analysis != null && !analysis.isAnalyzing) {
_analysisFinishedCompleter.complete(null);
_analysisFinishedCompleter!.complete(null);
}
}
break;
@ -669,7 +668,7 @@ class Server {
/// Handle a [response] received from the server.
void _handleResponse(Response response) {
var id = response.id.toString();
var requestData = _requestDataMap[id];
var requestData = _requestDataMap[id]!;
requestData.recordResponse(response);
// switch (requestData.method) {
// case "analysis.getErrors":
@ -754,8 +753,8 @@ class Server {
void _handleStdOut(String line) {
/// Cast the given [value] to a Map, or throw an [ArgumentError] if the
/// value cannot be cast.
Map asMap(Object value) {
if (value is Map) {
Map<String, Object?> asMap(Object value) {
if (value is Map<String, Object?>) {
return value;
}
throw ArgumentError('Expected a Map, found a ${value.runtimeType}');
@ -770,7 +769,7 @@ class Server {
var message = asMap(json.decoder.convert(trimmedLine));
if (message.containsKey('id')) {
// The message is a response.
var response = Response.fromJson(message);
var response = Response.fromJson(message)!;
_handleResponse(response);
} else {
// The message is a notification.
@ -793,12 +792,12 @@ class Server {
.listen(handler);
}
installHandler(_process.stdout, _handleStdOut);
installHandler(_process.stderr, _handleStdErr);
installHandler(_process!.stdout, _handleStdOut);
installHandler(_process!.stderr, _handleStdErr);
}
/// Send a command to the server. An 'id' will be automatically assigned.
RequestData _send(String method, Map<String, dynamic> params) {
RequestData _send(String method, Map<String, dynamic>? params) {
var id = '${_nextId++}';
var requestData = RequestData(id, method, params, currentTime);
_requestDataMap[id] = requestData;
@ -807,7 +806,7 @@ class Server {
command['params'] = params;
}
var line = json.encode(command);
_process.stdin.add(utf8.encoder.convert('$line\n'));
_process!.stdin.add(utf8.encoder.convert('$line\n'));
logger?.log(fromClient, '$line');
return requestData;
}

View file

@ -2,8 +2,6 @@
// for details. 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.9
import 'dart:async';
import 'dart:io';
@ -31,17 +29,17 @@ void main(List<String> args) {
/// minor change inside a method body.
class SimpleTest extends TimingTest {
/// The path to the file in which code completion is to be performed.
String mainFilePath;
late String mainFilePath;
/// The original content of the file.
String originalContent;
late String originalContent;
/// The offset of the cursor when requesting code completion.
int cursorOffset;
late int cursorOffset;
/// A completer that will be completed when code completion results have been
/// received from the server.
Completer completionReceived;
late Completer completionReceived;
/// Initialize a newly created test.
SimpleTest();

View file

@ -2,8 +2,6 @@
// for details. 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.9
import 'dart:async';
import 'dart:io';
import 'dart:math';
@ -117,10 +115,10 @@ abstract class TimingTest extends IntegrationTestMixin {
/// The connection to the analysis server.
@override
Server server;
late Server server;
/// The temporary directory in which source files can be stored.
Directory sourceDirectory;
late Directory sourceDirectory;
/// A flag indicating whether the teardown process should skip sending a
/// "server.shutdown" request because the server is known to have already
@ -214,7 +212,7 @@ abstract class TimingTest extends IntegrationTestMixin {
/// Repeatedly execute this test [count] times, adding timing information to
/// the given list of [times] if it is non-`null`.
Future _repeat(int count, List<int> times) {
Future _repeat(int count, List<int>? times) {
var stopwatch = Stopwatch();
return setUp().then((_) {
stopwatch.start();

View file

@ -2,20 +2,17 @@
// for details. 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.9
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/instrumentation/service.dart';
/// Implementation of [InstrumentationService] that throws on [logException].
class TestInstrumentationService implements InstrumentationService {
@override
void logException(
exception, [
StackTrace stackTrace,
List<InstrumentationServiceAttachment> attachments = const [],
Object exception, [
StackTrace? stackTrace,
List<InstrumentationServiceAttachment>? attachments,
]) {
throw CaughtException(exception, stackTrace);
throw StateError('$exception\n\n$stackTrace');
}
@override

View file

@ -2,8 +2,6 @@
// for details. 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.9
/// These classes were copied from `analyzer`. They should be moved into the
/// `analyzer/lib/src/test_utilities` directory so that they can be shared.
/// (This version has been converted to a more modern style.)
@ -25,7 +23,7 @@ class ExpectedContextMessage {
final int length;
/// The message text for the error.
final String text;
final String? text;
ExpectedContextMessage(this.filePath, this.offset, this.length, {this.text});
@ -53,12 +51,13 @@ class ExpectedError {
/// The offset of the beginning of the error's region.
final int length;
/// The message text of the error or `null` if the message should not be checked.
final String message;
/// The message text of the error or `null` if the message should not be
/// checked.
final String? message;
/// A pattern that should be contained in the error message or `null` if the message
/// contents should not be checked.
final Pattern messageContains;
/// A pattern that should be contained in the error message or `null` if the
/// message contents should not be checked.
final Pattern? messageContains;
/// The list of context messages that are expected to be associated with the
/// error.
@ -81,8 +80,9 @@ class ExpectedError {
if (message != null && error.message != message) {
return false;
}
var messageContains = this.messageContains;
if (messageContains != null &&
error.message?.contains(messageContains) != true) {
error.message.contains(messageContains) != true) {
return false;
}
var contextMessages = error.contextMessages.toList();
@ -359,7 +359,7 @@ class GatheringErrorListener implements AnalysisErrorListener {
/// Return the line information associated with the given [source], or `null`
/// if no line information has been associated with the source.
LineInfo getLineInfo(Source source) => _lineInfoMap[source];
LineInfo? getLineInfo(Source source) => _lineInfoMap[source];
/// Return `true` if an error with the given [errorCode] has been gathered.
bool hasError(ErrorCode errorCode) {

View file

@ -94,7 +94,7 @@ class FileResolver {
@deprecated ByteStore byteStore,
SourceFactory sourceFactory,
String Function(String path) getFileDigest,
void Function(List<String> paths) prefetchFiles, {
void Function(List<String> paths)? prefetchFiles, {
required Workspace workspace,
@deprecated Duration? libraryContextResetTimeout,
}) : this.from(