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

import 'dart:async';

7 8
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/common.dart';
9
import 'package:flutter_tools/src/cache.dart';
10
import 'package:mockito/mockito.dart';
11
import 'package:file/memory.dart';
12
import 'package:flutter_tools/src/base/file_system.dart';
13 14
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
15
import 'package:flutter_tools/src/base/platform.dart';
16
import 'package:flutter_tools/src/base/terminal.dart';
17
import 'package:flutter_tools/src/commands/analyze.dart';
18
import 'package:flutter_tools/src/dart/analysis.dart';
19
import 'package:flutter_tools/src/dart/pub.dart';
20
import 'package:flutter_tools/src/globals.dart' as globals;
21
import 'package:process/process.dart';
22

23 24
import '../../src/common.dart';
import '../../src/context.dart';
25 26

void main() {
27 28 29 30
  setUpAll(() {
    Cache.flutterRoot = getFlutterRoot();
  });

31 32
  AnalysisServer server;
  Directory tempDir;
33 34 35 36 37
  FileSystem fileSystem;
  Platform platform;
  ProcessManager processManager;
  AnsiTerminal terminal;
  Logger logger;
38 39

  setUp(() {
40
    fileSystem = LocalFileSystem.instance;
41 42 43 44 45
    platform = const LocalPlatform();
    processManager = const LocalProcessManager();
    terminal = AnsiTerminal(platform: platform, stdio: Stdio());
    logger = BufferLogger(outputPreferences: OutputPreferences.test(), terminal: terminal);
    tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_analysis_test.');
46 47 48
  });

  tearDown(() {
49
    tryToDelete(tempDir);
50 51 52
    return server?.dispose();
  });

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

  void _createSampleProject(Directory directory, { bool brokenCode = false }) {
    final File pubspecFile = fileSystem.file(fileSystem.path.join(directory.path, 'pubspec.yaml'));
    pubspecFile.writeAsStringSync('''
  name: foo_project
  ''');

    final File dartFile = fileSystem.file(fileSystem.path.join(directory.path, 'lib', 'main.dart'));
    dartFile.parent.createSync();
    dartFile.writeAsStringSync('''
  void main() {
    print('hello world');
    ${brokenCode ? 'prints("hello world");' : ''}
  }
  ''');
  }

70
  group('analyze --watch', () {
71 72
    testUsingContext('AnalysisServer success', () async {
      _createSampleProject(tempDir);
73

74 75 76 77 78 79 80 81
      final Pub pub = Pub(
        fileSystem: fileSystem,
        logger: logger,
        processManager: processManager,
        platform: const LocalPlatform(),
        botDetector: globals.botDetector,
        usage: globals.flutterUsage,
      );
82 83 84 85 86
      await pub.get(
        context: PubContext.flutterTests,
        directory: tempDir.path,
        generateSyntheticPackage: false,
      );
87

88 89 90
      server = AnalysisServer(
        globals.artifacts.getArtifactPath(Artifact.engineDartSdkPath),
        <String>[tempDir.path],
91 92 93 94 95
        fileSystem: fileSystem,
        platform: platform,
        processManager: processManager,
        logger: logger,
        terminal: terminal,
96
        experiments: <String>[],
97
      );
98 99 100 101

      int errorCount = 0;
      final Future<bool> onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first;
      server.onErrors.listen((FileAnalysisErrors errors) => errorCount += errors.errors.length);
102

103 104 105 106
      await server.start();
      await onDone;

      expect(errorCount, 0);
107
    });
108
  });
109

110 111 112
  testUsingContext('AnalysisServer errors', () async {
    _createSampleProject(tempDir, brokenCode: true);

113 114 115 116 117 118 119
    final Pub pub = Pub(
      fileSystem: fileSystem,
      logger: logger,
      processManager: processManager,
      platform: const LocalPlatform(),
      usage: globals.flutterUsage,
      botDetector: globals.botDetector,
120 121 122 123 124 125
      toolStampFile: globals.fs.file('test'),
    );
    await pub.get(
      context: PubContext.flutterTests,
      directory: tempDir.path,
      generateSyntheticPackage: false,
126
    );
127

128 129 130 131 132 133 134 135 136 137
      server = AnalysisServer(
        globals.artifacts.getArtifactPath(Artifact.engineDartSdkPath),
        <String>[tempDir.path],
        fileSystem: fileSystem,
        platform: platform,
        processManager: processManager,
        logger: logger,
        terminal: terminal,
        experiments: <String>[],
      );
138 139 140 141 142

    int errorCount = 0;
    final Future<bool> onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first;
    server.onErrors.listen((FileAnalysisErrors errors) {
      errorCount += errors.errors.length;
143
    });
144 145 146 147 148

    await server.start();
    await onDone;

    expect(errorCount, greaterThan(0));
149
  });
150

151
  testUsingContext('Returns no errors when source is error-free', () async {
152
    const String contents = "StringBuffer bar = StringBuffer('baz');";
153
    tempDir.childFile('main.dart').writeAsStringSync(contents);
154 155 156
    server = AnalysisServer(
      globals.artifacts.getArtifactPath(Artifact.engineDartSdkPath),
      <String>[tempDir.path],
157 158 159 160 161
      fileSystem: fileSystem,
      platform: platform,
      processManager: processManager,
      logger: logger,
      terminal: terminal,
162
      experiments: <String>[],
163
    );
164

165 166 167 168 169 170 171 172 173
    int errorCount = 0;
    final Future<bool> onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first;
    server.onErrors.listen((FileAnalysisErrors errors) {
      errorCount += errors.errors.length;
    });
    await server.start();
    await onDone;
    expect(errorCount, 0);
  });
174 175 176 177 178 179 180 181

  testWithoutContext('Can forward null-safety experiments to the AnalysisServer', () async {
    final Completer<void> completer = Completer<void>();
    final StreamController<List<int>> stdin = StreamController<List<int>>();
    const String fakeSdkPath = 'dart-sdk';
    final FakeCommand fakeCommand = FakeCommand(
      command: const <String>[
        'dart-sdk/bin/dart',
182
        '--disable-dart-dev',
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
        'dart-sdk/bin/snapshots/analysis_server.dart.snapshot',
        '--enable-experiment',
        'non-nullable',
        '--disable-server-feature-completion',
        '--disable-server-feature-search',
        '--sdk',
        'dart-sdk',
      ],
      completer: completer,
      stdin: IOSink(stdin.sink),
    );

    server = AnalysisServer(fakeSdkPath, <String>[''],
      fileSystem: MemoryFileSystem.test(),
      platform: FakePlatform(),
      processManager: FakeProcessManager.list(<FakeCommand>[
        fakeCommand,
      ]),
      logger: BufferLogger.test(),
      terminal: Terminal.test(),
      experiments: <String>[
        'non-nullable'
      ],
    );

    await server.start();
  });
210 211 212 213 214 215 216 217 218 219 220 221 222 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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

  testUsingContext('Can run AnalysisService with customized cache location', () async {
    final Completer<void> completer = Completer<void>();
    final StreamController<List<int>> stdin = StreamController<List<int>>();
    final FakeProcessManager processManager = FakeProcessManager.list(
      <FakeCommand>[
        FakeCommand(
          command: const <String>[
            'custom-dart-sdk/bin/dart',
            '--disable-dart-dev',
            'custom-dart-sdk/bin/snapshots/analysis_server.dart.snapshot',
            '--disable-server-feature-completion',
            '--disable-server-feature-search',
            '--sdk',
            'custom-dart-sdk',
          ],
          completer: completer,
          stdin: IOSink(stdin.sink),
        ),
      ]);

    final Artifacts artifacts = MockArtifacts();
    when(artifacts.getArtifactPath(Artifact.engineDartSdkPath))
      .thenReturn('custom-dart-sdk');

    final AnalyzeCommand command = AnalyzeCommand(
      terminal: Terminal.test(),
      artifacts: artifacts,
      logger: BufferLogger.test(),
      platform: FakePlatform(operatingSystem: 'linux'),
      fileSystem: MemoryFileSystem.test(),
      processManager: processManager,
    );

    final TestFlutterCommandRunner commandRunner = TestFlutterCommandRunner();
    commandRunner.addCommand(command);
    unawaited(commandRunner.run(<String>['analyze', '--watch']));
    await stdin.stream.first;

    expect(processManager.hasRemainingExpectations, false);
  });

  testUsingContext('Can run AnalysisService with customized cache location --watch', () async {
    final Completer<void> completer = Completer<void>();
    final StreamController<List<int>> stdin = StreamController<List<int>>();
    final FakeProcessManager processManager = FakeProcessManager.list(
      <FakeCommand>[
        FakeCommand(
          command: const <String>[
            'custom-dart-sdk/bin/dart',
            '--disable-dart-dev',
            'custom-dart-sdk/bin/snapshots/analysis_server.dart.snapshot',
            '--disable-server-feature-completion',
            '--disable-server-feature-search',
            '--sdk',
            'custom-dart-sdk',
          ],
          completer: completer,
          stdin: IOSink(stdin.sink),
        ),
      ]);

    final Artifacts artifacts = MockArtifacts();
    when(artifacts.getArtifactPath(Artifact.engineDartSdkPath))
      .thenReturn('custom-dart-sdk');

    final AnalyzeCommand command = AnalyzeCommand(
      terminal: Terminal.test(),
      artifacts: artifacts,
      logger: BufferLogger.test(),
      platform: FakePlatform(operatingSystem: 'linux'),
      fileSystem: MemoryFileSystem.test(),
      processManager: processManager,
    );

    final TestFlutterCommandRunner commandRunner = TestFlutterCommandRunner();
    commandRunner.addCommand(command);
    unawaited(commandRunner.run(<String>['analyze', '--watch']));
    await stdin.stream.first;

    expect(processManager.hasRemainingExpectations, false);
  });
292
}
293 294

class MockArtifacts extends Mock implements Artifacts {}