transitions_perf_test.dart 7.55 KB
Newer Older
1 2 3 4 5
// 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.

import 'dart:async';
6
import 'dart:convert' show JsonEncoder, JsonDecoder;
7

8
import 'package:file/file.dart';
9
import 'package:file/local.dart';
10
import 'package:flutter_driver/flutter_driver.dart';
11
import 'package:path/path.dart' as path;
12 13
import 'package:test/test.dart';

14
const FileSystem _fs = const LocalFileSystem();
15

16 17 18 19 20 21 22 23
// Demos for which timeline data will be collected using
// FlutterDriver.traceAction().
//
// Warning: The number of tests executed with timeline collection enabled
// significantly impacts heap size of the running app. When run with
// --trace-startup, as we do in this test, the VM stores trace events in an
// endless buffer instead of a ring buffer.
//
24 25
// These names must match GalleryItem titles from kAllGalleryDemos
// in examples/flutter_gallery/lib/gallery/demos.dart
26
const List<String> kProfiledDemos = const <String>[
27 28 29
  'Shrine@Studies',
  'Contact profile@Studies',
  'Animation@Studies',
30 31 32 33 34 35
  'Bottom navigation@Material',
  'Buttons@Material',
  'Cards@Material',
  'Chips@Material',
  'Dialogs@Material',
  'Pickers@Material',
36 37
];

38 39
// Demos that will be backed out of within FlutterDriver.runUnsynchronized();
//
40 41
// These names must match GalleryItem titles from kAllGalleryDemos
// in examples/flutter_gallery/lib/gallery/demos.dart
42
const List<String> kUnsynchronizedDemos = const <String>[
43 44 45 46 47 48 49
  'Progress indicators@Material',
  'Activity Indicator@Cupertino',
  'Video@Media',
];

const List<String> kSkippedDemos = const <String>[
  'Pull to refresh@Cupertino', // The back button lacks a tooltip.
50
];
51

52
// All of the gallery demos, identified as "title@category".
53 54 55 56
//
// These names are reported by the test app, see _handleMessages()
// in transitions_perf.dart.
List<String> _allDemos = <String>[];
57

58 59
/// Extracts event data from [events] recorded by timeline, validates it, turns
/// it into a histogram, and saves to a JSON file.
60
Future<Null> saveDurationsHistogram(List<Map<String, dynamic>> events, String outputPath) async {
61
  final Map<String, List<int>> durations = <String, List<int>>{};
62 63 64 65 66 67 68 69 70 71
  Map<String, dynamic> startEvent;

  // Save the duration of the first frame after each 'Start Transition' event.
  for (Map<String, dynamic> event in events) {
    final String eventName = event['name'];
    if (eventName == 'Start Transition') {
      assert(startEvent == null);
      startEvent = event;
    } else if (startEvent != null && eventName == 'Frame') {
      final String routeName = startEvent['args']['to'];
72
      durations[routeName] ??= <int>[];
73 74 75 76 77 78 79 80
      durations[routeName].add(event['dur']);
      startEvent = null;
    }
  }

  // Verify that the durations data is valid.
  if (durations.keys.isEmpty)
    throw 'no "Start Transition" timeline events found';
81
  final Map<String, int> unexpectedValueCounts = <String, int>{};
82 83 84 85 86 87 88
  durations.forEach((String routeName, List<int> values) {
    if (values.length != 2) {
      unexpectedValueCounts[routeName] = values.length;
    }
  });

  if (unexpectedValueCounts.isNotEmpty) {
89
    final StringBuffer error = new StringBuffer('Some routes recorded wrong number of values (expected 2 values/route):\n\n');
90 91 92 93
    unexpectedValueCounts.forEach((String routeName, int count) {
      error.writeln(' - $routeName recorded $count values.');
    });
    error.writeln('\nFull event sequence:');
94
    final Iterator<Map<String, dynamic>> eventIter = events.iterator;
95 96
    String lastEventName = '';
    String lastRouteName = '';
97
    while (eventIter.moveNext()) {
98
      final String eventName = eventIter.current['name'];
99 100 101 102

      if (!<String>['Start Transition', 'Frame'].contains(eventName))
        continue;

103
      final String routeName = eventName == 'Start Transition'
104 105 106 107 108 109 110 111 112 113 114 115 116
        ? eventIter.current['args']['to']
        : '';

      if (eventName == lastEventName && routeName == lastRouteName) {
        error.write('.');
      } else {
        error.write('\n - $eventName $routeName .');
      }

      lastEventName = eventName;
      lastRouteName = routeName;
    }
    throw error;
117 118 119
  }

  // Save the durations Map to a file.
120
  final File file = await _fs.file(outputPath).create(recursive: true);
121
  await file.writeAsString(const JsonEncoder.withIndent('  ').convert(durations));
122 123
}

124 125
/// Scrolls each demo menu item into view, launches it, then returns to the
/// home screen twice.
126
Future<Null> runDemos(List<String> demos, FlutterDriver driver) async {
127 128 129
  final SerializableFinder demoList = find.byValueKey('GalleryDemoList');
  String currentDemoCategory;

130
  for (String demo in demos) {
131 132 133 134 135 136
    if (kSkippedDemos.contains(demo))
      continue;

    final String demoName = demo.substring(0, demo.indexOf('@'));
    final String demoCategory = demo.substring(demo.indexOf('@') + 1);
    print('> $demo');
137 138 139 140 141 142

    if (currentDemoCategory == null) {
      await driver.tap(find.text(demoCategory));
    } else if (currentDemoCategory != demoCategory) {
      await driver.tap(find.byTooltip('Back'));
      await driver.tap(find.text(demoCategory));
143 144
      // Scroll back to the top
      await driver.scroll(demoList, 0.0, 10000.0, const Duration(milliseconds: 100));
145 146
    }
    currentDemoCategory = demoCategory;
147

148
    final SerializableFinder demoItem = find.text(demoName);
149
    await driver.scrollUntilVisible(demoList, demoItem, dyScroll: -48.0,  alignment: 0.5);
150

151 152
    for (int i = 0; i < 2; i += 1) {
      await driver.tap(demoItem); // Launch the demo
153 154

      if (kUnsynchronizedDemos.contains(demo)) {
155 156 157
        await driver.runUnsynchronized<Future<Null>>(() async {
          await driver.tap(find.byTooltip('Back'));
        });
158 159
      } else {
        await driver.tap(find.byTooltip('Back'));
160 161
      }
    }
162

163
    print('< Success');
164
  }
165 166 167

  // Return to the home screen
  await driver.tap(find.byTooltip('Back'));
168 169
}

170
void main([List<String> args = const <String>[]]) {
171 172 173 174
  group('flutter gallery transitions', () {
    FlutterDriver driver;
    setUpAll(() async {
      driver = await FlutterDriver.connect();
175

176 177 178 179
      if (args.contains('--with_semantics')) {
        print('Enabeling semantics...');
        await driver.setSemantics(true);
      }
180 181 182 183 184

      // See _handleMessages() in transitions_perf.dart.
      _allDemos = const JsonDecoder().convert(await driver.requestData('demoNames'));
      if (_allDemos.isEmpty)
        throw 'no demo names found';
185 186 187 188
    });

    tearDownAll(() async {
      if (driver != null)
189
        await driver.close();
190 191 192
    });

    test('all demos', () async {
193

194
      // Collect timeline data for just a limited set of demos to avoid OOMs.
195 196 197 198 199 200 201 202 203
      final Timeline timeline = await driver.traceAction(
        () async {
          await runDemos(kProfiledDemos, driver);
        },
        streams: const <TimelineStream>[
          TimelineStream.dart,
          TimelineStream.embedder,
        ],
      );
204 205 206 207

      // Save the duration (in microseconds) of the first timeline Frame event
      // that follows a 'Start Transition' event. The Gallery app adds a
      // 'Start Transition' event when a demo is launched (see GalleryItem).
208
      final TimelineSummary summary = new TimelineSummary.summarize(timeline);
209
      await summary.writeSummaryToFile('transitions', pretty: true);
210
      final String histogramPath = path.join(testOutputsDirectory, 'transition_durations.timeline.json');
211
      await saveDurationsHistogram(timeline.json['traceEvents'], histogramPath);
212 213

      // Execute the remaining tests.
214
      final Set<String> unprofiledDemos = new Set<String>.from(_allDemos)..removeAll(kProfiledDemos);
215
      await runDemos(unprofiledDemos.toList(), driver);
216

217
    }, timeout: const Timeout(const Duration(minutes: 5)));
218 219
  });
}