extension_test.dart 15 KB
Newer Older
1 2 3 4
// 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.

5
import 'package:flutter/material.dart';
6
import 'package:flutter/rendering.dart';
7
import 'package:flutter/scheduler.dart';
8
import 'package:flutter/widgets.dart';
9
import 'package:flutter_driver/flutter_driver.dart';
10
import 'package:flutter_driver/src/common/diagnostics_tree.dart';
11
import 'package:flutter_driver/src/common/find.dart';
12
import 'package:flutter_driver/src/common/geometry.dart';
13
import 'package:flutter_driver/src/common/request_data.dart';
14
import 'package:flutter_driver/src/common/text.dart';
15
import 'package:flutter_driver/src/extension/extension.dart';
16 17 18 19 20 21
import 'package:flutter_test/flutter_test.dart';

void main() {
  group('waitUntilNoTransientCallbacks', () {
    FlutterDriverExtension extension;
    Map<String, dynamic> result;
22 23
    int messageId = 0;
    final List<String> log = <String>[];
24 25 26

    setUp(() {
      result = null;
27
      extension = FlutterDriverExtension((String message) async { log.add(message); return (messageId += 1).toString(); }, false);
28 29 30
    });

    testWidgets('returns immediately when transient callback queue is empty', (WidgetTester tester) async {
31
      extension.call(const WaitUntilNoTransientCallbacks().serialize())
32 33 34
        .then<void>(expectAsync1((Map<String, dynamic> r) {
          result = r;
        }));
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

      await tester.idle();
      expect(
          result,
          <String, dynamic>{
            'isError': false,
            'response': null,
          },
      );
    });

    testWidgets('waits until no transient callbacks', (WidgetTester tester) async {
      SchedulerBinding.instance.scheduleFrameCallback((_) {
        // Intentionally blank. We only care about existence of a callback.
      });

51
      extension.call(const WaitUntilNoTransientCallbacks().serialize())
52 53 54
        .then<void>(expectAsync1((Map<String, dynamic> r) {
          result = r;
        }));
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
          result,
          <String, dynamic>{
            'isError': false,
            'response': null,
          },
      );
    });
70 71 72

    testWidgets('handler', (WidgetTester tester) async {
      expect(log, isEmpty);
73
      final dynamic result = RequestDataResult.fromJson((await extension.call(const RequestData('hello').serialize()))['response']);
74 75 76
      expect(log, <String>['hello']);
      expect(result.message, '1');
    });
77
  });
78 79 80 81

  group('getSemanticsId', () {
    FlutterDriverExtension extension;
    setUp(() {
82
      extension = FlutterDriverExtension((String arg) async => '', true);
83 84 85 86 87 88
    });

    testWidgets('works when semantics are enabled', (WidgetTester tester) async {
      final SemanticsHandle semantics = RendererBinding.instance.pipelineOwner.ensureSemantics();
      await tester.pumpWidget(
        const Text('hello', textDirection: TextDirection.ltr));
89

90
      final Map<String, Object> arguments = GetSemanticsId(const ByText('hello')).serialize();
91
      final GetSemanticsIdResult result = GetSemanticsIdResult.fromJson((await extension.call(arguments))['response']);
92

93 94 95 96 97 98 99
      expect(result.id, 1);
      semantics.dispose();
    });

    testWidgets('throws state error if no data is found', (WidgetTester tester) async {
      await tester.pumpWidget(
        const Text('hello', textDirection: TextDirection.ltr));
100

101
      final Map<String, Object> arguments = GetSemanticsId(const ByText('hello')).serialize();
102
      final Map<String, Object> response = await extension.call(arguments);
103

104 105
      expect(response['isError'], true);
      expect(response['response'], contains('Bad state: No semantics data found'));
106
    }, semanticsEnabled: false);
107 108 109 110

    testWidgets('throws state error multiple matches are found', (WidgetTester tester) async {
      final SemanticsHandle semantics = RendererBinding.instance.pipelineOwner.ensureSemantics();
      await tester.pumpWidget(
111
        Directionality(
112
          textDirection: TextDirection.ltr,
113
          child: ListView(children: const <Widget>[
114 115
            SizedBox(width: 100.0, height: 100.0, child: Text('hello')),
            SizedBox(width: 100.0, height: 100.0, child: Text('hello')),
116 117 118
          ]),
        ),
      );
119

120
      final Map<String, Object> arguments = GetSemanticsId(const ByText('hello')).serialize();
121
      final Map<String, Object> response = await extension.call(arguments);
122

123 124 125 126 127
      expect(response['isError'], true);
      expect(response['response'], contains('Bad state: Too many elements'));
      semantics.dispose();
    });
  });
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

  testWidgets('getOffset', (WidgetTester tester) async {
    final FlutterDriverExtension extension = FlutterDriverExtension((String arg) async => '', true);

    Future<Offset> getOffset(OffsetType offset) async {
      final Map<String, Object> arguments = GetOffset(ByValueKey(1), offset).serialize();
      final GetOffsetResult result = GetOffsetResult.fromJson((await extension.call(arguments))['response']);
      return Offset(result.dx, result.dy);
    }

    await tester.pumpWidget(
      Align(
        alignment: Alignment.topLeft,
        child: Transform.translate(
          offset: const Offset(40, 30),
          child: Container(
            key: const ValueKey<int>(1),
            width: 100,
            height: 120,
          ),
        ),
      ),
    );

    expect(await getOffset(OffsetType.topLeft), const Offset(40, 30));
    expect(await getOffset(OffsetType.topRight), const Offset(40 + 100.0, 30));
    expect(await getOffset(OffsetType.bottomLeft), const Offset(40, 30 + 120.0));
    expect(await getOffset(OffsetType.bottomRight), const Offset(40 + 100.0, 30 + 120.0));
    expect(await getOffset(OffsetType.center), const Offset(40 + (100 / 2), 30 + (120 / 2)));
  });
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 212 213 214 215 216 217 218 219 220 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 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

  testWidgets('descendant finder', (WidgetTester tester) async {
    flutterDriverLog.listen((LogRecord _) {}); // Silence logging.
    final FlutterDriverExtension extension = FlutterDriverExtension((String arg) async => '', true);

    Future<String> getDescendantText({ String of, bool matchRoot = false}) async {
      final Map<String, Object> arguments = GetText(Descendant(
        of: ByValueKey(of),
        matching: ByValueKey('text2'),
        matchRoot: matchRoot,
      ), timeout: const Duration(seconds: 1)).serialize();
      final Map<String, dynamic> result = await extension.call(arguments);
      if (result['isError']) {
        return null;
      }
      return GetTextResult.fromJson(result['response']).text;
    }

    await tester.pumpWidget(
        MaterialApp(
            home: Column(
              key: const ValueKey<String>('column'),
              children: const <Widget>[
                Text('Hello1', key: ValueKey<String>('text1')),
                Text('Hello2', key: ValueKey<String>('text2')),
                Text('Hello3', key: ValueKey<String>('text3')),
              ],
            )
        )
    );

    expect(await getDescendantText(of: 'column'), 'Hello2');
    expect(await getDescendantText(of: 'column', matchRoot: true), 'Hello2');
    expect(await getDescendantText(of: 'text2', matchRoot: true), 'Hello2');

    // Find nothing
    Future<String> result = getDescendantText(of: 'text1', matchRoot: true);
    await tester.pump(const Duration(seconds: 2));
    expect(await result, null);

    result = getDescendantText(of: 'text2');
    await tester.pump(const Duration(seconds: 2));
    expect(await result, null);
  });

  testWidgets('ancestor finder', (WidgetTester tester) async {
    flutterDriverLog.listen((LogRecord _) {}); // Silence logging.
    final FlutterDriverExtension extension = FlutterDriverExtension((String arg) async => '', true);

    Future<Offset> getAncestorTopLeft({ String of, String matching, bool matchRoot = false}) async {
      final Map<String, Object> arguments = GetOffset(Ancestor(
        of: ByValueKey(of),
        matching: ByValueKey(matching),
        matchRoot: matchRoot,
      ), OffsetType.topLeft, timeout: const Duration(seconds: 1)).serialize();
      final Map<String, dynamic> response = await extension.call(arguments);
      if (response['isError']) {
        return null;
      }
      final GetOffsetResult result = GetOffsetResult.fromJson(response['response']);
      return Offset(result.dx, result.dy);
    }

    await tester.pumpWidget(
        MaterialApp(
          home: Center(
              child: Container(
                key: const ValueKey<String>('parent'),
                height: 100,
                width: 100,
                child: Center(
                  child: Row(
                    children: <Widget>[
                      Container(
                        key: const ValueKey<String>('leftchild'),
                        width: 25,
                        height: 25,
                      ),
                      Container(
                        key: const ValueKey<String>('righttchild'),
                        width: 25,
                        height: 25,
                      ),
                    ],
                  ),
                ),
              )
          ),
        )
    );

    expect(
      await getAncestorTopLeft(of: 'leftchild', matching: 'parent'),
      const Offset((800 - 100) / 2, (600 - 100) / 2),
    );
    expect(
      await getAncestorTopLeft(of: 'leftchild', matching: 'parent', matchRoot: true),
      const Offset((800 - 100) / 2, (600 - 100) / 2),
    );
    expect(
      await getAncestorTopLeft(of: 'parent', matching: 'parent', matchRoot: true),
      const Offset((800 - 100) / 2, (600 - 100) / 2),
    );

    // Find nothing
    Future<Offset> result = getAncestorTopLeft(of: 'leftchild', matching: 'leftchild');
    await tester.pump(const Duration(seconds: 2));
    expect(await result, null);

    result = getAncestorTopLeft(of: 'leftchild', matching: 'righttchild');
    await tester.pump(const Duration(seconds: 2));
    expect(await result, null);
  });
271 272 273 274 275 276 277 278 279 280 281 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

  testWidgets('GetDiagnosticsTree', (WidgetTester tester) async {
    final FlutterDriverExtension extension = FlutterDriverExtension((String arg) async => '', true);

    Future<Map<String, Object>> getDiagnosticsTree(DiagnosticsType type, SerializableFinder finder, { int depth = 0, bool properties = true }) async {
      final Map<String, Object> arguments = GetDiagnosticsTree(finder, type, subtreeDepth: depth, includeProperties: properties).serialize();
      final DiagnosticsTreeResult result = DiagnosticsTreeResult((await extension.call(arguments))['response']);
      return result.json;
    }

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Center(
            child: const Text('Hello World', key: ValueKey<String>('Text'))
        ),
      ),
    );

    // Widget
    Map<String, Object> result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 0);
    expect(result['children'], isNull); // depth: 0
    expect(result['widgetRuntimeType'], 'Text');

    List<Map<String, Object>> properties = result['properties'];
    Map<String, Object> stringProperty = properties.singleWhere((Map<String, Object> property) => property['name'] == 'data');
    expect(stringProperty['description'], '"Hello World"');
    expect(stringProperty['propertyType'], 'String');

    result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 0, properties: false);
    expect(result['widgetRuntimeType'], 'Text');
    expect(result['properties'], isNull); // properties: false

    result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 1);
    List<Map<String, Object>> children = result['children'];
    expect(children.single['children'], isNull);

    result = await getDiagnosticsTree(DiagnosticsType.widget, ByValueKey('Text'), depth: 100);
    children = result['children'];
    expect(children.single['children'], isEmpty);

    // RenderObject
    result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 0);
    expect(result['children'], isNull); // depth: 0
    expect(result['properties'], isNotNull);
    expect(result['description'], startsWith('RenderParagraph'));

    result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 0, properties: false);
    expect(result['properties'], isNull); // properties: false
    expect(result['description'], startsWith('RenderParagraph'));

    result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 1);
    children = result['children'];
    final Map<String, Object> textSpan = children.single;
    expect(textSpan['description'], 'TextSpan');
    properties = textSpan['properties'];
    stringProperty = properties.singleWhere((Map<String, Object> property) => property['name'] == 'text');
    expect(stringProperty['description'], '"Hello World"');
    expect(stringProperty['propertyType'], 'String');
    expect(children.single['children'], isNull);

    result = await getDiagnosticsTree(DiagnosticsType.renderObject, ByValueKey('Text'), depth: 100);
    children = result['children'];
    expect(children.single['children'], isEmpty);
  });
336 337 338 339 340 341 342 343 344 345 346 347

  group('waitUntilFrameSync', () {
    FlutterDriverExtension extension;
    Map<String, dynamic> result;

    setUp(() {
      extension = FlutterDriverExtension((String arg) async => '', true);
      result = null;
    });

    testWidgets('returns immediately when frame is synced', (
        WidgetTester tester) async {
348
      extension.call(const WaitUntilNoPendingFrame().serialize())
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      await tester.idle();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
          'response': null,
        },
      );
    });

    testWidgets(
        'waits until no transient callbacks', (WidgetTester tester) async {
      SchedulerBinding.instance.scheduleFrameCallback((_) {
        // Intentionally blank. We only care about existence of a callback.
      });

369
      extension.call(const WaitUntilNoPendingFrame().serialize())
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
          'response': null,
        },
      );
    });

    testWidgets(
        'waits until no pending scheduled frame', (WidgetTester tester) async {
      SchedulerBinding.instance.scheduleFrame();

393
      extension.call(const WaitUntilNoPendingFrame().serialize())
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
          .then<void>(expectAsync1((Map<String, dynamic> r) {
        result = r;
      }));

      // Nothing should happen until the next frame.
      await tester.idle();
      expect(result, isNull);

      // NOW we should receive the result.
      await tester.pump();
      expect(
        result,
        <String, dynamic>{
          'isError': false,
          'response': null,
        },
      );
    });
  });
413
}