vmservice_test.dart 34.1 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
import 'dart:async';

7
import 'package:fake_async/fake_async.dart';
8
import 'package:flutter_tools/src/base/io.dart' as io;
9
import 'package:flutter_tools/src/base/logger.dart';
10
import 'package:flutter_tools/src/convert.dart';
11
import 'package:flutter_tools/src/device.dart';
12 13
import 'package:flutter_tools/src/ios/xcodeproj.dart';
import 'package:flutter_tools/src/project.dart';
14
import 'package:flutter_tools/src/vmservice.dart';
15 16
import 'package:test/fake.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
17

18
import '../src/common.dart';
19
import '../src/context.dart' hide testLogger;
20
import '../src/fake_vm_services.dart';
21

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
const String kExtensionName = 'ext.flutter.test.interestingExtension';

final vm_service.Isolate isolate = vm_service.Isolate(
  id: '1',
  pauseEvent: vm_service.Event(
    kind: vm_service.EventKind.kResume,
    timestamp: 0
  ),
  breakpoints: <vm_service.Breakpoint>[],
  libraries: <vm_service.LibraryRef>[
    vm_service.LibraryRef(
      id: '1',
      uri: 'file:///hello_world/main.dart',
      name: '',
    ),
  ],
  livePorts: 0,
  name: 'test',
  number: '1',
  pauseOnExit: false,
  runnable: true,
  startTime: 0,
  isSystemIsolate: false,
  isolateFlags: <vm_service.IsolateFlag>[],
  extensionRPCs: <String>[kExtensionName],
47 48
);

49 50 51 52 53 54 55 56 57 58 59 60 61
final FlutterView fakeFlutterView = FlutterView(
  id: 'a',
  uiIsolate: isolate,
);

final FakeVmServiceRequest listViewsRequest = FakeVmServiceRequest(
  method: kListViewsMethod,
  jsonResponse: <String, Object>{
    'views': <Object>[
      fakeFlutterView.toJson(),
    ],
  },
);
62

63
void main() {
64
  testWithoutContext('VM Service registers reloadSources', () async {
65
    Future<void> reloadSources(String isolateId, { bool? pause, bool? force}) async {}
66

67
    final MockVMService mockVMService = MockVMService();
68
    await setUpVmService(
69 70
      reloadSources: reloadSources,
      vmService: mockVMService,
71 72
    );

73
    expect(mockVMService.services, containsPair(kReloadSourcesServiceName, kFlutterToolAlias));
74
  });
75

76
  testWithoutContext('VM Service registers flutterMemoryInfo service', () async {
77
    final FakeDevice mockDevice = FakeDevice();
78

79
    final MockVMService mockVMService = MockVMService();
80
    await setUpVmService(
81 82
      device: mockDevice,
      vmService: mockVMService,
83 84
    );

85
    expect(mockVMService.services, containsPair(kFlutterMemoryInfoServiceName, kFlutterToolAlias));
86
  });
87

88 89
  testWithoutContext('VmService registers flutterGetIOSBuildOptions service', () async {
    final MockVMService mockVMService = MockVMService();
90 91 92 93
    final FlutterProject mockedFlutterProject = MockFlutterProject();
    await setUpVmService(
      flutterProject: mockedFlutterProject,
      vmService: mockVMService,
94
    );
95 96 97 98 99 100 101

    expect(mockVMService.services, containsPair(kFlutterGetIOSBuildOptionsServiceName, kFlutterToolAlias));
  });

  testWithoutContext('VmService registers flutterGetAndroidBuildVariants service', () async {
    final MockVMService mockVMService = MockVMService();
    final FlutterProject mockedFlutterProject = MockFlutterProject();
102
    await setUpVmService(
103
      flutterProject: mockedFlutterProject,
104 105 106
      vmService: mockVMService,
    );

107
    expect(mockVMService.services, containsPair(kFlutterGetAndroidBuildVariantsServiceName, kFlutterToolAlias));
108 109
  });

110
  testWithoutContext('VM Service registers flutterGetSkSL service', () async {
111
    final MockVMService mockVMService = MockVMService();
112
    await setUpVmService(
113 114
      skSLMethod: () async => 'hello',
      vmService: mockVMService,
115 116
    );

117
    expect(mockVMService.services, containsPair(kFlutterGetSkSLServiceName, kFlutterToolAlias));
118 119
  });

120
  testWithoutContext('VM Service throws tool exit on service registration failure.', () async {
121 122 123 124
    final MockVMService mockVMService = MockVMService()
      ..errorOnRegisterService = true;

    await expectLater(() async => setUpVmService(
125 126
      skSLMethod: () async => 'hello',
      vmService: mockVMService,
127 128 129
    ), throwsToolExit());
  });

130
  testWithoutContext('VM Service throws tool exit on service registration failure with awaited future.', () async {
131 132 133 134
    final MockVMService mockVMService = MockVMService()
      ..errorOnRegisterService = true;

    await expectLater(() async => setUpVmService(
135 136 137
      skSLMethod: () async => 'hello',
      printStructuredErrorLogMethod: (vm_service.Event event) { },
      vmService: mockVMService,
138
    ), throwsToolExit());
139 140
  });

141
  testWithoutContext('VM Service registers flutterPrintStructuredErrorLogMethod', () async {
142
    final MockVMService mockVMService = MockVMService();
143
    await setUpVmService(
144 145
      printStructuredErrorLogMethod: (vm_service.Event event) async => 'hello',
      vmService: mockVMService,
146
    );
147
    expect(mockVMService.listenedStreams, contains(vm_service.EventStreams.kExtension));
148 149
  });

150
  testWithoutContext('VM Service returns correct FlutterVersion', () async {
151
    final MockVMService mockVMService = MockVMService();
152
    await setUpVmService(
153
      vmService: mockVMService,
154 155
    );

156
    expect(mockVMService.services, containsPair(kFlutterVersionServiceName, kFlutterToolAlias));
157
  });
158

159
  testUsingContext('VM Service prints messages for connection failures', () {
160
    final BufferLogger logger = BufferLogger.test();
161 162
    FakeAsync().run((FakeAsync time) {
      final Uri uri = Uri.parse('ws://127.0.0.1:12345/QqL7EFEDNG0=/ws');
163
      unawaited(connectToVmService(uri, logger: logger));
164 165

      time.elapse(const Duration(seconds: 5));
166
      expect(logger.statusText, isEmpty);
167 168 169

      time.elapse(const Duration(minutes: 2));

170
      final String statusText = logger.statusText;
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
      expect(
        statusText,
        containsIgnoringWhitespace('Connecting to the VM Service is taking longer than expected...'),
      );
      expect(
        statusText,
        containsIgnoringWhitespace('try re-running with --host-vmservice-port'),
      );
      expect(
        statusText,
        containsIgnoringWhitespace('Exception attempting to connect to the VM Service:'),
      );
      expect(
        statusText,
        containsIgnoringWhitespace('This was attempt #50. Will retry'),
      );
    });
  }, overrides: <Type, Generator>{
    WebSocketConnector: () => failingWebSocketConnector,
  });

192 193 194 195 196 197
  testWithoutContext('setAssetDirectory forwards arguments correctly', () async {
    final Completer<String> completer = Completer<String>();
    final vm_service.VmService  vmService = vm_service.VmService(
      const Stream<String>.empty(),
      completer.complete,
    );
198
    final FlutterVmService flutterVmService = FlutterVmService(vmService);
199

200
    unawaited(flutterVmService.setAssetDirectory(
201 202 203
      assetsDirectory: Uri(path: 'abc', scheme: 'file'),
      viewId: 'abc',
      uiIsolateId: 'def',
204
      windows: false,
205 206
    ));

207
    final Map<String, Object?>? rawRequest = json.decode(await completer.future) as Map<String, Object?>?;
208 209 210 211 212 213 214

    expect(rawRequest, allOf(<Matcher>[
      containsPair('method', kSetAssetBundlePathMethod),
      containsPair('params', allOf(<Matcher>[
        containsPair('viewId', 'abc'),
        containsPair('assetDirectory', '/abc'),
        containsPair('isolateId', 'def'),
215
      ])),
216 217 218
    ]));
  });

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  testWithoutContext('setAssetDirectory forwards arguments correctly - windows', () async {
    final Completer<String> completer = Completer<String>();
    final vm_service.VmService  vmService = vm_service.VmService(
      const Stream<String>.empty(),
      completer.complete,
    );
    final FlutterVmService flutterVmService = FlutterVmService(vmService);
    unawaited(flutterVmService.setAssetDirectory(
      assetsDirectory: Uri(path: 'C:/Users/Tester/AppData/Local/Temp/hello_worldb42a6da5/hello_world/build/flutter_assets', scheme: 'file'),
      viewId: 'abc',
      uiIsolateId: 'def',
      // If windows is not set to `true`, then the file path below is incorrectly prepended with a `/` which
      // causes the engine asset manager to interpret the file scheme as invalid.
      windows: true,
    ));

235
    final Map<String, Object?>? rawRequest = json.decode(await completer.future) as Map<String, Object?>?;
236 237 238 239 240 241 242 243 244 245 246

    expect(rawRequest, allOf(<Matcher>[
      containsPair('method', kSetAssetBundlePathMethod),
      containsPair('params', allOf(<Matcher>[
        containsPair('viewId', 'abc'),
        containsPair('assetDirectory', r'C:\Users\Tester\AppData\Local\Temp\hello_worldb42a6da5\hello_world\build\flutter_assets'),
        containsPair('isolateId', 'def'),
      ])),
    ]));
  });

247 248 249 250 251 252
  testWithoutContext('getSkSLs forwards arguments correctly', () async {
    final Completer<String> completer = Completer<String>();
    final vm_service.VmService  vmService = vm_service.VmService(
      const Stream<String>.empty(),
      completer.complete,
    );
253
    final FlutterVmService flutterVmService = FlutterVmService(vmService);
254

255
    unawaited(flutterVmService.getSkSLs(
256 257 258
      viewId: 'abc',
    ));

259
    final Map<String, Object?>? rawRequest = json.decode(await completer.future) as Map<String, Object?>?;
260 261 262 263 264

    expect(rawRequest, allOf(<Matcher>[
      containsPair('method', kGetSkSLsMethod),
      containsPair('params', allOf(<Matcher>[
        containsPair('viewId', 'abc'),
265
      ])),
266 267 268 269 270
    ]));
  });

  testWithoutContext('flushUIThreadTasks forwards arguments correctly', () async {
    final Completer<String> completer = Completer<String>();
271
    final vm_service.VmService vmService = vm_service.VmService(
272 273 274
      const Stream<String>.empty(),
      completer.complete,
    );
275
    final FlutterVmService flutterVmService = FlutterVmService(vmService);
276

277
    unawaited(flutterVmService.flushUIThreadTasks(
278 279 280
      uiIsolateId: 'def',
    ));

281
    final Map<String, Object?>? rawRequest = json.decode(await completer.future) as Map<String, Object?>?;
282 283 284 285 286

    expect(rawRequest, allOf(<Matcher>[
      containsPair('method', kFlushUIThreadTasksMethod),
      containsPair('params', allOf(<Matcher>[
        containsPair('isolateId', 'def'),
287
      ])),
288 289
    ]));
  });
290

291 292 293 294 295 296 297 298
  testWithoutContext('VmService forward flutterGetIOSBuildOptions request and response correctly', () async {
    final MockVMService vmService = MockVMService();
    final XcodeProjectInfo expectedProjectInfo = XcodeProjectInfo(
      <String>['target1', 'target2'],
      <String>['config1', 'config2'],
      <String>['scheme1', 'scheme2'],
      MockLogger(),
    );
299
    final FlutterProject mockedFlutterProject = MockFlutterProject(
300 301 302
      mockedIos: MockIosProject(mockedInfo: expectedProjectInfo),
    );
    await setUpVmService(
303
      flutterProject: mockedFlutterProject,
304 305
      vmService: vmService
    );
306
    final vm_service.ServiceCallback cb = vmService.serviceCallBacks[kFlutterGetIOSBuildOptionsServiceName]!;
307 308 309 310 311 312 313 314 315

    final Map<String, dynamic> response = await cb(<String, dynamic>{});
    final Map<String, dynamic> result = response['result']! as Map<String, dynamic>;
    expect(result[kResultType], kResultTypeSuccess);
    expect(result['targets'], expectedProjectInfo.targets);
    expect(result['buildConfigurations'], expectedProjectInfo.buildConfigurations);
    expect(result['schemes'], expectedProjectInfo.schemes);
  });

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  testWithoutContext('VmService forward flutterGetAndroidBuildVariants request and response correctly', () async {
    final MockVMService vmService = MockVMService();
    final List<String> expectedOptions = <String>['debug', 'release', 'profile'];
    final FlutterProject mockedFlutterProject = MockFlutterProject(
      mockedAndroid: MockAndroidProject(mockedOptions: expectedOptions),
    );
    await setUpVmService(
        flutterProject: mockedFlutterProject,
        vmService: vmService
    );
    final vm_service.ServiceCallback cb = vmService.serviceCallBacks[kFlutterGetAndroidBuildVariantsServiceName]!;

    final Map<String, dynamic> response = await cb(<String, dynamic>{});
    final Map<String, dynamic> result = response['result']! as Map<String, dynamic>;
    expect(result[kResultType], kResultTypeSuccess);
    expect(result['variants'], expectedOptions);
  });

334 335
  testWithoutContext('VmService forward flutterGetIOSBuildOptions request and response correctly when no iOS project', () async {
    final MockVMService vmService = MockVMService();
336
    final FlutterProject mockedFlutterProject = MockFlutterProject(
337 338 339
      mockedIos: MockIosProject(),
    );
    await setUpVmService(
340
        flutterProject: mockedFlutterProject,
341 342
        vmService: vmService
    );
343
    final vm_service.ServiceCallback cb = vmService.serviceCallBacks[kFlutterGetIOSBuildOptionsServiceName]!;
344 345 346 347 348 349 350 351 352

    final Map<String, dynamic> response = await cb(<String, dynamic>{});
    final Map<String, dynamic> result = response['result']! as Map<String, dynamic>;
    expect(result[kResultType], kResultTypeSuccess);
    expect(result['targets'], isNull);
    expect(result['buildConfigurations'], isNull);
    expect(result['schemes'], isNull);
  });

353 354 355
  testWithoutContext('runInView forwards arguments correctly', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
356
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
357
          'streamId': 'Isolate',
358
        }),
359
        const FakeVmServiceRequest(method: kRunInViewMethod, args: <String, Object>{
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
          'viewId': '1234',
          'mainScript': 'main.dart',
          'assetDirectory': 'flutter_assets/',
        }),
        FakeVmServiceStreamResponse(
          streamId: 'Isolate',
          event: vm_service.Event(
            kind: vm_service.EventKind.kIsolateRunnable,
            timestamp: 1,
          )
        ),
      ]
    );

    await fakeVmServiceHost.vmService.runInView(
      viewId: '1234',
      main: Uri.file('main.dart'),
      assetsDirectory: Uri.file('flutter_assets/'),
    );
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
380 381 382 383 384 385 386 387
  });

  testWithoutContext('flutterDebugDumpSemanticsTreeInTraversalOrder handles missing method', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'ext.flutter.debugDumpSemanticsTreeInTraversalOrder',
          args: <String, Object>{
388
            'isolateId': '1',
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
          },
          errorCode: RPCErrorCodes.kMethodNotFound,
        ),
      ]
    );

    expect(await fakeVmServiceHost.vmService.flutterDebugDumpSemanticsTreeInTraversalOrder(
      isolateId: '1',
    ), '');
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  });

  testWithoutContext('flutterDebugDumpSemanticsTreeInInverseHitTestOrder handles missing method', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'ext.flutter.debugDumpSemanticsTreeInInverseHitTestOrder',
          args: <String, Object>{
407
            'isolateId': '1',
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
          },
          errorCode: RPCErrorCodes.kMethodNotFound,
        ),
      ]
    );

    expect(await fakeVmServiceHost.vmService.flutterDebugDumpSemanticsTreeInInverseHitTestOrder(
      isolateId: '1',
    ), '');
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  });

  testWithoutContext('flutterDebugDumpLayerTree handles missing method', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'ext.flutter.debugDumpLayerTree',
          args: <String, Object>{
426
            'isolateId': '1',
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
          },
          errorCode: RPCErrorCodes.kMethodNotFound,
        ),
      ]
    );

    expect(await fakeVmServiceHost.vmService.flutterDebugDumpLayerTree(
      isolateId: '1',
    ), '');
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  });

  testWithoutContext('flutterDebugDumpRenderTree handles missing method', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'ext.flutter.debugDumpRenderTree',
          args: <String, Object>{
445
            'isolateId': '1',
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
          },
          errorCode: RPCErrorCodes.kMethodNotFound,
        ),
      ]
    );

    expect(await fakeVmServiceHost.vmService.flutterDebugDumpRenderTree(
      isolateId: '1',
    ), '');
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  });

  testWithoutContext('flutterDebugDumpApp handles missing method', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'ext.flutter.debugDumpApp',
          args: <String, Object>{
464
            'isolateId': '1',
465 466 467 468 469 470 471 472 473 474
          },
          errorCode: RPCErrorCodes.kMethodNotFound,
        ),
      ]
    );

    expect(await fakeVmServiceHost.vmService.flutterDebugDumpApp(
      isolateId: '1',
    ), '');
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
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
  testWithoutContext('flutterDebugDumpFocusTree handles missing method', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'ext.flutter.debugDumpFocusTree',
          args: <String, Object>{
            'isolateId': '1',
          },
          errorCode: RPCErrorCodes.kMethodNotFound,
        ),
      ]
    );

    expect(await fakeVmServiceHost.vmService.flutterDebugDumpFocusTree(
      isolateId: '1',
    ), '');
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  });

  testWithoutContext('flutterDebugDumpFocusTree returns data', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'ext.flutter.debugDumpFocusTree',
          args: <String, Object>{
            'isolateId': '1',
          },
          jsonResponse: <String, Object> {
            'data': 'Hello world',
          },
        ),
      ]
    );

    expect(await fakeVmServiceHost.vmService.flutterDebugDumpFocusTree(
      isolateId: '1',
    ), 'Hello world');
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  });

517 518 519
  testWithoutContext('Framework service extension invocations return null if service disappears ', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
        const FakeVmServiceRequest(
          method: kGetSkSLsMethod,
          args: <String, Object>{
            'viewId': '1234',
          },
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
        const FakeVmServiceRequest(
          method: kListViewsMethod,
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
        const FakeVmServiceRequest(
          method: kScreenshotMethod,
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
        const FakeVmServiceRequest(
          method: kScreenshotSkpMethod,
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
        const FakeVmServiceRequest(
          method: 'setVMTimelineFlags',
          args: <String, dynamic>{
            'recordedStreams': <String>['test'],
          },
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
        const FakeVmServiceRequest(
          method: 'getVMTimeline',
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
550 551 552 553 554 555 556 557
        const FakeVmServiceRequest(
          method: kRenderFrameWithRasterStatsMethod,
          args: <String, dynamic>{
            'viewId': '1',
            'isolateId': '12',
          },
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
558 559 560
      ]
    );

561
    final Map<String, Object?>? skSLs = await fakeVmServiceHost.vmService.getSkSLs(
562 563
      viewId: '1234',
    );
564
    expect(skSLs, isNull);
565 566

    final List<FlutterView> views = await fakeVmServiceHost.vmService.getFlutterViews();
567
    expect(views, isEmpty);
568

569
    final vm_service.Response? screenshot = await fakeVmServiceHost.vmService.screenshot();
570 571
    expect(screenshot, isNull);

572
    final vm_service.Response? screenshotSkp = await fakeVmServiceHost.vmService.screenshotSkp();
573 574 575 576 577
    expect(screenshotSkp, isNull);

    // Checking that this doesn't throw.
    await fakeVmServiceHost.vmService.setTimelineFlags(<String>['test']);

578
    final vm_service.Response? timeline = await fakeVmServiceHost.vmService.getTimeline();
579
    expect(timeline, isNull);
580

581
    final Map<String, Object?>? rasterStats =
582 583 584
      await fakeVmServiceHost.vmService.renderFrameWithRasterStats(viewId: '1', uiIsolateId: '12');
    expect(rasterStats, isNull);

585 586 587
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  });

588 589 590 591 592 593 594 595 596
  testWithoutContext('getIsolateOrNull returns null if service disappears ', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(method: 'getIsolate', args: <String, Object>{
          'isolateId': 'isolate/123',
        }, errorCode: RPCErrorCodes.kServiceDisappeared),
      ]
    );

597
    final vm_service.Isolate? isolate = await fakeVmServiceHost.vmService.getIsolateOrNull(
598 599 600 601 602 603 604
      'isolate/123',
    );
    expect(isolate, null);

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

605 606 607 608 609 610 611 612 613
  testWithoutContext('renderWithStats forwards stats correctly', () async {
    // ignore: always_specify_types
    const Map<String, dynamic> response = {
      'type': 'RenderFrameWithRasterStats',
      'snapshots':<dynamic>[
        // ignore: always_specify_types
        {
          'layer_unique_id':1512,
          'duration_micros':477,
614
          'snapshot':'',
615 616 617 618 619 620 621 622 623 624 625 626
        },
      ],
    };
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(method: kRenderFrameWithRasterStatsMethod, args: <String, Object>{
          'isolateId': 'isolate/123',
          'viewId': 'view/1',
        }, jsonResponse: response),
      ]
    );

627
    final Map<String, Object?>? rasterStats =
628 629 630 631 632 633
      await fakeVmServiceHost.vmService.renderFrameWithRasterStats(viewId: 'view/1', uiIsolateId: 'isolate/123');
    expect(rasterStats, equals(response));

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

634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  testWithoutContext('getFlutterViews polls until a view is returned', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: kListViewsMethod,
          jsonResponse: <String, Object>{
            'views': <Object>[],
          },
        ),
        const FakeVmServiceRequest(
          method: kListViewsMethod,
          jsonResponse: <String, Object>{
            'views': <Object>[],
          },
        ),
649
        listViewsRequest,
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
      ]
    );

    expect(
      await fakeVmServiceHost.vmService.getFlutterViews(
        delay: Duration.zero,
      ),
      isNotEmpty,
    );
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  });

  testWithoutContext('getFlutterViews does not poll if returnEarly is true', () async {
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: kListViewsMethod,
          jsonResponse: <String, Object>{
            'views': <Object>[],
          },
        ),
      ]
    );

    expect(
      await fakeVmServiceHost.vmService.getFlutterViews(
        returnEarly: true,
      ),
      isEmpty,
    );
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  });
682

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
  group('findExtensionIsolate', () {

    testWithoutContext('returns an isolate with the registered extensionRPC', () async {
      final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'streamListen',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
        listViewsRequest,
        FakeVmServiceRequest(
          method: 'getIsolate',
          jsonResponse: isolate.toJson(),
          args: <String, Object>{
            'isolateId': '1',
          },
        ),
        const FakeVmServiceRequest(
          method: 'streamCancel',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
      ]);

      final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(kExtensionName);
      expect(isolateRef.id, '1');
    });

    testWithoutContext('returns the isolate with the registered extensionRPC when there are multiple FlutterViews', () async {
      const String otherExtensionName = 'ext.flutter.test.otherExtension';

      // Copy the other isolate and change a few fields.
      final vm_service.Isolate isolate2 = vm_service.Isolate.parse(
        isolate.toJson()
          ..['id'] = '2'
          ..['extensionRPCs'] = <String>[otherExtensionName],
721
      )!;
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769

      final FlutterView fakeFlutterView2 = FlutterView(
        id: '2',
        uiIsolate: isolate2,
      );

      final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'streamListen',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
        FakeVmServiceRequest(
          method: kListViewsMethod,
          jsonResponse: <String, Object>{
            'views': <Object>[
              fakeFlutterView.toJson(),
              fakeFlutterView2.toJson(),
            ],
          },
        ),
        FakeVmServiceRequest(
          method: 'getIsolate',
          jsonResponse: isolate.toJson(),
          args: <String, Object>{
            'isolateId': '1',
          },
        ),
        FakeVmServiceRequest(
          method: 'getIsolate',
          jsonResponse: isolate2.toJson(),
          args: <String, Object>{
            'isolateId': '2',
          },
        ),
        const FakeVmServiceRequest(
          method: 'streamCancel',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
      ]);

      final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(otherExtensionName);
      expect(isolateRef.id, '2');
    });

770 771
    testWithoutContext('does not rethrow a sentinel exception if the initially queried flutter view disappears', () async {
      const String otherExtensionName = 'ext.flutter.test.otherExtension';
772
      final vm_service.Isolate? isolate2 = vm_service.Isolate.parse(
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
        isolate.toJson()
          ..['id'] = '2'
          ..['extensionRPCs'] = <String>[otherExtensionName],
      );

      final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'streamListen',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
        FakeVmServiceRequest(
          method: kListViewsMethod,
          jsonResponse: <String, Object>{
            'views': <Object>[
              fakeFlutterView.toJson(),
            ],
          },
        ),
        const FakeVmServiceRequest(
          method: 'getIsolate',
          args: <String, Object>{
            'isolateId': '1',
          },
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
        // Assume a different isolate returns.
        FakeVmServiceStreamResponse(
          streamId: 'Isolate',
          event: vm_service.Event(
            kind: vm_service.EventKind.kServiceExtensionAdded,
            extensionRPC: otherExtensionName,
            timestamp: 1,
            isolate: isolate2,
          ),
        ),
        const FakeVmServiceRequest(
          method: 'streamCancel',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
      ]);

      final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(otherExtensionName);
      expect(isolateRef.id, '2');
    });

822 823 824 825 826 827 828
    testWithoutContext('when the isolate stream is already subscribed, returns an isolate with the registered extensionRPC', () async {
      final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'streamListen',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
829
          // Stream already subscribed - https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md#streamlisten
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
          errorCode: 103,
        ),
        listViewsRequest,
        FakeVmServiceRequest(
          method: 'getIsolate',
          jsonResponse: isolate.toJson()..['extensionRPCs'] = <String>[kExtensionName],
          args: <String, Object>{
            'isolateId': '1',
          },
        ),
        const FakeVmServiceRequest(
          method: 'streamCancel',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
      ]);

      final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(kExtensionName);
      expect(isolateRef.id, '1');
    });

    testWithoutContext('returns an isolate with a extensionRPC that is registered later', () async {
      final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'streamListen',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
        listViewsRequest,
        FakeVmServiceRequest(
          method: 'getIsolate',
          jsonResponse: isolate.toJson(),
          args: <String, Object>{
            'isolateId': '1',
          },
        ),
        FakeVmServiceStreamResponse(
          streamId: 'Isolate',
          event: vm_service.Event(
            kind: vm_service.EventKind.kServiceExtensionAdded,
            extensionRPC: kExtensionName,
            timestamp: 1,
          ),
        ),
        const FakeVmServiceRequest(
          method: 'streamCancel',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
      ]);

      final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(kExtensionName);
      expect(isolateRef.id, '1');
    });

    testWithoutContext('throws when the service disappears', () async {
      final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(
          method: 'streamListen',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
        ),
        const FakeVmServiceRequest(
          method: kListViewsMethod,
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
        const FakeVmServiceRequest(
          method: 'streamCancel',
          args: <String, Object>{
            'streamId': 'Isolate',
          },
          errorCode: RPCErrorCodes.kServiceDisappeared,
        ),
      ]);

      expect(
        () => fakeVmServiceHost.vmService.findExtensionIsolate(kExtensionName),
        throwsA(isA<VmServiceDisappearedException>()),
      );
    });
  });

916 917 918 919 920 921 922 923 924
  testWithoutContext('Can process log events from the vm service', () {
    final vm_service.Event event = vm_service.Event(
      bytes: base64.encode(utf8.encode('Hello There\n')),
      timestamp: 0,
      kind: vm_service.EventKind.kLogging,
    );

    expect(processVmServiceMessage(event), 'Hello There');
  });
925 926 927

  testUsingContext('WebSocket URL construction uses correct URI join primitives', () async {
    final Completer<String> completer = Completer<String>();
928
    openChannelForTesting = (String url, {io.CompressionOptions compression = io.CompressionOptions.compressionDefault, required Logger logger}) async {
929 930 931 932 933
      completer.complete(url);
      throw Exception('');
    };

    // Construct a URL that does not end in a `/`.
934
    await expectLater(() => connectToVmService(Uri.parse('http://localhost:8181/foo'), logger: BufferLogger.test()), throwsException);
935 936 937
    expect(await completer.future, 'ws://localhost:8181/foo/ws');
    openChannelForTesting = null;
  });
938 939
}

940 941
class MockFlutterProject extends Fake implements FlutterProject {
  MockFlutterProject({
942 943 944 945
    IosProject? mockedIos,
    AndroidProject? mockedAndroid,
  }) : ios = mockedIos ?? MockIosProject(),
       android = mockedAndroid ?? MockAndroidProject();
946 947 948

  @override
  final IosProject ios;
949 950 951

  @override
  final AndroidProject android;
952 953 954 955 956 957 958 959 960 961 962
}

class MockIosProject extends Fake implements IosProject {
  MockIosProject({this.mockedInfo});

  final XcodeProjectInfo? mockedInfo;

  @override
  Future<XcodeProjectInfo?> projectInfo() async => mockedInfo;
}

963 964 965 966 967 968 969 970 971
class MockAndroidProject extends Fake implements AndroidProject {
  MockAndroidProject({this.mockedOptions = const <String>[]});

  final List<String> mockedOptions;

  @override
  Future<List<String>> getBuildVariants() async => mockedOptions;
}

972 973
class MockLogger extends Fake implements Logger { }

974 975
class MockVMService extends Fake implements vm_service.VmService {
  final Map<String, String> services = <String, String>{};
976
  final Map<String, vm_service.ServiceCallback> serviceCallBacks = <String, vm_service.ServiceCallback>{};
977 978 979 980
  final Set<String> listenedStreams = <String>{};
  bool errorOnRegisterService = false;

  @override
981 982 983
  void registerServiceCallback(String service, vm_service.ServiceCallback cb) {
    serviceCallBacks[service] = cb;
  }
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003

  @override
  Future<vm_service.Success> registerService(String service, String alias) async {
    services[service] = alias;
    if (errorOnRegisterService) {
      throw vm_service.RPCError('registerService', 1234, 'error');
    }
    return vm_service.Success();
  }

  @override
  Stream<vm_service.Event> get onExtensionEvent => const Stream<vm_service.Event>.empty();

  @override
  Future<vm_service.Success> streamListen(String streamId) async {
    listenedStreams.add(streamId);
    return vm_service.Success();
  }
}

1004 1005 1006
// Unfortunately Device, despite not being immutable, has an `operator ==`.
// Until we fix that, we have to also ignore related lints here.
// ignore: avoid_implementing_value_types
1007
class FakeDevice extends Fake implements Device { }
1008

1009 1010 1011
/// A [WebSocketConnector] that always throws an [io.SocketException].
Future<io.WebSocket> failingWebSocketConnector(
  String url, {
1012 1013
  io.CompressionOptions? compression,
  Logger? logger,
1014 1015 1016
}) {
  throw const io.SocketException('Failed WebSocket connection');
}