app_test.dart 18 KB
Newer Older
1 2 3 4 5
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter_test/flutter_test.dart';
6
import 'package:flutter/cupertino.dart';
7
import 'package:flutter/material.dart';
8

9
class StateMarker extends StatefulWidget {
10
  const StateMarker({ Key key, this.child }) : super(key: key);
11 12 13 14

  final Widget child;

  @override
15
  StateMarkerState createState() => StateMarkerState();
16 17 18 19 20 21 22
}

class StateMarkerState extends State<StateMarker> {
  String marker;

  @override
  Widget build(BuildContext context) {
23 24
    if (widget.child != null)
      return widget.child;
25
    return Container();
26 27 28
  }
}

29 30 31
void main() {
  testWidgets('Can nest apps', (WidgetTester tester) async {
    await tester.pumpWidget(
32
      const MaterialApp(
33
        home: MaterialApp(
34
          home: Text('Home sweet home'),
35 36
        ),
      ),
37 38 39 40 41 42
    );

    expect(find.text('Home sweet home'), findsOneWidget);
  });

  testWidgets('Focus handling', (WidgetTester tester) async {
43 44 45 46 47
    final FocusNode focusNode = FocusNode();
    await tester.pumpWidget(MaterialApp(
      home: Material(
        child: Center(
          child: TextField(focusNode: focusNode, autofocus: true),
48 49
        ),
      ),
50 51
    ));

52
    expect(focusNode.hasFocus, isTrue);
53
  });
54

55
  testWidgets('Can place app inside FocusScope', (WidgetTester tester) async {
56
    final FocusScopeNode focusScopeNode = FocusScopeNode();
57

58
    await tester.pumpWidget(FocusScope(
59 60
      autofocus: true,
      node: focusScopeNode,
61 62
      child: const MaterialApp(
        home: Text('Home'),
63 64 65 66 67 68
      ),
    ));

    expect(find.text('Home'), findsOneWidget);
  });

69 70
  testWidgets('Can show grid without losing sync', (WidgetTester tester) async {
    await tester.pumpWidget(
71 72
      const MaterialApp(
        home: StateMarker(),
73
      ),
74 75
    );

76
    final StateMarkerState state1 = tester.state(find.byType(StateMarker));
77 78 79
    state1.marker = 'original';

    await tester.pumpWidget(
80
      const MaterialApp(
81
        debugShowMaterialGrid: true,
82
        home: StateMarker(),
83
      ),
84 85
    );

86
    final StateMarkerState state2 = tester.state(find.byType(StateMarker));
87 88 89
    expect(state1, equals(state2));
    expect(state2.marker, equals('original'));
  });
90

91
  testWidgets('Do not rebuild page during a route transition', (WidgetTester tester) async {
92 93
    int buildCounter = 0;
    await tester.pumpWidget(
94 95
      MaterialApp(
        home: Builder(
96
          builder: (BuildContext context) {
97 98
            return Material(
              child: RaisedButton(
99
                child: const Text('X'),
100 101
                onPressed: () { Navigator.of(context).pushNamed('/next'); },
              ),
102 103 104 105 106
            );
          }
        ),
        routes: <String, WidgetBuilder>{
          '/next': (BuildContext context) {
107
            return Builder(
108 109
              builder: (BuildContext context) {
                ++buildCounter;
110
                return const Text('Y');
111
              },
112
            );
113 114 115
          },
        },
      ),
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    );

    expect(buildCounter, 0);
    await tester.tap(find.text('X'));
    expect(buildCounter, 0);
    await tester.pump();
    expect(buildCounter, 1);
    await tester.pump(const Duration(milliseconds: 10));
    expect(buildCounter, 1);
    await tester.pump(const Duration(milliseconds: 10));
    expect(buildCounter, 1);
    await tester.pump(const Duration(milliseconds: 10));
    expect(buildCounter, 1);
    await tester.pump(const Duration(milliseconds: 10));
    expect(buildCounter, 1);
    await tester.pump(const Duration(seconds: 1));
132
    expect(buildCounter, 1);
133
    expect(find.text('Y'), findsOneWidget);
134 135
  });

136 137 138
  testWidgets('Do rebuild the home page if it changes', (WidgetTester tester) async {
    int buildCounter = 0;
    await tester.pumpWidget(
139 140
      MaterialApp(
        home: Builder(
141 142 143 144 145 146 147 148 149 150
          builder: (BuildContext context) {
            ++buildCounter;
            return const Text('A');
          }
        ),
      ),
    );
    expect(buildCounter, 1);
    expect(find.text('A'), findsOneWidget);
    await tester.pumpWidget(
151 152
      MaterialApp(
        home: Builder(
153 154 155 156 157 158 159 160 161 162 163 164 165
          builder: (BuildContext context) {
            ++buildCounter;
            return const Text('B');
          }
        ),
      ),
    );
    expect(buildCounter, 2);
    expect(find.text('B'), findsOneWidget);
  });

  testWidgets('Do not rebuild the home page if it does not actually change', (WidgetTester tester) async {
    int buildCounter = 0;
166
    final Widget home = Builder(
167 168 169 170 171 172
      builder: (BuildContext context) {
        ++buildCounter;
        return const Placeholder();
      }
    );
    await tester.pumpWidget(
173
      MaterialApp(
174 175 176 177 178
        home: home,
      ),
    );
    expect(buildCounter, 1);
    await tester.pumpWidget(
179
      MaterialApp(
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        home: home,
      ),
    );
    expect(buildCounter, 1);
  });

  testWidgets('Do rebuild pages that come from the routes table if the MaterialApp changes', (WidgetTester tester) async {
    int buildCounter = 0;
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
      '/': (BuildContext context) {
        ++buildCounter;
        return const Placeholder();
      },
    };
    await tester.pumpWidget(
195
      MaterialApp(
196 197 198 199 200
        routes: routes,
      ),
    );
    expect(buildCounter, 1);
    await tester.pumpWidget(
201
      MaterialApp(
202 203 204 205 206 207
        routes: routes,
      ),
    );
    expect(buildCounter, 2);
  });

208
  testWidgets('Cannot pop the initial route', (WidgetTester tester) async {
209
    await tester.pumpWidget(const MaterialApp(home: Text('Home')));
210 211 212

    expect(find.text('Home'), findsOneWidget);

213 214
    final NavigatorState navigator = tester.state(find.byType(Navigator));
    final bool result = await navigator.maybePop();
215 216 217 218 219

    expect(result, isFalse);

    expect(find.text('Home'), findsOneWidget);
  });
220 221

  testWidgets('Default initialRoute', (WidgetTester tester) async {
222
    await tester.pumpWidget(MaterialApp(routes: <String, WidgetBuilder>{
223 224 225 226 227 228
      '/': (BuildContext context) => const Text('route "/"'),
    }));

    expect(find.text('route "/"'), findsOneWidget);
  });

229
  testWidgets('One-step initial route', (WidgetTester tester) async {
230
    await tester.pumpWidget(
231
      MaterialApp(
232 233
        initialRoute: '/a',
        routes: <String, WidgetBuilder>{
234
          '/': (BuildContext context) => const Text('route "/"'),
235
          '/a': (BuildContext context) => const Text('route "/a"'),
236 237
          '/a/b': (BuildContext context) => const Text('route "/a/b"'),
          '/b': (BuildContext context) => const Text('route "/b"'),
238 239 240 241
        },
      )
    );

242
    expect(find.text('route "/"'), findsOneWidget);
243
    expect(find.text('route "/a"'), findsOneWidget);
244 245
    expect(find.text('route "/a/b"'), findsNothing);
    expect(find.text('route "/b"'), findsNothing);
246 247
  });

248
  testWidgets('Return value from pop is correct', (WidgetTester tester) async {
249
    Future<Object> result;
250
    await tester.pumpWidget(
251 252
        MaterialApp(
          home: Builder(
253
              builder: (BuildContext context) {
254 255
                return Material(
                  child: RaisedButton(
256 257 258 259 260 261 262 263 264 265
                      child: const Text('X'),
                      onPressed: () async {
                        result = Navigator.of(context).pushNamed('/a');
                      }
                  ),
                );
              }
          ),
          routes: <String, WidgetBuilder>{
            '/a': (BuildContext context) {
266 267
              return Material(
                child: RaisedButton(
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
                  child: const Text('Y'),
                  onPressed: () {
                    Navigator.of(context).pop('all done');
                  },
                ),
              );
            }
          },
        )
    );
    await tester.tap(find.text('X'));
    await tester.pump();
    await tester.pump(const Duration(seconds: 1));
    expect(find.text('Y'), findsOneWidget);
    await tester.tap(find.text('Y'));
    await tester.pump();

    expect(await result, equals('all done'));
  });

    testWidgets('Two-step initial route', (WidgetTester tester) async {
289 290 291
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
      '/': (BuildContext context) => const Text('route "/"'),
      '/a': (BuildContext context) => const Text('route "/a"'),
292
      '/a/b': (BuildContext context) => const Text('route "/a/b"'),
293 294 295 296
      '/b': (BuildContext context) => const Text('route "/b"'),
    };

    await tester.pumpWidget(
297
      MaterialApp(
298
        initialRoute: '/a/b',
299 300 301
        routes: routes,
      )
    );
302
    expect(find.text('route "/"'), findsOneWidget);
303
    expect(find.text('route "/a"'), findsOneWidget);
304 305 306 307 308 309 310 311 312 313 314 315 316
    expect(find.text('route "/a/b"'), findsOneWidget);
    expect(find.text('route "/b"'), findsNothing);
  });

  testWidgets('Initial route with missing step', (WidgetTester tester) async {
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
      '/': (BuildContext context) => const Text('route "/"'),
      '/a': (BuildContext context) => const Text('route "/a"'),
      '/a/b': (BuildContext context) => const Text('route "/a/b"'),
      '/b': (BuildContext context) => const Text('route "/b"'),
    };

    await tester.pumpWidget(
317
      MaterialApp(
318 319 320 321 322 323 324 325 326 327
        initialRoute: '/a/b/c',
        routes: routes,
      )
    );
    final dynamic exception = tester.takeException();
    expect(exception is String, isTrue);
    expect(exception.startsWith('Could not navigate to initial route.'), isTrue);
    expect(find.text('route "/"'), findsOneWidget);
    expect(find.text('route "/a"'), findsNothing);
    expect(find.text('route "/a/b"'), findsNothing);
328 329 330 331 332 333 334 335 336 337 338
    expect(find.text('route "/b"'), findsNothing);
  });

  testWidgets('Make sure initialRoute is only used the first time', (WidgetTester tester) async {
    final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
      '/': (BuildContext context) => const Text('route "/"'),
      '/a': (BuildContext context) => const Text('route "/a"'),
      '/b': (BuildContext context) => const Text('route "/b"'),
    };

    await tester.pumpWidget(
339
      MaterialApp(
340 341 342 343
        initialRoute: '/a',
        routes: routes,
      )
    );
344
    expect(find.text('route "/"'), findsOneWidget);
345 346 347
    expect(find.text('route "/a"'), findsOneWidget);
    expect(find.text('route "/b"'), findsNothing);

348
    // changing initialRoute has no effect
349
    await tester.pumpWidget(
350
      MaterialApp(
351 352 353 354
        initialRoute: '/b',
        routes: routes,
      )
    );
355
    expect(find.text('route "/"'), findsOneWidget);
356 357 358
    expect(find.text('route "/a"'), findsOneWidget);
    expect(find.text('route "/b"'), findsNothing);

359
    // removing it has no effect
360
    await tester.pumpWidget(MaterialApp(routes: routes));
361
    expect(find.text('route "/"'), findsOneWidget);
362 363 364
    expect(find.text('route "/a"'), findsOneWidget);
    expect(find.text('route "/b"'), findsNothing);
  });
365 366 367 368

  testWidgets('onGenerateRoute / onUnknownRoute', (WidgetTester tester) async {
    final List<String> log = <String>[];
    await tester.pumpWidget(
369
      MaterialApp(
370 371
        onGenerateRoute: (RouteSettings settings) {
          log.add('onGenerateRoute ${settings.name}');
372
          return null;
373 374 375
        },
        onUnknownRoute: (RouteSettings settings) {
          log.add('onUnknownRoute ${settings.name}');
376
          return null;
377 378 379 380 381 382
        },
      )
    );
    expect(tester.takeException(), isFlutterError);
    expect(log, <String>['onGenerateRoute /', 'onUnknownRoute /']);
  });
383 384 385

  testWidgets('Can get text scale from media query', (WidgetTester tester) async {
    double textScaleFactor;
386 387
    await tester.pumpWidget(MaterialApp(
      home: Builder(builder:(BuildContext context) {
388
        textScaleFactor = MediaQuery.of(context).textScaleFactor;
389
        return Container();
390 391 392 393 394
      }),
    ));
    expect(textScaleFactor, isNotNull);
    expect(textScaleFactor, equals(1.0));
  });
395 396

  testWidgets('MaterialApp.navigatorKey', (WidgetTester tester) async {
397 398
    final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>();
    await tester.pumpWidget(MaterialApp(
399 400 401 402
      navigatorKey: key,
      color: const Color(0xFF112233),
      home: const Placeholder(),
    ));
403
    expect(key.currentState, isInstanceOf<NavigatorState>());
404 405 406
    await tester.pumpWidget(const MaterialApp(
      color: Color(0xFF112233),
      home: Placeholder(),
407 408
    ));
    expect(key.currentState, isNull);
409
    await tester.pumpWidget(MaterialApp(
410 411 412 413
      navigatorKey: key,
      color: const Color(0xFF112233),
      home: const Placeholder(),
    ));
414
    expect(key.currentState, isInstanceOf<NavigatorState>());
415
  });
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437

  testWidgets('Has default material and cupertino localizations', (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        home: Builder(
          builder: (BuildContext context) {
            return Column(
              children: <Widget>[
                Text(MaterialLocalizations.of(context).selectAllButtonLabel),
                Text(CupertinoLocalizations.of(context).selectAllButtonLabel),
              ],
            );
          },
        ),
      ),
    );

    // Default US "select all" text.
    expect(find.text('SELECT ALL'), findsOneWidget);
    // Default Cupertino US "select all" text.
    expect(find.text('Select All'), findsOneWidget);
  });
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

  testWidgets('MaterialApp uses regular theme when platformBrightness is light', (WidgetTester tester) async {
    // Mock the Window to explicitly report a light platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
    binding.window.platformBrightnessTestValue = Brightness.light;

    ThemeData appliedTheme;

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          brightness: Brightness.light
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
            appliedTheme = Theme.of(context);
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.light);
  });

  testWidgets('MaterialApp uses light theme when platformBrightness is dark but no dark theme is provided', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
    binding.window.platformBrightnessTestValue = Brightness.dark;

    ThemeData appliedTheme;

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          brightness: Brightness.light
        ),
        home: Builder(
          builder: (BuildContext context) {
            appliedTheme = Theme.of(context);
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.light);
  });

  testWidgets('MaterialApp uses fallback light theme when platformBrightness is dark but no theme is provided at all', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
    binding.window.platformBrightnessTestValue = Brightness.dark;

    ThemeData appliedTheme;

    await tester.pumpWidget(
      MaterialApp(
        home: Builder(
          builder: (BuildContext context) {
            appliedTheme = Theme.of(context);
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.light);
  });

  testWidgets('MaterialApp uses fallback light theme when platformBrightness is light and a dark theme is provided', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
    binding.window.platformBrightnessTestValue = Brightness.light;

    ThemeData appliedTheme;

    await tester.pumpWidget(
      MaterialApp(
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
            appliedTheme = Theme.of(context);
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.light);
  });

  testWidgets('MaterialApp uses dark theme when platformBrightness is dark', (WidgetTester tester) async {
    // Mock the Window to explicitly report a dark platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
    binding.window.platformBrightnessTestValue = Brightness.dark;

    ThemeData appliedTheme;

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          brightness: Brightness.light
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
            appliedTheme = Theme.of(context);
            return const SizedBox();
          },
        ),
      ),
    );

    expect(appliedTheme.brightness, Brightness.dark);
  });

  testWidgets('MaterialApp switches themes when the Window platformBrightness changes.', (WidgetTester tester) async {
    // Mock the Window to explicitly report a light platformBrightness.
    final TestWidgetsFlutterBinding binding = tester.binding;
    binding.window.platformBrightnessTestValue = Brightness.light;

    ThemeData themeBeforeBrightnessChange;
    ThemeData themeAfterBrightnessChange;

    await tester.pumpWidget(
      MaterialApp(
        theme: ThemeData(
          brightness: Brightness.light
        ),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Builder(
          builder: (BuildContext context) {
            if (themeBeforeBrightnessChange == null) {
              themeBeforeBrightnessChange = Theme.of(context);
            } else {
              themeAfterBrightnessChange = Theme.of(context);
            }
            return const SizedBox();
          },
        ),
      ),
    );

    // Switch the platformBrightness from light to dark and pump the widget tree
    // to process changes.
    binding.window.platformBrightnessTestValue = Brightness.dark;
    await tester.pumpAndSettle();

    expect(themeBeforeBrightnessChange.brightness, Brightness.light);
    expect(themeAfterBrightnessChange.brightness, Brightness.dark);
  });
599
}