flutter_command_test.dart 14.3 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 6 7
import 'dart:async';
import 'dart:io' as io;

8
import 'package:flutter_tools/src/base/common.dart';
9
import 'package:flutter_tools/src/base/error_handling_file_system.dart';
10
import 'package:flutter_tools/src/base/io.dart';
11
import 'package:flutter_tools/src/base/signals.dart';
12 13 14
import 'package:flutter_tools/src/base/time.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
15
import 'package:flutter_tools/src/runner/flutter_command.dart';
16
import 'package:flutter_tools/src/version.dart';
17
import 'package:flutter_tools/src/globals.dart' as globals;
18 19
import 'package:mockito/mockito.dart';

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

24
void main() {
25
  group('Flutter Command', () {
26 27
    MockitoCache cache;
    MockitoUsage usage;
28
    MockClock clock;
29
    MockProcessInfo mockProcessInfo;
30
    List<int> mockTimes;
31 32

    setUp(() {
33 34
      cache = MockitoCache();
      usage = MockitoUsage();
35
      clock = MockClock();
36 37
      mockProcessInfo = MockProcessInfo();

38 39
      when(usage.isFirstRun).thenReturn(false);
      when(clock.now()).thenAnswer(
40
        (Invocation _) => DateTime.fromMillisecondsSinceEpoch(mockTimes.removeAt(0))
41
      );
42
      when(mockProcessInfo.maxRss).thenReturn(10);
43 44
    });

45 46 47 48 49 50
    testUsingContext('help text contains global options', () {
      final FakeCommand fake = FakeCommand();
      createTestCommandRunner(fake);
      expect(fake.usage, contains('Global options:\n'));
    });

51
    testUsingContext('honors shouldUpdateCache false', () async {
52
      final DummyFlutterCommand flutterCommand = DummyFlutterCommand(shouldUpdateCache: false);
53 54 55 56 57 58 59 60
      await flutterCommand.run();
      verifyZeroInteractions(cache);
    },
    overrides: <Type, Generator>{
      Cache: () => cache,
    });

    testUsingContext('honors shouldUpdateCache true', () async {
61
      final DummyFlutterCommand flutterCommand = DummyFlutterCommand(shouldUpdateCache: true);
62
      await flutterCommand.run();
63 64 65 66 67 68 69 70
      // First call for universal, second for the rest
      expect(
        verify(cache.updateAll(captureAny)).captured,
        <Set<DevelopmentArtifact>>[
          <DevelopmentArtifact>{DevelopmentArtifact.universal},
          <DevelopmentArtifact>{},
        ],
      );
71 72 73 74
    },
    overrides: <Type, Generator>{
      Cache: () => cache,
    });
75

76 77 78
    testUsingContext('uses the error handling file system', () async {
      final DummyFlutterCommand flutterCommand = DummyFlutterCommand(
        commandFunction: () async {
79
          expect(globals.fs, isA<ErrorHandlingFileSystem>());
80 81 82 83 84 85
          return const FlutterCommandResult(ExitStatus.success);
        }
      );
      await flutterCommand.run();
    });

86
    void testUsingCommandContext(String testName, dynamic Function() testBody) {
87 88 89 90 91 92 93 94
      testUsingContext(testName, testBody, overrides: <Type, Generator>{
        ProcessInfo: () => mockProcessInfo,
        SystemClock: () => clock,
        Usage: () => usage,
      });
    }

    testUsingCommandContext('reports command that results in success', () async {
95 96 97 98 99 100 101 102 103 104
      // Crash if called a third time which is unexpected.
      mockTimes = <int>[1000, 2000];

      final DummyFlutterCommand flutterCommand = DummyFlutterCommand(
        commandFunction: () async {
          return const FlutterCommandResult(ExitStatus.success);
        }
      );
      await flutterCommand.run();

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
      verify(usage.sendCommand(
        'dummy',
        parameters: anyNamed('parameters'),
      ));
      verify(usage.sendEvent(
        'tool-command-result',
        'dummy',
        label: 'success',
        parameters: anyNamed('parameters'),
      ));
      expect(verify(usage.sendEvent(
          'tool-command-max-rss',
          'dummy',
          label: 'success',
          value: captureAnyNamed('value'),
        )).captured[0],
        10,
      );
123 124
    });

125
    testUsingCommandContext('reports command that results in warning', () async {
126 127 128 129 130 131 132 133 134 135
      // Crash if called a third time which is unexpected.
      mockTimes = <int>[1000, 2000];

      final DummyFlutterCommand flutterCommand = DummyFlutterCommand(
        commandFunction: () async {
          return const FlutterCommandResult(ExitStatus.warning);
        }
      );
      await flutterCommand.run();

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
      verify(usage.sendCommand(
        'dummy',
        parameters: anyNamed('parameters'),
      ));
      verify(usage.sendEvent(
        'tool-command-result',
        'dummy',
        label: 'warning',
        parameters: anyNamed('parameters'),
      ));
      expect(verify(usage.sendEvent(
          'tool-command-max-rss',
          'dummy',
          label: 'warning',
          value: captureAnyNamed('value'),
        )).captured[0],
        10,
      );
154 155
    });

156
    testUsingCommandContext('reports command that results in failure', () async {
157 158 159 160 161 162 163 164 165 166 167 168
      // Crash if called a third time which is unexpected.
      mockTimes = <int>[1000, 2000];

      final DummyFlutterCommand flutterCommand = DummyFlutterCommand(
        commandFunction: () async {
          return const FlutterCommandResult(ExitStatus.fail);
        }
      );

      try {
        await flutterCommand.run();
      } on ToolExit {
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
        verify(usage.sendCommand(
          'dummy',
          parameters: anyNamed('parameters'),
        ));
        verify(usage.sendEvent(
          'tool-command-result',
          'dummy',
          label: 'fail',
          parameters: anyNamed('parameters'),
        ));
        expect(verify(usage.sendEvent(
            'tool-command-max-rss',
            'dummy',
            label: 'fail',
            value: captureAnyNamed('value'),
          )).captured[0],
          10,
        );
187 188 189
      }
    });

190
    testUsingCommandContext('reports command that results in error', () async {
191 192 193 194 195 196 197 198 199 200 201 202 203 204
      // Crash if called a third time which is unexpected.
      mockTimes = <int>[1000, 2000];

      final DummyFlutterCommand flutterCommand = DummyFlutterCommand(
        commandFunction: () async {
          throwToolExit('fail');
          return null; // unreachable
        }
      );

      try {
        await flutterCommand.run();
        fail('Mock should make this fail');
      } on ToolExit {
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        verify(usage.sendCommand(
          'dummy',
          parameters: anyNamed('parameters'),
        ));
        verify(usage.sendEvent(
          'tool-command-result',
          'dummy',
          label: 'fail',
          parameters: anyNamed('parameters'),
        ));
        expect(verify(usage.sendEvent(
            'tool-command-max-rss',
            'dummy',
            label: 'fail',
            value: captureAnyNamed('value'),
          )).captured[0],
          10,
        );
223 224 225
      }
    });

226 227 228 229 230 231 232 233
    test('FlutterCommandResult.success()', () async {
      expect(FlutterCommandResult.success().exitStatus, ExitStatus.success);
    });

    test('FlutterCommandResult.warning()', () async {
      expect(FlutterCommandResult.warning().exitStatus, ExitStatus.warning);
    });

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
    group('signals tests', () {
      MockIoProcessSignal mockSignal;
      ProcessSignal signalUnderTest;
      StreamController<io.ProcessSignal> signalController;

      setUp(() {
        mockSignal = MockIoProcessSignal();
        signalUnderTest = ProcessSignal(mockSignal);
        signalController = StreamController<io.ProcessSignal>();
        when(mockSignal.watch()).thenAnswer((Invocation invocation) => signalController.stream);
      });

      testUsingContext('reports command that is killed', () async {
        // Crash if called a third time which is unexpected.
        mockTimes = <int>[1000, 2000];

        final Completer<void> completer = Completer<void>();
        setExitFunctionForTests((int exitCode) {
          expect(exitCode, 0);
          restoreExitFunction();
          completer.complete();
        });

        final DummyFlutterCommand flutterCommand = DummyFlutterCommand(
          commandFunction: () async {
            final Completer<void> c = Completer<void>();
            await c.future;
            return null; // unreachable
          }
        );

        unawaited(flutterCommand.run());
        signalController.add(mockSignal);
        await completer.future;

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
        verify(usage.sendCommand(
          'dummy',
          parameters: anyNamed('parameters'),
        ));
        verify(usage.sendEvent(
          'tool-command-result',
          'dummy',
          label: 'killed',
          parameters: anyNamed('parameters'),
        ));
        expect(verify(usage.sendEvent(
            'tool-command-max-rss',
            'dummy',
            label: 'killed',
            value: captureAnyNamed('value'),
          )).captured[0],
          10,
        );
287 288 289 290 291 292 293 294 295
      }, overrides: <Type, Generator>{
        ProcessInfo: () => mockProcessInfo,
        Signals: () => FakeSignals(
          subForSigTerm: signalUnderTest,
          exitSignals: <ProcessSignal>[signalUnderTest],
        ),
        SystemClock: () => clock,
        Usage: () => usage,
      });
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

      testUsingContext('command release lock on kill signal', () async {
        mockTimes = <int>[1000, 2000];
        final Completer<void> completer = Completer<void>();
        setExitFunctionForTests((int exitCode) {
          expect(exitCode, 0);
          restoreExitFunction();
          completer.complete();
        });
        final Completer<void> checkLockCompleter = Completer<void>();
        final DummyFlutterCommand flutterCommand =
            DummyFlutterCommand(commandFunction: () async {
          await Cache.lock();
          checkLockCompleter.complete();
          final Completer<void> c = Completer<void>();
          await c.future;
          return null; // unreachable
        });

        unawaited(flutterCommand.run());
        await checkLockCompleter.future;

        Cache.checkLockAcquired();

        signalController.add(mockSignal);
        await completer.future;

        await Cache.lock();
        Cache.releaseLockEarly();
      }, overrides: <Type, Generator>{
        ProcessInfo: () => mockProcessInfo,
        Signals: () => FakeSignals(
              subForSigTerm: signalUnderTest,
              exitSignals: <ProcessSignal>[signalUnderTest],
            ),
        Usage: () => usage
      });
333 334
    });

335
    testUsingCommandContext('report execution timing by default', () async {
336 337 338
      // Crash if called a third time which is unexpected.
      mockTimes = <int>[1000, 2000];

339
      final DummyFlutterCommand flutterCommand = DummyFlutterCommand();
340 341 342 343
      await flutterCommand.run();
      verify(clock.now()).called(2);

      expect(
344
        verify(usage.sendTiming(
345
                captureAny, captureAny, captureAny,
346
                label: captureAnyNamed('label'))).captured,
347 348 349 350
        <dynamic>[
          'flutter',
          'dummy',
          const Duration(milliseconds: 1000),
351
          'fail',
352
        ],
353 354 355
      );
    });

356
    testUsingCommandContext('no timing report without usagePath', () async {
357 358 359
      // Crash if called a third time which is unexpected.
      mockTimes = <int>[1000, 2000];

360
      final DummyFlutterCommand flutterCommand =
361
          DummyFlutterCommand(noUsagePath: true);
362 363
      await flutterCommand.run();
      verify(clock.now()).called(2);
364
      verifyNever(usage.sendTiming(
365 366
                   any, any, any,
                   label: anyNamed('label')));
367
    });
368

369
    testUsingCommandContext('report additional FlutterCommandResult data', () async {
370 371 372
      // Crash if called a third time which is unexpected.
      mockTimes = <int>[1000, 2000];

373
      final FlutterCommandResult commandResult = FlutterCommandResult(
374
        ExitStatus.success,
375
        // nulls should be cleaned up.
376
        timingLabelParts: <String> ['blah1', 'blah2', null, 'blah3'],
377
        endTimeOverride: DateTime.fromMillisecondsSinceEpoch(1500),
378 379
      );

380
      final DummyFlutterCommand flutterCommand = DummyFlutterCommand(
381 382
        commandFunction: () async => commandResult
      );
383 384 385
      await flutterCommand.run();
      verify(clock.now()).called(2);
      expect(
386
        verify(usage.sendTiming(
387
                captureAny, captureAny, captureAny,
388
                label: captureAnyNamed('label'))).captured,
389
        <dynamic>[
390 391
          'flutter',
          'dummy',
392
          const Duration(milliseconds: 500), // FlutterCommandResult's end time used instead.
393
          'success-blah1-blah2-blah3',
394
        ],
395 396 397
      );
    });

398
    testUsingCommandContext('report failed execution timing too', () async {
399 400 401
      // Crash if called a third time which is unexpected.
      mockTimes = <int>[1000, 2000];

402
      final DummyFlutterCommand flutterCommand = DummyFlutterCommand(
403 404 405 406 407
        commandFunction: () async {
          throwToolExit('fail');
          return null; // unreachable
        },
      );
408 409 410 411 412 413 414 415 416

      try {
        await flutterCommand.run();
        fail('Mock should make this fail');
      } on ToolExit {
        // Should have still checked time twice.
        verify(clock.now()).called(2);

        expect(
417
          verify(usage.sendTiming(
418
                  captureAny, captureAny, captureAny,
419 420 421 422 423
                  label: captureAnyNamed('label'))).captured,
          <dynamic>[
            'flutter',
            'dummy',
            const Duration(milliseconds: 1000),
424 425
            'fail',
          ],
426 427
        );
      }
428
    });
429 430 431 432 433
  });
}

class FakeCommand extends FlutterCommand {
  @override
434
  String get description => 'A fake command';
435 436 437 438 439 440

  @override
  String get name => 'fake';

  @override
  Future<FlutterCommandResult> runCommand() async {
441
    return FlutterCommandResult.success();
442
  }
443
}
444 445

class MockVersion extends Mock implements FlutterVersion {}
446
class MockProcessInfo extends Mock implements ProcessInfo {}
447 448 449 450 451 452
class MockIoProcessSignal extends Mock implements io.ProcessSignal {}

class FakeSignals implements Signals {
  FakeSignals({
    this.subForSigTerm,
    List<ProcessSignal> exitSignals,
453
  }) : delegate = Signals.test(exitSignals: exitSignals);
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

  final ProcessSignal subForSigTerm;
  final Signals delegate;

  @override
  Object addHandler(ProcessSignal signal, SignalHandler handler) {
    if (signal == ProcessSignal.SIGTERM) {
      return delegate.addHandler(subForSigTerm, handler);
    }
    return delegate.addHandler(signal, handler);
  }

  @override
  Future<bool> removeHandler(ProcessSignal signal, Object token) =>
    delegate.removeHandler(signal, token);

  @override
  Stream<Object> get errors => delegate.errors;
}