Improve tracing (#93086)

This commit is contained in:
Ian Hickson
2021-12-10 10:09:24 -08:00
committed by GitHub
parent 14cf445acd
commit 840e109e07
50 changed files with 1166 additions and 133 deletions

View File

@@ -15,11 +15,11 @@ dependencies:
platform: 3.1.0
process: 4.2.4
test: 1.19.5
archive: 3.1.6
_discoveryapis_commons: 1.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
_fe_analyzer_shared: 31.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
analyzer: 2.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
archive: 3.1.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
async: 2.8.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
boolean_selector: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
charcode: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"

View File

@@ -6,7 +6,9 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:archive/archive.dart';
import 'package:file/file.dart' as fs;
import 'package:file/local.dart';
import 'package:path/path.dart' as path;
@@ -744,6 +746,89 @@ Future<void> _runFrameworkTests() async {
await _runFlutterTest(path.join(flutterRoot, 'examples', 'layers'), options: soundNullSafetyOptions);
}
Future<void> runTracingTests() async {
final String tracingDirectory = path.join(flutterRoot, 'dev', 'tracing_tests');
// run the tests for debug mode
await _runFlutterTest(tracingDirectory, options: <String>['--enable-vmservice']);
Future<List<String>> verifyTracingAppBuild({
required String modeArgument,
required String sourceFile,
required Set<String> allowed,
required Set<String> disallowed,
}) async {
await runCommand(
flutter,
<String>[
'build', 'appbundle', '--$modeArgument', path.join('lib', sourceFile),
],
workingDirectory: tracingDirectory,
);
final Archive archive = ZipDecoder().decodeBytes(File(path.join(tracingDirectory, 'build', 'app', 'outputs', 'bundle', modeArgument, 'app-$modeArgument.aab')).readAsBytesSync());
final ArchiveFile libapp = archive.findFile('base/lib/arm64-v8a/libapp.so')!;
final Uint8List libappBytes = libapp.content as Uint8List; // bytes decompressed here
final String libappStrings = utf8.decode(libappBytes, allowMalformed: true);
await runCommand(flutter, <String>['clean'], workingDirectory: tracingDirectory);
final List<String> results = <String>[];
for (final String pattern in allowed) {
if (!libappStrings.contains(pattern)) {
results.add('When building with --$modeArgument, expected to find "$pattern" in libapp.so but could not find it.');
}
}
for (final String pattern in disallowed) {
if (libappStrings.contains(pattern)) {
results.add('When building with --$modeArgument, expected to not find "$pattern" in libapp.so but did find it.');
}
}
return results;
}
final List<String> results = <String>[];
results.addAll(await verifyTracingAppBuild(
modeArgument: 'profile',
sourceFile: 'control.dart', // this is the control, the other two below are the actual test
allowed: <String>{
'TIMELINE ARGUMENTS TEST CONTROL FILE',
'toTimelineArguments used in non-debug build', // we call toTimelineArguments directly to check the message does exist
},
disallowed: <String>{
'BUILT IN DEBUG MODE', 'BUILT IN RELEASE MODE',
},
));
results.addAll(await verifyTracingAppBuild(
modeArgument: 'profile',
sourceFile: 'test.dart',
allowed: <String>{
'BUILT IN PROFILE MODE', 'RenderTest.performResize called', // controls
'BUILD', 'LAYOUT', 'PAINT', // we output these to the timeline in profile builds
// (LAYOUT and PAINT also exist because of NEEDS-LAYOUT and NEEDS-PAINT in RenderObject.toStringShort)
},
disallowed: <String>{
'BUILT IN DEBUG MODE', 'BUILT IN RELEASE MODE',
'TestWidget.debugFillProperties called', 'RenderTest.debugFillProperties called', // debug only
'toTimelineArguments used in non-debug build', // entire function should get dropped by tree shaker
},
));
results.addAll(await verifyTracingAppBuild(
modeArgument: 'release',
sourceFile: 'test.dart',
allowed: <String>{
'BUILT IN RELEASE MODE', 'RenderTest.performResize called', // controls
},
disallowed: <String>{
'BUILT IN DEBUG MODE', 'BUILT IN PROFILE MODE',
'BUILD', 'LAYOUT', 'PAINT', // these are only used in Timeline.startSync calls that should not appear in release builds
'TestWidget.debugFillProperties called', 'RenderTest.debugFillProperties called', // debug only
'toTimelineArguments used in non-debug build', // not included in release builds
},
));
if (results.isNotEmpty) {
print(results.join('\n'));
exit(1);
}
}
Future<void> runFixTests() async {
final List<String> args = <String>[
'fix',
@@ -808,10 +893,7 @@ Future<void> _runFrameworkTests() async {
await _runFlutterTest(path.join(flutterRoot, 'packages', 'flutter_test'), options: soundNullSafetyOptions);
await _runFlutterTest(path.join(flutterRoot, 'packages', 'fuchsia_remote_debug_protocol'), options: soundNullSafetyOptions);
await _runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'non_nullable'), options: mixedModeNullSafetyOptions);
await _runFlutterTest(
path.join(flutterRoot, 'dev', 'tracing_tests'),
options: <String>['--enable-vmservice'],
);
await runTracingTests();
await runFixTests();
await runPrivateTests();
const String httpClientWarning =

View File

@@ -382,14 +382,12 @@ class _VideoDemoState extends State<VideoDemo> with SingleTickerProviderStateMix
super.initState();
Future<void> initController(VideoPlayerController controller, String name) async {
print('> VideoDemo initController "$name" ${isDisposed ? "DISPOSED" : ""}');
controller.setLooping(true);
controller.setVolume(0.0);
controller.play();
await connectedCompleter.future;
await controller.initialize();
if (mounted) {
print('< VideoDemo initController "$name" done ${isDisposed ? "DISPOSED" : ""}');
setState(() { });
}
}
@@ -403,11 +401,9 @@ class _VideoDemoState extends State<VideoDemo> with SingleTickerProviderStateMix
@override
void dispose() {
print('> VideoDemo dispose');
isDisposed = true;
butterflyController.dispose();
beeController.dispose();
print('< VideoDemo dispose');
super.dispose();
}

View File

@@ -2,4 +2,20 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export 'package:flutter_goldens/flutter_goldens.dart' show testExecutable;
import 'dart:async';
import 'package:flutter/rendering.dart';
import 'package:flutter_goldens/flutter_goldens.dart' as flutter_goldens show testExecutable;
import 'package:flutter_test/flutter_test.dart';
Future<void> testExecutable(FutureOr<void> Function() testMain) {
// Enable extra checks since this package exercises a lot of the framework.
debugCheckIntrinsicSizes = true;
// Make tap() et al fail if the given finder specifies a widget that would not
// receive the event.
WidgetController.hitTestWarningShouldBeFatal = true;
// Enable golden file testing using Skia Gold.
return flutter_goldens.testExecutable(testMain);
}

View File

@@ -118,7 +118,7 @@ Future<void> smokeOptionsPage(WidgetTester tester) async {
// Switch back to system theme setting: first menu button, choose 'System Default'
await tester.tap(find.byIcon(Icons.arrow_drop_down).first);
await tester.pumpAndSettle();
await tester.tap(find.text('System Default').at(1));
await tester.tap(find.text('System Default').at(1), warnIfMissed: false); // https://github.com/flutter/flutter/issues/82908
await tester.pumpAndSettle();
// Switch text direction: first switch

View File

@@ -1,5 +1,16 @@
# Tracing tests
## "Application"
The `lib/test.dart` and `lib/control.dart` files in this directory are
used by `dev/bots/test.dart`'s `runTracingTests` function to check
whether aspects of the tracing logic in the framework get compiled out
in profile and release builds. They're not meant to be run directly.
The strings in these files are used in `dev/bots/test.dart`.
## Tests
The tests in this folder must be run with `flutter test --enable-vmservice`,
since they test that trace data is written to the timeline by connecting to
the observatory.

13
dev/tracing_tests/android/.gitignore vendored Normal file
View File

@@ -0,0 +1,13 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
# Remember to never publicly share your keystore.
# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app
key.properties
**/*.keystore
**/*.jks

View File

@@ -0,0 +1,72 @@
// 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.
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion flutter.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.tracing_tests"
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

View File

@@ -0,0 +1,11 @@
<!-- 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. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tracing_tests">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

View File

@@ -0,0 +1,38 @@
<!-- 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. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tracing_tests">
<application
android:label="tracing_tests"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>

View File

@@ -0,0 +1,6 @@
package com.example.tracing_tests
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}

View File

@@ -0,0 +1,15 @@
<!-- 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. -->
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>

View File

@@ -0,0 +1,15 @@
<!-- 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. -->
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>

Binary file not shown.

After

Width:  |  Height:  |  Size: 544 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1,21 @@
<!-- 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. -->
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

View File

@@ -0,0 +1,21 @@
<!-- 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. -->
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

View File

@@ -0,0 +1,11 @@
<!-- 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. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tracing_tests">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

View File

@@ -0,0 +1,35 @@
// 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.
buildscript {
ext.kotlin_version = '1.6.0'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@@ -0,0 +1,3 @@
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true

View File

@@ -0,0 +1,6 @@
#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip

View File

@@ -0,0 +1,15 @@
// 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.
include ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"

View File

@@ -0,0 +1,16 @@
// 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.
// This file is part of dev/bots/test.dart's runTracingTests test.
import 'package:flutter/foundation.dart';
void main() {
// This file is intended to be compiled in profile mode.
// In that mode, the function below throws an exception.
// The dev/bots/test.dart test looks for the string from that exception.
// The string below is matched verbatim in dev/bots/test.dart as a control
// to make sure this file did get compiled.
DiagnosticsNode.message('TIMELINE ARGUMENTS TEST CONTROL FILE').toTimelineArguments();
}

View File

@@ -0,0 +1,70 @@
// 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:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
class TestWidget extends LeafRenderObjectWidget {
const TestWidget({
Key? key,
}) : super(key: key);
@override
RenderObject createRenderObject(BuildContext context) => RenderTest();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
// This string is searched for verbatim by dev/bots/test.dart:
properties.add(MessageProperty('test', 'TestWidget.debugFillProperties called'));
}
}
class RenderTest extends RenderBox {
@override
bool get sizedByParent => true;
@override
void performResize() {
Timeline.instantSync('RenderTest.performResize called');
size = constraints.biggest;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
// This string is searched for verbatim by dev/bots/test.dart:
properties.add(MessageProperty('test', 'RenderTest.debugFillProperties called'));
}
}
Future<void> main() async {
// This section introduces strings that we can search for in dev/bots/test.dart
// as a sanity check:
if (kDebugMode) {
print('BUILT IN DEBUG MODE');
}
if (kProfileMode) {
print('BUILT IN PROFILE MODE');
}
if (kReleaseMode) {
print('BUILT IN RELEASE MODE');
}
// The point of this file is to make sure that toTimelineArguments is not
// called when we have debugProfileBuildsEnabled (et al) turned on. If that
// method is not called then the debugFillProperties methods above should also
// not get called and we should end up tree-shaking the entire Diagnostics
// logic out of the app. The dev/bots/test.dart test checks for this by
// looking for the strings in the methods above.
debugProfileBuildsEnabled = true;
debugProfileLayoutsEnabled = true;
debugProfilePaintsEnabled = true;
runApp(const TestWidget());
}

View File

@@ -0,0 +1,34 @@
// 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:developer' as developer;
import 'dart:isolate' as isolate;
import 'package:flutter_test/flutter_test.dart';
import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';
export 'package:vm_service/vm_service.dart' show TimelineEvent;
late String isolateId;
late VmService _vmService;
void initTimelineTests() {
setUpAll(() async {
final developer.ServiceProtocolInfo info = await developer.Service.getInfo();
if (info.serverUri == null) {
fail('This test _must_ be run with --enable-vmservice.');
}
_vmService = await vmServiceConnectUri('ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws');
await _vmService.setVMTimelineFlags(<String>['Dart']);
isolateId = developer.Service.getIsolateID(isolate.Isolate.current)!;
});
}
Future<List<TimelineEvent>> fetchTimelineEvents() async {
final Timeline timeline = await _vmService.getVMTimeline();
await _vmService.clearVMTimeline();
return timeline.traceEvents!;
}

View File

@@ -3,31 +3,15 @@
// found in the LICENSE file.
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:isolate' as isolate;
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';
import 'common.dart';
void main() {
late VmService vmService;
late String isolateId;
setUpAll(() async {
final developer.ServiceProtocolInfo info = await developer.Service.getInfo();
if (info.serverUri == null) {
fail('This test _must_ be run with --enable-vmservice.');
}
vmService = await vmServiceConnectUri('ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws');
await vmService.setVMTimelineFlags(<String>['Dart']);
isolateId = developer.Service.getIsolateID(isolate.Isolate.current)!;
// Initialize the image cache.
TestWidgetsFlutterBinding.ensureInitialized();
});
initTimelineTests();
TestWidgetsFlutterBinding.ensureInitialized();
test('Image cache tracing', () async {
final TestImageStreamCompleter completer1 = TestImageStreamCompleter();
@@ -45,9 +29,8 @@ void main() {
);
PaintingBinding.instance!.imageCache!.evict('Test2');
final Timeline timeline = await vmService.getVMTimeline();
_expectTimelineEvents(
timeline.traceEvents!,
await fetchTimelineEvents(),
<Map<String, dynamic>>[
<String, dynamic>{
'name': 'ImageCache.putIfAbsent',

View File

@@ -0,0 +1,155 @@
// 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 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_test/flutter_test.dart';
import 'common.dart';
final Set<String> interestingLabels = <String>{
'BUILD',
'LAYOUT',
'UPDATING COMPOSITING BITS',
'PAINT',
'COMPOSITING',
'FINALIZE TREE',
'$Placeholder',
'$CustomPaint',
'$RenderCustomPaint',
};
Future<List<TimelineEvent>> fetchInterestingEvents() async {
return (await fetchTimelineEvents()).where((TimelineEvent event) {
return interestingLabels.contains(event.json!['name'])
&& event.json!['ph'] == 'B'; // "Begin" mark of events, vs E which is for the "End" mark of events.
}).toList();
}
String eventToName(TimelineEvent event) => event.json!['name'] as String;
class TestRoot extends StatefulWidget {
const TestRoot({ Key? key }) : super(key: key);
static late final TestRootState state;
@override
State<TestRoot> createState() => TestRootState();
}
class TestRootState extends State<TestRoot> {
@override
void initState() {
super.initState();
TestRoot.state = this;
}
Widget _widget = const Placeholder();
void updateWidget(Widget newWidget) {
setState(() {
_widget = newWidget;
});
}
void rebuild() {
setState(() {
// no change, just force a rebuild
});
}
@override
Widget build(BuildContext context) {
return _widget;
}
}
Future<void> runFrame(VoidCallback callback) {
final Future<void> result = SchedulerBinding.instance!.endOfFrame; // schedules a frame
callback();
return result;
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
initTimelineTests();
test('Timeline', () async {
// We don't have expectations around the first frame because there's a race around
// the warm-up frame that we don't want to get involved in here.
await runFrame(() { runApp(const TestRoot()); });
await SchedulerBinding.instance!.endOfFrame;
await fetchInterestingEvents();
// The next few cases build the exact same tree so should have no effect.
debugProfileBuildsEnabled = true;
await runFrame(() { TestRoot.state.rebuild(); });
expect(
(await fetchInterestingEvents()).map<String>(eventToName),
<String>['BUILD', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
debugProfileBuildsEnabled = false;
debugProfileLayoutsEnabled = true;
await runFrame(() { TestRoot.state.rebuild(); });
expect(
(await fetchInterestingEvents()).map<String>(eventToName),
<String>['BUILD', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
debugProfileLayoutsEnabled = false;
debugProfilePaintsEnabled = true;
await runFrame(() { TestRoot.state.rebuild(); });
expect(
(await fetchInterestingEvents()).map<String>(eventToName),
<String>['BUILD', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
debugProfilePaintsEnabled = false;
// Now we replace the widgets each time to cause a rebuild.
List<TimelineEvent> events;
Map<String, String> args;
debugProfileBuildsEnabled = true;
await runFrame(() { TestRoot.state.updateWidget(Placeholder(key: UniqueKey(), color: const Color(0xFFFFFFFF))); });
events = await fetchInterestingEvents();
expect(
events.map<String>(eventToName),
<String>['BUILD', 'Placeholder', 'CustomPaint', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
args = (events.where((TimelineEvent event) => event.json!['name'] == '$Placeholder').single.json!['args'] as Map<String, Object?>).cast<String, String>();
expect(args['color'], 'Color(0xffffffff)');
debugProfileBuildsEnabled = false;
debugProfileLayoutsEnabled = true;
await runFrame(() { TestRoot.state.updateWidget(Placeholder(key: UniqueKey())); });
events = await fetchInterestingEvents();
expect(
events.map<String>(eventToName),
<String>['BUILD', 'LAYOUT', 'RenderCustomPaint', 'UPDATING COMPOSITING BITS', 'PAINT', 'COMPOSITING', 'FINALIZE TREE'],
);
args = (events.where((TimelineEvent event) => event.json!['name'] == '$RenderCustomPaint').single.json!['args'] as Map<String, Object?>).cast<String, String>();
expect(args['creator'], startsWith('CustomPaint'));
expect(args['creator'], contains('Placeholder'));
expect(args['foregroundPainter'], startsWith('_PlaceholderPainter#'));
debugProfileLayoutsEnabled = false;
debugProfilePaintsEnabled = true;
await runFrame(() { TestRoot.state.updateWidget(Placeholder(key: UniqueKey())); });
events = await fetchInterestingEvents();
expect(
events.map<String>(eventToName),
<String>['BUILD', 'LAYOUT', 'UPDATING COMPOSITING BITS', 'PAINT', 'RenderCustomPaint', 'COMPOSITING', 'FINALIZE TREE'],
);
args = (events.where((TimelineEvent event) => event.json!['name'] == '$RenderCustomPaint').single.json!['args'] as Map<String, Object?>).cast<String, String>();
expect(args['creator'], startsWith('CustomPaint'));
expect(args['creator'], contains('Placeholder'));
expect(args['foregroundPainter'], startsWith('_PlaceholderPainter#'));
debugProfilePaintsEnabled = false;
}, skip: isBrowser); // [intended] uses dart:isolate and io.
}