matchers.dart 95.2 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 579 580 581 582 583 584
/// 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();
///   ui.Image referenceImage = await picture.toImage(50, 50);
///
///   await expectLater(find.text('Save'), matchesReferenceImage(referenceImage));
///   await expectLater(image, matchesReferenceImage(referenceImage));
///   await expectLater(imageFuture, matchesReferenceImage(referenceImage));
/// });
585 586 587 588 589 590 591 592 593 594
/// ```
///
/// 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);
}

595
/// Asserts that a [SemanticsNode] contains the specified information.
596 597
///
/// If either the label, hint, value, textDirection, or rect fields are not
598
/// provided, then they are not part of the comparison. All of the boolean
599 600
/// flag and action fields must match, and default to false.
///
601
/// To retrieve the semantics data of a widget, use [WidgetTester.getSemantics]
602 603 604 605 606 607
/// with a [Finder] that returns a single widget. Semantics must be enabled
/// in order to use this method.
///
/// ## Sample code
///
/// ```dart
608 609 610 611 612 613
/// testWidgets('matchesSemantics', (WidgetTester tester) async {
///   final SemanticsHandle handle = tester.ensureSemantics();
///   // ...
///   expect(tester.getSemantics(find.text('hello')), matchesSemantics(label: 'hello'));
///   handle.dispose();
/// });
614 615 616 617
/// ```
///
/// See also:
///
618
///   * [SemanticsController.find] under [WidgetTester.semantics], the tester method which retrieves semantics.
619
///   * [containsSemantics], a similar matcher without default values for flags or actions.
620
Matcher matchesSemantics({
621
  String? label,
622
  AttributedString? attributedLabel,
623
  String? hint,
624
  AttributedString? attributedHint,
625
  String? value,
626
  AttributedString? attributedValue,
627
  String? increasedValue,
628
  AttributedString? attributedIncreasedValue,
629
  String? decreasedValue,
630
  AttributedString? attributedDecreasedValue,
631
  String? tooltip,
632 633 634 635 636 637 638 639
  TextDirection? textDirection,
  Rect? rect,
  Size? size,
  double? elevation,
  double? thickness,
  int? platformViewId,
  int? maxValueLength,
  int? currentValueLength,
640 641 642
  // Flags //
  bool hasCheckedState = false,
  bool isChecked = false,
643
  bool isCheckStateMixed = false,
644 645
  bool isSelected = false,
  bool isButton = false,
646
  bool isSlider = false,
647
  bool isKeyboardKey = false,
648
  bool isLink = false,
649
  bool isFocused = false,
650
  bool isFocusable = false,
651
  bool isTextField = false,
652
  bool isReadOnly = false,
653 654 655 656 657
  bool hasEnabledState = false,
  bool isEnabled = false,
  bool isInMutuallyExclusiveGroup = false,
  bool isHeader = false,
  bool isObscured = false,
658
  bool isMultiline = false,
659 660 661
  bool namesRoute = false,
  bool scopesRoute = false,
  bool isHidden = false,
662 663 664 665
  bool isImage = false,
  bool isLiveRegion = false,
  bool hasToggledState = false,
  bool isToggled = false,
666
  bool hasImplicitScrolling = false,
667 668
  bool hasExpandedState = false,
  bool isExpanded = false,
669 670 671 672 673 674 675 676 677 678 679 680
  // 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,
681 682
  bool hasMoveCursorForwardByWordAction = false,
  bool hasMoveCursorBackwardByWordAction = false,
683
  bool hasSetTextAction = false,
684 685 686 687 688 689
  bool hasSetSelectionAction = false,
  bool hasCopyAction = false,
  bool hasCutAction = false,
  bool hasPasteAction = false,
  bool hasDidGainAccessibilityFocusAction = false,
  bool hasDidLoseAccessibilityFocusAction = false,
690
  bool hasDismissAction = false,
691
  // Custom actions and overrides
692 693 694 695
  String? onTapHint,
  String? onLongPressHint,
  List<CustomSemanticsAction>? customActions,
  List<Matcher>? children,
696
}) {
697 698
  return _MatchesSemanticsData(
    label: label,
699
    attributedLabel: attributedLabel,
700
    hint: hint,
701
    attributedHint: attributedHint,
702
    value: value,
703
    attributedValue: attributedValue,
704
    increasedValue: increasedValue,
705
    attributedIncreasedValue: attributedIncreasedValue,
706
    decreasedValue: decreasedValue,
707
    attributedDecreasedValue: attributedDecreasedValue,
708
    tooltip: tooltip,
709 710 711
    textDirection: textDirection,
    rect: rect,
    size: size,
712 713
    elevation: elevation,
    thickness: thickness,
714
    platformViewId: platformViewId,
715
    customActions: customActions,
716
    maxValueLength: maxValueLength,
717
    currentValueLength: currentValueLength,
718 719 720
    // Flags
    hasCheckedState: hasCheckedState,
    isChecked: isChecked,
721
    isCheckStateMixed: isCheckStateMixed,
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
    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,
745 746
    hasExpandedState: hasExpandedState,
    isExpanded: isExpanded,
747 748 749 750 751 752 753 754 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
    // 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.
///
/// To retrieve the semantics data of a widget, use [WidgetTester.getSemantics]
/// with a [Finder] that returns a single widget. Semantics must be enabled
/// in order to use this method.
///
/// ## Sample code
///
/// ```dart
788 789 790 791 792 793
/// testWidgets('containsSemantics', (WidgetTester tester) async {
///   final SemanticsHandle handle = tester.ensureSemantics();
///   // ...
///   expect(tester.getSemantics(find.text('hello')), containsSemantics(label: 'hello'));
///   handle.dispose();
/// });
794 795 796 797
/// ```
///
/// See also:
///
798
///   * [SemanticsController.find] under [WidgetTester.semantics], the tester method which retrieves semantics.
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
///   * [matchesSemantics], a similar matcher with default values for flags and actions.
Matcher containsSemantics({
  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,
823
  bool? isCheckStateMixed,
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
  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,
847 848
  bool? hasExpandedState,
  bool? isExpanded,
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
  // 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(
    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,
896
    maxValueLength: maxValueLength,
897 898 899 900
    currentValueLength: currentValueLength,
    // Flags
    hasCheckedState: hasCheckedState,
    isChecked: isChecked,
901
    isCheckStateMixed: isCheckStateMixed,
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    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,
925 926
    hasExpandedState: hasExpandedState,
    isExpanded: isExpanded,
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
    // 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
950
    children: children,
951 952
    onLongPressHint: onLongPressHint,
    onTapHint: onTapHint,
953 954 955
  );
}

956 957 958 959 960 961 962 963 964
/// 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
965 966 967 968 969 970
/// testWidgets('containsSemantics', (WidgetTester tester) async {
///   final SemanticsHandle handle = tester.ensureSemantics();
///   // ...
///   await expectLater(tester, meetsGuideline(textContrastGuideline));
///   handle.dispose();
/// });
971 972 973 974
/// ```
///
/// Supported accessibility guidelines:
///
975 976
///   * [androidTapTargetGuideline], for Android minimum tappable area guidelines.
///   * [iOSTapTargetGuideline], for iOS minimum tappable area guidelines.
977
///   * [textContrastGuideline], for WCAG minimum text contrast guidelines.
978
///   * [labeledTapTargetGuideline], for enforcing labels on tappable areas.
979
AsyncMatcher meetsGuideline(AccessibilityGuideline guideline) {
980
  return _MatchesAccessibilityGuideline(guideline);
981 982 983 984 985 986 987
}

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

991 992
class _FindsCountMatcher extends Matcher {
  const _FindsCountMatcher(this.min, this.max);
993

994 995
  final int? min;
  final int? max;
996 997

  @override
998
  bool matches(covariant FinderBase<dynamic> finder, Map<dynamic, dynamic> matchState) {
999
    assert(min != null || max != null);
1000
    assert(min == null || max == null || min! <= max!);
1001
    matchState[FinderBase] = finder;
1002
    int count = 0;
1003
    final Iterator<dynamic> iterator = finder.evaluate().iterator;
1004
    if (min != null) {
1005
      while (count < min! && iterator.moveNext()) {
1006
        count += 1;
1007 1008
      }
      if (count < min!) {
1009
        return false;
1010
      }
1011 1012
    }
    if (max != null) {
1013
      while (count <= max! && iterator.moveNext()) {
1014
        count += 1;
1015 1016
      }
      if (count > max!) {
1017
        return false;
1018
      }
1019 1020 1021 1022 1023 1024 1025 1026
    }
    return true;
  }

  @override
  Description describe(Description description) {
    assert(min != null || max != null);
    if (min == max) {
1027
      if (min == 1) {
1028
        return description.add('exactly one matching candidate');
1029
      }
1030
      return description.add('exactly $min matching candidates');
1031 1032
    }
    if (min == null) {
1033
      if (max == 0) {
1034
        return description.add('no matching candidates');
1035 1036
      }
      if (max == 1) {
1037
        return description.add('at most one matching candidate');
1038
      }
1039
      return description.add('at most $max matching candidates');
1040 1041
    }
    if (max == null) {
1042
      if (min == 1) {
1043
        return description.add('at least one matching candidate');
1044
      }
1045
      return description.add('at least $min matching candidates');
1046
    }
1047
    return description.add('between $min and $max matching candidates (inclusive)');
1048 1049 1050 1051 1052 1053 1054
  }

  @override
  Description describeMismatch(
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
1055
    bool verbose,
1056
  ) {
1057 1058
    final FinderBase<dynamic> finder = matchState[FinderBase] as FinderBase<dynamic>;
    final int count = finder.found.length;
1059
    if (count == 0) {
1060
      assert(min != null && min! > 0);
1061
      if (min == 1 && max == 1) {
1062
        return mismatchDescription.add('means none were found but one was expected');
1063
      }
1064 1065 1066
      return mismatchDescription.add('means none were found but some were expected');
    }
    if (max == 0) {
1067
      if (count == 1) {
1068
        return mismatchDescription.add('means one was found but none were expected');
1069
      }
1070 1071
      return mismatchDescription.add('means some were found but none were expected');
    }
1072
    if (min != null && count < min!) {
1073
      return mismatchDescription.add('is not enough');
1074
    }
1075
    assert(max != null && count > min!);
1076 1077 1078 1079
    return mismatchDescription.add('is too many');
  }
}

1080
bool _hasAncestorMatching(Finder finder, bool Function(Widget widget) predicate) {
1081
  final Iterable<Element> nodes = finder.evaluate();
1082
  if (nodes.length != 1) {
1083
    return false;
1084
  }
1085
  bool result = false;
1086
  nodes.single.visitAncestorElements((Element ancestor) {
1087
    if (predicate(ancestor.widget)) {
1088 1089 1090 1091 1092 1093 1094 1095
      result = true;
      return false;
    }
    return true;
  });
  return result;
}

1096 1097 1098 1099
bool _hasAncestorOfType(Finder finder, Type targetType) {
  return _hasAncestorMatching(finder, (Widget widget) => widget.runtimeType == targetType);
}

1100 1101
class _IsOffstage extends Matcher {
  const _IsOffstage();
1102 1103

  @override
1104
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) {
1105
    return _hasAncestorMatching(finder, (Widget widget) {
1106
      if (widget is Offstage) {
1107
        return widget.offstage;
1108
      }
1109
      return false;
1110 1111
    });
  }
1112 1113 1114 1115 1116

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

1117 1118
class _IsOnstage extends Matcher {
  const _IsOnstage();
1119 1120

  @override
1121
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) {
1122
    final Iterable<Element> nodes = finder.evaluate();
1123
    if (nodes.length != 1) {
1124
      return false;
1125
    }
1126
    bool result = true;
1127
    nodes.single.visitAncestorElements((Element ancestor) {
1128
      final Widget widget = ancestor.widget;
1129 1130
      if (widget is Offstage) {
        result = !widget.offstage;
1131 1132 1133 1134 1135 1136
        return false;
      }
      return true;
    });
    return result;
  }
1137 1138 1139 1140 1141 1142 1143 1144 1145

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

class _IsInCard extends Matcher {
  const _IsInCard();

  @override
1146
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) => _hasAncestorOfType(finder, Card);
1147 1148 1149 1150 1151 1152 1153 1154 1155

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

class _IsNotInCard extends Matcher {
  const _IsNotInCard();

  @override
1156
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) => !_hasAncestorOfType(finder, Card);
1157 1158 1159 1160

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

1162 1163
class _HasOneLineDescription extends Matcher {
  const _HasOneLineDescription();
1164 1165

  @override
1166
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
1167
    final String description = object.toString();
1168 1169
    return description.isNotEmpty
        && !description.contains('\n')
1170
        && !description.contains('Instance of ')
1171
        && description.trim() == description;
1172 1173 1174 1175 1176
  }

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

1178
class _EqualsIgnoringHashCodes extends Matcher {
1179
  _EqualsIgnoringHashCodes(Object v) : _value = _normalize(v);
1180

1181
  final Object _value;
1182

1183
  static final Object _mismatchedValueKey = Object();
1184

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
  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}');
1199 1200 1201 1202
  }

  @override
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
1203 1204 1205
    final Object normalized = _normalize(object as Object, expected: false);
    if (!equals(_value).matches(normalized, matchState)) {
      matchState[_mismatchedValueKey] = normalized;
1206 1207 1208 1209 1210 1211 1212
      return false;
    }
    return true;
  }

  @override
  Description describe(Description description) {
1213 1214 1215 1216
    if (_value is String) {
      return description.add('normalized value matches $_value');
    }
    return description.add('normalized value matches\n').addDescriptionOf(_value);
1217 1218 1219 1220 1221 1222 1223
  }

  @override
  Description describeMismatch(
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
1224
    bool verbose,
1225 1226
  ) {
    if (matchState.containsKey(_mismatchedValueKey)) {
1227
      final Object actualValue = matchState[_mismatchedValueKey] as Object;
1228
      // Leading whitespace is added so that lines in the multiline
1229 1230 1231
      // description returned by addDescriptionOf are all indented equally
      // which makes the output easier to read for this case.
      return mismatchDescription
1232
          .add('was expected to be normalized value\n')
1233
          .addDescriptionOf(_value)
1234
          .add('\nbut got\n')
1235 1236 1237 1238 1239 1240
          .addDescriptionOf(actualValue);
    }
    return mismatchDescription;
  }
}

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

1244
/// Returns true if [c] represents a vertical line Unicode line art code unit.
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
///
/// 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);
1262
    if (!_isWhitespace(c) && !_isVerticalLine(c)) {
1263
      return false;
1264
    }
1265 1266 1267 1268 1269 1270 1271
  }
  return true;
}

class _HasGoodToStringDeep extends Matcher {
  const _HasGoodToStringDeep();

1272
  static final Object _toStringDeepErrorDescriptionKey = Object();
1273 1274 1275 1276

  @override
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
    final List<String> issues = <String>[];
1277
    String description = object.toStringDeep() as String; // ignore: avoid_dynamic_calls
1278 1279 1280 1281 1282 1283 1284 1285
    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.');
    }

1286
    if (description.trim() != description) {
1287
      issues.add('Has trailing whitespace.');
1288
    }
1289 1290

    final List<String> lines = description.split('\n');
1291
    if (lines.length < 2) {
1292
      issues.add('Does not have multiple lines.');
1293
    }
1294

1295
    if (description.contains('Instance of ')) {
1296
      issues.add('Contains text "Instance of ".');
1297
    }
1298 1299 1300

    for (int i = 0; i < lines.length; ++i) {
      final String line = lines[i];
1301
      if (line.isEmpty) {
1302
        issues.add('Line ${i + 1} is empty.');
1303
      }
1304

1305
      if (line.trimRight() != line) {
1306
        issues.add('Line ${i + 1} has trailing whitespace.');
1307
      }
1308 1309
    }

1310
    if (_isAllTreeConnectorCharacters(lines.last)) {
1311
      issues.add('Last line is all tree connector characters.');
1312
    }
1313 1314

    // If a toStringDeep method doesn't properly handle nested values that
1315
    // contain line breaks it can fail to add the required prefixes to all
1316
    // lined when toStringDeep is called specifying prefixes.
1317
    const String prefixLineOne = 'PREFIX_LINE_ONE____';
1318
    const String prefixOtherLines = 'PREFIX_OTHER_LINES_';
1319
    final List<String> prefixIssues = <String>[];
1320 1321
    // ignore: avoid_dynamic_calls
    String descriptionWithPrefixes = object.toStringDeep(prefixLineOne: prefixLineOne, prefixOtherLines: prefixOtherLines) as String;
1322 1323 1324 1325 1326 1327 1328
    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');
1329
    if (!linesWithPrefixes.first.startsWith(prefixLineOne)) {
1330
      prefixIssues.add('First line does not contain expected prefix.');
1331
    }
1332 1333

    for (int i = 1; i < linesWithPrefixes.length; ++i) {
1334
      if (!linesWithPrefixes[i].startsWith(prefixOtherLines)) {
1335
        prefixIssues.add('Line ${i + 1} does not contain the expected prefix.');
1336
      }
1337 1338
    }

1339
    final StringBuffer errorDescription = StringBuffer();
1340 1341 1342 1343 1344 1345 1346 1347
    if (issues.isNotEmpty) {
      errorDescription.writeln('Bad toStringDeep():');
      errorDescription.writeln(description);
      errorDescription.writeAll(issues, '\n');
    }

    if (prefixIssues.isNotEmpty) {
      errorDescription.writeln(
1348
          'Bad toStringDeep(prefixLineOne: "$prefixLineOne", prefixOtherLines: "$prefixOtherLines"):');
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
      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,
1366
    bool verbose,
1367 1368
  ) {
    if (matchState.containsKey(_toStringDeepErrorDescriptionKey)) {
1369
      return mismatchDescription.add(matchState[_toStringDeepErrorDescriptionKey] as String);
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
    }
    return mismatchDescription;
  }

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

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
/// 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.
1393
typedef DistanceFunction<T> = num Function(T a, T b);
1394

1395 1396 1397 1398
/// 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>]
1399
/// functions which have (potentially) unrelated argument types. Since the
1400 1401 1402
/// 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.
1403 1404 1405
///
/// Calling an instance of this type must either be done dynamically, or by
/// first casting it to a [DistanceFunction<T>] for some concrete T.
1406
typedef AnyDistanceFunction = num Function(Never a, Never b);
1407

1408
const Map<Type, AnyDistanceFunction> _kStandardDistanceFunctions = <Type, AnyDistanceFunction>{
1409
  Color: _maxComponentColorDistance,
1410 1411
  HSVColor: _maxComponentHSVColorDistance,
  HSLColor: _maxComponentHSLColorDistance,
1412 1413 1414
  Offset: _offsetDistance,
  int: _intDistance,
  double: _doubleDistance,
1415
  Rect: _rectDistance,
1416
  Size: _sizeDistance,
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
};

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();
}

1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
// 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());
}

1446 1447 1448 1449 1450 1451 1452
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;
}

1453 1454 1455 1456 1457 1458 1459 1460
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;
}

1461 1462 1463 1464 1465 1466 1467 1468
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;
}

1469
double _sizeDistance(Size a, Size b) {
1470 1471 1472
  // TODO(a14n): remove ignore when lint is updated, https://github.com/dart-lang/linter/issues/1843
  // ignore: unnecessary_parenthesis
  final Offset delta = (b - a) as Offset;
1473
  return delta.distance;
1474 1475
}

1476 1477 1478 1479 1480
/// 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
1481 1482
/// `T` generic argument. Standard functions are defined for the following
/// types:
1483 1484 1485 1486
///
///  * [Color], whose distance is the maximum component-wise delta.
///  * [Offset], whose distance is the Euclidean distance computed using the
///    method [Offset.distance].
1487 1488 1489
///  * [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.
1490 1491 1492 1493 1494 1495 1496
///  * [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.
1497 1498
///  * [rectMoreOrLessEquals], which is similar to this function, but
///    specializes in [Rect]s and has an optional `epsilon` parameter.
1499 1500
///  * [closeTo], which specializes in numbers only.
Matcher within<T>({
1501 1502 1503
  required num distance,
  required T from,
  DistanceFunction<T>? distanceFunction,
1504
}) {
1505
  distanceFunction ??= _kStandardDistanceFunctions[T] as DistanceFunction<T>?;
1506 1507

  if (distanceFunction == null) {
1508
    throw ArgumentError(
1509 1510 1511 1512 1513 1514
      'The specified distanceFunction was null, and a standard distance '
      'function was not found for type ${from.runtimeType} of the provided '
      '`from` argument.'
    );
  }

1515
  return _IsWithinDistance<T>(distanceFunction, from, distance);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
}

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

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

  @override
1526
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
1527
    if (object is! T) {
1528
      return false;
1529 1530
    }
    if (object == value) {
1531
      return true;
1532
    }
1533
    final num distance = distanceFunction(object, value);
1534
    if (distance < 0) {
1535
      throw ArgumentError(
1536 1537 1538 1539 1540
        '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.'
      );
    }
1541
    matchState['distance'] = distance;
1542 1543 1544 1545 1546
    return distance <= epsilon;
  }

  @override
  Description describe(Description description) => description.add('$value$epsilon)');
1547 1548 1549

  @override
  Description describeMismatch(
1550
    dynamic object,
1551 1552 1553 1554 1555 1556 1557
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
    bool verbose,
  ) {
    mismatchDescription.add('was ${matchState['distance']} away from the desired value.');
    return mismatchDescription;
  }
1558 1559
}

1560
class _MoreOrLessEquals extends Matcher {
1561 1562
  const _MoreOrLessEquals(this.value, this.epsilon)
    : assert(epsilon >= 0);
1563 1564 1565 1566 1567

  final double value;
  final double epsilon;

  @override
1568
  bool matches(dynamic object, Map<dynamic, dynamic> matchState) {
1569
    if (object is! num) {
1570
      return false;
1571 1572
    }
    if (object == value) {
1573
      return true;
1574
    }
1575
    return (object - value).abs() <= epsilon;
1576 1577 1578 1579
  }

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

  @override
1582
  Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) {
1583 1584 1585
    return super.describeMismatch(item, mismatchDescription, matchState, verbose)
      ..add('$item is not in the range of $value$epsilon).');
  }
1586
}
1587 1588 1589 1590 1591 1592 1593 1594 1595

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) {
1596
    if (item is! MethodCall) {
1597
      return false;
1598 1599
    }
    if (item.method != name) {
1600
      return false;
1601
    }
1602 1603 1604 1605
    return _deepEquals(item.arguments, arguments);
  }

  bool _deepEquals(dynamic a, dynamic b) {
1606
    if (a == b) {
1607
      return true;
1608 1609
    }
    if (a is List) {
1610
      return b is List && _deepEqualsList(a, b);
1611 1612
    }
    if (a is Map) {
1613
      return b is Map && _deepEqualsMap(a, b);
1614
    }
1615 1616 1617 1618
    return false;
  }

  bool _deepEqualsList(List<dynamic> a, List<dynamic> b) {
1619
    if (a.length != b.length) {
1620
      return false;
1621
    }
1622
    for (int i = 0; i < a.length; i++) {
1623
      if (!_deepEquals(a[i], b[i])) {
1624
        return false;
1625
      }
1626 1627 1628 1629 1630
    }
    return true;
  }

  bool _deepEqualsMap(Map<dynamic, dynamic> a, Map<dynamic, dynamic> b) {
1631
    if (a.length != b.length) {
1632
      return false;
1633
    }
1634
    for (final dynamic key in a.keys) {
1635
      if (!b.containsKey(key) || !_deepEquals(a[key], b[key])) {
1636
        return false;
1637
      }
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
    }
    return true;
  }

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

1650
/// Asserts that a [Finder] locates a single object whose root RenderObject
1651 1652
/// is a [RenderClipRect] with no clipper set, or an equivalent
/// [RenderClipPath].
1653
const Matcher clipsWithBoundingRect = _ClipsWithBoundingRect();
1654

1655 1656 1657 1658 1659
/// Asserts that a [Finder] locates a single object whose root RenderObject is
/// not a [RenderClipRect], [RenderClipRRect], [RenderClipOval], or
/// [RenderClipPath].
const Matcher hasNoImmediateClip = _MatchAnythingExceptClip();

1660 1661
/// Asserts that a [Finder] locates a single object whose root RenderObject
/// is a [RenderClipRRect] with no clipper set, and border radius equals to
1662
/// [borderRadius], or an equivalent [RenderClipPath].
1663
Matcher clipsWithBoundingRRect({ required BorderRadius borderRadius }) {
1664
  return _ClipsWithBoundingRRect(borderRadius: borderRadius);
1665 1666 1667
}

/// Asserts that a [Finder] locates a single object whose root RenderObject
1668
/// is a [RenderClipPath] with a [ShapeBorderClipper] that clips to
1669
/// [shape].
1670
Matcher clipsWithShapeBorder({ required ShapeBorder shape }) {
1671
  return _ClipsWithShapeBorder(shape: shape);
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
}

/// 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].
1691
Matcher rendersOnPhysicalModel({
1692 1693 1694
  BoxShape? shape,
  BorderRadius? borderRadius,
  double? elevation,
1695
}) {
1696
  return _RendersOnPhysicalModel(
1697 1698 1699 1700 1701 1702
    shape: shape,
    borderRadius: borderRadius,
    elevation: elevation,
  );
}

1703 1704 1705 1706 1707 1708
/// 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({
1709 1710
  required ShapeBorder shape,
  double? elevation,
1711
}) {
1712
  return _RendersOnPhysicalShape(
1713 1714 1715 1716 1717
    shape: shape,
    elevation: elevation,
  );
}

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
abstract class _FailWithDescriptionMatcher extends Matcher {
  const _FailWithDescriptionMatcher();

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

  @override
  Description describeMismatch(
1728 1729 1730
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
1731
    bool verbose,
1732
  ) {
1733
    return mismatchDescription.add(matchState['failure'] as String);
1734 1735 1736 1737 1738 1739 1740 1741 1742
  }
}

class _MatchAnythingExceptClip extends _FailWithDescriptionMatcher {
  const _MatchAnythingExceptClip();

  @override
  bool matches(covariant Finder finder, Map<dynamic, dynamic> matchState) {
    final Iterable<Element> nodes = finder.evaluate();
1743
    if (nodes.length != 1) {
1744
      return failWithDescription(matchState, 'did not have a exactly one child element');
1745
    }
1746
    final RenderObject renderObject = nodes.single.renderObject!;
1747 1748

    switch (renderObject.runtimeType) {
1749 1750 1751 1752
      case const (RenderClipPath):
      case const (RenderClipOval):
      case const (RenderClipRect):
      case const (RenderClipRRect):
1753 1754 1755 1756 1757 1758 1759 1760
        return failWithDescription(matchState, 'had a root render object of type: ${renderObject.runtimeType}');
      default:
        return true;
    }
  }

  @override
  Description describe(Description description) {
1761
    return description.add('does not have a clip as an immediate child');
1762 1763 1764 1765
  }
}

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

1768 1769
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, T renderObject);
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, M renderObject);
1770 1771 1772 1773

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

1779
    if (renderObject.runtimeType == T) {
1780
      return renderObjectMatchesT(matchState, renderObject as T);
1781
    }
1782

1783
    if (renderObject.runtimeType == M) {
1784
      return renderObjectMatchesM(matchState, renderObject as M);
1785
    }
1786 1787

    return failWithDescription(matchState, 'had a root render object of type: ${renderObject.runtimeType}');
1788 1789 1790
  }
}

1791
class _RendersOnPhysicalModel extends _MatchRenderObject<RenderPhysicalShape, RenderPhysicalModel> {
1792 1793 1794 1795 1796 1797
  const _RendersOnPhysicalModel({
    this.shape,
    this.borderRadius,
    this.elevation,
  });

1798 1799 1800
  final BoxShape? shape;
  final BorderRadius? borderRadius;
  final double? elevation;
1801 1802

  @override
1803
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, RenderPhysicalModel renderObject) {
1804
    if (shape != null && renderObject.shape != shape) {
1805
      return failWithDescription(matchState, 'had shape: ${renderObject.shape}');
1806
    }
1807

1808
    if (borderRadius != null && renderObject.borderRadius != borderRadius) {
1809
      return failWithDescription(matchState, 'had borderRadius: ${renderObject.borderRadius}');
1810
    }
1811

1812
    if (elevation != null && renderObject.elevation != elevation) {
1813
      return failWithDescription(matchState, 'had elevation: ${renderObject.elevation}');
1814
    }
1815 1816 1817 1818

    return true;
  }

1819 1820
  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderPhysicalShape renderObject) {
1821
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
1822
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
1823
    }
1824
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
1825

1826
    if (borderRadius != null && !assertRoundedRectangle(shapeClipper, borderRadius!, matchState)) {
1827
      return false;
1828
    }
1829

1830
    if (borderRadius == null &&
1831
      shape == BoxShape.rectangle &&
1832
      !assertRoundedRectangle(shapeClipper, BorderRadius.zero, matchState)) {
1833
      return false;
1834
    }
1835

1836
    if (borderRadius == null &&
1837
      shape == BoxShape.circle &&
1838
      !assertCircle(shapeClipper, matchState)) {
1839
      return false;
1840
    }
1841

1842
    if (elevation != null && renderObject.elevation != elevation) {
1843
      return failWithDescription(matchState, 'had elevation: ${renderObject.elevation}');
1844
    }
1845 1846 1847 1848 1849

    return true;
  }

  bool assertRoundedRectangle(ShapeBorderClipper shapeClipper, BorderRadius borderRadius, Map<dynamic, dynamic> matchState) {
1850
    if (shapeClipper.shape.runtimeType != RoundedRectangleBorder) {
1851
      return failWithDescription(matchState, 'had shape border: ${shapeClipper.shape}');
1852
    }
1853
    final RoundedRectangleBorder border = shapeClipper.shape as RoundedRectangleBorder;
1854
    if (border.borderRadius != borderRadius) {
1855
      return failWithDescription(matchState, 'had borderRadius: ${border.borderRadius}');
1856
    }
1857
    return true;
1858 1859 1860
  }

  bool assertCircle(ShapeBorderClipper shapeClipper, Map<dynamic, dynamic> matchState) {
1861
    if (shapeClipper.shape.runtimeType != CircleBorder) {
1862
      return failWithDescription(matchState, 'had shape border: ${shapeClipper.shape}');
1863
    }
1864
    return true;
1865 1866
  }

1867 1868 1869
  @override
  Description describe(Description description) {
    description.add('renders on a physical model');
1870
    if (shape != null) {
1871
      description.add(' with shape $shape');
1872 1873
    }
    if (borderRadius != null) {
1874
      description.add(' with borderRadius $borderRadius');
1875 1876
    }
    if (elevation != null) {
1877
      description.add(' with elevation $elevation');
1878
    }
1879 1880 1881 1882
    return description;
  }
}

1883
class _RendersOnPhysicalShape extends _MatchRenderObject<RenderPhysicalShape, RenderPhysicalModel> {
1884
  const _RendersOnPhysicalShape({
1885
    required this.shape,
1886 1887 1888 1889
    this.elevation,
  });

  final ShapeBorder shape;
1890
  final double? elevation;
1891 1892 1893

  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderPhysicalShape renderObject) {
1894
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
1895
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
1896
    }
1897
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
1898

1899
    if (shapeClipper.shape != shape) {
1900
      return failWithDescription(matchState, 'shape was: ${shapeClipper.shape}');
1901
    }
1902

1903
    if (elevation != null && renderObject.elevation != elevation) {
1904
      return failWithDescription(matchState, 'had elevation: ${renderObject.elevation}');
1905
    }
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917

    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');
1918
    if (elevation != null) {
1919
      description.add(' with elevation $elevation');
1920
    }
1921 1922 1923 1924 1925
    return description;
  }
}

class _ClipsWithBoundingRect extends _MatchRenderObject<RenderClipPath, RenderClipRect> {
1926 1927 1928
  const _ClipsWithBoundingRect();

  @override
1929
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, RenderClipRect renderObject) {
1930
    if (renderObject.clipper != null) {
1931
      return failWithDescription(matchState, 'had a non null clipper ${renderObject.clipper}');
1932
    }
1933 1934 1935
    return true;
  }

1936 1937
  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderClipPath renderObject) {
1938
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
1939
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
1940
    }
1941
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
1942
    if (shapeClipper.shape.runtimeType != RoundedRectangleBorder) {
1943
      return failWithDescription(matchState, 'shape was: ${shapeClipper.shape}');
1944
    }
1945
    final RoundedRectangleBorder border = shapeClipper.shape as RoundedRectangleBorder;
1946
    if (border.borderRadius != BorderRadius.zero) {
1947
      return failWithDescription(matchState, 'borderRadius was: ${border.borderRadius}');
1948
    }
1949 1950 1951
    return true;
  }

1952 1953 1954 1955 1956
  @override
  Description describe(Description description) =>
    description.add('clips with bounding rectangle');
}

1957
class _ClipsWithBoundingRRect extends _MatchRenderObject<RenderClipPath, RenderClipRRect> {
1958
  const _ClipsWithBoundingRRect({required this.borderRadius});
1959 1960 1961 1962 1963

  final BorderRadius borderRadius;


  @override
1964
  bool renderObjectMatchesT(Map<dynamic, dynamic> matchState, RenderClipRRect renderObject) {
1965
    if (renderObject.clipper != null) {
1966
      return failWithDescription(matchState, 'had a non null clipper ${renderObject.clipper}');
1967
    }
1968

1969
    if (renderObject.borderRadius != borderRadius) {
1970
      return failWithDescription(matchState, 'had borderRadius: ${renderObject.borderRadius}');
1971
    }
1972 1973 1974 1975

    return true;
  }

1976 1977
  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderClipPath renderObject) {
1978
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
1979
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
1980
    }
1981
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
1982
    if (shapeClipper.shape.runtimeType != RoundedRectangleBorder) {
1983
      return failWithDescription(matchState, 'shape was: ${shapeClipper.shape}');
1984
    }
1985
    final RoundedRectangleBorder border = shapeClipper.shape as RoundedRectangleBorder;
1986
    if (border.borderRadius != borderRadius) {
1987
      return failWithDescription(matchState, 'had borderRadius: ${border.borderRadius}');
1988
    }
1989 1990 1991
    return true;
  }

1992 1993 1994 1995
  @override
  Description describe(Description description) =>
    description.add('clips with bounding rounded rectangle with borderRadius: $borderRadius');
}
1996

1997
class _ClipsWithShapeBorder extends _MatchRenderObject<RenderClipPath, RenderClipRRect> {
1998
  const _ClipsWithShapeBorder({required this.shape});
1999 2000 2001 2002 2003

  final ShapeBorder shape;

  @override
  bool renderObjectMatchesM(Map<dynamic, dynamic> matchState, RenderClipPath renderObject) {
2004
    if (renderObject.clipper.runtimeType != ShapeBorderClipper) {
2005
      return failWithDescription(matchState, 'clipper was: ${renderObject.clipper}');
2006
    }
2007
    final ShapeBorderClipper shapeClipper = renderObject.clipper! as ShapeBorderClipper;
2008
    if (shapeClipper.shape != shape) {
2009
      return failWithDescription(matchState, 'shape was: ${shapeClipper.shape}');
2010
    }
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
    return true;
  }

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


  @override
  Description describe(Description description) =>
    description.add('clips with shape: $shape');
}
2024 2025 2026 2027

class _CoversSameAreaAs extends Matcher {
  _CoversSameAreaAs(
    this.expectedPath, {
2028
    required this.areaToCompare,
2029 2030 2031 2032
    this.sampleSize = 20,
  }) : maxHorizontalNoise = areaToCompare.width / sampleSize,
       maxVerticalNoise = areaToCompare.height / sampleSize {
    // Use a fixed random seed to make sure tests are deterministic.
2033
    random = math.Random(1);
2034 2035 2036 2037 2038 2039 2040
  }

  final Path expectedPath;
  final Rect areaToCompare;
  final int sampleSize;
  final double maxHorizontalNoise;
  final double maxVerticalNoise;
2041
  late math.Random random;
2042 2043 2044 2045 2046

  @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) {
2047
        final Offset offset = Offset(
2048
          i * (areaToCompare.width / sampleSize),
2049
          j * (areaToCompare.height / sampleSize),
2050 2051
        );

2052
        if (!_samplePoint(matchState, actualPath, offset)) {
2053
          return false;
2054
        }
2055

2056
        final Offset noise = Offset(
2057 2058 2059 2060
          maxHorizontalNoise * random.nextDouble(),
          maxVerticalNoise * random.nextDouble(),
        );

2061
        if (!_samplePoint(matchState, actualPath, offset + noise)) {
2062
          return false;
2063
        }
2064 2065 2066 2067 2068 2069
      }
    }
    return true;
  }

  bool _samplePoint(Map<dynamic, dynamic> matchState, Path actualPath, Offset offset) {
2070
    if (expectedPath.contains(offset) == actualPath.contains(offset)) {
2071
      return true;
2072
    }
2073

2074
    if (actualPath.contains(offset)) {
2075
      return failWithDescription(matchState, '$offset is contained in the actual path but not in the expected path');
2076
    } else {
2077
      return failWithDescription(matchState, '$offset is contained in the expected path but not in the actual path');
2078
    }
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
  }

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

  @override
  Description describeMismatch(
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
2091
    bool verbose,
2092
  ) {
2093
    return mismatchDescription.add(matchState['failure'] as String);
2094 2095 2096 2097 2098 2099
  }

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

2101 2102
class _ColorMatcher extends Matcher {
  const _ColorMatcher({
2103
    required this.targetColor,
2104
  });
2105 2106 2107 2108 2109

  final Color targetColor;

  @override
  bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
2110
    if (item is Color) {
2111
      return item == targetColor || item.value == targetColor.value;
2112
    }
2113 2114 2115 2116 2117 2118 2119
    return false;
  }

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

2120 2121 2122 2123 2124
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] ||
2125 2126 2127
        imageA[i + 1] != imageB[i + 1] ||
        imageA[i + 2] != imageB[i + 2] ||
        imageA[i + 3] != imageB[i + 3]) {
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
      delta++;
    }
  }
  return delta;
}

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

  final ui.Image referenceImage;

  @override
2140
  Future<String?> matchAsync(dynamic item) async {
2141 2142 2143 2144 2145 2146
    Future<ui.Image> imageFuture;
    if (item is Future<ui.Image>) {
      imageFuture = item;
    } else if (item is ui.Image) {
      imageFuture = Future<ui.Image>.value(item);
    } else {
2147
      final Finder finder = item as Finder;
2148 2149 2150 2151 2152 2153
      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';
      }
2154
      imageFuture = captureImage(elements.single);
2155 2156
    }

2157
    final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance;
2158
    return binding.runAsync<String?>(() async {
2159
      final ui.Image image = await imageFuture;
2160
      final ByteData? bytes = await image.toByteData();
2161
      if (bytes == null) {
2162
        return 'could not be encoded.';
2163
      }
2164

2165
      final ByteData? referenceBytes = await referenceImage.toByteData();
2166
      if (referenceBytes == null) {
2167
        return 'could not have its reference image encoded.';
2168
      }
2169

2170
      if (referenceImage.height != image.height || referenceImage.width != image.width) {
2171
        return 'does not match as width or height do not match. $image != $referenceImage';
2172
      }
2173 2174 2175 2176 2177 2178

      final int countDifferentPixels = _countDifferentPixels(
        Uint8List.view(bytes.buffer),
        Uint8List.view(referenceBytes.buffer),
      );
      return countDifferentPixels == 0 ? null : 'does not match on $countDifferentPixels pixels';
2179
    });
2180 2181 2182 2183 2184 2185 2186 2187
  }

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

2188 2189
class _MatchesSemanticsData extends Matcher {
  _MatchesSemanticsData({
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
    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,
2212
    required bool? isCheckStateMixed,
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
    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,
2236 2237
    required bool? hasExpandedState,
    required bool? isExpanded,
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
    // 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,
2268
          if (isCheckStateMixed != null) SemanticsFlag.isCheckStateMixed: isCheckStateMixed,
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
          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,
2293 2294
          if (hasExpandedState != null) SemanticsFlag.hasExpandedState: hasExpandedState,
          if (isExpanded != null) SemanticsFlag.isExpanded: isExpanded,
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
        },
        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,
              );
2326

2327
  final String? label;
2328
  final AttributedString? attributedLabel;
2329
  final String? hint;
2330 2331 2332
  final AttributedString? attributedHint;
  final String? value;
  final AttributedString? attributedValue;
2333
  final String? increasedValue;
2334
  final AttributedString? attributedIncreasedValue;
2335
  final String? decreasedValue;
2336
  final AttributedString? attributedDecreasedValue;
2337
  final String? tooltip;
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
  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;
2349

2350 2351 2352 2353 2354 2355 2356 2357
  /// 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;

2358 2359 2360
  @override
  Description describe(Description description) {
    description.add('has semantics');
2361
    if (label != null) {
2362
      description.add(' with label: $label');
2363 2364
    }
    if (attributedLabel != null) {
2365
      description.add(' with attributedLabel: $attributedLabel');
2366 2367
    }
    if (value != null) {
2368
      description.add(' with value: $value');
2369 2370
    }
    if (attributedValue != null) {
2371
      description.add(' with attributedValue: $attributedValue');
2372 2373
    }
    if (hint != null) {
2374
      description.add(' with hint: $hint');
2375 2376
    }
    if (attributedHint != null) {
2377
      description.add(' with attributedHint: $attributedHint');
2378 2379
    }
    if (increasedValue != null) {
2380
      description.add(' with increasedValue: $increasedValue ');
2381 2382
    }
    if (attributedIncreasedValue != null) {
2383
      description.add(' with attributedIncreasedValue: $attributedIncreasedValue');
2384 2385
    }
    if (decreasedValue != null) {
2386
      description.add(' with decreasedValue: $decreasedValue ');
2387 2388
    }
    if (attributedDecreasedValue != null) {
2389
      description.add(' with attributedDecreasedValue: $attributedDecreasedValue');
2390 2391
    }
    if (tooltip != null) {
2392
      description.add(' with tooltip: $tooltip');
2393
    }
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
    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) {
2405
        description.add(' with actions: ${_createEnumsSummary(expectedActions)} ');
2406 2407
      }
      if (notExpectedActions.isNotEmpty) {
2408
        description.add(' without actions: ${_createEnumsSummary(notExpectedActions)} ');
2409
      }
2410
    }
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
    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) {
2422
        description.add(' with flags: ${_createEnumsSummary(expectedFlags)} ');
2423 2424
      }
      if (notExpectedFlags.isNotEmpty) {
2425
        description.add(' without flags: ${_createEnumsSummary(notExpectedFlags)} ');
2426
      }
2427 2428
    }
    if (textDirection != null) {
2429
      description.add(' with textDirection: $textDirection ');
2430 2431
    }
    if (rect != null) {
2432
      description.add(' with rect: $rect');
2433 2434
    }
    if (size != null) {
2435
      description.add(' with size: $size');
2436 2437
    }
    if (elevation != null) {
2438
      description.add(' with elevation: $elevation');
2439 2440
    }
    if (thickness != null) {
2441
      description.add(' with thickness: $thickness');
2442 2443
    }
    if (platformViewId != null) {
2444
      description.add(' with platformViewId: $platformViewId');
2445 2446
    }
    if (maxValueLength != null) {
2447
      description.add(' with maxValueLength: $maxValueLength');
2448 2449
    }
    if (currentValueLength != null) {
2450
      description.add(' with currentValueLength: $currentValueLength');
2451 2452
    }
    if (customActions != null) {
2453
      description.add(' with custom actions: $customActions');
2454 2455
    }
    if (hintOverrides != null) {
2456
      description.add(' with custom hints: $hintOverrides');
2457
    }
2458 2459
    if (children != null) {
      description.add(' with children:\n');
2460
      for (final _MatchesSemanticsData child in children!.cast<_MatchesSemanticsData>()) {
2461
        child.describe(description);
2462
      }
2463
    }
2464 2465 2466
    return description;
  }

2467
  bool _stringAttributesEqual(List<StringAttribute> first, List<StringAttribute> second) {
2468
    if (first.length != second.length) {
2469
      return false;
2470
    }
2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
    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;
  }
2486 2487

  @override
2488
  bool matches(dynamic node, Map<dynamic, dynamic> matchState) {
2489
    if (node == null) {
2490
      return failWithDescription(matchState, 'No SemanticsData provided. '
2491
        'Maybe you forgot to enable semantics?');
2492
    }
2493
    final SemanticsData data = node is SemanticsNode ? node.getSemanticsData() : (node as SemanticsData);
2494
    if (label != null && label != data.label) {
2495
      return failWithDescription(matchState, 'label was: ${data.label}');
2496
    }
2497 2498 2499 2500 2501 2502
    if (attributedLabel != null &&
        (attributedLabel!.string != data.attributedLabel.string ||
         !_stringAttributesEqual(attributedLabel!.attributes, data.attributedLabel.attributes))) {
      return failWithDescription(
          matchState, 'attributedLabel was: ${data.attributedLabel}');
    }
2503
    if (hint != null && hint != data.hint) {
2504
      return failWithDescription(matchState, 'hint was: ${data.hint}');
2505
    }
2506 2507 2508 2509 2510 2511
    if (attributedHint != null &&
        (attributedHint!.string != data.attributedHint.string ||
         !_stringAttributesEqual(attributedHint!.attributes, data.attributedHint.attributes))) {
      return failWithDescription(
          matchState, 'attributedHint was: ${data.attributedHint}');
    }
2512
    if (value != null && value != data.value) {
2513
      return failWithDescription(matchState, 'value was: ${data.value}');
2514
    }
2515 2516 2517 2518 2519 2520
    if (attributedValue != null &&
        (attributedValue!.string != data.attributedValue.string ||
         !_stringAttributesEqual(attributedValue!.attributes, data.attributedValue.attributes))) {
      return failWithDescription(
          matchState, 'attributedValue was: ${data.attributedValue}');
    }
2521
    if (increasedValue != null && increasedValue != data.increasedValue) {
2522
      return failWithDescription(matchState, 'increasedValue was: ${data.increasedValue}');
2523
    }
2524 2525 2526 2527 2528 2529
    if (attributedIncreasedValue != null &&
        (attributedIncreasedValue!.string != data.attributedIncreasedValue.string ||
         !_stringAttributesEqual(attributedIncreasedValue!.attributes, data.attributedIncreasedValue.attributes))) {
      return failWithDescription(
          matchState, 'attributedIncreasedValue was: ${data.attributedIncreasedValue}');
    }
2530
    if (decreasedValue != null && decreasedValue != data.decreasedValue) {
2531
      return failWithDescription(matchState, 'decreasedValue was: ${data.decreasedValue}');
2532
    }
2533 2534 2535 2536 2537 2538
    if (attributedDecreasedValue != null &&
        (attributedDecreasedValue!.string != data.attributedDecreasedValue.string ||
         !_stringAttributesEqual(attributedDecreasedValue!.attributes, data.attributedDecreasedValue.attributes))) {
      return failWithDescription(
          matchState, 'attributedDecreasedValue was: ${data.attributedDecreasedValue}');
    }
2539
    if (tooltip != null && tooltip != data.tooltip) {
2540
      return failWithDescription(matchState, 'tooltip was: ${data.tooltip}');
2541 2542
    }
    if (textDirection != null && textDirection != data.textDirection) {
2543
      return failWithDescription(matchState, 'textDirection was: $textDirection');
2544 2545
    }
    if (rect != null && rect != data.rect) {
2546
      return failWithDescription(matchState, 'rect was: ${data.rect}');
2547 2548
    }
    if (size != null && size != data.rect.size) {
2549
      return failWithDescription(matchState, 'size was: ${data.rect.size}');
2550 2551
    }
    if (elevation != null && elevation != data.elevation) {
2552
      return failWithDescription(matchState, 'elevation was: ${data.elevation}');
2553 2554
    }
    if (thickness != null && thickness != data.thickness) {
2555
      return failWithDescription(matchState, 'thickness was: ${data.thickness}');
2556 2557
    }
    if (platformViewId != null && platformViewId != data.platformViewId) {
2558
      return failWithDescription(matchState, 'platformViewId was: ${data.platformViewId}');
2559 2560
    }
    if (currentValueLength != null && currentValueLength != data.currentValueLength) {
2561
      return failWithDescription(matchState, 'currentValueLength was: ${data.currentValueLength}');
2562 2563
    }
    if (maxValueLength != null && maxValueLength != data.maxValueLength) {
2564
      return failWithDescription(matchState, 'maxValueLength was: ${data.maxValueLength}');
2565
    }
2566
    if (actions.isNotEmpty) {
2567 2568
      final List<SemanticsAction> unexpectedActions = <SemanticsAction>[];
      final List<SemanticsAction> missingActions = <SemanticsAction>[];
2569 2570 2571 2572 2573
      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) {
2574
          if (actionExpected) {
2575 2576 2577 2578
            missingActions.add(action);
          } else {
            unexpectedActions.add(action);
          }
2579
        }
2580
      }
2581 2582 2583 2584

      if (unexpectedActions.isNotEmpty || missingActions.isNotEmpty) {
        return failWithDescription(matchState, 'missing actions: ${_createEnumsSummary(missingActions)} unexpected actions: ${_createEnumsSummary(unexpectedActions)}');
      }
2585
    }
2586
    if (customActions != null || hintOverrides != null) {
2587 2588 2589
      final List<CustomSemanticsAction> providedCustomActions = data.customSemanticsActionIds?.map<CustomSemanticsAction>((int id) {
        return CustomSemanticsAction.getAction(id)!;
      }).toList() ?? <CustomSemanticsAction>[];
2590
      final List<CustomSemanticsAction> expectedCustomActions = customActions?.toList() ?? <CustomSemanticsAction>[];
2591
      if (hintOverrides?.onTapHint != null) {
2592
        expectedCustomActions.add(CustomSemanticsAction.overridingAction(hint: hintOverrides!.onTapHint!, action: SemanticsAction.tap));
2593 2594
      }
      if (hintOverrides?.onLongPressHint != null) {
2595
        expectedCustomActions.add(CustomSemanticsAction.overridingAction(hint: hintOverrides!.onLongPressHint!, action: SemanticsAction.longPress));
2596 2597
      }
      if (expectedCustomActions.length != providedCustomActions.length) {
2598
        return failWithDescription(matchState, 'custom actions were: $providedCustomActions');
2599
      }
2600 2601 2602 2603 2604 2605
      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++) {
2606
        if (expectedCustomActions[i] != providedCustomActions[i]) {
2607
          return failWithDescription(matchState, 'custom actions were: $providedCustomActions');
2608
        }
2609 2610
      }
    }
2611
    if (flags.isNotEmpty) {
2612 2613
      final List<SemanticsFlag> unexpectedFlags = <SemanticsFlag>[];
      final List<SemanticsFlag> missingFlags = <SemanticsFlag>[];
2614 2615 2616 2617 2618
      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) {
2619
          if (flagExpected) {
2620 2621 2622 2623
            missingFlags.add(flag);
          } else {
            unexpectedFlags.add(flag);
          }
2624
        }
2625
      }
2626 2627 2628 2629

      if (unexpectedFlags.isNotEmpty || missingFlags.isNotEmpty) {
        return failWithDescription(matchState, 'missing flags: ${_createEnumsSummary(missingFlags)} unexpected flags: ${_createEnumsSummary(unexpectedFlags)}');
      }
2630
    }
2631 2632 2633
    bool allMatched = true;
    if (children != null) {
      int i = 0;
2634
      (node as SemanticsNode).visitChildren((SemanticsNode child) {
2635
        allMatched = children![i].matches(child, matchState) && allMatched;
2636 2637 2638 2639 2640
        i += 1;
        return allMatched;
      });
    }
    return allMatched;
2641 2642 2643 2644 2645 2646 2647 2648 2649
  }

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

  @override
  Description describeMismatch(
2650 2651 2652
    dynamic item,
    Description mismatchDescription,
    Map<dynamic, dynamic> matchState,
2653
    bool verbose,
2654
  ) {
2655
    return mismatchDescription.add(matchState['failure'] as String);
2656 2657 2658 2659
  }

  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.');
2660 2661 2662 2663 2664
    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(', ')}]';
    }
2665
  }
2666
}
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678

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

  final AccessibilityGuideline guideline;

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

  @override
2679
  Future<String?> matchAsync(covariant WidgetTester tester) async {
2680
    final Evaluation result = await guideline.evaluate(tester);
2681
    if (result.passed) {
2682
      return null;
2683
    }
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
    return result.reason;
  }
}

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

  final AccessibilityGuideline guideline;

  @override
  Description describe(Description description) {
2695
    return description.add('Does not ${guideline.description}');
2696 2697 2698
  }

  @override
2699
  Future<String?> matchAsync(covariant WidgetTester tester) async {
2700
    final Evaluation result = await guideline.evaluate(tester);
2701
    if (result.passed) {
2702
      return 'Failed';
2703
    }
2704 2705
    return null;
  }
2706
}