analyze_once_test.dart 18.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:flutter_tools/src/base/error_handling_io.dart';
6
import 'package:flutter_tools/src/base/user_messages.dart';
7 8
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/artifacts.dart';
9 10
import 'package:flutter_tools/src/base/common.dart';
import 'package:flutter_tools/src/base/file_system.dart';
11 12
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
13
import 'package:flutter_tools/src/base/platform.dart';
14
import 'package:flutter_tools/src/base/terminal.dart';
15 16 17
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/analyze.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
18
import 'package:process/process.dart';
19

20 21
import '../../src/common.dart';
import '../../src/context.dart';
22

23
final Platform _kNoColorTerminalPlatform = FakePlatform(stdoutSupportsAnsi: false);
24

25
void main() {
26 27 28 29 30 31 32 33 34
  String analyzerSeparator;
  FileSystem fileSystem;
  Platform platform;
  BufferLogger logger;
  AnsiTerminal terminal;
  ProcessManager processManager;
  Directory tempDir;
  String projectPath;
  File libMain;
35
  Artifacts artifacts;
36 37 38 39 40 41 42 43

  Future<void> runCommand({
    FlutterCommand command,
    List<String> arguments,
    List<String> statusTextContains,
    List<String> errorTextContains,
    bool toolExit = false,
    String exitMessageContains,
44
    int exitCode = 0,
45 46 47 48 49 50 51 52
  }) async {
    try {
      await createTestCommandRunner(command).run(arguments);
      expect(toolExit, isFalse, reason: 'Expected ToolExit exception');
    } on ToolExit catch (e) {
      if (!toolExit) {
        testLogger.clear();
        rethrow;
53
      }
54 55
      if (exitMessageContains != null) {
        expect(e.message, contains(exitMessageContains));
56 57
        // May not analyzer exception the `exitCode` is `null`.
        expect(e.exitCode ?? 0, exitCode);
58 59 60 61 62 63 64 65
      }
    }
    assertContains(logger.statusText, statusTextContains);
    assertContains(logger.errorText, errorTextContains);

    logger.clear();
  }

66
  void _createDotPackages(String projectPath, [bool nullSafe = false]) {
67 68 69 70 71
    final StringBuffer flutterRootUri = StringBuffer('file://');
    final String canonicalizedFlutterRootPath = fileSystem.path.canonicalize(Cache.flutterRoot);
    if (platform.isWindows) {
      flutterRootUri
          ..write('/')
72
          ..write(canonicalizedFlutterRootPath.replaceAll(r'\', '/'));
73 74 75
    } else {
      flutterRootUri.write(canonicalizedFlutterRootPath);
    }
76
    final String dotPackagesSrc = '''
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
{
  "configVersion": 2,
  "packages": [
    {
      "name": "flutter",
      "rootUri": "$flutterRootUri/packages/flutter",
      "packageUri": "lib/",
      "languageVersion": "2.10"
    },
    {
      "name": "sky_engine",
      "rootUri": "$flutterRootUri/bin/cache/pkg/sky_engine",
      "packageUri": "lib/",
      "languageVersion": "2.10"
    },
    {
      "name": "flutter_project",
      "rootUri": "../",
      "packageUri": "lib/",
      "languageVersion": "${nullSafe ? "2.10" : "2.7"}"
    }
  ]
}
100
''';
101 102

    fileSystem.file(fileSystem.path.join(projectPath, '.dart_tool', 'package_config.json'))
103 104
      ..createSync(recursive: true)
      ..writeAsStringSync(dotPackagesSrc);
105
  }
106

107 108 109 110
  setUpAll(() {
    Cache.disableLocking();
    processManager = const LocalProcessManager();
    platform = const LocalPlatform();
111 112
    terminal = AnsiTerminal(platform: platform, stdio: Stdio());
    fileSystem = LocalFileSystem.instance;
113
    logger = BufferLogger.test();
114
    analyzerSeparator = platform.isWindows ? '-' : '•';
115 116 117 118 119
    artifacts = CachedArtifacts(
      cache: globals.cache,
      fileSystem: fileSystem,
      platform: platform,
    );
120 121 122 123 124
    Cache.flutterRoot = Cache.defaultFlutterRoot(
      fileSystem: fileSystem,
      platform: platform,
      userMessages: UserMessages(),
    );
125 126 127 128 129 130
  });

  setUp(() {
    tempDir = fileSystem.systemTempDirectory.createTempSync(
      'flutter_analyze_once_test_1.',
    ).absolute;
131 132 133 134 135 136 137 138 139
    projectPath = fileSystem.path.join(tempDir.path, 'flutter_project');
    fileSystem.file(fileSystem.path.join(projectPath, 'pubspec.yaml'))
        ..createSync(recursive: true)
        ..writeAsStringSync(pubspecYamlSrc);
    _createDotPackages(projectPath);
    libMain = fileSystem.file(fileSystem.path.join(projectPath, 'lib', 'main.dart'))
        ..createSync(recursive: true)
        ..writeAsStringSync(mainDartSrc);
  });
140

141
  tearDown(() {
142 143 144 145 146 147 148 149 150 151 152 153 154
    tryToDelete(tempDir);
  });

  // Analyze in the current directory - no arguments
  testUsingContext('working directory', () async {
    await runCommand(
      command: AnalyzeCommand(
        workingDirectory: fileSystem.directory(projectPath),
        fileSystem: fileSystem,
        logger: logger,
        platform: platform,
        processManager: processManager,
        terminal: terminal,
155
        artifacts: artifacts,
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
      ),
      arguments: <String>['analyze', '--no-pub'],
      statusTextContains: <String>['No issues found!'],
    );
  });

  // Analyze a specific file outside the current directory
  testUsingContext('passing one file throws', () async {
    await runCommand(
      command: AnalyzeCommand(
        platform: platform,
        fileSystem: fileSystem,
        logger: logger,
        processManager: processManager,
        terminal: terminal,
171
        artifacts: artifacts,
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
      ),
      arguments: <String>['analyze', '--no-pub', libMain.path],
      toolExit: true,
      exitMessageContains: 'is not a directory',
    );
  });

  // Analyze in the current directory - no arguments
  testUsingContext('working directory with errors', () async {
    // Break the code to produce the "Avoid empty else" 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(
      'return MaterialApp(',
      'if (debugPrintRebuildDirtyWidgets) {} else ; return MaterialApp(',
    );
    source = source.replaceFirst(
      'onPressed: _incrementCounter,',
      '// onPressed: _incrementCounter,',
    );
    source = source.replaceFirst(
        '_counter++;',
        '_counter++; throw "an error message";',
      );
    libMain.writeAsStringSync(source);

    // Analyze in the current directory - no arguments
    await runCommand(
      command: AnalyzeCommand(
        workingDirectory: fileSystem.directory(projectPath),
        platform: platform,
        fileSystem: fileSystem,
        logger: logger,
        processManager: processManager,
        terminal: terminal,
210
        artifacts: artifacts,
211 212 213 214 215 216 217
      ),
      arguments: <String>['analyze', '--no-pub'],
      statusTextContains: <String>[
        'Analyzing',
        'info $analyzerSeparator Avoid empty else statements',
        'info $analyzerSeparator Avoid empty statements',
        'info $analyzerSeparator The declaration \'_incrementCounter\' isn\'t',
218
        'warning $analyzerSeparator The parameter \'onPressed\' is required',
219
      ],
220
      exitMessageContains: '4 issues found.',
221
      toolExit: true,
222
      exitCode: 1,
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    );
  });

  // Analyze in the current directory - no arguments
  testUsingContext('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
    final File optionsFile = fileSystem.file(fileSystem.path.join(projectPath, 'analysis_options.yaml'));
    try {
      optionsFile.writeAsStringSync('''
  include: package:flutter/analysis_options_user.yaml
  linter:
    rules:
      - only_throw_errors
  ''');
      String source = libMain.readAsStringSync();
      source = source.replaceFirst(
        'onPressed: _incrementCounter,',
        '// onPressed: _incrementCounter,',
      );
      source = source.replaceFirst(
        '_counter++;',
        '_counter++; throw "an error message";',
      );
      libMain.writeAsStringSync(source);
248 249

      // Analyze in the current directory - no arguments
250 251 252 253 254 255 256 257
      await runCommand(
        command: AnalyzeCommand(
          workingDirectory: fileSystem.directory(projectPath),
          platform: platform,
          fileSystem: fileSystem,
          logger: logger,
          processManager: processManager,
          terminal: terminal,
258
          artifacts: artifacts,
259 260 261 262 263 264
        ),
        arguments: <String>['analyze', '--no-pub'],
        statusTextContains: <String>[
          'Analyzing',
          'info $analyzerSeparator The declaration \'_incrementCounter\' isn\'t',
          'info $analyzerSeparator Only throw instances of classes extending either Exception or Error',
265
          'warning $analyzerSeparator The parameter \'onPressed\' is required',
266
        ],
267
        exitMessageContains: '3 issues found.',
268
        toolExit: true,
269
        exitCode: 1,
270 271
      );
    } finally {
272
      ErrorHandlingFileSystem.deleteIfExists(optionsFile);
273 274 275 276 277 278 279 280 281 282
    }
  });

  testUsingContext('analyze once no duplicate issues', () async {
    final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_analyze_once_test_2.').absolute;
    _createDotPackages(tempDir.path);

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

285
void foo() => bar();
286 287
''');

288 289
      final File bar = fileSystem.file(fileSystem.path.join(tempDir.path, 'bar.dart'));
      bar.writeAsStringSync('''
290 291 292 293 294 295
import 'dart:async'; // unused

void bar() {
}
''');

296 297 298 299 300 301 302 303 304
      // Analyze in the current directory - no arguments
      await runCommand(
        command: AnalyzeCommand(
          workingDirectory: tempDir,
          platform: platform,
          fileSystem: fileSystem,
          logger: logger,
          processManager: processManager,
          terminal: terminal,
305
          artifacts: artifacts,
306 307 308 309 310 311 312
        ),
        arguments: <String>['analyze', '--no-pub'],
        statusTextContains: <String>[
          'Analyzing',
        ],
        exitMessageContains: '1 issue found.',
        toolExit: true,
313
        exitCode: 1
314 315 316 317 318
      );
    } finally {
      tryToDelete(tempDir);
    }
  });
319

320 321
  testUsingContext('analyze once returns no issues when source is error-free', () async {
    const String contents = '''
322 323
StringBuffer bar = StringBuffer('baz');
''';
324 325 326 327 328 329 330 331 332 333 334 335 336
    final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_analyze_once_test_3.');
    _createDotPackages(tempDir.path);

    tempDir.childFile('main.dart').writeAsStringSync(contents);
    try {
      await runCommand(
        command: AnalyzeCommand(
          workingDirectory: fileSystem.directory(tempDir),
          platform: _kNoColorTerminalPlatform,
          fileSystem: fileSystem,
          logger: logger,
          processManager: processManager,
          terminal: terminal,
337
          artifacts: artifacts,
338 339 340 341 342 343 344 345
        ),
        arguments: <String>['analyze', '--no-pub'],
        statusTextContains: <String>['No issues found!'],
      );
    } finally {
      tryToDelete(tempDir);
    }
  });
346

347 348
  testUsingContext('analyze once returns no issues for todo comments', () async {
    const String contents = '''
349 350 351
// TODO(foobar):
StringBuffer bar = StringBuffer('baz');
''';
352 353 354 355 356 357 358 359 360 361 362 363 364
    final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_analyze_once_test_4.');
    _createDotPackages(tempDir.path);

    tempDir.childFile('main.dart').writeAsStringSync(contents);
    try {
      await runCommand(
        command: AnalyzeCommand(
          workingDirectory: fileSystem.directory(tempDir),
          platform: _kNoColorTerminalPlatform,
          terminal: terminal,
          processManager: processManager,
          logger: logger,
          fileSystem: fileSystem,
365
          artifacts: artifacts,
366 367 368 369 370 371 372
        ),
        arguments: <String>['analyze', '--no-pub'],
        statusTextContains: <String>['No issues found!'],
      );
    } finally {
      tryToDelete(tempDir);
    }
373
  });
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520

  testUsingContext('analyze once with default options has info issue finally exit code 1.', () async {
    final Directory tempDir = fileSystem.systemTempDirectory.createTempSync(
        'flutter_analyze_once_default_options_info_issue_exit_code_1.');
    _createDotPackages(tempDir.path);

    const String infoSourceCode = '''
int analyze() {}
''';

    tempDir.childFile('main.dart').writeAsStringSync(infoSourceCode);
    try {
      await runCommand(
        command: AnalyzeCommand(
          workingDirectory: fileSystem.directory(tempDir),
          platform: _kNoColorTerminalPlatform,
          terminal: terminal,
          processManager: processManager,
          logger: logger,
          fileSystem: fileSystem,
          artifacts: artifacts,
        ),
        arguments: <String>['analyze', '--no-pub'],
        statusTextContains: <String>[
          'info',
          'missing_return',
        ],
        exitMessageContains: '1 issue found.',
        toolExit: true,
        exitCode: 1,
      );
    } finally {
      tryToDelete(tempDir);
    }
  });

  testUsingContext('analyze once with no-fatal-infos has info issue finally exit code 0.', () async {
    final Directory tempDir = fileSystem.systemTempDirectory.createTempSync(
        'flutter_analyze_once_no_fatal_infos_info_issue_exit_code_0.');
    _createDotPackages(tempDir.path);

    const String infoSourceCode = '''
int analyze() {}
''';

    tempDir.childFile('main.dart').writeAsStringSync(infoSourceCode);
    try {
      await runCommand(
        command: AnalyzeCommand(
          workingDirectory: fileSystem.directory(tempDir),
          platform: _kNoColorTerminalPlatform,
          terminal: terminal,
          processManager: processManager,
          logger: logger,
          fileSystem: fileSystem,
          artifacts: artifacts,
        ),
        arguments: <String>['analyze', '--no-pub', '--no-fatal-infos'],
        statusTextContains: <String>[
          'info',
          'missing_return',
        ],
        exitMessageContains: '1 issue found.',
        toolExit: true,
        exitCode: 0,
      );
    } finally {
      tryToDelete(tempDir);
    }
  });

  testUsingContext('analyze once only fatal-warnings has info issue finally exit code 0.', () async {
    final Directory tempDir = fileSystem.systemTempDirectory.createTempSync(
        'flutter_analyze_once_only_fatal_warnings_info_issue_exit_code_0.');
    _createDotPackages(tempDir.path);

    const String infoSourceCode = '''
int analyze() {}
''';

    tempDir.childFile('main.dart').writeAsStringSync(infoSourceCode);
    try {
      await runCommand(
        command: AnalyzeCommand(
          workingDirectory: fileSystem.directory(tempDir),
          platform: _kNoColorTerminalPlatform,
          terminal: terminal,
          processManager: processManager,
          logger: logger,
          fileSystem: fileSystem,
          artifacts: artifacts,
        ),
        arguments: <String>['analyze', '--no-pub', '--fatal-warnings', '--no-fatal-infos'],
        statusTextContains: <String>[
          'info',
          'missing_return',
        ],
        exitMessageContains: '1 issue found.',
        toolExit: true,
        exitCode: 0,
      );
    } finally {
      tryToDelete(tempDir);
    }
  });

  testUsingContext('analyze once only fatal-infos has warning issue finally exit code 1.', () async {
    final Directory tempDir = fileSystem.systemTempDirectory.createTempSync(
        'flutter_analyze_once_only_fatal_infos_warning_issue_exit_code_1.');
    _createDotPackages(tempDir.path);

    const String warningSourceCode = '''
int analyze() {}
''';

    final File optionsFile = fileSystem.file(fileSystem.path.join(tempDir.path, 'analysis_options.yaml'));
    optionsFile.writeAsStringSync('''
analyzer:
  errors:
    missing_return: warning
  ''');

    tempDir.childFile('main.dart').writeAsStringSync(warningSourceCode);
    try {
      await runCommand(
        command: AnalyzeCommand(
          workingDirectory: fileSystem.directory(tempDir),
          platform: _kNoColorTerminalPlatform,
          terminal: terminal,
          processManager: processManager,
          logger: logger,
          fileSystem: fileSystem,
          artifacts: artifacts,
        ),
        arguments: <String>['analyze','--no-pub', '--fatal-infos', '--no-fatal-warnings'],
        statusTextContains: <String>[
          'warning',
          'missing_return',
        ],
        exitMessageContains: '1 issue found.',
        toolExit: true,
        exitCode: 1,
      );
    } finally {
      tryToDelete(tempDir);
    }
  });
521 522 523
}

void assertContains(String text, List<String> patterns) {
524
  if (patterns != null) {
525
    for (final String pattern in patterns) {
526 527 528 529 530
      expect(text, contains(pattern));
    }
  }
}

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
const String mainDartSrc = r'''
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
582
              style: Theme.of(context).textTheme.headline4,
583 584 585 586 587 588 589 590 591 592 593 594 595 596
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
''';

597 598
const String pubspecYamlSrc = r'''
name: flutter_project
599 600 601 602 603 604 605
environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
''';