Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(mocktail_image_network): add customizable imageBytes #214

Merged
merged 8 commits into from Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:mocktail/mocktail.dart';

Expand Down Expand Up @@ -39,10 +40,12 @@ import 'package:mocktail/mocktail.dart';
/// }
/// ```
/// {@endtemplate}
T mockNetworkImages<T>(T Function() body) {
T mockNetworkImages<T>(T Function() body, {Uint8List? imageBytes}) {
return HttpOverrides.runZoned(
body,
createHttpClient: (_) => _createHttpClient(),
createHttpClient: (_) => _createHttpClient(
data: imageBytes ?? _transparentPixelPng,
),
);
}

Expand All @@ -59,7 +62,7 @@ class _MockHttpClientResponse extends Mock implements HttpClientResponse {}

class _MockHttpHeaders extends Mock implements HttpHeaders {}

HttpClient _createHttpClient() {
HttpClient _createHttpClient({required List<int> data}) {
final client = _MockHttpClient();
final request = _MockHttpClientRequest();
final response = _MockHttpClientResponse();
Expand All @@ -79,7 +82,7 @@ HttpClient _createHttpClient() {
final onData =
invocation.positionalArguments[0] as void Function(List<int>);
final onDone = invocation.namedArguments[#onDone] as void Function()?;
return Stream<List<int>>.fromIterable(<List<int>>[_transparentPixelPng])
return Stream<List<int>>.fromIterable(<List<int>>[data])
.listen(onData, onDone: onDone);
});
when(() => request.headers).thenReturn(headers);
Expand Down
Expand Up @@ -44,5 +44,27 @@ void main() {
expect(onDoneCalled, isTrue);
});
});

test('should properly use custom imageBytes', () async {
final greenPixel = base64Decode(
'''iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAEBgIApD5fRAAAAABJRU5ErkJggg==''',
);
await mockNetworkImages(
() async {
final client = HttpClient()..autoUncompress = false;
final request = await client.getUrl(Uri.https(''));
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(greenPixel));
},
imageBytes: greenPixel,
);
});
});
}