image_provider_network_image_test.dart 9.81 KB
Newer Older
1 2 3 4 5 6 7 8
// 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:io';
import 'dart:math' as math;
import 'dart:typed_data';
9
import 'dart:ui' show Codec, FrameInfo;
10 11 12 13 14

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

15
import '../image_data.dart';
16 17 18
import '../rendering/rendering_tester.dart';

void main() {
19
  TestRenderingFlutterBinding.ensureInitialized();
20

21
  Future<Codec>  basicDecoder(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
22
    return PaintingBinding.instance.instantiateImageCodec(bytes, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling ?? false);
23
  }
24

25
  late _FakeHttpClient httpClient;
26 27

  setUp(() {
28
    httpClient = _FakeHttpClient();
29 30 31 32 33
    debugNetworkImageHttpClientProvider = () => httpClient;
  });

  tearDown(() {
    debugNetworkImageHttpClientProvider = null;
34 35
    PaintingBinding.instance.imageCache.clear();
    PaintingBinding.instance.imageCache.clearLiveImages();
36 37
  });

38
  test('Expect thrown exception with statusCode - evicts from cache and drains', () async {
39
    const int errorStatusCode = HttpStatus.notFound;
40 41
    const String requestUrl = 'foo-url';

42
    httpClient.request.response.statusCode = errorStatusCode;
43 44 45 46

    final Completer<dynamic> caughtError = Completer<dynamic>();

    final ImageProvider imageProvider = NetworkImage(nonconst(requestUrl));
47 48
    expect(imageCache.pendingImageCount, 0);
    expect(imageCache.statusForKey(imageProvider).untracked, true);
49 50 51

    final ImageStream result = imageProvider.resolve(ImageConfiguration.empty);

52 53
    expect(imageCache.pendingImageCount, 1);
    expect(imageCache.statusForKey(imageProvider).pending, true);
54 55

    result.addListener(ImageStreamListener((ImageInfo info, bool syncCall) {
56
    }, onError: (dynamic error, StackTrace? stackTrace) {
57 58 59 60 61
      caughtError.complete(error);
    }));

    final dynamic err = await caughtError.future;

62 63
    expect(imageCache.pendingImageCount, 0);
    expect(imageCache.statusForKey(imageProvider).untracked, true);
64 65 66 67 68 69 70

    expect(
      err,
      isA<NetworkImageLoadException>()
        .having((NetworkImageLoadException e) => e.statusCode, 'statusCode', errorStatusCode)
        .having((NetworkImageLoadException e) => e.uri, 'uri', Uri.base.resolve(requestUrl)),
    );
71
    expect(httpClient.request.response.drained, true);
72
  }, skip: isBrowser); // [intended] Browser implementation does not use HTTP client but an <img> tag.
73 74

  test('Uses the HttpClient provided by debugNetworkImageHttpClientProvider if set', () async {
75
    httpClient.thrownError = 'client1';
76 77 78 79
    final List<dynamic> capturedErrors = <dynamic>[];

    Future<void> loadNetworkImage() async {
      final NetworkImage networkImage = NetworkImage(nonconst('foo'));
80
      final ImageStreamCompleter completer = networkImage.load(networkImage, basicDecoder);
81 82
      completer.addListener(ImageStreamListener(
        (ImageInfo image, bool synchronousCall) { },
83
        onError: (dynamic error, StackTrace? stackTrace) {
84 85 86 87 88 89 90 91
          capturedErrors.add(error);
        },
      ));
      await Future<void>.value();
    }

    await loadNetworkImage();
    expect(capturedErrors, <dynamic>['client1']);
92 93
    final _FakeHttpClient client2 = _FakeHttpClient();
    client2.thrownError = 'client2';
94 95 96
    debugNetworkImageHttpClientProvider = () => client2;
    await loadNetworkImage();
    expect(capturedErrors, <dynamic>['client1', 'client2']);
97
  }, skip: isBrowser); // [intended] Browser implementation does not use HTTP client but an <img> tag.
98 99

  test('Propagates http client errors during resolve()', () async {
100
    httpClient.thrownError = Error();
101 102
    bool uncaught = false;

103
    final FlutterExceptionHandler? oldError = FlutterError.onError;
104 105 106 107 108 109 110 111
    await runZoned(() async {
      const ImageProvider imageProvider = NetworkImage('asdasdasdas');
      final Completer<bool> caughtError = Completer<bool>();
      FlutterError.onError = (FlutterErrorDetails details) {
        throw Error();
      };
      final ImageStream result = imageProvider.resolve(ImageConfiguration.empty);
      result.addListener(ImageStreamListener((ImageInfo info, bool syncCall) {
112
      }, onError: (dynamic error, StackTrace? stackTrace) {
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        caughtError.complete(true);
      }));
      expect(await caughtError.future, true);
    }, zoneSpecification: ZoneSpecification(
      handleUncaughtError: (Zone zone, ZoneDelegate zoneDelegate, Zone parent, Object error, StackTrace stackTrace) {
        uncaught = true;
      },
    ));
    expect(uncaught, false);
    FlutterError.onError = oldError;
  });

  test('Notifies listeners of chunk events', () async {
    const int chunkSize = 8;
    final List<Uint8List> chunks = <Uint8List>[
      for (int offset = 0; offset < kTransparentImage.length; offset += chunkSize)
        Uint8List.fromList(kTransparentImage.skip(offset).take(chunkSize).toList()),
    ];
    final Completer<void> imageAvailable = Completer<void>();
132 133 134 135 136

    httpClient.request.response
      ..statusCode = HttpStatus.ok
      ..contentLength = kTransparentImage.length
      ..content = chunks;
137 138 139 140 141 142 143 144 145 146 147

    final ImageProvider imageProvider = NetworkImage(nonconst('foo'));
    final ImageStream result = imageProvider.resolve(ImageConfiguration.empty);
    final List<ImageChunkEvent> events = <ImageChunkEvent>[];
    result.addListener(ImageStreamListener(
      (ImageInfo image, bool synchronousCall) {
        imageAvailable.complete();
      },
      onChunk: (ImageChunkEvent event) {
        events.add(event);
      },
148 149
      onError: (dynamic error, StackTrace? stackTrace) {
        imageAvailable.completeError(error as Object, stackTrace);
150 151 152 153 154 155 156 157
      },
    ));
    await imageAvailable.future;
    expect(events.length, chunks.length);
    for (int i = 0; i < events.length; i++) {
      expect(events[i].cumulativeBytesLoaded, math.min((i + 1) * chunkSize, kTransparentImage.length));
      expect(events[i].expectedTotalBytes, kTransparentImage.length);
    }
158
  }, skip: isBrowser); // [intended] Browser loads images through <img> not Http.
159 160

  test('NetworkImage is evicted from cache on SocketException', () async {
161 162
    final _FakeHttpClient mockHttpClient = _FakeHttpClient();
    mockHttpClient.thrownError = const SocketException('test exception');
163 164 165
    debugNetworkImageHttpClientProvider = () => mockHttpClient;

    final ImageProvider imageProvider = NetworkImage(nonconst('testing.url'));
166 167
    expect(imageCache.pendingImageCount, 0);
    expect(imageCache.statusForKey(imageProvider).untracked, true);
168 169 170

    final ImageStream result = imageProvider.resolve(ImageConfiguration.empty);

171 172
    expect(imageCache.pendingImageCount, 1);
    expect(imageCache.statusForKey(imageProvider).pending, true);
173 174 175
    final Completer<dynamic> caughtError = Completer<dynamic>();
    result.addListener(ImageStreamListener(
      (ImageInfo info, bool syncCall) {},
176
      onError: (dynamic error, StackTrace? stackTrace) {
177 178 179 180 181 182 183 184
        caughtError.complete(error);
      },
    ));

    final dynamic err = await caughtError.future;

    expect(err, isA<SocketException>());

185 186 187
    expect(imageCache.pendingImageCount, 0);
    expect(imageCache.statusForKey(imageProvider).untracked, true);
    expect(imageCache.containsKey(result), isFalse);
188 189

    debugNetworkImageHttpClientProvider = null;
190
  }, skip: isBrowser); // [intended] Browser does not resolve images this way.
191

192
  Future<Codec> decoder(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) async {
193 194 195 196 197 198 199 200 201 202
    return FakeCodec();
  }

  test('Network image sets tag', () async {
    const String url = 'http://test.png';
    const int chunkSize = 8;
    final List<Uint8List> chunks = <Uint8List>[
      for (int offset = 0; offset < kTransparentImage.length; offset += chunkSize)
        Uint8List.fromList(kTransparentImage.skip(offset).take(chunkSize).toList()),
    ];
203 204 205 206
    httpClient.request.response
      ..statusCode = HttpStatus.ok
      ..contentLength = kTransparentImage.length
      ..content = chunks;
207 208 209

    const NetworkImage provider = NetworkImage(url);

210
    final MultiFrameImageStreamCompleter completer = provider.load(provider, decoder) as MultiFrameImageStreamCompleter;
211 212 213

    expect(completer.debugLabel, url);
  });
214
}
215

216 217
class _FakeHttpClient extends Fake implements HttpClient {
  final _FakeHttpClientRequest request = _FakeHttpClientRequest();
218
  Object? thrownError;
219 220 221 222

  @override
  Future<HttpClientRequest> getUrl(Uri url) async {
    if (thrownError != null) {
223
      throw thrownError!;
224 225 226 227 228 229 230 231 232 233 234
    }
    return request;
  }
}
class _FakeHttpClientRequest extends Fake implements HttpClientRequest {
  final _FakeHttpClientResponse response = _FakeHttpClientResponse();

  @override
  Future<HttpClientResponse> close() async {
    return response;
  }
235 236
}

237
class _FakeHttpClientResponse extends Fake implements HttpClientResponse {
238 239
  bool drained = false;

240 241 242 243 244 245 246 247 248
  @override
  int statusCode = HttpStatus.ok;

  @override
  int contentLength = 0;

  @override
  HttpClientResponseCompressionState get compressionState => HttpClientResponseCompressionState.notCompressed;

249
  late List<List<int>> content;
250 251

  @override
252
  StreamSubscription<List<int>> listen(void Function(List<int> event)? onData, {Function? onError, void Function()? onDone, bool? cancelOnError}) {
253 254 255 256 257 258 259
    return Stream<List<int>>.fromIterable(content).listen(
      onData,
      onDone: onDone,
      onError: onError,
      cancelOnError: cancelOnError,
    );
  }
260 261 262 263

  @override
  Future<E> drain<E>([E? futureValue]) async {
    drained = true;
264
    return futureValue ?? futureValue as E; // Mirrors the implementation in Stream.
265
  }
266
}
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

class FakeCodec implements Codec {
  @override
  void dispose() {}

  @override
  int get frameCount => throw UnimplementedError();

  @override
  Future<FrameInfo> getNextFrame() {
    throw UnimplementedError();
  }

  @override
  int get repetitionCount => throw UnimplementedError();
}