feat(diary): tests

This commit is contained in:
mso7nueh
2026-05-05 19:40:28 +03:00
parent 48af13e37c
commit 2859607f4d
4 changed files with 1556 additions and 397 deletions

View File

@@ -0,0 +1,561 @@
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:drift/native.dart';
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_state.dart';
import 'package:eatvio_app/core/local_db/app_database.dart';
import 'package:eatvio_app/core/local_db/dao/diary_dao.dart';
import 'package:eatvio_app/core/local_db/dao/glossary_dao.dart';
import 'package:eatvio_app/core/local_db/dao/pending_ops_dao.dart';
import 'package:eatvio_app/core/local_db/dao/sync_meta_dao.dart';
import 'package:eatvio_app/core/local_db/diary_local_data_source.dart';
import 'package:eatvio_app/features/diary/models/diary_day_model.dart';
import 'package:eatvio_app/features/diary/repositories/diary_repository.dart';
import 'package:eatvio_app/features/diary/services/diary_service.dart';
import 'package:eatvio_app/features/glossary/models/glossary_model.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'diary_repository_offline_test.mocks.dart';
@GenerateNiceMocks([
MockSpec<DiaryService>(),
MockSpec<InternetConnectionCubit>(),
])
void main() {
late AppDatabase db;
late DiaryLocalDataSource localDataSource;
late MockDiaryService mockDiaryService;
late MockInternetConnectionCubit mockConnectionCubit;
late DiaryRepository repository;
AppDatabase createInMemoryDb() => AppDatabase.forTesting(NativeDatabase.memory());
void stubOnline() {
when(mockConnectionCubit.state).thenReturn(
InternetConnectionState(isInternetAvailable: true),
);
}
void stubOffline() {
when(mockConnectionCubit.state).thenReturn(
InternetConnectionState(isInternetAvailable: false),
);
}
setUp(() {
db = createInMemoryDb();
localDataSource = DiaryLocalDataSource(
diaryDao: DiaryDao(db),
glossaryDao: GlossaryDao(db),
pendingOpsDao: PendingOpsDao(db),
syncMetaDao: SyncMetaDao(db),
);
mockDiaryService = MockDiaryService();
mockConnectionCubit = MockInternetConnectionCubit();
repository = DiaryRepository(
diaryService: mockDiaryService,
localDataSource: localDataSource,
connectionCubit: mockConnectionCubit,
);
});
tearDown(() async {
await db.close();
});
// ──────────────────────────────────────────────────────────────────────────
// deleteProductFromMeal
// ──────────────────────────────────────────────────────────────────────────
group('deleteProductFromMeal', () {
test('офлайн — кладёт delete_portion в очередь', () async {
stubOffline();
await repository.deleteProductFromMeal(diaryId: 10, mealId: 2, portionId: 55);
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
expect(ops.first.type, 'delete_portion');
final payload = jsonDecode(ops.first.payload) as Map<String, dynamic>;
expect(payload['diary_id'], 10);
expect(payload['meal_id'], 2);
expect(payload['portion_id'], 55);
});
test('онлайн — вызывает сервис напрямую', () async {
stubOnline();
when(mockDiaryService.deleteProductFromMeal(
diary: 10, typeNo: 2, portionModel: 55,
)).thenAnswer((_) async {});
await repository.deleteProductFromMeal(diaryId: 10, mealId: 2, portionId: 55);
verify(mockDiaryService.deleteProductFromMeal(diary: 10, typeNo: 2, portionModel: 55)).called(1);
final ops = await localDataSource.getPendingOps();
expect(ops.isEmpty, isTrue);
});
test('онлайн 5xx — кладёт в очередь', () async {
stubOnline();
when(mockDiaryService.deleteProductFromMeal(
diary: anyNamed('diary'), typeNo: anyNamed('typeNo'), portionModel: anyNamed('portionModel'),
)).thenThrow(DioException(
requestOptions: RequestOptions(),
response: Response(requestOptions: RequestOptions(), statusCode: 500),
type: DioExceptionType.badResponse,
));
await repository.deleteProductFromMeal(diaryId: 10, mealId: 2, portionId: 55);
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
expect(ops.first.type, 'delete_portion');
});
test('онлайн 4xx — пробрасывает ошибку, не кладёт в очередь', () async {
stubOnline();
when(mockDiaryService.deleteProductFromMeal(
diary: anyNamed('diary'), typeNo: anyNamed('typeNo'), portionModel: anyNamed('portionModel'),
)).thenThrow(DioException(
requestOptions: RequestOptions(),
response: Response(requestOptions: RequestOptions(), statusCode: 404),
type: DioExceptionType.badResponse,
));
expect(
() => repository.deleteProductFromMeal(diaryId: 10, mealId: 2, portionId: 55),
throwsA(isA<DioException>()),
);
final ops = await localDataSource.getPendingOps();
expect(ops.isEmpty, isTrue);
});
});
// ──────────────────────────────────────────────────────────────────────────
// fillSatiety
// ──────────────────────────────────────────────────────────────────────────
group('fillSatiety', () {
test('офлайн — кладёт fill_satiety в очередь', () async {
stubOffline();
await repository.fillSatiety(diaryId: 5, mealId: 1, satiety: 7);
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
expect(ops.first.type, 'fill_satiety');
final payload = jsonDecode(ops.first.payload) as Map<String, dynamic>;
expect(payload['diary_id'], 5);
expect(payload['type_no'], 1);
expect(payload['satiety'], 7);
});
test('онлайн — вызывает сервис напрямую', () async {
stubOnline();
when(mockDiaryService.fillSatiety(
diary: 5, typeNo: 1, satiety: 7,
)).thenAnswer((_) async {});
await repository.fillSatiety(diaryId: 5, mealId: 1, satiety: 7);
verify(mockDiaryService.fillSatiety(diary: 5, typeNo: 1, satiety: 7)).called(1);
});
test('онлайн connection error — fallback в очередь', () async {
stubOnline();
when(mockDiaryService.fillSatiety(
diary: anyNamed('diary'), typeNo: anyNamed('typeNo'), satiety: anyNamed('satiety'),
)).thenThrow(DioException(
requestOptions: RequestOptions(),
type: DioExceptionType.connectionError,
));
await repository.fillSatiety(diaryId: 5, mealId: 1, satiety: 7);
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
});
});
// ──────────────────────────────────────────────────────────────────────────
// fillMood
// ──────────────────────────────────────────────────────────────────────────
group('fillMood', () {
test('офлайн — кладёт fill_mood в очередь', () async {
stubOffline();
await repository.fillMood(diaryId: 5, mealId: 3, mood: 4);
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
expect(ops.first.type, 'fill_mood');
final payload = jsonDecode(ops.first.payload) as Map<String, dynamic>;
expect(payload['mood'], 4);
});
test('онлайн — вызывает сервис', () async {
stubOnline();
when(mockDiaryService.fillMood(
diary: 5, typeNo: 3, mood: 4,
)).thenAnswer((_) async {});
await repository.fillMood(diaryId: 5, mealId: 3, mood: 4);
verify(mockDiaryService.fillMood(diary: 5, typeNo: 3, mood: 4)).called(1);
});
});
// ──────────────────────────────────────────────────────────────────────────
// fillTime
// ──────────────────────────────────────────────────────────────────────────
group('fillTime', () {
test('офлайн — кладёт fill_time в очередь', () async {
stubOffline();
await repository.fillTime(diaryId: 5, mealId: 2, time: '13:30');
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
expect(ops.first.type, 'fill_time');
final payload = jsonDecode(ops.first.payload) as Map<String, dynamic>;
expect(payload['time'], '13:30');
});
test('онлайн — вызывает сервис', () async {
stubOnline();
when(mockDiaryService.fillTime(
diary: 5, typeNo: 2, time: '13:30',
)).thenAnswer((_) async {});
await repository.fillTime(diaryId: 5, mealId: 2, time: '13:30');
verify(mockDiaryService.fillTime(diary: 5, typeNo: 2, time: '13:30')).called(1);
});
});
// ──────────────────────────────────────────────────────────────────────────
// fillWakeup / fillRetire
// ──────────────────────────────────────────────────────────────────────────
group('fillWakeup', () {
test('офлайн — кладёт fill_wakeup в очередь', () async {
stubOffline();
await repository.fillWakeup(diaryId: 5, time: '07:00');
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
expect(ops.first.type, 'fill_wakeup');
final payload = jsonDecode(ops.first.payload) as Map<String, dynamic>;
expect(payload['wakeup'], '07:00');
});
test('онлайн — вызывает сервис', () async {
stubOnline();
when(mockDiaryService.fillWakeup(
diary: 5, wakeUp: '07:00',
)).thenAnswer((_) async {});
await repository.fillWakeup(diaryId: 5, time: '07:00');
verify(mockDiaryService.fillWakeup(diary: 5, wakeUp: '07:00')).called(1);
});
});
group('fillRetire', () {
test('офлайн — кладёт fill_retire в очередь', () async {
stubOffline();
await repository.fillRetire(diaryId: 5, time: '22:00');
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
expect(ops.first.type, 'fill_retire');
final payload = jsonDecode(ops.first.payload) as Map<String, dynamic>;
expect(payload['retire'], '22:00');
});
test('онлайн — вызывает сервис', () async {
stubOnline();
when(mockDiaryService.fillRetire(
diary: 5, retire: '22:00',
)).thenAnswer((_) async {});
await repository.fillRetire(diaryId: 5, time: '22:00');
verify(mockDiaryService.fillRetire(diary: 5, retire: '22:00')).called(1);
});
});
// ──────────────────────────────────────────────────────────────────────────
// addPortionToMeal — 4xx НЕ ставится в очередь
// ──────────────────────────────────────────────────────────────────────────
group('addPortionToMeal — 4xx handling', () {
test('4xx ошибка пробрасывается, не ставится в очередь', () async {
stubOnline();
when(mockDiaryService.addProductToMealIdempotent(
idempotencyKey: anyNamed('idempotencyKey'),
diary: anyNamed('diary'),
typeNo: anyNamed('typeNo'),
productName: anyNamed('productName'),
portion: anyNamed('portion'),
quantity: anyNamed('quantity'),
productNutritionalValueId: anyNamed('productNutritionalValueId'),
)).thenThrow(DioException(
requestOptions: RequestOptions(),
response: Response(requestOptions: RequestOptions(), statusCode: 422),
type: DioExceptionType.badResponse,
));
expect(
() => repository.addPortionToMeal(
diaryId: 1, mealId: 1, productName: 'test', portion: 'gr', quantity: 100,
),
throwsA(isA<DioException>()),
);
final ops = await localDataSource.getPendingOps();
expect(ops.isEmpty, isTrue);
});
test('5xx ошибка кладёт в очередь', () async {
stubOnline();
when(mockDiaryService.addProductToMealIdempotent(
idempotencyKey: anyNamed('idempotencyKey'),
diary: anyNamed('diary'),
typeNo: anyNamed('typeNo'),
productName: anyNamed('productName'),
portion: anyNamed('portion'),
quantity: anyNamed('quantity'),
productNutritionalValueId: anyNamed('productNutritionalValueId'),
)).thenThrow(DioException(
requestOptions: RequestOptions(),
response: Response(requestOptions: RequestOptions(), statusCode: 503),
type: DioExceptionType.badResponse,
));
await repository.addPortionToMeal(
diaryId: 1, mealId: 1, productName: 'test', portion: 'gr', quantity: 100,
);
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
});
});
// ──────────────────────────────────────────────────────────────────────────
// Кэширование и загрузка (round-trip)
// ──────────────────────────────────────────────────────────────────────────
group('Cache round-trip', () {
test('getDiaryDayV2 онлайн — кэширует ответ, офлайн — загружает из кэша', () async {
const diaryDay = DiaryDayModel(
id: 100,
date: '2026-05-01',
wakeup: '07:30',
retire: '23:00',
closed: 0,
comment: 'test comment',
typeOfDiary: TypeOfDiaryModel(hasChosenDiet: false, hasChosenPlan: false, diaryState: null),
meals: [
MealModel(
id: 1,
time: '08:00',
typeNumber: 1,
satiety: 5,
mood: 3,
portions: [
PortionModel(
id: 10,
productName: 'Banana',
quantity: 2,
portion: 'pcs',
fromDiet: false,
productNutritionalValueId: 42,
portionState: PortionState.eaten,
),
],
photos: [],
),
],
chosenPlanId: null,
dayOfChosenDiet: null,
diet: null,
);
// Онлайн: сервис возвращает данные
stubOnline();
when(mockDiaryService.getDiaryDayV2(day: '2026-05-01T00:00:00+00:00'))
.thenAnswer((_) async => diaryDay);
when(mockDiaryService.getGlossariesIndex(filters: anyNamed('filters')))
.thenAnswer((_) async => const GlossaryPaginationModel(glossariesList: []));
final onlineResult = await repository.getDiaryDayV2(day: '2026-05-01T00:00:00+00:00');
expect(onlineResult.id, 100);
// Офлайн: загружает из кэша
stubOffline();
final offlineResult = await repository.getDiaryDayV2(day: '2026-05-01T00:00:00+00:00');
expect(offlineResult.id, 100);
expect(offlineResult.wakeup, '07:30');
expect(offlineResult.retire, '23:00');
expect(offlineResult.meals.length, 1);
expect(offlineResult.meals.first.portions.length, 1);
expect(offlineResult.meals.first.portions.first.productName, 'Banana');
expect(offlineResult.meals.first.portions.first.productNutritionalValueId, 42);
});
test('getDiaryDayV2 офлайн без кэша — пробует сеть, при ошибке выбрасывает', () async {
stubOffline();
when(mockDiaryService.getDiaryDayV2(day: anyNamed('day')))
.thenThrow(DioException(
requestOptions: RequestOptions(),
type: DioExceptionType.connectionError,
));
expect(
() => repository.getDiaryDayV2(day: '2099-01-01T00:00:00+00:00'),
throwsA(isA<DioException>()),
);
});
test('createDiaryDay онлайн 422 — не ставит в очередь (день уже существует)', () async {
stubOnline();
when(mockDiaryService.createDay(
idempotencyKey: anyNamed('idempotencyKey'),
body: anyNamed('body'),
)).thenThrow(DioException(
requestOptions: RequestOptions(),
response: Response(requestOptions: RequestOptions(), statusCode: 422),
type: DioExceptionType.badResponse,
));
await repository.createDiaryDay(day: '2026-05-01T00:00:00+00:00');
final ops = await localDataSource.getPendingOps();
expect(ops.isEmpty, isTrue);
});
test('createDiaryDay сетевая ошибка — ставит create_day в очередь', () async {
stubOnline();
when(mockDiaryService.createDay(
idempotencyKey: anyNamed('idempotencyKey'),
body: anyNamed('body'),
)).thenThrow(DioException(
requestOptions: RequestOptions(),
type: DioExceptionType.connectionError,
));
await repository.createDiaryDay(day: '2026-05-01T00:00:00+00:00');
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
expect(ops.first.type, 'create_day');
});
});
// ──────────────────────────────────────────────────────────────────────────
// _loadCachedDiaryDay — serverId == null
// ──────────────────────────────────────────────────────────────────────────
group('_loadCachedDiaryDay edge cases', () {
test('возвращает null если serverId == null (офлайн-созданный день)', () async {
// Кэшируем день без serverId
await localDataSource.cacheDiaryDay(date: '2026-05-02');
stubOffline();
// getDiaryDayV2 должен попробовать загрузить из кэша, но serverId == null → null
// Потом пробует сеть
when(mockDiaryService.getDiaryDayV2(day: anyNamed('day')))
.thenThrow(DioException(
requestOptions: RequestOptions(),
type: DioExceptionType.connectionError,
));
expect(
() => repository.getDiaryDayV2(day: '2026-05-02T00:00:00+00:00'),
throwsA(isA<DioException>()),
);
});
});
// ──────────────────────────────────────────────────────────────────────────
// _encodePayload — спецсимволы в JSON
// ──────────────────────────────────────────────────────────────────────────
group('JSON payload encoding', () {
test('продукт с кавычками в имени корректно сериализуется', () async {
stubOffline();
await repository.addPortionToMeal(
diaryId: 1,
mealId: 1,
productName: 'Сыр "Российский"',
portion: '100г',
quantity: 1,
);
final ops = await localDataSource.getPendingOps();
expect(ops.length, 1);
// jsonDecode не должен упасть
final payload = jsonDecode(ops.first.payload) as Map<String, dynamic>;
expect(payload['product_name'], 'Сыр "Российский"');
});
test('продукт с обратными слешами и переносами корректно сериализуется', () async {
stubOffline();
await repository.addPortionToMeal(
diaryId: 1,
mealId: 1,
productName: 'Product\\with\\slashes\nand\nnewlines',
portion: 'gr',
quantity: 1,
);
final ops = await localDataSource.getPendingOps();
final payload = jsonDecode(ops.first.payload) as Map<String, dynamic>;
expect(payload['product_name'], 'Product\\with\\slashes\nand\nnewlines');
});
});
// ──────────────────────────────────────────────────────────────────────────
// Multiple operations enqueued
// ──────────────────────────────────────────────────────────────────────────
group('Множество операций в очереди', () {
test('разные типы операций ставятся в очередь в FIFO порядке', () async {
stubOffline();
await repository.addPortionToMeal(
diaryId: 1, mealId: 1, productName: 'A', portion: 'gr', quantity: 1,
);
await repository.fillSatiety(diaryId: 1, mealId: 1, satiety: 5);
await repository.fillMood(diaryId: 1, mealId: 1, mood: 3);
await repository.fillTime(diaryId: 1, mealId: 1, time: '12:00');
await repository.deleteProductFromMeal(diaryId: 1, mealId: 1, portionId: 10);
await repository.fillWakeup(diaryId: 1, time: '07:00');
await repository.fillRetire(diaryId: 1, time: '23:00');
final ops = await localDataSource.getPendingOps();
expect(ops.length, 7);
expect(ops[0].type, 'create_portion');
expect(ops[1].type, 'fill_satiety');
expect(ops[2].type, 'fill_mood');
expect(ops[3].type, 'fill_time');
expect(ops[4].type, 'delete_portion');
expect(ops[5].type, 'fill_wakeup');
expect(ops[6].type, 'fill_retire');
});
});
}