matchers.dart 96.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:math' as math;
6
import 'dart:ui' as ui;
7

8
import 'package:flutter/foundation.dart';
9
import 'package:flutter/material.dart' show Card;
10
import 'package:flutter/rendering.dart';
11
import 'package:flutter/services.dart';
12
import 'package:flutter/widgets.dart';
13 14
import 'package:matcher/expect.dart';
import 'package:matcher/src/expect/async_matcher.dart'; // ignore: implementation_imports
15
import 'package:vector_math/vector_math_64.dart' show Matrix3;
16

17
import '_matchers_io.dart' if (dart.library.html) '_matchers_web.dart' show MatchesGoldenFile, captureImage;
18
import 'accessibility.dart';
19
import 'binding.dart';
20
import 'controller.dart';
21
import 'finders.dart';
22
import 'goldens.dart';
23
import 'widget_tester.dart' show WidgetTester;
24

25
/// Asserts that the [FinderBase] matches nothing in the available candidates.
26
///
27
/// ## Sample code
28
///
29 30 31 32 33 34
/// ```dart
/// expect(find.text('Save'), findsNothing);
/// ```
///
/// See also:
///
35 36 37 38 39
///  * [findsAny], when you want the finder to find one or more candidates.
///  * [findsOne], when you want the finder to find exactly one candidate.
///  * [findsExactly], when you want the finder to find a specific number of candidates.
///  * [findsAtLeast], when you want the finder to find at least a specific number of candidates.
const Matcher findsNothing = _FindsCountMatcher(null, 0);
40 41 42

/// Asserts that the [Finder] locates at least one widget in the widget tree.
///
43 44
/// This is equivalent to the preferred [findsAny] method.
///
45 46 47 48 49 50 51
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsWidgets);
/// ```
///
/// See also:
52
///
53
///  * [findsNothing], when you want the finder to not find anything.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
///  * [findsOne], when you want the finder to find exactly one candidate.
///  * [findsExactly], when you want the finder to find a specific number of candidates.
///  * [findsAtLeast], when you want the finder to find at least a specific number of candidates.
const Matcher findsWidgets = _FindsCountMatcher(1, null);

/// Asserts that the [FinderBase] locates at least one matching candidate.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsAny);
/// ```
///
/// See also:
///
///  * [findsNothing], when you want the finder to not find anything.
///  * [findsOne], when you want the finder to find exactly one candidate.
///  * [findsExactly], when you want the finder to find a specific number of candidates.
///  * [findsAtLeast], when you want the finder to find at least a specific number of candidates.
const Matcher findsAny = _FindsCountMatcher(1, null);
74 75 76

/// Asserts that the [Finder] locates at exactly one widget in the widget tree.
///
77 78
/// This is equivalent to the preferred [findsOne] method.
///
79
/// ## Sample code
80
///
81 82 83 84 85 86 87
/// ```dart
/// expect(find.text('Save'), findsOneWidget);
/// ```
///
/// See also:
///
///  * [findsNothing], when you want the finder to not find anything.
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
///  * [findsAny], when you want the finder to find one or more candidates.
///  * [findsExactly], when you want the finder to find a specific number of candidates.
///  * [findsAtLeast], when you want the finder to find at least a specific number of candidates.
const Matcher findsOneWidget = _FindsCountMatcher(1, 1);

/// Asserts that the [FinderBase] finds exactly one matching candidate.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsOne);
/// ```
///
/// See also:
///
///  * [findsNothing], when you want the finder to not find anything.
///  * [findsAny], when you want the finder to find one or more candidates.
///  * [findsExactly], when you want the finder to find a specific number candidates.
///  * [findsAtLeast], when you want the finder to find at least a specific number of candidates.
const Matcher findsOne = _FindsCountMatcher(1, 1);
108 109 110

/// Asserts that the [Finder] locates the specified number of widgets in the widget tree.
///
111 112
/// This is equivalent to the preferred [findsExactly] method.
///
113 114 115 116 117 118 119
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsNWidgets(2));
/// ```
///
/// See also:
120
///
121
///  * [findsNothing], when you want the finder to not find anything.
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
///  * [findsAny], when you want the finder to find one or more candidates.
///  * [findsOne], when you want the finder to find exactly one candidate.
///  * [findsAtLeast], when you want the finder to find at least a specific number of candidates.
Matcher findsNWidgets(int n) => _FindsCountMatcher(n, n);

/// Asserts that the [FinderBase] locates the specified number of candidates.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsExactly(2));
/// ```
///
/// See also:
///
///  * [findsNothing], when you want the finder to not find anything.
///  * [findsAny], when you want the finder to find one or more candidates.
///  * [findsOne], when you want the finder to find exactly one candidates.
///  * [findsAtLeast], when you want the finder to find at least a specific number of candidates.
Matcher findsExactly(int n) => _FindsCountMatcher(n, n);
142

143 144
/// Asserts that the [Finder] locates at least a number of widgets in the widget tree.
///
145 146
/// This is equivalent to the preferred [findsAtLeast] method.
///
147 148 149 150 151 152 153 154 155
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsAtLeastNWidgets(2));
/// ```
///
/// See also:
///
///  * [findsNothing], when you want the finder to not find anything.
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
///  * [findsAny], when you want the finder to find one or more candidates.
///  * [findsOne], when you want the finder to find exactly one candidate.
///  * [findsExactly], when you want the finder to find a specific number of candidates.
Matcher findsAtLeastNWidgets(int n) => _FindsCountMatcher(n, null);

/// Asserts that the [FinderBase] locates at least the given number of candidates.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsAtLeast(2));
/// ```
///
/// See also:
///
///  * [findsNothing], when you want the finder to not find anything.
///  * [findsAny], when you want the finder to find one or more candidates.
///  * [findsOne], when you want the finder to find exactly one candidates.
///  * [findsExactly], when you want the finder to find a specific number of candidates.
Matcher findsAtLeast(int n) => _FindsCountMatcher(n, null);
176

177
/// Asserts that the [Finder] locates a single widget that has at
178 179 180 181 182
/// least one [Offstage] widget ancestor.
///
/// It's important to use a full finder, since by default finders exclude
/// offstage widgets.
///
183
/// ## Sample code
184
///
185 186 187 188 189 190
/// ```dart
/// expect(find.text('Save', skipOffstage: false), isOffstage);
/// ```
///
/// See also:
///
191
///  * [isOnstage], the opposite.
192
const Matcher isOffstage = _IsOffstage();
193

194
/// Asserts that the [Finder] locates a single widget that has no
195
/// [Offstage] widget ancestors.
196 197 198
///
/// See also:
///
199
///  * [isOffstage], the opposite.
200
const Matcher isOnstage = _IsOnstage();
201

202
/// Asserts that the [Finder] locates a single widget that has at
203
/// least one [Card] widget ancestor.
204 205 206 207
///
/// See also:
///
///  * [isNotInCard], the opposite.
208
const Matcher isInCard = _IsInCard();
209

210
/// Asserts that the [Finder] locates a single widget that has no
211
/// [Card] widget ancestors.
212 213 214 215 216 217
///
/// This is equivalent to `isNot(isInCard)`.
///
/// See also:
///
///  * [isInCard], the opposite.
218
const Matcher isNotInCard = _IsNotInCard();
219

220 221 222 223 224 225
/// Asserts that the object represents the same color as [color] when used to paint.
///
/// Specifically this matcher checks the object is of type [Color] and its [Color.value]
/// equals to that of the given [color].
Matcher isSameColorAs(Color color) => _ColorMatcher(targetColor: color);

226
/// Asserts that an object's toString() is a plausible one-line description.
227 228
///
/// Specifically, this matcher checks that the string does not contains newline
229 230
/// characters, and does not have leading or trailing whitespace, is not
/// empty, and does not contain the default `Instance of ...` string.
231
const Matcher hasOneLineDescription = _HasOneLineDescription();
232

233
/// Asserts that an object's toStringDeep() is a plausible multiline
234 235 236 237 238 239 240 241 242 243 244 245 246 247
/// description.
///
/// Specifically, this matcher checks that an object's
/// `toStringDeep(prefixLineOne, prefixOtherLines)`:
///
///  * Does not have leading or trailing whitespace.
///  * Does not contain the default `Instance of ...` string.
///  * The last line has characters other than tree connector characters and
///    whitespace. For example: the line ` │ ║ ╎` has only tree connector
///    characters and whitespace.
///  * Does not contain lines with trailing white space.
///  * Has multiple lines.
///  * The first line starts with `prefixLineOne`
///  * All subsequent lines start with `prefixOtherLines`.
248
const Matcher hasAGoodToStringDeep = _HasGoodToStringDeep();
249

250
/// A matcher for functions that throw [FlutterError].
251
///
Dan Field's avatar
Dan Field committed
252
/// This is equivalent to `throwsA(isA<FlutterError>())`.
253
///
254 255 256
/// If you are trying to test whether a call to [WidgetTester.pumpWidget]
/// results in a [FlutterError], see [TestWidgetsFlutterBinding.takeException].
///
257 258 259
/// See also:
///
///  * [throwsAssertionError], to test if a function throws any [AssertionError].
260
///  * [throwsArgumentError], to test if a functions throws an [ArgumentError].
261
///  * [isFlutterError], to test if any object is a [FlutterError].
262
final Matcher throwsFlutterError = throwsA(isFlutterError);
263 264

/// A matcher for functions that throw [AssertionError].
265
///
Dan Field's avatar
Dan Field committed
266
/// This is equivalent to `throwsA(isA<AssertionError>())`.
267
///
268 269 270 271
/// If you are trying to test whether a call to [WidgetTester.pumpWidget]
/// results in an [AssertionError], see
/// [TestWidgetsFlutterBinding.takeException].
///
272 273 274
/// See also:
///
///  * [throwsFlutterError], to test if a function throws a [FlutterError].
275
///  * [throwsArgumentError], to test if a functions throws an [ArgumentError].
276
///  * [isAssertionError], to test if any object is any kind of [AssertionError].
277
final Matcher throwsAssertionError = throwsA(isAssertionError);
278 279

/// A matcher for [FlutterError].
280
///
281
/// This is equivalent to `isInstanceOf<FlutterError>()`.
282 283 284 285 286
///
/// See also:
///
///  * [throwsFlutterError], to test if a function throws a [FlutterError].
///  * [isAssertionError], to test if any object is any kind of [AssertionError].
287
final TypeMatcher<FlutterError> isFlutterError = isA<FlutterError>();
288

289
/// A matcher for [AssertionError].
290
///
291
/// This is equivalent to `isInstanceOf<AssertionError>()`.
292 293 294 295 296
///
/// See also:
///
///  * [throwsAssertionError], to test if a function throws any [AssertionError].
///  * [isFlutterError], to test if any object is a [FlutterError].
297
final TypeMatcher<AssertionError> isAssertionError = isA<AssertionError>();
298 299

/// A matcher that compares the type of the actual value to the type argument T.
300 301 302
///
/// This is identical to [isA] and is included for backwards compatibility.
TypeMatcher<T> isInstanceOf<T>() => isA<T>();
303

304 305
/// Asserts that two [double]s are equal, within some tolerated error.
///
306
/// {@template flutter.flutter_test.moreOrLessEquals}
307
/// Two values are considered equal if the difference between them is within
308 309 310 311 312
/// [precisionErrorTolerance] of the larger one. This is an arbitrary value
/// which can be adjusted using the `epsilon` argument. This matcher is intended
/// to compare floating point numbers that are the result of different sequences
/// of operations, such that they may have accumulated slightly different
/// errors.
313
/// {@endtemplate}
314 315 316 317 318
///
/// See also:
///
///  * [closeTo], which is identical except that the epsilon argument is
///    required and not named.
319
///  * [inInclusiveRange], which matches if the argument is in a specified
320
///    range.
321 322
///  * [rectMoreOrLessEquals] and [offsetMoreOrLessEquals], which do something
///    similar but for [Rect]s and [Offset]s respectively.
323
Matcher moreOrLessEquals(double value, { double epsilon = precisionErrorTolerance }) {
324
  return _MoreOrLessEquals(value, epsilon);
325 326
}

327 328
/// Asserts that two [Rect]s are equal, within some tolerated error.
///
329
/// {@macro flutter.flutter_test.moreOrLessEquals}
330 331 332 333
///
/// See also:
///
///  * [moreOrLessEquals], which is for [double]s.
334
///  * [offsetMoreOrLessEquals], which is for [Offset]s.
335 336
///  * [within], which offers a generic version of this functionality that can
///    be used to match [Rect]s as well as other types.
337
Matcher rectMoreOrLessEquals(Rect value, { double epsilon = precisionErrorTolerance }) {
338 339 340
  return _IsWithinDistance<Rect>(_rectDistance, value, epsilon);
}

341 342 343 344 345 346 347 348
/// Asserts that two [Matrix4]s are equal, within some tolerated error.
///
/// {@macro flutter.flutter_test.moreOrLessEquals}
///
/// See also:
///
///  * [moreOrLessEquals], which is for [double]s.
///  * [offsetMoreOrLessEquals], which is for [Offset]s.
349
///  * [matrix3MoreOrLessEquals], which is for [Matrix3]s.
350 351 352 353
Matcher matrixMoreOrLessEquals(Matrix4 value, { double epsilon = precisionErrorTolerance }) {
  return _IsWithinDistance<Matrix4>(_matrixDistance, value, epsilon);
}

354 355 356 357 358 359 360 361 362 363 364 365 366
/// Asserts that two [Matrix3]s are equal, within some tolerated error.
///
/// {@macro flutter.flutter_test.moreOrLessEquals}
///
/// See also:
///
///  * [moreOrLessEquals], which is for [double]s.
///  * [offsetMoreOrLessEquals], which is for [Offset]s.
///  * [matrixMoreOrLessEquals], which is for [Matrix4]s.
Matcher matrix3MoreOrLessEquals(Matrix3 value, { double epsilon = precisionErrorTolerance }) {
  return _IsWithinDistance<Matrix3>(_matrix3Distance, value, epsilon);
}

367 368
/// Asserts that two [Offset]s are equal, within some tolerated error.
///
369
/// {@macro flutter.flutter_test.moreOrLessEquals}
370 371 372 373 374 375 376 377 378 379 380
///
/// See also:
///
///  * [moreOrLessEquals], which is for [double]s.
///  * [rectMoreOrLessEquals], which is for [Rect]s.
///  * [within], which offers a generic version of this functionality that can
///    be used to match [Offset]s as well as other types.
Matcher offsetMoreOrLessEquals(Offset value, { double epsilon = precisionErrorTolerance }) {
  return _IsWithinDistance<Offset>(_offsetDistance, value, epsilon);
}

381 382
/// Asserts that two [String]s or `Iterable<String>`s are equal after
/// normalizing likely hash codes.
383 384
///
/// A `#` followed by 5 hexadecimal digits is assumed to be a short hash code
385
/// and is normalized to `#00000`.
386
///
387 388
/// Only [String] or `Iterable<String>` are allowed types for `value`.
///
389 390 391
/// See Also:
///
///  * [describeIdentity], a method that generates short descriptions of objects
392
///    with ids that match the pattern `#[0-9a-f]{5}`.
393 394
///  * [shortHash], a method that generates a 5 character long hexadecimal
///    [String] based on [Object.hashCode].
395
///  * [DiagnosticableTree.toStringDeep], a method that returns a [String]
396
///    typically containing multiple hash codes.
397 398
Matcher equalsIgnoringHashCodes(Object value) {
  assert(value is String || value is Iterable<String>, "Only String or Iterable<String> are allowed types for equalsIgnoringHashCodes, it doesn't accept ${value.runtimeType}");
399
  return _EqualsIgnoringHashCodes(value);
400 401
}

402 403 404 405
/// A matcher for [MethodCall]s, asserting that it has the specified
/// method [name] and [arguments].
///
/// Arguments checking implements deep equality for [List] and [Map] types.
406
Matcher isMethodCall(String name, { required dynamic arguments }) {
407
  return _IsMethodCall(name, arguments);
408 409
}

410 411 412 413 414 415 416 417 418
/// Asserts that 2 paths cover the same area by sampling multiple points.
///
/// Samples at least [sampleSize]^2 points inside [areaToCompare], and asserts
/// that the [Path.contains] method returns the same value for each of the
/// points for both paths.
///
/// When using this matcher you typically want to use a rectangle larger than
/// the area you expect to paint in for [areaToCompare] to catch errors where
/// the path draws outside the expected area.
419
Matcher coversSameAreaAs(Path expectedPath, { required Rect areaToCompare, int sampleSize = 20 })
420
  => _CoversSameAreaAs(expectedPath, areaToCompare: areaToCompare, sampleSize: sampleSize);
421

422 423 424 425 426 427 428
// Examples can assume:
// late Image image;
// late Future<Image> imageFuture;
// typedef MyWidget = Placeholder;
// late Future<ByteData> someFont;
// late WidgetTester tester;

429
/// Asserts that a [Finder], [Future<ui.Image>], or [ui.Image] matches the
430
/// golden image file identified by [key], with an optional [version] number.
431 432 433
///
/// For the case of a [Finder], the [Finder] must match exactly one widget and
/// the rendered image of the first [RepaintBoundary] ancestor of the widget is
434 435
/// treated as the image for the widget. As such, you may choose to wrap a test
/// widget in a [RepaintBoundary] to specify a particular focus for the test.
436
///
437
/// The [key] may be either a [Uri] or a [String] representation of a URL.
438
///
439
/// The [version] is a number that can be used to differentiate historical
440
/// golden files. This parameter is optional.
441
///
442 443 444 445
/// This is an asynchronous matcher, meaning that callers should use
/// [expectLater] when using this matcher and await the future returned by
/// [expectLater].
///
446 447 448 449 450 451 452 453 454
/// ## Golden File Testing
///
/// The term __golden file__ refers to a master image that is considered the true
/// rendering of a given widget, state, application, or other visual
/// representation you have chosen to capture.
///
/// The master golden image files that are tested against can be created or
/// updated by running `flutter test --update-goldens` on the test.
///
455
/// {@tool snippet}
456
/// Sample invocations of [matchesGoldenFile].
457 458
///
/// ```dart
459 460 461 462 463 464 465 466 467 468 469 470
/// await expectLater(
///   find.text('Save'),
///   matchesGoldenFile('save.png'),
/// );
///
/// await expectLater(
///   image,
///   matchesGoldenFile('save.png'),
/// );
///
/// await expectLater(
///   imageFuture,
471 472 473 474 475
///   matchesGoldenFile(
///     'save.png',
///     version: 2,
///   ),
/// );
476 477 478 479 480
///
/// await expectLater(
///   find.byType(MyWidget),
///   matchesGoldenFile('goldens/myWidget.png'),
/// );
481
/// ```
482
/// {@end-tool}
483
///
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
/// {@template flutter.flutter_test.matchesGoldenFile.custom_fonts}
/// ## Including Fonts
///
/// Custom fonts may render differently across different platforms, or
/// between different versions of Flutter. For example, a golden file generated
/// on Windows with fonts will likely differ from the one produced by another
/// operating system. Even on the same platform, if the generated golden is
/// tested with a different Flutter version, the test may fail and require an
/// updated image.
///
/// By default, the Flutter framework uses a font called 'Ahem' which shows
/// squares instead of characters, however, it is possible to render images using
/// custom fonts. For example, this is how to load the 'Roboto' font for a
/// golden test:
///
/// {@tool snippet}
/// How to load a custom font for golden images.
/// ```dart
502
/// testWidgets('Creating a golden image with a custom font', (WidgetTester tester) async {
503
///   // Assuming the 'Roboto.ttf' file is declared in the pubspec.yaml file
504
///   final Future<ByteData> font = rootBundle.load('path/to/font-file/Roboto.ttf');
505
///
506
///   final FontLoader fontLoader = FontLoader('Roboto')..addFont(font);
507 508
///   await fontLoader.load();
///
509
///   await tester.pumpWidget(const MyWidget());
510 511
///
///   await expectLater(
512 513
///     find.byType(MyWidget),
///     matchesGoldenFile('myWidget.png'),
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
///   );
/// });
/// ```
/// {@end-tool}
///
/// The example above loads the desired font only for that specific test. To load
/// a font for all golden file tests, the `FontLoader.load()` call could be
/// moved in the `flutter_test_config.dart`. In this way, the font will always be
/// loaded before a test:
///
/// {@tool snippet}
/// Loading a custom font from the flutter_test_config.dart file.
/// ```dart
/// Future<void> testExecutable(FutureOr<void> Function() testMain) async {
///   setUpAll(() async {
529
///     final FontLoader fontLoader = FontLoader('SomeFont')..addFont(someFont);
530 531 532 533
///     await fontLoader.load();
///   });
///
///   await testMain();
534
/// }
535 536 537 538
/// ```
/// {@end-tool}
/// {@endtemplate}
///
539 540
/// See also:
///
541 542 543
///  * [GoldenFileComparator], which acts as the backend for this matcher.
///  * [LocalFileComparator], which is the default [GoldenFileComparator]
///    implementation for `flutter test`.
544 545
///  * [matchesReferenceImage], which should be used instead if you want to
///    verify that two different code paths create identical images.
546 547
///  * [flutter_test] for a discussion of test configurations, whereby callers
///    may swap out the backend for this matcher.
548
AsyncMatcher matchesGoldenFile(Object key, {int? version}) {
549
  if (key is Uri) {
550
    return MatchesGoldenFile(key, version);
551
  } else if (key is String) {
552
    return MatchesGoldenFile.forStringPath(key, version);
553
  }
554
  throw ArgumentError('Unexpected type for golden file: ${key.runtimeType}');
555
}
556

557 558 559 560 561 562 563 564 565 566 567 568 569 570
/// Asserts that a [Finder], [Future<ui.Image>], or [ui.Image] matches a
/// reference image identified by [image].
///
/// For the case of a [Finder], the [Finder] must match exactly one widget and
/// the rendered image of the first [RepaintBoundary] ancestor of the widget is
/// treated as the image for the widget.
///
/// This is an asynchronous matcher, meaning that callers should use
/// [expectLater] when using this matcher and await the future returned by
/// [expectLater].
///
/// ## Sample code
///
/// ```dart
571 572 573 574 575 576 577 578
/// testWidgets('matchesReferenceImage', (WidgetTester tester) async {
///   final ui.Paint paint = ui.Paint()
///     ..style = ui.PaintingStyle.stroke
///     ..strokeWidth = 1.0;
///   final ui.PictureRecorder recorder = ui.PictureRecorder();
///   final ui.Canvas pictureCanvas = ui.Canvas(recorder);
///   pictureCanvas.drawCircle(Offset.zero, 20.0, paint);
///   final ui.Picture picture = recorder.endRecording();
579
///   addTearDown(picture.dispose);
580
///   ui.Image referenceImage = await picture.toImage(50, 50);
581
///   addTearDown(referenceImage.dispose);
582 583 584 585 586
///
///   await expectLater(find.text('Save'), matchesReferenceImage(referenceImage));
///   await expectLater(image, matchesReferenceImage(referenceImage));
///   await expectLater(imageFuture, matchesReferenceImage(referenceImage));
/// });
587 588 589 590 591 592 593 594 595 596
/// ```
///
/// See also:
///
///  * [matchesGoldenFile], which should be used instead if you need to verify
///    that a [Finder] or [ui.Image] matches a golden image.
AsyncMatcher matchesReferenceImage(ui.Image image) {
  return _MatchesReferenceImage(image);
}

597
/// Asserts that a [SemanticsNode] contains the specified information.
598 599
///
/// If either the label, hint, value, textDirection, or rect fields are not
600
/// provided, then they are not part of the comparison. All of the boolean
601 602
/// flag and action fields must match, and default to false.
///
603 604 605 606 607
/// To find a [SemanticsNode] directly, use [CommonFinders.semantics].
/// These methods will search the semantics tree directly and avoid the edge
/// cases that [SemanticsController.find] sometimes runs into.
///
/// To retrieve the semantics data of a widget, use [SemanticsController.find]
608 609 610 611 612 613
/// with a [Finder] that returns a single widget. Semantics must be enabled
/// in order to use this method.
///
/// ## Sample code
///
/// ```dart
614 615 616 617 618 619
/// testWidgets('matchesSemantics', (WidgetTester tester) async {
///   final SemanticsHandle handle = tester.ensureSemantics();
///   // ...
///   expect(tester.getSemantics(find.text('hello')), matchesSemantics(label: 'hello'));
///   handle.dispose();
/// });
620 621 622 623
/// ```
///
/// See also:
///
624
///   * [SemanticsController.find] under [WidgetTester.semantics], the tester method which retrieves semantics.
625
///   * [containsSemantics], a similar matcher without default values for flags or actions.
626
Matcher matchesSemantics({
627
  String? identifier,
628
  String? label,
629
  AttributedString? attributedLabel,
630
  String? hint,
631
  AttributedString? attributedHint,
632
  String? value,
633
  AttributedString? attributedValue,
634
  String? increasedValue,
635
  AttributedString? attributedIncreasedValue,
636
  String? decreasedValue,
637
  AttributedString? attributedDecreasedValue,
638
  String? tooltip,
639 640 641 642 643 644 645 646
  TextDirection? textDirection,
  Rect? rect,
  Size? size,
  double? elevation,
  double? thickness,
  int? platformViewId,
  int? maxValueLength,
  int? currentValueLength,
647 648 649
  // Flags //
  bool hasCheckedState = false,
  bool isChecked = false,
650
  bool isCheckStateMixed = false,
651 652
  bool isSelected = false,
  bool isButton = false,
653
  bool isSlider = false,
654
  bool isKeyboardKey = false,
655
  bool isLink = false,
656
  bool isFocused = false,
657
  bool isFocusable = false,
658
  bool isTextField = false,
659
  bool isReadOnly = false,
660 661 662 663 664
  bool hasEnabledState = false,
  bool isEnabled = false,
  bool isInMutuallyExclusiveGroup = false,
  bool isHeader = false,
  bool isObscured = false,
665
  bool isMultiline = false,
666 667 668
  bool namesRoute = false,
  bool scopesRoute = false,
  bool isHidden = false,
669 670 671 672
  bool isImage = false,
  bool isLiveRegion = false,
  bool hasToggledState = false,
  bool isToggled = false,
673
  bool hasImplicitScrolling = false,
674 675
  bool hasExpandedState = false,
  bool isExpanded = false,
676 677 678 679 680 681 682 683 684 685 686 687
  // Actions //
  bool hasTapAction = false,
  bool hasLongPressAction = false,
  bool hasScrollLeftAction = false,
  bool hasScrollRightAction = false,
  bool hasScrollUpAction = false,
  bool hasScrollDownAction = false,
  bool hasIncreaseAction = false,
  bool hasDecreaseAction = false,
  bool hasShowOnScreenAction = false,
  bool hasMoveCursorForwardByCharacterAction = false,
  bool hasMoveCursorBackwardByCharacterAction = false,
688 689
  bool hasMoveCursorForwardByWordAction = false,
  bool hasMoveCursorBackwardByWordAction = false,
690
  bool hasSetTextAction = false,
691 692 693 694 695 696
  bool hasSetSelectionAction = false,
  bool hasCopyAction = false,
  bool hasCutAction = false,
  bool hasPasteAction = false,
  bool hasDidGainAccessibilityFocusAction = false,
  bool hasDidLoseAccessibilityFocusAction = false,
697
  bool hasDismissAction = false,
698
  // Custom actions and overrides
699 700 701 702
  String? onTapHint,
  String? onLongPressHint,
  List<CustomSemanticsAction>? customActions,
  List<Matcher>? children,
703
}) {
704
  return _MatchesSemanticsData(
705
    identifier: identifier,
706
    label: label,
707
    attributedLabel: attributedLabel,
708
    hint: hint,
709
    attributedHint: attributedHint,
710
    value: value,
711
    attributedValue: attributedValue,
712
    increasedValue: increasedValue,
713
    attributedIncreasedValue: attributedIncreasedValue,
714
    decreasedValue: decreasedValue,
715
    attributedDecreasedValue: attributedDecreasedValue,
716
    tooltip: tooltip,
717 718 719
    textDirection: textDirection,
    rect: rect,
    size: size,
720 721
    elevation: elevation,
    thickness: thickness,
722
    platformViewId: platformViewId,
723
    customActions: customActions,
724
    maxValueLength: maxValueLength,
725
    currentValueLength: currentValueLength,
726 727 728
    // Flags
    hasCheckedState: hasCheckedState,
    isChecked: isChecked,
729
    isCheckStateMixed: isCheckStateMixed,
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
    isSelected: isSelected,
    isButton: isButton,
    isSlider: isSlider,
    isKeyboardKey: isKeyboardKey,
    isLink: isLink,
    isFocused: isFocused,
    isFocusable: isFocusable,
    isTextField: isTextField,
    isReadOnly: isReadOnly,
    hasEnabledState: hasEnabledState,
    isEnabled: isEnabled,
    isInMutuallyExclusiveGroup: isInMutuallyExclusiveGroup,
    isHeader: isHeader,
    isObscured: isObscured,
    isMultiline: isMultiline,
    namesRoute: namesRoute,
    scopesRoute: scopesRoute,
    isHidden: isHidden,
    isImage: isImage,
    isLiveRegion: isLiveRegion,
    hasToggledState: hasToggledState,
    isToggled: isToggled,
    hasImplicitScrolling: hasImplicitScrolling,
753 754
    hasExpandedState: hasExpandedState,
    isExpanded: isExpanded,
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
    // Actions
    hasTapAction: hasTapAction,
    hasLongPressAction: hasLongPressAction,
    hasScrollLeftAction: hasScrollLeftAction,
    hasScrollRightAction: hasScrollRightAction,
    hasScrollUpAction: hasScrollUpAction,
    hasScrollDownAction: hasScrollDownAction,
    hasIncreaseAction: hasIncreaseAction,
    hasDecreaseAction: hasDecreaseAction,
    hasShowOnScreenAction: hasShowOnScreenAction,
    hasMoveCursorForwardByCharacterAction: hasMoveCursorForwardByCharacterAction,
    hasMoveCursorBackwardByCharacterAction: hasMoveCursorBackwardByCharacterAction,
    hasMoveCursorForwardByWordAction: hasMoveCursorForwardByWordAction,
    hasMoveCursorBackwardByWordAction: hasMoveCursorBackwardByWordAction,
    hasSetTextAction: hasSetTextAction,
    hasSetSelectionAction: hasSetSelectionAction,
    hasCopyAction: hasCopyAction,
    hasCutAction: hasCutAction,
    hasPasteAction: hasPasteAction,
    hasDidGainAccessibilityFocusAction: hasDidGainAccessibilityFocusAction,
    hasDidLoseAccessibilityFocusAction: hasDidLoseAccessibilityFocusAction,
    hasDismissAction: hasDismissAction,
    // Custom actions and overrides
    children: children,
    onLongPressHint: onLongPressHint,
    onTapHint: onTapHint,
  );
}

/// Asserts that a [SemanticsNode] contains the specified information.
///
/// There are no default expected values, so no unspecified values will be
/// validated.
///
789 790 791 792 793
/// To find a [SemanticsNode] directly, use [CommonFinders.semantics].
/// These methods will search the semantics tree directly and avoid the edge
/// cases that [SemanticsController.find] sometimes runs into.
///
/// To retrieve the semantics data of a widget, use [SemanticsController.find]
794 795 796 797 798 799
/// with a [Finder] that returns a single widget. Semantics must be enabled
/// in order to use this method.
///
/// ## Sample code
///
/// ```dart
800 801 802 803 804 805
/// testWidgets('containsSemantics', (WidgetTester tester) async {
///   final SemanticsHandle handle = tester.ensureSemantics();
///   // ...
///   expect(tester.getSemantics(find.text('hello')), containsSemantics(label: 'hello'));
///   handle.dispose();
/// });
806 807 808 809
/// ```
///
/// See also:
///
810
///   * [SemanticsController.find] under [WidgetTester.semantics], the tester method which retrieves semantics.
811 812
///   * [matchesSemantics], a similar matcher with default values for flags and actions.
Matcher containsSemantics({
813
  String? identifier,
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
  String? label,
  AttributedString? attributedLabel,
  String? hint,
  AttributedString? attributedHint,
  String? value,
  AttributedString? attributedValue,
  String? increasedValue,
  AttributedString? attributedIncreasedValue,
  String? decreasedValue,
  AttributedString? attributedDecreasedValue,
  String? tooltip,
  TextDirection? textDirection,
  Rect? rect,
  Size? size,
  double? elevation,
  double? thickness,
  int? platformViewId,
  int? maxValueLength,
  int? currentValueLength,
  // Flags
  bool? hasCheckedState,
  bool? isChecked,
836
  bool? isCheckStateMixed,
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
  bool? isSelected,
  bool? isButton,
  bool? isSlider,
  bool? isKeyboardKey,
  bool? isLink,
  bool? isFocused,
  bool? isFocusable,
  bool? isTextField,
  bool? isReadOnly,
  bool? hasEnabledState,
  bool? isEnabled,
  bool? isInMutuallyExclusiveGroup,
  bool? isHeader,
  bool? isObscured,
  bool? isMultiline,
  bool? namesRoute,
  bool? scopesRoute,
  bool? isHidden,
  bool? isImage,
  bool? isLiveRegion,
  bool? hasToggledState,
  bool? isToggled,
  bool? hasImplicitScrolling,
860 861
  bool? hasExpandedState,
  bool? isExpanded,
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
  // Actions
  bool? hasTapAction,
  bool? hasLongPressAction,
  bool? hasScrollLeftAction,
  bool? hasScrollRightAction,
  bool? hasScrollUpAction,
  bool? hasScrollDownAction,
  bool? hasIncreaseAction,
  bool? hasDecreaseAction,
  bool? hasShowOnScreenAction,
  bool? hasMoveCursorForwardByCharacterAction,
  bool? hasMoveCursorBackwardByCharacterAction,
  bool? hasMoveCursorForwardByWordAction,
  bool? hasMoveCursorBackwardByWordAction,
  bool? hasSetTextAction,
  bool? hasSetSelectionAction,
  bool? hasCopyAction,
  bool? hasCutAction,
  bool? hasPasteAction,
  bool? hasDidGainAccessibilityFocusAction,
  bool? hasDidLoseAccessibilityFocusAction,
  bool? hasDismissAction,
  // Custom actions and overrides
  String? onTapHint,
  String? onLongPressHint,
  List<CustomSemanticsAction>? customActions,
  List<Matcher>? children,
}) {
  return _MatchesSemanticsData(
891
    identifier: identifier,
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
    label: label,
    attributedLabel: attributedLabel,
    hint: hint,
    attributedHint: attributedHint,
    value: value,
    attributedValue: attributedValue,
    increasedValue: increasedValue,
    attributedIncreasedValue: attributedIncreasedValue,
    decreasedValue: decreasedValue,
    attributedDecreasedValue: attributedDecreasedValue,
    tooltip: tooltip,
    textDirection: textDirection,
    rect: rect,
    size: size,
    elevation: elevation,
    thickness: thickness,
    platformViewId: platformViewId,
    customActions: customActions,
910
    maxValueLength: maxValueLength,
911 912 913 914
    currentValueLength: currentValueLength,
    // Flags
    hasCheckedState: hasCheckedState,
    isChecked: isChecked,
915
    isCheckStateMixed: isCheckStateMixed,
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    isSelected: isSelected,
    isButton: isButton,
    isSlider: isSlider,
    isKeyboardKey: isKeyboardKey,
    isLink: isLink,
    isFocused: isFocused,
    isFocusable: isFocusable,
    isTextField: isTextField,
    isReadOnly: isReadOnly,
    hasEnabledState: hasEnabledState,
    isEnabled: isEnabled,
    isInMutuallyExclusiveGroup: isInMutuallyExclusiveGroup,
    isHeader: isHeader,
    isObscured: isObscured,
    isMultiline: isMultiline,
    namesRoute: namesRoute,
    scopesRoute: scopesRoute,
    isHidden: isHidden,
    isImage: isImage,
    isLiveRegion: isLiveRegion,
    hasToggledState: hasToggledState,
    isToggled: isToggled,
    hasImplicitScrolling: hasImplicitScrolling,
939 940
    hasExpandedState: hasExpandedState,
    isExpanded: isExpanded,
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
    // Actions
    hasTapAction: hasTapAction,
    hasLongPressAction: hasLongPressAction,
    hasScrollLeftAction: hasScrollLeftAction,
    hasScrollRightAction: hasScrollRightAction,
    hasScrollUpAction: hasScrollUpAction,
    hasScrollDownAction: hasScrollDownAction,
    hasIncreaseAction: hasIncreaseAction,
    hasDecreaseAction: hasDecreaseAction,
    hasShowOnScreenAction: hasShowOnScreenAction,
    hasMoveCursorForwardByCharacterAction: hasMoveCursorForwardByCharacterAction,
    hasMoveCursorBackwardByCharacterAction: hasMoveCursorBackwardByCharacterAction,
    hasMoveCursorForwardByWordAction: hasMoveCursorForwardByWordAction,
    hasMoveCursorBackwardByWordAction: hasMoveCursorBackwardByWordAction,
    hasSetTextAction: hasSetTextAction,
    hasSetSelectionAction: hasSetSelectionAction,
    hasCopyAction: hasCopyAction,
    hasCutAction: hasCutAction,
    hasPasteAction: hasPasteAction,
    hasDidGainAccessibilityFocusAction: hasDidGainAccessibilityFocusAction,
    hasDidLoseAccessibilityFocusAction: hasDidLoseAccessibilityFocusAction,
    hasDismissAction: hasDismissAction,
    // Custom actions and overrides
964
    children: children,
965 966
    onLongPressHint: onLongPressHint,
    onTapHint: onTapHint,
967 968 969
  );
}

970 971 972 973 974 975 976 977 978
/// Asserts that the currently rendered widget meets the provided accessibility
/// `guideline`.
///
/// This matcher requires the result to be awaited and for semantics to be
/// enabled first.
///
/// ## Sample code
///
/// ```dart
979 980 981 982 983 984
/// testWidgets('containsSemantics', (WidgetTester tester) async {
///   final SemanticsHandle handle = tester.ensureSemantics();
///   // ...
///   await expectLater(tester, meetsGuideline(textContrastGuideline));
///   handle.dispose();
/// });
985 986 987 988
/// ```
///
/// Supported accessibility guidelines:
///
989 990
///   * [androidTapTargetGuideline], for Android minimum tappable area guidelines.
///   * [iOSTapTargetGuideline], for iOS minimum tappable area guidelines.
991
///   * [textContrastGuideline], for WCAG minimum text contrast guidelines.
992
///   * [labeledTapTargetGuideline], for enforcing labels on tappable areas.
993
AsyncMatcher meetsGuideline(AccessibilityGuideline guideline) {
994
  return _MatchesAccessibilityGuideline(guideline);
995 996 997 998 999 1000 1001
}

/// The inverse matcher of [meetsGuideline].
///
/// This is needed because the [isNot] matcher does not compose with an
/// [AsyncMatcher].
AsyncMatcher doesNotMeetGuideline(AccessibilityGuideline guideline) {
1002
  return _DoesNotMatchAccessibilityGuideline(guideline);
1003 1004
}

1005 1006
class _FindsCountMatcher extends Matcher {
  const _FindsCountMatcher(this.min, this.max);
1007

1008 1009
  final int? min;
  final int? max;
1010 1011

  @override
1012
  bool matches(covariant FinderBase<dynamic> finder, Map<dynamic, dynamic> matchState) {
1013
    assert(min != null || max != null);
1014
    assert(min == null || max == null || min! <= max!);
1015
    matchState[FinderBase] = finder;
1016
    int count = 0;
1017
    final Iterator<dynamic> iterator = finder.evaluate().iterator;
1018
    if (min != null) {
1019
      while (count < min! && iterator.moveNext()) {
1020
        count += 1;
1021 1022
      }
      if (count < min!) {
1023
        return false;
1024
      }
1025 1026
    }
    if (max != null) {
1027
      while (count <= max! && iterator.moveNext()) {
1028
        count += 1;
1029 1030
      }
      if (count > max!) {
1031
        return false;
1032
      }
1033 1034 1035 1036 1037 1038 1039 1040
    }
    return true;
  }

  @override
  Description describe(Description description) {
    assert(min != null || max != null);
    if (min == max) {
1041
      if (min == 1) {
1042
        return description.add('exactly one matching candidate');
1043
      }
1044
      return description.add('exactly $min matching candidates');
1045 1046
    }
    if (min == null) {
1047
      if (max == 0) {
1048
        return description.add('no matching candidates');
1049 1050
      }
      if (max == 1) {
1051
        return description.add('at most one matching candidate');
1052
      }
1053
      return description.add('at most $max matching candidates');
1054 1055
    }
    if (max == null) {
1056
      if (min == 1) {
1057
        return description.add('at least one matching candidate');
1058
      }
1059
      return description.add('at least $min matching candidates');
1060
    }
1061
    return description.add('between $min and $max matching candidates (inclusive)');
1062 1063 1064 1065 1066 1067 1068
  }

  @override
  Description describeMismatch(
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
1069
    bool verbose,
1070
  ) {
1071 1072
    final FinderBase<dynamic> finder = matchState[FinderBase] as FinderBase<dynamic>;
    final int count = finder.found.length;
1073
    if (count == 0) {
1074
      assert(min != null && min! > 0);
1075
      if (min == 1 && max == 1) {
1076
        return mismatchDescription.add('means none were found but one was expected');
1077
      }
1078 1079 1080
      return mismatchDescription.add('means none were found but some were expected');
    }
    if (max == 0) {
1081
      if (count == 1) {
1082
        return mismatchDescription.add('means one was found but none were expected');
1083
      }
1084 1085
      return mismatchDescription.add('means some were found but none were expected');
    }
1086
    if (min != null && count < min!) {
1087
      return mismatchDescription.add('is not enough');
1088
    }
1089
    assert(max != null && count > min!);
1090 1091 1092 1093
    return mismatchDescription.add('is too many');
  }
}

1094
bool _hasAncestorMatching(Finder finder, bool Function(Widget widget) predicate) {
1095
  final Iterable<Element> nodes = finder.evaluate();
1096
  if (nodes.length != 1) {
1097
    return false;
1098
  }
1099
  bool result = false;
1100
  nodes.single.visitAncestorElements((Element ancestor) {
1101
    if (predicate(ancestor.widget)) {
1102 1103 1104 1105 1106 1107 1108 1109
      result = true;
      return false;
    }
    return true;
  });
  return result;
}

1110 1111 1112 1113
bool _hasAncestorOfType(Finder finder, Type targetType) {
  return _hasAncestorMatching(finder, (Widget widget) => widget.runtimeType == targetType);
}

1114 1115
class _IsOffstage extends Matcher {
  const _IsOffstage();
1116 1117

  @override
1118
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) {
1119
    return _hasAncestorMatching(finder, (Widget widget) {
1120
      if (widget is Offstage) {
1121
        return widget.offstage;
1122
      }
1123
      return false;
1124 1125
    });
  }
1126 1127 1128 1129 1130

  @override
  Description describe(Description description) => description.add('offstage');
}

1131 1132
class _IsOnstage extends Matcher {
  const _IsOnstage();
1133 1134

  @override
1135
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) {
1136
    final Iterable<Element> nodes = finder.evaluate();
1137
    if (nodes.length != 1) {
1138
      return false;
1139
    }
1140
    bool result = true;
1141
    nodes.single.visitAncestorElements((Element ancestor) {
1142
      final Widget widget = ancestor.widget;
1143 1144
      if (widget is Offstage) {
        result = !widget.offstage;
1145 1146 1147 1148 1149 1150
        return false;
      }
      return true;
    });
    return result;
  }
1151 1152 1153 1154 1155 1156 1157 1158 1159

  @override
  Description describe(Description description) => description.add('onstage');
}

class _IsInCard extends Matcher {
  const _IsInCard();

  @override
1160
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) => _hasAncestorOfType(finder, Card);
1161 1162 1163 1164 1165 1166 1167 1168 1169

  @override
  Description describe(Description description) => description.add('in card');
}

class _IsNotInCard extends Matcher {
  const _IsNotInCard();

  @override
1170
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) => !_hasAncestorOfType(finder, Card);
1171 1172 1173 1174

  @override
  Description describe(Description description) => description.add('not in card');
}
1175

1176 1177
class _HasOneLineDescription extends Matcher {
  const _HasOneLineDescription();
1178 1179

  @override
1180
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
1181
    final String description = object.toString();
1182 1183
    return description.isNotEmpty
        && !description.contains('\n')
1184
        && !description.contains('Instance of ')
1185
        && description.trim() == description;
1186 1187 1188 1189 1190
  }

  @override
  Description describe(Description description) => description.add('one line description');
}
1191

1192
class _EqualsIgnoringHashCodes extends Matcher {
1193
  _EqualsIgnoringHashCodes(Object v) : _value = _normalize(v);
1194

1195
  final Object _value;
1196

1197
  static final Object _mismatchedValueKey = Object();
1198

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
  static String _normalizeString(String value) {
    return value.replaceAll(RegExp(r'#[\da-fA-F]{5}'), '#00000');
  }

  static Object _normalize(Object value, {bool expected = true}) {
    if (value is String) {
      return _normalizeString(value);
    }
    if (value is Iterable<String>) {
      return value.map<String>((dynamic item) => _normalizeString(item.toString()));
    }
    throw ArgumentError('The specified ${expected ? 'expected' : 'comparison'} value for '
        'equalsIgnoringHashCodes must be a String or an Iterable<String>, '
        'not a ${value.runtimeType}');
1213 1214 1215 1216
  }

  @override
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
1217 1218 1219
    final Object normalized = _normalize(object as Object, expected: false);
    if (!equals(_value).matches(normalized, matchState)) {
      matchState[_mismatchedValueKey] = normalized;
1220 1221 1222 1223 1224 1225 1226
      return false;
    }
    return true;
  }

  @override
  Description describe(Description description) {
1227 1228 1229 1230
    if (_value is String) {
      return description.add('normalized value matches $_value');
    }
    return description.add('normalized value matches\n').addDescriptionOf(_value);
1231 1232 1233 1234 1235 1236 1237
  }

  @override
  Description describeMismatch(
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
1238
    bool verbose,
1239 1240
  ) {
    if (matchState.containsKey(_mismatchedValueKey)) {
1241
      final Object actualValue = matchState[_mismatchedValueKey] as Object;
1242
      // Leading whitespace is added so that lines in the multiline
1243 1244 1245
      // description returned by addDescriptionOf are all indented equally
      // which makes the output easier to read for this case.
      return mismatchDescription
1246
          .add('was expected to be normalized value\n')
1247
          .addDescriptionOf(_value)
1248
          .add('\nbut got\n')
1249 1250 1251 1252 1253 1254
          .addDescriptionOf(actualValue);
    }
    return mismatchDescription;
  }
}

1255
/// Returns true if [c] represents a whitespace code unit.
1256 1257
bool _isWhitespace(int c) => (c <= 0x000D && c >= 0x0009) || c == 0x0020;

1258
/// Returns true if [c] represents a vertical line Unicode line art code unit.
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
///
/// See [https://en.wikipedia.org/wiki/Box-drawing_character]. This method only
/// specifies vertical line art code units currently used by Flutter line art.
/// There are other line art characters that technically also represent vertical
/// lines.
bool _isVerticalLine(int c) {
  return c == 0x2502 || c == 0x2503 || c == 0x2551 || c == 0x254e;
}

/// Returns whether a [line] is all vertical tree connector characters.
///
/// Example vertical tree connector characters: `│ ║ ╎`.
/// The last line of a text tree contains only vertical tree connector
/// characters indicates a poorly formatted tree.
bool _isAllTreeConnectorCharacters(String line) {
  for (int i = 0; i < line.length; ++i) {
    final int c = line.codeUnitAt(i);
1276
    if (!_isWhitespace(c) && !_isVerticalLine(c)) {
1277
      return false;
1278
    }
1279 1280 1281 1282 1283 1284 1285
  }
  return true;
}

class _HasGoodToStringDeep extends Matcher {
  const _HasGoodToStringDeep();

1286
  static final Object _toStringDeepErrorDescriptionKey = Object();
1287 1288 1289 1290

  @override
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
    final List<String> issues = <String>[];
1291
    String description = object.toStringDeep() as String; // ignore: avoid_dynamic_calls
1292 1293 1294 1295 1296 1297 1298 1299
    if (description.endsWith('\n')) {
      // Trim off trailing \n as the remaining calculations assume
      // the description does not end with a trailing \n.
      description = description.substring(0, description.length - 1);
    } else {
      issues.add('Not terminated with a line break.');
    }

1300
    if (description.trim() != description) {
1301
      issues.add('Has trailing whitespace.');
1302
    }
1303 1304

    final List<String> lines = description.split('\n');
1305
    if (lines.length < 2) {
1306
      issues.add('Does not have multiple lines.');
1307
    }
1308

1309
    if (description.contains('Instance of ')) {
1310
      issues.add('Contains text "Instance of ".');
1311
    }
1312 1313 1314

    for (int i = 0; i < lines.length; ++i) {
      final String line = lines[i];
1315
      if (line.isEmpty) {
1316
        issues.add('Line ${i + 1} is empty.');
1317
      }
1318

1319
      if (line.trimRight() != line) {
1320
        issues.add('Line ${i + 1} has trailing whitespace.');
1321
      }
1322 1323
    }

1324
    if (_isAllTreeConnectorCharacters(lines.last)) {
1325
      issues.add('Last line is all tree connector characters.');
1326
    }
1327 1328

    // If a toStringDeep method doesn't properly handle nested values that
1329
    // contain line breaks it can fail to add the required prefixes to all
1330
    // lined when toStringDeep is called specifying prefixes.
1331
    const String prefixLineOne = 'PREFIX_LINE_ONE____';
1332
    const String prefixOtherLines = 'PREFIX_OTHER_LINES_';
1333
    final List<String> prefixIssues = <String>[];
1334 1335
    // ignore: avoid_dynamic_calls
    String descriptionWithPrefixes = object.toStringDeep(prefixLineOne: prefixLineOne, prefixOtherLines: prefixOtherLines) as String;
1336 1337 1338 1339 1340 1341 1342
    if (descriptionWithPrefixes.endsWith('\n')) {
      // Trim off trailing \n as the remaining calculations assume
      // the description does not end with a trailing \n.
      descriptionWithPrefixes = descriptionWithPrefixes.substring(
          0, descriptionWithPrefixes.length - 1);
    }
    final List<String> linesWithPrefixes = descriptionWithPrefixes.split('\n');
1343
    if (!linesWithPrefixes.first.startsWith(prefixLineOne)) {
1344
      prefixIssues.add('First line does not contain expected prefix.');
1345
    }
1346 1347

    for (int i = 1; i < linesWithPrefixes.length; ++i) {
1348
      if (!linesWithPrefixes[i].startsWith(prefixOtherLines)) {
1349
        prefixIssues.add('Line ${i + 1} does not contain the expected prefix.');
1350
      }
1351 1352
    }

1353
    final StringBuffer errorDescription = StringBuffer();
1354 1355 1356 1357 1358 1359 1360 1361
    if (issues.isNotEmpty) {
      errorDescription.writeln('Bad toStringDeep():');
      errorDescription.writeln(description);
      errorDescription.writeAll(issues, '\n');
    }

    if (prefixIssues.isNotEmpty) {
      errorDescription.writeln(
1362
          'Bad toStringDeep(prefixLineOne: "$prefixLineOne", prefixOtherLines: "$prefixOtherLines"):');
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
      errorDescription.writeln(descriptionWithPrefixes);
      errorDescription.writeAll(prefixIssues, '\n');
    }

    if (errorDescription.isNotEmpty) {
      matchState[_toStringDeepErrorDescriptionKey] =
          errorDescription.toString();
      return false;
    }
    return true;
  }

  @override
  Description describeMismatch(
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
1380
    bool verbose,
1381 1382
  ) {
    if (matchState.containsKey(_toStringDeepErrorDescriptionKey)) {
1383
      return mismatchDescription.add(matchState[_toStringDeepErrorDescriptionKey] as String);
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
    }
    return mismatchDescription;
  }

  @override
  Description describe(Description description) {
    return description.add('multi line description');
  }
}

1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
/// Computes the distance between two values.
///
/// The distance should be a metric in a metric space (see
/// https://en.wikipedia.org/wiki/Metric_space). Specifically, if `f` is a
/// distance function then the following conditions should hold:
///
/// - f(a, b) >= 0
/// - f(a, b) == 0 if and only if a == b
/// - f(a, b) == f(b, a)
/// - f(a, c) <= f(a, b) + f(b, c), known as triangle inequality
///
/// This makes it useful for comparing numbers, [Color]s, [Offset]s and other
/// sets of value for which a metric space is defined.
1407
typedef DistanceFunction<T> = num Function(T a, T b);
1408

1409 1410 1411 1412
/// The type of a union of instances of [DistanceFunction<T>] for various types
/// T.
///
/// This type is used to describe a collection of [DistanceFunction<T>]
1413
/// functions which have (potentially) unrelated argument types. Since the
1414 1415 1416
/// argument types of the functions may be unrelated, their type is declared as
/// `Never`, which is the bottom type in dart to which all other types can be
/// assigned to.
1417 1418 1419
///
/// Calling an instance of this type must either be done dynamically, or by
/// first casting it to a [DistanceFunction<T>] for some concrete T.
1420
typedef AnyDistanceFunction = num Function(Never a, Never b);
1421

1422
const Map<Type, AnyDistanceFunction> _kStandardDistanceFunctions = <Type, AnyDistanceFunction>{
1423
  Color: _maxComponentColorDistance,
1424 1425
  HSVColor: _maxComponentHSVColorDistance,
  HSLColor: _maxComponentHSLColorDistance,
1426 1427 1428
  Offset: _offsetDistance,
  int: _intDistance,
  double: _doubleDistance,
1429
  Rect: _rectDistance,
1430
  Size: _sizeDistance,
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
};

int _intDistance(int a, int b) => (b - a).abs();
double _doubleDistance(double a, double b) => (b - a).abs();
double _offsetDistance(Offset a, Offset b) => (b - a).distance;

double _maxComponentColorDistance(Color a, Color b) {
  int delta = math.max<int>((a.red - b.red).abs(), (a.green - b.green).abs());
  delta = math.max<int>(delta, (a.blue - b.blue).abs());
  delta = math.max<int>(delta, (a.alpha - b.alpha).abs());
  return delta.toDouble();
}

1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
// Compares hue by converting it to a 0.0 - 1.0 range, so that the comparison
// can be a similar error percentage per component.
double _maxComponentHSVColorDistance(HSVColor a, HSVColor b) {
  double delta = math.max<double>((a.saturation - b.saturation).abs(), (a.value - b.value).abs());
  delta = math.max<double>(delta, ((a.hue - b.hue) / 360.0).abs());
  return math.max<double>(delta, (a.alpha - b.alpha).abs());
}

// Compares hue by converting it to a 0.0 - 1.0 range, so that the comparison
// can be a similar error percentage per component.
double _maxComponentHSLColorDistance(HSLColor a, HSLColor b) {
  double delta = math.max<double>((a.saturation - b.saturation).abs(), (a.lightness - b.lightness).abs());
  delta = math.max<double>(delta, ((a.hue - b.hue) / 360.0).abs());
  return math.max<double>(delta, (a.alpha - b.alpha).abs());
}

1460 1461 1462 1463 1464 1465 1466
double _rectDistance(Rect a, Rect b) {
  double delta = math.max<double>((a.left - b.left).abs(), (a.top - b.top).abs());
  delta = math.max<double>(delta, (a.right - b.right).abs());
  delta = math.max<double>(delta, (a.bottom - b.bottom).abs());
  return delta;
}

1467 1468 1469 1470 1471 1472 1473 1474
double _matrixDistance(Matrix4 a, Matrix4 b) {
  double delta = 0.0;
  for (int i = 0; i < 16; i += 1) {
    delta = math.max<double>((a[i] - b[i]).abs(), delta);
  }
  return delta;
}

1475 1476 1477 1478 1479 1480 1481 1482
double _matrix3Distance(Matrix3 a, Matrix3 b) {
  double delta = 0.0;
  for (int i = 0; i < 9; i += 1) {
    delta = math.max<double>((a[i] - b[i]).abs(), delta);
  }
  return delta;
}

1483
double _sizeDistance(Size a, Size b) {
1484
  final Offset delta = (b - a) as Offset;
1485
  return delta.distance;
1486 1487
}

1488 1489 1490 1491 1492
/// Asserts that two values are within a certain distance from each other.
///
/// The distance is computed by a [DistanceFunction].
///
/// If `distanceFunction` is null, a standard distance function is used for the
1493 1494
/// `T` generic argument. Standard functions are defined for the following
/// types:
1495 1496 1497 1498
///
///  * [Color], whose distance is the maximum component-wise delta.
///  * [Offset], whose distance is the Euclidean distance computed using the
///    method [Offset.distance].
1499 1500 1501
///  * [Rect], whose distance is the maximum component-wise delta.
///  * [Size], whose distance is the [Offset.distance] of the offset computed as
///    the difference between two sizes.
1502 1503 1504 1505 1506 1507 1508
///  * [int], whose distance is the absolute difference between two integers.
///  * [double], whose distance is the absolute difference between two doubles.
///
/// See also:
///
///  * [moreOrLessEquals], which is similar to this function, but specializes in
///    [double]s and has an optional `epsilon` parameter.
1509 1510
///  * [rectMoreOrLessEquals], which is similar to this function, but
///    specializes in [Rect]s and has an optional `epsilon` parameter.
1511 1512
///  * [closeTo], which specializes in numbers only.
Matcher within<T>({
1513 1514 1515
  required num distance,
  required T from,
  DistanceFunction<T>? distanceFunction,
1516
}) {
1517
  distanceFunction ??= _kStandardDistanceFunctions[T] as DistanceFunction<T>?;
1518 1519

  if (distanceFunction == null) {
1520
    throw ArgumentError(
1521 1522 1523 1524 1525 1526
      'The specified distanceFunction was null, and a standard distance '
      'function was not found for type ${from.runtimeType} of the provided '
      '`from` argument.'
    );
  }

1527
  return _IsWithinDistance<T>(distanceFunction, from, distance);
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
}

class _IsWithinDistance<T> extends Matcher {
  const _IsWithinDistance(this.distanceFunction, this.value, this.epsilon);

  final DistanceFunction<T> distanceFunction;
  final T value;
  final num epsilon;

  @override
1538
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
1539
    if (object is! T) {
1540
      return false;
1541 1542
    }
    if (object == value) {
1543
      return true;
1544
    }
1545
    final num distance = distanceFunction(object, value);
1546
    if (distance < 0) {
1547
      throw ArgumentError(
1548 1549 1550 1551 1552
        'Invalid distance function was used to compare a ${value.runtimeType} '
        'to a ${object.runtimeType}. The function must return a non-negative '
        'double value, but it returned $distance.'
      );
    }
1553
    matchState['distance'] = distance;
1554 1555 1556 1557 1558
    return distance <= epsilon;
  }

  @override
  Description describe(Description description) => description.add('$value$epsilon)');
1559 1560 1561

  @override
  Description describeMismatch(
1562
    dynamic object,
1563 1564 1565 1566 1567 1568 1569
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
    bool verbose,
  ) {
    mismatchDescription.add('was ${matchState['distance']} away from the desired value.');
    return mismatchDescription;
  }
1570 1571
}

1572
class _MoreOrLessEquals extends Matcher {
1573 1574
  const _MoreOrLessEquals(this.value, this.epsilon)
    : assert(epsilon >= 0);
1575 1576 1577 1578 1579

  final double value;
  final double epsilon;

  @override
1580
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
1581
    if (object is! num) {
1582
      return false;
1583 1584
    }
    if (object == value) {
1585
      return true;
1586
    }
1587
    return (object - value).abs() <= epsilon;
1588 1589 1590 1591
  }

  @override
  Description describe(Description description) => description.add('$value$epsilon)');
1592 1593

  @override
1594
  Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) {
1595 1596 1597
    return super.describeMismatch(item, mismatchDescription, matchState, verbose)
      ..add('$item is not in the range of $value$epsilon).');
  }
1598
}
1599 1600 1601 1602 1603 1604 1605 1606 1607

class _IsMethodCall extends Matcher {
  const _IsMethodCall(this.name, this.arguments);

  final String name;
  final dynamic arguments;

  @override
  bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
1608
    if (item is! MethodCall) {
1609
      return false;
1610 1611
    }
    if (item.method != name) {
1612
      return false;
1613
    }
1614 1615 1616 1617
    return _deepEquals(item.arguments, arguments);
  }

  bool _deepEquals(dynamic a, dynamic b) {
1618
    if (a == b) {
1619
      return true;
1620 1621
    }
    if (a is List) {
1622
      return b is List && _deepEqualsList(a, b);
1623 1624
    }
    if (a is Map) {
1625
      return b is Map && _deepEqualsMap(a, b);
1626
    }
1627 1628 1629 1630
    return false;
  }

  bool _deepEqualsList(List<dynamic> a, List<dynamic> b) {
1631
    if (a.length != b.length) {
1632
      return false;
1633
    }
1634
    for (int i = 0; i < a.length; i++) {
1635
      if (!_deepEquals(a[i], b[i])) {
1636
        return false;
1637
      }
1638 1639 1640 1641 1642
    }
    return true;
  }

  bool _deepEqualsMap(Map<dynamic, dynamic> a, Map<dynamic, dynamic> b) {
1643
    if (a.length != b.length) {
1644
      return false;
1645
    }
1646
    for (final dynamic key in a.keys) {
1647
      if (!b.containsKey(key) || !_deepEquals(a[key], b[key])) {
1648
        return false;
1649
      }
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
    }
    return true;
  }

  @override
  Description describe(Description description) {
    return description
        .add('has method name: ').addDescriptionOf(name)
        .add(' with arguments: ').addDescriptionOf(arguments);
  }
}

1662
/// Asserts that a [Finder] locates a single object whose root RenderObject
1663 1664
/// is a [RenderClipRect] with no clipper set, or an equivalent
/// [RenderClipPath].
1665
const Matcher clipsWithBoundingRect = _ClipsWithBoundingRect();
1666

1667 1668 1669 1670 1671
/// Asserts that a [Finder] locates a single object whose root RenderObject is
/// not a [RenderClipRect], [RenderClipRRect], [RenderClipOval], or
/// [RenderClipPath].
const Matcher hasNoImmediateClip = _MatchAnythingExceptClip();

1672 1673
/// Asserts that a [Finder] locates a single object whose root RenderObject
/// is a [RenderClipRRect] with no clipper set, and border radius equals to
1674
/// [borderRadius], or an equivalent [RenderClipPath].
1675
Matcher clipsWithBoundingRRect({ required BorderRadius borderRadius }) {
1676
  return _ClipsWithBoundingRRect(borderRadius: borderRadius);
1677 1678 1679
}

/// Asserts that a [Finder] locates a single object whose root RenderObject
1680
/// is a [RenderClipPath] with a [ShapeBorderClipper] that clips to
1681
/// [shape].
1682
Matcher clipsWithShapeBorder({ required ShapeBorder shape }) {
1683
  return _ClipsWithShapeBorder(shape: shape);
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
}

/// Asserts that a [Finder] locates a single object whose root RenderObject
/// is a [RenderPhysicalModel] or a [RenderPhysicalShape].
///
/// - If the render object is a [RenderPhysicalModel]
///    - If [shape] is non null asserts that [RenderPhysicalModel.shape] is equal to
///   [shape].
///    - If [borderRadius] is non null asserts that [RenderPhysicalModel.borderRadius] is equal to
///   [borderRadius].
///     - If [elevation] is non null asserts that [RenderPhysicalModel.elevation] is equal to
///   [elevation].
/// - If the render object is a [RenderPhysicalShape]
///    - If [borderRadius] is non null asserts that the shape is a rounded
///   rectangle with this radius.
///    - If [borderRadius] is null, asserts that the shape is equivalent to
///   [shape].
///    - If [elevation] is non null asserts that [RenderPhysicalModel.elevation] is equal to
///   [elevation].
1703
Matcher rendersOnPhysicalModel({
1704 1705 1706
  BoxShape? shape,
  BorderRadius? borderRadius,
  double? elevation,
1707
}) {
1708
  return _RendersOnPhysicalModel(
1709 1710 1711 1712 1713 1714
    shape: shape,
    borderRadius: borderRadius,
    elevation: elevation,
  );
}

1715 1716 1717 1718 1719 1720
/// Asserts that a [Finder] locates a single object whose root RenderObject
/// is [RenderPhysicalShape] that uses a [ShapeBorderClipper] that clips to
/// [shape] as its clipper.
/// If [elevation] is non null asserts that [RenderPhysicalShape.elevation] is
/// equal to [elevation].
Matcher rendersOnPhysicalShape({
1721 1722
  required ShapeBorder shape,
  double? elevation,
1723
}) {
1724
  return _RendersOnPhysicalShape(
1725 1726 1727 1728 1729
    shape: shape,
    elevation: elevation,
  );
}

1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
abstract class _FailWithDescriptionMatcher extends Matcher {
  const _FailWithDescriptionMatcher();

  bool failWithDescription(Map<dynamic, dynamic> matchState, String description) {
    matchState['failure'] = description;
    return false;
  }

  @override
  Description describeMismatch(
1740 1741 1742
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
1743
    bool verbose,
1744
  ) {
1745
    return mismatchDescription.add(matchState['failure'] as String);
1746 1747 1748 1749 1750 1751 1752 1753 1754
  }
}

class _MatchAnythingExceptClip extends _FailWithDescriptionMatcher {
  const _MatchAnythingExceptClip();

  @override
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) {
    final Iterable<Element> nodes = finder.evaluate();
1755
    if (nodes.length != 1) {
1756
      return failWithDescription(matchState, 'did not have a exactly one child element');
1757
    }
1758
    final RenderObject renderObject = nodes.single.renderObject!;
1759 1760

    switch (renderObject.runtimeType) {
1761 1762 1763 1764
      case const (RenderClipPath):
      case const (RenderClipOval):
      case const (RenderClipRect):
      case const (RenderClipRRect):
1765 1766 1767 1768 1769 1770 1771 1772
        return failWithDescription(matchState, 'had a root render object of type: ${renderObject.runtimeType}');
      default:
        return true;
    }
  }

  @override
  Description describe(Description description) {
1773
    return description.add('does not have a clip as an immediate child');
1774 1775 1776 1777
  }
}

abstract class _MatchRenderObject<M extends RenderObject, T extends RenderObject> extends _FailWithDescriptionMatcher {
1778 1779
  const _MatchRenderObject();

1780 1781
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, T renderObject);
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, M renderObject);
1782 1783 1784 1785

  @override
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) {
    final Iterable<Element> nodes = finder.evaluate();
1786
    if (nodes.length != 1) {
1787
      return failWithDescription(matchState, 'did not have a exactly one child element');
1788
    }
1789
    final RenderObject renderObject = nodes.single.renderObject!;
1790

1791
    if (renderObject.runtimeType == T) {
1792
      return renderObjectMatchesT(matchState, renderObject as T);
1793
    }
1794

1795
    if (renderObject.runtimeType == M) {
1796
      return renderObjectMatchesM(matchState, renderObject as M);
1797
    }
1798 1799

    return failWithDescription(matchState, 'had a root render object of type: ${renderObject.runtimeType}');
1800 1801 1802
  }
}

1803
class _RendersOnPhysicalModel extends _MatchRenderObject<RenderPhysicalShape, RenderPhysicalModel> {
1804 1805 1806 1807 1808 1809
  const _RendersOnPhysicalModel({
    this.shape,
    this.borderRadius,
    this.elevation,
  });

1810 1811 1812
  final BoxShape? shape;
  final BorderRadius? borderRadius;
  final double? elevation;
1813 1814

  @override
1815
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, RenderPhysicalModel renderObject) {
1816
    if (shape != null && renderObject.shape != shape) {
1817
      return failWithDescription(matchState, 'had shape: ${renderObject.shape}');
1818
    }
1819

1820
    if (borderRadius != null && renderObject.borderRadius != borderRadius) {
1821
      return failWithDescription(matchState, 'had borderRadius: ${renderObject.borderRadius}');
1822
    }
1823

1824
    if (elevation != null && renderObject.elevation != elevation) {
1825
      return failWithDescription(matchState, 'had elevation: ${renderObject.elevation}');
1826
    }
1827 1828 1829 1830

    return true;
  }

1831 1832
  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderPhysicalShape renderObject) {
1833
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
1834
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
1835
    }
1836
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
1837

1838
    if (borderRadius != null && !assertRoundedRectangle(shapeClipper, borderRadius!, matchState)) {
1839
      return false;
1840
    }
1841

1842
    if (borderRadius == null &&
1843
      shape == BoxShape.rectangle &&
1844
      !assertRoundedRectangle(shapeClipper, BorderRadius.zero, matchState)) {
1845
      return false;
1846
    }
1847

1848
    if (borderRadius == null &&
1849
      shape == BoxShape.circle &&
1850
      !assertCircle(shapeClipper, matchState)) {
1851
      return false;
1852
    }
1853

1854
    if (elevation != null && renderObject.elevation != elevation) {
1855
      return failWithDescription(matchState, 'had elevation: ${renderObject.elevation}');
1856
    }
1857 1858 1859 1860 1861

    return true;
  }

  bool assertRoundedRectangle(ShapeBorderClipper shapeClipper, BorderRadius borderRadius, Map<dynamic, dynamic> matchState) {
1862
    if (shapeClipper.shape.runtimeType != RoundedRectangleBorder) {
1863
      return failWithDescription(matchState, 'had shape border: ${shapeClipper.shape}');
1864
    }
1865
    final RoundedRectangleBorder border = shapeClipper.shape as RoundedRectangleBorder;
1866
    if (border.borderRadius != borderRadius) {
1867
      return failWithDescription(matchState, 'had borderRadius: ${border.borderRadius}');
1868
    }
1869
    return true;
1870 1871 1872
  }

  bool assertCircle(ShapeBorderClipper shapeClipper, Map<dynamic, dynamic> matchState) {
1873
    if (shapeClipper.shape.runtimeType != CircleBorder) {
1874
      return failWithDescription(matchState, 'had shape border: ${shapeClipper.shape}');
1875
    }
1876
    return true;
1877 1878
  }

1879 1880 1881
  @override
  Description describe(Description description) {
    description.add('renders on a physical model');
1882
    if (shape != null) {
1883
      description.add(' with shape $shape');
1884 1885
    }
    if (borderRadius != null) {
1886
      description.add(' with borderRadius $borderRadius');
1887 1888
    }
    if (elevation != null) {
1889
      description.add(' with elevation $elevation');
1890
    }
1891 1892 1893 1894
    return description;
  }
}

1895
class _RendersOnPhysicalShape extends _MatchRenderObject<RenderPhysicalShape, RenderPhysicalModel> {
1896
  const _RendersOnPhysicalShape({
1897
    required this.shape,
1898 1899 1900 1901
    this.elevation,
  });

  final ShapeBorder shape;
1902
  final double? elevation;
1903 1904 1905

  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderPhysicalShape renderObject) {
1906
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
1907
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
1908
    }
1909
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
1910

1911
    if (shapeClipper.shape != shape) {
1912
      return failWithDescription(matchState, 'shape was: ${shapeClipper.shape}');
1913
    }
1914

1915
    if (elevation != null && renderObject.elevation != elevation) {
1916
      return failWithDescription(matchState, 'had elevation: ${renderObject.elevation}');
1917
    }
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929

    return true;
  }

  @override
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, RenderPhysicalModel renderObject) {
    return false;
  }

  @override
  Description describe(Description description) {
    description.add('renders on a physical model with shape $shape');
1930
    if (elevation != null) {
1931
      description.add(' with elevation $elevation');
1932
    }
1933 1934 1935 1936 1937
    return description;
  }
}

class _ClipsWithBoundingRect extends _MatchRenderObject<RenderClipPath, RenderClipRect> {
1938 1939 1940
  const _ClipsWithBoundingRect();

  @override
1941
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, RenderClipRect renderObject) {
1942
    if (renderObject.clipper != null) {
1943
      return failWithDescription(matchState, 'had a non null clipper ${renderObject.clipper}');
1944
    }
1945 1946 1947
    return true;
  }

1948 1949
  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderClipPath renderObject) {
1950
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
1951
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
1952
    }
1953
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
1954
    if (shapeClipper.shape.runtimeType != RoundedRectangleBorder) {
1955
      return failWithDescription(matchState, 'shape was: ${shapeClipper.shape}');
1956
    }
1957
    final RoundedRectangleBorder border = shapeClipper.shape as RoundedRectangleBorder;
1958
    if (border.borderRadius != BorderRadius.zero) {
1959
      return failWithDescription(matchState, 'borderRadius was: ${border.borderRadius}');
1960
    }
1961 1962 1963
    return true;
  }

1964 1965 1966 1967 1968
  @override
  Description describe(Description description) =>
    description.add('clips with bounding rectangle');
}

1969
class _ClipsWithBoundingRRect extends _MatchRenderObject<RenderClipPath, RenderClipRRect> {
1970
  const _ClipsWithBoundingRRect({required this.borderRadius});
1971 1972 1973 1974 1975

  final BorderRadius borderRadius;


  @override
1976
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, RenderClipRRect renderObject) {
1977
    if (renderObject.clipper != null) {
1978
      return failWithDescription(matchState, 'had a non null clipper ${renderObject.clipper}');
1979
    }
1980

1981
    if (renderObject.borderRadius != borderRadius) {
1982
      return failWithDescription(matchState, 'had borderRadius: ${renderObject.borderRadius}');
1983
    }
1984 1985 1986 1987

    return true;
  }

1988 1989
  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderClipPath renderObject) {
1990
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
1991
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
1992
    }
1993
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
1994
    if (shapeClipper.shape.runtimeType != RoundedRectangleBorder) {
1995
      return failWithDescription(matchState, 'shape was: ${shapeClipper.shape}');
1996
    }
1997
    final RoundedRectangleBorder border = shapeClipper.shape as RoundedRectangleBorder;
1998
    if (border.borderRadius != borderRadius) {
1999
      return failWithDescription(matchState, 'had borderRadius: ${border.borderRadius}');
2000
    }
2001 2002 2003
    return true;
  }

2004 2005 2006 2007
  @override
  Description describe(Description description) =>
    description.add('clips with bounding rounded rectangle with borderRadius: $borderRadius');
}
2008

2009
class _ClipsWithShapeBorder extends _MatchRenderObject<RenderClipPath, RenderClipRRect> {
2010
  const _ClipsWithShapeBorder({required this.shape});
2011 2012 2013 2014 2015

  final ShapeBorder shape;

  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderClipPath renderObject) {
2016
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
2017
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
2018
    }
2019
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
2020
    if (shapeClipper.shape != shape) {
2021
      return failWithDescription(matchState, 'shape was: ${shapeClipper.shape}');
2022
    }
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
    return true;
  }

  @override
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, RenderClipRRect renderObject) {
    return false;
  }


  @override
  Description describe(Description description) =>
    description.add('clips with shape: $shape');
}
2036 2037 2038 2039

class _CoversSameAreaAs extends Matcher {
  _CoversSameAreaAs(
    this.expectedPath, {
2040
    required this.areaToCompare,
2041 2042 2043 2044
    this.sampleSize = 20,
  }) : maxHorizontalNoise = areaToCompare.width / sampleSize,
       maxVerticalNoise = areaToCompare.height / sampleSize {
    // Use a fixed random seed to make sure tests are deterministic.
2045
    random = math.Random(1);
2046 2047 2048 2049 2050 2051 2052
  }

  final Path expectedPath;
  final Rect areaToCompare;
  final int sampleSize;
  final double maxHorizontalNoise;
  final double maxVerticalNoise;
2053
  late math.Random random;
2054 2055 2056 2057 2058

  @override
  bool matches(covariant Path actualPath, Map<dynamic, dynamic> matchState) {
    for (int i = 0; i < sampleSize; i += 1) {
      for (int j = 0; j < sampleSize; j += 1) {
2059
        final Offset offset = Offset(
2060
          i * (areaToCompare.width / sampleSize),
2061
          j * (areaToCompare.height / sampleSize),
2062 2063
        );

2064
        if (!_samplePoint(matchState, actualPath, offset)) {
2065
          return false;
2066
        }
2067

2068
        final Offset noise = Offset(
2069 2070 2071 2072
          maxHorizontalNoise * random.nextDouble(),
          maxVerticalNoise * random.nextDouble(),
        );

2073
        if (!_samplePoint(matchState, actualPath, offset + noise)) {
2074
          return false;
2075
        }
2076 2077 2078 2079 2080 2081
      }
    }
    return true;
  }

  bool _samplePoint(Map<dynamic, dynamic> matchState, Path actualPath, Offset offset) {
2082
    if (expectedPath.contains(offset) == actualPath.contains(offset)) {
2083
      return true;
2084
    }
2085

2086
    if (actualPath.contains(offset)) {
2087
      return failWithDescription(matchState, '$offset is contained in the actual path but not in the expected path');
2088
    } else {
2089
      return failWithDescription(matchState, '$offset is contained in the expected path but not in the actual path');
2090
    }
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
  }

  bool failWithDescription(Map<dynamic, dynamic> matchState, String description) {
    matchState['failure'] = description;
    return false;
  }

  @override
  Description describeMismatch(
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
2103
    bool verbose,
2104
  ) {
2105
    return mismatchDescription.add(matchState['failure'] as String);
2106 2107 2108 2109 2110 2111
  }

  @override
  Description describe(Description description) =>
    description.add('covers expected area and only expected area');
}
2112

2113 2114
class _ColorMatcher extends Matcher {
  const _ColorMatcher({
2115
    required this.targetColor,
2116
  });
2117 2118 2119 2120 2121

  final Color targetColor;

  @override
  bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
2122
    if (item is Color) {
2123
      return item == targetColor || item.value == targetColor.value;
2124
    }
2125 2126 2127 2128 2129 2130 2131
    return false;
  }

  @override
  Description describe(Description description) => description.add('matches color $targetColor');
}

2132 2133 2134 2135 2136
int _countDifferentPixels(Uint8List imageA, Uint8List imageB) {
  assert(imageA.length == imageB.length);
  int delta = 0;
  for (int i = 0; i < imageA.length; i+=4) {
    if (imageA[i] != imageB[i] ||
2137 2138 2139
        imageA[i + 1] != imageB[i + 1] ||
        imageA[i + 2] != imageB[i + 2] ||
        imageA[i + 3] != imageB[i + 3]) {
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
      delta++;
    }
  }
  return delta;
}

class _MatchesReferenceImage extends AsyncMatcher {
  const _MatchesReferenceImage(this.referenceImage);

  final ui.Image referenceImage;

  @override
2152
  Future<String?> matchAsync(dynamic item) async {
2153
    Future<ui.Image> imageFuture;
2154
    final bool disposeImage; // set to true if the matcher created and owns the image and must therefore dispose it.
2155 2156
    if (item is Future<ui.Image>) {
      imageFuture = item;
2157
      disposeImage = false;
2158 2159
    } else if (item is ui.Image) {
      imageFuture = Future<ui.Image>.value(item);
2160
      disposeImage = false;
2161
    } else {
2162
      final Finder finder = item as Finder;
2163 2164 2165 2166 2167 2168
      final Iterable<Element> elements = finder.evaluate();
      if (elements.isEmpty) {
        return 'could not be rendered because no widget was found';
      } else if (elements.length > 1) {
        return 'matched too many widgets';
      }
2169
      imageFuture = captureImage(elements.single);
2170
      disposeImage = true;
2171 2172
    }

2173
    final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance;
2174
    return binding.runAsync<String?>(() async {
2175
      final ui.Image image = await imageFuture;
2176 2177 2178 2179 2180
      try {
        final ByteData? bytes = await image.toByteData();
        if (bytes == null) {
          return 'could not be encoded.';
        }
2181

2182 2183 2184 2185
        final ByteData? referenceBytes = await referenceImage.toByteData();
        if (referenceBytes == null) {
          return 'could not have its reference image encoded.';
        }
2186

2187 2188 2189
        if (referenceImage.height != image.height || referenceImage.width != image.width) {
          return 'does not match as width or height do not match. $image != $referenceImage';
        }
2190

2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
        final int countDifferentPixels = _countDifferentPixels(
          Uint8List.view(bytes.buffer),
          Uint8List.view(referenceBytes.buffer),
        );
        return countDifferentPixels == 0 ? null : 'does not match on $countDifferentPixels pixels';
      } finally {
        if (disposeImage) {
          image.dispose();
        }
      }
2201
    });
2202 2203 2204 2205 2206 2207 2208 2209
  }

  @override
  Description describe(Description description) {
    return description.add('rasterized image matches that of a $referenceImage reference image');
  }
}

2210 2211
class _MatchesSemanticsData extends Matcher {
  _MatchesSemanticsData({
2212
    required this.identifier,
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
    required this.label,
    required this.attributedLabel,
    required this.hint,
    required this.attributedHint,
    required this.value,
    required this.attributedValue,
    required this.increasedValue,
    required this.attributedIncreasedValue,
    required this.decreasedValue,
    required this.attributedDecreasedValue,
    required this.tooltip,
    required this.textDirection,
    required this.rect,
    required this.size,
    required this.elevation,
    required this.thickness,
    required this.platformViewId,
    required this.maxValueLength,
    required this.currentValueLength,
    // Flags
    required bool? hasCheckedState,
    required bool? isChecked,
2235
    required bool? isCheckStateMixed,
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
    required bool? isSelected,
    required bool? isButton,
    required bool? isSlider,
    required bool? isKeyboardKey,
    required bool? isLink,
    required bool? isFocused,
    required bool? isFocusable,
    required bool? isTextField,
    required bool? isReadOnly,
    required bool? hasEnabledState,
    required bool? isEnabled,
    required bool? isInMutuallyExclusiveGroup,
    required bool? isHeader,
    required bool? isObscured,
    required bool? isMultiline,
    required bool? namesRoute,
    required bool? scopesRoute,
    required bool? isHidden,
    required bool? isImage,
    required bool? isLiveRegion,
    required bool? hasToggledState,
    required bool? isToggled,
    required bool? hasImplicitScrolling,
2259 2260
    required bool? hasExpandedState,
    required bool? isExpanded,
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
    // Actions
    required bool? hasTapAction,
    required bool? hasLongPressAction,
    required bool? hasScrollLeftAction,
    required bool? hasScrollRightAction,
    required bool? hasScrollUpAction,
    required bool? hasScrollDownAction,
    required bool? hasIncreaseAction,
    required bool? hasDecreaseAction,
    required bool? hasShowOnScreenAction,
    required bool? hasMoveCursorForwardByCharacterAction,
    required bool? hasMoveCursorBackwardByCharacterAction,
    required bool? hasMoveCursorForwardByWordAction,
    required bool? hasMoveCursorBackwardByWordAction,
    required bool? hasSetTextAction,
    required bool? hasSetSelectionAction,
    required bool? hasCopyAction,
    required bool? hasCutAction,
    required bool? hasPasteAction,
    required bool? hasDidGainAccessibilityFocusAction,
    required bool? hasDidLoseAccessibilityFocusAction,
    required bool? hasDismissAction,
    // Custom actions and overrides
    required String? onTapHint,
    required String? onLongPressHint,
    required this.customActions,
    required this.children,
  })  : flags = <SemanticsFlag, bool>{
          if (hasCheckedState != null) SemanticsFlag.hasCheckedState: hasCheckedState,
          if (isChecked != null) SemanticsFlag.isChecked: isChecked,
2291
          if (isCheckStateMixed != null) SemanticsFlag.isCheckStateMixed: isCheckStateMixed,
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
          if (isSelected != null) SemanticsFlag.isSelected: isSelected,
          if (isButton != null) SemanticsFlag.isButton: isButton,
          if (isSlider != null) SemanticsFlag.isSlider: isSlider,
          if (isKeyboardKey != null) SemanticsFlag.isKeyboardKey: isKeyboardKey,
          if (isLink != null) SemanticsFlag.isLink: isLink,
          if (isTextField != null) SemanticsFlag.isTextField: isTextField,
          if (isReadOnly != null) SemanticsFlag.isReadOnly: isReadOnly,
          if (isFocused != null) SemanticsFlag.isFocused: isFocused,
          if (isFocusable != null) SemanticsFlag.isFocusable: isFocusable,
          if (hasEnabledState != null) SemanticsFlag.hasEnabledState: hasEnabledState,
          if (isEnabled != null) SemanticsFlag.isEnabled: isEnabled,
          if (isInMutuallyExclusiveGroup != null) SemanticsFlag.isInMutuallyExclusiveGroup: isInMutuallyExclusiveGroup,
          if (isHeader != null) SemanticsFlag.isHeader: isHeader,
          if (isObscured != null) SemanticsFlag.isObscured: isObscured,
          if (isMultiline != null) SemanticsFlag.isMultiline: isMultiline,
          if (namesRoute != null) SemanticsFlag.namesRoute: namesRoute,
          if (scopesRoute != null) SemanticsFlag.scopesRoute: scopesRoute,
          if (isHidden != null) SemanticsFlag.isHidden: isHidden,
          if (isImage != null) SemanticsFlag.isImage: isImage,
          if (isLiveRegion != null) SemanticsFlag.isLiveRegion: isLiveRegion,
          if (hasToggledState != null) SemanticsFlag.hasToggledState: hasToggledState,
          if (isToggled != null) SemanticsFlag.isToggled: isToggled,
          if (hasImplicitScrolling != null) SemanticsFlag.hasImplicitScrolling: hasImplicitScrolling,
          if (isSlider != null) SemanticsFlag.isSlider: isSlider,
2316 2317
          if (hasExpandedState != null) SemanticsFlag.hasExpandedState: hasExpandedState,
          if (isExpanded != null) SemanticsFlag.isExpanded: isExpanded,
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
        },
        actions = <SemanticsAction, bool>{
          if (hasTapAction != null) SemanticsAction.tap: hasTapAction,
          if (hasLongPressAction != null) SemanticsAction.longPress: hasLongPressAction,
          if (hasScrollLeftAction != null) SemanticsAction.scrollLeft: hasScrollLeftAction,
          if (hasScrollRightAction != null) SemanticsAction.scrollRight: hasScrollRightAction,
          if (hasScrollUpAction != null) SemanticsAction.scrollUp: hasScrollUpAction,
          if (hasScrollDownAction != null) SemanticsAction.scrollDown: hasScrollDownAction,
          if (hasIncreaseAction != null) SemanticsAction.increase: hasIncreaseAction,
          if (hasDecreaseAction != null) SemanticsAction.decrease: hasDecreaseAction,
          if (hasShowOnScreenAction != null) SemanticsAction.showOnScreen: hasShowOnScreenAction,
          if (hasMoveCursorForwardByCharacterAction != null) SemanticsAction.moveCursorForwardByCharacter: hasMoveCursorForwardByCharacterAction,
          if (hasMoveCursorBackwardByCharacterAction != null) SemanticsAction.moveCursorBackwardByCharacter: hasMoveCursorBackwardByCharacterAction,
          if (hasSetSelectionAction != null) SemanticsAction.setSelection: hasSetSelectionAction,
          if (hasCopyAction != null) SemanticsAction.copy: hasCopyAction,
          if (hasCutAction != null) SemanticsAction.cut: hasCutAction,
          if (hasPasteAction != null) SemanticsAction.paste: hasPasteAction,
          if (hasDidGainAccessibilityFocusAction != null) SemanticsAction.didGainAccessibilityFocus: hasDidGainAccessibilityFocusAction,
          if (hasDidLoseAccessibilityFocusAction != null) SemanticsAction.didLoseAccessibilityFocus: hasDidLoseAccessibilityFocusAction,
          if (customActions != null) SemanticsAction.customAction: customActions.isNotEmpty,
          if (hasDismissAction != null) SemanticsAction.dismiss: hasDismissAction,
          if (hasMoveCursorForwardByWordAction != null) SemanticsAction.moveCursorForwardByWord: hasMoveCursorForwardByWordAction,
          if (hasMoveCursorBackwardByWordAction != null) SemanticsAction.moveCursorBackwardByWord: hasMoveCursorBackwardByWordAction,
          if (hasSetTextAction != null) SemanticsAction.setText: hasSetTextAction,
        },
        hintOverrides = onTapHint == null && onLongPressHint == null
            ? null
            : SemanticsHintOverrides(
                onTapHint: onTapHint,
                onLongPressHint: onLongPressHint,
              );
2349

2350
  final String? identifier;
2351
  final String? label;
2352
  final AttributedString? attributedLabel;
2353
  final String? hint;
2354 2355 2356
  final AttributedString? attributedHint;
  final String? value;
  final AttributedString? attributedValue;
2357
  final String? increasedValue;
2358
  final AttributedString? attributedIncreasedValue;
2359
  final String? decreasedValue;
2360
  final AttributedString? attributedDecreasedValue;
2361
  final String? tooltip;
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
  final SemanticsHintOverrides? hintOverrides;
  final List<CustomSemanticsAction>? customActions;
  final TextDirection? textDirection;
  final Rect? rect;
  final Size? size;
  final double? elevation;
  final double? thickness;
  final int? platformViewId;
  final int? maxValueLength;
  final int? currentValueLength;
  final List<Matcher>? children;
2373

2374 2375 2376 2377 2378 2379 2380 2381
  /// There are three possible states for these two maps:
  ///
  ///  1. If the flag/action maps to `true`, then it must be present in the SemanticData
  ///  2. If the flag/action maps to `false`, then it must not be present in the SemanticData
  ///  3. If the flag/action is not in the map, then it will not be validated against
  final Map<SemanticsAction, bool> actions;
  final Map<SemanticsFlag, bool> flags;

2382 2383 2384
  @override
  Description describe(Description description) {
    description.add('has semantics');
2385
    if (label != null) {
2386
      description.add(' with label: $label');
2387 2388
    }
    if (attributedLabel != null) {
2389
      description.add(' with attributedLabel: $attributedLabel');
2390 2391
    }
    if (value != null) {
2392
      description.add(' with value: $value');
2393 2394
    }
    if (attributedValue != null) {
2395
      description.add(' with attributedValue: $attributedValue');
2396 2397
    }
    if (hint != null) {
2398
      description.add(' with hint: $hint');
2399 2400
    }
    if (attributedHint != null) {
2401
      description.add(' with attributedHint: $attributedHint');
2402 2403
    }
    if (increasedValue != null) {
2404
      description.add(' with increasedValue: $increasedValue ');
2405 2406
    }
    if (attributedIncreasedValue != null) {
2407
      description.add(' with attributedIncreasedValue: $attributedIncreasedValue');
2408 2409
    }
    if (decreasedValue != null) {
2410
      description.add(' with decreasedValue: $decreasedValue ');
2411 2412
    }
    if (attributedDecreasedValue != null) {
2413
      description.add(' with attributedDecreasedValue: $attributedDecreasedValue');
2414 2415
    }
    if (tooltip != null) {
2416
      description.add(' with tooltip: $tooltip');
2417
    }
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
    if (actions.isNotEmpty) {
      final List<SemanticsAction> expectedActions = actions.entries
        .where((MapEntry<ui.SemanticsAction, bool> e) => e.value)
        .map((MapEntry<ui.SemanticsAction, bool> e) => e.key)
        .toList();
      final List<SemanticsAction> notExpectedActions = actions.entries
        .where((MapEntry<ui.SemanticsAction, bool> e) => !e.value)
        .map((MapEntry<ui.SemanticsAction, bool> e) => e.key)
        .toList();

      if (expectedActions.isNotEmpty) {
2429
        description.add(' with actions: ${_createEnumsSummary(expectedActions)} ');
2430 2431
      }
      if (notExpectedActions.isNotEmpty) {
2432
        description.add(' without actions: ${_createEnumsSummary(notExpectedActions)} ');
2433
      }
2434
    }
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445
    if (flags.isNotEmpty) {
      final List<SemanticsFlag> expectedFlags = flags.entries
        .where((MapEntry<ui.SemanticsFlag, bool> e) => e.value)
        .map((MapEntry<ui.SemanticsFlag, bool> e) => e.key)
        .toList();
      final List<SemanticsFlag> notExpectedFlags = flags.entries
        .where((MapEntry<ui.SemanticsFlag, bool> e) => !e.value)
        .map((MapEntry<ui.SemanticsFlag, bool> e) => e.key)
        .toList();

      if (expectedFlags.isNotEmpty) {
2446
        description.add(' with flags: ${_createEnumsSummary(expectedFlags)} ');
2447 2448
      }
      if (notExpectedFlags.isNotEmpty) {
2449
        description.add(' without flags: ${_createEnumsSummary(notExpectedFlags)} ');
2450
      }
2451 2452
    }
    if (textDirection != null) {
2453
      description.add(' with textDirection: $textDirection ');
2454 2455
    }
    if (rect != null) {
2456
      description.add(' with rect: $rect');
2457 2458
    }
    if (size != null) {
2459
      description.add(' with size: $size');
2460 2461
    }
    if (elevation != null) {
2462
      description.add(' with elevation: $elevation');
2463 2464
    }
    if (thickness != null) {
2465
      description.add(' with thickness: $thickness');
2466 2467
    }
    if (platformViewId != null) {
2468
      description.add(' with platformViewId: $platformViewId');
2469 2470
    }
    if (maxValueLength != null) {
2471
      description.add(' with maxValueLength: $maxValueLength');
2472 2473
    }
    if (currentValueLength != null) {
2474
      description.add(' with currentValueLength: $currentValueLength');
2475 2476
    }
    if (customActions != null) {
2477
      description.add(' with custom actions: $customActions');
2478 2479
    }
    if (hintOverrides != null) {
2480
      description.add(' with custom hints: $hintOverrides');
2481
    }
2482 2483
    if (children != null) {
      description.add(' with children:\n');
2484
      for (final _MatchesSemanticsData child in children!.cast<_MatchesSemanticsData>()) {
2485
        child.describe(description);
2486
      }
2487
    }
2488 2489 2490
    return description;
  }

2491
  bool _stringAttributesEqual(List<StringAttribute> first, List<StringAttribute> second) {
2492
    if (first.length != second.length) {
2493
      return false;
2494
    }
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
    for (int i = 0; i < first.length; i++) {
      if (first[i] is SpellOutStringAttribute &&
          (second[i] is! SpellOutStringAttribute ||
           second[i].range != first[i].range)) {
        return false;
      }
      if (first[i] is LocaleStringAttribute &&
          (second[i] is! LocaleStringAttribute ||
           second[i].range != first[i].range ||
           (second[i] as LocaleStringAttribute).locale != (second[i] as LocaleStringAttribute).locale)) {
        return false;
      }
    }
    return true;
  }
2510 2511

  @override
2512
  bool matches(dynamic node, Map<dynamic, dynamic> matchState) {
2513
    if (node == null) {
2514
      return failWithDescription(matchState, 'No SemanticsData provided. '
2515
        'Maybe you forgot to enable semantics?');
2516
    }
2517 2518 2519 2520 2521 2522 2523

    final SemanticsData data = switch (node) {
      SemanticsNode() => node.getSemanticsData(),
      FinderBase<SemanticsNode>() => node.evaluate().single.getSemanticsData(),
      _ => node as SemanticsData,
    };

2524
    if (label != null && label != data.label) {
2525
      return failWithDescription(matchState, 'label was: ${data.label}');
2526
    }
2527 2528 2529 2530 2531 2532
    if (attributedLabel != null &&
        (attributedLabel!.string != data.attributedLabel.string ||
         !_stringAttributesEqual(attributedLabel!.attributes, data.attributedLabel.attributes))) {
      return failWithDescription(
          matchState, 'attributedLabel was: ${data.attributedLabel}');
    }
2533
    if (hint != null && hint != data.hint) {
2534
      return failWithDescription(matchState, 'hint was: ${data.hint}');
2535
    }
2536 2537 2538 2539 2540 2541
    if (attributedHint != null &&
        (attributedHint!.string != data.attributedHint.string ||
         !_stringAttributesEqual(attributedHint!.attributes, data.attributedHint.attributes))) {
      return failWithDescription(
          matchState, 'attributedHint was: ${data.attributedHint}');
    }
2542
    if (value != null && value != data.value) {
2543
      return failWithDescription(matchState, 'value was: ${data.value}');
2544
    }
2545 2546 2547 2548 2549 2550
    if (attributedValue != null &&
        (attributedValue!.string != data.attributedValue.string ||
         !_stringAttributesEqual(attributedValue!.attributes, data.attributedValue.attributes))) {
      return failWithDescription(
          matchState, 'attributedValue was: ${data.attributedValue}');
    }
2551
    if (increasedValue != null && increasedValue != data.increasedValue) {
2552
      return failWithDescription(matchState, 'increasedValue was: ${data.increasedValue}');
2553
    }
2554 2555 2556 2557 2558 2559
    if (attributedIncreasedValue != null &&
        (attributedIncreasedValue!.string != data.attributedIncreasedValue.string ||
         !_stringAttributesEqual(attributedIncreasedValue!.attributes, data.attributedIncreasedValue.attributes))) {
      return failWithDescription(
          matchState, 'attributedIncreasedValue was: ${data.attributedIncreasedValue}');
    }
2560
    if (decreasedValue != null && decreasedValue != data.decreasedValue) {
2561
      return failWithDescription(matchState, 'decreasedValue was: ${data.decreasedValue}');
2562
    }
2563 2564 2565 2566 2567 2568
    if (attributedDecreasedValue != null &&
        (attributedDecreasedValue!.string != data.attributedDecreasedValue.string ||
         !_stringAttributesEqual(attributedDecreasedValue!.attributes, data.attributedDecreasedValue.attributes))) {
      return failWithDescription(
          matchState, 'attributedDecreasedValue was: ${data.attributedDecreasedValue}');
    }
2569
    if (tooltip != null && tooltip != data.tooltip) {
2570
      return failWithDescription(matchState, 'tooltip was: ${data.tooltip}');
2571 2572
    }
    if (textDirection != null && textDirection != data.textDirection) {
2573
      return failWithDescription(matchState, 'textDirection was: $textDirection');
2574 2575
    }
    if (rect != null && rect != data.rect) {
2576
      return failWithDescription(matchState, 'rect was: ${data.rect}');
2577 2578
    }
    if (size != null && size != data.rect.size) {
2579
      return failWithDescription(matchState, 'size was: ${data.rect.size}');
2580 2581
    }
    if (elevation != null && elevation != data.elevation) {
2582
      return failWithDescription(matchState, 'elevation was: ${data.elevation}');
2583 2584
    }
    if (thickness != null && thickness != data.thickness) {
2585
      return failWithDescription(matchState, 'thickness was: ${data.thickness}');
2586 2587
    }
    if (platformViewId != null && platformViewId != data.platformViewId) {
2588
      return failWithDescription(matchState, 'platformViewId was: ${data.platformViewId}');
2589 2590
    }
    if (currentValueLength != null && currentValueLength != data.currentValueLength) {
2591
      return failWithDescription(matchState, 'currentValueLength was: ${data.currentValueLength}');
2592 2593
    }
    if (maxValueLength != null && maxValueLength != data.maxValueLength) {
2594
      return failWithDescription(matchState, 'maxValueLength was: ${data.maxValueLength}');
2595
    }
2596
    if (actions.isNotEmpty) {
2597 2598
      final List<SemanticsAction> unexpectedActions = <SemanticsAction>[];
      final List<SemanticsAction> missingActions = <SemanticsAction>[];
2599 2600 2601 2602 2603
      for (final MapEntry<ui.SemanticsAction, bool> actionEntry in actions.entries) {
        final ui.SemanticsAction action = actionEntry.key;
        final bool actionExpected = actionEntry.value;
        final bool actionPresent = (action.index & data.actions) == action.index;
        if (actionPresent != actionExpected) {
2604
          if (actionExpected) {
2605 2606 2607 2608
            missingActions.add(action);
          } else {
            unexpectedActions.add(action);
          }
2609
        }
2610
      }
2611 2612 2613 2614

      if (unexpectedActions.isNotEmpty || missingActions.isNotEmpty) {
        return failWithDescription(matchState, 'missing actions: ${_createEnumsSummary(missingActions)} unexpected actions: ${_createEnumsSummary(unexpectedActions)}');
      }
2615
    }
2616
    if (customActions != null || hintOverrides != null) {
2617 2618 2619
      final List<CustomSemanticsAction> providedCustomActions = data.customSemanticsActionIds?.map<CustomSemanticsAction>((int id) {
        return CustomSemanticsAction.getAction(id)!;
      }).toList() ?? <CustomSemanticsAction>[];
2620
      final List<CustomSemanticsAction> expectedCustomActions = customActions?.toList() ?? <CustomSemanticsAction>[];
2621
      if (hintOverrides?.onTapHint != null) {
2622
        expectedCustomActions.add(CustomSemanticsAction.overridingAction(hint: hintOverrides!.onTapHint!, action: SemanticsAction.tap));
2623 2624
      }
      if (hintOverrides?.onLongPressHint != null) {
2625
        expectedCustomActions.add(CustomSemanticsAction.overridingAction(hint: hintOverrides!.onLongPressHint!, action: SemanticsAction.longPress));
2626 2627
      }
      if (expectedCustomActions.length != providedCustomActions.length) {
2628
        return failWithDescription(matchState, 'custom actions were: $providedCustomActions');
2629
      }
2630 2631 2632 2633 2634 2635
      int sortActions(CustomSemanticsAction left, CustomSemanticsAction right) {
        return CustomSemanticsAction.getIdentifier(left) - CustomSemanticsAction.getIdentifier(right);
      }
      expectedCustomActions.sort(sortActions);
      providedCustomActions.sort(sortActions);
      for (int i = 0; i < expectedCustomActions.length; i++) {
2636
        if (expectedCustomActions[i] != providedCustomActions[i]) {
2637
          return failWithDescription(matchState, 'custom actions were: $providedCustomActions');
2638
        }
2639 2640
      }
    }
2641
    if (flags.isNotEmpty) {
2642 2643
      final List<SemanticsFlag> unexpectedFlags = <SemanticsFlag>[];
      final List<SemanticsFlag> missingFlags = <SemanticsFlag>[];
2644 2645 2646 2647 2648
      for (final MapEntry<ui.SemanticsFlag, bool> flagEntry in flags.entries) {
        final ui.SemanticsFlag flag = flagEntry.key;
        final bool flagExpected = flagEntry.value;
        final bool flagPresent = flag.index & data.flags == flag.index;
        if (flagPresent != flagExpected) {
2649
          if (flagExpected) {
2650 2651 2652 2653
            missingFlags.add(flag);
          } else {
            unexpectedFlags.add(flag);
          }
2654
        }
2655
      }
2656 2657 2658 2659

      if (unexpectedFlags.isNotEmpty || missingFlags.isNotEmpty) {
        return failWithDescription(matchState, 'missing flags: ${_createEnumsSummary(missingFlags)} unexpected flags: ${_createEnumsSummary(unexpectedFlags)}');
      }
2660
    }
2661 2662 2663
    bool allMatched = true;
    if (children != null) {
      int i = 0;
2664
      (node as SemanticsNode).visitChildren((SemanticsNode child) {
2665
        allMatched = children![i].matches(child, matchState) && allMatched;
2666 2667 2668 2669 2670
        i += 1;
        return allMatched;
      });
    }
    return allMatched;
2671 2672 2673 2674 2675 2676 2677 2678 2679
  }

  bool failWithDescription(Map<dynamic, dynamic> matchState, String description) {
    matchState['failure'] = description;
    return false;
  }

  @override
  Description describeMismatch(
2680 2681 2682
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
2683
    bool verbose,
2684
  ) {
2685
    return mismatchDescription.add(matchState['failure'] as String);
2686 2687 2688 2689
  }

  static String _createEnumsSummary<T extends Object>(List<T> enums) {
    assert(T == SemanticsAction || T == SemanticsFlag, 'This method is only intended for lists of SemanticsActions or SemanticsFlags.');
2690 2691 2692 2693 2694
    if (T == SemanticsAction) {
      return '[${(enums as List<SemanticsAction>).map((SemanticsAction d) => d.name).join(', ')}]';
    } else {
      return '[${(enums as List<SemanticsFlag>).map((SemanticsFlag d) => d.name).join(', ')}]';
    }
2695
  }
2696
}
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708

class _MatchesAccessibilityGuideline extends AsyncMatcher {
  _MatchesAccessibilityGuideline(this.guideline);

  final AccessibilityGuideline guideline;

  @override
  Description describe(Description description) {
    return description.add(guideline.description);
  }

  @override
2709
  Future<String?> matchAsync(covariant WidgetTester tester) async {
2710
    final Evaluation result = await guideline.evaluate(tester);
2711
    if (result.passed) {
2712
      return null;
2713
    }
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
    return result.reason;
  }
}

class _DoesNotMatchAccessibilityGuideline extends AsyncMatcher {
  _DoesNotMatchAccessibilityGuideline(this.guideline);

  final AccessibilityGuideline guideline;

  @override
  Description describe(Description description) {
2725
    return description.add('Does not ${guideline.description}');
2726 2727 2728
  }

  @override
2729
  Future<String?> matchAsync(covariant WidgetTester tester) async {
2730
    final Evaluation result = await guideline.evaluate(tester);
2731
    if (result.passed) {
2732
      return 'Failed';
2733
    }
2734 2735
    return null;
  }
2736
}