doctor_test.dart 37.8 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
// @dart = 2.8

7 8 9 10 11 12
// TODO(gspencergoog): Remove this tag once this test's state leaks/test
// dependencies have been fixed.
// https://github.com/flutter/flutter/issues/85160
// Fails with "flutter test --test-randomize-ordering-seed=20210723"
@Tags(<String>['no-shuffle'])

13 14
import 'dart:async';

15
import 'package:args/command_runner.dart';
16
import 'package:fake_async/fake_async.dart';
17
import 'package:file/memory.dart';
18
import 'package:flutter_tools/src/android/android_studio_validator.dart';
19
import 'package:flutter_tools/src/android/android_workflow.dart';
20
import 'package:flutter_tools/src/base/common.dart';
21
import 'package:flutter_tools/src/base/file_system.dart';
22
import 'package:flutter_tools/src/base/logger.dart';
23
import 'package:flutter_tools/src/base/platform.dart';
24
import 'package:flutter_tools/src/base/terminal.dart';
25
import 'package:flutter_tools/src/base/user_messages.dart';
26
import 'package:flutter_tools/src/build_info.dart';
27 28
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/doctor.dart';
29
import 'package:flutter_tools/src/device.dart';
30
import 'package:flutter_tools/src/doctor.dart';
31
import 'package:flutter_tools/src/doctor_validator.dart';
32
import 'package:flutter_tools/src/features.dart';
33
import 'package:flutter_tools/src/globals_null_migrated.dart' as globals;
34
import 'package:flutter_tools/src/reporting/reporting.dart';
35
import 'package:flutter_tools/src/version.dart';
36 37
import 'package:flutter_tools/src/vscode/vscode.dart';
import 'package:flutter_tools/src/vscode/vscode_validator.dart';
38
import 'package:flutter_tools/src/web/workflow.dart';
39
import 'package:test/fake.dart';
40

41 42
import '../../src/common.dart';
import '../../src/context.dart';
43
import '../../src/fakes.dart';
44
import '../../src/test_flutter_command_runner.dart';
45

46 47 48 49 50
final Platform macPlatform = FakePlatform(
  operatingSystem: 'macos',
  environment: <String, String>{'HOME': '/foo/bar'}
);

51
void main() {
52
  FakeFlutterVersion flutterVersion;
53
  BufferLogger logger;
54
  FakeProcessManager fakeProcessManager;
55 56

  setUp(() {
57
    flutterVersion = FakeFlutterVersion();
58
    logger = BufferLogger.test();
59
    fakeProcessManager = FakeProcessManager.empty();
60 61
  });

62 63 64 65 66 67 68 69 70 71
  testWithoutContext('ValidationMessage equality and hashCode includes contextUrl', () {
    const ValidationMessage messageA = ValidationMessage('ab', contextUrl: 'a');
    const ValidationMessage messageB = ValidationMessage('ab', contextUrl: 'b');

    expect(messageB, isNot(messageA));
    expect(messageB.hashCode, isNot(messageA.hashCode));
    expect(messageA, isNot(messageB));
    expect(messageA.hashCode, isNot(messageB.hashCode));
  });

72
  group('doctor', () {
73 74 75 76 77 78 79 80 81 82 83
    testUsingContext('vs code validator when both installed', () async {
      final ValidationResult result = await VsCodeValidatorTestTargets.installedWithExtension.validate();
      expect(result.type, ValidationType.installed);
      expect(result.statusInfo, 'version 1.2.3');
      expect(result.messages, hasLength(2));

      ValidationMessage message = result.messages
          .firstWhere((ValidationMessage m) => m.message.startsWith('VS Code '));
      expect(message.message, 'VS Code at ${VsCodeValidatorTestTargets.validInstall}');

      message = result.messages
84 85
          .firstWhere((ValidationMessage m) => m.message.startsWith('Flutter '));
      expect(message.message, 'Flutter extension version 4.5.6');
86
      expect(message.isError, isFalse);
87
    });
88

89 90 91 92 93 94 95 96
    testUsingContext('No IDE Validator includes expected installation messages', () async {
      final ValidationResult result = await NoIdeValidator().validate();
      expect(result.type, ValidationType.missing);

      expect(
        result.messages.map((ValidationMessage vm) => vm.message),
        UserMessages().noIdeInstallationInfo,
      );
97
    });
98

99 100 101 102 103 104 105 106 107 108 109 110
    testUsingContext('vs code validator when 64bit installed', () async {
      expect(VsCodeValidatorTestTargets.installedWithExtension64bit.title, 'VS Code, 64-bit edition');
      final ValidationResult result = await VsCodeValidatorTestTargets.installedWithExtension64bit.validate();
      expect(result.type, ValidationType.installed);
      expect(result.statusInfo, 'version 1.2.3');
      expect(result.messages, hasLength(2));

      ValidationMessage message = result.messages
          .firstWhere((ValidationMessage m) => m.message.startsWith('VS Code '));
      expect(message.message, 'VS Code at ${VsCodeValidatorTestTargets.validInstall}');

      message = result.messages
111 112
          .firstWhere((ValidationMessage m) => m.message.startsWith('Flutter '));
      expect(message.message, 'Flutter extension version 4.5.6');
113
    });
114

115 116
    testUsingContext('vs code validator when extension missing', () async {
      final ValidationResult result = await VsCodeValidatorTestTargets.installedWithoutExtension.validate();
117
      expect(result.type, ValidationType.installed);
118 119 120 121 122 123 124 125
      expect(result.statusInfo, 'version 1.2.3');
      expect(result.messages, hasLength(2));

      ValidationMessage message = result.messages
          .firstWhere((ValidationMessage m) => m.message.startsWith('VS Code '));
      expect(message.message, 'VS Code at ${VsCodeValidatorTestTargets.validInstall}');

      message = result.messages
126
          .firstWhere((ValidationMessage m) => m.message.startsWith('Flutter '));
127 128 129
      expect(message.message, startsWith('Flutter extension can be installed from'));
      expect(message.contextUrl, 'https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter');
      expect(message.isError, false);
130
    });
131 132 133

    group('device validator', () {
      testWithoutContext('no devices', () async {
134
        final FakeDeviceManager deviceManager = FakeDeviceManager();
135
        final DeviceValidator deviceValidator = DeviceValidator(
136
          deviceManager: deviceManager,
137 138 139 140 141 142 143 144 145 146 147
          userMessages: UserMessages(),
        );
        final ValidationResult result = await deviceValidator.validate();
        expect(result.type, ValidationType.notAvailable);
        expect(result.messages, const <ValidationMessage>[
          ValidationMessage.hint('No devices available'),
        ]);
        expect(result.statusInfo, isNull);
      });

      testWithoutContext('diagnostic message', () async {
148 149
        final FakeDeviceManager deviceManager = FakeDeviceManager()
          ..diagnostics = <String>['Device locked'];
150 151

        final DeviceValidator deviceValidator = DeviceValidator(
152
          deviceManager: deviceManager,
153 154 155 156 157 158 159 160 161 162 163
          userMessages: UserMessages(),
        );
        final ValidationResult result = await deviceValidator.validate();
        expect(result.type, ValidationType.notAvailable);
        expect(result.messages, const <ValidationMessage>[
          ValidationMessage.hint('Device locked'),
        ]);
        expect(result.statusInfo, isNull);
      });

      testWithoutContext('diagnostic message and devices', () async {
164 165 166 167
        final FakeDevice device = FakeDevice();
        final FakeDeviceManager deviceManager = FakeDeviceManager()
          ..devices = <Device>[device]
          ..diagnostics = <String>['Device locked'];
168 169

        final DeviceValidator deviceValidator = DeviceValidator(
170
          deviceManager: deviceManager,
171 172 173 174 175
          userMessages: UserMessages(),
        );
        final ValidationResult result = await deviceValidator.validate();
        expect(result.type, ValidationType.installed);
        expect(result.messages, const <ValidationMessage>[
176
          ValidationMessage('name (mobile) • device-id • android • 1.2.3'),
177 178 179 180 181
          ValidationMessage.hint('Device locked'),
        ]);
        expect(result.statusInfo, '1 available');
      });
    });
182
  });
183

Chris Bracken's avatar
Chris Bracken committed
184
  group('doctor with overridden validators', () {
185
    testUsingContext('validate non-verbose output format for run without issues', () async {
186
      final Doctor doctor = Doctor(logger: logger);
187
      expect(await doctor.diagnose(verbose: false), isTrue);
188
      expect(logger.statusText, equals(
189 190 191 192 193 194 195 196
              'Doctor summary (to see all details, run flutter doctor -v):\n'
              '[✓] Passing Validator (with statusInfo)\n'
              '[✓] Another Passing Validator (with statusInfo)\n'
              '[✓] Providing validators is fun (with statusInfo)\n'
              '\n'
              '• No issues found!\n'
      ));
    }, overrides: <Type, Generator>{
197
      DoctorValidatorsProvider: () => FakeDoctorValidatorsProvider(),
198 199 200
    });
  });

201
  group('doctor usage params', () {
202
    TestUsage testUsage;
203 204

    setUp(() {
205
      testUsage = TestUsage();
206 207 208
    });

    testUsingContext('contains installed', () async {
209
      final Doctor doctor = Doctor(logger: logger);
210 211
      await doctor.diagnose(verbose: false);

212 213 214
      expect(testUsage.events.length, 3);
      expect(testUsage.events, contains(
        const TestUsageEvent(
215 216
          'doctor-result',
          'PassingValidator',
217 218 219
          label: 'installed',
        ),
      ));
220 221
    }, overrides: <Type, Generator>{
      DoctorValidatorsProvider: () => FakeDoctorValidatorsProvider(),
222
      Usage: () => testUsage,
223 224 225
    });

    testUsingContext('contains installed and partial', () async {
226
      await FakePassingDoctor(logger).diagnose(verbose: false);
227

228 229
      expect(testUsage.events, unorderedEquals(<TestUsageEvent>[
        const TestUsageEvent(
230 231
          'doctor-result',
          'PassingValidator',
232 233 234 235 236 237 238 239
          label: 'installed',
        ),
        const TestUsageEvent(
          'doctor-result',
          'PassingValidator',
          label: 'installed',
        ),
        const TestUsageEvent(
240 241
          'doctor-result',
          'PartialValidatorWithHintsOnly',
242 243 244
          label: 'partial',
        ),
        const TestUsageEvent(
245 246
          'doctor-result',
          'PartialValidatorWithErrors',
247 248 249
          label: 'partial',
        ),
      ]));
250
    }, overrides: <Type, Generator>{
251
      Usage: () => testUsage,
252 253 254
    });

    testUsingContext('contains installed, missing and partial', () async {
255
      await FakeDoctor(logger).diagnose(verbose: false);
256

257 258
      expect(testUsage.events, unorderedEquals(<TestUsageEvent>[
        const TestUsageEvent(
259 260
          'doctor-result',
          'PassingValidator',
261 262 263
          label: 'installed',
        ),
        const TestUsageEvent(
264 265
          'doctor-result',
          'MissingValidator',
266 267 268
          label: 'missing',
        ),
        const TestUsageEvent(
269 270
          'doctor-result',
          'NotAvailableValidator',
271 272 273
          label: 'notAvailable',
        ),
        const TestUsageEvent(
274 275
          'doctor-result',
          'PartialValidatorWithHintsOnly',
276 277 278
          label: 'partial',
        ),
        const TestUsageEvent(
279 280
          'doctor-result',
          'PartialValidatorWithErrors',
281 282 283
          label: 'partial',
        ),
      ]));
284
    }, overrides: <Type, Generator>{
285
      Usage: () => testUsage,
286
    });
287 288

    testUsingContext('events for grouped validators are properly decomposed', () async {
289
      await FakeGroupedDoctor(logger).diagnose(verbose: false);
290

291 292
      expect(testUsage.events, unorderedEquals(<TestUsageEvent>[
        const TestUsageEvent(
293 294
          'doctor-result',
          'PassingGroupedValidator',
295 296 297 298 299 300 301 302 303 304 305 306 307
          label: 'installed',
        ),
        const TestUsageEvent(
          'doctor-result',
          'PassingGroupedValidator',
          label: 'installed',
        ),
        const TestUsageEvent(
          'doctor-result',
          'PassingGroupedValidator',
          label: 'installed',
        ),
        const TestUsageEvent(
308 309
          'doctor-result',
          'MissingGroupedValidator',
310 311 312
          label: 'missing',
        ),
      ]));
313
    }, overrides: <Type, Generator>{
314
      Usage: () => testUsage,
315
    });
316
  });
317

318
  group('doctor with fake validators', () {
319
    testUsingContext('validate non-verbose output format for run without issues', () async {
320 321
      expect(await FakeQuietDoctor(logger).diagnose(verbose: false), isTrue);
      expect(logger.statusText, equals(
322 323 324 325 326 327 328 329
              'Doctor summary (to see all details, run flutter doctor -v):\n'
              '[✓] Passing Validator (with statusInfo)\n'
              '[✓] Another Passing Validator (with statusInfo)\n'
              '[✓] Validators are fun (with statusInfo)\n'
              '[✓] Four score and seven validators ago (with statusInfo)\n'
              '\n'
              '• No issues found!\n'
      ));
330
    });
331

332
    testUsingContext('validate non-verbose output format for run with crash', () async {
333 334
      expect(await FakeCrashingDoctor(logger).diagnose(verbose: false), isFalse);
      expect(logger.statusText, equals(
335 336 337 338 339 340 341 342 343 344 345 346
              'Doctor summary (to see all details, run flutter doctor -v):\n'
              '[✓] Passing Validator (with statusInfo)\n'
              '[✓] Another Passing Validator (with statusInfo)\n'
              '[☠] Crashing validator (the doctor check crashed)\n'
              '    ✗ Due to an error, the doctor check did not complete. If the error message below is not helpful, '
              'please let us know about this issue at https://github.com/flutter/flutter/issues.\n'
              '    ✗ fatal error\n'
              '[✓] Validators are fun (with statusInfo)\n'
              '[✓] Four score and seven validators ago (with statusInfo)\n'
              '\n'
              '! Doctor found issues in 1 category.\n'
      ));
347
    });
348

349
    testUsingContext('validate verbose output format contains trace for run with crash', () async {
350 351
      expect(await FakeCrashingDoctor(logger).diagnose(verbose: true), isFalse);
      expect(logger.statusText, contains('#0      CrashingValidator.validate'));
352
    });
353

354 355 356 357

    testUsingContext('validate non-verbose output format for run with an async crash', () async {
      final Completer<void> completer = Completer<void>();
      await FakeAsync().run((FakeAsync time) {
358
        unawaited(FakeAsyncCrashingDoctor(time, logger).diagnose(verbose: false).then((bool r) {
359 360 361 362 363 364 365
          expect(r, isFalse);
          completer.complete(null);
        }));
        time.elapse(const Duration(seconds: 1));
        time.flushMicrotasks();
        return completer.future;
      });
366
      expect(logger.statusText, equals(
367 368 369 370 371 372 373 374 375 376 377 378
              'Doctor summary (to see all details, run flutter doctor -v):\n'
              '[✓] Passing Validator (with statusInfo)\n'
              '[✓] Another Passing Validator (with statusInfo)\n'
              '[☠] Async crashing validator (the doctor check crashed)\n'
              '    ✗ Due to an error, the doctor check did not complete. If the error message below is not helpful, '
              'please let us know about this issue at https://github.com/flutter/flutter/issues.\n'
              '    ✗ fatal error\n'
              '[✓] Validators are fun (with statusInfo)\n'
              '[✓] Four score and seven validators ago (with statusInfo)\n'
              '\n'
              '! Doctor found issues in 1 category.\n'
      ));
379
    });
380 381


382
    testUsingContext('validate non-verbose output format when only one category fails', () async {
383 384
      expect(await FakeSinglePassingDoctor(logger).diagnose(verbose: false), isTrue);
      expect(logger.statusText, equals(
385 386 387 388 389 390
              'Doctor summary (to see all details, run flutter doctor -v):\n'
              '[!] Partial Validator with only a Hint\n'
              '    ! There is a hint here\n'
              '\n'
              '! Doctor found issues in 1 category.\n'
      ));
391
    });
392 393

    testUsingContext('validate non-verbose output format for a passing run', () async {
394 395
      expect(await FakePassingDoctor(logger).diagnose(verbose: false), isTrue);
      expect(logger.statusText, equals(
396 397 398 399 400
              'Doctor summary (to see all details, run flutter doctor -v):\n'
              '[✓] Passing Validator (with statusInfo)\n'
              '[!] Partial Validator with only a Hint\n'
              '    ! There is a hint here\n'
              '[!] Partial Validator with Errors\n'
401
              '    ✗ An error message indicating partial installation\n'
402 403 404 405 406
              '    ! Maybe a hint will help the user\n'
              '[✓] Another Passing Validator (with statusInfo)\n'
              '\n'
              '! Doctor found issues in 2 categories.\n'
      ));
407
    });
408 409

    testUsingContext('validate non-verbose output format', () async {
410 411
      expect(await FakeDoctor(logger).diagnose(verbose: false), isFalse);
      expect(logger.statusText, equals(
412 413 414 415 416
              'Doctor summary (to see all details, run flutter doctor -v):\n'
              '[✓] Passing Validator (with statusInfo)\n'
              '[✗] Missing Validator\n'
              '    ✗ A useful error message\n'
              '    ! A hint message\n'
417 418 419
              '[!] Not Available Validator\n'
              '    ✗ A useful error message\n'
              '    ! A hint message\n'
420 421 422
              '[!] Partial Validator with only a Hint\n'
              '    ! There is a hint here\n'
              '[!] Partial Validator with Errors\n'
423
              '    ✗ An error message indicating partial installation\n'
424 425
              '    ! Maybe a hint will help the user\n'
              '\n'
426
              '! Doctor found issues in 4 categories.\n'
427
      ));
428
    });
429 430

    testUsingContext('validate verbose output format', () async {
431 432
      expect(await FakeDoctor(logger).diagnose(verbose: true), isFalse);
      expect(logger.statusText, equals(
433 434 435 436 437 438 439 440 441
              '[✓] Passing Validator (with statusInfo)\n'
              '    • A helpful message\n'
              '    • A second, somewhat longer helpful message\n'
              '\n'
              '[✗] Missing Validator\n'
              '    ✗ A useful error message\n'
              '    • A message that is not an error\n'
              '    ! A hint message\n'
              '\n'
442 443 444 445 446
              '[!] Not Available Validator\n'
              '    ✗ A useful error message\n'
              '    • A message that is not an error\n'
              '    ! A hint message\n'
              '\n'
447 448 449 450 451
              '[!] Partial Validator with only a Hint\n'
              '    ! There is a hint here\n'
              '    • But there is no error\n'
              '\n'
              '[!] Partial Validator with Errors\n'
452
              '    ✗ An error message indicating partial installation\n'
453 454 455
              '    ! Maybe a hint will help the user\n'
              '    • An extra message with some verbose details\n'
              '\n'
456
              '! Doctor found issues in 4 categories.\n'
457
      ));
458
    });
459
  });
460

461
  testUsingContext('validate non-verbose output wrapping', () async {
462 463 464 465 466
    final BufferLogger wrapLogger = BufferLogger.test(
      outputPreferences: OutputPreferences(wrapText: true, wrapColumn: 30),
    );
    expect(await FakeDoctor(wrapLogger).diagnose(verbose: false), isFalse);
    expect(wrapLogger.statusText, equals(
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
        'Doctor summary (to see all\n'
        'details, run flutter doctor\n'
        '-v):\n'
        '[✓] Passing Validator (with\n'
        '    statusInfo)\n'
        '[✗] Missing Validator\n'
        '    ✗ A useful error message\n'
        '    ! A hint message\n'
        '[!] Not Available Validator\n'
        '    ✗ A useful error message\n'
        '    ! A hint message\n'
        '[!] Partial Validator with\n'
        '    only a Hint\n'
        '    ! There is a hint here\n'
        '[!] Partial Validator with\n'
        '    Errors\n'
        '    ✗ An error message\n'
        '      indicating partial\n'
        '      installation\n'
        '    ! Maybe a hint will help\n'
        '      the user\n'
        '\n'
        '! Doctor found issues in 4\n'
        '  categories.\n'
    ));
  });

  testUsingContext('validate verbose output wrapping', () async {
495 496 497 498 499
    final BufferLogger wrapLogger = BufferLogger.test(
      outputPreferences: OutputPreferences(wrapText: true, wrapColumn: 30),
    );
    expect(await FakeDoctor(wrapLogger).diagnose(verbose: true), isFalse);
    expect(wrapLogger.statusText, equals(
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        '[✓] Passing Validator (with\n'
        '    statusInfo)\n'
        '    • A helpful message\n'
        '    • A second, somewhat\n'
        '      longer helpful message\n'
        '\n'
        '[✗] Missing Validator\n'
        '    ✗ A useful error message\n'
        '    • A message that is not an\n'
        '      error\n'
        '    ! A hint message\n'
        '\n'
        '[!] Not Available Validator\n'
        '    ✗ A useful error message\n'
        '    • A message that is not an\n'
        '      error\n'
        '    ! A hint message\n'
        '\n'
        '[!] Partial Validator with\n'
        '    only a Hint\n'
        '    ! There is a hint here\n'
        '    • But there is no error\n'
        '\n'
        '[!] Partial Validator with\n'
        '    Errors\n'
        '    ✗ An error message\n'
        '      indicating partial\n'
        '      installation\n'
        '    ! Maybe a hint will help\n'
        '      the user\n'
        '    • An extra message with\n'
        '      some verbose details\n'
        '\n'
        '! Doctor found issues in 4\n'
        '  categories.\n'
    ));
  });


539 540
  group('doctor with grouped validators', () {
    testUsingContext('validate diagnose combines validator output', () async {
541 542
      expect(await FakeGroupedDoctor(logger).diagnose(), isTrue);
      expect(logger.statusText, equals(
543 544 545 546 547 548 549 550 551 552
              '[✓] Category 1\n'
              '    • A helpful message\n'
              '    • A helpful message\n'
              '\n'
              '[!] Category 2\n'
              '    • A helpful message\n'
              '    ✗ A useful error message\n'
              '\n'
              '! Doctor found issues in 1 category.\n'
      ));
553
    });
554

555 556
    testUsingContext('validate merging assigns statusInfo and title', () async {
      // There are two subvalidators. Only the second contains statusInfo.
557 558
      expect(await FakeGroupedDoctorWithStatus(logger).diagnose(), isTrue);
      expect(logger.statusText, equals(
559 560 561
              '[✓] First validator title (A status message)\n'
              '    • A helpful message\n'
              '    • A different message\n'
562
              '\n'
563
              '• No issues found!\n'
564
      ));
565
    });
566 567
  });

568 569 570 571
  group('grouped validator merging results', () {
    final PassingGroupedValidator installed = PassingGroupedValidator('Category');
    final PartialGroupedValidator partial = PartialGroupedValidator('Category');
    final MissingGroupedValidator missing = MissingGroupedValidator('Category');
572 573

    testUsingContext('validate installed + installed = installed', () async {
574 575
      expect(await FakeSmallGroupDoctor(logger, installed, installed).diagnose(), isTrue);
      expect(logger.statusText, startsWith('[✓]'));
576
    });
577 578

    testUsingContext('validate installed + partial = partial', () async {
579 580
      expect(await FakeSmallGroupDoctor(logger, installed, partial).diagnose(), isTrue);
      expect(logger.statusText, startsWith('[!]'));
581
    });
582 583

    testUsingContext('validate installed + missing = partial', () async {
584 585
      expect(await FakeSmallGroupDoctor(logger, installed, missing).diagnose(), isTrue);
      expect(logger.statusText, startsWith('[!]'));
586
    });
587 588

    testUsingContext('validate partial + installed = partial', () async {
589 590
      expect(await FakeSmallGroupDoctor(logger, partial, installed).diagnose(), isTrue);
      expect(logger.statusText, startsWith('[!]'));
591
    });
592 593

    testUsingContext('validate partial + partial = partial', () async {
594 595
      expect(await FakeSmallGroupDoctor(logger, partial, partial).diagnose(), isTrue);
      expect(logger.statusText, startsWith('[!]'));
596
    });
597 598

    testUsingContext('validate partial + missing = partial', () async {
599 600
      expect(await FakeSmallGroupDoctor(logger, partial, missing).diagnose(), isTrue);
      expect(logger.statusText, startsWith('[!]'));
601
    });
602 603

    testUsingContext('validate missing + installed = partial', () async {
604 605
      expect(await FakeSmallGroupDoctor(logger, missing, installed).diagnose(), isTrue);
      expect(logger.statusText, startsWith('[!]'));
606
    });
607 608

    testUsingContext('validate missing + partial = partial', () async {
609 610
      expect(await FakeSmallGroupDoctor(logger, missing, partial).diagnose(), isTrue);
      expect(logger.statusText, startsWith('[!]'));
611
    });
612 613

    testUsingContext('validate missing + missing = missing', () async {
614 615
      expect(await FakeSmallGroupDoctor(logger, missing, missing).diagnose(), isFalse);
      expect(logger.statusText, startsWith('[✗]'));
616
    });
617
  });
618 619

  testUsingContext('WebWorkflow is a part of validator workflows if enabled', () async {
620 621
    expect(DoctorValidatorsProvider.defaultInstance.workflows,
      contains(isA<WebWorkflow>()));
622 623
  }, overrides: <Type, Generator>{
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
624
    FileSystem: () => MemoryFileSystem.test(),
625
    ProcessManager: () => fakeProcessManager,
626
  });
627 628 629 630 631 632 633 634 635

  testUsingContext('Fetches tags to get the right version', () async {
    Cache.disableLocking();

    final DoctorCommand doctorCommand = DoctorCommand();
    final CommandRunner<void> commandRunner = createTestCommandRunner(doctorCommand);

    await commandRunner.run(<String>['doctor']);

636
    expect(flutterVersion.didFetchTagsAndUpdate, true);
637 638 639 640
    Cache.enableLocking();
  }, overrides: <Type, Generator>{
    ProcessManager: () => FakeProcessManager.any(),
    FileSystem: () => MemoryFileSystem.test(),
641
    FlutterVersion: () => flutterVersion,
642 643
    Doctor: () => NoOpDoctor(),
  }, initializeFlutterRoot: false);
644 645 646 647 648 649 650

  testUsingContext('If android workflow is disabled, AndroidStudio validator is not included', () {
    expect(DoctorValidatorsProvider.defaultInstance.validators, isNot(contains(isA<AndroidStudioValidator>())));
    expect(DoctorValidatorsProvider.defaultInstance.validators, isNot(contains(isA<NoAndroidStudioValidator>())));
  }, overrides: <Type, Generator>{
    FeatureFlags: () => TestFeatureFlags(isAndroidEnabled: false),
  });
651 652 653 654 655 656 657 658 659 660 661 662 663
}

class NoOpDoctor implements Doctor {
  @override
  bool get canLaunchAnything => true;

  @override
  bool get canListAnything => true;

  @override
  Future<bool> checkRemoteArtifacts(String engineRevision) async => true;

  @override
664 665 666 667 668 669
  Future<bool> diagnose({
    bool androidLicenses = false,
    bool verbose = true,
    bool showColor = true,
    AndroidLicenseValidator androidLicenseValidator,
  }) async => true;
670 671 672 673 674 675 676 677 678 679 680 681

  @override
  List<ValidatorTask> startValidatorTasks() => <ValidatorTask>[];

  @override
  Future<void> summary() => null;

  @override
  List<DoctorValidator> get validators => <DoctorValidator>[];

  @override
  List<Workflow> get workflows => <Workflow>[];
682 683
}

684 685 686 687 688
class PassingValidator extends DoctorValidator {
  PassingValidator(String name) : super(name);

  @override
  Future<ValidationResult> validate() async {
689
    const List<ValidationMessage> messages = <ValidationMessage>[
690 691 692
      ValidationMessage('A helpful message'),
      ValidationMessage('A second, somewhat longer helpful message'),
    ];
693
    return const ValidationResult(ValidationType.installed, messages, statusInfo: 'with statusInfo');
694 695 696 697
  }
}

class MissingValidator extends DoctorValidator {
698
  MissingValidator() : super('Missing Validator');
699 700 701

  @override
  Future<ValidationResult> validate() async {
702
    const List<ValidationMessage> messages = <ValidationMessage>[
703 704 705 706
      ValidationMessage.error('A useful error message'),
      ValidationMessage('A message that is not an error'),
      ValidationMessage.hint('A hint message'),
    ];
707
    return const ValidationResult(ValidationType.missing, messages);
708 709 710
  }
}

711
class NotAvailableValidator extends DoctorValidator {
712
  NotAvailableValidator() : super('Not Available Validator');
713 714 715

  @override
  Future<ValidationResult> validate() async {
716
    const List<ValidationMessage> messages = <ValidationMessage>[
717 718 719 720
      ValidationMessage.error('A useful error message'),
      ValidationMessage('A message that is not an error'),
      ValidationMessage.hint('A hint message'),
    ];
721
    return const ValidationResult(ValidationType.notAvailable, messages);
722 723 724
  }
}

725 726 727 728 729
class PartialValidatorWithErrors extends DoctorValidator {
  PartialValidatorWithErrors() : super('Partial Validator with Errors');

  @override
  Future<ValidationResult> validate() async {
730
    const List<ValidationMessage> messages = <ValidationMessage>[
731 732 733 734
      ValidationMessage.error('An error message indicating partial installation'),
      ValidationMessage.hint('Maybe a hint will help the user'),
      ValidationMessage('An extra message with some verbose details'),
    ];
735
    return const ValidationResult(ValidationType.partial, messages);
736 737 738 739 740 741 742 743
  }
}

class PartialValidatorWithHintsOnly extends DoctorValidator {
  PartialValidatorWithHintsOnly() : super('Partial Validator with only a Hint');

  @override
  Future<ValidationResult> validate() async {
744
    const List<ValidationMessage> messages = <ValidationMessage>[
745 746 747
      ValidationMessage.hint('There is a hint here'),
      ValidationMessage('But there is no error'),
    ];
748
    return const ValidationResult(ValidationType.partial, messages);
749 750 751
  }
}

752 753 754 755 756 757 758 759 760
class CrashingValidator extends DoctorValidator {
  CrashingValidator() : super('Crashing validator');

  @override
  Future<ValidationResult> validate() async {
    throw 'fatal error';
  }
}

761 762 763 764 765 766 767 768
class AsyncCrashingValidator extends DoctorValidator {
  AsyncCrashingValidator(this._time) : super('Async crashing validator');

  final FakeAsync _time;

  @override
  Future<ValidationResult> validate() {
    const Duration delay = Duration(seconds: 1);
769 770 771 772
    final Future<ValidationResult> result = Future<ValidationResult>.delayed(delay)
      .then((_) {
        throw 'fatal error';
      });
773 774 775 776 777 778
    _time.elapse(const Duration(seconds: 1));
    _time.flushMicrotasks();
    return result;
  }
}

779 780
/// A doctor that fails with a missing [ValidationResult].
class FakeDoctor extends Doctor {
781 782
  FakeDoctor(Logger logger) : super(logger: logger);

783 784 785 786
  List<DoctorValidator> _validators;

  @override
  List<DoctorValidator> get validators {
787 788 789 790 791 792 793
    return _validators ??= <DoctorValidator>[
      PassingValidator('Passing Validator'),
      MissingValidator(),
      NotAvailableValidator(),
      PartialValidatorWithHintsOnly(),
      PartialValidatorWithErrors(),
    ];
794 795 796 797 798
  }
}

/// A doctor that should pass, but still has issues in some categories.
class FakePassingDoctor extends Doctor {
799 800
  FakePassingDoctor(Logger logger) : super(logger: logger);

801 802 803
  List<DoctorValidator> _validators;
  @override
  List<DoctorValidator> get validators {
804 805 806 807 808 809
    return _validators ??= <DoctorValidator>[
      PassingValidator('Passing Validator'),
      PartialValidatorWithHintsOnly(),
      PartialValidatorWithErrors(),
      PassingValidator('Another Passing Validator'),
    ];
810 811 812 813 814 815
  }
}

/// A doctor that should pass, but still has 1 issue to test the singular of
/// categories.
class FakeSinglePassingDoctor extends Doctor {
816 817
  FakeSinglePassingDoctor(Logger logger) : super(logger: logger);

818 819 820
  List<DoctorValidator> _validators;
  @override
  List<DoctorValidator> get validators {
821 822 823
    return _validators ??= <DoctorValidator>[
      PartialValidatorWithHintsOnly(),
    ];
824 825 826 827 828
  }
}

/// A doctor that passes and has no issues anywhere.
class FakeQuietDoctor extends Doctor {
829 830
  FakeQuietDoctor(Logger logger) : super(logger: logger);

831 832 833
  List<DoctorValidator> _validators;
  @override
  List<DoctorValidator> get validators {
834 835 836 837 838 839
    return _validators ??= <DoctorValidator>[
      PassingValidator('Passing Validator'),
      PassingValidator('Another Passing Validator'),
      PassingValidator('Validators are fun'),
      PassingValidator('Four score and seven validators ago'),
    ];
840
  }
841 842
}

843 844
/// A doctor with a validator that throws an exception.
class FakeCrashingDoctor extends Doctor {
845 846
  FakeCrashingDoctor(Logger logger) : super(logger: logger);

847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
  List<DoctorValidator> _validators;
  @override
  List<DoctorValidator> get validators {
    if (_validators == null) {
      _validators = <DoctorValidator>[];
      _validators.add(PassingValidator('Passing Validator'));
      _validators.add(PassingValidator('Another Passing Validator'));
      _validators.add(CrashingValidator());
      _validators.add(PassingValidator('Validators are fun'));
      _validators.add(PassingValidator('Four score and seven validators ago'));
    }
    return _validators;
  }
}

862 863
/// A doctor with a validator that throws an exception.
class FakeAsyncCrashingDoctor extends Doctor {
864
  FakeAsyncCrashingDoctor(this._time, Logger logger) : super(logger: logger);
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882

  final FakeAsync _time;

  List<DoctorValidator> _validators;
  @override
  List<DoctorValidator> get validators {
    if (_validators == null) {
      _validators = <DoctorValidator>[];
      _validators.add(PassingValidator('Passing Validator'));
      _validators.add(PassingValidator('Another Passing Validator'));
      _validators.add(AsyncCrashingValidator(_time));
      _validators.add(PassingValidator('Validators are fun'));
      _validators.add(PassingValidator('Four score and seven validators ago'));
    }
    return _validators;
  }
}

883 884 885 886 887 888
/// A DoctorValidatorsProvider that overrides the default validators without
/// overriding the doctor.
class FakeDoctorValidatorsProvider implements DoctorValidatorsProvider {
  @override
  List<DoctorValidator> get validators {
    return <DoctorValidator>[
889 890
      PassingValidator('Passing Validator'),
      PassingValidator('Another Passing Validator'),
891
      PassingValidator('Providing validators is fun'),
892 893
    ];
  }
894 895 896 897 898 899

  @override
  List<Workflow> get workflows => <Workflow>[];
}

class PassingGroupedValidator extends DoctorValidator {
900
  PassingGroupedValidator(String name) : super(name);
901 902 903

  @override
  Future<ValidationResult> validate() async {
904
    const List<ValidationMessage> messages = <ValidationMessage>[
905 906
      ValidationMessage('A helpful message'),
    ];
907
    return const ValidationResult(ValidationType.installed, messages);
908 909 910 911
  }
}

class MissingGroupedValidator extends DoctorValidator {
912
  MissingGroupedValidator(String name) : super(name);
913 914 915

  @override
  Future<ValidationResult> validate() async {
916
    const List<ValidationMessage> messages = <ValidationMessage>[
917 918
      ValidationMessage.error('A useful error message'),
    ];
919
    return const ValidationResult(ValidationType.missing, messages);
920 921 922 923
  }
}

class PartialGroupedValidator extends DoctorValidator {
924
  PartialGroupedValidator(String name) : super(name);
925 926 927

  @override
  Future<ValidationResult> validate() async {
928
    const List<ValidationMessage> messages = <ValidationMessage>[
929 930
      ValidationMessage.error('An error message for partial installation'),
    ];
931
    return const ValidationResult(ValidationType.partial, messages);
932 933 934
  }
}

935 936 937 938 939
class PassingGroupedValidatorWithStatus extends DoctorValidator {
  PassingGroupedValidatorWithStatus(String name) : super(name);

  @override
  Future<ValidationResult> validate() async {
940
    const List<ValidationMessage> messages = <ValidationMessage>[
941 942
      ValidationMessage('A different message'),
    ];
943
    return const ValidationResult(ValidationType.installed, messages, statusInfo: 'A status message');
944 945 946 947
  }
}

/// A doctor that has two groups of two validators each.
948
class FakeGroupedDoctor extends Doctor {
949 950
  FakeGroupedDoctor(Logger logger) : super(logger: logger);

951 952 953
  List<DoctorValidator> _validators;
  @override
  List<DoctorValidator> get validators {
954 955
    return _validators ??= <DoctorValidator>[
      GroupedValidator(<DoctorValidator>[
956
        PassingGroupedValidator('Category 1'),
957
        PassingGroupedValidator('Category 1'),
958 959
      ]),
      GroupedValidator(<DoctorValidator>[
960
        PassingGroupedValidator('Category 2'),
961
        MissingGroupedValidator('Category 2'),
962 963
      ]),
    ];
964 965 966
  }
}

967
class FakeGroupedDoctorWithStatus extends Doctor {
968 969
  FakeGroupedDoctorWithStatus(Logger logger) : super(logger: logger);

970 971 972
  List<DoctorValidator> _validators;
  @override
  List<DoctorValidator> get validators {
973
    return _validators ??= <DoctorValidator>[
974 975 976
      GroupedValidator(<DoctorValidator>[
        PassingGroupedValidator('First validator title'),
        PassingGroupedValidatorWithStatus('Second validator title'),
977 978
      ]),
    ];
979 980 981
  }
}

982 983 984
/// A doctor that takes any two validators. Used to check behavior when
/// merging ValidationTypes (installed, missing, partial).
class FakeSmallGroupDoctor extends Doctor {
985
  FakeSmallGroupDoctor(Logger logger, DoctorValidator val1, DoctorValidator val2) : super(logger: logger) {
986
    _validators = <DoctorValidator>[GroupedValidator(<DoctorValidator>[val1, val2])];
987
  }
988 989 990

  List<DoctorValidator> _validators;

991 992
  @override
  List<DoctorValidator> get validators => _validators;
993 994
}

995
class VsCodeValidatorTestTargets extends VsCodeValidator {
996
  VsCodeValidatorTestTargets._(String installDirectory, String extensionDirectory, {String edition})
997
    : super(VsCode.fromDirectory(installDirectory, extensionDirectory, edition: edition, fileSystem: globals.fs));
998 999

  static VsCodeValidatorTestTargets get installedWithExtension =>
1000
      VsCodeValidatorTestTargets._(validInstall, validExtensions);
1001

1002
  static VsCodeValidatorTestTargets get installedWithExtension64bit =>
1003
      VsCodeValidatorTestTargets._(validInstall, validExtensions, edition: '64-bit edition');
1004

1005
  static VsCodeValidatorTestTargets get installedWithoutExtension =>
1006
      VsCodeValidatorTestTargets._(validInstall, missingExtensions);
1007

1008 1009 1010
  static final String validInstall = globals.fs.path.join('test', 'data', 'vscode', 'application');
  static final String validExtensions = globals.fs.path.join('test', 'data', 'vscode', 'extensions');
  static final String missingExtensions = globals.fs.path.join('test', 'data', 'vscode', 'notExtensions');
1011
}
1012

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
class FakeDeviceManager extends Fake implements DeviceManager {
  List<String> diagnostics = <String>[];
  List<Device> devices = <Device>[];

  @override
  Future<List<Device>> getAllConnectedDevices() async => devices;

  @override
  Future<List<String>> getDeviceDiagnostics() async => diagnostics;
}

class FakeDevice extends Fake implements Device {
  @override
  String get name => 'name';

  @override
  String get id => 'device-id';

  @override
  Category get category => Category.mobile;

  @override
  bool isSupported() => true;

  @override
  Future<bool> get isLocalEmulator async => false;

  @override
  Future<String> get targetPlatformDisplayName async => 'android';

  @override
  Future<String> get sdkNameAndVersion async => '1.2.3';

  @override
  Future<TargetPlatform> get targetPlatform =>  Future<TargetPlatform>.value(TargetPlatform.android);
1048
}