finders.dart 21 KB
Newer Older
1 2 3 4
// Copyright 2016 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/gestures.dart';
6
import 'package:flutter/material.dart';
7
import 'package:meta/meta.dart';
8 9 10

import 'all_elements.dart';

11
/// Signature for [CommonFinders.byWidgetPredicate].
12 13
typedef bool WidgetPredicate(Widget widget);

14
/// Signature for [CommonFinders.byElementPredicate].
15 16 17 18 19 20 21 22 23 24 25
typedef bool ElementPredicate(Element element);

/// Some frequently used widget [Finder]s.
final CommonFinders find = const CommonFinders._();

/// Provides lightweight syntax for getting frequently used widget [Finder]s.
///
/// This class is instantiated once, as [find].
class CommonFinders {
  const CommonFinders._();

26 27
  /// Finds [Text] and [EditableText] widgets containing string equal to the
  /// `text` argument.
28 29 30
  ///
  /// Example:
  ///
31
  ///     expect(find.text('Back'), findsOneWidget);
32 33 34 35
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
  Finder text(String text, { bool skipOffstage: true }) => new _TextFinder(text, skipOffstage: skipOffstage);
36 37 38 39 40 41 42 43 44 45 46 47 48

  /// Looks for widgets that contain a [Text] descendant with `text`
  /// in it.
  ///
  /// Example:
  ///
  ///     // Suppose you have a button with text 'Update' in it:
  ///     new Button(
  ///       child: new Text('Update')
  ///     )
  ///
  ///     // You can find and tap on it like this:
  ///     tester.tap(find.widgetWithText(Button, 'Update'));
49 50 51 52 53
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
  Finder widgetWithText(Type widgetType, String text, { bool skipOffstage: true }) {
    return new _WidgetWithTextFinder(widgetType, text, skipOffstage: skipOffstage);
54 55 56 57 58 59
  }

  /// Finds widgets by searching for one with a particular [Key].
  ///
  /// Example:
  ///
60
  ///     expect(find.byKey(backKey), findsOneWidget);
61 62 63 64
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
  Finder byKey(Key key, { bool skipOffstage: true }) => new _KeyFinder(key, skipOffstage: skipOffstage);
65 66 67 68 69 70 71 72 73 74 75

  /// Finds widgets by searching for widgets with a particular type.
  ///
  /// This does not do subclass tests, so for example
  /// `byType(StatefulWidget)` will never find anything since that's
  /// an abstract class.
  ///
  /// The `type` argument must be a subclass of [Widget].
  ///
  /// Example:
  ///
76
  ///     expect(find.byType(IconButton), findsOneWidget);
77 78 79 80
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
  Finder byType(Type type, { bool skipOffstage: true }) => new _WidgetTypeFinder(type, skipOffstage: skipOffstage);
81

82 83
  /// Finds [Icon] widgets containing icon data equal to the `icon`
  /// argument.
84 85 86 87 88 89 90 91 92
  ///
  /// Example:
  ///
  ///     expect(find.byIcon(Icons.inbox), findsOneWidget);
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
  Finder byIcon(IconData icon, { bool skipOffstage: true }) => new _WidgetIconFinder(icon, skipOffstage: skipOffstage);

93 94 95 96 97 98 99 100 101 102
  /// Finds widgets by searching for elements with a particular type.
  ///
  /// This does not do subclass tests, so for example
  /// `byElementType(VirtualViewportElement)` will never find anything
  /// since that's an abstract class.
  ///
  /// The `type` argument must be a subclass of [Element].
  ///
  /// Example:
  ///
103
  ///     expect(find.byElementType(SingleChildRenderObjectElement), findsOneWidget);
104 105 106 107
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
  Finder byElementType(Type type, { bool skipOffstage: true }) => new _ElementTypeFinder(type, skipOffstage: skipOffstage);
108 109 110 111 112 113 114 115 116 117 118 119

  /// Finds widgets whose current widget is the instance given by the
  /// argument.
  ///
  /// Example:
  ///
  ///     // Suppose you have a button created like this:
  ///     Widget myButton = new Button(
  ///       child: new Text('Update')
  ///     );
  ///
  ///     // You can find and tap on it like this:
120
  ///     tester.tap(find.byWidget(myButton));
121 122 123
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
124
  Finder byWidget(Widget widget, { bool skipOffstage: true }) => new _WidgetFinder(widget, skipOffstage: skipOffstage);
125

126
  /// Finds widgets using a widget [predicate].
127 128 129
  ///
  /// Example:
  ///
130
  ///     expect(find.byWidgetPredicate(
131 132
  ///       (Widget widget) => widget is Tooltip && widget.message == 'Back',
  ///       description: 'widget with tooltip "Back"',
133
  ///     ), findsOneWidget);
134
  ///
135 136 137 138 139
  /// If [description] is provided, then this uses it as the description of the
  /// [Finder] and appears, for example, in the error message when the finder
  /// fails to locate the desired widget. Otherwise, the description prints the
  /// signature of the predicate function.
  ///
140 141
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
142 143
  Finder byWidgetPredicate(WidgetPredicate predicate, { String description, bool skipOffstage: true }) {
    return new _WidgetPredicateFinder(predicate, description: description, skipOffstage: skipOffstage);
144 145
  }

146 147 148 149
  /// Finds Tooltip widgets with the given message.
  ///
  /// Example:
  ///
150
  ///     expect(find.byTooltip('Back'), findsOneWidget);
151 152 153 154 155 156 157 158 159 160
  ///
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
  Finder byTooltip(String message, { bool skipOffstage: true }) {
    return byWidgetPredicate(
      (Widget widget) => widget is Tooltip && widget.message == message,
      skipOffstage: skipOffstage,
    );
  }

161
  /// Finds widgets using an element [predicate].
162 163 164
  ///
  /// Example:
  ///
165
  ///     expect(find.byElementPredicate(
166 167 168
  ///       // finds elements of type SingleChildRenderObjectElement, including
  ///       // those that are actually subclasses of that type.
  ///       // (contrast with byElementType, which only returns exact matches)
169 170
  ///       (Element element) => element is SingleChildRenderObjectElement,
  ///       description: '$SingleChildRenderObjectElement element',
171
  ///     ), findsOneWidget);
172
  ///
173 174 175 176 177
  /// If [description] is provided, then this uses it as the description of the
  /// [Finder] and appears, for example, in the error message when the finder
  /// fails to locate the desired widget. Otherwise, the description prints the
  /// signature of the predicate function.
  ///
178 179
  /// If the `skipOffstage` argument is true (the default), then this skips
  /// nodes that are [Offstage] or that are from inactive [Route]s.
180 181
  Finder byElementPredicate(ElementPredicate predicate, { String description, bool skipOffstage: true }) {
    return new _ElementPredicateFinder(predicate, description: description, skipOffstage: skipOffstage);
182
  }
183

184 185
  /// Finds widgets that are descendants of the [of] parameter and that match
  /// the [matching] parameter.
186 187 188 189 190
  ///
  /// Example:
  ///
  ///     expect(find.descendant(
  ///       of: find.widgetWithText(Row, 'label_1'), matching: find.text('value_1')
191
  ///     ), findsOneWidget);
192
  ///
193 194 195
  /// If the [matchRoot] argument is true then the widget(s) specified by [of]
  /// will be matched along with the descendants.
  ///
196 197
  /// If the [skipOffstage] argument is true (the default), then nodes that are
  /// [Offstage] or that are from inactive [Route]s are skipped.
198 199
  Finder descendant({ Finder of, Finder matching, bool matchRoot: false, bool skipOffstage: true }) {
    return new _DescendantFinder(of, matching, matchRoot: matchRoot, skipOffstage: skipOffstage);
200
  }
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

  /// Finds widgets that are ancestors of the [of] parameter and that match
  /// the [matching] parameter.
  ///
  /// Example:
  ///
  ///     // Test if a Text widget that contains 'faded' is the
  ///     // descendant of an Opacity widget with opacity 0.5:
  ///     expect(
  ///       tester.widget<Opacity>(
  ///         find.ancestor(
  ///           of: find.text('faded'),
  ///           matching: find.byType('Opacity'),
  ///         )
  ///       ).opacity,
  ///       0.5
  ///     );
  ///
  /// If the [matchRoot] argument is true then the widget(s) specified by [of]
  /// will be matched along with the ancestors.
  Finder ancestor({ Finder of, Finder matching, bool matchRoot: false}) {
    return new _AncestorFinder(of, matching, matchRoot: matchRoot);
  }
224 225 226 227 228
}

/// Searches a widget tree and returns nodes that match a particular
/// pattern.
abstract class Finder {
229
  /// Initializes a Finder. Used by subclasses to initialize the [skipOffstage]
230 231 232
  /// property.
  Finder({ this.skipOffstage: true });

233 234 235 236 237 238 239 240 241 242 243 244 245
  /// Describes what the finder is looking for. The description should be
  /// a brief English noun phrase describing the finder's pattern.
  String get description;

  /// Returns all the elements in the given list that match this
  /// finder's pattern.
  ///
  /// When implementing your own Finders that inherit directly from
  /// [Finder], this is the main method to override. If your finder
  /// can efficiently be described just in terms of a predicate
  /// function, consider extending [MatchFinder] instead.
  Iterable<Element> apply(Iterable<Element> candidates);

246 247 248
  /// Whether this finder skips nodes that are offstage.
  ///
  /// If this is true, then the elements are walked using
249
  /// [Element.debugVisitOnstageChildren]. This skips offstage children of
250 251 252
  /// [Offstage] widgets, as well as children of inactive [Route]s.
  final bool skipOffstage;

253 254 255
  /// Returns all the [Element]s that will be considered by this finder.
  ///
  /// See [collectAllElementsFrom].
256 257
  @protected
  Iterable<Element> get allCandidates {
258 259 260 261 262
    return collectAllElementsFrom(
      WidgetsBinding.instance.renderViewElement,
      skipOffstage: skipOffstage
    );
  }
263 264 265 266 267 268 269 270 271

  Iterable<Element> _cachedResult;

  /// Returns the current result. If [precache] was called and returned true, this will
  /// cheaply return the result that was computed then. Otherwise, it creates a new
  /// iterable to compute the answer.
  ///
  /// Calling this clears the cache from [precache].
  Iterable<Element> evaluate() {
272
    final Iterable<Element> result = _cachedResult ?? apply(allCandidates);
273 274 275 276 277 278 279 280 281 282 283
    _cachedResult = null;
    return result;
  }

  /// Attempts to evaluate the finder. Returns whether any elements in the tree
  /// matched the finder. If any did, then the result is cached and can be obtained
  /// from [evaluate].
  ///
  /// If this returns true, you must call [evaluate] before you call [precache] again.
  bool precache() {
    assert(_cachedResult == null);
284
    final Iterable<Element> result = apply(allCandidates);
285 286 287 288 289 290 291 292
    if (result.isNotEmpty) {
      _cachedResult = result;
      return true;
    }
    _cachedResult = null;
    return false;
  }

293 294 295 296 297 298 299 300
  /// Returns a variant of this finder that only matches the first element
  /// matched by this finder.
  Finder get first => new _FirstFinder(this);

  /// Returns a variant of this finder that only matches the last element
  /// matched by this finder.
  Finder get last => new _LastFinder(this);

301 302 303 304
  /// Returns a variant of this finder that only matches the element at the
  /// given index matched by this finder.
  Finder at(int index) => new _IndexFinder(this, index);

305 306 307 308 309
  /// Returns a variant of this finder that only matches elements reachable by
  /// a hit test.
  ///
  /// The [at] parameter specifies the location relative to the size of the
  /// target element where the hit test is performed.
310
  Finder hitTestable({ Alignment at: Alignment.center }) => new _HitTestableFinder(this, at);
311

312 313
  @override
  String toString() {
314
    final String additional = skipOffstage ? ' (ignoring offstage widgets)' : '';
315 316 317
    final List<Element> widgets = evaluate().toList();
    final int count = widgets.length;
    if (count == 0)
318
      return 'zero widgets with $description$additional';
319
    if (count == 1)
320
      return 'exactly one widget with $description$additional: ${widgets.single}';
321
    if (count < 4)
322 323
      return '$count widgets with $description$additional: $widgets';
    return '$count widgets with $description$additional: ${widgets[0]}, ${widgets[1]}, ${widgets[2]}, ...';
324 325 326
  }
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
class _FirstFinder extends Finder {
  _FirstFinder(this.parent);

  final Finder parent;

  @override
  String get description => '${parent.description} (ignoring all but first)';

  @override
  Iterable<Element> apply(Iterable<Element> candidates) sync* {
    yield parent.apply(candidates).first;
  }
}

class _LastFinder extends Finder {
  _LastFinder(this.parent);

  final Finder parent;

  @override
  String get description => '${parent.description} (ignoring all but last)';

  @override
  Iterable<Element> apply(Iterable<Element> candidates) sync* {
    yield parent.apply(candidates).last;
  }
}

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
class _IndexFinder extends Finder {
  _IndexFinder(this.parent, this.index);

  final Finder parent;

  final int index;

  @override
  String get description => '${parent.description} (ignoring all but index $index)';

  @override
  Iterable<Element> apply(Iterable<Element> candidates) sync* {
    yield parent.apply(candidates).elementAt(index);
  }
}

371
class _HitTestableFinder extends Finder {
372
  _HitTestableFinder(this.parent, this.alignment);
373 374

  final Finder parent;
375
  final Alignment alignment;
376 377 378 379 380 381 382 383 384

  @override
  String get description => '${parent.description} (considering only hit-testable ones)';

  @override
  Iterable<Element> apply(Iterable<Element> candidates) sync* {
    for (final Element candidate in parent.apply(candidates)) {
      final RenderBox box = candidate.renderObject;
      assert(box != null);
385
      final Offset absoluteOffset = box.localToGlobal(alignment.alongSize(box.size));
386 387 388 389 390 391 392 393 394 395 396 397
      final HitTestResult hitResult = new HitTestResult();
      WidgetsBinding.instance.hitTest(hitResult, absoluteOffset);
      for (final HitTestEntry entry in hitResult.path) {
        if (entry.target == candidate.renderObject) {
          yield candidate;
          break;
        }
      }
    }
  }
}

398 399 400
/// Searches a widget tree and returns nodes that match a particular
/// pattern.
abstract class MatchFinder extends Finder {
401
  /// Initializes a predicate-based Finder. Used by subclasses to initialize the
402 403 404
  /// [skipOffstage] property.
  MatchFinder({ bool skipOffstage: true }) : super(skipOffstage: skipOffstage);

405 406 407 408 409 410 411 412 413 414 415 416
  /// Returns true if the given element matches the pattern.
  ///
  /// When implementing your own MatchFinder, this is the main method to override.
  bool matches(Element candidate);

  @override
  Iterable<Element> apply(Iterable<Element> candidates) {
    return candidates.where(matches);
  }
}

class _TextFinder extends MatchFinder {
417
  _TextFinder(this.text, { bool skipOffstage: true }) : super(skipOffstage: skipOffstage);
418 419 420 421 422 423 424 425

  final String text;

  @override
  String get description => 'text "$text"';

  @override
  bool matches(Element candidate) {
426 427 428 429 430 431 432 433
    if (candidate.widget is Text) {
      final Text textWidget = candidate.widget;
      return textWidget.data == text;
    } else if (candidate.widget is EditableText) {
      final EditableText editable = candidate.widget;
      return editable.controller.text == text;
    }
    return false;
434 435 436 437
  }
}

class _WidgetWithTextFinder extends Finder {
438
  _WidgetWithTextFinder(this.widgetType, this.text, { bool skipOffstage: true }) : super(skipOffstage: skipOffstage);
439 440 441 442 443 444 445 446 447 448 449 450 451 452

  final Type widgetType;
  final String text;

  @override
  String get description => 'type $widgetType with text "$text"';

  @override
  Iterable<Element> apply(Iterable<Element> candidates) {
    return candidates
      .map((Element textElement) {
        if (textElement.widget is! Text)
          return null;

453
        final Text textWidget = textElement.widget;
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
        if (textWidget.data == text) {
          try {
            textElement.visitAncestorElements((Element element) {
              if (element.widget.runtimeType == widgetType)
                throw element;
              return true;
            });
          } on Element catch (result) {
            return result;
          }
        }
        return null;
      })
      .where((Element element) => element != null);
  }
}

class _KeyFinder extends MatchFinder {
472
  _KeyFinder(this.key, { bool skipOffstage: true }) : super(skipOffstage: skipOffstage);
473 474 475 476 477 478 479 480 481 482 483 484 485

  final Key key;

  @override
  String get description => 'key $key';

  @override
  bool matches(Element candidate) {
    return candidate.widget.key == key;
  }
}

class _WidgetTypeFinder extends MatchFinder {
486
  _WidgetTypeFinder(this.widgetType, { bool skipOffstage: true }) : super(skipOffstage: skipOffstage);
487 488 489 490 491 492 493 494 495 496 497 498

  final Type widgetType;

  @override
  String get description => 'type "$widgetType"';

  @override
  bool matches(Element candidate) {
    return candidate.widget.runtimeType == widgetType;
  }
}

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
class _WidgetIconFinder extends MatchFinder {
  _WidgetIconFinder(this.icon, { bool skipOffstage: true }) : super(skipOffstage: skipOffstage);

  final IconData icon;

  @override
  String get description => 'icon "$icon"';

  @override
  bool matches(Element candidate) {
    final Widget widget = candidate.widget;
    return widget is Icon && widget.icon == icon;
  }
}

514
class _ElementTypeFinder extends MatchFinder {
515
  _ElementTypeFinder(this.elementType, { bool skipOffstage: true }) : super(skipOffstage: skipOffstage);
516 517 518 519 520 521 522 523 524 525 526 527

  final Type elementType;

  @override
  String get description => 'type "$elementType"';

  @override
  bool matches(Element candidate) {
    return candidate.runtimeType == elementType;
  }
}

528 529
class _WidgetFinder extends MatchFinder {
  _WidgetFinder(this.widget, { bool skipOffstage: true }) : super(skipOffstage: skipOffstage);
530

531
  final Widget widget;
532 533

  @override
534
  String get description => 'the given widget ($widget)';
535 536 537

  @override
  bool matches(Element candidate) {
538
    return candidate.widget == widget;
539 540 541 542
  }
}

class _WidgetPredicateFinder extends MatchFinder {
543 544 545
  _WidgetPredicateFinder(this.predicate, { String description, bool skipOffstage: true })
      : _description = description,
        super(skipOffstage: skipOffstage);
546 547

  final WidgetPredicate predicate;
548
  final String _description;
549 550

  @override
551
  String get description => _description ?? 'widget matching predicate ($predicate)';
552 553 554 555 556 557 558 559

  @override
  bool matches(Element candidate) {
    return predicate(candidate.widget);
  }
}

class _ElementPredicateFinder extends MatchFinder {
560 561 562
  _ElementPredicateFinder(this.predicate, { String description, bool skipOffstage: true })
      : _description = description,
        super(skipOffstage: skipOffstage);
563 564

  final ElementPredicate predicate;
565
  final String _description;
566 567

  @override
568
  String get description => _description ?? 'element matching predicate ($predicate)';
569 570 571 572 573 574

  @override
  bool matches(Element candidate) {
    return predicate(candidate);
  }
}
575 576

class _DescendantFinder extends Finder {
577 578 579 580
  _DescendantFinder(this.ancestor, this.descendant, {
    this.matchRoot: false,
    bool skipOffstage: true,
  }) : super(skipOffstage: skipOffstage);
581 582 583

  final Finder ancestor;
  final Finder descendant;
584
  final bool matchRoot;
585 586

  @override
587 588 589 590 591
  String get description {
    if (matchRoot)
      return '${descendant.description} in the subtree(s) beginning with ${ancestor.description}';
    return '${descendant.description} that has ancestor(s) with ${ancestor.description}';
  }
592 593 594 595 596 597 598 599

  @override
  Iterable<Element> apply(Iterable<Element> candidates) {
    return candidates.where((Element element) => descendant.evaluate().contains(element));
  }

  @override
  Iterable<Element> get allCandidates {
600 601
    final Iterable<Element> ancestorElements = ancestor.evaluate();
    final List<Element> candidates = ancestorElements.expand(
602 603
      (Element element) => collectAllElementsFrom(element, skipOffstage: skipOffstage)
    ).toSet().toList();
604 605 606
    if (matchRoot)
      candidates.insertAll(0, ancestorElements);
    return candidates;
607 608
  }
}
609 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 641 642 643 644

class _AncestorFinder extends Finder {
  _AncestorFinder(this.descendant, this.ancestor, { this.matchRoot: false }) : super(skipOffstage: false);

  final Finder ancestor;
  final Finder descendant;
  final bool matchRoot;

  @override
  String get description {
    if (matchRoot)
      return 'ancestor ${ancestor.description} beginning with ${descendant.description}';
    return '${ancestor.description} which is an ancestor of ${descendant.description}';
  }

  @override
  Iterable<Element> apply(Iterable<Element> candidates) {
    return candidates.where((Element element) => ancestor.evaluate().contains(element));
  }

  @override
  Iterable<Element> get allCandidates {
    final List<Element> candidates = <Element>[];
    for (Element root in descendant.evaluate()) {
      final List<Element> ancestors = <Element>[];
      if (matchRoot)
        ancestors.add(root);
      root.visitAncestorElements((Element element) {
        ancestors.add(element);
        return true;
      });
      candidates.addAll(ancestors);
    }
    return candidates;
  }
}