memory_allocations_test.dart 2.17 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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.

import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  final MemoryAllocations ma = MemoryAllocations.instance;

  setUp(() {
    assert(!ma.hasListeners);
    _checkSdkHandlersNotSet();
  });

  test('kFlutterMemoryAllocationsEnabled is false in release mode.', () {
    expect(kFlutterMemoryAllocationsEnabled, isFalse);
  });

22
  testWidgets(
23
    '$MemoryAllocations is noop when kFlutterMemoryAllocationsEnabled is false.',
24
    (WidgetTester tester) async {
Lioness100's avatar
Lioness100 committed
25 26
      ObjectEvent? receivedEvent;
      ObjectEvent listener(ObjectEvent event) => receivedEvent = event;
27 28 29

      ma.addListener(listener);
      _checkSdkHandlersNotSet();
30
      expect(ma.hasListeners, isFalse);
31

32
      await _activateFlutterObjects(tester);
33
      _checkSdkHandlersNotSet();
Lioness100's avatar
Lioness100 committed
34
      expect(receivedEvent, isNull);
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
      expect(ma.hasListeners, isFalse);

      ma.removeListener(listener);
      _checkSdkHandlersNotSet();
    },
  );
}

void _checkSdkHandlersNotSet() {
  expect(Image.onCreate, isNull);
  expect(Picture.onCreate, isNull);
  expect(Image.onDispose, isNull);
  expect(Picture.onDispose, isNull);
}

/// Create and dispose Flutter objects to fire memory allocation events.
51
Future<void> _activateFlutterObjects(WidgetTester tester) async {
52 53 54 55 56 57 58
  final ValueNotifier<bool> valueNotifier = ValueNotifier<bool>(true);
  final ChangeNotifier changeNotifier = ChangeNotifier()..addListener(() {});
  final Picture picture = _createPicture();

  valueNotifier.dispose();
  changeNotifier.dispose();
  picture.dispose();
59

60 61
  final Image image = await _createImage();
  image.dispose();
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
}

Future<Image> _createImage() async {
  final Picture picture = _createPicture();
  final Image result = await picture.toImage(10, 10);
  picture.dispose();
  return result;
}

Picture _createPicture() {
  final PictureRecorder recorder = PictureRecorder();
  final Canvas canvas = Canvas(recorder);
  const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0);
  canvas.clipRect(rect);
  return recorder.endRecording();
}