event_printer.dart 1.6 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
import '../convert.dart';
6 7

import 'test_device.dart';
8 9 10 11
import 'watcher.dart';

/// Prints JSON events when running a test in --machine mode.
class EventPrinter extends TestWatcher {
12 13
  EventPrinter({required StringSink out, TestWatcher? parent})
    : _out = out,
14
      _parent = parent;
15 16

  final StringSink _out;
17
  final TestWatcher? _parent;
18 19

  @override
20
  void handleStartedDevice(Uri? observatoryUri) {
21
    _sendEvent('test.startedProcess',
22
        <String, dynamic>{'observatoryUri': observatoryUri?.toString()});
23
    _parent?.handleStartedDevice(observatoryUri);
24 25
  }

26
  @override
27 28
  Future<void> handleTestCrashed(TestDevice testDevice) async {
    return _parent?.handleTestCrashed(testDevice);
29 30 31
  }

  @override
32 33
  Future<void> handleTestTimedOut(TestDevice testDevice) async {
    return _parent?.handleTestTimedOut(testDevice);
34 35 36
  }

  @override
37 38
  Future<void> handleFinishedTest(TestDevice testDevice) async {
    return _parent?.handleFinishedTest(testDevice);
39 40
  }

41
  void _sendEvent(String name, [ dynamic params ]) {
42
    final Map<String, dynamic> map = <String, dynamic>{'event': name};
43 44 45 46 47 48 49
    if (params != null) {
      map['params'] = params;
    }
    _send(map);
  }

  void _send(Map<String, dynamic> command) {
50
    final String encoded = json.encode(command, toEncodable: _jsonEncodeObject);
51 52 53 54 55 56 57 58 59 60
    _out.writeln('\n[$encoded]');
  }

  dynamic _jsonEncodeObject(dynamic object) {
    if (object is Uri) {
      return object.toString();
    }
    return object;
  }
}