android_choreographer_do_frame_test.dart 5.92 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright 2014 The Flutter 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';
import 'dart:convert';
import 'dart:io';

import 'package:path/path.dart' as path;

import '../framework/framework.dart';
import '../framework/task_result.dart';
import '../framework/utils.dart';

const List<String> kSentinelStr = <String>[
  '==== sentinel #1 ====',
  '==== sentinel #2 ====',
  '==== sentinel #3 ====',
];

21 22 23 24
/// Tests that Choreographer#doFrame finishes during application startup.
/// This test fails if the application hangs during this period.
/// https://ui.perfetto.dev/#!/?s=da6628c3a92456ae8fa3f345d0186e781da77e90fc8a64d073e9fee11d1e65
/// Regression test for https://github.com/flutter/flutter/issues/98973
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
TaskFunction androidChoreographerDoFrameTest({
  Map<String, String>? environment,
}) {
  final Directory tempDir = Directory.systemTemp
      .createTempSync('flutter_devicelab_android_surface_recreation.');
  return () async {
    try {
      section('Create app');
      await inDirectory(tempDir, () async {
        await flutter(
          'create',
          options: <String>[
            '--platforms',
            'android',
            'app',
          ],
          environment: environment,
        );
      });

      final File mainDart = File(path.join(
        tempDir.absolute.path,
        'app',
        'lib',
        'main.dart',
      ));
      if (!mainDart.existsSync()) {
        return TaskResult.failure('${mainDart.path} does not exist');
      }

      section('Patch lib/main.dart');
      await mainDart.writeAsString('''
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  print('${kSentinelStr[0]}');
  await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);

  print('${kSentinelStr[1]}');
  // If the Android UI thread is blocked, then this Future won't resolve.
  await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);

  print('${kSentinelStr[2]}');
  runApp(
    Container(
      decoration: BoxDecoration(
        color: const Color(0xff7c94b6),
      ),
    ),
  );
}
''', flush: true);

      Future<TaskResult> runTestFor(String mode) async {
        int nextCompleterIdx = 0;
        final Map<String, Completer<void>> sentinelCompleters = <String, Completer<void>>{};
        for (final String sentinel in kSentinelStr) {
          sentinelCompleters[sentinel] = Completer<void>();
        }

        section('Flutter run (mode: $mode)');
89
        late Process run;
90
        await inDirectory(path.join(tempDir.path, 'app'), () async {
91
          run = await startProcess(
92 93 94
            path.join(flutterDirectory.path, 'bin', 'flutter'),
            flutterCommandArgs('run', <String>['--$mode', '--verbose']),
          );
95
        });
96

97 98 99 100 101
        int currSentinelIdx = 0;
        final StreamSubscription<void> stdout = run.stdout
          .transform<String>(utf8.decoder)
          .transform<String>(const LineSplitter())
          .listen((String line) {
102 103 104 105 106 107 108 109 110 111
            if (currSentinelIdx < sentinelCompleters.keys.length &&
                line.contains(sentinelCompleters.keys.elementAt(currSentinelIdx))) {
              sentinelCompleters.values.elementAt(currSentinelIdx).complete();
              currSentinelIdx++;
              print('stdout(MATCHED): $line');
            } else {
              print('stdout: $line');
            }
          });

112 113 114 115 116 117
        final StreamSubscription<void> stderr = run.stderr
          .transform<String>(utf8.decoder)
          .transform<String>(const LineSplitter())
          .listen((String line) {
            print('stderr: $line');
          });
118

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
        final Completer<void> exitCompleter = Completer<void>();

        unawaited(run.exitCode.then((int exitCode) {
          exitCompleter.complete();
        }));

        section('Wait for sentinels (mode: $mode)');
        for (final Completer<void> completer in sentinelCompleters.values) {
          if (nextCompleterIdx == 0) {
            // Don't time out because we don't know how long it would take to get the first log.
            await Future.any<dynamic>(
              <Future<dynamic>>[
                completer.future,
                exitCompleter.future,
              ],
            );
          } else {
            try {
              // Time out since this should not take 1s after the first log was received.
138 139
              await Future.any<dynamic>(
                <Future<dynamic>>[
140
                  completer.future.timeout(const Duration(seconds: 1)),
141 142 143
                  exitCompleter.future,
                ],
              );
144
            } on TimeoutException {
145 146 147
              break;
            }
          }
148 149 150 151 152 153
          if (exitCompleter.isCompleted) {
            // The process exited.
            break;
          }
          nextCompleterIdx++;
        }
154

155 156 157
        section('Quit app (mode: $mode)');
        run.stdin.write('q');
        await exitCompleter.future;
158

159 160 161 162
        section('Stop listening to stdout and stderr (mode: $mode)');
        await stdout.cancel();
        await stderr.cancel();
        run.kill();
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

        if (nextCompleterIdx == sentinelCompleters.values.length) {
          return TaskResult.success(null);
        }
        final String nextSentinel = sentinelCompleters.keys.elementAt(nextCompleterIdx);
        return TaskResult.failure('Expected sentinel `$nextSentinel` in mode $mode');
      }

      final TaskResult debugResult = await runTestFor('debug');
      if (debugResult.failed) {
        return debugResult;
      }

      final TaskResult profileResult = await runTestFor('profile');
      if (profileResult.failed) {
        return profileResult;
      }

      final TaskResult releaseResult = await runTestFor('release');
       if (releaseResult.failed) {
        return releaseResult;
      }

      return TaskResult.success(null);
    } finally {
      rmTree(tempDir);
    }
  };
}