transitions_perf_test.dart 8.36 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:flutter_gallery/demo_lists.dart';
11
import 'package:path/path.dart' as path;
12
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
13

14
const FileSystem _fs = LocalFileSystem();
15

16 17 18 19 20 21 22 23 24
/// The demos we don't run as part of the integration test.
///
/// Demo names are formatted as 'DEMO_NAME@DEMO_CATEGORY' (see
/// `demo_lists.dart` for more examples).
const List<String> kSkippedDemos = <String>[
  // This demo is flaky on CI due to hitting the network.
  // See: https://github.com/flutter/flutter/issues/100497
  'Video@Media',
];
25

26
// All of the gallery demos, identified as "title@category".
27
//
28 29
// These names are reported by the test app, see _handleMessages()
// in transitions_perf.dart.
30
List<String> _allDemos = <String>[];
31

32 33
/// Extracts event data from [events] recorded by timeline, validates it, turns
/// it into a histogram, and saves to a JSON file.
34
Future<void> saveDurationsHistogram(List<Map<String, dynamic>> events, String outputPath) async {
35
  final Map<String, List<int>> durations = <String, List<int>>{};
36 37
  Map<String, dynamic>? startEvent;
  int? frameStart;
38 39

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

  // Verify that the durations data is valid.
  if (durations.keys.isEmpty)
    throw 'no "Start Transition" timeline events found';
65
  final Map<String, int> unexpectedValueCounts = <String, int>{};
66 67 68 69 70 71 72
  durations.forEach((String routeName, List<int> values) {
    if (values.length != 2) {
      unexpectedValueCounts[routeName] = values.length;
    }
  });

  if (unexpectedValueCounts.isNotEmpty) {
73
    final StringBuffer error = StringBuffer('Some routes recorded wrong number of values (expected 2 values/route):\n\n');
74 75
    // 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');
76 77 78 79
    unexpectedValueCounts.forEach((String routeName, int count) {
      error.writeln(' - $routeName recorded $count values.');
    });
    error.writeln('\nFull event sequence:');
80
    final Iterator<Map<String, dynamic>> eventIter = events.iterator;
81 82
    String lastEventName = '';
    String lastRouteName = '';
83
    while (eventIter.moveNext()) {
84
      final String eventName = eventIter.current['name'] as String;
85 86 87 88

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

89
      final String routeName = eventName == 'Start Transition'
90
        ? (eventIter.current['args'] as Map<String, dynamic>)['to'] as String
91 92 93 94 95 96 97 98 99 100 101 102
        : '';

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

      lastEventName = eventName;
      lastRouteName = routeName;
    }
    throw error;
103 104 105
  }

  // Save the durations Map to a file.
106
  final File file = await _fs.file(outputPath).create(recursive: true);
107
  await file.writeAsString(const JsonEncoder.withIndent('  ').convert(durations));
108 109
}

110 111
/// Scrolls each demo menu item into view, launches it, then returns to the
/// home screen twice.
112
Future<void> runDemos(List<String> demos, FlutterDriver driver) async {
113
  final SerializableFinder demoList = find.byValueKey('GalleryDemoList');
114
  String? currentDemoCategory;
115

116
  for (final String demo in demos) {
117 118 119 120 121 122
    if (kSkippedDemos.contains(demo))
      continue;

    final String demoName = demo.substring(0, demo.indexOf('@'));
    final String demoCategory = demo.substring(demo.indexOf('@') + 1);
    print('> $demo');
123

124
    final SerializableFinder demoCategoryItem = find.text(demoCategory);
125
    if (currentDemoCategory == null) {
126 127
      await driver.scrollIntoView(demoCategoryItem);
      await driver.tap(demoCategoryItem);
128 129
    } else if (currentDemoCategory != demoCategory) {
      await driver.tap(find.byTooltip('Back'));
130 131
      await driver.scrollIntoView(demoCategoryItem);
      await driver.tap(demoCategoryItem);
132 133
      // Scroll back to the top
      await driver.scroll(demoList, 0.0, 10000.0, const Duration(milliseconds: 100));
134 135
    }
    currentDemoCategory = demoCategory;
136

137
    final SerializableFinder demoItem = find.text(demoName);
138 139 140 141
    await driver.scrollUntilVisible(demoList, demoItem,
      dyScroll: -48.0,
      alignment: 0.5,
    );
142

143 144
    for (int i = 0; i < 2; i += 1) {
      await driver.tap(demoItem); // Launch the demo
145 146

      if (kUnsynchronizedDemos.contains(demo)) {
147
        await driver.runUnsynchronized<void>(() async {
148
          await driver.tap(find.pageBack());
149
        });
150
      } else {
151
        await driver.tap(find.pageBack());
152 153
      }
    }
154

155
    print('< Success');
156
  }
157 158 159

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

162
void main([List<String> args = const <String>[]]) {
163
  final bool withSemantics = args.contains('--with_semantics');
164
  final bool hybrid = args.contains('--hybrid');
165
  group('flutter gallery transitions', () {
166
    late FlutterDriver driver;
167 168
    setUpAll(() async {
      driver = await FlutterDriver.connect();
169

170 171
      // Wait for the first frame to be rasterized.
      await driver.waitUntilFirstFrameRasterized();
172
      if (withSemantics) {
173
        print('Enabling semantics...');
174 175
        await driver.setSemantics(true);
      }
176 177

      // See _handleMessages() in transitions_perf.dart.
178
      _allDemos = List<String>.from(json.decode(await driver.requestData('demoNames')) as List<dynamic>);
179 180
      if (_allDemos.isEmpty)
        throw 'no demo names found';
181 182 183
    });

    tearDownAll(() async {
184
        await driver.close();
185 186
    });

187 188 189 190
    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));
191 192 193 194
    },
        skip: !withSemantics, // [intended] test only makes sense when semantics are turned on.
        timeout: Timeout.none,
    );
195

196
    test('all demos', () async {
197
      // Collect timeline data for just a limited set of demos to avoid OOMs.
198 199
      final Timeline timeline = await driver.traceAction(
        () async {
200 201 202 203 204
          if (hybrid) {
            await driver.requestData('profileDemos');
          } else {
            await runDemos(kProfiledDemos, driver);
          }
205 206 207 208
        },
        streams: const <TimelineStream>[
          TimelineStream.dart,
          TimelineStream.embedder,
209
          TimelineStream.gc,
210 211
        ],
      );
212 213 214 215

      // 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).
216
      final TimelineSummary summary = TimelineSummary.summarize(timeline);
217
      await summary.writeTimelineToFile('transitions', pretty: true);
218
      final String histogramPath = path.join(testOutputsDirectory, 'transition_durations.timeline.json');
219
      await saveDurationsHistogram(
220
          List<Map<String, dynamic>>.from(timeline.json['traceEvents'] as List<dynamic>),
221
          histogramPath);
222 223

      // Execute the remaining tests.
224
      if (hybrid) {
225
        await driver.requestData('restDemos');
226 227 228 229
      } else {
        final Set<String> unprofiledDemos = Set<String>.from(_allDemos)..removeAll(kProfiledDemos);
        await runDemos(unprofiledDemos.toList(), driver);
      }
230

231
    }, timeout: Timeout.none);
232 233
  });
}