find.dart 15 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 'dart:convert';

7 8
import 'package:meta/meta.dart';

9 10 11
import 'error.dart';
import 'message.dart';

12
const List<Type> _supportedKeyValueTypes = <Type>[String, int];
13

14
DriverError _createInvalidKeyValueTypeError(String invalidType) {
15
  return DriverError('Unsupported key value type $invalidType. Flutter Driver only supports ${_supportedKeyValueTypes.join(", ")}');
16 17
}

18
/// A Flutter Driver command aimed at an object to be located by [finder].
19 20 21 22 23
///
/// Implementations must provide a concrete [kind]. If additional data is
/// required beyond the [finder] the implementation may override [serialize]
/// and add more keys to the returned map.
abstract class CommandWithTarget extends Command {
24
  /// Constructs this command given a [finder].
25
  CommandWithTarget(this.finder, {Duration timeout}) : super(timeout: timeout) {
26
    if (finder == null)
27
      throw DriverError('$runtimeType target cannot be null');
28 29
  }

30
  /// Deserializes this command from the value generated by [serialize].
31
  CommandWithTarget.deserialize(Map<String, String> json)
32 33
    : finder = SerializableFinder.deserialize(json),
      super.deserialize(json);
34

35 36 37 38 39 40 41 42 43 44 45
  /// Locates the object or objects targeted by this command.
  final SerializableFinder finder;

  /// This method is meant to be overridden if data in addition to [finder]
  /// is serialized to JSON.
  ///
  /// Example:
  ///
  ///     Map<String, String> toJson() => super.toJson()..addAll({
  ///       'foo': this.foo,
  ///     });
46
  @override
47 48
  Map<String, String> serialize() =>
      super.serialize()..addAll(finder.serialize());
49 50
}

51
/// A Flutter Driver command that waits until [finder] can locate the target.
52
class WaitFor extends CommandWithTarget {
53 54 55 56
  /// Creates a command that waits for the widget identified by [finder] to
  /// appear within the [timeout] amount of time.
  ///
  /// If [timeout] is not specified the command times out after 5 seconds.
57
  WaitFor(SerializableFinder finder, {Duration timeout})
58
    : super(finder, timeout: timeout);
59

60
  /// Deserializes this command from the value generated by [serialize].
61
  WaitFor.deserialize(Map<String, String> json) : super.deserialize(json);
62 63

  @override
64
  String get kind => 'waitFor';
65
}
66

67 68
/// The result of a [WaitFor] command.
class WaitForResult extends Result {
69 70 71
  /// Creates a [WaitForResult].
  const WaitForResult();

72 73
  /// Deserializes the result from JSON.
  static WaitForResult fromJson(Map<String, dynamic> json) {
74
    return const WaitForResult();
75 76
  }

77
  @override
78 79
  Map<String, dynamic> toJson() => <String, dynamic>{};
}
80

81 82
/// A Flutter Driver command that waits until [finder] can no longer locate the target.
class WaitForAbsent extends CommandWithTarget {
83 84 85 86 87
  /// Creates a command that waits for the widget identified by [finder] to
  /// disappear within the [timeout] amount of time.
  ///
  /// If [timeout] is not specified the command times out after 5 seconds.
  WaitForAbsent(SerializableFinder finder, {Duration timeout})
88
    : super(finder, timeout: timeout);
89

90
  /// Deserializes this command from the value generated by [serialize].
91 92
  WaitForAbsent.deserialize(Map<String, String> json) : super.deserialize(json);

93
  @override
94
  String get kind => 'waitForAbsent';
95 96
}

97 98
/// The result of a [WaitForAbsent] command.
class WaitForAbsentResult extends Result {
99 100 101
  /// Creates a [WaitForAbsentResult].
  const WaitForAbsentResult();

102 103
  /// Deserializes the result from JSON.
  static WaitForAbsentResult fromJson(Map<String, dynamic> json) {
104
    return const WaitForAbsentResult();
105 106 107 108 109 110
  }

  @override
  Map<String, dynamic> toJson() => <String, dynamic>{};
}

111 112
/// Base class for Flutter Driver finders, objects that describe how the driver
/// should search for elements.
113
abstract class SerializableFinder {
114 115 116 117

  /// A const constructor to allow subclasses to be const.
  const SerializableFinder();

118
  /// Identifies the type of finder to be used by the driver extension.
119
  String get finderType;
120

121 122 123 124 125 126 127 128 129
  /// Serializes common fields to JSON.
  ///
  /// Methods that override [serialize] are expected to call `super.serialize`
  /// and add more fields to the returned [Map].
  @mustCallSuper
  Map<String, String> serialize() => <String, String>{
    'finderType': finderType,
  };

130
  /// Deserializes a finder from JSON generated by [serialize].
131
  static SerializableFinder deserialize(Map<String, String> json) {
132
    final String finderType = json['finderType'];
133
    switch (finderType) {
134
      case 'ByType': return ByType.deserialize(json);
135 136
      case 'ByValueKey': return ByValueKey.deserialize(json);
      case 'ByTooltipMessage': return ByTooltipMessage.deserialize(json);
137
      case 'BySemanticsLabel': return BySemanticsLabel.deserialize(json);
138
      case 'ByText': return ByText.deserialize(json);
139
      case 'PageBack': return const PageBack();
140 141
      case 'Descendant': return Descendant.deserialize(json);
      case 'Ancestor': return Ancestor.deserialize(json);
142
    }
143
    throw DriverError('Unsupported search specification type $finderType');
144 145 146
  }
}

147
/// A Flutter Driver finder that finds widgets by tooltip text.
148
class ByTooltipMessage extends SerializableFinder {
149
  /// Creates a tooltip finder given the tooltip's message [text].
150
  const ByTooltipMessage(this.text);
151 152 153 154

  /// Tooltip message text.
  final String text;

155
  @override
156
  String get finderType => 'ByTooltipMessage';
157

158
  @override
pq's avatar
pq committed
159
  Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
160 161 162
    'text': text,
  });

163
  /// Deserializes the finder from JSON generated by [serialize].
164
  static ByTooltipMessage deserialize(Map<String, String> json) {
165
    return ByTooltipMessage(json['text']);
166 167 168
  }
}

169 170 171 172 173 174
/// A Flutter Driver finder that finds widgets by semantic label.
///
/// If the [label] property is a [String], the finder will try to find an exact
/// match. If it is a [RegExp], it will return true for [RegExp.hasMatch].
class BySemanticsLabel extends SerializableFinder {
  /// Creates a semantic label finder given the [label].
175
  const BySemanticsLabel(this.label);
176 177 178 179 180 181 182

  /// A [Pattern] matching the [Semantics.properties.label].
  ///
  /// If this is a [String], it will be treated as an exact match.
  final Pattern label;

  @override
183
  String get finderType => 'BySemanticsLabel';
184 185 186 187

  @override
  Map<String, String> serialize() {
    if (label is RegExp) {
188
      final RegExp regExp = label as RegExp;
189 190 191 192 193 194
      return super.serialize()..addAll(<String, String>{
        'label': regExp.pattern,
        'isRegExp': 'true',
      });
    } else {
      return super.serialize()..addAll(<String, String>{
195
        'label': label as String,
196 197 198 199 200 201 202 203 204 205 206
      });
    }
  }

  /// Deserializes the finder from JSON generated by [serialize].
  static BySemanticsLabel deserialize(Map<String, String> json) {
    final bool isRegExp = json['isRegExp'] == 'true';
    return BySemanticsLabel(isRegExp ? RegExp(json['label']) : json['label']);
  }
}

207 208
/// A Flutter Driver finder that finds widgets by [text] inside a [Text] or
/// [EditableText] widget.
209
class ByText extends SerializableFinder {
210
  /// Creates a text finder given the text.
211
  const ByText(this.text);
212

213
  /// The text that appears inside the [Text] or [EditableText] widget.
214 215
  final String text;

216
  @override
217
  String get finderType => 'ByText';
218

219
  @override
pq's avatar
pq committed
220
  Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
221 222 223
    'text': text,
  });

224
  /// Deserializes the finder from JSON generated by [serialize].
225
  static ByText deserialize(Map<String, String> json) {
226
    return ByText(json['text']);
227 228 229
  }
}

230
/// A Flutter Driver finder that finds widgets by `ValueKey`.
231
class ByValueKey extends SerializableFinder {
232
  /// Creates a finder given the key value.
233
  ByValueKey(this.keyValue)
234 235
      : keyValueString = '$keyValue',
        keyValueType = '${keyValue.runtimeType}' {
236
    if (!_supportedKeyValueTypes.contains(keyValue.runtimeType))
237
      throw _createInvalidKeyValueTypeError('$keyValue.runtimeType');
238 239 240 241 242 243 244 245 246 247 248 249 250
  }

  /// The true value of the key.
  final dynamic keyValue;

  /// Stringified value of the key (we can only send strings to the VM service)
  final String keyValueString;

  /// The type name of the key.
  ///
  /// May be one of "String", "int". The list of supported types may change.
  final String keyValueType;

251
  @override
252
  String get finderType => 'ByValueKey';
253

254
  @override
pq's avatar
pq committed
255
  Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
256 257
    'keyValueString': keyValueString,
    'keyValueType': keyValueType,
258
  });
259

260
  /// Deserializes the finder from JSON generated by [serialize].
261
  static ByValueKey deserialize(Map<String, String> json) {
262 263
    final String keyValueString = json['keyValueString'];
    final String keyValueType = json['keyValueType'];
264
    switch (keyValueType) {
265
      case 'int':
266
        return ByValueKey(int.parse(keyValueString));
267
      case 'String':
268
        return ByValueKey(keyValueString);
269
      default:
270
        throw _createInvalidKeyValueTypeError(keyValueType);
271 272 273 274
    }
  }
}

275
/// A Flutter Driver finder that finds widgets by their [runtimeType].
276 277
class ByType extends SerializableFinder {
  /// Creates a finder that given the runtime type in string form.
278
  const ByType(this.type);
279 280 281 282

  /// The widget's [runtimeType], in string form.
  final String type;

283
  @override
284
  String get finderType => 'ByType';
285

286 287 288 289 290 291 292
  @override
  Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
    'type': type,
  });

  /// Deserializes the finder from JSON generated by [serialize].
  static ByType deserialize(Map<String, String> json) {
293
    return ByType(json['type']);
294 295
  }
}
296

297 298 299 300 301 302 303
/// A Flutter Driver finder that finds the back button on the page's Material
/// or Cupertino scaffold.
///
/// See also:
///
///  * [WidgetTester.pageBack], for a similar functionality in widget tests.
class PageBack extends SerializableFinder {
304 305 306
  /// Creates a [PageBack].
  const PageBack();

307 308 309 310
  @override
  String get finderType => 'PageBack';
}

311 312 313 314 315 316 317 318 319 320 321
/// A Flutter Driver finder that finds a descendant of [of] that matches
/// [matching].
///
/// If the `matchRoot` argument is true, then the widget specified by [of] will
/// be considered for a match. The argument defaults to false.
class Descendant extends SerializableFinder {
  /// Creates a descendant finder.
  const Descendant({
    @required this.of,
    @required this.matching,
    this.matchRoot = false,
322
    this.firstMatchOnly = false,
323 324 325 326 327 328 329 330 331 332 333
  });

  /// The finder specifying the widget of which the descendant is to be found.
  final SerializableFinder of;

  /// Only a descendant of [of] matching this finder will be found.
  final SerializableFinder matching;

  /// Whether the widget matching [of] will be considered for a match.
  final bool matchRoot;

334 335 336
  /// If true then only the first descendant matching `matching` will be returned.
  final bool firstMatchOnly;

337 338 339 340 341 342 343
  @override
  String get finderType => 'Descendant';

  @override
  Map<String, String> serialize() {
    return super.serialize()
        ..addAll(<String, String>{
344 345
          'of': jsonEncode(of.serialize()),
          'matching': jsonEncode(matching.serialize()),
346
          'matchRoot': matchRoot ? 'true' : 'false',
347
          'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
348 349 350 351 352
        });
  }

  /// Deserializes the finder from JSON generated by [serialize].
  static Descendant deserialize(Map<String, String> json) {
353
    final Map<String, String> jsonOfMatcher =
354
        Map<String, String>.from(jsonDecode(json['of']) as Map<String, dynamic>);
355
    final Map<String, String> jsonMatchingMatcher =
356
        Map<String, String>.from(jsonDecode(json['matching']) as Map<String, dynamic>);
357
    return Descendant(
358 359 360 361
      of: SerializableFinder.deserialize(jsonOfMatcher),
      matching: SerializableFinder.deserialize(jsonMatchingMatcher),
      matchRoot: json['matchRoot'] == 'true',
      firstMatchOnly: json['firstMatchOnly'] == 'true',
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    );
  }
}

/// A Flutter Driver finder that finds an ancestor of [of] that matches
/// [matching].
///
/// If the `matchRoot` argument is true, then the widget specified by [of] will
/// be considered for a match. The argument defaults to false.
class Ancestor extends SerializableFinder {
  /// Creates an ancestor finder.
  const Ancestor({
    @required this.of,
    @required this.matching,
    this.matchRoot = false,
377
    this.firstMatchOnly = false,
378 379 380 381 382 383 384 385 386 387 388
  });

  /// The finder specifying the widget of which the ancestor is to be found.
  final SerializableFinder of;

  /// Only an ancestor of [of] matching this finder will be found.
  final SerializableFinder matching;

  /// Whether the widget matching [of] will be considered for a match.
  final bool matchRoot;

389 390 391
  /// If true then only the first ancestor matching `matching` will be returned.
  final bool firstMatchOnly;

392 393 394 395 396 397 398
  @override
  String get finderType => 'Ancestor';

  @override
  Map<String, String> serialize() {
    return super.serialize()
      ..addAll(<String, String>{
399 400
        'of': jsonEncode(of.serialize()),
        'matching': jsonEncode(matching.serialize()),
401
        'matchRoot': matchRoot ? 'true' : 'false',
402
        'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
403 404 405 406 407
      });
  }

  /// Deserializes the finder from JSON generated by [serialize].
  static Ancestor deserialize(Map<String, String> json) {
408
    final Map<String, String> jsonOfMatcher =
409
        Map<String, String>.from(jsonDecode(json['of']) as Map<String, dynamic>);
410
    final Map<String, String> jsonMatchingMatcher =
411
        Map<String, String>.from(jsonDecode(json['matching']) as Map<String, dynamic>);
412
    return Ancestor(
413 414 415 416
      of: SerializableFinder.deserialize(jsonOfMatcher),
      matching: SerializableFinder.deserialize(jsonMatchingMatcher),
      matchRoot: json['matchRoot'] == 'true',
      firstMatchOnly: json['firstMatchOnly'] == 'true',
417 418 419 420
    );
  }
}

421 422 423 424 425 426
/// A Flutter driver command that retrieves a semantics id using a specified finder.
///
/// This command requires assertions to be enabled on the device.
///
/// If the object returned by the finder does not have its own semantics node,
/// then the semantics node of the first ancestor is returned instead.
427
///
428 429 430 431 432 433 434 435 436 437
/// Throws an error if a finder returns multiple objects or if there are no
/// semantics nodes.
///
/// Semantics must be enabled to use this method, either using a platform
/// specific shell command or [FlutterDriver.setSemantics].
class GetSemanticsId extends CommandWithTarget {

  /// Creates a command which finds a Widget and then looks up the semantic id.
  GetSemanticsId(SerializableFinder finder, {Duration timeout}) : super(finder, timeout: timeout);

438
  /// Creates a command from a JSON map.
439
  GetSemanticsId.deserialize(Map<String, String> json)
440
    : super.deserialize(json);
441 442 443 444 445 446 447 448 449

  @override
  String get kind => 'get_semantics_id';
}

/// The result of a [GetSemanticsId] command.
class GetSemanticsIdResult extends Result {

  /// Creates a new [GetSemanticsId] result.
450
  const GetSemanticsIdResult(this.id);
451 452 453 454 455 456

  /// The semantics id of the node;
  final int id;

  /// Deserializes this result from JSON.
  static GetSemanticsIdResult fromJson(Map<String, dynamic> json) {
457
    return GetSemanticsIdResult(json['id'] as int);
458 459 460 461 462
  }

  @override
  Map<String, dynamic> toJson() => <String, dynamic>{'id': id};
}