Skip to content

Commit

Permalink
add ability to mock images by url
Browse files Browse the repository at this point in the history
  • Loading branch information
pedrox-hs committed Mar 2, 2024
1 parent d4df7d2 commit 2fd21e9
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import 'dart:typed_data';

import 'package:mocktail/mocktail.dart';

/// Signature for a function that returns a [Uint8List] for a given [Uri].
typedef ImageMockProvider = Uint8List Function(Uri uri);

/// {@template mocktail_image_network}
/// Utility method that allows you to execute a widget test when you pump a
/// widget that contains an `Image.network` node in its tree.
Expand Down Expand Up @@ -41,11 +44,20 @@ import 'package:mocktail/mocktail.dart';
/// ```
/// {@endtemplate}
T mockNetworkImages<T>(T Function() body, {Uint8List? imageBytes}) {
return mockNetworkImagesWith(
body,
provider: (uri) => imageBytes ?? _defaultMockProvider(uri),
);
}

/// {@macro mocktail_image_network}
T mockNetworkImagesWith<T>(
T Function() body, {
ImageMockProvider provider = _defaultMockProvider,
}) {
return HttpOverrides.runZoned(
body,
createHttpClient: (_) => _createHttpClient(
data: imageBytes ?? _transparentPixelPng,
),
createHttpClient: (_) => _createHttpClient(provider),
);
}

Expand All @@ -62,14 +74,43 @@ class _MockHttpClientResponse extends Mock implements HttpClientResponse {}

class _MockHttpHeaders extends Mock implements HttpHeaders {}

HttpClient _createHttpClient({required List<int> data}) {
HttpClient _createHttpClient(ImageMockProvider mockProvider) {
final client = _MockHttpClient();
when(() => client.getUrl(any())).thenAnswer(
(invokation) async => _createRequest(
invokation.positionalArguments.first as Uri,
mockProvider,
),
);
return client;
}

HttpClientRequest _createRequest(
Uri uri,
ImageMockProvider mockProvider,
) {
final request = _MockHttpClientRequest();
final headers = _MockHttpHeaders();
when(() => request.headers).thenReturn(headers);
when(request.close).thenAnswer(
(invokation) async => _createResponseForUri(uri, mockProvider),
);

return request;
}

HttpClientResponse _createResponseForUri(
Uri uri,
ImageMockProvider mockProvider,
) {
final response = _MockHttpClientResponse();
final headers = _MockHttpHeaders();

final data = mockProvider(uri);

when(() => response.compressionState)
.thenReturn(HttpClientResponseCompressionState.notCompressed);
when(() => response.contentLength).thenReturn(_transparentPixelPng.length);
when(() => response.contentLength).thenReturn(data.length);
when(() => response.statusCode).thenReturn(HttpStatus.ok);
when(
() => response.listen(
Expand All @@ -85,12 +126,23 @@ HttpClient _createHttpClient({required List<int> data}) {
return Stream<List<int>>.fromIterable(<List<int>>[data])
.listen(onData, onDone: onDone);
});
when(() => request.headers).thenReturn(headers);
when(request.close).thenAnswer((_) async => response);
when(() => client.getUrl(any())).thenAnswer((_) async => request);
return client;
when(() => response.headers).thenReturn(headers);

return response;
}

Uint8List _defaultMockProvider(Uri uri) {
final extension = uri.path.split('.').last;
return _mockedResponses[extension] ?? _transparentPixelPng;
}

final _mockedResponses = <String, Uint8List>{
'png': _transparentPixelPng,
'svg': base64Decode(
'''PHN2ZyB3aWR0aD0nMTAwJyBoZWlnaHQ9JzEwMCcgdmlld0JveD0nMCAwIDEgMCAxMDAnIC8+''',
),
};

final _transparentPixelPng = base64Decode(
'''iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==''',
);
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,27 @@ void main() {
imageBytes: greenPixel,
);
});

test(
'should properly mock svg response and complete without exceptions',
() async {
await mockNetworkImages(() async {
final expectedData = base64Decode(
'''PHN2ZyB3aWR0aD0nMTAwJyBoZWlnaHQ9JzEwMCcgdmlld0JveD0nMCAwIDEgMCAxMDAnIC8+''',
);
final client = HttpClient()..autoUncompress = false;
final request = await client.getUrl(Uri.https('', '/image.svg'));
final response = await request.close();
final data = <int>[];

response.listen(data.addAll);

// Wait for all microtasks to run
await Future<void>.delayed(Duration.zero);

expect(data, equals(expectedData));
});
},
);
});
}

0 comments on commit 2fd21e9

Please sign in to comment.