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

import 'package:flutter/cupertino.dart';
6
import 'package:flutter/foundation.dart';
7
import 'package:flutter/rendering.dart';
8
import 'package:flutter/services.dart';
9
import 'package:flutter_test/flutter_test.dart';
10
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
11 12

void main() {
13
  testWidgetsWithLeakTracking('Heroes work', (WidgetTester tester) async {
14
    await tester.pumpWidget(CupertinoApp(
15 16 17 18 19 20 21 22 23 24 25
      home: ListView(children: <Widget>[
        const Hero(tag: 'a', child: Text('foo')),
        Builder(builder: (BuildContext context) {
          return CupertinoButton(
            child: const Text('next'),
            onPressed: () {
              Navigator.push(
                context,
                CupertinoPageRoute<void>(builder: (BuildContext context) {
                  return const Hero(tag: 'a', child: Text('foo'));
                }),
26
              );
27 28 29 30
            },
          );
        }),
      ]),
31 32 33 34 35 36 37 38 39 40 41
    ));

    await tester.tap(find.text('next'));
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));

    // During the hero transition, the hero widget is lifted off of both
    // page routes and exists as its own overlay on top of both routes.
    expect(find.widgetWithText(CupertinoPageRoute, 'foo'), findsNothing);
    expect(find.widgetWithText(Navigator, 'foo'), findsOneWidget);
  });
42

43
  testWidgetsWithLeakTracking('Has default cupertino localizations', (WidgetTester tester) async {
44 45 46 47 48 49
    await tester.pumpWidget(
      CupertinoApp(
        home: Builder(
          builder: (BuildContext context) {
            return Column(
              children: <Widget>[
50 51
                Text(CupertinoLocalizations.of(context).selectAllButtonLabel),
                Text(CupertinoLocalizations.of(context).datePickerMediumDate(
52 53 54 55 56 57 58 59 60 61 62 63
                  DateTime(2018, 10, 4),
                )),
              ],
            );
          },
        ),
      ),
    );

    expect(find.text('Select All'), findsOneWidget);
    expect(find.text('Thu Oct 4 '), findsOneWidget);
  });
64

65
  testWidgetsWithLeakTracking('Can use dynamic color', (WidgetTester tester) async {
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    const CupertinoDynamicColor dynamicColor = CupertinoDynamicColor.withBrightness(
      color: Color(0xFF000000),
      darkColor: Color(0xFF000001),
    );
    await tester.pumpWidget(const CupertinoApp(
      theme: CupertinoThemeData(brightness: Brightness.light),
      color: dynamicColor,
      home: Placeholder(),
    ));

    expect(tester.widget<Title>(find.byType(Title)).color.value, 0xFF000000);

    await tester.pumpWidget(const CupertinoApp(
      theme: CupertinoThemeData(brightness: Brightness.dark),
      color: dynamicColor,
      home: Placeholder(),
    ));

    expect(tester.widget<Title>(find.byType(Title)).color.value, 0xFF000001);
  });
86

87
  testWidgetsWithLeakTracking('Can customize initial routes', (WidgetTester tester) async {
88 89 90 91 92 93 94 95 96 97 98
    final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
    await tester.pumpWidget(
      CupertinoApp(
        navigatorKey: navigatorKey,
        onGenerateInitialRoutes: (String initialRoute) {
          expect(initialRoute, '/abc');
          return <Route<void>>[
            PageRouteBuilder<void>(
              pageBuilder: (
                BuildContext context,
                Animation<double> animation,
99 100
                Animation<double> secondaryAnimation,
              ) {
101
                return const Text('non-regular page one');
102
              },
103 104 105 106 107
            ),
            PageRouteBuilder<void>(
              pageBuilder: (
                BuildContext context,
                Animation<double> animation,
108 109
                Animation<double> secondaryAnimation,
              ) {
110
                return const Text('non-regular page two');
111
              },
112 113 114 115 116 117 118 119
            ),
          ];
        },
        initialRoute: '/abc',
        routes: <String, WidgetBuilder>{
          '/': (BuildContext context) => const Text('regular page one'),
          '/abc': (BuildContext context) => const Text('regular page two'),
        },
120
      ),
121 122 123 124 125
    );
    expect(find.text('non-regular page two'), findsOneWidget);
    expect(find.text('non-regular page one'), findsNothing);
    expect(find.text('regular page one'), findsNothing);
    expect(find.text('regular page two'), findsNothing);
126
    navigatorKey.currentState!.pop();
127 128 129 130 131 132
    await tester.pumpAndSettle();
    expect(find.text('non-regular page two'), findsNothing);
    expect(find.text('non-regular page one'), findsOneWidget);
    expect(find.text('regular page one'), findsNothing);
    expect(find.text('regular page two'), findsNothing);
  });
133

134
  testWidgetsWithLeakTracking('CupertinoApp.navigatorKey can be updated', (WidgetTester tester) async {
135 136 137 138 139 140 141 142 143 144 145 146 147 148
    final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>();
    await tester.pumpWidget(CupertinoApp(
      navigatorKey: key1,
      home: const Placeholder(),
    ));
    expect(key1.currentState, isA<NavigatorState>());
    final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>();
    await tester.pumpWidget(CupertinoApp(
      navigatorKey: key2,
      home: const Placeholder(),
    ));
    expect(key2.currentState, isA<NavigatorState>());
    expect(key1.currentState, isNull);
  });
149

150
  testWidgetsWithLeakTracking('CupertinoApp.router works', (WidgetTester tester) async {
151
    final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
152 153
      initialRouteInformation: RouteInformation(
        uri: Uri.parse('initial'),
154 155
      ),
    );
156
    addTearDown(provider.dispose);
157 158
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
159
        return Text(information.uri.toString());
160 161
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
162 163
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
164 165
        );
        return route.didPop(result);
166
      },
167
    );
168
    addTearDown(delegate.dispose);
169 170 171 172 173 174 175 176 177
    await tester.pumpWidget(CupertinoApp.router(
      routeInformationProvider: provider,
      routeInformationParser: SimpleRouteInformationParser(),
      routerDelegate: delegate,
    ));
    expect(find.text('initial'), findsOneWidget);

    // Simulate android back button intent.
    final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
178
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
179 180
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
181
  });
182 183

  testWidgetsWithLeakTracking('CupertinoApp.router route information parser is optional', (WidgetTester tester) async {
184 185
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
186
        return Text(information.uri.toString());
187 188
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
189 190
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
191 192 193 194
        );
        return route.didPop(result);
      },
    );
195
    addTearDown(delegate.dispose);
196
    delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
197 198 199 200 201 202 203
    await tester.pumpWidget(CupertinoApp.router(
      routerDelegate: delegate,
    ));
    expect(find.text('initial'), findsOneWidget);

    // Simulate android back button intent.
    final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
204
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
205 206
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
207
  });
208 209

  testWidgetsWithLeakTracking('CupertinoApp.router throw if route information provider is provided but no route information parser', (WidgetTester tester) async {
210 211
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
212
        return Text(information.uri.toString());
213 214
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
215 216
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
217 218 219 220
        );
        return route.didPop(result);
      },
    );
221
    addTearDown(delegate.dispose);
222
    delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
223
    final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
224 225
      initialRouteInformation: RouteInformation(
        uri: Uri.parse('initial'),
226 227
      ),
    );
228
    addTearDown(provider.dispose);
229 230 231 232 233 234 235
    await tester.pumpWidget(CupertinoApp.router(
      routeInformationProvider: provider,
      routerDelegate: delegate,
    ));
    expect(tester.takeException(), isAssertionError);
  });

236
  testWidgetsWithLeakTracking('CupertinoApp.router throw if route configuration is provided along with other delegate', (WidgetTester tester) async {
237 238
    final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
      builder: (BuildContext context, RouteInformation information) {
239
        return Text(information.uri.toString());
240 241
      },
      onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
242 243
        delegate.routeInformation = RouteInformation(
          uri: Uri.parse('popped'),
244 245 246 247
        );
        return route.didPop(result);
      },
    );
248
    addTearDown(delegate.dispose);
249
    delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
250 251 252 253 254 255 256 257
    final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(routerDelegate: delegate);
    await tester.pumpWidget(CupertinoApp.router(
      routerDelegate: delegate,
      routerConfig: routerConfig,
    ));
    expect(tester.takeException(), isAssertionError);
  });

258 259 260 261 262 263 264 265 266
  testWidgetsWithLeakTracking('CupertinoApp.router router config works', (WidgetTester tester) async {
    late SimpleNavigatorRouterDelegate delegate;
    addTearDown(() => delegate.dispose());
    final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
      initialRouteInformation: RouteInformation(
        uri: Uri.parse('initial'),
      ),
    );
    addTearDown(provider.dispose);
267
    final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(
268
        routeInformationProvider: provider,
269
        routeInformationParser: SimpleRouteInformationParser(),
270
        routerDelegate: delegate = SimpleNavigatorRouterDelegate(
271
          builder: (BuildContext context, RouteInformation information) {
272
            return Text(information.uri.toString());
273 274
          },
          onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
275 276
            delegate.routeInformation = RouteInformation(
              uri: Uri.parse('popped'),
277 278 279 280 281 282 283 284 285 286 287 288 289
            );
            return route.didPop(result);
          },
        ),
        backButtonDispatcher: RootBackButtonDispatcher()
    );
    await tester.pumpWidget(CupertinoApp.router(
      routerConfig: routerConfig,
    ));
    expect(find.text('initial'), findsOneWidget);

    // Simulate android back button intent.
    final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
290
    await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
291 292
    await tester.pumpAndSettle();
    expect(find.text('popped'), findsOneWidget);
293
  });
294 295

  testWidgetsWithLeakTracking('CupertinoApp has correct default ScrollBehavior', (WidgetTester tester) async {
296 297 298 299 300 301 302 303 304 305 306 307 308 309
    late BuildContext capturedContext;
    await tester.pumpWidget(
      CupertinoApp(
        home: Builder(
          builder: (BuildContext context) {
            capturedContext = context;
            return const Placeholder();
          },
        ),
      ),
    );
    expect(ScrollConfiguration.of(capturedContext).runtimeType, CupertinoScrollBehavior);
  });

310
  testWidgetsWithLeakTracking('A ScrollBehavior can be set for CupertinoApp', (WidgetTester tester) async {
311 312 313
    late BuildContext capturedContext;
    await tester.pumpWidget(
      CupertinoApp(
314
        scrollBehavior: const MockScrollBehavior(),
315 316 317 318 319 320 321 322 323 324 325 326
        home: Builder(
          builder: (BuildContext context) {
            capturedContext = context;
            return const Placeholder();
          },
        ),
      ),
    );
    final ScrollBehavior scrollBehavior = ScrollConfiguration.of(capturedContext);
    expect(scrollBehavior.runtimeType, MockScrollBehavior);
    expect(scrollBehavior.getScrollPhysics(capturedContext).runtimeType, NeverScrollableScrollPhysics);
  });
327

328
  testWidgetsWithLeakTracking('When `useInheritedMediaQuery` is true an existing MediaQuery is used if one is available', (WidgetTester tester) async {
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    late BuildContext capturedContext;
    final UniqueKey uniqueKey = UniqueKey();
    await tester.pumpWidget(
      MediaQuery(
        key: uniqueKey,
        data: const MediaQueryData(),
        child: CupertinoApp(
          useInheritedMediaQuery: true,
          builder: (BuildContext context, Widget? child) {
            capturedContext = context;
            return const Placeholder();
          },
          color: const Color(0xFF123456),
        ),
      ),
    );
    expect(capturedContext.dependOnInheritedWidgetOfExactType<MediaQuery>()?.key, uniqueKey);
  });
347

348
  testWidgetsWithLeakTracking('Text color is correctly resolved when CupertinoThemeData.brightness is null', (WidgetTester tester) async {
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
    debugBrightnessOverride = Brightness.dark;

    await tester.pumpWidget(
      const CupertinoApp(
        home: CupertinoPageScaffold(
          child: Text('Hello'),
        ),
      ),
    );

    final RenderParagraph paragraph = tester.renderObject(find.text('Hello'));
    final CupertinoDynamicColor textColor = paragraph.text.style!.color! as CupertinoDynamicColor;

    // App with non-null brightness, so resolving color
    // doesn't depend on the MediaQuery.platformBrightness.
    late BuildContext capturedContext;
    await tester.pumpWidget(
      CupertinoApp(
        theme: const CupertinoThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
            capturedContext = context;

            return const Placeholder();
          },
        ),
      ),
    );

    // We expect the string representations of the colors to have darkColor indicated (*) as effective color.
    // (color = Color(0xff000000), *darkColor = Color(0xffffffff)*, resolved by: Builder)
    expect(textColor.toString(), CupertinoColors.label.resolveFrom(capturedContext).toString());

    debugBrightnessOverride = null;
  });

387
  testWidgetsWithLeakTracking('Cursor color is resolved when CupertinoThemeData.brightness is null', (WidgetTester tester) async {
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    debugBrightnessOverride = Brightness.dark;

    RenderEditable findRenderEditable(WidgetTester tester) {
      final RenderObject root = tester.renderObject(find.byType(EditableText));
      expect(root, isNotNull);

      RenderEditable? renderEditable;
      void recursiveFinder(RenderObject child) {
        if (child is RenderEditable) {
          renderEditable = child;
          return;
        }
        child.visitChildren(recursiveFinder);
      }

      root.visitChildren(recursiveFinder);
      expect(renderEditable, isNotNull);
      return renderEditable!;
    }

408 409 410 411 412
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);
    final TextEditingController controller = TextEditingController();
    addTearDown(controller.dispose);

413 414 415 416 417 418 419 420 421 422 423
    await tester.pumpWidget(
      CupertinoApp(
        theme: const CupertinoThemeData(
          primaryColor: CupertinoColors.activeOrange,
        ),
        home: CupertinoPageScaffold(
          child: Builder(
            builder: (BuildContext context) {
              return EditableText(
                backgroundCursorColor: DefaultSelectionStyle.of(context).selectionColor!,
                cursorColor: DefaultSelectionStyle.of(context).cursorColor!,
424 425
                controller: controller,
                focusNode: focusNode,
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
                style: const TextStyle(),
              );
            },
          ),
        ),
      ),
    );

    final RenderEditable editableText = findRenderEditable(tester);
    final Color cursorColor = editableText.cursorColor!;

    // Cursor color should be equal to the dark variant of the primary color.
    // Alpha value needs to be 0, because cursor is not visible by default.
    expect(cursorColor, CupertinoColors.activeOrange.darkColor.withAlpha(0));

    debugBrightnessOverride = null;
  });
443

444
  testWidgetsWithLeakTracking('Assert in buildScrollbar that controller != null when using it', (WidgetTester tester) async {
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    const ScrollBehavior defaultBehavior = CupertinoScrollBehavior();
    late BuildContext capturedContext;

    await tester.pumpWidget(ScrollConfiguration(
      // Avoid the default ones here.
      behavior: const CupertinoScrollBehavior().copyWith(scrollbars: false),
      child: SingleChildScrollView(
        child: Builder(
          builder: (BuildContext context) {
            capturedContext = context;
            return Container(height: 1000.0);
          },
        ),
      ),
    ));

    const ScrollableDetails details = ScrollableDetails(direction: AxisDirection.down);
    final Widget child = Container();

464
    switch (defaultTargetPlatform) {
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.iOS:
        // Does not throw if we aren't using it.
        defaultBehavior.buildScrollbar(capturedContext, child, details);
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        expect(
          () {
            defaultBehavior.buildScrollbar(capturedContext, child, details);
          },
          throwsA(
            isA<AssertionError>().having((AssertionError error) => error.toString(),
                'description', contains('details.controller != null')),
          ),
        );
    }
  }, variant: TargetPlatformVariant.all());
484 485 486
}

class MockScrollBehavior extends ScrollBehavior {
487 488
  const MockScrollBehavior();

489 490
  @override
  ScrollPhysics getScrollPhysics(BuildContext context) => const NeverScrollableScrollPhysics();
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
}

typedef SimpleRouterDelegateBuilder = Widget Function(BuildContext, RouteInformation);
typedef SimpleNavigatorRouterDelegatePopPage<T> = bool Function(Route<T> route, T result, SimpleNavigatorRouterDelegate delegate);

class SimpleRouteInformationParser extends RouteInformationParser<RouteInformation> {
  SimpleRouteInformationParser();

  @override
  Future<RouteInformation> parseRouteInformation(RouteInformation information) {
    return SynchronousFuture<RouteInformation>(information);
  }

  @override
  RouteInformation restoreRouteInformation(RouteInformation configuration) {
    return configuration;
  }
}

class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> with PopNavigatorRouterDelegateMixin<RouteInformation>, ChangeNotifier {
  SimpleNavigatorRouterDelegate({
512
    required this.builder,
513 514 515 516 517 518 519
    this.onPopPage,
  });

  @override
  GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  RouteInformation get routeInformation => _routeInformation;
520
  late RouteInformation _routeInformation;
521 522 523 524 525 526
  set routeInformation(RouteInformation newValue) {
    _routeInformation = newValue;
    notifyListeners();
  }

  SimpleRouterDelegateBuilder builder;
527
  SimpleNavigatorRouterDelegatePopPage<void>? onPopPage;
528 529 530 531 532 533 534 535

  @override
  Future<void> setNewRoutePath(RouteInformation configuration) {
    _routeInformation = configuration;
    return SynchronousFuture<void>(null);
  }

  bool _handlePopPage(Route<void> route, void data) {
536
    return onPopPage!(route, data, this);
537 538 539 540 541 542 543 544 545 546
  }

  @override
  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      onPopPage: _handlePopPage,
      pages: <Page<void>>[
        // We need at least two pages for the pop to propagate through.
        // Otherwise, the navigator will bubble the pop to the system navigator.
547 548
        const CupertinoPage<void>(
          child:  Text('base'),
549 550
        ),
        CupertinoPage<void>(
551
          key: ValueKey<String?>(routeInformation.uri.toString()),
552
          child: builder(context, routeInformation),
553
        ),
554 555 556
      ],
    );
  }
557
}