analyze_once_test.dart 7.23 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 50 51 52 53 54
        statusTextContains: <String>[
          'All done!',
          'Your main program file is lib/main.dart',
        ],
      );
      expect(libMain.existsSync(), isTrue);
    });

    // 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        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 {

      // Break the code to produce the "The parameter 'child' is required" hint
      // 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(
        'child: new Icon(Icons.add),',
        '// child: new Icon(Icons.add),',
      );
      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
          'warning $analyzerSeparator The parameter \'child\' is required',
96
          '1 issue found.',
97 98 99 100 101 102 103 104 105 106 107 108
        ],
        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',
109
          'warning $analyzerSeparator The parameter \'child\' is required',
110
          '1 issue found.',
111 112 113 114 115 116 117 118 119 120
        ],
        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
121
      final File optionsFile = fs.file(fs.path.join(projectPath, 'analysis_options.yaml'));
122 123 124 125 126 127 128
      await optionsFile.writeAsString('''
  include: package:flutter/analysis_options_user.yaml
  linter:
    rules:
      - only_throw_errors
  ''');

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

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 168 169 170 171 172 173 174 175 176
    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);
      }
    });

177 178 179 180 181 182 183
    // 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',
184 185
          'warning $analyzerSeparator The parameter \'child\' is required',
          'lint $analyzerSeparator Only throw instances of classes extending either Exception or Error',
186
          '2 issues found.',
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
        ],
        toolExit: true,
      );
    });
  });
}

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();
}