find.dart 13.8 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
import 'deserialization_factory.dart';
10 11 12
import 'error.dart';
import 'message.dart';

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

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

19
/// A Flutter Driver command aimed at an object to be located by [finder].
20 21 22 23 24
///
/// 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 {
25
  /// Constructs this command given a [finder].
26
  CommandWithTarget(this.finder, {Duration? timeout}) : super(timeout: timeout) {
27
    assert(finder != null, '$runtimeType target cannot be null');
28 29
  }

30
  /// Deserializes this command from the value generated by [serialize].
31 32
  CommandWithTarget.deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory)
    : finder = finderFactory.deserializeFinder(json),
33
      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
  /// Creates a command that waits for the widget identified by [finder] to
  /// appear within the [timeout] amount of time.
  ///
56
  /// If [timeout] is not specified, the command defaults to no timeout.
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, DeserializeFinderFactory finderFactory) : super.deserialize(json, finderFactory);
62 63

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

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

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

79
  @override
80
  String get kind => 'waitForAbsent';
81 82
}

83 84
/// Base class for Flutter Driver finders, objects that describe how the driver
/// should search for elements.
85
abstract class SerializableFinder {
86 87 88 89

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

90
  /// Identifies the type of finder to be used by the driver extension.
91
  String get finderType;
92

93 94 95 96 97 98 99 100
  /// 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,
  };
101 102
}

103
/// A Flutter Driver finder that finds widgets by tooltip text.
104
class ByTooltipMessage extends SerializableFinder {
105
  /// Creates a tooltip finder given the tooltip's message [text].
106
  const ByTooltipMessage(this.text);
107 108 109 110

  /// Tooltip message text.
  final String text;

111
  @override
112
  String get finderType => 'ByTooltipMessage';
113

114
  @override
pq's avatar
pq committed
115
  Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
116 117 118
    'text': text,
  });

119
  /// Deserializes the finder from JSON generated by [serialize].
120
  static ByTooltipMessage deserialize(Map<String, String> json) {
121
    return ByTooltipMessage(json['text']!);
122 123 124
  }
}

125 126 127 128 129 130
/// 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].
131
  const BySemanticsLabel(this.label);
132

133
  /// A [Pattern] matching the label of a [SemanticsNode].
134 135 136 137 138
  ///
  /// If this is a [String], it will be treated as an exact match.
  final Pattern label;

  @override
139
  String get finderType => 'BySemanticsLabel';
140 141 142 143

  @override
  Map<String, String> serialize() {
    if (label is RegExp) {
144
      final RegExp regExp = label as RegExp;
145 146 147 148 149 150
      return super.serialize()..addAll(<String, String>{
        'label': regExp.pattern,
        'isRegExp': 'true',
      });
    } else {
      return super.serialize()..addAll(<String, String>{
151
        'label': label as String,
152 153 154 155 156 157 158
      });
    }
  }

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

163 164
/// A Flutter Driver finder that finds widgets by [text] inside a [Text] or
/// [EditableText] widget.
165
class ByText extends SerializableFinder {
166
  /// Creates a text finder given the text.
167
  const ByText(this.text);
168

169
  /// The text that appears inside the [Text] or [EditableText] widget.
170 171
  final String text;

172
  @override
173
  String get finderType => 'ByText';
174

175
  @override
pq's avatar
pq committed
176
  Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
177 178 179
    'text': text,
  });

180
  /// Deserializes the finder from JSON generated by [serialize].
181
  static ByText deserialize(Map<String, String> json) {
182
    return ByText(json['text']!);
183 184 185
  }
}

186
/// A Flutter Driver finder that finds widgets by `ValueKey`.
187
class ByValueKey extends SerializableFinder {
188
  /// Creates a finder given the key value.
189
  ByValueKey(this.keyValue)
190 191
      : keyValueString = '$keyValue',
        keyValueType = '${keyValue.runtimeType}' {
192
    if (!_supportedKeyValueTypes.contains(keyValue.runtimeType))
193
      throw _createInvalidKeyValueTypeError('$keyValue.runtimeType');
194 195 196 197 198 199 200 201 202 203 204 205 206
  }

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

207
  @override
208
  String get finderType => 'ByValueKey';
209

210
  @override
pq's avatar
pq committed
211
  Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
212 213
    'keyValueString': keyValueString,
    'keyValueType': keyValueType,
214
  });
215

216
  /// Deserializes the finder from JSON generated by [serialize].
217
  static ByValueKey deserialize(Map<String, String> json) {
218 219
    final String keyValueString = json['keyValueString']!;
    final String keyValueType = json['keyValueType']!;
220
    switch (keyValueType) {
221
      case 'int':
222
        return ByValueKey(int.parse(keyValueString));
223
      case 'String':
224
        return ByValueKey(keyValueString);
225
      default:
226
        throw _createInvalidKeyValueTypeError(keyValueType);
227 228 229 230
    }
  }
}

231
/// A Flutter Driver finder that finds widgets by their [runtimeType].
232 233
class ByType extends SerializableFinder {
  /// Creates a finder that given the runtime type in string form.
234
  const ByType(this.type);
235 236 237 238

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

239
  @override
240
  String get finderType => 'ByType';
241

242 243 244 245 246 247 248
  @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) {
249
    return ByType(json['type']!);
250 251
  }
}
252

253 254 255 256 257 258 259
/// 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 {
260 261 262
  /// Creates a [PageBack].
  const PageBack();

263 264 265 266
  @override
  String get finderType => 'PageBack';
}

267 268 269 270 271 272 273 274
/// 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({
275 276
    required this.of,
    required this.matching,
277
    this.matchRoot = false,
278
    this.firstMatchOnly = false,
279 280 281 282 283 284 285 286 287 288 289
  });

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

290 291 292
  /// If true then only the first descendant matching `matching` will be returned.
  final bool firstMatchOnly;

293 294 295 296 297 298 299
  @override
  String get finderType => 'Descendant';

  @override
  Map<String, String> serialize() {
    return super.serialize()
        ..addAll(<String, String>{
300 301
          'of': jsonEncode(of.serialize()),
          'matching': jsonEncode(matching.serialize()),
302
          'matchRoot': matchRoot ? 'true' : 'false',
303
          'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
304 305 306 307
        });
  }

  /// Deserializes the finder from JSON generated by [serialize].
308
  static Descendant deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory) {
309
    final Map<String, String> jsonOfMatcher =
310
        Map<String, String>.from(jsonDecode(json['of']!) as Map<String, dynamic>);
311
    final Map<String, String> jsonMatchingMatcher =
312
        Map<String, String>.from(jsonDecode(json['matching']!) as Map<String, dynamic>);
313
    return Descendant(
314 315
      of: finderFactory.deserializeFinder(jsonOfMatcher),
      matching: finderFactory.deserializeFinder(jsonMatchingMatcher),
316 317
      matchRoot: json['matchRoot'] == 'true',
      firstMatchOnly: json['firstMatchOnly'] == 'true',
318 319 320 321 322 323 324 325 326 327 328 329
    );
  }
}

/// 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({
330 331
    required this.of,
    required this.matching,
332
    this.matchRoot = false,
333
    this.firstMatchOnly = false,
334 335 336 337 338 339 340 341 342 343 344
  });

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

345 346 347
  /// If true then only the first ancestor matching `matching` will be returned.
  final bool firstMatchOnly;

348 349 350 351 352 353 354
  @override
  String get finderType => 'Ancestor';

  @override
  Map<String, String> serialize() {
    return super.serialize()
      ..addAll(<String, String>{
355 356
        'of': jsonEncode(of.serialize()),
        'matching': jsonEncode(matching.serialize()),
357
        'matchRoot': matchRoot ? 'true' : 'false',
358
        'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
359 360 361 362
      });
  }

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

377 378 379 380 381 382
/// 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.
383
///
384 385 386 387 388 389 390 391
/// 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.
392
  GetSemanticsId(SerializableFinder finder, {Duration? timeout}) : super(finder, timeout: timeout);
393

394
  /// Creates a command from a JSON map.
395 396
  GetSemanticsId.deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory)
    : super.deserialize(json, finderFactory);
397 398 399 400 401 402 403 404 405

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

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

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

408
  /// The semantics id of the node.
409 410 411 412
  final int id;

  /// Deserializes this result from JSON.
  static GetSemanticsIdResult fromJson(Map<String, dynamic> json) {
413
    return GetSemanticsIdResult(json['id'] as int);
414 415 416 417 418
  }

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