widget_inspector_test_utils.dart 2.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// 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:convert';

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

class TestWidgetInspectorService extends Object with WidgetInspectorService {
13
  final Map<String, ServiceExtensionCallback> extensions = <String, ServiceExtensionCallback>{};
14

15
  final Map<String, List<Map<Object, Object?>>> eventsDispatched = <String, List<Map<Object, Object?>>>{};
16 17 18

  @override
  void registerServiceExtension({
19 20
    required String name,
    required ServiceExtensionCallback callback,
21 22 23 24 25 26
  }) {
    assert(!extensions.containsKey(name));
    extensions[name] = callback;
  }

  @override
27
  void postEvent(String eventKind, Map<Object, Object?> eventData) {
28 29 30
    getEventsDispatched(eventKind).add(eventData);
  }

31
  List<Map<Object, Object?>> getEventsDispatched(String eventKind) {
32
    return eventsDispatched.putIfAbsent(eventKind, () => <Map<Object, Object?>>[]);
33 34
  }

35
  Iterable<Map<Object, Object?>> getServiceExtensionStateChangedEvents(String extensionName) {
36
    return getEventsDispatched('Flutter.ServiceExtensionStateChanged')
37
      .where((Map<Object, Object?> event) => event['extension'] == extensionName);
38 39
  }

40
  Future<Object?> testExtension(String name, Map<String, String> arguments) async {
41 42 43
    expect(extensions, contains(name));
    // Encode and decode to JSON to match behavior using a real service
    // extension where only JSON is allowed.
44
    return (json.decode(json.encode(await extensions[name]!(arguments))) as Map<String, dynamic>)['result'];
45 46 47 48 49 50
  }

  Future<String> testBoolExtension(String name, Map<String, String> arguments) async {
    expect(extensions, contains(name));
    // Encode and decode to JSON to match behavior using a real service
    // extension where only JSON is allowed.
51
    return (json.decode(json.encode(await extensions[name]!(arguments))) as Map<String, dynamic>)['enabled'] as String;
52 53 54 55 56 57 58
  }

  int rebuildCount = 0;

  @override
  Future<void> forceRebuild() async {
    rebuildCount++;
59
    final WidgetsBinding binding = WidgetsBinding.instance;
60 61

    if (binding.renderViewElement != null) {
62
      binding.buildOwner!.reassemble(binding.renderViewElement!, null);
63 64
    }
  }
65 66 67 68 69 70 71

  @override
  void resetAllState() {
    super.resetAllState();
    eventsDispatched.clear();
    rebuildCount = 0;
  }
72
}