transitions_perf_test.dart 7.83 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 'dart:convert' show JsonEncoder, json;
6

7
import 'package:file/file.dart';
8
import 'package:file/local.dart';
9
import 'package:flutter_driver/flutter_driver.dart';
10
import 'package:path/path.dart' as path;
11
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
12

13
import 'package:flutter_gallery/demo_lists.dart';
14

15
const FileSystem _fs = LocalFileSystem();
16

17
const List<String> kSkippedDemos = <String>[];
18

19
// All of the gallery demos, identified as "title@category".
20
//
21 22
// These names are reported by the test app, see _handleMessages()
// in transitions_perf.dart.
23
List<String> _allDemos = <String>[];
24

25 26
/// Extracts event data from [events] recorded by timeline, validates it, turns
/// it into a histogram, and saves to a JSON file.
27
Future<void> saveDurationsHistogram(List<Map<String, dynamic>> events, String outputPath) async {
28
  final Map<String, List<int>> durations = <String, List<int>>{};
29
  Map<String, dynamic> startEvent;
30
  int frameStart;
31 32

  // Save the duration of the first frame after each 'Start Transition' event.
33
  for (final Map<String, dynamic> event in events) {
34
    final String eventName = event['name'] as String;
35 36 37 38
    if (eventName == 'Start Transition') {
      assert(startEvent == null);
      startEvent = event;
    } else if (startEvent != null && eventName == 'Frame') {
39 40 41 42 43 44 45 46 47 48 49 50 51
      final String phase = event['ph'] as String;
      final int timestamp = event['ts'] as int;
      if (phase == 'B') {
        assert(frameStart == null);
        frameStart = timestamp;
      } else {
        assert(phase == 'E');
        final String routeName = startEvent['args']['to'] as String;
        durations[routeName] ??= <int>[];
        durations[routeName].add(timestamp - frameStart);
        startEvent = null;
        frameStart = null;
      }
52 53 54 55 56 57
    }
  }

  // Verify that the durations data is valid.
  if (durations.keys.isEmpty)
    throw 'no "Start Transition" timeline events found';
58
  final Map<String, int> unexpectedValueCounts = <String, int>{};
59 60 61 62 63 64 65
  durations.forEach((String routeName, List<int> values) {
    if (values.length != 2) {
      unexpectedValueCounts[routeName] = values.length;
    }
  });

  if (unexpectedValueCounts.isNotEmpty) {
66
    final StringBuffer error = StringBuffer('Some routes recorded wrong number of values (expected 2 values/route):\n\n');
67 68
    // When run with --trace-startup, the VM stores trace events in an endless buffer instead of a ring buffer.
    error.write('You must add the --trace-startup parameter to run the test. \n\n');
69 70 71 72
    unexpectedValueCounts.forEach((String routeName, int count) {
      error.writeln(' - $routeName recorded $count values.');
    });
    error.writeln('\nFull event sequence:');
73
    final Iterator<Map<String, dynamic>> eventIter = events.iterator;
74 75
    String lastEventName = '';
    String lastRouteName = '';
76
    while (eventIter.moveNext()) {
77
      final String eventName = eventIter.current['name'] as String;
78 79 80 81

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

82
      final String routeName = eventName == 'Start Transition'
83
        ? eventIter.current['args']['to'] as String
84 85 86 87 88 89 90 91 92 93 94 95
        : '';

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

      lastEventName = eventName;
      lastRouteName = routeName;
    }
    throw error;
96 97 98
  }

  // Save the durations Map to a file.
99
  final File file = await _fs.file(outputPath).create(recursive: true);
100
  await file.writeAsString(const JsonEncoder.withIndent('  ').convert(durations));
101 102
}

103 104
/// Scrolls each demo menu item into view, launches it, then returns to the
/// home screen twice.
105
Future<void> runDemos(List<String> demos, FlutterDriver driver) async {
106 107 108
  final SerializableFinder demoList = find.byValueKey('GalleryDemoList');
  String currentDemoCategory;

109
  for (final String demo in demos) {
110 111 112 113 114 115
    if (kSkippedDemos.contains(demo))
      continue;

    final String demoName = demo.substring(0, demo.indexOf('@'));
    final String demoCategory = demo.substring(demo.indexOf('@') + 1);
    print('> $demo');
116 117 118 119 120 121

    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));
122 123
      // Scroll back to the top
      await driver.scroll(demoList, 0.0, 10000.0, const Duration(milliseconds: 100));
124 125
    }
    currentDemoCategory = demoCategory;
126

127
    final SerializableFinder demoItem = find.text(demoName);
128 129 130 131 132
    await driver.scrollUntilVisible(demoList, demoItem,
      dyScroll: -48.0,
      alignment: 0.5,
      timeout: const Duration(seconds: 30),
    );
133

134 135
    for (int i = 0; i < 2; i += 1) {
      await driver.tap(demoItem); // Launch the demo
136 137

      if (kUnsynchronizedDemos.contains(demo)) {
138
        await driver.runUnsynchronized<void>(() async {
139
          await driver.tap(find.pageBack());
140
        });
141
      } else {
142
        await driver.tap(find.pageBack());
143 144
      }
    }
145

146
    print('< Success');
147
  }
148 149 150

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

153
void main([List<String> args = const <String>[]]) {
154
  final bool withSemantics = args.contains('--with_semantics');
155
  final bool hybrid = args.contains('--hybrid');
156 157 158 159
  group('flutter gallery transitions', () {
    FlutterDriver driver;
    setUpAll(() async {
      driver = await FlutterDriver.connect();
160

161 162
      // Wait for the first frame to be rasterized.
      await driver.waitUntilFirstFrameRasterized();
163
      if (withSemantics) {
164 165 166
        print('Enabeling semantics...');
        await driver.setSemantics(true);
      }
167 168

      // See _handleMessages() in transitions_perf.dart.
169
      _allDemos = List<String>.from(json.decode(await driver.requestData('demoNames')) as List<dynamic>);
170 171
      if (_allDemos.isEmpty)
        throw 'no demo names found';
172 173 174 175
    });

    tearDownAll(() async {
      if (driver != null)
176
        await driver.close();
177 178
    });

179 180 181 182 183 184
    test('find.bySemanticsLabel', () async {
      // Assert that we can use semantics related finders in profile mode.
      final int id = await driver.getSemanticsId(find.bySemanticsLabel('Material'));
      expect(id, greaterThan(-1));
    }, skip: !withSemantics);

185
    test('all demos', () async {
186
      // Collect timeline data for just a limited set of demos to avoid OOMs.
187 188
      final Timeline timeline = await driver.traceAction(
        () async {
189 190 191 192 193
          if (hybrid) {
            await driver.requestData('profileDemos');
          } else {
            await runDemos(kProfiledDemos, driver);
          }
194 195 196 197 198 199
        },
        streams: const <TimelineStream>[
          TimelineStream.dart,
          TimelineStream.embedder,
        ],
      );
200 201 202 203

      // 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).
204
      final TimelineSummary summary = TimelineSummary.summarize(timeline);
205
      await summary.writeSummaryToFile('transitions', pretty: true);
206
      await summary.writeTimelineToFile('transitions', pretty: true);
207
      final String histogramPath = path.join(testOutputsDirectory, 'transition_durations.timeline.json');
208
      await saveDurationsHistogram(
209
          List<Map<String, dynamic>>.from(timeline.json['traceEvents'] as List<dynamic>),
210
          histogramPath);
211 212

      // Execute the remaining tests.
213
      if (hybrid) {
214
        await driver.requestData('restDemos');
215 216 217 218
      } else {
        final Set<String> unprofiledDemos = Set<String>.from(_allDemos)..removeAll(kProfiledDemos);
        await runDemos(unprofiledDemos.toList(), driver);
      }
219

220
    }, timeout: const Timeout(Duration(minutes: 5)));
221 222
  });
}