forked from eatvio/eatvio_app
test(session): cover avatar refresh and session teardown
Add regression tests for avatar reset and token-change refresh, stale 401 handling, idempotent session teardown and account-scoped preference cleanup. Update existing cubit tests for the new session dependency. Refs: #1113
This commit is contained in:
118
test/core/interceptors/token_interceptor_session_test.dart
Normal file
118
test/core/interceptors/token_interceptor_session_test.dart
Normal file
@@ -0,0 +1,118 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/interceptors/token_interceptor.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../fixtures/doubles/session_doubles.dart';
|
||||
|
||||
class _RecordingErrorInterceptorHandler extends ErrorInterceptorHandler {
|
||||
int nextCalls = 0;
|
||||
DioException? nextError;
|
||||
|
||||
@override
|
||||
void next(DioException error) {
|
||||
nextCalls++;
|
||||
nextError = error;
|
||||
}
|
||||
|
||||
@override
|
||||
void resolve(Response<dynamic> response) {
|
||||
throw UnimplementedError('resolve should not be called');
|
||||
}
|
||||
|
||||
@override
|
||||
void reject(
|
||||
DioException error, [
|
||||
bool callFollowingErrorInterceptor = false,
|
||||
]) {
|
||||
throw UnimplementedError('reject should not be called');
|
||||
}
|
||||
}
|
||||
|
||||
DioException _unauthorized(RequestOptions options) {
|
||||
return DioException(
|
||||
requestOptions: options,
|
||||
response: Response<dynamic>(requestOptions: options, statusCode: 401),
|
||||
type: DioExceptionType.badResponse,
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late FakeSessionLifecycleService sessionLifecycleService;
|
||||
late TokenInterceptor interceptor;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
TokenStorage.clearCache();
|
||||
await sl.reset();
|
||||
|
||||
sessionLifecycleService = FakeSessionLifecycleService();
|
||||
sl.registerSingleton<SessionLifecycleService>(sessionLifecycleService);
|
||||
interceptor = TokenInterceptor();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await sl.reset();
|
||||
TokenStorage.clearCache();
|
||||
});
|
||||
|
||||
group('TokenInterceptor.onError 401', () {
|
||||
test('request without Authorization does not end the session', () async {
|
||||
await TokenStorage.saveTokenInStorage('current-token');
|
||||
|
||||
final options = RequestOptions(path: '/api/profile/index');
|
||||
final error = _unauthorized(options);
|
||||
final handler = _RecordingErrorInterceptorHandler();
|
||||
|
||||
await interceptor.onError(error, handler);
|
||||
|
||||
expect(handler.nextCalls, 1);
|
||||
expect(handler.nextError, same(error));
|
||||
expect(sessionLifecycleService.endSessionCalls, 0);
|
||||
});
|
||||
|
||||
test('stale request token does not end the new session', () async {
|
||||
await TokenStorage.saveTokenInStorage('new-token');
|
||||
|
||||
final options = RequestOptions(path: '/api/profile/index');
|
||||
options.headers['Authorization'] = 'Bearer old-token';
|
||||
options.extra['authToken'] = 'old-token';
|
||||
|
||||
final error = _unauthorized(options);
|
||||
final handler = _RecordingErrorInterceptorHandler();
|
||||
|
||||
await interceptor.onError(error, handler);
|
||||
|
||||
expect(handler.nextCalls, 1);
|
||||
expect(sessionLifecycleService.endSessionCalls, 0);
|
||||
});
|
||||
|
||||
test(
|
||||
'current request token ends the session once as unauthorized',
|
||||
() async {
|
||||
await TokenStorage.saveTokenInStorage('current-token');
|
||||
|
||||
final options = RequestOptions(path: '/api/profile/index');
|
||||
options.headers['Authorization'] = 'Bearer current-token';
|
||||
options.extra['authToken'] = 'current-token';
|
||||
|
||||
final error = _unauthorized(options);
|
||||
final handler = _RecordingErrorInterceptorHandler();
|
||||
|
||||
await interceptor.onError(error, handler);
|
||||
|
||||
expect(handler.nextCalls, 1);
|
||||
expect(sessionLifecycleService.endSessionCalls, 1);
|
||||
expect(
|
||||
sessionLifecycleService.lastEndReason,
|
||||
SessionEndReason.unauthorized,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,22 +1,24 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/interceptors/token_interceptor.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../fixtures/doubles/session_doubles.dart';
|
||||
|
||||
class MockRequestOptions extends Mock implements RequestOptions {}
|
||||
|
||||
class MockRequestInterceptorHandler extends Mock implements RequestInterceptorHandler {}
|
||||
class MockRequestInterceptorHandler extends Mock
|
||||
implements RequestInterceptorHandler {}
|
||||
|
||||
class MockErrorInterceptorHandler extends Mock implements ErrorInterceptorHandler {}
|
||||
class MockErrorInterceptorHandler extends Mock
|
||||
implements ErrorInterceptorHandler {}
|
||||
|
||||
class MockResponse extends Mock implements Response {}
|
||||
|
||||
class MockWsManager extends Mock implements WsManager {}
|
||||
|
||||
class MockDioException extends Mock implements DioException {}
|
||||
|
||||
class FakeRequestOptions extends Fake implements RequestOptions {}
|
||||
@@ -32,23 +34,18 @@ void main() {
|
||||
});
|
||||
group('TokenInterceptor', () {
|
||||
late TokenInterceptor interceptor;
|
||||
late FakeSessionLifecycleService fakeSession;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
final mockWsManager = MockWsManager();
|
||||
when(() => mockWsManager.clear()).thenAnswer((_) async {});
|
||||
|
||||
await sl.reset(); // Сбрасываем sl перед каждым тестом
|
||||
sl.registerSingleton<WsManager>(mockWsManager);
|
||||
|
||||
TokenStorage.clearCache();
|
||||
|
||||
await sl.reset();
|
||||
fakeSession = FakeSessionLifecycleService();
|
||||
sl.registerSingleton<SessionLifecycleService>(fakeSession);
|
||||
|
||||
interceptor = TokenInterceptor();
|
||||
// Сбрасываем токен перед каждым тестом
|
||||
try {
|
||||
await TokenStorage.removeTokenInStorage();
|
||||
} catch (e) {
|
||||
// Игнорируем ошибки при очистке
|
||||
}
|
||||
await TokenStorage.removeTokenInStorage();
|
||||
});
|
||||
|
||||
group('onRequest', () {
|
||||
@@ -59,6 +56,7 @@ void main() {
|
||||
final headers = <String, dynamic>{};
|
||||
final options = MockRequestOptions();
|
||||
when(() => options.headers).thenReturn(headers);
|
||||
when(() => options.extra).thenReturn(<String, dynamic>{});
|
||||
final handler = MockRequestInterceptorHandler();
|
||||
|
||||
when(() => handler.next(any())).thenReturn(null);
|
||||
@@ -73,6 +71,7 @@ void main() {
|
||||
final headers = <String, dynamic>{};
|
||||
final options = MockRequestOptions();
|
||||
when(() => options.headers).thenReturn(headers);
|
||||
when(() => options.extra).thenReturn(<String, dynamic>{});
|
||||
final handler = MockRequestInterceptorHandler();
|
||||
|
||||
when(() => handler.next(any())).thenReturn(null);
|
||||
@@ -89,6 +88,7 @@ void main() {
|
||||
final headers = <String, dynamic>{};
|
||||
final options = MockRequestOptions();
|
||||
when(() => options.headers).thenReturn(headers);
|
||||
when(() => options.extra).thenReturn(<String, dynamic>{});
|
||||
final handler = MockRequestInterceptorHandler();
|
||||
|
||||
when(() => handler.next(any())).thenReturn(null);
|
||||
@@ -101,11 +101,16 @@ void main() {
|
||||
});
|
||||
|
||||
group('onError', () {
|
||||
test('удаляет токен и перенаправляет на auth при 401', () async {
|
||||
test('завершает сессию при 401 для текущего токена', () async {
|
||||
const token = 'test-token';
|
||||
await TokenStorage.saveTokenInStorage(token);
|
||||
|
||||
final options = MockRequestOptions();
|
||||
when(
|
||||
() => options.headers,
|
||||
).thenReturn({'Authorization': 'Bearer $token'});
|
||||
when(() => options.extra).thenReturn({'authToken': token});
|
||||
|
||||
final response = MockResponse();
|
||||
when(() => response.statusCode).thenReturn(401);
|
||||
|
||||
@@ -116,14 +121,10 @@ void main() {
|
||||
final handler = MockErrorInterceptorHandler();
|
||||
when(() => handler.next(any())).thenReturn(null);
|
||||
|
||||
// Проверяем, что токен был удален
|
||||
final tokenBefore = await TokenStorage.getTokenFromStorage();
|
||||
expect(tokenBefore, token);
|
||||
|
||||
await interceptor.onError(error, handler);
|
||||
|
||||
final tokenAfter = await TokenStorage.getTokenFromStorage();
|
||||
expect(tokenAfter, null);
|
||||
expect(fakeSession.endSessionCalls, 1);
|
||||
expect(fakeSession.lastEndReason, SessionEndReason.unauthorized);
|
||||
verify(() => handler.next(error)).called(1);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user