Skip to content

Commit 27e819f

Browse files
srawlinsCommit Queue
authored and
Commit Queue
committed
linter: combine test classes into one
Work towards #55660 The only direct subclass of `_ContextResolutionTest` is `PubPackageResolutionTest`, so they can be combined. I keep all of the API the same, with a few exceptions: * Make `addTestFile`, `testFilePath`, `resolveTestFile` private. They were very lightly used outside of `rule_test_support.dart`, in exceptional situations, where they can be replaced with local members. * This allows for a much more idiomatic impl for `file_names_test.dart`. Change-Id: Icfa63ca488c4722067fc7d471343afd398a9dddc Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/428161 Reviewed-by: Brian Wilkerson <[email protected]> Commit-Queue: Samuel Rawlins <[email protected]>
1 parent 2ddf0c6 commit 27e819f

5 files changed

+123
-147
lines changed

pkg/linter/test/rule_test_support.dart

Lines changed: 109 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,21 @@ abstract class LintRuleTest extends PubPackageResolutionTest {
130130
);
131131
}
132132

133-
class PubPackageResolutionTest extends _ContextResolutionTest {
133+
class PubPackageResolutionTest with MockPackagesMixin, ResourceProviderMixin {
134+
static bool _lintRulesAreRegistered = false;
135+
136+
/// The byte store that is reused between tests. This allows reusing all
137+
/// unlinked and linked summaries for SDK, so that tests run much faster.
138+
/// However nothing is preserved between Dart VM runs, so changes to the
139+
/// implementation are still fully verified.
140+
static final MemoryByteStore _sharedByteStore = MemoryByteStore();
141+
142+
final MemoryByteStore _byteStore = _sharedByteStore;
143+
144+
AnalysisContextCollectionImpl? _analysisContextCollection;
145+
146+
late ResolvedUnitResult result;
147+
134148
final List<String> _lintRules = const [];
135149

136150
/// Adds the 'fixnum' package as a dependency to the package-under-test.
@@ -170,10 +184,17 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
170184
/// The list of language experiments to be enabled for these tests.
171185
List<String> get experiments => experimentsForTests;
172186

173-
String get testFileName => 'test.dart';
187+
/// Error codes that by default should be ignored in test expectations.
188+
List<DiagnosticCode> get ignoredErrorCodes => [
189+
WarningCode.UNUSED_LOCAL_VARIABLE,
190+
];
174191

192+
/// The path to the root of the external packages.
175193
@override
176-
String get testFilePath => '$testPackageLibPath/$testFileName';
194+
String get packagesRootPath => '/packages';
195+
196+
/// The name of the test file.
197+
String get testFileName => 'test.dart';
177198

178199
/// The language version for the package-under-test.
179200
///
@@ -189,9 +210,18 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
189210

190211
String get workspaceRootPath => '/home';
191212

192-
@override
193213
List<String> get _collectionIncludedPaths => [workspaceRootPath];
194214

215+
/// The diagnostics that were computed during analysis.
216+
List<Diagnostic> get _diagnostics =>
217+
result.errors
218+
.whereNot((e) => ignoredErrorCodes.any((c) => e.errorCode == c))
219+
.toList();
220+
221+
Folder get _sdkRoot => newFolder('/sdk');
222+
223+
String get _testFilePath => '$testPackageLibPath/$testFileName';
224+
195225
/// Asserts that the number of diagnostics reported in [content] matches the
196226
/// number of [expectedDiagnostics] and that they have the expected error
197227
/// descriptions and locations.
@@ -201,9 +231,9 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
201231
String content,
202232
List<ExpectedDiagnostic> expectedDiagnostics,
203233
) async {
204-
addTestFile(content);
205-
await resolveTestFile();
206-
await _assertDiagnosticsIn(_diagnostics, expectedDiagnostics);
234+
_addTestFile(content);
235+
await _resolveTestFile();
236+
_assertDiagnosticsIn(_diagnostics, expectedDiagnostics);
207237
}
208238

209239
/// Asserts that the number of diagnostics that have been gathered at [path]
@@ -216,7 +246,7 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
216246
List<ExpectedDiagnostic> expectedDiagnostics,
217247
) async {
218248
await _resolveFile(path);
219-
await _assertDiagnosticsIn(_diagnostics, expectedDiagnostics);
249+
_assertDiagnosticsIn(_diagnostics, expectedDiagnostics);
220250
}
221251

222252
/// Asserts that the diagnostics for each `path` match those in the paired
@@ -230,7 +260,7 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
230260
) async {
231261
for (var (path, expectedDiagnostics) in unitsAndDiagnostics) {
232262
result = await resolveFile(convertPath(path));
233-
await _assertDiagnosticsIn(result.errors, expectedDiagnostics);
263+
_assertDiagnosticsIn(result.errors, expectedDiagnostics);
234264
}
235265
}
236266

@@ -246,7 +276,7 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
246276
Future<void> assertNoPubspecDiagnostics(String content) async {
247277
newFile(testPackagePubspecPath, content);
248278
var errors = await _resolvePubspecFile(content);
249-
await _assertDiagnosticsIn(errors, []);
279+
_assertDiagnosticsIn(errors, []);
250280
}
251281

252282
/// Asserts that [expectedDiagnostics] are reported when resolving [content].
@@ -256,13 +286,36 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
256286
) async {
257287
newFile(testPackagePubspecPath, content);
258288
var errors = await _resolvePubspecFile(content);
259-
await _assertDiagnosticsIn(errors, expectedDiagnostics);
289+
_assertDiagnosticsIn(errors, expectedDiagnostics);
260290
}
261291

262292
@override
293+
File newFile(String path, String content) {
294+
if (_analysisContextCollection != null && !path.endsWith('.dart')) {
295+
throw StateError('Only dart files can be changed after analysis.');
296+
}
297+
298+
return super.newFile(path, content);
299+
}
300+
301+
/// Resolves a Dart source file at [path].
302+
///
303+
/// [path] must be converted for this file system.
304+
Future<ResolvedUnitResult> resolveFile(String path) async {
305+
var analysisContext = _contextFor(path);
306+
var session = analysisContext.currentSession;
307+
return await session.getResolvedUnit(path) as ResolvedUnitResult;
308+
}
309+
263310
@mustCallSuper
264311
void setUp() {
265-
super.setUp();
312+
if (!_lintRulesAreRegistered) {
313+
registerLintRules();
314+
_lintRulesAreRegistered = true;
315+
}
316+
317+
createMockSdk(resourceProvider: resourceProvider, root: _sdkRoot);
318+
266319
// Check for any needlessly enabled experiments.
267320
for (var experiment in experiments) {
268321
var feature = ExperimentStatus.knownFeatures[experiment];
@@ -282,6 +335,12 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
282335
_writeTestPackagePubspecYamlFile(pubspecYamlContent(name: 'test'));
283336
}
284337

338+
@mustCallSuper
339+
Future<void> tearDown() async {
340+
await _analysisContextCollection?.dispose();
341+
_analysisContextCollection = null;
342+
}
343+
285344
void writePackageConfig(String path, PackageConfigFileBuilder config) {
286345
newFile(path, config.toContent(toUriStr: toUriStr));
287346
}
@@ -335,11 +394,15 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
335394
writePackageConfig(path, configCopy);
336395
}
337396

397+
void _addTestFile(String content) {
398+
newFile(_testFilePath, content);
399+
}
400+
338401
/// Asserts that the diagnostics in [diagnostics] match [expectedDiagnostics].
339-
Future<void> _assertDiagnosticsIn(
402+
void _assertDiagnosticsIn(
340403
List<Diagnostic> diagnostics,
341404
List<ExpectedDiagnostic> expectedDiagnostics,
342-
) async {
405+
) {
343406
//
344407
// Match actual diagnostics to expected diagnostics.
345408
//
@@ -464,6 +527,36 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
464527
}
465528
}
466529

530+
DriverBasedAnalysisContext _contextFor(String path) {
531+
_createAnalysisContexts();
532+
533+
var convertedPath = convertPath(path);
534+
return _analysisContextCollection!.contextFor(convertedPath);
535+
}
536+
537+
/// Creates all analysis contexts in [_collectionIncludedPaths].
538+
void _createAnalysisContexts() {
539+
if (_analysisContextCollection != null) {
540+
return;
541+
}
542+
543+
_analysisContextCollection = AnalysisContextCollectionImpl(
544+
byteStore: _byteStore,
545+
declaredVariables: {},
546+
enableIndex: true,
547+
includedPaths: _collectionIncludedPaths.map(convertPath).toList(),
548+
resourceProvider: resourceProvider,
549+
sdkPath: _sdkRoot.path,
550+
);
551+
}
552+
553+
/// Resolves the file with the [path] into [result].
554+
Future<void> _resolveFile(String path) async {
555+
var convertedPath = convertPath(path);
556+
557+
result = await resolveFile(convertedPath);
558+
}
559+
467560
Future<List<Diagnostic>> _resolvePubspecFile(String content) async {
468561
var path = convertPath(testPackagePubspecPath);
469562
var pubspecRules = <AbstractAnalysisRule, PubspecVisitor<Object?>>{};
@@ -499,119 +592,13 @@ class PubPackageResolutionTest extends _ContextResolutionTest {
499592
return [...listener.errors];
500593
}
501594

595+
Future<void> _resolveTestFile() => _resolveFile(_testFilePath);
596+
502597
void _writeTestPackagePubspecYamlFile(String content) {
503598
newPubspecYamlFile(testPackageRootPath, content);
504599
}
505600
}
506601

507-
abstract class _ContextResolutionTest
508-
with MockPackagesMixin, ResourceProviderMixin {
509-
static bool _lintRulesAreRegistered = false;
510-
511-
/// The byte store that is reused between tests. This allows reusing all
512-
/// unlinked and linked summaries for SDK, so that tests run much faster.
513-
/// However nothing is preserved between Dart VM runs, so changes to the
514-
/// implementation are still fully verified.
515-
static final MemoryByteStore _sharedByteStore = MemoryByteStore();
516-
517-
final MemoryByteStore _byteStore = _sharedByteStore;
518-
519-
AnalysisContextCollectionImpl? _analysisContextCollection;
520-
521-
late ResolvedUnitResult result;
522-
523-
/// Error codes that by default should be ignored in test expectations.
524-
List<DiagnosticCode> get ignoredErrorCodes => [
525-
WarningCode.UNUSED_LOCAL_VARIABLE,
526-
];
527-
528-
/// The path to the root of the external packages.
529-
@override
530-
String get packagesRootPath => '/packages';
531-
532-
String get testFilePath;
533-
534-
List<String> get _collectionIncludedPaths;
535-
536-
/// The diagnostics that were computed during analysis.
537-
List<Diagnostic> get _diagnostics =>
538-
result.errors
539-
.whereNot((e) => ignoredErrorCodes.any((c) => e.errorCode == c))
540-
.toList();
541-
542-
Folder get _sdkRoot => newFolder('/sdk');
543-
544-
void addTestFile(String content) {
545-
newFile(testFilePath, content);
546-
}
547-
548-
@override
549-
File newFile(String path, String content) {
550-
if (_analysisContextCollection != null && !path.endsWith('.dart')) {
551-
throw StateError('Only dart files can be changed after analysis.');
552-
}
553-
554-
return super.newFile(path, content);
555-
}
556-
557-
/// Resolves a Dart source file at [path].
558-
///
559-
/// [path] must be converted for this file system.
560-
Future<ResolvedUnitResult> resolveFile(String path) async {
561-
var analysisContext = _contextFor(path);
562-
var session = analysisContext.currentSession;
563-
return await session.getResolvedUnit(path) as ResolvedUnitResult;
564-
}
565-
566-
Future<void> resolveTestFile() => _resolveFile(testFilePath);
567-
568-
@mustCallSuper
569-
void setUp() {
570-
if (!_lintRulesAreRegistered) {
571-
registerLintRules();
572-
_lintRulesAreRegistered = true;
573-
}
574-
575-
createMockSdk(resourceProvider: resourceProvider, root: _sdkRoot);
576-
}
577-
578-
@mustCallSuper
579-
Future<void> tearDown() async {
580-
await _analysisContextCollection?.dispose();
581-
_analysisContextCollection = null;
582-
}
583-
584-
DriverBasedAnalysisContext _contextFor(String path) {
585-
_createAnalysisContexts();
586-
587-
var convertedPath = convertPath(path);
588-
return _analysisContextCollection!.contextFor(convertedPath);
589-
}
590-
591-
/// Creates all analysis contexts in [_collectionIncludedPaths].
592-
void _createAnalysisContexts() {
593-
if (_analysisContextCollection != null) {
594-
return;
595-
}
596-
597-
_analysisContextCollection = AnalysisContextCollectionImpl(
598-
byteStore: _byteStore,
599-
declaredVariables: {},
600-
enableIndex: true,
601-
includedPaths: _collectionIncludedPaths.map(convertPath).toList(),
602-
resourceProvider: resourceProvider,
603-
sdkPath: _sdkRoot.path,
604-
);
605-
}
606-
607-
/// Resolves the file with the [path] into [result].
608-
Future<void> _resolveFile(String path) async {
609-
var convertedPath = convertPath(path);
610-
611-
result = await resolveFile(convertedPath);
612-
}
613-
}
614-
615602
/// A description of an expected error.
616603
final class _ExpectedError extends ExpectedDiagnostic {
617604
final DiagnosticCode _code;

pkg/linter/test/rules/always_use_package_imports_test.dart

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ class C {}
5353
/// This provides [C].
5454
import 'package:test/lib.dart';
5555
''');
56-
await resolveTestFile();
5756
await assertNoDiagnosticsInFile(bin.path);
5857
}
5958

pkg/linter/test/rules/file_names_test.dart

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,40 +8,29 @@ import '../rule_test_support.dart';
88

99
void main() {
1010
defineReflectiveSuite(() {
11-
defineReflectiveTests(FileNamesInvalidTest);
12-
defineReflectiveTests(FileNamesNonStrictTest);
11+
defineReflectiveTests(FileNamesTest);
1312
});
1413
}
1514

1615
@reflectiveTest
17-
class FileNamesInvalidTest extends LintRuleTest {
16+
class FileNamesTest extends LintRuleTest {
1817
@override
1918
String get lintRule => LintNames.file_names;
2019

21-
@override
22-
String get testFilePath => '$testPackageLibPath/a-test.dart';
23-
2420
test_invalidName() async {
25-
await assertDiagnostics(
26-
r'''
21+
var testFilePath = convertPath('$testPackageLibPath/a-test.dart');
22+
newFile(testFilePath, r'''
2723
class A { }
28-
''',
29-
[lint(0, 0)],
30-
);
31-
}
32-
}
33-
34-
@reflectiveTest
35-
class FileNamesNonStrictTest extends LintRuleTest {
36-
@override
37-
String get lintRule => LintNames.file_names;
24+
''');
3825

39-
@override
40-
String get testFilePath => '$testPackageLibPath/non-strict.css.dart';
26+
await assertDiagnosticsInFile(testFilePath, [lint(0, 0)]);
27+
}
4128

4229
test_validName() async {
43-
await assertNoDiagnostics(r'''
30+
var testFilePath = convertPath('$testPackageLibPath/non-strict.css.dart');
31+
newFile(testFilePath, r'''
4432
class A { }
4533
''');
34+
await assertNoDiagnosticsInFile(testFilePath);
4635
}
4736
}

pkg/linter/test/rules/prefer_relative_imports_test.dart

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@ class C {}
6666
/// This provides [C].
6767
import 'package:test/lib.dart';
6868
''');
69-
await resolveTestFile();
7069
await assertNoDiagnosticsInFile(bin.path);
7170
}
7271

0 commit comments

Comments
 (0)