analyze_once_test.dart 8.83 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 22

  final String analyzerSeparator = platform.isWindows ? '-' : '•';

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

    setUpAll(() {
      Cache.disableLocking();
      tempDir = fs.systemTempDirectory.createTempSync('analyze_once_test_').absolute;
31 32
      projectPath = fs.path.join(tempDir.path, 'flutter_project');
      libMain = fs.file(fs.path.join(projectPath, 'lib', 'main.dart'));
33 34 35 36 37 38 39 40 41 42
    });

    tearDownAll(() {
      tempDir?.deleteSync(recursive: true);
    });

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

    // Analyze in the current directory - no arguments
    testUsingContext('flutter analyze working directory', () async {
      await runCommand(
55
        command: new AnalyzeCommand(workingDirectory: fs.directory(projectPath)),
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
        arguments: <String>['analyze'],
        statusTextContains: <String>['No issues found!'],
      );
    });

    // Analyze a specific file outside the current directory
    testUsingContext('flutter analyze one file', () async {
      await runCommand(
        command: new AnalyzeCommand(),
        arguments: <String>['analyze', libMain.path],
        statusTextContains: <String>['No issues found!'],
      );
    });

    // Analyze in the current directory - no arguments
    testUsingContext('flutter analyze working directory with errors', () async {

73
      // Break the code to produce the "The parameter 'onPressed' is required" hint
74 75 76 77 78 79
      // 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(
80 81
        'onPressed: _incrementCounter,',
        '// onPressed: _incrementCounter,',
82 83 84 85 86 87 88
      );
      source = source.replaceFirst(
        '_counter++;',
        '_counter++; throw "an error message";',
      );
      await libMain.writeAsString(source);

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

    // Analyze a specific file outside the current directory
    testUsingContext('flutter analyze one file with errors', () async {
      await runCommand(
        command: new AnalyzeCommand(),
        arguments: <String>['analyze', libMain.path],
        statusTextContains: <String>[
          'Analyzing',
110 111 112
          'warning $analyzerSeparator The parameter \'onPressed\' is required',
          'hint $analyzerSeparator The method \'_incrementCounter\' isn\'t used',
          '2 issues found.',
113 114 115 116 117 118 119 120 121 122
        ],
        toolExit: true,
      );
    });

    // Analyze in the current directory - no arguments
    testUsingContext('flutter analyze working directory with local options', () async {

      // Insert an analysis_options.yaml file in the project
      // which will trigger a lint for broken code that was inserted earlier
123
      final File optionsFile = fs.file(fs.path.join(projectPath, 'analysis_options.yaml'));
124 125 126 127 128 129 130
      await optionsFile.writeAsString('''
  include: package:flutter/analysis_options_user.yaml
  linter:
    rules:
      - only_throw_errors
  ''');

131
      // Analyze in the current directory - no arguments
132
      await runCommand(
133
        command: new AnalyzeCommand(workingDirectory: fs.directory(projectPath)),
134 135 136
        arguments: <String>['analyze'],
        statusTextContains: <String>[
          'Analyzing',
137 138
          'warning $analyzerSeparator The parameter \'onPressed\' is required',
          'hint $analyzerSeparator The method \'_incrementCounter\' isn\'t used',
139
          'lint $analyzerSeparator Only throw instances of classes extending either Exception or Error',
140
          '3 issues found.',
141 142 143 144 145
        ],
        toolExit: true,
      );
    });

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    testUsingContext('flutter analyze no duplicate issues', () async {
      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);
      }
    });

180 181 182 183 184 185 186
    // Analyze a specific file outside the current directory
    testUsingContext('flutter analyze one file with local options', () async {
      await runCommand(
        command: new AnalyzeCommand(),
        arguments: <String>['analyze', libMain.path],
        statusTextContains: <String>[
          'Analyzing',
187 188
          'warning $analyzerSeparator The parameter \'onPressed\' is required',
          'hint $analyzerSeparator The method \'_incrementCounter\' isn\'t used',
189
          'lint $analyzerSeparator Only throw instances of classes extending either Exception or Error',
190
          '3 issues found.',
191 192 193 194
        ],
        toolExit: true,
      );
    });
195 196

    testUsingContext('--preview-dart-2', () async {
197
      const String contents = '''
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
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 {
216
      const String contents = '''
217 218 219 220 221 222 223 224 225
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)),
226
          arguments: <String>['analyze', '--no-preview-dart-2'],
227 228 229 230 231 232 233
          statusTextContains: <String>['1 issue found.'],
          toolExit: true,
        );
      } finally {
        tempDir.deleteSync(recursive: true);
      }
    });
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  });
}

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,
}) async {
  try {
    arguments.insert(0, '--flutter-root=${Cache.flutterRoot}');
    await createTestCommandRunner(command).run(arguments);
    expect(toolExit, isFalse, reason: 'Expected ToolExit exception');
  } on ToolExit {
    if (!toolExit) {
      testLogger.clear();
      rethrow;
    }
  }
  assertContains(testLogger.statusText, statusTextContains);
  assertContains(testLogger.errorText, errorTextContains);
  testLogger.clear();
}