search_test.dart 22 KB
Newer Older
1 2 3 4
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:flutter/foundation.dart';
6
import 'package:flutter/material.dart';
7
import 'package:flutter/services.dart';
8 9
import 'package:flutter_test/flutter_test.dart';

10 11
import '../widgets/semantics_tester.dart';

12 13
void main() {
  testWidgets('Can open and close search', (WidgetTester tester) async {
14
    final _TestSearchDelegate delegate = _TestSearchDelegate();
15 16
    final List<String> selectedResults = <String>[];

17
    await tester.pumpWidget(TestHomePage(
18 19 20 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 47 48
      delegate: delegate,
      results: selectedResults,
    ));

    // We are on the homepage
    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);

    // Open search
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('HomeTitle'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
    expect(selectedResults, hasLength(0));

    final TextField textField = tester.widget(find.byType(TextField));
    expect(textField.focusNode.hasFocus, isTrue);

    // Close search
    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);
    expect(selectedResults, <String>['Result']);
  });

49 50 51
  testWidgets('Can close search with system back button to return null', (WidgetTester tester) async {
    // regression test for https://github.com/flutter/flutter/issues/18145

52
    final _TestSearchDelegate delegate = _TestSearchDelegate();
53 54
    final List<String> selectedResults = <String>[];

55
    await tester.pumpWidget(TestHomePage(
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
      delegate: delegate,
      results: selectedResults,
    ));

    // We are on the homepage
    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);

    // Open search
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('HomeTitle'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);

    // Simulate system back button
    final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
    await BinaryMessages.handlePlatformMessage('flutter/navigation', message, (_) {});
    await tester.pumpAndSettle();

    expect(selectedResults, <void>[null]);

    // We are on the homepage again
    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);

    // Open search again
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('HomeTitle'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
  });

94
  testWidgets('Requests suggestions', (WidgetTester tester) async {
95
    final _TestSearchDelegate delegate = _TestSearchDelegate();
96

97
    await tester.pumpWidget(TestHomePage(
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, '');
    expect(delegate.querysForSuggestions.last, '');
    expect(delegate.querysForResults, hasLength(0));

    // Type W o w into search field
    delegate.querysForSuggestions.clear();
    await tester.enterText(find.byType(TextField), 'W');
    await tester.pumpAndSettle();
    expect(delegate.query, 'W');
    await tester.enterText(find.byType(TextField), 'Wo');
    await tester.pumpAndSettle();
    expect(delegate.query, 'Wo');
    await tester.enterText(find.byType(TextField), 'Wow');
    await tester.pumpAndSettle();
    expect(delegate.query, 'Wow');

    expect(delegate.querysForSuggestions, <String>['W', 'Wo', 'Wow']);
    expect(delegate.querysForResults, hasLength(0));
  });

  testWidgets('Shows Results and closes search', (WidgetTester tester) async {
124
    final _TestSearchDelegate delegate = _TestSearchDelegate();
125 126
    final List<String> selectedResults = <String>[];

127
    await tester.pumpWidget(TestHomePage(
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
      delegate: delegate,
      results: selectedResults,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();
    await tester.enterText(find.byType(TextField), 'Wow');
    await tester.pumpAndSettle();
    await tester.tap(find.text('Suggestions'));
    await tester.pumpAndSettle();

    // We are on the results page for Wow
    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('HomeTitle'), findsNothing);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Results'), findsOneWidget);

    final TextField textField = tester.widget(find.byType(TextField));
    expect(textField.focusNode.hasFocus, isFalse);
    expect(delegate.querysForResults, <String>['Wow']);

    // Close search
    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('HomeTitle'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Results'), findsNothing);
    expect(selectedResults, <String>['Result']);
  });

  testWidgets('Can switch between results and suggestions',
      (WidgetTester tester) async {
161
    final _TestSearchDelegate delegate = _TestSearchDelegate();
162

163
    await tester.pumpWidget(TestHomePage(
164 165 166
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
167
    await tester.pumpAndSettle();
168 169 170 171 172 173 174 175

    // Showing suggestions
    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Results'), findsNothing);

    // Typing query Wow
    delegate.querysForSuggestions.clear();
    await tester.enterText(find.byType(TextField), 'Wow');
176
    await tester.pumpAndSettle();
177 178 179 180 181 182

    expect(delegate.query, 'Wow');
    expect(delegate.querysForSuggestions, <String>['Wow']);
    expect(delegate.querysForResults, hasLength(0));

    await tester.tap(find.text('Suggestions'));
183
    await tester.pumpAndSettle();
184 185 186 187 188 189 190 191 192 193 194 195 196 197

    // Showing Results
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Results'), findsOneWidget);

    expect(delegate.query, 'Wow');
    expect(delegate.querysForSuggestions, <String>['Wow']);
    expect(delegate.querysForResults, <String>['Wow']);

    TextField textField = tester.widget(find.byType(TextField));
    expect(textField.focusNode.hasFocus, isFalse);

    // Taping search field to go back to suggestions
    await tester.tap(find.byType(TextField));
198
    await tester.pumpAndSettle();
199 200 201 202 203 204 205 206 207 208

    textField = tester.widget(find.byType(TextField));
    expect(textField.focusNode.hasFocus, isTrue);

    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Results'), findsNothing);
    expect(delegate.querysForSuggestions, <String>['Wow', 'Wow']);
    expect(delegate.querysForResults, <String>['Wow']);

    await tester.enterText(find.byType(TextField), 'Foo');
209
    await tester.pumpAndSettle();
210 211 212 213 214 215 216

    expect(delegate.query, 'Foo');
    expect(delegate.querysForSuggestions, <String>['Wow', 'Wow', 'Foo']);
    expect(delegate.querysForResults, <String>['Wow']);

    // Go to results again
    await tester.tap(find.text('Suggestions'));
217
    await tester.pumpAndSettle();
218 219 220 221 222 223 224 225 226 227 228 229 230 231

    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Results'), findsOneWidget);

    expect(delegate.query, 'Foo');
    expect(delegate.querysForSuggestions, <String>['Wow', 'Wow', 'Foo']);
    expect(delegate.querysForResults, <String>['Wow', 'Foo']);

    textField = tester.widget(find.byType(TextField));
    expect(textField.focusNode.hasFocus, isFalse);
  });

  testWidgets('Fresh search allways starts with empty query',
      (WidgetTester tester) async {
232
    final _TestSearchDelegate delegate = _TestSearchDelegate();
233

234
    await tester.pumpWidget(TestHomePage(
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, '');

    delegate.query = 'Foo';
    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, '');
  });

  testWidgets('Initial queries are honored', (WidgetTester tester) async {
252
    final _TestSearchDelegate delegate = _TestSearchDelegate();
253 254 255

    expect(delegate.query, '');

256
    await tester.pumpWidget(TestHomePage(
257 258 259 260 261 262 263 264 265 266 267
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: 'Foo',
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, 'Foo');
  });

  testWidgets('Initial query null re-used previous query', (WidgetTester tester) async {
268
    final _TestSearchDelegate delegate = _TestSearchDelegate();
269 270 271

    delegate.query = 'Foo';

272
    await tester.pumpWidget(TestHomePage(
273 274 275 276 277 278 279 280 281 282 283
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: null,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(delegate.query, 'Foo');
  });

  testWidgets('Changing query shows up in search field', (WidgetTester tester) async {
284
    final _TestSearchDelegate delegate = _TestSearchDelegate();
285

286
    await tester.pumpWidget(TestHomePage(
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: null,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    delegate.query = 'Foo';

    expect(find.text('Foo'), findsOneWidget);
    expect(find.text('Bar'), findsNothing);

    delegate.query = 'Bar';

    expect(find.text('Foo'), findsNothing);
    expect(find.text('Bar'), findsOneWidget);
  });

  testWidgets('transitionAnimation runs while search fades in/out', (WidgetTester tester) async {
306
    final _TestSearchDelegate delegate = _TestSearchDelegate();
307

308
    await tester.pumpWidget(TestHomePage(
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
      delegate: delegate,
      passInInitialQuery: true,
      initialQuery: null,
    ));

    // runs while search fades in
    expect(delegate.transitionAnimation.status, AnimationStatus.dismissed);
    await tester.tap(find.byTooltip('Search'));
    expect(delegate.transitionAnimation.status, AnimationStatus.forward);
    await tester.pumpAndSettle();
    expect(delegate.transitionAnimation.status, AnimationStatus.completed);

    // does not run while switching to results
    await tester.tap(find.text('Suggestions'));
    expect(delegate.transitionAnimation.status, AnimationStatus.completed);
    await tester.pumpAndSettle();
    expect(delegate.transitionAnimation.status, AnimationStatus.completed);

    // runs while search fades out
    await tester.tap(find.byTooltip('Back'));
    expect(delegate.transitionAnimation.status, AnimationStatus.reverse);
    await tester.pumpAndSettle();
    expect(delegate.transitionAnimation.status, AnimationStatus.dismissed);
  });

  testWidgets('Closing nested search returns to search', (WidgetTester tester) async {
    final List<String> nestedSearchResults = <String>[];
336
    final _TestSearchDelegate nestedSearchDelegate = _TestSearchDelegate(
337 338 339 340 341
      suggestions: 'Nested Suggestions',
      result: 'Nested Result',
    );

    final List<String> selectedResults = <String>[];
342
    final _TestSearchDelegate delegate = _TestSearchDelegate(
343
      actions: <Widget>[
344
        Builder(
345
          builder: (BuildContext context) {
346
            return IconButton(
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
              tooltip: 'Nested Search',
              icon: const Icon(Icons.search),
              onPressed: () async {
                final String result = await showSearch(
                  context: context,
                  delegate: nestedSearchDelegate,
                );
                nestedSearchResults.add(result);
              },
            );
          },
        )
      ],
    );

362
    await tester.pumpWidget(TestHomePage(
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
      delegate: delegate,
      results: selectedResults,
    ));
    expect(find.text('HomeBody'), findsOneWidget);
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Nested Suggestions'), findsNothing);

    await tester.tap(find.byTooltip('Nested Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Nested Suggestions'), findsOneWidget);

    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();
    expect(nestedSearchResults, <String>['Nested Result']);

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Nested Suggestions'), findsNothing);

    await tester.tap(find.byTooltip('Back'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Nested Suggestions'), findsNothing);
    expect(selectedResults, <String>['Result']);
  });

  testWidgets('Closing search with nested search shown goes back to underlying route', (WidgetTester tester) async {
    _TestSearchDelegate delegate;
    final List<String> nestedSearchResults = <String>[];
401
    final _TestSearchDelegate nestedSearchDelegate = _TestSearchDelegate(
402 403 404
      suggestions: 'Nested Suggestions',
      result: 'Nested Result',
      actions: <Widget>[
405
        Builder(
406
          builder: (BuildContext context) {
407
            return IconButton(
408 409 410 411 412 413 414 415 416 417 418 419
              tooltip: 'Close Search',
              icon: const Icon(Icons.close),
              onPressed: () async {
                delegate.close(context, 'Result Foo');
              },
            );
          },
        )
      ],
    );

    final List<String> selectedResults = <String>[];
420
    delegate = _TestSearchDelegate(
421
      actions: <Widget>[
422
        Builder(
423
          builder: (BuildContext context) {
424
            return IconButton(
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
              tooltip: 'Nested Search',
              icon: const Icon(Icons.search),
              onPressed: () async {
                final String result = await showSearch(
                  context: context,
                  delegate: nestedSearchDelegate,
                );
                nestedSearchResults.add(result);
              },
            );
          },
        )
      ],
    );

440
    await tester.pumpWidget(TestHomePage(
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
      delegate: delegate,
      results: selectedResults,
    ));

    expect(find.text('HomeBody'), findsOneWidget);
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsOneWidget);
    expect(find.text('Nested Suggestions'), findsNothing);

    await tester.tap(find.byTooltip('Nested Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsNothing);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Nested Suggestions'), findsOneWidget);

    await tester.tap(find.byTooltip('Close Search'));
    await tester.pumpAndSettle();

    expect(find.text('HomeBody'), findsOneWidget);
    expect(find.text('Suggestions'), findsNothing);
    expect(find.text('Nested Suggestions'), findsNothing);
466
    expect(nestedSearchResults, <String>[null]);
467 468
    expect(selectedResults, <String>['Result Foo']);
  });
469 470

  testWidgets('keyboard show search button', (WidgetTester tester) async {
471
    final _TestSearchDelegate delegate = _TestSearchDelegate();
472

473
    await tester.pumpWidget(TestHomePage(
474 475 476 477 478 479 480 481 482
      delegate: delegate,
    ));
    await tester.tap(find.byTooltip('Search'));
    await tester.pumpAndSettle();

    await tester.showKeyboard(find.byType(TextField));

    expect(tester.testTextInput.setClientArgs['inputAction'], TextInputAction.search.toString());
  });
483 484 485

  group('contributes semantics', () {
    TestSemantics buildExpected({String routeName}) {
486
      return TestSemantics.root(
487
        children: <TestSemantics>[
488
          TestSemantics(
489 490 491
            id: 1,
            textDirection: TextDirection.ltr,
            children: <TestSemantics>[
492
              TestSemantics(
493 494 495 496 497 498 499 500
                id: 7,
                flags: <SemanticsFlag>[
                  SemanticsFlag.scopesRoute,
                  SemanticsFlag.namesRoute,
                ],
                label: routeName,
                textDirection: TextDirection.ltr,
                children: <TestSemantics>[
501
                  TestSemantics(
502 503
                    id: 9,
                    children: <TestSemantics>[
504
                      TestSemantics(
505 506 507 508 509 510 511 512 513 514
                        id: 10,
                        flags: <SemanticsFlag>[
                          SemanticsFlag.isButton,
                          SemanticsFlag.hasEnabledState,
                          SemanticsFlag.isEnabled,
                        ],
                        actions: <SemanticsAction>[SemanticsAction.tap],
                        label: 'Back',
                        textDirection: TextDirection.ltr,
                      ),
515
                      TestSemantics(
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
                        id: 11,
                        flags: <SemanticsFlag>[
                          SemanticsFlag.isTextField,
                          SemanticsFlag.isFocused,
                          SemanticsFlag.isHeader,
                          SemanticsFlag.namesRoute,
                        ],
                        actions: <SemanticsAction>[
                          SemanticsAction.tap,
                          SemanticsAction.setSelection,
                          SemanticsAction.paste,
                        ],
                        label: 'Search',
                        textDirection: TextDirection.ltr,
                      ),
                    ],
                  ),
533
                  TestSemantics(
534 535 536 537 538 539 540 541 542 543
                    id: 8,
                    flags: <SemanticsFlag>[
                      SemanticsFlag.isButton,
                      SemanticsFlag.hasEnabledState,
                      SemanticsFlag.isEnabled,
                    ],
                    actions: <SemanticsAction>[SemanticsAction.tap],
                    label: 'Suggestions',
                    textDirection: TextDirection.ltr,
                  ),
544 545 546 547 548 549 550 551 552
                ],
              ),
            ],
          ),
        ],
      );
    }

    testWidgets('includes routeName on Android', (WidgetTester tester) async {
553 554 555
      final SemanticsTester semantics = SemanticsTester(tester);
      final _TestSearchDelegate delegate = _TestSearchDelegate();
      await tester.pumpWidget(TestHomePage(
556 557 558 559 560 561 562 563 564 565 566 567 568 569
        delegate: delegate,
      ));

      await tester.tap(find.byTooltip('Search'));
      await tester.pumpAndSettle();

      expect(semantics, hasSemantics(buildExpected(routeName: 'Search'),
          ignoreId: true, ignoreRect: true, ignoreTransform: true));

      semantics.dispose();
    });

    testWidgets('does not include routeName on iOS', (WidgetTester tester) async {
      debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
570 571 572
      final SemanticsTester semantics = SemanticsTester(tester);
      final _TestSearchDelegate delegate = _TestSearchDelegate();
      await tester.pumpWidget(TestHomePage(
573 574 575 576 577 578 579 580 581 582 583 584 585
        delegate: delegate,
      ));

      await tester.tap(find.byTooltip('Search'));
      await tester.pumpAndSettle();

      expect(semantics, hasSemantics(buildExpected(routeName: ''),
          ignoreId: true, ignoreRect: true, ignoreTransform: true));

      debugDefaultTargetPlatformOverride = null;
      semantics.dispose();
    });
  });
586 587 588 589 590 591
}

class TestHomePage extends StatelessWidget {
  const TestHomePage({
    this.results,
    this.delegate,
592
    this.passInInitialQuery = false,
593 594 595 596 597 598 599 600 601 602
    this.initialQuery,
  });

  final List<String> results;
  final SearchDelegate<String> delegate;
  final bool passInInitialQuery;
  final String initialQuery;

  @override
  Widget build(BuildContext context) {
603
    return MaterialApp(
604
      home: Builder(builder: (BuildContext context) {
605 606
        return Scaffold(
          appBar: AppBar(
607 608
            title: const Text('HomeTitle'),
            actions: <Widget>[
609
              IconButton(
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
                tooltip: 'Search',
                icon: const Icon(Icons.search),
                onPressed: () async {
                  String selectedResult;
                  if (passInInitialQuery) {
                    selectedResult = await showSearch<String>(
                      context: context,
                      delegate: delegate,
                      query: initialQuery,
                    );
                  } else {
                    selectedResult = await showSearch<String>(
                      context: context,
                      delegate: delegate,
                    );
                  }
                  results?.add(selectedResult);
                },
              ),
            ],
          ),
          body: const Text('HomeBody'),
        );
      }),
    );
  }
}

class _TestSearchDelegate extends SearchDelegate<String> {

  _TestSearchDelegate({
641 642 643
    this.suggestions = 'Suggestions',
    this.result = 'Result',
    this.actions = const <Widget>[],
644 645 646 647 648 649 650 651
  });

  final String suggestions;
  final String result;
  final List<Widget> actions;

  @override
  Widget buildLeading(BuildContext context) {
652
    return IconButton(
653 654 655 656 657 658 659 660 661 662 663 664 665 666
      tooltip: 'Back',
      icon: const Icon(Icons.arrow_back),
      onPressed: () {
        close(context, result);
      },
    );
  }

  final List<String> querysForSuggestions = <String>[];
  final List<String> querysForResults = <String>[];

  @override
  Widget buildSuggestions(BuildContext context) {
    querysForSuggestions.add(query);
667
    return MaterialButton(
668 669 670
      onPressed: () {
        showResults(context);
      },
671
      child: Text(suggestions),
672 673 674 675 676 677 678 679 680 681 682 683 684 685
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    querysForResults.add(query);
    return const Text('Results');
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return actions;
  }
}