Skip to content

Commit

Permalink
✅ Add test
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexV525 committed Jun 27, 2024
1 parent f5c3a16 commit 84264e7
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions dio/test/cancel_token_test.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:typed_data' show Uint8List;

import 'package:dio/dio.dart';
import 'package:dio/src/adapters/io_adapter.dart';
import 'package:dio_test/util.dart';
Expand Down Expand Up @@ -112,4 +114,66 @@ void main() {
expect(walkThroughHandlers, isFalse);
});
});

test('deallocates HttpClientRequest', () async {
final client = MockHttpClient();
final dio = Dio();
dio.httpClientAdapter = IOHttpClientAdapter(
createHttpClient: () => client,
);
final token = CancelToken();
final requests = <MockHttpClientRequest>{};
final requestsReferences = <WeakReference<MockHttpClientRequest>>{};
when(client.openUrl(any, any)).thenAnswer((_) async {
final request = MockHttpClientRequest();
requests.add(request);
requestsReferences.add(WeakReference(request));
when(request.close()).thenAnswer((_) async {
final response = MockHttpClientResponse();
when(response.headers).thenReturn(MockHttpHeaders());
when(response.statusCode).thenReturn(200);
when(response.reasonPhrase).thenReturn('OK');
when(response.isRedirect).thenReturn(false);
when(response.redirects).thenReturn([]);
when(response.cast())
.thenAnswer((_) => const Stream<Uint8List>.empty());
await Future.delayed(const Duration(milliseconds: 200));
return response;
});
when(request.abort()).thenAnswer((realInvocation) {
requests.remove(request);
});
return request;
});

final futures = [
dio.get('https://does.not.exists', cancelToken: token),
dio.get('https://does.not.exists', cancelToken: token),
];
for (final future in futures) {
expectLater(
future,
throwsDioException(DioExceptionType.cancel),
);
}

// Opening requests.
await Future.delayed(const Duration(milliseconds: 100));
token.cancel();
// Aborting requests.
await Future.delayed(const Duration(seconds: 1));
expect(requests, isEmpty);

try {
await Future.wait(futures);
} catch (_) {
// Waiting here until all futures are completed.
}
expect(requests, isEmpty);
expect(requestsReferences, hasLength(2));

// GC.
List.generate(1 * 1024 * 1024, (index) => Object());
expect(requestsReferences.every((e) => e.target == null), isTrue);
});
}

0 comments on commit 84264e7

Please sign in to comment.