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

5
import 'dart:math' as math;
6
import 'package:flutter_test/flutter_test.dart';
7
import 'package:flutter/material.dart';
8 9
import 'package:flutter/widgets.dart';
import 'package:flutter/rendering.dart';
10
import 'package:mockito/mockito.dart';
11 12 13 14 15 16

void main() {
  group('PhysicalShape', () {
    testWidgets('properties', (WidgetTester tester) async {
      await tester.pumpWidget(
        const PhysicalShape(
17
          clipper: ShapeBorderClipper(shape: CircleBorder()),
18
          elevation: 2.0,
19 20
          color: Color(0xFF0000FF),
          shadowColor: Color(0xFF00FF00),
21
        ),
22 23
      );
      final RenderPhysicalShape renderObject = tester.renderObject(find.byType(PhysicalShape));
24
      expect(renderObject.clipper, const ShapeBorderClipper(shape: CircleBorder()));
25 26 27 28 29 30 31
      expect(renderObject.color, const Color(0xFF0000FF));
      expect(renderObject.shadowColor, const Color(0xFF00FF00));
      expect(renderObject.elevation, 2.0);
    });

    testWidgets('hit test', (WidgetTester tester) async {
      await tester.pumpWidget(
32
        PhysicalShape(
33
          clipper: const ShapeBorderClipper(shape: CircleBorder()),
34 35 36
          elevation: 2.0,
          color: const Color(0xFF0000FF),
          shadowColor: const Color(0xFF00FF00),
37
          child: Container(color: const Color(0xFF0000FF)),
38
        ),
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
      );

      final RenderPhysicalShape renderPhysicalShape =
        tester.renderObject(find.byType(PhysicalShape));

      // The viewport is 800x600, the CircleBorder is centered and fits
      // the shortest edge, so we get a circle of radius 300, centered at
      // (400, 300).
      //
      // We test by sampling a few points around the left-most point of the
      // circle (100, 300).

      expect(tester.hitTestOnBinding(const Offset(99.0, 300.0)), doesNotHit(renderPhysicalShape));
      expect(tester.hitTestOnBinding(const Offset(100.0, 300.0)), hits(renderPhysicalShape));
      expect(tester.hitTestOnBinding(const Offset(100.0, 299.0)), doesNotHit(renderPhysicalShape));
      expect(tester.hitTestOnBinding(const Offset(100.0, 301.0)), doesNotHit(renderPhysicalShape));
55
    }, skip: isBrowser);
56 57 58

  });

Emmanuel Garcia's avatar
Emmanuel Garcia committed
59 60
  group('FractionalTranslation', () {
    testWidgets('hit test - entirely inside the bounding box', (WidgetTester tester) async {
61
      final GlobalKey key1 = GlobalKey();
Emmanuel Garcia's avatar
Emmanuel Garcia committed
62 63 64
      bool _pointerDown = false;

      await tester.pumpWidget(
65 66
        Center(
          child: FractionalTranslation(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
67 68
            translation: Offset.zero,
            transformHitTests: true,
69
            child: Listener(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
70 71 72
              onPointerDown: (PointerDownEvent event) {
                _pointerDown = true;
              },
73
              child: SizedBox(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
74 75 76
                key: key1,
                width: 100.0,
                height: 100.0,
77
                child: Container(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
78 79 80
                  color: const Color(0xFF0000FF)
                ),
              ),
81 82
            ),
          ),
83
        ),
Emmanuel Garcia's avatar
Emmanuel Garcia committed
84 85 86 87 88 89 90
      );
      expect(_pointerDown, isFalse);
      await tester.tap(find.byKey(key1));
      expect(_pointerDown, isTrue);
    });

    testWidgets('hit test - partially inside the bounding box', (WidgetTester tester) async {
91
      final GlobalKey key1 = GlobalKey();
Emmanuel Garcia's avatar
Emmanuel Garcia committed
92 93 94
      bool _pointerDown = false;

      await tester.pumpWidget(
95 96
        Center(
          child: FractionalTranslation(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
97 98
            translation: const Offset(0.5, 0.5),
            transformHitTests: true,
99
            child: Listener(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
100 101 102
              onPointerDown: (PointerDownEvent event) {
                _pointerDown = true;
              },
103
              child: SizedBox(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
104 105 106
                key: key1,
                width: 100.0,
                height: 100.0,
107
                child: Container(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
108 109 110
                  color: const Color(0xFF0000FF)
                ),
              ),
111 112
            ),
          ),
113
        ),
Emmanuel Garcia's avatar
Emmanuel Garcia committed
114 115 116 117 118 119 120
      );
      expect(_pointerDown, isFalse);
      await tester.tap(find.byKey(key1));
      expect(_pointerDown, isTrue);
    });

    testWidgets('hit test - completely outside the bounding box', (WidgetTester tester) async {
121
      final GlobalKey key1 = GlobalKey();
Emmanuel Garcia's avatar
Emmanuel Garcia committed
122 123 124
      bool _pointerDown = false;

      await tester.pumpWidget(
125 126
        Center(
          child: FractionalTranslation(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
127 128
            translation: const Offset(1.0, 1.0),
            transformHitTests: true,
129
            child: Listener(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
130 131 132
              onPointerDown: (PointerDownEvent event) {
                _pointerDown = true;
              },
133
              child: SizedBox(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
134 135 136
                key: key1,
                width: 100.0,
                height: 100.0,
137
                child: Container(
Emmanuel Garcia's avatar
Emmanuel Garcia committed
138 139 140
                  color: const Color(0xFF0000FF)
                ),
              ),
141 142
            ),
          ),
143
        ),
Emmanuel Garcia's avatar
Emmanuel Garcia committed
144 145 146 147 148
      );
      expect(_pointerDown, isFalse);
      await tester.tap(find.byKey(key1));
      expect(_pointerDown, isTrue);
    });
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

    testWidgets('semantics bounds are updated', (WidgetTester tester) async {
      final GlobalKey fractionalTranslationKey = GlobalKey();
      final GlobalKey textKey = GlobalKey();
      Offset offset = const Offset(0.4, 0.4);

      await tester.pumpWidget(
          StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return Directionality(
                textDirection: TextDirection.ltr,
                child: Center(
                  child: Semantics(
                    explicitChildNodes: true,
                    child: FractionalTranslation(
                      key: fractionalTranslationKey,
                      translation: offset,
                      transformHitTests: true,
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            offset = const Offset(0.8, 0.8);
                          });
                        },
                        child: SizedBox(
                          width: 100.0,
                          height: 100.0,
                          child: Text(
                            'foo',
                            key: textKey,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              );
            },
          )
      );

      expect(
        tester.getSemantics(find.byKey(textKey)).transform,
        Matrix4(
          3.0, 0.0, 0.0, 0.0,
          0.0, 3.0, 0.0, 0.0,
          0.0, 0.0, 1.0, 0.0,
          1170.0, 870.0, 0.0, 1.0,
        ),
      );

      await tester.tap(find.byKey(fractionalTranslationKey));
      await tester.pump();
      expect(
        tester.getSemantics(find.byKey(textKey)).transform,
        Matrix4(
          3.0, 0.0, 0.0, 0.0,
          0.0, 3.0, 0.0, 0.0,
          0.0, 0.0, 1.0, 0.0,
          1290.0, 990.0, 0.0, 1.0,
        ),
      );
    });
Emmanuel Garcia's avatar
Emmanuel Garcia committed
212
  });
213

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  group('Row', () {
    testWidgets('multiple baseline aligned children', (WidgetTester tester) async {
      final UniqueKey key1 = UniqueKey();
      final UniqueKey key2 = UniqueKey();
      const double fontSize1 = 54;
      const double fontSize2 = 14;

      await tester.pumpWidget(
        MaterialApp(
          home: Scaffold(
            body: Container(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.baseline,
                textBaseline: TextBaseline.alphabetic,
                children: <Widget>[
                  Text('big text',
                    key: key1,
                    style: const TextStyle(fontSize: fontSize1),
                  ),
                  Text('one\ntwo\nthree\nfour\nfive\nsix\nseven',
                    key: key2,
235
                    style: const TextStyle(fontSize: fontSize2),
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
                  ),
                ],
              ),
            ),
          ),
        ),
      );

      final RenderBox textBox1 = tester.renderObject(find.byKey(key1));
      final RenderBox textBox2 = tester.renderObject(find.byKey(key2));
      final RenderBox rowBox = tester.renderObject(find.byType(Row));

      // The two Texts are baseline aligned, so some portion of them extends
      // both above and below the baseline. The first has a huge font size, so
      // it extends higher above the baseline than usual. The second has many
      // lines, but being aligned by the first line's baseline, they hang far
      // below the baseline. The size of the parent row is just enough to
      // contain both of them.
      const double ahemBaselineLocation = 0.8; // https://web-platform-tests.org/writing-tests/ahem.html
      const double aboveBaseline1 = fontSize1 * ahemBaselineLocation;
      const double belowBaseline1 = fontSize1 * (1 - ahemBaselineLocation);
      const double aboveBaseline2 = fontSize2 * ahemBaselineLocation;
      const double belowBaseline2 = fontSize2 * (1 - ahemBaselineLocation) + fontSize2 * 6;
      final double aboveBaseline = math.max(aboveBaseline1, aboveBaseline2);
      final double belowBaseline = math.max(belowBaseline1, belowBaseline2);
      expect(rowBox.size.height, greaterThan(textBox1.size.height));
      expect(rowBox.size.height, greaterThan(textBox2.size.height));
      expect(rowBox.size.height, closeTo(aboveBaseline + belowBaseline, .001));
      expect(tester.getTopLeft(find.byKey(key1)).dy, 0);
      expect(
        tester.getTopLeft(find.byKey(key2)).dy,
        closeTo(aboveBaseline1 - aboveBaseline2, .001),
      );
269
    }, skip: isBrowser);
270 271
  });

272 273 274 275 276 277 278 279 280 281
  test('UnconstrainedBox toString', () {
    expect(
      const UnconstrainedBox(constrainedAxis: Axis.vertical,).toString(),
      equals('UnconstrainedBox(alignment: center, constrainedAxis: vertical)'),
    );
    expect(
      const UnconstrainedBox(constrainedAxis: Axis.horizontal, textDirection: TextDirection.rtl, alignment: Alignment.topRight).toString(),
      equals('UnconstrainedBox(alignment: topRight, constrainedAxis: horizontal, textDirection: rtl)'),
    );
  });
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

  group('ColoredBox', () {
    _MockCanvas mockCanvas;
    _MockPaintingContext mockContext;
    const Color colorToPaint = Color(0xFFABCDEF);

    setUp(() {
      mockContext = _MockPaintingContext();
      mockCanvas = _MockCanvas();
      when(mockContext.canvas).thenReturn(mockCanvas);
    });

    testWidgets('ColoredBox - no size, no child', (WidgetTester tester) async {
      await tester.pumpWidget(Flex(
        direction: Axis.horizontal,
        textDirection: TextDirection.ltr,
        children: const <Widget>[
          SizedBox.shrink(
            child: ColoredBox(color: colorToPaint),
          ),
        ],
      ));
      expect(find.byType(ColoredBox), findsOneWidget);
      final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox));

      renderColoredBox.paint(mockContext, Offset.zero);

      verifyNever(mockCanvas.drawRect(any, any));
      verifyNever(mockContext.paintChild(any, any));
    });

    testWidgets('ColoredBox - no size, child', (WidgetTester tester) async {
      const ValueKey<int> key = ValueKey<int>(0);
      const Widget child = SizedBox.expand(key: key);
      await tester.pumpWidget(Flex(
        direction: Axis.horizontal,
        textDirection: TextDirection.ltr,
        children: const <Widget>[
          SizedBox.shrink(
            child: ColoredBox(color: colorToPaint, child: child),
          ),
        ],
      ));
      expect(find.byType(ColoredBox), findsOneWidget);
      final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox));
      final RenderObject renderSizedBox = tester.renderObject(find.byKey(key));

      renderColoredBox.paint(mockContext, Offset.zero);

      verifyNever(mockCanvas.drawRect(any, any));
      verify(mockContext.paintChild(renderSizedBox, Offset.zero)).called(1);
    });

    testWidgets('ColoredBox - size, no child', (WidgetTester tester) async {
      await tester.pumpWidget(const ColoredBox(color: colorToPaint));
      expect(find.byType(ColoredBox), findsOneWidget);
      final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox));

      renderColoredBox.paint(mockContext, Offset.zero);

      final List<dynamic> drawRect = verify(mockCanvas.drawRect(captureAny, captureAny)).captured;
      expect(drawRect.length, 2);
      expect(drawRect[0], const Rect.fromLTWH(0, 0, 800, 600));
      expect(drawRect[1].color, colorToPaint);
      verifyNever(mockContext.paintChild(any, any));
    });

    testWidgets('ColoredBox - size, child', (WidgetTester tester) async {
      const ValueKey<int> key = ValueKey<int>(0);
      const Widget child = SizedBox.expand(key: key);
      await tester.pumpWidget(const ColoredBox(color: colorToPaint, child: child));
      expect(find.byType(ColoredBox), findsOneWidget);
      final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox));
      final RenderObject renderSizedBox = tester.renderObject(find.byKey(key));

      renderColoredBox.paint(mockContext, Offset.zero);

      final List<dynamic> drawRect = verify(mockCanvas.drawRect(captureAny, captureAny)).captured;
      expect(drawRect.length, 2);
      expect(drawRect[0], const Rect.fromLTWH(0, 0, 800, 600));
      expect(drawRect[1].color, colorToPaint);
      verify(mockContext.paintChild(renderSizedBox, Offset.zero)).called(1);
      });
  });
366 367
}

368
HitsRenderBox hits(RenderBox renderBox) => HitsRenderBox(renderBox);
369 370 371 372 373 374 375 376 377 378 379 380

class HitsRenderBox extends Matcher {
  const HitsRenderBox(this.renderBox);

  final RenderBox renderBox;

  @override
  Description describe(Description description) =>
    description.add('hit test result contains ').addDescriptionOf(renderBox);

  @override
  bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
381
    final HitTestResult hitTestResult = item as HitTestResult;
382 383 384 385 386 387
    return hitTestResult.path.where(
      (HitTestEntry entry) => entry.target == renderBox
    ).isNotEmpty;
  }
}

388
DoesNotHitRenderBox doesNotHit(RenderBox renderBox) => DoesNotHitRenderBox(renderBox);
389 390 391 392 393 394 395 396

class DoesNotHitRenderBox extends Matcher {
  const DoesNotHitRenderBox(this.renderBox);

  final RenderBox renderBox;

  @override
  Description describe(Description description) =>
397
    description.add("hit test result doesn't contain ").addDescriptionOf(renderBox);
398 399 400

  @override
  bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
401
    final HitTestResult hitTestResult = item as HitTestResult;
402 403 404 405 406
    return hitTestResult.path.where(
      (HitTestEntry entry) => entry.target == renderBox
    ).isEmpty;
  }
}
407 408 409

class _MockPaintingContext extends Mock implements PaintingContext {}
class _MockCanvas extends Mock implements Canvas {}