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