forked from eatvio/eatvio_app
feat(app): refactoring of sentry using, feat(become_consultant): fixed possible infinite loading, feat(push_notifications): fixed push navigation from paid plan push
This commit is contained in:
@@ -103,11 +103,12 @@ void main() {
|
||||
.called(1);
|
||||
});
|
||||
|
||||
test('rethrows exception when error occurs', () async {
|
||||
test('returns false when prefs throws (error is reported)', () async {
|
||||
when(mockPrefs.getInt(PrefsKeys.registrationDate))
|
||||
.thenThrow(Exception('Test error'));
|
||||
|
||||
expect(() => cubit.checkRegistrationDate(), throwsException);
|
||||
final result = await cubit.checkRegistrationDate();
|
||||
expect(result, false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
114
test/core/error_reporting/error_report_policy_test.dart
Normal file
114
test/core/error_reporting/error_report_policy_test.dart
Normal file
@@ -0,0 +1,114 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/error_report_policy.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
|
||||
void main() {
|
||||
group('ErrorReportPolicy.shouldReport', () {
|
||||
test('returns false for null', () {
|
||||
expect(ErrorReportPolicy.shouldReport(null), false);
|
||||
});
|
||||
|
||||
test('returns false for String', () {
|
||||
expect(ErrorReportPolicy.shouldReport('user message'), false);
|
||||
});
|
||||
|
||||
test('returns false for SocketException', () {
|
||||
expect(ErrorReportPolicy.shouldReport(const SocketException('offline')), false);
|
||||
});
|
||||
|
||||
test('returns false for cancelled Dio request', () {
|
||||
final e = DioException(
|
||||
requestOptions: RequestOptions(path: '/x'),
|
||||
type: DioExceptionType.cancel,
|
||||
);
|
||||
expect(ErrorReportPolicy.shouldReport(e), false);
|
||||
});
|
||||
|
||||
test('returns false for Dio timeouts', () {
|
||||
for (final type in [
|
||||
DioExceptionType.connectionTimeout,
|
||||
DioExceptionType.sendTimeout,
|
||||
DioExceptionType.receiveTimeout,
|
||||
]) {
|
||||
final e = DioException(
|
||||
requestOptions: RequestOptions(path: '/x'),
|
||||
type: type,
|
||||
);
|
||||
expect(ErrorReportPolicy.shouldReport(e), false, reason: '$type');
|
||||
}
|
||||
});
|
||||
|
||||
test('returns false for HTTP 4xx with response', () {
|
||||
final e = DioException(
|
||||
requestOptions: RequestOptions(path: '/x'),
|
||||
response: Response(statusCode: 422, requestOptions: RequestOptions(path: '/x')),
|
||||
type: DioExceptionType.badResponse,
|
||||
);
|
||||
expect(ErrorReportPolicy.shouldReport(e), false);
|
||||
});
|
||||
|
||||
test('returns false for HTTP 5xx (handled by sentry_dio failed-request)', () {
|
||||
final e = DioException(
|
||||
requestOptions: RequestOptions(path: '/x'),
|
||||
response: Response(statusCode: 503, requestOptions: RequestOptions(path: '/x')),
|
||||
type: DioExceptionType.badResponse,
|
||||
);
|
||||
expect(ErrorReportPolicy.shouldReport(e), false);
|
||||
});
|
||||
|
||||
test('returns false for Dio connectionError / offline-style', () {
|
||||
final e = DioException(
|
||||
requestOptions: RequestOptions(path: '/x'),
|
||||
type: DioExceptionType.connectionError,
|
||||
error: const SocketException('offline'),
|
||||
);
|
||||
expect(ErrorReportPolicy.shouldReport(e), false);
|
||||
});
|
||||
|
||||
test('returns true for arbitrary exceptions', () {
|
||||
expect(ErrorReportPolicy.shouldReport(StateError('x')), true);
|
||||
});
|
||||
});
|
||||
|
||||
group('ErrorReportPolicy.allowSentryEvent', () {
|
||||
final hint = Hint();
|
||||
|
||||
test('allows 5xx Dio so sentry_dio events are not dropped in beforeSend', () {
|
||||
final e = DioException(
|
||||
requestOptions: RequestOptions(path: '/x'),
|
||||
response: Response(statusCode: 503, requestOptions: RequestOptions(path: '/x')),
|
||||
type: DioExceptionType.badResponse,
|
||||
);
|
||||
final event = SentryEvent(throwable: e);
|
||||
expect(ErrorReportPolicy.allowSentryEvent(event, hint), true);
|
||||
});
|
||||
|
||||
test('drops 4xx Dio from SDK', () {
|
||||
final e = DioException(
|
||||
requestOptions: RequestOptions(path: '/x'),
|
||||
response: Response(statusCode: 422, requestOptions: RequestOptions(path: '/x')),
|
||||
type: DioExceptionType.badResponse,
|
||||
);
|
||||
final event = SentryEvent(throwable: e);
|
||||
expect(ErrorReportPolicy.allowSentryEvent(event, hint), false);
|
||||
});
|
||||
|
||||
test('drops transient Dio from SDK (connectionError)', () {
|
||||
final e = DioException(
|
||||
requestOptions: RequestOptions(path: '/x'),
|
||||
type: DioExceptionType.connectionError,
|
||||
error: const SocketException('reset'),
|
||||
);
|
||||
final event = SentryEvent(throwable: e);
|
||||
expect(ErrorReportPolicy.allowSentryEvent(event, hint), false);
|
||||
});
|
||||
|
||||
test('drops SocketException from SDK when not wrapped in Dio', () {
|
||||
final event = SentryEvent(throwable: const SocketException('x'));
|
||||
expect(ErrorReportPolicy.allowSentryEvent(event, hint), false);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:eatvio_app/core/error_reporting/no_op_error_reporter.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
@@ -7,7 +8,7 @@ void main() {
|
||||
// В тестах Firebase не может быть инициализирован
|
||||
// Проверяем, что попытка создания приводит к ожидаемой ошибке
|
||||
expect(
|
||||
() => FirebaseApi(),
|
||||
() => FirebaseApi(errorReporter: const NoOpErrorReporter()),
|
||||
throwsA(isA<Exception>()),
|
||||
);
|
||||
});
|
||||
@@ -16,7 +17,7 @@ void main() {
|
||||
// Метод getToken требует инициализированный Firebase
|
||||
// В тестах мы проверяем, что он выбрасывает ожидаемую ошибку
|
||||
try {
|
||||
final api = FirebaseApi();
|
||||
final api = FirebaseApi(errorReporter: const NoOpErrorReporter());
|
||||
expect(() => api.getToken(), throwsA(isA<Exception>()));
|
||||
} catch (e) {
|
||||
expect(e.toString(), contains('No Firebase App'));
|
||||
@@ -26,7 +27,7 @@ void main() {
|
||||
test('registerAnonymousPushToken возвращает Future', () {
|
||||
// Метод registerAnonymousPushToken требует инициализированный Firebase
|
||||
try {
|
||||
final api = FirebaseApi();
|
||||
final api = FirebaseApi(errorReporter: const NoOpErrorReporter());
|
||||
expect(() => api.registerAnonymousPushToken(), throwsA(isA<Exception>()));
|
||||
} catch (e) {
|
||||
expect(e.toString(), contains('No Firebase App'));
|
||||
@@ -36,7 +37,7 @@ void main() {
|
||||
test('registerPushToken возвращает Future', () {
|
||||
// Метод registerPushToken требует инициализированный Firebase
|
||||
try {
|
||||
final api = FirebaseApi();
|
||||
final api = FirebaseApi(errorReporter: const NoOpErrorReporter());
|
||||
expect(() => api.registerPushToken(), throwsA(isA<Exception>()));
|
||||
} catch (e) {
|
||||
expect(e.toString(), contains('No Firebase App'));
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:eatvio_app/core/error_reporting/no_op_error_reporter.dart';
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/app_initializer.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
@@ -29,7 +30,7 @@ void main() {
|
||||
|
||||
test('initialize returns early when client is not null', () async {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
await manager.initialize();
|
||||
|
||||
@@ -38,35 +39,35 @@ void main() {
|
||||
|
||||
test('newMessagesStream returns null when channel is null', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
expect(manager.newMessagesStream, isNull);
|
||||
});
|
||||
|
||||
test('newNotificationsStream returns null when channel is null', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
expect(manager.newNotificationsStream, isNull);
|
||||
});
|
||||
|
||||
test('directChatStream returns null when channel is null', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
expect(manager.directChatStream, isNull);
|
||||
});
|
||||
|
||||
test('clientTypingStream returns null when channel is null', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
expect(manager.clientTypingStream, isNull);
|
||||
});
|
||||
|
||||
test('subscribeDirectChatChannel does nothing when channel is null', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
// Не должно быть исключений
|
||||
manager.subscribeDirectChatChannel();
|
||||
@@ -74,7 +75,7 @@ void main() {
|
||||
|
||||
test('unsubscribeDirectChatChannel does nothing when channel is null', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
// Не должно быть исключений
|
||||
manager.unsubscribeDirectChatChannel();
|
||||
@@ -82,7 +83,7 @@ void main() {
|
||||
|
||||
test('clear sets client and userId to null', () async {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
manager.userId = 1;
|
||||
|
||||
@@ -94,7 +95,7 @@ void main() {
|
||||
|
||||
test('initPrivateDirectChatChannel - создает канал для прямого чата', () async {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
const chatId = 'chat-123';
|
||||
const token = 'test-token';
|
||||
|
||||
@@ -109,7 +110,7 @@ void main() {
|
||||
|
||||
test('initialize - обрабатывает ошибку при отсутствии токена', () async {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
// Убеждаемся, что токена нет
|
||||
await TokenStorage.removeTokenInStorage();
|
||||
@@ -122,7 +123,7 @@ void main() {
|
||||
|
||||
test('initialize - обрабатывает ошибку при ошибке getWebsocket', () async {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
const token = 'test-token';
|
||||
|
||||
await TokenStorage.saveTokenInStorage(token);
|
||||
@@ -136,7 +137,7 @@ void main() {
|
||||
|
||||
test('initialize - устанавливает userId из WebsocketInfoModel', () async {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
const token = 'test-token';
|
||||
const userId = 42;
|
||||
|
||||
@@ -158,7 +159,7 @@ void main() {
|
||||
|
||||
test('clear - отписывается от всех каналов', () async {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
manager.userId = 1;
|
||||
|
||||
@@ -171,7 +172,7 @@ void main() {
|
||||
|
||||
test('initialize - не инициализирует повторно если client уже существует', () async {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
const token = 'test-token';
|
||||
|
||||
await TokenStorage.saveTokenInStorage(token);
|
||||
@@ -193,7 +194,7 @@ void main() {
|
||||
|
||||
test('subscribeDirectChatChannel - подписывается на канал когда он существует', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
// Когда канал null, метод не должен выбрасывать исключение
|
||||
manager.subscribeDirectChatChannel();
|
||||
@@ -203,7 +204,7 @@ void main() {
|
||||
|
||||
test('unsubscribeDirectChatChannel - отписывается от канала когда он существует', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
// Когда канал null, метод не должен выбрасывать исключение
|
||||
manager.unsubscribeDirectChatChannel();
|
||||
@@ -213,35 +214,35 @@ void main() {
|
||||
|
||||
test('newMessagesStream - возвращает null когда канал не инициализирован', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
expect(manager.newMessagesStream, isNull);
|
||||
});
|
||||
|
||||
test('newNotificationsStream - возвращает null когда канал не инициализирован', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
expect(manager.newNotificationsStream, isNull);
|
||||
});
|
||||
|
||||
test('directChatStream - возвращает null когда канал не инициализирован', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
expect(manager.directChatStream, isNull);
|
||||
});
|
||||
|
||||
test('clientTypingStream - возвращает null когда канал не инициализирован', () {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
expect(manager.clientTypingStream, isNull);
|
||||
});
|
||||
|
||||
test('initialize - обрабатывает случай когда TokenStorage.haveTokenInStorage возвращает false', () async {
|
||||
final wsService = MockWsService();
|
||||
final manager = WsManager(wsService: wsService);
|
||||
final manager = WsManager(wsService: wsService, errorReporter: const NoOpErrorReporter());
|
||||
|
||||
// Убеждаемся, что токена нет
|
||||
await TokenStorage.removeTokenInStorage();
|
||||
|
||||
@@ -379,25 +379,22 @@ void main() {
|
||||
),
|
||||
).thenThrow(Exception('Ошибка подтверждения'));
|
||||
|
||||
expect(
|
||||
() => oauthCubit!.confirmOAuthVerification(
|
||||
provider: 'google',
|
||||
accessToken: 'access_token',
|
||||
refreshToken: 'refresh_token',
|
||||
clientId: 'client_id',
|
||||
id: 'id',
|
||||
email: 'test@example.com',
|
||||
phone: null,
|
||||
code: '123456',
|
||||
verificationType: 'email',
|
||||
firstName: 'Test',
|
||||
lastName: 'User',
|
||||
dateOfBirth: '2000-01-01',
|
||||
gender: 'male',
|
||||
weight: 70,
|
||||
height: 175,
|
||||
),
|
||||
throwsException,
|
||||
await oauthCubit!.confirmOAuthVerification(
|
||||
provider: 'google',
|
||||
accessToken: 'access_token',
|
||||
refreshToken: 'refresh_token',
|
||||
clientId: 'client_id',
|
||||
id: 'id',
|
||||
email: 'test@example.com',
|
||||
phone: null,
|
||||
code: '123456',
|
||||
verificationType: 'email',
|
||||
firstName: 'Test',
|
||||
lastName: 'User',
|
||||
dateOfBirth: '2000-01-01',
|
||||
gender: 'male',
|
||||
weight: 70,
|
||||
height: 175,
|
||||
);
|
||||
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
|
||||
@@ -21,7 +21,7 @@ void main() {
|
||||
mockResetPasswordService = MockResetPasswordService();
|
||||
resetPasswordRepository = ResetPasswordRepository(
|
||||
resetPasswordService: mockResetPasswordService,
|
||||
);
|
||||
);
|
||||
});
|
||||
|
||||
test('sendEmailCodeForPasswordChange - успешная отправка кода (200)', () async {
|
||||
|
||||
@@ -24,74 +24,54 @@ void main() {
|
||||
test('getProductByBarcode - возвращает успешный результат (200)', () async {
|
||||
const barcode = '1234567890123';
|
||||
final productData = {'GTIN': barcode, 'Описание (ru)': 'Test Product'};
|
||||
final response = Response(
|
||||
final response = Response<Map<String, dynamic>>(
|
||||
data: productData,
|
||||
statusCode: 200,
|
||||
requestOptions: RequestOptions(path: '/api/gsone/barcode/$barcode'),
|
||||
);
|
||||
|
||||
when(mockDio.get('/api/gsone/barcode/$barcode')).thenAnswer((_) async => response);
|
||||
when(mockDio.get<Map<String, dynamic>>(any, options: anyNamed('options'))).thenAnswer((_) async => response);
|
||||
|
||||
final result = await repository.getProductByBarcode(barcode);
|
||||
|
||||
expect(result.type, BarcodeResultType.success);
|
||||
expect(result.product, isNotNull);
|
||||
expect(result.product!.description, 'Test Product');
|
||||
verify(mockDio.get('/api/gsone/barcode/$barcode')).called(1);
|
||||
verify(mockDio.get<Map<String, dynamic>>(any, options: anyNamed('options'))).called(1);
|
||||
});
|
||||
|
||||
test('getProductByBarcode - возвращает статус обработки (202)', () async {
|
||||
const barcode = '1234567890123';
|
||||
final taskData = {'task_id': 'task-123', 'status': 'processing'};
|
||||
final response = Response(
|
||||
final response = Response<Map<String, dynamic>>(
|
||||
data: taskData,
|
||||
statusCode: 202,
|
||||
requestOptions: RequestOptions(path: '/api/gsone/barcode/$barcode'),
|
||||
);
|
||||
|
||||
when(mockDio.get('/api/gsone/barcode/$barcode')).thenAnswer((_) async => response);
|
||||
when(mockDio.get<Map<String, dynamic>>(any, options: anyNamed('options'))).thenAnswer((_) async => response);
|
||||
|
||||
final result = await repository.getProductByBarcode(barcode);
|
||||
|
||||
expect(result.type, BarcodeResultType.processing);
|
||||
expect(result.taskId, equals('task-123'));
|
||||
verify(mockDio.get('/api/gsone/barcode/$barcode')).called(1);
|
||||
verify(mockDio.get<Map<String, dynamic>>(any, options: anyNamed('options'))).called(1);
|
||||
});
|
||||
|
||||
test('getProductByBarcode - обрабатывает DioException с 202 статусом', () async {
|
||||
test('getProductByBarcode - пробрасывает DioException при нестандартном ответе', () async {
|
||||
const barcode = '1234567890123';
|
||||
final taskData = {'task_id': 'task-456', 'status': 'processing'};
|
||||
final dioException = DioException(
|
||||
final response = Response<Map<String, dynamic>>(
|
||||
data: {'error': 'Not found'},
|
||||
statusCode: 404,
|
||||
requestOptions: RequestOptions(path: '/api/gsone/barcode/$barcode'),
|
||||
response: Response(
|
||||
data: taskData,
|
||||
statusCode: 202,
|
||||
requestOptions: RequestOptions(path: '/api/gsone/barcode/$barcode'),
|
||||
),
|
||||
);
|
||||
|
||||
when(mockDio.get('/api/gsone/barcode/$barcode')).thenThrow(dioException);
|
||||
when(mockDio.get<Map<String, dynamic>>(any, options: anyNamed('options'))).thenAnswer((_) async => response);
|
||||
|
||||
final result = await repository.getProductByBarcode(barcode);
|
||||
|
||||
expect(result.type, BarcodeResultType.processing);
|
||||
expect(result.taskId, equals('task-456'));
|
||||
});
|
||||
|
||||
test('getProductByBarcode - пробрасывает исключение при другой ошибке', () async {
|
||||
const barcode = '1234567890123';
|
||||
final dioException = DioException(
|
||||
requestOptions: RequestOptions(path: '/api/gsone/barcode/$barcode'),
|
||||
response: Response(
|
||||
data: {'error': 'Not found'},
|
||||
statusCode: 404,
|
||||
requestOptions: RequestOptions(path: '/api/gsone/barcode/$barcode'),
|
||||
),
|
||||
await expectLater(
|
||||
repository.getProductByBarcode(barcode),
|
||||
throwsA(isA<DioException>()),
|
||||
);
|
||||
|
||||
when(mockDio.get('/api/gsone/barcode/$barcode')).thenThrow(dioException);
|
||||
|
||||
expect(() => repository.getProductByBarcode(barcode), throwsException);
|
||||
});
|
||||
|
||||
test('getTaskStatus - возвращает completed статус', () async {
|
||||
|
||||
@@ -357,15 +357,16 @@ void main() {
|
||||
verify(mockChatService.getChatByUserSlug(slug: slug)).called(1);
|
||||
});
|
||||
|
||||
test('getChatByUserSlug - возвращает error при ошибке', () async {
|
||||
test('getChatByUserSlug - пробрасывает исключение при ошибке сети', () async {
|
||||
const slug = 'user-slug';
|
||||
|
||||
when(mockChatService.getChatByUserSlug(slug: slug))
|
||||
.thenThrow(Exception('Network error'));
|
||||
|
||||
final result = await chatRepository.getChatByUserSlug(slug);
|
||||
|
||||
expect(result, 'error');
|
||||
await expectLater(
|
||||
chatRepository.getChatByUserSlug(slug),
|
||||
throwsA(isA<Exception>()),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,75 +1,75 @@
|
||||
import 'package:eatvio_app/features/glossary/models/glossary_model.dart';
|
||||
import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart';
|
||||
import 'package:eatvio_app/features/glossary/services/glossary_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
|
||||
class MockGlossaryService extends Mock implements GlossaryService {}
|
||||
|
||||
void main() {
|
||||
group('GlossaryRepository', () {
|
||||
late GlossaryRepository repository;
|
||||
late MockGlossaryService mockService;
|
||||
|
||||
setUp(() {
|
||||
mockService = MockGlossaryService();
|
||||
repository = GlossaryRepository(glossaryService: mockService);
|
||||
});
|
||||
|
||||
test('getGlossaryListByQuery - успешный запрос', () async {
|
||||
const query = 'test';
|
||||
final mockGlossaries = <GlossaryModel>[];
|
||||
final mockPagination = GlossaryPaginationModel(glossariesList: mockGlossaries);
|
||||
|
||||
when(() => mockService.getGlossaryByQuery(query: query))
|
||||
.thenAnswer((_) async => mockPagination);
|
||||
|
||||
final result = await repository.getGlossaryListByQuery(query);
|
||||
|
||||
expect(result, mockGlossaries);
|
||||
verify(() => mockService.getGlossaryByQuery(query: query)).called(1);
|
||||
});
|
||||
|
||||
test('getGlossaryListByQuery - пробрасывает ошибку', () async {
|
||||
const query = 'test';
|
||||
|
||||
when(() => mockService.getGlossaryByQuery(query: query))
|
||||
.thenThrow(Exception('Error'));
|
||||
|
||||
expect(() => repository.getGlossaryListByQuery(query), throwsException);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
import 'package:eatvio_app/features/glossary/models/glossary_model.dart';
|
||||
import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart';
|
||||
import 'package:eatvio_app/features/glossary/services/glossary_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
|
||||
class MockGlossaryService extends Mock implements GlossaryService {}
|
||||
|
||||
void main() {
|
||||
group('GlossaryRepository', () {
|
||||
late GlossaryRepository repository;
|
||||
late MockGlossaryService mockService;
|
||||
|
||||
setUp(() {
|
||||
mockService = MockGlossaryService();
|
||||
repository = GlossaryRepository(glossaryService: mockService);
|
||||
});
|
||||
|
||||
test('getGlossaryListByQuery - успешный запрос', () async {
|
||||
const query = 'test';
|
||||
final mockGlossaries = <GlossaryModel>[];
|
||||
final mockPagination = GlossaryPaginationModel(glossariesList: mockGlossaries);
|
||||
|
||||
when(() => mockService.getGlossaryByQuery(query: query))
|
||||
.thenAnswer((_) async => mockPagination);
|
||||
|
||||
final result = await repository.getGlossaryListByQuery(query);
|
||||
|
||||
expect(result, mockGlossaries);
|
||||
verify(() => mockService.getGlossaryByQuery(query: query)).called(1);
|
||||
});
|
||||
|
||||
test('getGlossaryListByQuery - пробрасывает ошибку', () async {
|
||||
const query = 'test';
|
||||
|
||||
when(() => mockService.getGlossaryByQuery(query: query))
|
||||
.thenThrow(Exception('Error'));
|
||||
|
||||
expect(() => repository.getGlossaryListByQuery(query), throwsException);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ void main() {
|
||||
mockBlockedUserService = MockBlockedUserService();
|
||||
blockedUsersRepository = BlockedUsersRepository(
|
||||
blockedUserService: mockBlockedUserService,
|
||||
);
|
||||
);
|
||||
});
|
||||
|
||||
test('getBlockedUsers - возвращает список заблокированных пользователей', () async {
|
||||
|
||||
@@ -18,7 +18,7 @@ void main() {
|
||||
mockService = MockPersonalDietSuggestionService();
|
||||
repository = PersonalDietSuggestionRepository(
|
||||
personalDietSuggestionService: mockService,
|
||||
);
|
||||
);
|
||||
});
|
||||
|
||||
test('getConsultationWithPersonalDiets - успешная загрузка консультаций', () async {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:easy_debounce/easy_debounce.dart';
|
||||
import 'package:eatvio_app/core/models/pagination_model.dart';
|
||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart';
|
||||
@@ -59,9 +60,12 @@ void main() {
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
EasyDebounce.cancel('loadPlans');
|
||||
EasyDebounce.cancel('like_plan');
|
||||
EasyDebounce.cancel('add_or_remove_plan_from_favorite');
|
||||
if (plansCubit != null && !plansCubit!.isClosed) {
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
plansCubit!.close();
|
||||
await plansCubit!.close();
|
||||
plansCubit = null;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -143,7 +143,7 @@ void main() {
|
||||
|
||||
when(mockProfileRepository.getProfileBySlug('test-user')).thenThrow(Exception('Ошибка загрузки'));
|
||||
|
||||
expect(() => profileCubit!.getProfileBySlug('test-user'), throwsException);
|
||||
await profileCubit!.getProfileBySlug('test-user');
|
||||
|
||||
final state = profileCubit!.state;
|
||||
expect(state, isA<ProfileStateError>());
|
||||
|
||||
@@ -280,9 +280,8 @@ void main() {
|
||||
|
||||
when(mockService.tryVerifyEmailByCode(code: '{"code": "$code"}')).thenAnswer((_) async => Future<void>.value());
|
||||
|
||||
final result = await repository.tryVerifyEmailByCode(code);
|
||||
await repository.tryVerifyEmailByCode(code);
|
||||
|
||||
expect(result, isTrue);
|
||||
verify(mockService.tryVerifyEmailByCode(code: '{"code": "$code"}')).called(1);
|
||||
});
|
||||
|
||||
@@ -291,9 +290,10 @@ void main() {
|
||||
|
||||
when(mockService.tryVerifyEmailByCode(code: '{"code": "$code"}')).thenThrow(Exception('Invalid code'));
|
||||
|
||||
final result = await repository.tryVerifyEmailByCode(code);
|
||||
|
||||
expect(result, isFalse);
|
||||
await expectLater(
|
||||
repository.tryVerifyEmailByCode(code),
|
||||
throwsA(isA<Exception>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('deleteAccount - удаляет аккаунт', () async {
|
||||
|
||||
@@ -228,7 +228,8 @@ void main() {
|
||||
final result = await myRecipesCubit!.getRecipeById('test-recipe');
|
||||
|
||||
expect(result, isA<Recipe>());
|
||||
expect(result.id, 1);
|
||||
expect(result, isNotNull);
|
||||
expect(result!.id, 1);
|
||||
expect(result.slug, 'test-recipe');
|
||||
verify(mockAboutRecipeRepository.getRecipe('test-recipe')).called(1);
|
||||
});
|
||||
|
||||
@@ -139,13 +139,14 @@ void main() {
|
||||
expect(cubit.state.sheet.responseBody, '{"locations": ["London, UK"]}');
|
||||
});
|
||||
|
||||
test('getLocationsByQuery rethrows exception on error', () async {
|
||||
test('getLocationsByQuery returns empty list on error', () async {
|
||||
const query = 'Invalid';
|
||||
final exception = Exception('Network error');
|
||||
|
||||
when(() => mockRepository.getLocationsListByQuery(query)).thenThrow(exception);
|
||||
|
||||
expect(() => cubit.getLocationsByQuery(query), throwsException);
|
||||
final result = await cubit.getLocationsByQuery(query);
|
||||
expect(result, isEmpty);
|
||||
});
|
||||
|
||||
test('getLocationsByCoordinates returns list of locations', () async {
|
||||
@@ -176,14 +177,15 @@ void main() {
|
||||
expect(cubit.state.sheet.responseBody, '{"locations": ["London, UK"]}');
|
||||
});
|
||||
|
||||
test('getLocationsByCoordinates rethrows exception on error', () async {
|
||||
test('getLocationsByCoordinates returns empty list on error', () async {
|
||||
const latitude = 'invalid';
|
||||
const longitude = 'invalid';
|
||||
final exception = Exception('Invalid coordinates');
|
||||
|
||||
when(() => mockRepository.getLocationsListByCoordinates(latitude, longitude)).thenThrow(exception);
|
||||
|
||||
expect(() => cubit.getLocationsByCoordinates(latitude, longitude), throwsException);
|
||||
final result = await cubit.getLocationsByCoordinates(latitude, longitude);
|
||||
expect(result, isEmpty);
|
||||
});
|
||||
|
||||
test('getLocationsByQuery handles empty query', () async {
|
||||
|
||||
@@ -140,7 +140,7 @@ void main() {
|
||||
when(mockRepository.sendEmailCode())
|
||||
.thenAnswer((_) async => {});
|
||||
when(mockRepository.tryVerifyEmailByCode('wrong'))
|
||||
.thenAnswer((_) async => false);
|
||||
.thenThrow(Exception('Неверный код'));
|
||||
|
||||
await cubit!.sendEmailCode();
|
||||
await cubit!.tryVerify('wrong');
|
||||
|
||||
@@ -145,7 +145,10 @@ void main() {
|
||||
when(() => mockService.register(sheet: any(named: 'sheet')))
|
||||
.thenThrow(dioException);
|
||||
|
||||
expect(() => repository.tryRegister(sheet), throwsA(isA<String>()));
|
||||
await expectLater(
|
||||
repository.tryRegister(sheet),
|
||||
throwsA(isA<DioException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('getLocationsListByQuery - возвращает LocationModel', () async {
|
||||
|
||||
3
test/fixtures/doubles/auth_doubles.dart
vendored
3
test/fixtures/doubles/auth_doubles.dart
vendored
@@ -14,7 +14,8 @@ import 'package:eatvio_app/features/auth/services/auth_service.dart';
|
||||
/// - Returns data loaded from fixture files so QA/backenders can see
|
||||
/// exactly what is exchanged.
|
||||
class FixtureAuthRepository extends AuthRepository {
|
||||
FixtureAuthRepository({required this.tokenFixture}) : super(authService: _NoopAuthService());
|
||||
FixtureAuthRepository({required this.tokenFixture})
|
||||
: super(authService: _NoopAuthService());
|
||||
|
||||
final TokenModel tokenFixture;
|
||||
|
||||
|
||||
3
test/fixtures/doubles/blog_post_doubles.dart
vendored
3
test/fixtures/doubles/blog_post_doubles.dart
vendored
@@ -4,7 +4,8 @@ import 'package:eatvio_app/features/blog_post_create/services/blog_post_service.
|
||||
import 'package:flutter_image_compress/flutter_image_compress.dart';
|
||||
|
||||
class FixtureBlogPostRepository extends BlogPostRepository {
|
||||
FixtureBlogPostRepository() : super(blogPostService: _NoopBlogPostService());
|
||||
FixtureBlogPostRepository()
|
||||
: super(blogPostService: _NoopBlogPostService());
|
||||
|
||||
final List<BlogPostCreatePayload> createPayloads = <BlogPostCreatePayload>[];
|
||||
final List<BlogPostUpdatePayload> updatePayloads = <BlogPostUpdatePayload>[];
|
||||
|
||||
@@ -12,7 +12,8 @@ import 'package:retrofit/dio.dart' show HttpResponse;
|
||||
import '../../fixtures/fixture_reader.dart';
|
||||
|
||||
class FixtureCreateDietRepository extends CreateDietRepository {
|
||||
FixtureCreateDietRepository() : super(createDietService: _NoopCreateDietService());
|
||||
FixtureCreateDietRepository()
|
||||
: super(createDietService: _NoopCreateDietService());
|
||||
|
||||
final List<Map<String, dynamic>> createRequests = <Map<String, dynamic>>[];
|
||||
final List<Map<String, dynamic>> updateRequests = <Map<String, dynamic>>[];
|
||||
@@ -136,7 +137,8 @@ class FixtureCreateDietRepository extends CreateDietRepository {
|
||||
}
|
||||
|
||||
class FixtureGlossaryRepository extends GlossaryRepository {
|
||||
FixtureGlossaryRepository() : super(glossaryService: _NoopGlossaryService());
|
||||
FixtureGlossaryRepository()
|
||||
: super(glossaryService: _NoopGlossaryService());
|
||||
|
||||
@override
|
||||
Future<List<GlossaryModel>> getGlossaryListByQuery(String query) async {
|
||||
|
||||
@@ -3,7 +3,8 @@ import 'package:eatvio_app/features/create_plan/repositories/create_plan_reposit
|
||||
import 'package:eatvio_app/features/create_plan/services/create_plan_service.dart';
|
||||
|
||||
class FixtureCreatePlanRepository extends CreatePlanRepository {
|
||||
FixtureCreatePlanRepository() : super(createPlanService: _NoopCreatePlanService());
|
||||
FixtureCreatePlanRepository()
|
||||
: super(createPlanService: _NoopCreatePlanService());
|
||||
|
||||
final List<Map<String, dynamic>> createPlanRequests = <Map<String, dynamic>>[];
|
||||
|
||||
|
||||
9
test/fixtures/doubles/profile_doubles.dart
vendored
9
test/fixtures/doubles/profile_doubles.dart
vendored
@@ -13,7 +13,8 @@ import 'package:eatvio_app/features/profile/services/profile_service.dart';
|
||||
import '../fixture_reader.dart';
|
||||
|
||||
class FixtureProfileRepository extends ProfileRepository {
|
||||
FixtureProfileRepository() : super(profileService: _NoopProfileService());
|
||||
FixtureProfileRepository()
|
||||
: super(profileService: _NoopProfileService());
|
||||
|
||||
final List<Map<String, dynamic>> addWeightRequests = <Map<String, dynamic>>[];
|
||||
final List<Map<String, dynamic>> addCircumferenceRequests = <Map<String, dynamic>>[];
|
||||
@@ -64,7 +65,8 @@ class _NoopProfileService implements ProfileService {
|
||||
}
|
||||
|
||||
class FixtureChatRepository extends ChatRepository {
|
||||
FixtureChatRepository() : super(chatService: _NoopChatService());
|
||||
FixtureChatRepository()
|
||||
: super(chatService: _NoopChatService());
|
||||
|
||||
@override
|
||||
Future<String> getChatByUserSlug(String slug) async {
|
||||
@@ -78,7 +80,8 @@ class _NoopChatService implements ChatService {
|
||||
}
|
||||
|
||||
class FixtureConsultantRepository extends ConsultantRepository {
|
||||
FixtureConsultantRepository() : super(consultantService: _NoopConsultantService());
|
||||
FixtureConsultantRepository()
|
||||
: super(consultantService: _NoopConsultantService());
|
||||
|
||||
@override
|
||||
Future<ConsultationRequestModel> getConsultantRequestStatus(String slug) async {
|
||||
|
||||
Reference in New Issue
Block a user