find.dart 15.4 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 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/// A factory for deserializing [Finder]s.
mixin DeserializeFinderFactory {
  /// Deserializes the finder from JSON generated by [SerializableFinder.serialize].
  SerializableFinder deserializeFinder(Map<String, String> json) {
    final String finderType = json['finderType'];
    switch (finderType) {
      case 'ByType': return ByType.deserialize(json);
      case 'ByValueKey': return ByValueKey.deserialize(json);
      case 'ByTooltipMessage': return ByTooltipMessage.deserialize(json);
      case 'BySemanticsLabel': return BySemanticsLabel.deserialize(json);
      case 'ByText': return ByText.deserialize(json);
      case 'PageBack': return const PageBack();
      case 'Descendant': return Descendant.deserialize(json, this);
      case 'Ancestor': return Ancestor.deserialize(json, this);
    }
    throw DriverError('Unsupported search specification type $finderType');
  }
}

31
const List<Type> _supportedKeyValueTypes = <Type>[String, int];
32

33
DriverError _createInvalidKeyValueTypeError(String invalidType) {
34
  return DriverError('Unsupported key value type $invalidType. Flutter Driver only supports ${_supportedKeyValueTypes.join(", ")}');
35 36
}

37
/// A Flutter Driver command aimed at an object to be located by [finder].
38 39 40 41 42
///
/// 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 {
43
  /// Constructs this command given a [finder].
44
  CommandWithTarget(this.finder, {Duration timeout}) : super(timeout: timeout) {
45
    if (finder == null)
46
      throw DriverError('$runtimeType target cannot be null');
47 48
  }

49
  /// Deserializes this command from the value generated by [serialize].
50 51
  CommandWithTarget.deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory)
    : finder = finderFactory.deserializeFinder(json),
52
      super.deserialize(json);
53

54 55 56 57 58 59 60 61 62 63 64
  /// 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,
  ///     });
65
  @override
66 67
  Map<String, String> serialize() =>
      super.serialize()..addAll(finder.serialize());
68 69
}

70
/// A Flutter Driver command that waits until [finder] can locate the target.
71
class WaitFor extends CommandWithTarget {
72 73 74
  /// Creates a command that waits for the widget identified by [finder] to
  /// appear within the [timeout] amount of time.
  ///
75
  /// If [timeout] is not specified, the command defaults to no timeout.
76
  WaitFor(SerializableFinder finder, {Duration timeout})
77
    : super(finder, timeout: timeout);
78

79
  /// Deserializes this command from the value generated by [serialize].
80
  WaitFor.deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory) : super.deserialize(json, finderFactory);
81 82

  @override
83
  String get kind => 'waitFor';
84
}
85

86 87
/// The result of a [WaitFor] command.
class WaitForResult extends Result {
88 89 90
  /// Creates a [WaitForResult].
  const WaitForResult();

91 92
  /// Deserializes the result from JSON.
  static WaitForResult fromJson(Map<String, dynamic> json) {
93
    return const WaitForResult();
94 95
  }

96
  @override
97 98
  Map<String, dynamic> toJson() => <String, dynamic>{};
}
99

100 101
/// A Flutter Driver command that waits until [finder] can no longer locate the target.
class WaitForAbsent extends CommandWithTarget {
102 103 104
  /// Creates a command that waits for the widget identified by [finder] to
  /// disappear within the [timeout] amount of time.
  ///
105
  /// If [timeout] is not specified, the command defaults to no timeout.
106
  WaitForAbsent(SerializableFinder finder, {Duration timeout})
107
    : super(finder, timeout: timeout);
108

109
  /// Deserializes this command from the value generated by [serialize].
110
  WaitForAbsent.deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory) : super.deserialize(json, finderFactory);
111

112
  @override
113
  String get kind => 'waitForAbsent';
114 115
}

116 117
/// The result of a [WaitForAbsent] command.
class WaitForAbsentResult extends Result {
118 119 120
  /// Creates a [WaitForAbsentResult].
  const WaitForAbsentResult();

121 122
  /// Deserializes the result from JSON.
  static WaitForAbsentResult fromJson(Map<String, dynamic> json) {
123
    return const WaitForAbsentResult();
124 125 126 127 128 129
  }

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

130 131
/// Base class for Flutter Driver finders, objects that describe how the driver
/// should search for elements.
132
abstract class SerializableFinder {
133 134 135 136

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

137
  /// Identifies the type of finder to be used by the driver extension.
138
  String get finderType;
139

140 141 142 143 144 145 146 147
  /// 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,
  };
148 149
}

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

  /// Tooltip message text.
  final String text;

158
  @override
159
  String get finderType => 'ByTooltipMessage';
160

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

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

172 173 174 175 176 177
/// 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].
178
  const BySemanticsLabel(this.label);
179

180
  /// A [Pattern] matching the label of a [SemanticsNode].
181 182 183 184 185
  ///
  /// If this is a [String], it will be treated as an exact match.
  final Pattern label;

  @override
186
  String get finderType => 'BySemanticsLabel';
187 188 189 190

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

  /// 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']);
  }
}

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

216
  /// The text that appears inside the [Text] or [EditableText] widget.
217 218
  final String text;

219
  @override
220
  String get finderType => 'ByText';
221

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

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

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

  /// 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;

254
  @override
255
  String get finderType => 'ByValueKey';
256

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

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

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

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

286
  @override
287
  String get finderType => 'ByType';
288

289 290 291 292 293 294 295
  @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) {
296
    return ByType(json['type']);
297 298
  }
}
299

300 301 302 303 304 305 306
/// 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 {
307 308 309
  /// Creates a [PageBack].
  const PageBack();

310 311 312 313
  @override
  String get finderType => 'PageBack';
}

314 315 316 317 318 319 320 321 322 323 324
/// 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,
325
    this.firstMatchOnly = false,
326 327 328 329 330 331 332 333 334 335 336
  });

  /// 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;

337 338 339
  /// If true then only the first descendant matching `matching` will be returned.
  final bool firstMatchOnly;

340 341 342 343 344 345 346
  @override
  String get finderType => 'Descendant';

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

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

/// 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,
380
    this.firstMatchOnly = false,
381 382 383 384 385 386 387 388 389 390 391
  });

  /// 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;

392 393 394
  /// If true then only the first ancestor matching `matching` will be returned.
  final bool firstMatchOnly;

395 396 397 398 399 400 401
  @override
  String get finderType => 'Ancestor';

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

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

424 425 426 427 428 429
/// 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.
430
///
431 432 433 434 435 436 437 438 439 440
/// 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);

441
  /// Creates a command from a JSON map.
442 443
  GetSemanticsId.deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory)
    : super.deserialize(json, finderFactory);
444 445 446 447 448 449 450 451 452

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

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

  /// Creates a new [GetSemanticsId] result.
453
  const GetSemanticsIdResult(this.id);
454

455
  /// The semantics id of the node.
456 457 458 459
  final int id;

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

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