readtimeout_test.dart 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:pedantic/pedantic.dart';
  4. import 'package:dio/dio.dart';
  5. import 'package:test/test.dart';
  6. const SLEEP_DURATION_AFTER_CONNECTION_ESTABLISHED = 5000;
  7. HttpServer? _server;
  8. late Uri serverUrl;
  9. Future<int> getUnusedPort() async {
  10. HttpServer? server;
  11. try {
  12. server = await HttpServer.bind('localhost', 0);
  13. return server.port;
  14. } finally {
  15. unawaited(server?.close());
  16. }
  17. }
  18. void startServer() async {
  19. var port = await getUnusedPort();
  20. serverUrl = Uri.parse('http://localhost:$port');
  21. _server = await HttpServer.bind('localhost', port);
  22. _server?.listen((request) {
  23. const content = 'success';
  24. var response = request.response;
  25. sleep(const Duration(
  26. milliseconds: SLEEP_DURATION_AFTER_CONNECTION_ESTABLISHED));
  27. response
  28. ..statusCode = 200
  29. ..contentLength = content.length
  30. ..write(content);
  31. response.close();
  32. return;
  33. });
  34. }
  35. void stopServer() {
  36. if (_server != null) {
  37. _server!.close();
  38. _server = null;
  39. }
  40. }
  41. void main() {
  42. setUp(startServer);
  43. tearDown(stopServer);
  44. test(
  45. '#read_timeout - catch DioError when receiveTimeout < $SLEEP_DURATION_AFTER_CONNECTION_ESTABLISHED',
  46. () async {
  47. var dio = Dio();
  48. dio.options
  49. ..baseUrl = serverUrl.toString()
  50. ..connectTimeout = SLEEP_DURATION_AFTER_CONNECTION_ESTABLISHED - 1000;
  51. DioError error;
  52. try {
  53. await dio.get('/');
  54. fail('did not throw');
  55. } on DioError catch (e) {
  56. error = e;
  57. }
  58. expect(error, isNotNull);
  59. expect(error.type == DioErrorType.connectTimeout, isTrue);
  60. });
  61. test(
  62. '#read_timeout - no DioError when receiveTimeout > $SLEEP_DURATION_AFTER_CONNECTION_ESTABLISHED',
  63. () async {
  64. var dio = Dio();
  65. dio.options
  66. ..baseUrl = serverUrl.toString()
  67. ..connectTimeout = SLEEP_DURATION_AFTER_CONNECTION_ESTABLISHED + 1000;
  68. DioError? error;
  69. try {
  70. await dio.get('/');
  71. } on DioError catch (e) {
  72. error = e;
  73. print(e.requestOptions.uri);
  74. }
  75. expect(error, isNull);
  76. });
  77. }