date_picker_test.dart 10.7 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
import 'package:intl/intl.dart' as intl;

7 8 9 10 11
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
12 13 14
  late DateTime firstDate;
  late DateTime lastDate;
  late DateTime initialDate;
15 16

  setUp(() {
17 18 19
    firstDate = DateTime(2001, DateTime.january, 1);
    lastDate = DateTime(2031, DateTime.december, 31);
    initialDate = DateTime(2016, DateTime.january, 15);
20 21
  });

22
  group(CalendarDatePicker, () {
23
    final intl.NumberFormat arabicNumbers = intl.NumberFormat('0', 'ar');
24 25 26 27 28
    final Map<Locale, Map<String, dynamic>> testLocales = <Locale, Map<String, dynamic>>{
      // Tests the default.
      const Locale('en', 'US'): <String, dynamic>{
        'textDirection': TextDirection.ltr,
        'expectedDaysOfWeek': <String>['S', 'M', 'T', 'W', 'T', 'F', 'S'],
29
        'expectedDaysOfMonth': List<String>.generate(30, (int i) => '${i + 1}'),
30 31 32 33 34 35
        'expectedMonthYearHeader': 'September 2017',
      },
      // Tests a different first day of week.
      const Locale('ru', 'RU'): <String, dynamic>{
        'textDirection': TextDirection.ltr,
        'expectedDaysOfWeek': <String>['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'],
36
        'expectedDaysOfMonth': List<String>.generate(30, (int i) => '${i + 1}'),
37 38
        'expectedMonthYearHeader': 'сентябрь 2017 г.',
      },
39 40 41
      const Locale('ro', 'RO'): <String, dynamic>{
        'textDirection': TextDirection.ltr,
        'expectedDaysOfWeek': <String>['D', 'L', 'M', 'M', 'J', 'V', 'S'],
42
        'expectedDaysOfMonth': List<String>.generate(30, (int i) => '${i + 1}'),
43 44
        'expectedMonthYearHeader': 'septembrie 2017',
      },
45 46 47 48
      // Tests RTL.
      const Locale('ar', 'AR'): <String, dynamic>{
        'textDirection': TextDirection.rtl,
        'expectedDaysOfWeek': <String>['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
49
        'expectedDaysOfMonth': List<String>.generate(30, (int i) => arabicNumbers.format(i + 1)),
50
        'expectedMonthYearHeader': 'سبتمبر ٢٠١٧',
51 52 53
      },
    };

54
    for (final Locale locale in testLocales.keys) {
55
      testWidgets('shows dates for $locale', (WidgetTester tester) async {
56 57 58 59
        final List<String> expectedDaysOfWeek = testLocales[locale]!['expectedDaysOfWeek'] as List<String>;
        final List<String> expectedDaysOfMonth = testLocales[locale]!['expectedDaysOfMonth'] as List<String>;
        final String expectedMonthYearHeader = testLocales[locale]!['expectedMonthYearHeader'] as String;
        final TextDirection textDirection = testLocales[locale]!['textDirection'] as TextDirection;
60
        final DateTime baseDate = DateTime(2017, 9, 27);
61

62 63
        await _pumpBoilerplate(tester, CalendarDatePicker(
          initialDate: baseDate,
64 65
          firstDate: baseDate.subtract(const Duration(days: 90)),
          lastDate: baseDate.add(const Duration(days: 90)),
66
          onDateChanged: (DateTime newValue) {},
67 68 69 70
        ), locale: locale, textDirection: textDirection);

        expect(find.text(expectedMonthYearHeader), findsOneWidget);

71
        for (final String dayOfWeek in expectedDaysOfWeek) {
72
          expect(find.text(dayOfWeek), findsWidgets);
73
        }
74

75
        Offset? previousCellOffset;
76
        for (final String dayOfMonth in expectedDaysOfMonth) {
77 78 79 80 81 82 83 84 85 86 87 88 89 90
          final Finder dayCell = find.descendant(of: find.byType(GridView), matching: find.text(dayOfMonth));
          expect(dayCell, findsOneWidget);

          // Check that cells are correctly positioned relative to each other,
          // taking text direction into account.
          final Offset offset = tester.getCenter(dayCell);
          if (previousCellOffset != null) {
            if (textDirection == TextDirection.ltr) {
              expect(offset.dx > previousCellOffset.dx && offset.dy == previousCellOffset.dy || offset.dy > previousCellOffset.dy, true);
            } else {
              expect(offset.dx < previousCellOffset.dx && offset.dy == previousCellOffset.dy || offset.dy > previousCellOffset.dy, true);
            }
          }
          previousCellOffset = offset;
91
        }
92 93 94 95 96
      });
    }
  });

  testWidgets('locale parameter overrides ambient locale', (WidgetTester tester) async {
97
    await tester.pumpWidget(MaterialApp(
98 99
      locale: const Locale('en', 'US'),
      supportedLocales: const <Locale>[
100 101
        Locale('en', 'US'),
        Locale('fr', 'CA'),
102 103
      ],
      localizationsDelegates: GlobalMaterialLocalizations.delegates,
104 105
      home: Material(
        child: Builder(
106
          builder: (BuildContext context) {
107
            return TextButton(
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
              onPressed: () async {
                await showDatePicker(
                  context: context,
                  initialDate: initialDate,
                  firstDate: firstDate,
                  lastDate: lastDate,
                  locale: const Locale('fr', 'CA'),
                );
              },
              child: const Text('X'),
            );
          },
        ),
      ),
    ));

    await tester.tap(find.text('X'));
    await tester.pumpAndSettle(const Duration(seconds: 1));

127
    final Element picker = tester.element(find.byType(CalendarDatePicker));
128
    expect(
129
      Localizations.localeOf(picker),
130 131 132 133
      const Locale('fr', 'CA'),
    );

    expect(
134
      Directionality.of(picker),
135 136 137 138 139 140 141
      TextDirection.ltr,
    );

    await tester.tap(find.text('ANNULER'));
  });

  testWidgets('textDirection parameter overrides ambient textDirection', (WidgetTester tester) async {
142
    await tester.pumpWidget(MaterialApp(
143 144
      locale: const Locale('en', 'US'),
      supportedLocales: const <Locale>[
145
        Locale('en', 'US'),
146
      ],
147 148
      home: Material(
        child: Builder(
149
          builder: (BuildContext context) {
150
            return TextButton(
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
              onPressed: () async {
                await showDatePicker(
                  context: context,
                  initialDate: initialDate,
                  firstDate: firstDate,
                  lastDate: lastDate,
                  textDirection: TextDirection.rtl,
                );
              },
              child: const Text('X'),
            );
          },
        ),
      ),
    ));

    await tester.tap(find.text('X'));
    await tester.pumpAndSettle(const Duration(seconds: 1));

170
    final Element picker = tester.element(find.byType(CalendarDatePicker));
171
    expect(
172
      Directionality.of(picker),
173 174 175 176 177 178
      TextDirection.rtl,
    );

    await tester.tap(find.text('CANCEL'));
  });

Josh Soref's avatar
Josh Soref committed
179
  testWidgets('textDirection parameter takes precedence over locale parameter', (WidgetTester tester) async {
180
    await tester.pumpWidget(MaterialApp(
181 182
      locale: const Locale('en', 'US'),
      supportedLocales: const <Locale>[
183 184
        Locale('en', 'US'),
        Locale('fr', 'CA'),
185 186
      ],
      localizationsDelegates: GlobalMaterialLocalizations.delegates,
187 188
      home: Material(
        child: Builder(
189
          builder: (BuildContext context) {
190
            return TextButton(
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
              onPressed: () async {
                await showDatePicker(
                  context: context,
                  initialDate: initialDate,
                  firstDate: firstDate,
                  lastDate: lastDate,
                  locale: const Locale('fr', 'CA'),
                  textDirection: TextDirection.rtl,
                );
              },
              child: const Text('X'),
            );
          },
        ),
      ),
    ));

    await tester.tap(find.text('X'));
    await tester.pumpAndSettle(const Duration(seconds: 1));

211
    final Element picker = tester.element(find.byType(CalendarDatePicker));
212
    expect(
213
      Localizations.localeOf(picker),
214 215 216 217
      const Locale('fr', 'CA'),
    );

    expect(
218
      Directionality.of(picker),
219 220 221 222 223
      TextDirection.rtl,
    );

    await tester.tap(find.text('ANNULER'));
  });
224

225
  group("locale fonts don't overflow layout", () {
226 227 228 229 230 231 232 233 234
    // Test screen layouts in various locales to ensure the fonts used
    // don't overflow the layout

    // Common screen size roughly based on a Pixel 1
    const Size kCommonScreenSizePortrait = Size(1070, 1770);
    const Size kCommonScreenSizeLandscape = Size(1770, 1070);

    Future<void> _showPicker(WidgetTester tester, Locale locale, Size size) async {
      tester.binding.window.physicalSizeTestValue = size;
235
      addTearDown(tester.binding.window.clearPhysicalSizeTestValue);
236
      tester.binding.window.devicePixelRatioTestValue = 1.0;
237
      addTearDown(tester.binding.window.clearDevicePixelRatioTestValue);
238 239 240 241 242 243 244
      await tester.pumpWidget(
        MaterialApp(
          home: Builder(
            builder: (BuildContext context) {
              return Localizations(
                locale: locale,
                delegates: GlobalMaterialLocalizations.delegates,
245
                child: TextButton(
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
                  child: const Text('X'),
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      initialDate: initialDate,
                      firstDate: firstDate,
                      lastDate: lastDate,
                    );
                  },
                ),
              );
            },
          ),
        )
      );
      await tester.tap(find.text('X'));
      await tester.pumpAndSettle();
    }

    // Regression test for https://github.com/flutter/flutter/issues/20171
    testWidgets('common screen size - portrait - Chinese', (WidgetTester tester) async {
      await _showPicker(tester, const Locale('zh', 'CN'), kCommonScreenSizePortrait);
      expect(tester.takeException(), isNull);
    });

    testWidgets('common screen size - landscape - Chinese', (WidgetTester tester) async {
      await _showPicker(tester, const Locale('zh', 'CN'), kCommonScreenSizeLandscape);
      expect(tester.takeException(), isNull);
    });

    testWidgets('common screen size - portrait - Japanese', (WidgetTester tester) async {
      await _showPicker(tester, const Locale('ja', 'JA'), kCommonScreenSizePortrait);
      expect(tester.takeException(), isNull);
    });

    testWidgets('common screen size - landscape - Japanese', (WidgetTester tester) async {
      await _showPicker(tester, const Locale('ja', 'JA'), kCommonScreenSizeLandscape);
      expect(tester.takeException(), isNull);
    });
  });

287 288
}

289
Future<void> _pumpBoilerplate(
290 291 292
  WidgetTester tester,
  Widget child, {
  Locale locale = const Locale('en', 'US'),
293
  TextDirection textDirection = TextDirection.ltr,
294
}) async {
295 296 297 298 299 300 301 302 303 304
  await tester.pumpWidget(MaterialApp(
    home: Directionality(
      textDirection: TextDirection.ltr,
      child: Localizations(
        locale: locale,
        delegates: GlobalMaterialLocalizations.delegates,
        child: Material(
          child: child,
        ),
      ),
305 306 307
    ),
  ));
}