forked from flutter/flutter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matchers.dart
2738 lines (2512 loc) · 96.2 KB
/
matchers.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' show Card;
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:matcher/expect.dart';
import 'package:matcher/src/expect/async_matcher.dart'; // ignore: implementation_imports
import 'package:vector_math/vector_math_64.dart' show Matrix3;
import '_matchers_io.dart' if (dart.library.html) '_matchers_web.dart' show MatchesGoldenFile, captureImage;
import 'accessibility.dart';
import 'binding.dart';
import 'controller.dart';
import 'finders.dart';
import 'goldens.dart';
import 'widget_tester.dart' show WidgetTester;
/// Asserts that the [FinderBase] matches nothing in the available candidates.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsNothing);
/// ```
///
/// See also:
///
/// * [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);
/// Asserts that the [Finder] locates at least one widget in the widget tree.
///
/// This is equivalent to the preferred [findsAny] method.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsWidgets);
/// ```
///
/// 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 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);
/// Asserts that the [Finder] locates at exactly one widget in the widget tree.
///
/// This is equivalent to the preferred [findsOne] method.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsOneWidget);
/// ```
///
/// 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 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);
/// Asserts that the [Finder] locates the specified number of widgets in the widget tree.
///
/// This is equivalent to the preferred [findsExactly] method.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsNWidgets(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 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);
/// Asserts that the [Finder] locates at least a number of widgets in the widget tree.
///
/// This is equivalent to the preferred [findsAtLeast] method.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save'), findsAtLeastNWidgets(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 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);
/// Asserts that the [Finder] locates a single widget that has at
/// least one [Offstage] widget ancestor.
///
/// It's important to use a full finder, since by default finders exclude
/// offstage widgets.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Save', skipOffstage: false), isOffstage);
/// ```
///
/// See also:
///
/// * [isOnstage], the opposite.
const Matcher isOffstage = _IsOffstage();
/// Asserts that the [Finder] locates a single widget that has no
/// [Offstage] widget ancestors.
///
/// See also:
///
/// * [isOffstage], the opposite.
const Matcher isOnstage = _IsOnstage();
/// Asserts that the [Finder] locates a single widget that has at
/// least one [Card] widget ancestor.
///
/// See also:
///
/// * [isNotInCard], the opposite.
const Matcher isInCard = _IsInCard();
/// Asserts that the [Finder] locates a single widget that has no
/// [Card] widget ancestors.
///
/// This is equivalent to `isNot(isInCard)`.
///
/// See also:
///
/// * [isInCard], the opposite.
const Matcher isNotInCard = _IsNotInCard();
/// 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);
/// Asserts that an object's toString() is a plausible one-line description.
///
/// Specifically, this matcher checks that the string does not contains newline
/// characters, and does not have leading or trailing whitespace, is not
/// empty, and does not contain the default `Instance of ...` string.
const Matcher hasOneLineDescription = _HasOneLineDescription();
/// Asserts that an object's toStringDeep() is a plausible multiline
/// 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`.
const Matcher hasAGoodToStringDeep = _HasGoodToStringDeep();
/// A matcher for functions that throw [FlutterError].
///
/// This is equivalent to `throwsA(isA<FlutterError>())`.
///
/// If you are trying to test whether a call to [WidgetTester.pumpWidget]
/// results in a [FlutterError], see [TestWidgetsFlutterBinding.takeException].
///
/// See also:
///
/// * [throwsAssertionError], to test if a function throws any [AssertionError].
/// * [throwsArgumentError], to test if a functions throws an [ArgumentError].
/// * [isFlutterError], to test if any object is a [FlutterError].
final Matcher throwsFlutterError = throwsA(isFlutterError);
/// A matcher for functions that throw [AssertionError].
///
/// This is equivalent to `throwsA(isA<AssertionError>())`.
///
/// If you are trying to test whether a call to [WidgetTester.pumpWidget]
/// results in an [AssertionError], see
/// [TestWidgetsFlutterBinding.takeException].
///
/// See also:
///
/// * [throwsFlutterError], to test if a function throws a [FlutterError].
/// * [throwsArgumentError], to test if a functions throws an [ArgumentError].
/// * [isAssertionError], to test if any object is any kind of [AssertionError].
final Matcher throwsAssertionError = throwsA(isAssertionError);
/// A matcher for [FlutterError].
///
/// This is equivalent to `isInstanceOf<FlutterError>()`.
///
/// See also:
///
/// * [throwsFlutterError], to test if a function throws a [FlutterError].
/// * [isAssertionError], to test if any object is any kind of [AssertionError].
final TypeMatcher<FlutterError> isFlutterError = isA<FlutterError>();
/// A matcher for [AssertionError].
///
/// This is equivalent to `isInstanceOf<AssertionError>()`.
///
/// See also:
///
/// * [throwsAssertionError], to test if a function throws any [AssertionError].
/// * [isFlutterError], to test if any object is a [FlutterError].
final TypeMatcher<AssertionError> isAssertionError = isA<AssertionError>();
/// A matcher that compares the type of the actual value to the type argument T.
///
/// This is identical to [isA] and is included for backwards compatibility.
TypeMatcher<T> isInstanceOf<T>() => isA<T>();
/// Asserts that two [double]s are equal, within some tolerated error.
///
/// {@template flutter.flutter_test.moreOrLessEquals}
/// Two values are considered equal if the difference between them is within
/// [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.
/// {@endtemplate}
///
/// See also:
///
/// * [closeTo], which is identical except that the epsilon argument is
/// required and not named.
/// * [inInclusiveRange], which matches if the argument is in a specified
/// range.
/// * [rectMoreOrLessEquals] and [offsetMoreOrLessEquals], which do something
/// similar but for [Rect]s and [Offset]s respectively.
Matcher moreOrLessEquals(double value, { double epsilon = precisionErrorTolerance }) {
return _MoreOrLessEquals(value, epsilon);
}
/// Asserts that two [Rect]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.
/// * [within], which offers a generic version of this functionality that can
/// be used to match [Rect]s as well as other types.
Matcher rectMoreOrLessEquals(Rect value, { double epsilon = precisionErrorTolerance }) {
return _IsWithinDistance<Rect>(_rectDistance, value, epsilon);
}
/// 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.
/// * [matrix3MoreOrLessEquals], which is for [Matrix3]s.
Matcher matrixMoreOrLessEquals(Matrix4 value, { double epsilon = precisionErrorTolerance }) {
return _IsWithinDistance<Matrix4>(_matrixDistance, value, epsilon);
}
/// 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);
}
/// Asserts that two [Offset]s are equal, within some tolerated error.
///
/// {@macro flutter.flutter_test.moreOrLessEquals}
///
/// 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);
}
/// Asserts that two [String]s or `Iterable<String>`s are equal after
/// normalizing likely hash codes.
///
/// A `#` followed by 5 hexadecimal digits is assumed to be a short hash code
/// and is normalized to `#00000`.
///
/// Only [String] or `Iterable<String>` are allowed types for `value`.
///
/// See Also:
///
/// * [describeIdentity], a method that generates short descriptions of objects
/// with ids that match the pattern `#[0-9a-f]{5}`.
/// * [shortHash], a method that generates a 5 character long hexadecimal
/// [String] based on [Object.hashCode].
/// * [DiagnosticableTree.toStringDeep], a method that returns a [String]
/// typically containing multiple hash codes.
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}");
return _EqualsIgnoringHashCodes(value);
}
/// 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.
Matcher isMethodCall(String name, { required dynamic arguments }) {
return _IsMethodCall(name, arguments);
}
/// 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.
Matcher coversSameAreaAs(Path expectedPath, { required Rect areaToCompare, int sampleSize = 20 })
=> _CoversSameAreaAs(expectedPath, areaToCompare: areaToCompare, sampleSize: sampleSize);
// Examples can assume:
// late Image image;
// late Future<Image> imageFuture;
// typedef MyWidget = Placeholder;
// late Future<ByteData> someFont;
// late WidgetTester tester;
/// Asserts that a [Finder], [Future<ui.Image>], or [ui.Image] matches the
/// golden image file identified by [key], with an optional [version] number.
///
/// 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. As such, you may choose to wrap a test
/// widget in a [RepaintBoundary] to specify a particular focus for the test.
///
/// The [key] may be either a [Uri] or a [String] representation of a URL.
///
/// The [version] is a number that can be used to differentiate historical
/// golden files. This parameter is optional.
///
/// This is an asynchronous matcher, meaning that callers should use
/// [expectLater] when using this matcher and await the future returned by
/// [expectLater].
///
/// ## 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.
///
/// {@tool snippet}
/// Sample invocations of [matchesGoldenFile].
///
/// ```dart
/// await expectLater(
/// find.text('Save'),
/// matchesGoldenFile('save.png'),
/// );
///
/// await expectLater(
/// image,
/// matchesGoldenFile('save.png'),
/// );
///
/// await expectLater(
/// imageFuture,
/// matchesGoldenFile(
/// 'save.png',
/// version: 2,
/// ),
/// );
///
/// await expectLater(
/// find.byType(MyWidget),
/// matchesGoldenFile('goldens/myWidget.png'),
/// );
/// ```
/// {@end-tool}
///
/// {@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
/// testWidgets('Creating a golden image with a custom font', (WidgetTester tester) async {
/// // Assuming the 'Roboto.ttf' file is declared in the pubspec.yaml file
/// final Future<ByteData> font = rootBundle.load('path/to/font-file/Roboto.ttf');
///
/// final FontLoader fontLoader = FontLoader('Roboto')..addFont(font);
/// await fontLoader.load();
///
/// await tester.pumpWidget(const MyWidget());
///
/// await expectLater(
/// find.byType(MyWidget),
/// matchesGoldenFile('myWidget.png'),
/// );
/// });
/// ```
/// {@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 {
/// final FontLoader fontLoader = FontLoader('SomeFont')..addFont(someFont);
/// await fontLoader.load();
/// });
///
/// await testMain();
/// }
/// ```
/// {@end-tool}
/// {@endtemplate}
///
/// See also:
///
/// * [GoldenFileComparator], which acts as the backend for this matcher.
/// * [LocalFileComparator], which is the default [GoldenFileComparator]
/// implementation for `flutter test`.
/// * [matchesReferenceImage], which should be used instead if you want to
/// verify that two different code paths create identical images.
/// * [flutter_test] for a discussion of test configurations, whereby callers
/// may swap out the backend for this matcher.
AsyncMatcher matchesGoldenFile(Object key, {int? version}) {
if (key is Uri) {
return MatchesGoldenFile(key, version);
} else if (key is String) {
return MatchesGoldenFile.forStringPath(key, version);
}
throw ArgumentError('Unexpected type for golden file: ${key.runtimeType}');
}
/// 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
/// 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();
/// addTearDown(picture.dispose);
/// ui.Image referenceImage = await picture.toImage(50, 50);
/// addTearDown(referenceImage.dispose);
///
/// await expectLater(find.text('Save'), matchesReferenceImage(referenceImage));
/// await expectLater(image, matchesReferenceImage(referenceImage));
/// await expectLater(imageFuture, matchesReferenceImage(referenceImage));
/// });
/// ```
///
/// 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);
}
/// Asserts that a [SemanticsNode] contains the specified information.
///
/// If either the label, hint, value, textDirection, or rect fields are not
/// provided, then they are not part of the comparison. All of the boolean
/// flag and action fields must match, and default to false.
///
/// To find a [SemanticsNode] directly, use [CommonFinders.semantics].
/// These methods will search the semantics tree directly and avoid the edge
/// cases that [SemanticsController.find] sometimes runs into.
///
/// To retrieve the semantics data of a widget, use [SemanticsController.find]
/// with a [Finder] that returns a single widget. Semantics must be enabled
/// in order to use this method.
///
/// ## Sample code
///
/// ```dart
/// testWidgets('matchesSemantics', (WidgetTester tester) async {
/// final SemanticsHandle handle = tester.ensureSemantics();
/// // ...
/// expect(tester.getSemantics(find.text('hello')), matchesSemantics(label: 'hello'));
/// handle.dispose();
/// });
/// ```
///
/// See also:
///
/// * [SemanticsController.find] under [WidgetTester.semantics], the tester method which retrieves semantics.
/// * [containsSemantics], a similar matcher without default values for flags or actions.
Matcher matchesSemantics({
String? identifier,
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 = false,
bool isChecked = false,
bool isCheckStateMixed = false,
bool isSelected = false,
bool isButton = false,
bool isSlider = false,
bool isKeyboardKey = false,
bool isLink = false,
bool isFocused = false,
bool isFocusable = false,
bool isTextField = false,
bool isReadOnly = false,
bool hasEnabledState = false,
bool isEnabled = false,
bool isInMutuallyExclusiveGroup = false,
bool isHeader = false,
bool isObscured = false,
bool isMultiline = false,
bool namesRoute = false,
bool scopesRoute = false,
bool isHidden = false,
bool isImage = false,
bool isLiveRegion = false,
bool hasToggledState = false,
bool isToggled = false,
bool hasImplicitScrolling = false,
bool hasExpandedState = false,
bool isExpanded = false,
// 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,
bool hasMoveCursorForwardByWordAction = false,
bool hasMoveCursorBackwardByWordAction = false,
bool hasSetTextAction = false,
bool hasSetSelectionAction = false,
bool hasCopyAction = false,
bool hasCutAction = false,
bool hasPasteAction = false,
bool hasDidGainAccessibilityFocusAction = false,
bool hasDidLoseAccessibilityFocusAction = false,
bool hasDismissAction = false,
// Custom actions and overrides
String? onTapHint,
String? onLongPressHint,
List<CustomSemanticsAction>? customActions,
List<Matcher>? children,
}) {
return _MatchesSemanticsData(
identifier: identifier,
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,
maxValueLength: maxValueLength,
currentValueLength: currentValueLength,
// Flags
hasCheckedState: hasCheckedState,
isChecked: isChecked,
isCheckStateMixed: isCheckStateMixed,
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,
hasExpandedState: hasExpandedState,
isExpanded: isExpanded,
// 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 find a [SemanticsNode] directly, use [CommonFinders.semantics].
/// These methods will search the semantics tree directly and avoid the edge
/// cases that [SemanticsController.find] sometimes runs into.
///
/// To retrieve the semantics data of a widget, use [SemanticsController.find]
/// with a [Finder] that returns a single widget. Semantics must be enabled
/// in order to use this method.
///
/// ## Sample code
///
/// ```dart
/// testWidgets('containsSemantics', (WidgetTester tester) async {
/// final SemanticsHandle handle = tester.ensureSemantics();
/// // ...
/// expect(tester.getSemantics(find.text('hello')), containsSemantics(label: 'hello'));
/// handle.dispose();
/// });
/// ```
///
/// See also:
///
/// * [SemanticsController.find] under [WidgetTester.semantics], the tester method which retrieves semantics.
/// * [matchesSemantics], a similar matcher with default values for flags and actions.
Matcher containsSemantics({
String? identifier,
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,
bool? isCheckStateMixed,
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,
bool? hasExpandedState,
bool? isExpanded,
// 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(
identifier: identifier,
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,
maxValueLength: maxValueLength,
currentValueLength: currentValueLength,
// Flags
hasCheckedState: hasCheckedState,
isChecked: isChecked,
isCheckStateMixed: isCheckStateMixed,
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,
hasExpandedState: hasExpandedState,
isExpanded: isExpanded,
// 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 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
/// testWidgets('containsSemantics', (WidgetTester tester) async {
/// final SemanticsHandle handle = tester.ensureSemantics();
/// // ...
/// await expectLater(tester, meetsGuideline(textContrastGuideline));
/// handle.dispose();
/// });
/// ```
///
/// Supported accessibility guidelines:
///
/// * [androidTapTargetGuideline], for Android minimum tappable area guidelines.
/// * [iOSTapTargetGuideline], for iOS minimum tappable area guidelines.
/// * [textContrastGuideline], for WCAG minimum text contrast guidelines.
/// * [labeledTapTargetGuideline], for enforcing labels on tappable areas.
AsyncMatcher meetsGuideline(AccessibilityGuideline guideline) {
return _MatchesAccessibilityGuideline(guideline);
}
/// The inverse matcher of [meetsGuideline].
///
/// This is needed because the [isNot] matcher does not compose with an
/// [AsyncMatcher].