analyze_once_test.dart 8.01 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:flutter_tools/src/base/common.dart';
import 'package:flutter_tools/src/base/file_system.dart';
9
import 'package:flutter_tools/src/base/platform.dart';
10 11 12 13 14 15
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/analyze.dart';
import 'package:flutter_tools/src/commands/create.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:test/test.dart';

16 17
import '../src/common.dart';
import '../src/context.dart';
18 19

void main() {
20 21
  final String analyzerSeparator = platform.isWindows ? '-' : '•';

22 23
  group('analyze once', () {
    Directory tempDir;
24
    String projectPath;
25 26 27 28 29
    File libMain;

    setUpAll(() {
      Cache.disableLocking();
      tempDir = fs.systemTempDirectory.createTempSync('analyze_once_test_').absolute;
30 31
      projectPath = fs.path.join(tempDir.path, 'flutter_project');
      libMain = fs.file(fs.path.join(projectPath, 'lib', 'main.dart'));
32 33 34
    });

    tearDownAll(() {
35 36 37 38 39 40
      try {
        tempDir?.deleteSync(recursive: true);
      } on FileSystemException catch (e) {
        // ignore errors deleting the temporary directory
        print('Ignored exception during tearDown: $e');
      }
41 42 43 44 45 46
    });

    // Create a project to be analyzed
    testUsingContext('flutter create', () async {
      await runCommand(
        command: new CreateCommand(),
47
        arguments: <String>['create', projectPath],
48 49 50 51 52 53
        statusTextContains: <String>[
          'All done!',
          'Your main program file is lib/main.dart',
        ],
      );
      expect(libMain.existsSync(), isTrue);
54
    }, timeout: allowForRemotePubInvocation);
55 56

    // Analyze in the current directory - no arguments
57
    testUsingContext('working directory', () async {
58
      await runCommand(
59
        command: new AnalyzeCommand(workingDirectory: fs.directory(projectPath)),
60 61 62
        arguments: <String>['analyze'],
        statusTextContains: <String>['No issues found!'],
      );
63
    }, timeout: const Timeout.factor(2.0));
64 65

    // Analyze a specific file outside the current directory
66
    testUsingContext('passing one file throws', () async {
67 68 69
      await runCommand(
        command: new AnalyzeCommand(),
        arguments: <String>['analyze', libMain.path],
70 71
        toolExit: true,
        exitMessageContains: 'is not a directory',
72 73 74 75
      );
    });

    // Analyze in the current directory - no arguments
76
    testUsingContext('working directory with errors', () async {
77
      // Break the code to produce the "The parameter 'onPressed' is required" hint
78 79 80 81 82 83
      // that is upgraded to a warning in package:flutter/analysis_options_user.yaml
      // to assert that we are using the default Flutter analysis options.
      // Also insert a statement that should not trigger a lint here
      // but will trigger a lint later on when an analysis_options.yaml is added.
      String source = await libMain.readAsString();
      source = source.replaceFirst(
84 85
        'onPressed: _incrementCounter,',
        '// onPressed: _incrementCounter,',
86 87 88 89 90 91 92
      );
      source = source.replaceFirst(
        '_counter++;',
        '_counter++; throw "an error message";',
      );
      await libMain.writeAsString(source);

93
      // Analyze in the current directory - no arguments
94
      await runCommand(
95
        command: new AnalyzeCommand(workingDirectory: fs.directory(projectPath)),
96 97 98
        arguments: <String>['analyze'],
        statusTextContains: <String>[
          'Analyzing',
99
          'warning $analyzerSeparator The parameter \'onPressed\' is required',
100
          'info $analyzerSeparator The method \'_incrementCounter\' isn\'t used',
101
          '2 issues found.',
102 103 104
        ],
        toolExit: true,
      );
105
    }, timeout: const Timeout.factor(2.0));
106 107

    // Analyze in the current directory - no arguments
108
    testUsingContext('working directory with local options', () async {
109 110
      // Insert an analysis_options.yaml file in the project
      // which will trigger a lint for broken code that was inserted earlier
111
      final File optionsFile = fs.file(fs.path.join(projectPath, 'analysis_options.yaml'));
112 113 114 115 116 117 118
      await optionsFile.writeAsString('''
  include: package:flutter/analysis_options_user.yaml
  linter:
    rules:
      - only_throw_errors
  ''');

119
      // Analyze in the current directory - no arguments
120
      await runCommand(
121
        command: new AnalyzeCommand(workingDirectory: fs.directory(projectPath)),
122 123 124
        arguments: <String>['analyze'],
        statusTextContains: <String>[
          'Analyzing',
125
          'warning $analyzerSeparator The parameter \'onPressed\' is required',
126 127
          'info $analyzerSeparator The method \'_incrementCounter\' isn\'t used',
          'info $analyzerSeparator Only throw instances of classes extending either Exception or Error',
128
          '3 issues found.',
129 130 131
        ],
        toolExit: true,
      );
132
    }, timeout: const Timeout.factor(2.0));
133

134
    testUsingContext('no duplicate issues', () async {
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
      final Directory tempDir = fs.systemTempDirectory.createTempSync('analyze_once_test_').absolute;

      try {
        final File foo = fs.file(fs.path.join(tempDir.path, 'foo.dart'));
        foo.writeAsStringSync('''
import 'bar.dart';

foo() => bar();
''');

        final File bar = fs.file(fs.path.join(tempDir.path, 'bar.dart'));
        bar.writeAsStringSync('''
import 'dart:async'; // unused

void bar() {
}
''');

        // Analyze in the current directory - no arguments
        await runCommand(
          command: new AnalyzeCommand(workingDirectory: tempDir),
          arguments: <String>['analyze'],
          statusTextContains: <String>[
            'Analyzing',
            '1 issue found.',
          ],
          toolExit: true,
        );
      } finally {
        tempDir.deleteSync(recursive: true);
      }
    });

168
    testUsingContext('--preview-dart-2', () async {
169
      const String contents = '''
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
StringBuffer bar = StringBuffer('baz');
''';

      final Directory tempDir = fs.systemTempDirectory.createTempSync();
      tempDir.childFile('main.dart').writeAsStringSync(contents);

      try {
        await runCommand(
          command: new AnalyzeCommand(workingDirectory: fs.directory(tempDir)),
          arguments: <String>['analyze', '--preview-dart-2'],
          statusTextContains: <String>['No issues found!'],
        );
      } finally {
        tempDir.deleteSync(recursive: true);
      }
    });

    testUsingContext('no --preview-dart-2 shows errors', () async {
188
      const String contents = '''
189 190 191 192 193 194 195 196 197
StringBuffer bar = StringBuffer('baz');
''';

      final Directory tempDir = fs.systemTempDirectory.createTempSync();
      tempDir.childFile('main.dart').writeAsStringSync(contents);

      try {
        await runCommand(
          command: new AnalyzeCommand(workingDirectory: fs.directory(tempDir)),
198
          arguments: <String>['analyze', '--no-preview-dart-2'],
199 200 201 202 203 204 205
          statusTextContains: <String>['1 issue found.'],
          toolExit: true,
        );
      } finally {
        tempDir.deleteSync(recursive: true);
      }
    });
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  });
}

void assertContains(String text, List<String> patterns) {
  if (patterns == null) {
    expect(text, isEmpty);
  } else {
    for (String pattern in patterns) {
      expect(text, contains(pattern));
    }
  }
}

Future<Null> runCommand({
  FlutterCommand command,
  List<String> arguments,
  List<String> statusTextContains,
  List<String> errorTextContains,
  bool toolExit: false,
225
  String exitMessageContains,
226 227 228 229 230
}) async {
  try {
    arguments.insert(0, '--flutter-root=${Cache.flutterRoot}');
    await createTestCommandRunner(command).run(arguments);
    expect(toolExit, isFalse, reason: 'Expected ToolExit exception');
231
  } on ToolExit catch (e) {
232 233 234 235
    if (!toolExit) {
      testLogger.clear();
      rethrow;
    }
236 237 238
    if (exitMessageContains != null) {
      expect(e.message, contains(exitMessageContains));
    }
239 240 241
  }
  assertContains(testLogger.statusText, statusTextContains);
  assertContains(testLogger.errorText, errorTextContains);
242

243 244
  testLogger.clear();
}