extension_test.dart 45.5 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 8 9 10
// 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=20210721"
@Tags(<String>['no-shuffle'])

11
import 'package:flutter/foundation.dart';
12
import 'package:flutter/material.dart';
13
import 'package:flutter/rendering.dart';
14
import 'package:flutter/scheduler.dart';
15
import 'package:flutter/services.dart';
16
import 'package:flutter_driver/flutter_driver.dart';
17
import 'package:flutter_driver/src/extension/extension.dart';
18 19
import 'package:flutter_test/flutter_test.dart';

20 21
import 'stubs/stub_command.dart';
import 'stubs/stub_command_extension.dart';
22 23 24
import 'stubs/stub_finder.dart';
import 'stubs/stub_finder_extension.dart';

25 26 27 28 29 30 31 32 33 34
Future<void> silenceDriverLogger(AsyncCallback callback) async {
  final DriverLogCallback oldLogger = driverLog;
  driverLog = (String source, String message) { };
  try {
    await callback();
  } finally {
    driverLog = oldLogger;
  }
}

35 36
void main() {
  group('waitUntilNoTransientCallbacks', () {
37 38
    late FlutterDriverExtension driverExtension;
    Map<String, dynamic>? result;
39
    int messageId = 0;
40
    final List<String?> log = <String?>[];
41 42 43

    setUp(() {
      result = null;
44
      driverExtension = FlutterDriverExtension((String? message) async { log.add(message); return (messageId += 1).toString(); }, false, true);
45 46 47
    });

    testWidgets('returns immediately when transient callback queue is empty', (WidgetTester tester) async {
48
      driverExtension.call(const WaitForCondition(NoTransientCallbacks()).serialize())
49 50 51
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));
52 53 54

      await tester.idle();
      expect(
55 56 57
        result,
        <String, dynamic>{
          'isError': false,
58
          'response': <String, dynamic>{},
59
        },
60 61 62 63
      );
    });

    testWidgets('waits until no transient callbacks', (WidgetTester tester) async {
64
      SchedulerBinding.instance!.scheduleFrameCallback((_) {
65 66 67
        // Intentionally blank. We only care about existence of a callback.
      });

68
      driverExtension.call(const WaitForCondition(NoTransientCallbacks()).serialize())
69 70 71
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));
72 73 74 75 76 77 78 79

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
80 81 82
        result,
        <String, dynamic>{
          'isError': false,
83
          'response': <String, dynamic>{},
84
        },
85 86
      );
    });
87 88 89

    testWidgets('handler', (WidgetTester tester) async {
      expect(log, isEmpty);
90
      final Map<String, dynamic> response = await driverExtension.call(const RequestData('hello').serialize());
91
      final RequestDataResult result = RequestDataResult.fromJson(response['response'] as Map<String, dynamic>);
92 93 94
      expect(log, <String>['hello']);
      expect(result.message, '1');
    });
95
  });
96

97
  group('waitForCondition', () {
98 99
    late FlutterDriverExtension driverExtension;
    Map<String, dynamic>? result;
100
    int messageId = 0;
101
    final List<String?> log = <String?>[];
102 103 104

    setUp(() {
      result = null;
105
      driverExtension = FlutterDriverExtension((String? message) async { log.add(message); return (messageId += 1).toString(); }, false, true);
106 107 108
    });

    testWidgets('waiting for NoTransientCallbacks returns immediately when transient callback queue is empty', (WidgetTester tester) async {
109
      driverExtension.call(const WaitForCondition(NoTransientCallbacks()).serialize())
110 111 112 113 114 115 116 117 118
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      await tester.idle();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
119
          'response': <String, dynamic>{},
120 121 122 123 124
        },
      );
    });

    testWidgets('waiting for NoTransientCallbacks returns until no transient callbacks', (WidgetTester tester) async {
125
      SchedulerBinding.instance!.scheduleFrameCallback((_) {
126 127 128
        // Intentionally blank. We only care about existence of a callback.
      });

129
      driverExtension.call(const WaitForCondition(NoTransientCallbacks()).serialize())
130 131 132 133 134 135 136 137 138 139 140 141 142 143
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
144
          'response': <String, dynamic>{},
145 146 147 148 149 150
        },
      );
    });

    testWidgets('waiting for NoPendingFrame returns immediately when frame is synced', (
        WidgetTester tester) async {
151
      driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
152 153 154 155 156 157 158 159 160
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      await tester.idle();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
161
          'response': <String, dynamic>{},
162 163 164 165 166
        },
      );
    });

    testWidgets('waiting for NoPendingFrame returns until no pending scheduled frame', (WidgetTester tester) async {
167
      SchedulerBinding.instance!.scheduleFrame();
168

169
      driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
170 171 172 173 174 175 176 177 178 179 180 181 182 183
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
184
          'response': <String, dynamic>{},
185 186 187 188 189 190 191 192
        },
      );
    });

    testWidgets(
        'waiting for combined conditions returns immediately', (WidgetTester tester) async {
      const SerializableWaitCondition combinedCondition =
          CombinedCondition(<SerializableWaitCondition>[NoTransientCallbacks(), NoPendingFrame()]);
193
      driverExtension.call(const WaitForCondition(combinedCondition).serialize())
194 195 196 197 198 199 200 201 202
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      await tester.idle();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
203
          'response': <String, dynamic>{},
204 205 206 207 208 209
        },
      );
    });

    testWidgets(
        'waiting for combined conditions returns until no transient callbacks', (WidgetTester tester) async {
210 211
      SchedulerBinding.instance!.scheduleFrame();
      SchedulerBinding.instance!.scheduleFrameCallback((_) {
212 213 214 215 216
        // Intentionally blank. We only care about existence of a callback.
      });

      const SerializableWaitCondition combinedCondition =
          CombinedCondition(<SerializableWaitCondition>[NoTransientCallbacks(), NoPendingFrame()]);
217
      driverExtension.call(const WaitForCondition(combinedCondition).serialize())
218 219 220 221 222 223 224 225 226 227 228 229 230 231
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
232
          'response': <String, dynamic>{},
233 234 235 236 237 238
        },
      );
    });

    testWidgets(
        'waiting for combined conditions returns until no pending scheduled frame', (WidgetTester tester) async {
239 240
      SchedulerBinding.instance!.scheduleFrame();
      SchedulerBinding.instance!.scheduleFrameCallback((_) {
241 242 243 244 245
        // Intentionally blank. We only care about existence of a callback.
      });

      const SerializableWaitCondition combinedCondition =
          CombinedCondition(<SerializableWaitCondition>[NoPendingFrame(), NoTransientCallbacks()]);
246
      driverExtension.call(const WaitForCondition(combinedCondition).serialize())
247 248 249 250 251 252 253 254 255 256 257 258 259 260
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
261
          'response': <String, dynamic>{},
262 263 264
        },
      );
    });
265 266

    testWidgets(
267
        'waiting for NoPendingPlatformMessages returns immediately when there are no platform messages', (WidgetTester tester) async {
268
      driverExtension
269 270 271 272 273 274 275 276 277 278
          .call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      await tester.idle();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
279
          'response': <String, dynamic>{},
280 281 282 283 284 285 286 287
        },
      );
    });

    testWidgets(
        'waiting for NoPendingPlatformMessages returns until a single method channel call returns', (WidgetTester tester) async {
      const MethodChannel channel = MethodChannel('helloChannel', JSONMethodCodec());
      const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
288
      tester.binding.defaultBinaryMessenger.setMockMessageHandler(
289
          'helloChannel', (ByteData? message) {
290 291
            return Future<ByteData>.delayed(
                const Duration(milliseconds: 10),
292
                () => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
293 294 295
          });
      channel.invokeMethod<String>('sayHello', 'hello');

296
      driverExtension
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
          .call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // The channel message are delayed for 10 milliseconds, so nothing happens yet.
      await tester.pump(const Duration(milliseconds: 5));
      expect(result, isNull);

      // Now we receive the result.
      await tester.pump(const Duration(milliseconds: 5));
      expect(
        result,
        <String, dynamic>{
          'isError': false,
312
          'response': <String, dynamic>{},
313 314 315 316 317 318 319 320 321
        },
      );
    });

    testWidgets(
        'waiting for NoPendingPlatformMessages returns until both method channel calls return', (WidgetTester tester) async {
      const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
      // Configures channel 1
      const MethodChannel channel1 = MethodChannel('helloChannel1', JSONMethodCodec());
322
      tester.binding.defaultBinaryMessenger.setMockMessageHandler(
323
          'helloChannel1', (ByteData? message) {
324 325
            return Future<ByteData>.delayed(
                const Duration(milliseconds: 10),
326
                () => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
327 328 329 330
          });

      // Configures channel 2
      const MethodChannel channel2 = MethodChannel('helloChannel2', JSONMethodCodec());
331
      tester.binding.defaultBinaryMessenger.setMockMessageHandler(
332
          'helloChannel2', (ByteData? message) {
333 334
            return Future<ByteData>.delayed(
                const Duration(milliseconds: 20),
335
                () => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
336 337 338 339 340
          });

      channel1.invokeMethod<String>('sayHello', 'hello');
      channel2.invokeMethod<String>('sayHello', 'hello');

341
      driverExtension
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
          .call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // Neither of the channel responses is received, so nothing happens yet.
      await tester.pump(const Duration(milliseconds: 5));
      expect(result, isNull);

      // Result of channel 1 is received, but channel 2 is still pending, so still waiting.
      await tester.pump(const Duration(milliseconds: 10));
      expect(result, isNull);

      // Both of the results are received. Now we receive the result.
      await tester.pump(const Duration(milliseconds: 30));
      expect(
        result,
        <String, dynamic>{
          'isError': false,
361
          'response': <String, dynamic>{},
362 363 364 365 366 367 368 369 370
        },
      );
    });

    testWidgets(
        'waiting for NoPendingPlatformMessages returns until new method channel call returns', (WidgetTester tester) async {
      const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
      // Configures channel 1
      const MethodChannel channel1 = MethodChannel('helloChannel1', JSONMethodCodec());
371
      tester.binding.defaultBinaryMessenger.setMockMessageHandler(
372
          'helloChannel1', (ByteData? message) {
373 374
            return Future<ByteData>.delayed(
                const Duration(milliseconds: 10),
375
                () => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
376 377 378 379
          });

      // Configures channel 2
      const MethodChannel channel2 = MethodChannel('helloChannel2', JSONMethodCodec());
380
      tester.binding.defaultBinaryMessenger.setMockMessageHandler(
381
          'helloChannel2', (ByteData? message) {
382 383
            return Future<ByteData>.delayed(
                const Duration(milliseconds: 20),
384
                () => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
385 386 387 388 389
          });

      channel1.invokeMethod<String>('sayHello', 'hello');

      // Calls the waiting API before the second channel message is sent.
390
      driverExtension
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
          .call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // The first channel message is not received, so nothing happens yet.
      await tester.pump(const Duration(milliseconds: 5));
      expect(result, isNull);

      channel2.invokeMethod<String>('sayHello', 'hello');

      // Result of channel 1 is received, but channel 2 is still pending, so still waiting.
      await tester.pump(const Duration(milliseconds: 15));
      expect(result, isNull);

      // Both of the results are received. Now we receive the result.
      await tester.pump(const Duration(milliseconds: 10));
      expect(
        result,
        <String, dynamic>{
          'isError': false,
412
          'response': <String, dynamic>{},
413 414 415 416 417 418 419 420 421
        },
      );
    });

    testWidgets(
        'waiting for NoPendingPlatformMessages returns until both old and new method channel calls return', (WidgetTester tester) async {
      const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
      // Configures channel 1
      const MethodChannel channel1 = MethodChannel('helloChannel1', JSONMethodCodec());
422
      tester.binding.defaultBinaryMessenger.setMockMessageHandler(
423
          'helloChannel1', (ByteData? message) {
424 425
            return Future<ByteData>.delayed(
                const Duration(milliseconds: 20),
426
                () => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
427 428 429 430
          });

      // Configures channel 2
      const MethodChannel channel2 = MethodChannel('helloChannel2', JSONMethodCodec());
431
      tester.binding.defaultBinaryMessenger.setMockMessageHandler(
432
          'helloChannel2', (ByteData? message) {
433 434
            return Future<ByteData>.delayed(
                const Duration(milliseconds: 10),
435
                () => jsonMessage.encodeMessage(<dynamic>['hello world'])!);
436 437 438 439
          });

      channel1.invokeMethod<String>('sayHello', 'hello');

440
      driverExtension
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
          .call(const WaitForCondition(NoPendingPlatformMessages()).serialize())
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // The first channel message is not received, so nothing happens yet.
      await tester.pump(const Duration(milliseconds: 5));
      expect(result, isNull);

      channel2.invokeMethod<String>('sayHello', 'hello');

      // Result of channel 2 is received, but channel 1 is still pending, so still waiting.
      await tester.pump(const Duration(milliseconds: 10));
      expect(result, isNull);

      // Now we receive the result.
      await tester.pump(const Duration(milliseconds: 5));
      expect(
        result,
        <String, dynamic>{
          'isError': false,
462
          'response': <String, dynamic>{},
463 464 465
        },
      );
    });
466 467
  });

468
  group('getSemanticsId', () {
469
    late FlutterDriverExtension driverExtension;
470
    setUp(() {
471
      driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
472 473 474
    });

    testWidgets('works when semantics are enabled', (WidgetTester tester) async {
475
      final SemanticsHandle semantics = RendererBinding.instance!.pipelineOwner.ensureSemantics();
476 477
      await tester.pumpWidget(
        const Text('hello', textDirection: TextDirection.ltr));
478

479
      final Map<String, String> arguments = GetSemanticsId(const ByText('hello')).serialize();
480
      final Map<String, dynamic> response = await driverExtension.call(arguments);
481
      final GetSemanticsIdResult result = GetSemanticsIdResult.fromJson(response['response'] as Map<String, dynamic>);
482

483 484 485 486 487 488 489
      expect(result.id, 1);
      semantics.dispose();
    });

    testWidgets('throws state error if no data is found', (WidgetTester tester) async {
      await tester.pumpWidget(
        const Text('hello', textDirection: TextDirection.ltr));
490

491
      final Map<String, String> arguments = GetSemanticsId(const ByText('hello')).serialize();
492
      final Map<String, dynamic> response = await driverExtension.call(arguments);
493

494 495
      expect(response['isError'], true);
      expect(response['response'], contains('Bad state: No semantics data found'));
496
    }, semanticsEnabled: false);
497 498

    testWidgets('throws state error multiple matches are found', (WidgetTester tester) async {
499
      final SemanticsHandle semantics = RendererBinding.instance!.pipelineOwner.ensureSemantics();
500
      await tester.pumpWidget(
501
        Directionality(
502
          textDirection: TextDirection.ltr,
503
          child: ListView(children: const <Widget>[
504 505
            SizedBox(width: 100.0, height: 100.0, child: Text('hello')),
            SizedBox(width: 100.0, height: 100.0, child: Text('hello')),
506 507 508
          ]),
        ),
      );
509

510
      final Map<String, String> arguments = GetSemanticsId(const ByText('hello')).serialize();
511
      final Map<String, dynamic> response = await driverExtension.call(arguments);
512

513
      expect(response['isError'], true);
514
      expect(response['response'], contains('Bad state: Found more than one element with the same ID'));
515 516 517
      semantics.dispose();
    });
  });
518 519

  testWidgets('getOffset', (WidgetTester tester) async {
520
    final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
521 522

    Future<Offset> getOffset(OffsetType offset) async {
523
      final Map<String, String> arguments = GetOffset(ByValueKey(1), offset).serialize();
524
      final Map<String, dynamic> response = await driverExtension.call(arguments);
525
      final GetOffsetResult result = GetOffsetResult.fromJson(response['response'] as Map<String, dynamic>);
526 527 528 529 530 531 532 533
      return Offset(result.dx, result.dy);
    }

    await tester.pumpWidget(
      Align(
        alignment: Alignment.topLeft,
        child: Transform.translate(
          offset: const Offset(40, 30),
534 535
          child: const SizedBox(
            key: ValueKey<int>(1),
536 537 538 539 540 541 542 543 544 545 546 547 548
            width: 100,
            height: 120,
          ),
        ),
      ),
    );

    expect(await getOffset(OffsetType.topLeft), const Offset(40, 30));
    expect(await getOffset(OffsetType.topRight), const Offset(40 + 100.0, 30));
    expect(await getOffset(OffsetType.bottomLeft), const Offset(40, 30 + 120.0));
    expect(await getOffset(OffsetType.bottomRight), const Offset(40 + 100.0, 30 + 120.0));
    expect(await getOffset(OffsetType.center), const Offset(40 + (100 / 2), 30 + (120 / 2)));
  });
549

550 551
  testWidgets('getText', (WidgetTester tester) async {
    await silenceDriverLogger(() async {
552
      final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
553

554
      Future<String?> getTextInternal(SerializableFinder search) async {
555
        final Map<String, String> arguments = GetText(search, timeout: const Duration(seconds: 1)).serialize();
556
        final Map<String, dynamic> result = await driverExtension.call(arguments);
557 558 559 560 561 562 563 564 565 566 567 568
        if (result['isError'] as bool) {
          return null;
        }
        return GetTextResult.fromJson(result['response'] as Map<String, dynamic>).text;
      }

      await tester.pumpWidget(
          MaterialApp(
              home: Scaffold(body:Column(
                key: const ValueKey<String>('column'),
                children: <Widget>[
                  const Text('Hello1', key: ValueKey<String>('text1')),
569
                  SizedBox(
Dan Field's avatar
Dan Field committed
570 571 572 573 574
                    height: 25.0,
                    child: RichText(
                      key: const ValueKey<String>('text2'),
                      text: const TextSpan(text: 'Hello2'),
                    ),
575
                  ),
576
                  SizedBox(
577
                    height: 25.0,
Dan Field's avatar
Dan Field committed
578 579 580 581 582 583 584 585
                    child: EditableText(
                      key: const ValueKey<String>('text3'),
                      controller: TextEditingController(text: 'Hello3'),
                      focusNode: FocusNode(),
                      style: const TextStyle(),
                      cursorColor: Colors.red,
                      backgroundCursorColor: Colors.black,
                    ),
586
                  ),
587
                  SizedBox(
588
                    height: 25.0,
Dan Field's avatar
Dan Field committed
589 590 591 592
                    child: TextField(
                      key: const ValueKey<String>('text4'),
                      controller: TextEditingController(text: 'Hello4'),
                    ),
593
                  ),
594
                  SizedBox(
595
                    height: 25.0,
Dan Field's avatar
Dan Field committed
596 597 598 599
                    child: TextFormField(
                      key: const ValueKey<String>('text5'),
                      controller: TextEditingController(text: 'Hello5'),
                    ),
600
                  ),
601
                  SizedBox(
602 603 604 605 606 607 608 609 610 611 612
                    height: 25.0,
                    child: RichText(
                      key: const ValueKey<String>('text6'),
                      text: const TextSpan(children: <TextSpan>[
                        TextSpan(text: 'Hello'),
                        TextSpan(text: ', '),
                        TextSpan(text: 'World'),
                        TextSpan(text: '!'),
                      ]),
                    ),
                  ),
613 614 615 616 617 618 619 620 621 622
                ],
              ))
          )
      );

      expect(await getTextInternal(ByValueKey('text1')), 'Hello1');
      expect(await getTextInternal(ByValueKey('text2')), 'Hello2');
      expect(await getTextInternal(ByValueKey('text3')), 'Hello3');
      expect(await getTextInternal(ByValueKey('text4')), 'Hello4');
      expect(await getTextInternal(ByValueKey('text5')), 'Hello5');
623
      expect(await getTextInternal(ByValueKey('text6')), 'Hello, World!');
624 625 626

      // Check if error thrown for other types
      final Map<String, String> arguments = GetText(ByValueKey('column'), timeout: const Duration(seconds: 1)).serialize();
627
      final Map<String, dynamic> response = await driverExtension.call(arguments);
628 629 630 631 632
      expect(response['isError'], true);
      expect(response['response'], contains('is currently not supported by getText'));
    });
  });

633
  testWidgets('descendant finder', (WidgetTester tester) async {
634
    await silenceDriverLogger(() async {
635
      final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
636

637
      Future<String?> getDescendantText({ String? of, bool matchRoot = false}) async {
638
        final Map<String, String> arguments = GetText(Descendant(
639 640 641 642
          of: ByValueKey(of),
          matching: ByValueKey('text2'),
          matchRoot: matchRoot,
        ), timeout: const Duration(seconds: 1)).serialize();
643
        final Map<String, dynamic> result = await driverExtension.call(arguments);
644
        if (result['isError'] as bool) {
645 646
          return null;
        }
647
        return GetTextResult.fromJson(result['response'] as Map<String, dynamic>).text;
648 649
      }

650 651 652 653 654 655 656 657 658 659 660 661
      await tester.pumpWidget(
          MaterialApp(
              home: Column(
                key: const ValueKey<String>('column'),
                children: const <Widget>[
                  Text('Hello1', key: ValueKey<String>('text1')),
                  Text('Hello2', key: ValueKey<String>('text2')),
                  Text('Hello3', key: ValueKey<String>('text3')),
                ],
              )
          )
      );
662

663 664 665
      expect(await getDescendantText(of: 'column'), 'Hello2');
      expect(await getDescendantText(of: 'column', matchRoot: true), 'Hello2');
      expect(await getDescendantText(of: 'text2', matchRoot: true), 'Hello2');
666

667
      // Find nothing
668
      Future<String?> result = getDescendantText(of: 'text1', matchRoot: true);
669 670
      await tester.pump(const Duration(seconds: 2));
      expect(await result, null);
671

672 673 674 675
      result = getDescendantText(of: 'text2');
      await tester.pump(const Duration(seconds: 2));
      expect(await result, null);
    });
676 677
  });

678
  testWidgets('descendant finder firstMatchOnly', (WidgetTester tester) async {
679
    await silenceDriverLogger(() async {
680
      final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
681

682
      Future<String?> getDescendantText() async {
683
        final Map<String, String> arguments = GetText(Descendant(
684 685 686 687
          of: ByValueKey('column'),
          matching: const ByType('Text'),
          firstMatchOnly: true,
        ), timeout: const Duration(seconds: 1)).serialize();
688
        final Map<String, dynamic> result = await driverExtension.call(arguments);
689
        if (result['isError'] as bool) {
690 691
          return null;
        }
692
        return GetTextResult.fromJson(result['response'] as Map<String, dynamic>).text;
693 694
      }

695 696 697 698 699 700 701 702 703 704
      await tester.pumpWidget(
        MaterialApp(
          home: Column(
            key: const ValueKey<String>('column'),
            children: const <Widget>[
              Text('Hello1', key: ValueKey<String>('text1')),
              Text('Hello2', key: ValueKey<String>('text2')),
              Text('Hello3', key: ValueKey<String>('text3')),
            ],
          ),
705
        ),
706
      );
707

708 709
      expect(await getDescendantText(), 'Hello1');
    });
710 711
  });

712
  testWidgets('ancestor finder', (WidgetTester tester) async {
713
    await silenceDriverLogger(() async {
714
      final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
715

716
      Future<Offset?> getAncestorTopLeft({ String? of, String? matching, bool matchRoot = false}) async {
717
        final Map<String, String> arguments = GetOffset(Ancestor(
718 719 720 721
          of: ByValueKey(of),
          matching: ByValueKey(matching),
          matchRoot: matchRoot,
        ), OffsetType.topLeft, timeout: const Duration(seconds: 1)).serialize();
722
        final Map<String, dynamic> response = await driverExtension.call(arguments);
723
        if (response['isError'] as bool) {
724 725
          return null;
        }
726
        final GetOffsetResult result = GetOffsetResult.fromJson(response['response'] as Map<String, dynamic>);
727
        return Offset(result.dx, result.dy);
728 729
      }

730 731 732
      await tester.pumpWidget(
          MaterialApp(
            home: Center(
733
                child: SizedBox(
734 735 736 737 738
                  key: const ValueKey<String>('parent'),
                  height: 100,
                  width: 100,
                  child: Center(
                    child: Row(
739 740 741
                      children: const <Widget>[
                        SizedBox(
                          key: ValueKey<String>('leftchild'),
742 743 744
                          width: 25,
                          height: 25,
                        ),
745 746
                        SizedBox(
                          key: ValueKey<String>('righttchild'),
747 748 749 750 751
                          width: 25,
                          height: 25,
                        ),
                      ],
                    ),
752
                  ),
753 754 755 756
                )
            ),
          )
      );
757

758 759 760 761 762 763 764 765 766 767 768 769
      expect(
        await getAncestorTopLeft(of: 'leftchild', matching: 'parent'),
        const Offset((800 - 100) / 2, (600 - 100) / 2),
      );
      expect(
        await getAncestorTopLeft(of: 'leftchild', matching: 'parent', matchRoot: true),
        const Offset((800 - 100) / 2, (600 - 100) / 2),
      );
      expect(
        await getAncestorTopLeft(of: 'parent', matching: 'parent', matchRoot: true),
        const Offset((800 - 100) / 2, (600 - 100) / 2),
      );
770

771
      // Find nothing
772
      Future<Offset?> result = getAncestorTopLeft(of: 'leftchild', matching: 'leftchild');
773 774
      await tester.pump(const Duration(seconds: 2));
      expect(await result, null);
775

776 777 778 779
      result = getAncestorTopLeft(of: 'leftchild', matching: 'righttchild');
      await tester.pump(const Duration(seconds: 2));
      expect(await result, null);
    });
780
  });
781

782
  testWidgets('ancestor finder firstMatchOnly', (WidgetTester tester) async {
783
    await silenceDriverLogger(() async {
784
      final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
785

786
      Future<Offset?> getAncestorTopLeft() async {
787
        final Map<String, String> arguments = GetOffset(Ancestor(
788
          of: ByValueKey('leaf'),
789
          matching: const ByType('SizedBox'),
790 791
          firstMatchOnly: true,
        ), OffsetType.topLeft, timeout: const Duration(seconds: 1)).serialize();
792
        final Map<String, dynamic> response = await driverExtension.call(arguments);
793
        if (response['isError'] as bool) {
794 795
          return null;
        }
796
        final GetOffsetResult result = GetOffsetResult.fromJson(response['response'] as Map<String, dynamic>);
797
        return Offset(result.dx, result.dy);
798 799
      }

800
      await tester.pumpWidget(
801
        const MaterialApp(
802
          home: Center(
803
            child: SizedBox(
804 805 806
              height: 200,
              width: 200,
              child: Center(
807
                child: SizedBox(
808 809 810
                  height: 100,
                  width: 100,
                  child: Center(
811 812
                    child: SizedBox(
                      key: ValueKey<String>('leaf'),
813 814 815
                      height: 50,
                      width: 50,
                    ),
816 817 818 819 820 821
                  ),
                ),
              ),
            ),
          ),
        ),
822
      );
823

824 825 826 827 828
      expect(
        await getAncestorTopLeft(),
        const Offset((800 - 100) / 2, (600 - 100) / 2),
      );
    });
829 830
  });

831
  testWidgets('GetDiagnosticsTree', (WidgetTester tester) async {
832
    final FlutterDriverExtension driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
833

834
    Future<Map<String, dynamic>> getDiagnosticsTree(DiagnosticsType type, SerializableFinder finder, { int depth = 0, bool properties = true }) async {
835
      final Map<String, String> arguments = GetDiagnosticsTree(finder, type, subtreeDepth: depth, includeProperties: properties).serialize();
836
      final Map<String, dynamic> response = await driverExtension.call(arguments);
837
      final DiagnosticsTreeResult result = DiagnosticsTreeResult(response['response'] as Map<String, dynamic>);
838 839 840 841
      return result.json;
    }

    await tester.pumpWidget(
842
      const Directionality(
843 844
        textDirection: TextDirection.ltr,
        child: Center(
845
            child: Text('Hello World', key: ValueKey<String>('Text'))
846 847 848 849 850
        ),
      ),
    );

    // Widget
851
    Map<String, dynamic> result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 0);
852 853 854
    expect(result['children'], isNull); // depth: 0
    expect(result['widgetRuntimeType'], 'Text');

855 856
    List<Map<String, dynamic>> properties = (result['properties']! as List<Object>).cast<Map<String, dynamic>>();
    Map<String, dynamic> stringProperty = properties.singleWhere((Map<String, dynamic> property) => property['name'] == 'data');
857 858 859 860 861 862 863 864
    expect(stringProperty['description'], '"Hello World"');
    expect(stringProperty['propertyType'], 'String');

    result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 0, properties: false);
    expect(result['widgetRuntimeType'], 'Text');
    expect(result['properties'], isNull); // properties: false

    result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 1);
865
    List<Map<String, dynamic>> children = (result['children']! as List<Object>).cast<Map<String, dynamic>>();
866 867 868
    expect(children.single['children'], isNull);

    result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 100);
869
    children = (result['children']! as List<Object>).cast<Map<String, dynamic>>();
870 871 872 873 874 875 876 877 878 879 880 881 882
    expect(children.single['children'], isEmpty);

    // RenderObject
    result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 0);
    expect(result['children'], isNull); // depth: 0
    expect(result['properties'], isNotNull);
    expect(result['description'], startsWith('RenderParagraph'));

    result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 0, properties: false);
    expect(result['properties'], isNull); // properties: false
    expect(result['description'], startsWith('RenderParagraph'));

    result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 1);
883 884
    children = (result['children']! as List<Object>).cast<Map<String, dynamic>>();
    final Map<String, dynamic> textSpan = children.single;
885
    expect(textSpan['description'], 'TextSpan');
886 887
    properties = (textSpan['properties']! as List<Object>).cast<Map<String, dynamic>>();
    stringProperty = properties.singleWhere((Map<String, dynamic> property) => property['name'] == 'text');
888 889 890 891 892
    expect(stringProperty['description'], '"Hello World"');
    expect(stringProperty['propertyType'], 'String');
    expect(children.single['children'], isNull);

    result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 100);
893
    children = (result['children']! as List<Object>).cast<Map<String, dynamic>>();
894 895
    expect(children.single['children'], isEmpty);
  });
896

897
  group('enableTextEntryEmulation', () {
898
    late FlutterDriverExtension driverExtension;
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917

    Future<Map<String, dynamic>> enterText() async {
      final Map<String, String> arguments = const EnterText('foo').serialize();
      final Map<String, dynamic> result = await driverExtension.call(arguments);
      return result;
    }

    const Widget testWidget = MaterialApp(
      home: Material(
        child: Center(
          child: TextField(
            key: ValueKey<String>('foo'),
            autofocus: true,
          ),
        ),
      ),
    );

    testWidgets('enableTextEntryEmulation false', (WidgetTester tester) async {
918
      driverExtension = FlutterDriverExtension((String? arg) async => '', true, false);
919 920 921 922 923 924 925 926

      await tester.pumpWidget(testWidget);

      final Map<String, dynamic> enterTextResult = await enterText();
      expect(enterTextResult['isError'], isTrue);
    });

    testWidgets('enableTextEntryEmulation true', (WidgetTester tester) async {
927
      driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
928 929 930 931 932 933 934 935

      await tester.pumpWidget(testWidget);

      final Map<String, dynamic> enterTextResult = await enterText();
      expect(enterTextResult['isError'], isFalse);
    });
  });

936 937 938 939 940 941 942 943 944
  group('extension finders', () {
    final Widget debugTree = Directionality(
      textDirection: TextDirection.ltr,
      child: Center(
        child: Column(
          key: const ValueKey<String>('Column'),
          children: <Widget>[
            const Text('Foo', key: ValueKey<String>('Text1')),
            const Text('Bar', key: ValueKey<String>('Text2')),
945
            TextButton(
946 947
              key: const ValueKey<String>('Button'),
              onPressed: () {},
948
              child: const Text('Whatever'),
949 950 951 952 953 954 955 956
            ),
          ],
        ),
      ),
    );

    testWidgets('unknown extension finder', (WidgetTester tester) async {
      final FlutterDriverExtension driverExtension = FlutterDriverExtension(
957
        (String? arg) async => '',
958
        true,
959
        true,
960 961 962 963 964
        finders: <FinderExtension>[],
      );

      Future<Map<String, dynamic>> getText(SerializableFinder finder) async {
        final Map<String, String> arguments = GetText(finder, timeout: const Duration(seconds: 1)).serialize();
965
        return driverExtension.call(arguments);
966 967 968 969 970 971 972
      }

      await tester.pumpWidget(debugTree);

      final Map<String, dynamic> result = await getText(StubFinder('Text1'));
      expect(result['isError'], true);
      expect(result['response'] is String, true);
973
      expect(result['response'] as String?, contains('Unsupported search specification type Stub'));
974 975 976 977
    });

    testWidgets('simple extension finder', (WidgetTester tester) async {
      final FlutterDriverExtension driverExtension = FlutterDriverExtension(
978
        (String? arg) async => '',
979
        true,
980
        true,
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
        finders: <FinderExtension>[
          StubFinderExtension(),
        ],
      );

      Future<GetTextResult> getText(SerializableFinder finder) async {
        final Map<String, String> arguments = GetText(finder, timeout: const Duration(seconds: 1)).serialize();
        final Map<String, dynamic> response = await driverExtension.call(arguments);
        return GetTextResult.fromJson(response['response'] as Map<String, dynamic>);
      }

      await tester.pumpWidget(debugTree);

      final GetTextResult result = await getText(StubFinder('Text1'));
      expect(result.text, 'Foo');
    });

    testWidgets('complex extension finder', (WidgetTester tester) async {
      final FlutterDriverExtension driverExtension = FlutterDriverExtension(
1000
        (String? arg) async => '',
1001
        true,
1002
        true,
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
        finders: <FinderExtension>[
          StubFinderExtension(),
        ],
      );

      Future<GetTextResult> getText(SerializableFinder finder) async {
        final Map<String, String> arguments = GetText(finder, timeout: const Duration(seconds: 1)).serialize();
        final Map<String, dynamic> response = await driverExtension.call(arguments);
        return GetTextResult.fromJson(response['response'] as Map<String, dynamic>);
      }

      await tester.pumpWidget(debugTree);

      final GetTextResult result = await getText(Descendant(of: StubFinder('Column'), matching: StubFinder('Text1')));
      expect(result.text, 'Foo');
    });

    testWidgets('extension finder with command', (WidgetTester tester) async {
      final FlutterDriverExtension driverExtension = FlutterDriverExtension(
1022
        (String? arg) async => '',
1023
        true,
1024
        true,
1025 1026 1027 1028 1029 1030 1031
        finders: <FinderExtension>[
          StubFinderExtension(),
        ],
      );

      Future<Map<String, dynamic>> tap(SerializableFinder finder) async {
        final Map<String, String> arguments = Tap(finder, timeout: const Duration(seconds: 1)).serialize();
1032
        return driverExtension.call(arguments);
1033 1034 1035 1036 1037 1038 1039 1040
      }

      await tester.pumpWidget(debugTree);

      final Map<String, dynamic> result = await tap(StubFinder('Button'));
      expect(result['isError'], false);
    });
  });
1041 1042 1043

  group('extension commands', () {
    int invokes = 0;
1044
    void stubCallback() => invokes++;
1045 1046 1047 1048 1049 1050

    final Widget debugTree = Directionality(
      textDirection: TextDirection.ltr,
      child: Center(
        child: Column(
          children: <Widget>[
1051
            TextButton(
1052 1053
              key: const ValueKey<String>('Button'),
              onPressed: stubCallback,
1054
              child: const Text('Whatever'),
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
            ),
          ],
        ),
      ),
    );

    setUp(() {
      invokes = 0;
    });

    testWidgets('unknown extension command', (WidgetTester tester) async {
      final FlutterDriverExtension driverExtension = FlutterDriverExtension(
1067
        (String? arg) async => '',
1068
        true,
1069
        true,
1070 1071 1072 1073 1074
        commands: <CommandExtension>[],
      );

      Future<Map<String, dynamic>> invokeCommand(SerializableFinder finder, int times) async {
        final Map<String, String> arguments = StubNestedCommand(finder, times).serialize();
1075
        return driverExtension.call(arguments);
1076 1077 1078 1079 1080 1081 1082
      }

      await tester.pumpWidget(debugTree);

      final Map<String, dynamic> result = await invokeCommand(ByValueKey('Button'), 10);
      expect(result['isError'], true);
      expect(result['response'] is String, true);
1083
      expect(result['response'] as String?, contains('Unsupported command kind StubNestedCommand'));
1084 1085 1086 1087
    });

    testWidgets('nested command', (WidgetTester tester) async {
      final FlutterDriverExtension driverExtension = FlutterDriverExtension(
1088
        (String? arg) async => '',
1089
        true,
1090
        true,
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
        commands: <CommandExtension>[
          StubNestedCommandExtension(),
        ],
      );

      Future<StubCommandResult> invokeCommand(SerializableFinder finder, int times) async {
        await driverExtension.call(const SetFrameSync(false).serialize()); // disable frame sync for test to avoid lock
        final Map<String, String> arguments = StubNestedCommand(finder, times, timeout: const Duration(seconds: 1)).serialize();
        final Map<String, dynamic> response = await driverExtension.call(arguments);
        final Map<String, dynamic> commandResponse = response['response'] as Map<String, dynamic>;
        return StubCommandResult(commandResponse['resultParam'] as String);
      }

      await tester.pumpWidget(debugTree);

      const int times = 10;
      final StubCommandResult result = await invokeCommand(ByValueKey('Button'), times);
      expect(result.resultParam, 'stub response');
      expect(invokes, times);
    });

    testWidgets('prober command', (WidgetTester tester) async {
      final FlutterDriverExtension driverExtension = FlutterDriverExtension(
1114
        (String? arg) async => '',
1115
        true,
1116
        true,
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
        commands: <CommandExtension>[
          StubProberCommandExtension(),
        ],
      );

      Future<StubCommandResult> invokeCommand(SerializableFinder finder, int times) async {
        await driverExtension.call(const SetFrameSync(false).serialize()); // disable frame sync for test to avoid lock
        final Map<String, String> arguments = StubProberCommand(finder, times, timeout: const Duration(seconds: 1)).serialize();
        final Map<String, dynamic> response = await driverExtension.call(arguments);
        final Map<String, dynamic> commandResponse = response['response'] as Map<String, dynamic>;
        return StubCommandResult(commandResponse['resultParam'] as String);
      }

      await tester.pumpWidget(debugTree);

      const int times = 10;
      final StubCommandResult result = await invokeCommand(ByValueKey('Button'), times);
      expect(result.resultParam, 'stub response');
      expect(invokes, times);
    });
  });
1138

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
  group('waitForTappable', () {
    late FlutterDriverExtension driverExtension;

    Future<Map<String, dynamic>> waitForTappable() async {
      final SerializableFinder finder = ByValueKey('widgetOne');
      final Map<String, String> arguments = WaitForTappable(finder).serialize();
      final Map<String, dynamic> result = await driverExtension.call(arguments);
      return result;
    }

    final Widget testWidget = MaterialApp(
      home: Material(
        child: Column(children: const<Widget> [
          Text('Hello ', key: Key('widgetOne')),
          SizedBox(
            height: 0,
            width: 0,
            child: Text('World!', key: Key('widgetTwo')),
            )
          ],
        ),
      ),
    );

    testWidgets('returns true when widget is tappable', (
        WidgetTester tester) async {
      driverExtension = FlutterDriverExtension((String? arg) async => '', true, false);

      await tester.pumpWidget(testWidget);

      final Map<String, dynamic> waitForTappableResult = await waitForTappable();
      expect(waitForTappableResult['isError'], isFalse);
    });
  });

1174
  group('waitUntilFrameSync', () {
1175 1176
    late FlutterDriverExtension driverExtension;
    Map<String, dynamic>? result;
1177 1178

    setUp(() {
1179
      driverExtension = FlutterDriverExtension((String? arg) async => '', true, true);
1180 1181 1182 1183 1184
      result = null;
    });

    testWidgets('returns immediately when frame is synced', (
        WidgetTester tester) async {
1185
      driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
1186 1187 1188 1189 1190 1191 1192 1193 1194
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      await tester.idle();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
1195
          'response': <String, dynamic>{},
1196 1197 1198 1199 1200 1201
        },
      );
    });

    testWidgets(
        'waits until no transient callbacks', (WidgetTester tester) async {
1202
      SchedulerBinding.instance!.scheduleFrameCallback((_) {
1203 1204 1205
        // Intentionally blank. We only care about existence of a callback.
      });

1206
      driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
1221
          'response': <String, dynamic>{},
1222 1223 1224 1225 1226 1227
        },
      );
    });

    testWidgets(
        'waits until no pending scheduled frame', (WidgetTester tester) async {
1228
      SchedulerBinding.instance!.scheduleFrame();
1229

1230
      driverExtension.call(const WaitForCondition(NoPendingFrame()).serialize())
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
1245
          'response': <String, dynamic>{},
1246 1247 1248 1249
        },
      );
    });
  });
1250
}