Something went wrong. Try again.
Main coves client
Something went wrong. Try again.
14 kB 428 lines
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429import 'dart:io';
import 'package:coves_flutter/services/api_exceptions.dart';import 'package:dio/dio.dart';import 'package:flutter/foundation.dart';import 'package:flutter_test/flutter_test.dart';
/// Tests for the canonical DioException → ApiException mapper.////// This is the single mapping used by CovesApiService, VoteService, and/// CommentService — behavior asserted here holds for every endpoint that/// delegates to it (CommentService.deleteComment substitutes its own/// message copy for 403/404 but keeps the taxonomy).void main() { DioException responseError( int statusCode, Object? data, { DioExceptionType type = DioExceptionType.badResponse, Headers? headers, }) { return DioException( requestOptions: RequestOptions(path: '/test'), type: type, response: Response( requestOptions: RequestOptions(path: '/test'), statusCode: statusCode, data: data, headers: headers, ), ); }
Headers retryAfterHeaders(List<String> values) { return Headers.fromMap({'Retry-After': values}); }
DioException networkError(DioExceptionType type, {String? message}) { return DioException( requestOptions: RequestOptions(path: '/test'), type: type, message: message, ); }
group('ApiException.fromDioError - responses with status codes', () { test('maps 401 to AuthenticationException', () { final exception = ApiException.fromDioError( responseError(401, {'message': 'Unauthorized'}), );
expect(exception, isA<AuthenticationException>()); expect(exception.statusCode, 401); expect(exception.message, 'Unauthorized'); });
test('maps 404 to NotFoundException', () { final exception = ApiException.fromDioError( responseError(404, {'message': 'Post not found'}), );
expect(exception, isA<NotFoundException>()); expect(exception.statusCode, 404); expect(exception.message, 'Post not found'); });
test('maps 5xx to ServerException', () { final exception = ApiException.fromDioError( responseError(500, {'error': 'Internal server error'}), );
expect(exception, isA<ServerException>()); expect(exception.statusCode, 500); expect(exception.message, 'Internal server error'); });
test('maps other status codes to plain ApiException', () { final exception = ApiException.fromDioError( responseError(400, {'message': 'Invalid post URI'}), );
expect(exception, isA<ApiException>()); expect(exception, isNot(isA<AuthenticationException>())); expect(exception.statusCode, 400); expect(exception.message, 'Invalid post URI'); });
test('prefers human-readable message over XRPC error code', () { final exception = ApiException.fromDioError( responseError(400, { 'error': 'InvalidRequest', 'message': 'title too long', }), );
expect(exception.message, 'title too long'); });
test('retains the XRPC error code through every response subtype', () { final cases = [ (statusCode: 400, expectedType: ApiException), (statusCode: 401, expectedType: AuthenticationException), (statusCode: 404, expectedType: NotFoundException), (statusCode: 500, expectedType: ServerException), ];
for (final testCase in cases) { final errorCode = 'MachineError${testCase.statusCode}'; final message = 'Display message ${testCase.statusCode}'; final error = responseError(testCase.statusCode, { 'error': errorCode, 'message': message, });
final exception = ApiException.fromDioError(error);
expect(exception.runtimeType, testCase.expectedType); expect(exception.errorCode, errorCode); expect(exception.message, message); expect(exception.statusCode, testCase.statusCode); expect(exception.originalError, same(error)); } });
test('parses and caps Retry-After for DiscoverUnavailable 503 only', () { for (var seconds = 0; seconds <= 300; seconds++) { final error = responseError(503, { 'error': 'DiscoverUnavailable', 'message': 'Discover is temporarily unavailable', }, headers: retryAfterHeaders(['$seconds']));
final exception = ApiException.fromDioError(error);
expect( exception.retryAfterSeconds, seconds, reason: 'Retry-After: $seconds', ); expect(exception.message, 'Discover is temporarily unavailable'); expect(exception.statusCode, 503); expect(exception.originalError, same(error)); }
for (final value in [ '301', '99999999999999999999999999999999999999999999999999', ]) { final exception = ApiException.fromDioError( responseError(503, { 'error': 'DiscoverUnavailable', }, headers: retryAfterHeaders([value])), );
expect(exception.retryAfterSeconds, 300, reason: 'Retry-After: $value'); } });
test('rejects invalid or inapplicable Retry-After values', () { for (final values in [ [''], ['not-a-number'], ['-1'], ['+1'], ['1.5'], ['1e2'], [' 1'], ['1 '], ['301seconds'], ['301, 20'], ['301.5'], ['999seconds'], ['999, 20'], ['999.5'], ['Wed, 21 Oct 2015 07:28:00 GMT'], ['10', '20'], ]) { final exception = ApiException.fromDioError( responseError(503, { 'error': 'DiscoverUnavailable', }, headers: retryAfterHeaders(values)), );
expect(exception.retryAfterSeconds, isNull, reason: '$values'); }
for (final statusCode in [502, 504]) { final exception = ApiException.fromDioError( responseError(statusCode, { 'error': 'DiscoverUnavailable', }, headers: retryAfterHeaders(['10'])), );
expect(exception.retryAfterSeconds, isNull); }
final wrongCode = ApiException.fromDioError( responseError(503, { 'error': 'OtherUnavailable', }, headers: retryAfterHeaders(['10'])), ); expect(wrongCode.retryAfterSeconds, isNull); });
test('falls back to the XRPC error code when message is absent', () { final exception = ApiException.fromDioError( responseError(400, {'error': 'InvalidRequest'}), );
expect(exception.message, 'InvalidRequest'); });
test('uses plain-text response bodies as the message', () { final exception = ApiException.fromDioError( responseError(502, 'upstream unavailable'), );
expect(exception, isA<ServerException>()); expect(exception.message, 'upstream unavailable'); });
test('uses a default message when the body has none', () { final exception = ApiException.fromDioError( responseError(400, <String, dynamic>{}), );
expect(exception.message, 'Request failed with status 400'); });
test('does not throw on non-string message/error fields', () { // A hostile or buggy server can return structured values here; the // mapper must never let a TypeError escape the taxonomy. final exception = ApiException.fromDioError( responseError(400, { 'message': {'detail': 'structured'}, 'error': 400, }), );
expect(exception, isA<ApiException>()); expect(exception.message, 'Request failed with status 400'); });
test('treats empty-string message as absent', () { final exception = ApiException.fromDioError( responseError(401, {'message': '', 'error': 'ExpiredToken'}), );
expect(exception, isA<AuthenticationException>()); expect(exception.message, 'ExpiredToken'); });
test('uses the default message for non-Map, non-String bodies', () { final exception = ApiException.fromDioError( responseError(400, ['unexpected', 'list']), );
expect(exception.message, 'Request failed with status 400'); });
test('maps by status code regardless of DioExceptionType', () { final exception = ApiException.fromDioError( responseError(401, { 'message': 'Token expired', }, type: DioExceptionType.unknown), );
expect(exception, isA<AuthenticationException>()); }); });
group('ApiException.fromDioError - network-level errors', () { test('maps timeouts to NetworkException', () { for (final type in [ DioExceptionType.connectionTimeout, DioExceptionType.sendTimeout, DioExceptionType.receiveTimeout, ]) { final exception = ApiException.fromDioError(networkError(type));
expect(exception, isA<NetworkException>()); expect(exception.message, contains('timeout')); } });
test('maps transformation timeout to a response processing error', () { final error = DioException.transformTimeout( timeout: const Duration(seconds: 5), requestOptions: RequestOptions(path: '/test'), );
final exception = ApiException.fromDioError(error);
expect(exception, isA<ApiException>()); expect(exception, isNot(isA<NetworkException>())); expect(exception.message, 'Timed out processing server response'); expect(exception.originalError, same(error)); });
test('maps connection errors to NetworkException', () { final exception = ApiException.fromDioError( networkError(DioExceptionType.connectionError), );
expect(exception, isA<NetworkException>()); expect(exception.message, contains('Network error')); });
test('maps DNS resolution failures to FederationException', () { final exception = ApiException.fromDioError( networkError( DioExceptionType.connectionError, message: 'Failed host lookup: pds.example.com', ), );
expect(exception, isA<FederationException>()); });
test('detects DNS failure via the typed SocketException too', () { // Dio's message text varies by platform; the typed inner error is // the reliable signal. final exception = ApiException.fromDioError( DioException( requestOptions: RequestOptions(path: '/test'), type: DioExceptionType.connectionError, error: const SocketException("Failed host lookup: 'x.example'"), ), );
expect(exception, isA<FederationException>()); });
test('maps bad certificates to NetworkException', () { final exception = ApiException.fromDioError( networkError(DioExceptionType.badCertificate), );
expect(exception, isA<NetworkException>()); expect(exception.message, contains('certificate')); });
test('maps cancelled requests to ApiException', () { final exception = ApiException.fromDioError( networkError(DioExceptionType.cancel), );
expect(exception.message, contains('cancelled')); });
test('maps unknown errors wrapping an IOException to NetworkException', () { final exception = ApiException.fromDioError( DioException( requestOptions: RequestOptions(path: '/test'), error: const SocketException('Connection reset by peer'), ), );
expect(exception, isA<NetworkException>()); expect(exception.message, contains('Network error')); });
test('maps unknown errors wrapping a FormatException to a parse ' 'ApiException, not a network error', () { // A truncated 200 body must not tell the user to check their // connection. final exception = ApiException.fromDioError( DioException( requestOptions: RequestOptions(path: '/test'), error: const FormatException('Unexpected end of input'), ), );
expect(exception, isA<ApiException>()); expect(exception, isNot(isA<NetworkException>())); expect(exception.message, 'Failed to parse server response'); });
test('maps bare unknown errors to a plain ApiException', () { final exception = ApiException.fromDioError( networkError(DioExceptionType.unknown), );
expect(exception, isA<ApiException>()); expect(exception, isNot(isA<NetworkException>())); expect(exception.message, contains('Unknown error')); }); });
group('mapDioException', () { late List<String> logLines; late DebugPrintCallback originalDebugPrint;
setUp(() { logLines = <String>[]; originalDebugPrint = debugPrint; debugPrint = (String? message, {int? wrapWidth}) { logLines.add(message ?? ''); }; });
tearDown(() { debugPrint = originalDebugPrint; });
test('returns the same mapping as fromDioError', () { final error = responseError(404, {'message': 'gone'});
final exception = mapDioException(error, operation: 'test op');
expect(exception, isA<NotFoundException>()); expect(exception.message, 'gone'); });
test('redacts tokens echoed in the logged response body', () { const token = 'abc!def.secret~token'; final error = responseError(500, { 'error': 'InternalServerError', 'message': 'debug echo: Bearer $token from upstream', });
mapDioException(error, operation: 'test op');
final output = logLines.join('\n'); expect(output, contains('Data:')); expect(output, contains('Bearer [REDACTED]')); expect(output, isNot(contains(token))); }); });}