matchers_test.dart 49 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 6
// flutter_ignore_for_file: golden_tag (see analyze.dart)

7
import 'dart:math' as math;
8
import 'dart:typed_data';
9

10
import 'package:flutter/rendering.dart';
11
import 'package:flutter/widgets.dart';
12
import 'package:flutter_test/flutter_test.dart';
13
import 'package:vector_math/vector_math_64.dart' show Matrix3;
14

15 16
/// Class that makes it easy to mock common toStringDeep behavior.
class _MockToStringDeep {
17
  _MockToStringDeep(String str) : _lines = <String>[] {
18
    final List<String> lines = str.split('\n');
19
    for (int i = 0; i < lines.length - 1; ++i) {
20
      _lines.add('${lines[i]}\n');
21
    }
22 23 24 25 26 27 28 29 30 31 32 33 34

    // If the last line is empty, that really just means that the previous
    // line was terminated with a line break.
    if (lines.isNotEmpty && lines.last.isNotEmpty) {
      _lines.add(lines.last);
    }
  }

  _MockToStringDeep.fromLines(this._lines);

  /// Lines in the message to display when [toStringDeep] is called.
  /// For correct toStringDeep behavior, each line should be terminated with a
  /// line break.
35
  final List<String> _lines;
36

37
  String toStringDeep({ String prefixLineOne = '', String prefixOtherLines = '' }) {
38
    final StringBuffer sb = StringBuffer();
39
    if (_lines.isNotEmpty) {
40
      sb.write('$prefixLineOne${_lines.first}');
41
    }
42

43
    for (int i = 1; i < _lines.length; ++i) {
44
      sb.write('$prefixOtherLines${_lines[i]}');
45
    }
46 47 48 49 50 51 52 53

    return sb.toString();
  }

  @override
  String toString() => toStringDeep();
}

54
void main() {
55 56 57 58 59
  test('hasOneLineDescription', () {
    expect('Hello', hasOneLineDescription);
    expect('Hello\nHello', isNot(hasOneLineDescription));
    expect(' Hello', isNot(hasOneLineDescription));
    expect('Hello ', isNot(hasOneLineDescription));
60
    expect(Object(), isNot(hasOneLineDescription));
61 62
  });

63
  test('hasAGoodToStringDeep', () {
64
    expect(_MockToStringDeep('Hello\n World\n'), hasAGoodToStringDeep);
65
    // Not terminated with a line break.
66
    expect(_MockToStringDeep('Hello\n World'), isNot(hasAGoodToStringDeep));
67
    // Trailing whitespace on last line.
68
    expect(_MockToStringDeep('Hello\n World \n'),
69
        isNot(hasAGoodToStringDeep));
70
    expect(_MockToStringDeep('Hello\n World\t\n'),
71 72
        isNot(hasAGoodToStringDeep));
    // Leading whitespace on line 1.
73
    expect(_MockToStringDeep(' Hello\n World \n'),
74 75 76
        isNot(hasAGoodToStringDeep));

    // Single line.
77 78
    expect(_MockToStringDeep('Hello World'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('Hello World\n'), isNot(hasAGoodToStringDeep));
79

80
    expect(_MockToStringDeep('Hello: World\nFoo: bar\n'),
81
        hasAGoodToStringDeep);
82
    expect(_MockToStringDeep('Hello: World\nFoo: 42\n'),
83 84
        hasAGoodToStringDeep);
    // Contains default Object.toString().
85
    expect(_MockToStringDeep('Hello: World\nFoo: ${Object()}\n'),
86
        isNot(hasAGoodToStringDeep));
87 88
    expect(_MockToStringDeep('A\n├─B\n'), hasAGoodToStringDeep);
    expect(_MockToStringDeep('A\n├─B\n╘══════\n'), hasAGoodToStringDeep);
89
    // Last line is all whitespace or vertical line art.
90 91 92 93 94 95 96 97 98 99 100 101
    expect(_MockToStringDeep('A\n├─B\n\n'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('A\n├─B\n\n'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('A\n├─B\n\n'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('A\n├─B\n\n'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('A\n├─B\n\n'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('A\n├─B\n\n'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('A\n├─B\n\n'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('A\n├─B\n\n'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('A\n├─B\n\n'), isNot(hasAGoodToStringDeep));
    expect(_MockToStringDeep('A\n├─B\n ││\n'), isNot(hasAGoodToStringDeep));

    expect(_MockToStringDeep(
102 103 104 105 106
        'A\n'
        '├─B\n'
        '│\n'
        '└─C\n'), hasAGoodToStringDeep);
    // Last line is all whitespace or vertical line art.
107
    expect(_MockToStringDeep(
108 109 110 111
        'A\n'
        '├─B\n'
        '│\n'), isNot(hasAGoodToStringDeep));

112 113 114 115 116 117 118 119 120 121 122 123
    expect(
      _MockToStringDeep.fromLines(<String>[
        'Paragraph#00000\n',
        ' │ size: (400x200)\n',
        ' ╘═╦══ text ═══\n',
        '   ║ TextSpan:\n',
        '   ║   "I polished up that handle so carefullee\n',
        '   ║   That now I am the Ruler of the Queen\'s Navee!"\n',
        '   ╚═══════════\n',
      ]),
      hasAGoodToStringDeep,
    );
124 125

    // Text span
126 127 128 129 130 131 132 133 134 135 136
    expect(
      _MockToStringDeep.fromLines(<String>[
        'Paragraph#00000\n',
        ' │ size: (400x200)\n',
        ' ╘═╦══ text ═══\n',
        '   ║ TextSpan:\n',
        '   ║   "I polished up that handle so carefullee\nThat now I am the Ruler of the Queen\'s Navee!"\n',
        '   ╚═══════════\n',
      ]),
      isNot(hasAGoodToStringDeep),
    );
137 138
  });

139
  test('equalsIgnoringHashCodes', () {
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
    expect('Foo#34219', equalsIgnoringHashCodes('Foo#00000'));
    expect('Foo#34219', equalsIgnoringHashCodes('Foo#12345'));
    expect('Foo#34219', equalsIgnoringHashCodes('Foo#abcdf'));
    expect('Foo#34219', isNot(equalsIgnoringHashCodes('Foo')));
    expect('Foo#34219', isNot(equalsIgnoringHashCodes('Foo#')));
    expect('Foo#34219', isNot(equalsIgnoringHashCodes('Foo#0')));
    expect('Foo#34219', isNot(equalsIgnoringHashCodes('Foo#00')));
    expect('Foo#34219', isNot(equalsIgnoringHashCodes('Foo#00000 ')));
    expect('Foo#34219', isNot(equalsIgnoringHashCodes('Foo#000000')));
    expect('Foo#34219', isNot(equalsIgnoringHashCodes('Foo#123456')));

    expect('Foo#34219:', equalsIgnoringHashCodes('Foo#00000:'));
    expect('Foo#34219:', isNot(equalsIgnoringHashCodes('Foo#00000')));

    expect('Foo#a3b4d', equalsIgnoringHashCodes('Foo#00000'));
    expect('Foo#a3b4d', equalsIgnoringHashCodes('Foo#12345'));
    expect('Foo#a3b4d', equalsIgnoringHashCodes('Foo#abcdf'));
    expect('Foo#a3b4d', isNot(equalsIgnoringHashCodes('Foo')));
    expect('Foo#a3b4d', isNot(equalsIgnoringHashCodes('Foo#')));
    expect('Foo#a3b4d', isNot(equalsIgnoringHashCodes('Foo#0')));
    expect('Foo#a3b4d', isNot(equalsIgnoringHashCodes('Foo#00')));
    expect('Foo#a3b4d', isNot(equalsIgnoringHashCodes('Foo#00000 ')));
    expect('Foo#a3b4d', isNot(equalsIgnoringHashCodes('Foo#000000')));
    expect('Foo#a3b4d', isNot(equalsIgnoringHashCodes('Foo#123456')));

165 166
    expect('FOO#A3b4D', equalsIgnoringHashCodes('FOO#00000'));
    expect('FOO#A3b4J', isNot(equalsIgnoringHashCodes('FOO#00000')));
167 168 169 170 171 172 173 174 175 176

    expect('Foo#12345(Bar#9110f)',
        equalsIgnoringHashCodes('Foo#00000(Bar#00000)'));
    expect('Foo#12345(Bar#9110f)',
        isNot(equalsIgnoringHashCodes('Foo#00000(Bar#)')));

    expect('Foo', isNot(equalsIgnoringHashCodes('Foo#00000')));
    expect('Foo#', isNot(equalsIgnoringHashCodes('Foo#00000')));
    expect('Foo#3421', isNot(equalsIgnoringHashCodes('Foo#00000')));
    expect('Foo#342193', isNot(equalsIgnoringHashCodes('Foo#00000')));
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    expect(<String>['Foo#a3b4d'], equalsIgnoringHashCodes(<String>['Foo#12345']));
    expect(
      <String>['Foo#a3b4d', 'Foo#12345'],
      equalsIgnoringHashCodes(<String>['Foo#00000', 'Foo#00000']),
    );
    expect(
      <String>['Foo#a3b4d', 'Bar#12345'],
      equalsIgnoringHashCodes(<String>['Foo#00000', 'Bar#00000']),
    );
    expect(
      <String>['Foo#a3b4d', 'Bar#12345'],
      isNot(equalsIgnoringHashCodes(<String>['Bar#00000', 'Foo#00000'])),
    );
    expect(<String>['Foo#a3b4d'], isNot(equalsIgnoringHashCodes(<String>['Foo'])));
    expect(
      <String>['Foo#a3b4d'],
      isNot(equalsIgnoringHashCodes(<String>['Foo#00000', 'Bar#00000'])),
    );
195 196
  });

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  test('moreOrLessEquals', () {
    expect(0.0, moreOrLessEquals(1e-11));
    expect(1e-11, moreOrLessEquals(0.0));
    expect(-1e-11, moreOrLessEquals(0.0));

    expect(0.0, isNot(moreOrLessEquals(1e11)));
    expect(1e11, isNot(moreOrLessEquals(0.0)));
    expect(-1e11, isNot(moreOrLessEquals(0.0)));

    expect(0.0, isNot(moreOrLessEquals(1.0)));
    expect(1.0, isNot(moreOrLessEquals(0.0)));
    expect(-1.0, isNot(moreOrLessEquals(0.0)));

    expect(1e-11, moreOrLessEquals(-1e-11));
    expect(-1e-11, moreOrLessEquals(1e-11));

    expect(11.0, isNot(moreOrLessEquals(-11.0, epsilon: 1.0)));
    expect(-11.0, isNot(moreOrLessEquals(11.0, epsilon: 1.0)));

    expect(11.0, moreOrLessEquals(-11.0, epsilon: 100.0));
    expect(-11.0, moreOrLessEquals(11.0, epsilon: 100.0));
218 219 220

    expect(0, moreOrLessEquals(0.0));
    expect(0.0, moreOrLessEquals(0));
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
  test('matrixMoreOrLessEquals', () {
    expect(
      Matrix4.rotationZ(math.pi),
      matrixMoreOrLessEquals(Matrix4.fromList(<double>[
       -1,  0, 0, 0,
        0, -1, 0, 0,
        0,  0, 1, 0,
        0,  0, 0, 1,
      ]))
    );

    expect(
      Matrix4.rotationZ(math.pi),
      matrixMoreOrLessEquals(Matrix4.fromList(<double>[
       -2,  0, 0, 0,
        0, -2, 0, 0,
        0,  0, 1, 0,
        0,  0, 0, 1,
      ]), epsilon: 2)
    );

    expect(
      Matrix4.rotationZ(math.pi),
      isNot(matrixMoreOrLessEquals(Matrix4.fromList(<double>[
       -2,  0, 0, 0,
        0, -2, 0, 0,
        0,  0, 1, 0,
        0,  0, 0, 1,
      ])))
    );
  });

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
  test('matrix3MoreOrLessEquals', () {
    expect(
      Matrix3.rotationZ(math.pi),
      matrix3MoreOrLessEquals(Matrix3.fromList(<double>[
       -1,  0, 0,
        0, -1, 0,
        0,  0, 1,
      ]))
    );

    expect(
      Matrix3.rotationZ(math.pi),
      matrix3MoreOrLessEquals(Matrix3.fromList(<double>[
       -2,  0, 0,
        0, -2, 0,
        0,  0, 1,
      ]), epsilon: 2)
    );

    expect(
      Matrix3.rotationZ(math.pi),
      isNot(matrix3MoreOrLessEquals(Matrix3.fromList(<double>[
       -2,  0, 0,
        0, -2, 0,
        0,  0, 1,
      ])))
    );
  });

284 285
  test('rectMoreOrLessEquals', () {
    expect(
Dan Field's avatar
Dan Field committed
286 287
      const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
      rectMoreOrLessEquals(const Rect.fromLTRB(0.0, 0.0, 10.0, 10.00000000001)),
288 289 290
    );

    expect(
Dan Field's avatar
Dan Field committed
291 292
      const Rect.fromLTRB(11.0, 11.0, 20.0, 20.0),
      isNot(rectMoreOrLessEquals(const Rect.fromLTRB(-11.0, -11.0, 20.0, 20.0), epsilon: 1.0)),
293 294 295
    );

    expect(
Dan Field's avatar
Dan Field committed
296 297
      const Rect.fromLTRB(11.0, 11.0, 20.0, 20.0),
      rectMoreOrLessEquals(const Rect.fromLTRB(-11.0, -11.0, 20.0, 20.0), epsilon: 100.0),
298 299 300
    );
  });

301 302 303 304 305 306 307 308 309 310 311 312 313 314
  test('within', () {
    expect(0.0, within<double>(distance: 0.1, from: 0.05));
    expect(0.0, isNot(within<double>(distance: 0.1, from: 0.2)));

    expect(0, within<int>(distance: 1, from: 1));
    expect(0, isNot(within<int>(distance: 1, from: 2)));

    expect(const Color(0x00000000), within<Color>(distance: 1, from: const Color(0x01000000)));
    expect(const Color(0x00000000), within<Color>(distance: 1, from: const Color(0x00010000)));
    expect(const Color(0x00000000), within<Color>(distance: 1, from: const Color(0x00000100)));
    expect(const Color(0x00000000), within<Color>(distance: 1, from: const Color(0x00000001)));
    expect(const Color(0x00000000), within<Color>(distance: 1, from: const Color(0x01010101)));
    expect(const Color(0x00000000), isNot(within<Color>(distance: 1, from: const Color(0x02000000))));

315
    expect(const Offset(1.0, 0.0), within(distance: 1.0, from: Offset.zero));
316 317
    expect(const Offset(1.0, 0.0), isNot(within(distance: 1.0, from: const Offset(-1.0, 0.0))));

Dan Field's avatar
Dan Field committed
318 319
    expect(const Rect.fromLTRB(0.0, 1.0, 2.0, 3.0), within<Rect>(distance: 4.0, from: const Rect.fromLTRB(1.0, 3.0, 5.0, 7.0)));
    expect(const Rect.fromLTRB(0.0, 1.0, 2.0, 3.0), isNot(within<Rect>(distance: 3.9, from: const Rect.fromLTRB(1.0, 3.0, 5.0, 7.0))));
320 321 322 323

    expect(const Size(1.0, 1.0), within<Size>(distance: 1.415, from: const Size(2.0, 2.0)));
    expect(const Size(1.0, 1.0), isNot(within<Size>(distance: 1.414, from: const Size(2.0, 2.0))));

324 325 326 327 328 329 330 331 332 333
    expect(
      () => within<bool>(distance: 1, from: false),
      throwsArgumentError,
    );

    expect(
      () => within<int>(distance: 1, from: 2, distanceFunction: (int a, int b) => -1).matches(1, <dynamic, dynamic>{}),
      throwsArgumentError,
    );
  });
334

335 336 337
  test('isSameColorAs', () {
    expect(
      const Color(0x87654321),
338
      isSameColorAs(const _CustomColor(0x87654321)),
339 340 341
    );

    expect(
342
      const _CustomColor(0x87654321),
343 344 345 346 347
      isSameColorAs(const Color(0x87654321)),
    );

    expect(
      const Color(0x12345678),
348
      isNot(isSameColorAs(const _CustomColor(0x87654321))),
349 350 351
    );

    expect(
352
      const _CustomColor(0x87654321),
353 354 355 356
      isNot(isSameColorAs(const Color(0x12345678))),
    );

    expect(
357 358
      const _CustomColor(0xFF123456),
      isSameColorAs(const _CustomColor(0xFF123456, isEqual: false)),
359 360 361
    );
  });

362 363 364
  group('coversSameAreaAs', () {
    test('empty Paths', () {
      expect(
365
        Path(),
366
        coversSameAreaAs(
367
          Path(),
Dan Field's avatar
Dan Field committed
368
          areaToCompare: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
369 370 371 372 373
        ),
      );
    });

    test('mismatch', () {
374
      final Path rectPath = Path()
Dan Field's avatar
Dan Field committed
375
        ..addRect(const Rect.fromLTRB(5.0, 5.0, 6.0, 6.0));
376
      expect(
377
        Path(),
378 379
        isNot(coversSameAreaAs(
          rectPath,
Dan Field's avatar
Dan Field committed
380
          areaToCompare: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
381 382 383 384 385
        )),
      );
    });

    test('mismatch out of examined area', () {
386
      final Path rectPath = Path()
Dan Field's avatar
Dan Field committed
387 388
        ..addRect(const Rect.fromLTRB(5.0, 5.0, 6.0, 6.0));
      rectPath.addRect(const Rect.fromLTRB(5.0, 5.0, 6.0, 6.0));
389
      expect(
390
        Path(),
391 392
        coversSameAreaAs(
          rectPath,
Dan Field's avatar
Dan Field committed
393
          areaToCompare: const Rect.fromLTRB(0.0, 0.0, 4.0, 4.0),
394 395 396 397 398
        ),
      );
    });

    test('differently constructed rects match', () {
399
      final Path rectPath = Path()
Dan Field's avatar
Dan Field committed
400
        ..addRect(const Rect.fromLTRB(5.0, 5.0, 6.0, 6.0));
401
      final Path linePath = Path()
402 403 404 405 406 407 408 409 410
        ..moveTo(5.0, 5.0)
        ..lineTo(5.0, 6.0)
        ..lineTo(6.0, 6.0)
        ..lineTo(6.0, 5.0)
        ..close();
      expect(
        linePath,
        coversSameAreaAs(
          rectPath,
Dan Field's avatar
Dan Field committed
411
          areaToCompare: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
412 413 414 415
        ),
      );
    });

416
    test('partially overlapping paths', () {
417
      final Path rectPath = Path()
Dan Field's avatar
Dan Field committed
418
        ..addRect(const Rect.fromLTRB(5.0, 5.0, 6.0, 6.0));
419
      final Path linePath = Path()
420 421 422 423 424 425 426 427 428
        ..moveTo(5.0, 5.0)
        ..lineTo(5.0, 6.0)
        ..lineTo(6.0, 6.0)
        ..lineTo(6.0, 5.5)
        ..close();
      expect(
        linePath,
        isNot(coversSameAreaAs(
          rectPath,
Dan Field's avatar
Dan Field committed
429
          areaToCompare: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
430 431 432 433
        )),
      );
    });
  });
434 435

  group('matchesGoldenFile', () {
436
    late _FakeComparator comparator;
437 438

    Widget boilerplate(Widget child) {
439
      return Directionality(
440 441 442 443 444 445
        textDirection: TextDirection.ltr,
        child: child,
      );
    }

    setUp(() {
446
      comparator = _FakeComparator();
447 448 449 450 451 452 453 454 455 456 457 458
      goldenFileComparator = comparator;
    });

    group('matches', () {
      testWidgets('if comparator succeeds', (WidgetTester tester) async {
        await tester.pumpWidget(boilerplate(const Text('hello')));
        final Finder finder = find.byType(Text);
        await expectLater(finder, matchesGoldenFile('foo.png'));
        expect(comparator.invocation, _ComparatorInvocation.compare);
        expect(comparator.imageBytes, hasLength(greaterThan(0)));
        expect(comparator.golden, Uri.parse('foo.png'));
      });
459 460 461 462 463 464 465 466 467 468 469 470 471 472

      testWidgets('list of integers', (WidgetTester tester) async {
        await expectLater(<int>[1, 2], matchesGoldenFile('foo.png'));
        expect(comparator.invocation, _ComparatorInvocation.compare);
        expect(comparator.imageBytes, equals(<int>[1, 2]));
        expect(comparator.golden, Uri.parse('foo.png'));
      });

      testWidgets('future list of integers', (WidgetTester tester) async {
        await expectLater(Future<List<int>>.value(<int>[1, 2]), matchesGoldenFile('foo.png'));
        expect(comparator.invocation, _ComparatorInvocation.compare);
        expect(comparator.imageBytes, equals(<int>[1, 2]));
        expect(comparator.golden, Uri.parse('foo.png'));
      });
473 474 475 476 477 478 479 480

      testWidgets('future nullable list of integers',
          (WidgetTester tester) async {
        await expectLater(Future<List<int>?>.value(<int>[1, 2]), matchesGoldenFile('foo.png'));
        expect(comparator.invocation, _ComparatorInvocation.compare);
        expect(comparator.imageBytes, equals(<int>[1, 2]));
        expect(comparator.golden, Uri.parse('foo.png'));
      });
481 482 483 484 485 486 487
    });

    group('does not match', () {
      testWidgets('if comparator returns false', (WidgetTester tester) async {
        comparator.behavior = _ComparatorBehavior.returnFalse;
        await tester.pumpWidget(boilerplate(const Text('hello')));
        final Finder finder = find.byType(Text);
488 489 490 491 492 493 494 495 496
        await expectLater(
          () => expectLater(finder, matchesGoldenFile('foo.png')),
          throwsA(isA<TestFailure>().having(
            (TestFailure error) => error.message,
            'message',
            contains('does not match'),
          )),
        );
        expect(comparator.invocation, _ComparatorInvocation.compare);
497 498 499 500 501 502
      });

      testWidgets('if comparator throws', (WidgetTester tester) async {
        comparator.behavior = _ComparatorBehavior.throwTestFailure;
        await tester.pumpWidget(boilerplate(const Text('hello')));
        final Finder finder = find.byType(Text);
503 504 505 506 507 508 509 510 511
        await expectLater(
          () => expectLater(finder, matchesGoldenFile('foo.png')),
          throwsA(isA<TestFailure>().having(
            (TestFailure error) => error.message,
            'message',
            contains('fake message'),
          )),
        );
        expect(comparator.invocation, _ComparatorInvocation.compare);
512 513 514
      });

      testWidgets('if finder finds no widgets', (WidgetTester tester) async {
515
        await tester.pumpWidget(boilerplate(Container()));
516
        final Finder finder = find.byType(Text);
517 518 519 520 521 522 523 524 525
        await expectLater(
          () => expectLater(finder, matchesGoldenFile('foo.png')),
          throwsA(isA<TestFailure>().having(
            (TestFailure error) => error.message,
            'message',
            contains('no widget was found'),
          )),
        );
        expect(comparator.invocation, isNull);
526 527 528
      });

      testWidgets('if finder finds multiple widgets', (WidgetTester tester) async {
529 530
        await tester.pumpWidget(boilerplate(const Column(
          children: <Widget>[Text('hello'), Text('world')],
531 532
        )));
        final Finder finder = find.byType(Text);
533 534 535 536 537 538 539 540 541
        await expectLater(
          () => expectLater(finder, matchesGoldenFile('foo.png')),
          throwsA(isA<TestFailure>().having(
            (TestFailure error) => error.message,
            'message',
            contains('too many widgets'),
          )),
        );
        expect(comparator.invocation, isNull);
542 543 544 545 546 547 548 549 550 551 552
      });
    });

    testWidgets('calls update on comparator if autoUpdateGoldenFiles is true', (WidgetTester tester) async {
      autoUpdateGoldenFiles = true;
      await tester.pumpWidget(boilerplate(const Text('hello')));
      final Finder finder = find.byType(Text);
      await expectLater(finder, matchesGoldenFile('foo.png'));
      expect(comparator.invocation, _ComparatorInvocation.update);
      expect(comparator.imageBytes, hasLength(greaterThan(0)));
      expect(comparator.golden, Uri.parse('foo.png'));
553
      autoUpdateGoldenFiles = false;
554 555
    });
  });
556 557 558 559

  group('matchesSemanticsData', () {
    testWidgets('matches SemanticsData', (WidgetTester tester) async {
      final SemanticsHandle handle = tester.ensureSemantics();
560
      const Key key = Key('semantics');
561
      await tester.pumpWidget(Semantics(
562 563 564 565
        key: key,
        namesRoute: true,
        header: true,
        button: true,
566
        link: true,
567 568
        onTap: () { },
        onLongPress: () { },
569 570 571
        label: 'foo',
        hint: 'bar',
        value: 'baz',
572 573
        increasedValue: 'a',
        decreasedValue: 'b',
574
        textDirection: TextDirection.rtl,
575 576 577
        onTapHint: 'scan',
        onLongPressHint: 'fill',
        customSemanticsActions: <CustomSemanticsAction, VoidCallback>{
578 579
          const CustomSemanticsAction(label: 'foo'): () { },
          const CustomSemanticsAction(label: 'bar'): () { },
580
        },
581 582
      ));

583 584
      expect(tester.getSemantics(find.byKey(key)),
        matchesSemantics(
585 586 587
          label: 'foo',
          hint: 'bar',
          value: 'baz',
588 589
          increasedValue: 'a',
          decreasedValue: 'b',
590 591
          textDirection: TextDirection.rtl,
          hasTapAction: true,
592
          hasLongPressAction: true,
593
          isButton: true,
594
          isLink: true,
595 596
          isHeader: true,
          namesRoute: true,
597 598 599 600
          onTapHint: 'scan',
          onLongPressHint: 'fill',
          customActions: <CustomSemanticsAction>[
            const CustomSemanticsAction(label: 'foo'),
601
            const CustomSemanticsAction(label: 'bar'),
602
          ],
603 604
        ),
      );
605 606

      // Doesn't match custom actions
607 608
      expect(tester.getSemantics(find.byKey(key)),
        isNot(matchesSemantics(
609 610 611 612 613 614 615
          label: 'foo',
          hint: 'bar',
          value: 'baz',
          textDirection: TextDirection.rtl,
          hasTapAction: true,
          hasLongPressAction: true,
          isButton: true,
616
          isLink: true,
617 618 619 620 621 622
          isHeader: true,
          namesRoute: true,
          onTapHint: 'scan',
          onLongPressHint: 'fill',
          customActions: <CustomSemanticsAction>[
            const CustomSemanticsAction(label: 'foo'),
623
            const CustomSemanticsAction(label: 'barz'),
624 625 626 627 628
          ],
        )),
      );

      // Doesn't match wrong hints
629 630
      expect(tester.getSemantics(find.byKey(key)),
        isNot(matchesSemantics(
631 632 633 634 635 636 637
          label: 'foo',
          hint: 'bar',
          value: 'baz',
          textDirection: TextDirection.rtl,
          hasTapAction: true,
          hasLongPressAction: true,
          isButton: true,
638
          isLink: true,
639 640 641 642 643 644
          isHeader: true,
          namesRoute: true,
          onTapHint: 'scans',
          onLongPressHint: 'fills',
          customActions: <CustomSemanticsAction>[
            const CustomSemanticsAction(label: 'foo'),
645
            const CustomSemanticsAction(label: 'bar'),
646 647 648 649
          ],
        )),
      );

650 651 652 653 654 655
      handle.dispose();
    });

    testWidgets('Can match all semantics flags and actions', (WidgetTester tester) async {
      int actions = 0;
      int flags = 0;
Jonah Williams's avatar
Jonah Williams committed
656
      const CustomSemanticsAction action = CustomSemanticsAction(label: 'test');
657 658
      for (final SemanticsAction action in SemanticsAction.values) {
        actions |= action.index;
659
      }
660 661
      for (final SemanticsFlag flag in SemanticsFlag.values) {
        flags |= flag.index;
662
      }
663
      final SemanticsData data = SemanticsData(
664 665
        flags: flags,
        actions: actions,
666 667 668 669 670
        attributedLabel: AttributedString('a'),
        attributedIncreasedValue: AttributedString('b'),
        attributedValue: AttributedString('c'),
        attributedDecreasedValue: AttributedString('d'),
        attributedHint: AttributedString('e'),
671
        tooltip: 'f',
672
        textDirection: TextDirection.ltr,
Dan Field's avatar
Dan Field committed
673
        rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
674 675
        elevation: 3.0,
        thickness: 4.0,
676
        textSelection: null,
677 678
        scrollIndex: null,
        scrollChildCount: null,
679 680 681
        scrollPosition: null,
        scrollExtentMax: null,
        scrollExtentMin: null,
682
        platformViewId: 105,
683
        customSemanticsActionIds: <int>[CustomSemanticsAction.getIdentifier(action)],
684 685
        currentValueLength: 10,
        maxValueLength: 15,
686
      );
687
      final _FakeSemanticsNode node = _FakeSemanticsNode(data);
688

689
      expect(node, matchesSemantics(
Dan Field's avatar
Dan Field committed
690
         rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
691
         size: const Size(10.0, 10.0),
692 693
         elevation: 3.0,
         thickness: 4.0,
694
         platformViewId: 105,
695 696
         currentValueLength: 10,
         maxValueLength: 15,
697 698 699
         /* Flags */
         hasCheckedState: true,
         isChecked: true,
700
         isCheckStateMixed: true,
701 702
         isSelected: true,
         isButton: true,
703
         isSlider: true,
704
         isKeyboardKey: true,
705
         isLink: true,
706
         isTextField: true,
707
         isReadOnly: true,
708 709
         hasEnabledState: true,
         isFocused: true,
710
         isFocusable: true,
711 712 713 714
         isEnabled: true,
         isInMutuallyExclusiveGroup: true,
         isHeader: true,
         isObscured: true,
715
         isMultiline: true,
716 717 718
         namesRoute: true,
         scopesRoute: true,
         isHidden: true,
719 720 721 722
         isImage: true,
         isLiveRegion: true,
         hasToggledState: true,
         isToggled: true,
723
         hasImplicitScrolling: true,
724 725
         hasExpandedState: true,
         isExpanded: true,
726 727 728 729 730 731 732 733 734 735 736 737
         /* Actions */
         hasTapAction: true,
         hasLongPressAction: true,
         hasScrollLeftAction: true,
         hasScrollRightAction: true,
         hasScrollUpAction: true,
         hasScrollDownAction: true,
         hasIncreaseAction: true,
         hasDecreaseAction: true,
         hasShowOnScreenAction: true,
         hasMoveCursorForwardByCharacterAction: true,
         hasMoveCursorBackwardByCharacterAction: true,
738 739
         hasMoveCursorForwardByWordAction: true,
         hasMoveCursorBackwardByWordAction: true,
740
         hasSetTextAction: true,
741 742 743 744 745 746
         hasSetSelectionAction: true,
         hasCopyAction: true,
         hasCutAction: true,
         hasPasteAction: true,
         hasDidGainAccessibilityFocusAction: true,
         hasDidLoseAccessibilityFocusAction: true,
747
         hasDismissAction: true,
748
         customActions: <CustomSemanticsAction>[action],
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

    testWidgets('Can match child semantics', (WidgetTester tester) async {
      final SemanticsHandle handle = tester.ensureSemantics();
      const Key key = Key('a');
      await tester.pumpWidget(Semantics(
        key: key,
        label: 'Foo',
        container: true,
        explicitChildNodes: true,
        textDirection: TextDirection.ltr,
        child: Semantics(
          label: 'Bar',
          textDirection: TextDirection.ltr,
        ),
      ));
      final SemanticsNode node = tester.getSemantics(find.byKey(key));

      expect(node, matchesSemantics(
        label: 'Foo',
        textDirection: TextDirection.ltr,
        children: <Matcher>[
          matchesSemantics(
            label: 'Bar',
            textDirection: TextDirection.ltr,
          ),
        ],
      ));
      handle.dispose();
    });
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

    testWidgets('failure does not throw unexpected errors', (WidgetTester tester) async {
      final SemanticsHandle handle = tester.ensureSemantics();

      const Key key = Key('semantics');
      await tester.pumpWidget(Semantics(
        key: key,
        namesRoute: true,
        header: true,
        button: true,
        link: true,
        onTap: () { },
        onLongPress: () { },
        label: 'foo',
        hint: 'bar',
        value: 'baz',
        increasedValue: 'a',
        decreasedValue: 'b',
        textDirection: TextDirection.rtl,
        onTapHint: 'scan',
        onLongPressHint: 'fill',
        customSemanticsActions: <CustomSemanticsAction, VoidCallback>{
          const CustomSemanticsAction(label: 'foo'): () { },
          const CustomSemanticsAction(label: 'bar'): () { },
        },
      ));

      // This should fail due to the mis-match between the `namesRoute` value.
      void failedExpectation() => expect(tester.getSemantics(find.byKey(key)),
        matchesSemantics(
          // Adding the explicit `false` for test readability
          // ignore: avoid_redundant_argument_values
          namesRoute: false,
          label: 'foo',
          hint: 'bar',
          value: 'baz',
          increasedValue: 'a',
          decreasedValue: 'b',
          textDirection: TextDirection.rtl,
          hasTapAction: true,
          hasLongPressAction: true,
          isButton: true,
          isLink: true,
          isHeader: true,
          onTapHint: 'scan',
          onLongPressHint: 'fill',
          customActions: <CustomSemanticsAction>[
            const CustomSemanticsAction(label: 'foo'),
            const CustomSemanticsAction(label: 'bar'),
          ],
        ),
      );

      expect(failedExpectation, throwsA(isA<TestFailure>()));
834
      handle.dispose();
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
  group('containsSemantics', () {
    testWidgets('matches SemanticsData', (WidgetTester tester) async {
      final SemanticsHandle handle = tester.ensureSemantics();

      const Key key = Key('semantics');
      await tester.pumpWidget(Semantics(
        key: key,
        namesRoute: true,
        header: true,
        button: true,
        link: true,
        onTap: () { },
        onLongPress: () { },
        label: 'foo',
        hint: 'bar',
        value: 'baz',
        increasedValue: 'a',
        decreasedValue: 'b',
        textDirection: TextDirection.rtl,
        onTapHint: 'scan',
        onLongPressHint: 'fill',
        customSemanticsActions: <CustomSemanticsAction, VoidCallback>{
          const CustomSemanticsAction(label: 'foo'): () { },
          const CustomSemanticsAction(label: 'bar'): () { },
        },
      ));

      expect(
        tester.getSemantics(find.byKey(key)),
        containsSemantics(
          label: 'foo',
          hint: 'bar',
          value: 'baz',
          increasedValue: 'a',
          decreasedValue: 'b',
          textDirection: TextDirection.rtl,
          hasTapAction: true,
          hasLongPressAction: true,
          isButton: true,
          isLink: true,
          isHeader: true,
          namesRoute: true,
          onTapHint: 'scan',
          onLongPressHint: 'fill',
          customActions: <CustomSemanticsAction>[
            const CustomSemanticsAction(label: 'foo'),
            const CustomSemanticsAction(label: 'bar'),
          ],
        ),
      );

      expect(
        tester.getSemantics(find.byKey(key)),
        isNot(containsSemantics(
          label: 'foo',
          hint: 'bar',
          value: 'baz',
          textDirection: TextDirection.rtl,
          hasTapAction: true,
          hasLongPressAction: true,
          isButton: true,
          isLink: true,
          isHeader: true,
          namesRoute: true,
          onTapHint: 'scan',
          onLongPressHint: 'fill',
          customActions: <CustomSemanticsAction>[
            const CustomSemanticsAction(label: 'foo'),
            const CustomSemanticsAction(label: 'barz'),
          ],
        )),
        reason: 'CustomSemanticsAction "barz" should not have matched "bar".'
      );

      expect(
        tester.getSemantics(find.byKey(key)),
        isNot(matchesSemantics(
          label: 'foo',
          hint: 'bar',
          value: 'baz',
          textDirection: TextDirection.rtl,
          hasTapAction: true,
          hasLongPressAction: true,
          isButton: true,
          isLink: true,
          isHeader: true,
          namesRoute: true,
          onTapHint: 'scans',
          onLongPressHint: 'fills',
          customActions: <CustomSemanticsAction>[
            const CustomSemanticsAction(label: 'foo'),
            const CustomSemanticsAction(label: 'bar'),
          ],
        )),
        reason: 'onTapHint "scans" should not have matched "scan".',
      );
934
      handle.dispose();
935 936 937 938 939 940
    });

    testWidgets('can match all semantics flags and actions enabled', (WidgetTester tester) async {
      int actions = 0;
      int flags = 0;
      const CustomSemanticsAction action = CustomSemanticsAction(label: 'test');
941 942
      for (final SemanticsAction action in SemanticsAction.values) {
        actions |= action.index;
943
      }
944 945
      for (final SemanticsFlag flag in SemanticsFlag.values) {
        flags |= flag.index;
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 1001 1002 1003 1004 1005 1006 1007 1008
      }
      final SemanticsData data = SemanticsData(
        flags: flags,
        actions: actions,
        attributedLabel: AttributedString('a'),
        attributedIncreasedValue: AttributedString('b'),
        attributedValue: AttributedString('c'),
        attributedDecreasedValue: AttributedString('d'),
        attributedHint: AttributedString('e'),
        tooltip: 'f',
        textDirection: TextDirection.ltr,
        rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
        elevation: 3.0,
        thickness: 4.0,
        textSelection: null,
        scrollIndex: null,
        scrollChildCount: null,
        scrollPosition: null,
        scrollExtentMax: null,
        scrollExtentMin: null,
        platformViewId: 105,
        customSemanticsActionIds: <int>[CustomSemanticsAction.getIdentifier(action)],
        currentValueLength: 10,
        maxValueLength: 15,
      );
      final _FakeSemanticsNode node = _FakeSemanticsNode(data);

      expect(
        node,
        containsSemantics(
          rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
          size: const Size(10.0, 10.0),
          elevation: 3.0,
          thickness: 4.0,
          platformViewId: 105,
          currentValueLength: 10,
          maxValueLength: 15,
          /* Flags */
          hasCheckedState: true,
          isChecked: true,
          isSelected: true,
          isButton: true,
          isSlider: true,
          isKeyboardKey: true,
          isLink: true,
          isTextField: true,
          isReadOnly: true,
          hasEnabledState: true,
          isFocused: true,
          isFocusable: true,
          isEnabled: true,
          isInMutuallyExclusiveGroup: true,
          isHeader: true,
          isObscured: true,
          isMultiline: true,
          namesRoute: true,
          scopesRoute: true,
          isHidden: true,
          isImage: true,
          isLiveRegion: true,
          hasToggledState: true,
          isToggled: true,
          hasImplicitScrolling: true,
1009 1010
          hasExpandedState: true,
          isExpanded: true,
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
          /* Actions */
          hasTapAction: true,
          hasLongPressAction: true,
          hasScrollLeftAction: true,
          hasScrollRightAction: true,
          hasScrollUpAction: true,
          hasScrollDownAction: true,
          hasIncreaseAction: true,
          hasDecreaseAction: true,
          hasShowOnScreenAction: true,
          hasMoveCursorForwardByCharacterAction: true,
          hasMoveCursorBackwardByCharacterAction: true,
          hasMoveCursorForwardByWordAction: true,
          hasMoveCursorBackwardByWordAction: true,
          hasSetTextAction: true,
          hasSetSelectionAction: true,
          hasCopyAction: true,
          hasCutAction: true,
          hasPasteAction: true,
          hasDidGainAccessibilityFocusAction: true,
          hasDidLoseAccessibilityFocusAction: true,
          hasDismissAction: true,
          customActions: <CustomSemanticsAction>[action],
        ),
      );
    });

    testWidgets('can match all flags and actions disabled', (WidgetTester tester) async {
      final SemanticsData data = SemanticsData(
        flags: 0,
        actions: 0,
        attributedLabel: AttributedString('a'),
        attributedIncreasedValue: AttributedString('b'),
        attributedValue: AttributedString('c'),
        attributedDecreasedValue: AttributedString('d'),
        attributedHint: AttributedString('e'),
        tooltip: 'f',
        textDirection: TextDirection.ltr,
        rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
        elevation: 3.0,
        thickness: 4.0,
        textSelection: null,
        scrollIndex: null,
        scrollChildCount: null,
        scrollPosition: null,
        scrollExtentMax: null,
        scrollExtentMin: null,
        platformViewId: 105,
        currentValueLength: 10,
        maxValueLength: 15,
      );
      final _FakeSemanticsNode node = _FakeSemanticsNode(data);

      expect(
        node,
        containsSemantics(
          rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
          size: const Size(10.0, 10.0),
          elevation: 3.0,
          thickness: 4.0,
          platformViewId: 105,
          currentValueLength: 10,
          maxValueLength: 15,
          /* Flags */
          hasCheckedState: false,
          isChecked: false,
          isSelected: false,
          isButton: false,
          isSlider: false,
          isKeyboardKey: false,
          isLink: false,
          isTextField: false,
          isReadOnly: false,
          hasEnabledState: false,
          isFocused: false,
          isFocusable: false,
          isEnabled: false,
          isInMutuallyExclusiveGroup: false,
          isHeader: false,
          isObscured: false,
          isMultiline: false,
          namesRoute: false,
          scopesRoute: false,
          isHidden: false,
          isImage: false,
          isLiveRegion: false,
          hasToggledState: false,
          isToggled: false,
          hasImplicitScrolling: false,
1100 1101
          hasExpandedState: false,
          isExpanded: false,
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
          /* Actions */
          hasTapAction: false,
          hasLongPressAction: false,
          hasScrollLeftAction: false,
          hasScrollRightAction: false,
          hasScrollUpAction: false,
          hasScrollDownAction: false,
          hasIncreaseAction: false,
          hasDecreaseAction: false,
          hasShowOnScreenAction: false,
          hasMoveCursorForwardByCharacterAction: false,
          hasMoveCursorBackwardByCharacterAction: false,
          hasMoveCursorForwardByWordAction: false,
          hasMoveCursorBackwardByWordAction: false,
          hasSetTextAction: false,
          hasSetSelectionAction: false,
          hasCopyAction: false,
          hasCutAction: false,
          hasPasteAction: false,
          hasDidGainAccessibilityFocusAction: false,
          hasDidLoseAccessibilityFocusAction: false,
          hasDismissAction: false,
        ),
      );
    });

    testWidgets('only matches given flags and actions', (WidgetTester tester) async {
      int allActions = 0;
      int allFlags = 0;
1131 1132
      for (final SemanticsAction action in SemanticsAction.values) {
        allActions |= action.index;
1133
      }
1134 1135
      for (final SemanticsFlag flag in SemanticsFlag.values) {
        allFlags |= flag.index;
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
      }
      final SemanticsData emptyData = SemanticsData(
        flags: 0,
        actions: 0,
        attributedLabel: AttributedString('a'),
        attributedIncreasedValue: AttributedString('b'),
        attributedValue: AttributedString('c'),
        attributedDecreasedValue: AttributedString('d'),
        attributedHint: AttributedString('e'),
        tooltip: 'f',
        textDirection: TextDirection.ltr,
        rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
        elevation: 3.0,
        thickness: 4.0,
        textSelection: null,
        scrollIndex: null,
        scrollChildCount: null,
        scrollPosition: null,
        scrollExtentMax: null,
        scrollExtentMin: null,
        platformViewId: 105,
        currentValueLength: 10,
        maxValueLength: 15,
      );
      final _FakeSemanticsNode emptyNode = _FakeSemanticsNode(emptyData);

      const CustomSemanticsAction action = CustomSemanticsAction(label: 'test');
      final SemanticsData fullData = SemanticsData(
        flags: allFlags,
        actions: allActions,
        attributedLabel: AttributedString('a'),
        attributedIncreasedValue: AttributedString('b'),
        attributedValue: AttributedString('c'),
        attributedDecreasedValue: AttributedString('d'),
        attributedHint: AttributedString('e'),
        tooltip: 'f',
        textDirection: TextDirection.ltr,
        rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
        elevation: 3.0,
        thickness: 4.0,
        textSelection: null,
        scrollIndex: null,
        scrollChildCount: null,
        scrollPosition: null,
        scrollExtentMax: null,
        scrollExtentMin: null,
        platformViewId: 105,
        currentValueLength: 10,
        maxValueLength: 15,
        customSemanticsActionIds: <int>[CustomSemanticsAction.getIdentifier(action)],
      );
      final _FakeSemanticsNode fullNode = _FakeSemanticsNode(fullData);

      expect(
        emptyNode,
        containsSemantics(
          rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
          size: const Size(10.0, 10.0),
          elevation: 3.0,
          thickness: 4.0,
          platformViewId: 105,
          currentValueLength: 10,
          maxValueLength: 15,
        ),
      );

      expect(
        fullNode,
        containsSemantics(
          rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
          size: const Size(10.0, 10.0),
          elevation: 3.0,
          thickness: 4.0,
          platformViewId: 105,
          currentValueLength: 10,
          maxValueLength: 15,
          customActions: <CustomSemanticsAction>[action],
        ),
      );
    });

    testWidgets('can match child semantics', (WidgetTester tester) async {
      final SemanticsHandle handle = tester.ensureSemantics();
      const Key key = Key('a');
      await tester.pumpWidget(Semantics(
        key: key,
        label: 'Foo',
        container: true,
        explicitChildNodes: true,
        textDirection: TextDirection.ltr,
        child: Semantics(
          label: 'Bar',
          textDirection: TextDirection.ltr,
        ),
      ));
      final SemanticsNode node = tester.getSemantics(find.byKey(key));

      expect(
        node,
        containsSemantics(
          label: 'Foo',
          textDirection: TextDirection.ltr,
          children: <Matcher>[
            containsSemantics(
              label: 'Bar',
              textDirection: TextDirection.ltr,
            ),
          ],
        ),
      );

      handle.dispose();
    });

    testWidgets('can match only custom actions', (WidgetTester tester) async {
      const CustomSemanticsAction action = CustomSemanticsAction(label: 'test');
      final SemanticsData data = SemanticsData(
        flags: 0,
        actions: SemanticsAction.customAction.index,
        attributedLabel: AttributedString('a'),
        attributedIncreasedValue: AttributedString('b'),
        attributedValue: AttributedString('c'),
        attributedDecreasedValue: AttributedString('d'),
        attributedHint: AttributedString('e'),
        tooltip: 'f',
        textDirection: TextDirection.ltr,
        rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
        elevation: 3.0,
        thickness: 4.0,
        textSelection: null,
        scrollIndex: null,
        scrollChildCount: null,
        scrollPosition: null,
        scrollExtentMax: null,
        scrollExtentMin: null,
        platformViewId: 105,
        currentValueLength: 10,
        maxValueLength: 15,
        customSemanticsActionIds: <int>[CustomSemanticsAction.getIdentifier(action)],
      );
      final _FakeSemanticsNode node = _FakeSemanticsNode(data);

      expect(node, containsSemantics(customActions: <CustomSemanticsAction>[action]));
    });
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331

    testWidgets('failure does not throw unexpected errors', (WidgetTester tester) async {
      final SemanticsHandle handle = tester.ensureSemantics();

      const Key key = Key('semantics');
      await tester.pumpWidget(Semantics(
        key: key,
        namesRoute: true,
        header: true,
        button: true,
        link: true,
        onTap: () { },
        onLongPress: () { },
        label: 'foo',
        hint: 'bar',
        value: 'baz',
        increasedValue: 'a',
        decreasedValue: 'b',
        textDirection: TextDirection.rtl,
        onTapHint: 'scan',
        onLongPressHint: 'fill',
        customSemanticsActions: <CustomSemanticsAction, VoidCallback>{
          const CustomSemanticsAction(label: 'foo'): () { },
          const CustomSemanticsAction(label: 'bar'): () { },
        },
      ));

      // This should fail due to the mis-match between the `namesRoute` value.
      void failedExpectation() => expect(tester.getSemantics(find.byKey(key)),
        containsSemantics(
          label: 'foo',
          hint: 'bar',
          value: 'baz',
          increasedValue: 'a',
          decreasedValue: 'b',
          textDirection: TextDirection.rtl,
          hasTapAction: true,
          hasLongPressAction: true,
          isButton: true,
          isLink: true,
          isHeader: true,
          namesRoute: false,
          onTapHint: 'scan',
          onLongPressHint: 'fill',
          customActions: <CustomSemanticsAction>[
            const CustomSemanticsAction(label: 'foo'),
            const CustomSemanticsAction(label: 'bar'),
          ],
        ),
      );

      expect(failedExpectation, throwsA(isA<TestFailure>()));
1332
      handle.dispose();
1333
    });
1334 1335
  });

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
  group('findsAtLeastNWidgets', () {
    Widget boilerplate(Widget child) {
      return Directionality(
        textDirection: TextDirection.ltr,
        child: child,
      );
    }

    testWidgets('succeeds when finds more then the specified count',
        (WidgetTester tester) async {
1346 1347
      await tester.pumpWidget(boilerplate(const Column(
        children: <Widget>[Text('1'), Text('2'), Text('3')],
1348 1349 1350 1351 1352 1353 1354
      )));

      expect(find.byType(Text), findsAtLeastNWidgets(2));
    });

    testWidgets('succeeds when finds the exact specified count',
        (WidgetTester tester) async {
1355 1356
      await tester.pumpWidget(boilerplate(const Column(
        children: <Widget>[Text('1'), Text('2')],
1357 1358 1359 1360 1361 1362 1363
      )));

      expect(find.byType(Text), findsAtLeastNWidgets(2));
    });

    testWidgets('fails when finds less then specified count',
        (WidgetTester tester) async {
1364 1365
      await tester.pumpWidget(boilerplate(const Column(
        children: <Widget>[Text('1'), Text('2')],
1366 1367 1368 1369 1370
      )));

      expect(find.byType(Text), isNot(findsAtLeastNWidgets(3)));
    });
  });
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

  group('findsOneWidget', () {
    testWidgets('finds exactly one widget', (WidgetTester tester) async {
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
      expect(find.text('foo'), findsOneWidget);
    });

    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
      late TestFailure failure;
      try {
        expect(find.text('foo', skipOffstage: false), findsOneWidget);
      } on TestFailure catch (e) {
        failure = e;
      }

      expect(failure, isNotNull);
      final String? message = failure.message;
      expect(message, contains('Expected: exactly one matching candidate\n'));
      expect(message, contains('Actual: _TextWidgetFinder:<Found 0 widgets with text "foo"'));
      expect(message, contains('Which: means none were found but one was expected\n'));
    });
  });

  group('findsNothing', () {
    testWidgets('finds no widgets', (WidgetTester tester) async {
      expect(find.text('foo'), findsNothing);
    });

    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));

      late TestFailure failure;
      try {
        expect(find.text('foo', skipOffstage: false), findsNothing);
      } on TestFailure catch (e) {
        failure = e;
      }

      expect(failure, isNotNull);
      final String? message = failure.message;

      expect(message, contains('Expected: no matching candidates\n'));
      expect(message, contains('Actual: _TextWidgetFinder:<Found 1 widget with text "foo"'));
      expect(message, contains('Text("foo", textDirection: ltr, dependencies: [MediaQuery])'));
      expect(message, contains('Which: means one was found but none were expected\n'));
    });

    testWidgets('fails with a descriptive message when skipping', (WidgetTester tester) async {
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));

      late TestFailure failure;
      try {
        expect(find.text('foo'), findsNothing);
      } on TestFailure catch (e) {
        failure = e;
      }

      expect(failure, isNotNull);
      final String? message = failure.message;

      expect(message, contains('Expected: no matching candidates\n'));
      expect(message, contains('Actual: _TextWidgetFinder:<Found 1 widget with text "foo"'));
      expect(message, contains('Text("foo", textDirection: ltr, dependencies: [MediaQuery])'));
      expect(message, contains('Which: means one was found but none were expected\n'));
    });
  });
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
}

enum _ComparatorBehavior {
  returnTrue,
  returnFalse,
  throwTestFailure,
}

enum _ComparatorInvocation {
  compare,
  update,
}

class _FakeComparator implements GoldenFileComparator {
  _ComparatorBehavior behavior = _ComparatorBehavior.returnTrue;
1452 1453 1454
  _ComparatorInvocation? invocation;
  Uint8List? imageBytes;
  Uri? golden;
1455 1456 1457 1458 1459 1460 1461 1462

  @override
  Future<bool> compare(Uint8List imageBytes, Uri golden) {
    invocation = _ComparatorInvocation.compare;
    this.imageBytes = imageBytes;
    this.golden = golden;
    switch (behavior) {
      case _ComparatorBehavior.returnTrue:
1463
        return Future<bool>.value(true);
1464
      case _ComparatorBehavior.returnFalse:
1465
        return Future<bool>.value(false);
1466
      case _ComparatorBehavior.throwTestFailure:
1467
        fail('fake message');
1468 1469 1470 1471 1472 1473 1474 1475
    }
  }

  @override
  Future<void> update(Uri golden, Uint8List imageBytes) {
    invocation = _ComparatorInvocation.update;
    this.golden = golden;
    this.imageBytes = imageBytes;
1476
    return Future<void>.value();
1477
  }
1478 1479

  @override
1480
  Uri getTestUri(Uri key, int? version) {
1481 1482
    return key;
  }
1483
}
1484 1485

class _FakeSemanticsNode extends SemanticsNode {
1486 1487
  _FakeSemanticsNode(this.data);

1488 1489 1490
  SemanticsData data;
  @override
  SemanticsData getSemanticsData() => data;
1491
}
1492

1493
@immutable
1494
class _CustomColor extends Color {
1495
  const _CustomColor(super.value, {this.isEqual});
1496
  final bool? isEqual;
1497 1498

  @override
1499
  bool operator ==(Object other) => isEqual ?? super == other;
1500 1501

  @override
1502
  int get hashCode => Object.hash(super.hashCode, isEqual);
1503
}