feat(feed): fixed comments state updating in feed, feat(consultantRegistration): fixed registration flow for users with unverified phone, feat(tests): fixed tests coverage

This commit is contained in:
misha
2026-04-01 10:37:59 +03:00
parent ee2dd75a94
commit a13b623ca2
20 changed files with 949 additions and 343 deletions

View File

@@ -1,4 +1,9 @@
import 'dart:io';
import 'package:dio/dio.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';
import 'package:eatvio_app/core/models/pagination_model.dart';
import 'package:eatvio_app/features/create_recipe/models/ingredient.dart';
import 'package:eatvio_app/features/create_recipe/models/recipe_model.dart';
@@ -8,31 +13,123 @@ import 'package:eatvio_app/features/create_recipe/models/step.dart';
import 'package:eatvio_app/features/create_recipe/reporitories/recipe_repository.dart';
import 'package:eatvio_app/features/create_recipe/services/recipe_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:mocktail/mocktail.dart';
import 'package:retrofit/retrofit.dart';
class MockCreateRecipeService extends Mock implements CreateRecipeService {}
final mockHttpResponse = HttpResponse(
null,
Response(requestOptions: RequestOptions(path: ''), statusCode: 200),
);
final mockHttpResponse = HttpResponse(null, Response(requestOptions: RequestOptions(path: ''), statusCode: 200));
void main() {
setUpAll(() {
dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost');
if (sl.isRegistered<AppConfig>()) {
sl.unregister<AppConfig>();
}
sl.registerSingleton<AppConfig>(AppConfig(buildType: AppBuildType.tests));
registerFallbackValue(FormData());
});
group('RecipeRepository', () {
late RecipeRepository repository;
late MockCreateRecipeService mockService;
late Directory tempDir;
late File recipeImage;
late File stepImage;
setUp(() {
mockService = MockCreateRecipeService();
repository = RecipeRepository(recipeService: mockService);
});
setUp(() async {
tempDir = await Directory.systemTemp.createTemp('eatvio_recipe_repo_test_');
recipeImage = File('${tempDir.path}/recipe.png');
stepImage = File('${tempDir.path}/step.png');
// Valid 1x1 transparent PNG to satisfy ImageCompressUtility decoding.
const png1x1 = <int>[
0x89,
0x50,
0x4E,
0x47,
0x0D,
0x0A,
0x1A,
0x0A,
0x00,
0x00,
0x00,
0x0D,
0x49,
0x48,
0x44,
0x52,
0x00,
0x00,
0x00,
0x01,
0x00,
0x00,
0x00,
0x01,
0x08,
0x06,
0x00,
0x00,
0x00,
0x1F,
0x15,
0xC4,
0x89,
0x00,
0x00,
0x00,
0x0A,
0x49,
0x44,
0x41,
0x54,
0x78,
0x9C,
0x63,
0x00,
0x01,
0x00,
0x00,
0x05,
0x00,
0x01,
0x0D,
0x0A,
0x2D,
0xB4,
0x00,
0x00,
0x00,
0x00,
0x49,
0x45,
0x4E,
0x44,
0xAE,
0x42,
0x60,
0x82,
];
await recipeImage.writeAsBytes(png1x1, flush: true);
await stepImage.writeAsBytes(png1x1, flush: true);
});
tearDown(() async {
if (tempDir.existsSync()) {
await tempDir.delete(recursive: true);
}
});
test('inputProduct - возвращает Map с продуктами', () async {
const name = 'test-product';
const expected = {
@@ -177,12 +274,12 @@ void main() {
test('updateRecipe - вызывает updateRecipe с правильными параметрами', () async {
const slug = 'recipe-slug';
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Updated Recipe',
description: 'Updated description',
videoUrl: null,
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: null,
tags: null,
@@ -192,27 +289,29 @@ void main() {
energyPerServing: 300,
);
// Мокируем ImageCompressUtility.compressFile
// Это сложно, так как это статический метод, но мы можем проверить, что вызывается updateRecipe
when(() => mockService.updateRecipe(slug: slug, formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(
() => mockService.updateRecipe(
slug: slug,
formData: any(named: 'formData'),
),
).thenAnswer((_) async => Future.value(mockHttpResponse));
// Этот тест может упасть из-за ImageCompressUtility, но мы проверяем логику
try {
await repository.publishRecipe(recipe, true, slug);
verify(() => mockService.updateRecipe(slug: slug, formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe, true, slug);
verify(
() => mockService.updateRecipe(
slug: slug,
formData: any(named: 'formData'),
),
).called(1);
});
test('publishRecipe - обрабатывает рецепт с тегами', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: null,
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: null,
tags: ['tag1', 'tag2'],
@@ -222,24 +321,19 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
try {
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('publishRecipe - обрабатывает рецепт с videoUrl', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: 'https://example.com/video.mp4',
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: null,
tags: null,
@@ -249,24 +343,19 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
try {
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('publishRecipe - обрабатывает рецепт без videoUrl (null)', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: null,
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: null,
tags: null,
@@ -276,24 +365,19 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
try {
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('publishRecipe - обрабатывает рецепт с пустым videoUrl', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: '',
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: null,
tags: null,
@@ -303,24 +387,19 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
try {
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('publishRecipe - пробрасывает исключение при ошибке', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: null,
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: null,
tags: null,
@@ -330,37 +409,21 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenThrow(Exception('Error'));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenThrow(Exception('Error'));
try {
await repository.publishRecipe(recipe);
fail('Should have thrown exception');
} catch (e) {
expect(e, isA<Exception>());
}
expect(() => repository.publishRecipe(recipe), throwsA(isA<Exception>()));
});
test('publishRecipe - обрабатывает рецепт с ингредиентами', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: null,
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: [
Ingredient(
name: 'Apple',
unit: '100',
portion: 'grams',
productId: 1,
),
Ingredient(
name: 'Banana',
unit: '50',
portion: 'grams',
productId: 2,
),
const Ingredient(name: 'Apple', unit: '100', portion: 'grams', productId: 1),
const Ingredient(name: 'Banana', unit: '50', portion: 'grams', productId: 2),
],
steps: null,
tags: null,
@@ -370,31 +433,21 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
try {
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('publishRecipe - обрабатывает рецепт с null ингредиентами', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: null,
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: [
Ingredient(
name: 'Apple',
unit: '100',
portion: 'grams',
productId: 1,
),
const Ingredient(name: 'Apple', unit: '100', portion: 'grams', productId: 1),
null, // null ингредиент должен быть отфильтрован
],
steps: null,
@@ -405,34 +458,23 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
try {
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('publishRecipe - обрабатывает рецепт со шагами без изображений', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: null,
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: [
Step(
description: 'Step 1 description',
image: null,
),
Step(
description: 'Step 2 description',
image: '',
),
const Step(description: 'Step 1 description', image: null),
const Step(description: 'Step 2 description', image: ''),
],
tags: null,
totalCookingTime: 30,
@@ -441,35 +483,24 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
try {
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('publishRecipe - обрабатывает рецепт со смешанными шагами (с null)', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: null,
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: [
Step(
description: 'Step 1 description',
image: null,
),
const Step(description: 'Step 1 description', image: null),
null, // null шаг должен быть отфильтрован
Step(
description: 'Step 3 description',
image: '',
),
const Step(description: 'Step 3 description', image: ''),
],
tags: null,
totalCookingTime: 30,
@@ -478,24 +509,19 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
try {
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('publishRecipe - удаляет пустые значения из formMap', () async {
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: '', // Пустое описание должно быть удалено
videoUrl: '', // Пустой videoUrl должен быть удален
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: null,
tags: null,
@@ -505,25 +531,20 @@ void main() {
energyPerServing: null,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData')))
.thenAnswer((_) async => Future.value(mockHttpResponse));
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
try {
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
} catch (e) {
// Игнорируем ошибки, связанные с ImageCompressUtility в тестах
}
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('updateRecipe - пробрасывает исключение при ошибке', () async {
const slug = 'recipe-slug';
const recipe = RecipeModel(
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: null,
image: '/test/path/image.jpg',
image: recipeImage.path,
ingredients: null,
steps: null,
tags: null,
@@ -533,16 +554,132 @@ void main() {
energyPerServing: 300,
);
when(() => mockService.updateRecipe(slug: slug, formData: any(named: 'formData')))
.thenThrow(Exception('Error'));
when(
() => mockService.updateRecipe(
slug: slug,
formData: any(named: 'formData'),
),
).thenThrow(Exception('Error'));
try {
await repository.publishRecipe(recipe, true, slug);
fail('Should have thrown exception');
} catch (e) {
expect(e, isA<Exception>());
}
expect(() => repository.publishRecipe(recipe, true, slug), throwsA(isA<Exception>()));
});
test('publishRecipe - собирает steps с изображением (MultipartFile)', () async {
final recipe = RecipeModel(
type: 'main',
title: 'Test Recipe',
description: 'Test description',
videoUrl: null,
image: recipeImage.path,
ingredients: null,
steps: [Step(description: 'Step with image', image: stepImage.path)],
tags: null,
totalCookingTime: 30,
activeCookTime: 15,
servings: 4,
energyPerServing: 300,
);
when(() => mockService.publishRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
await repository.publishRecipe(recipe);
verify(() => mockService.publishRecipe(formData: any(named: 'formData'))).called(1);
});
test('saveAsDraft - создает draft (createDraftedRecipe)', () async {
final recipe = RecipeModel(
type: 'main',
title: 'Draft title',
description: 'Draft desc',
videoUrl: null,
image: recipeImage.path,
ingredients: null,
steps: null,
tags: const ['tag1'],
totalCookingTime: 30,
activeCookTime: 15,
servings: 2,
energyPerServing: 200,
);
when(() => mockService.createDraftedRecipe(formData: any(named: 'formData'))).thenAnswer((_) async => Future.value(mockHttpResponse));
await repository.saveAsDraft(recipe);
verify(() => mockService.createDraftedRecipe(formData: any(named: 'formData'))).called(1);
verifyNever(
() => mockService.updateRecipe(
slug: any(named: 'slug'),
formData: any(named: 'formData'),
),
);
});
test('saveAsDraft - обновляет draft (updateRecipe)', () async {
const slug = 'draft-slug';
final recipe = RecipeModel(
type: 'main',
title: 'Draft title',
description: 'Draft desc',
videoUrl: null,
image: recipeImage.path,
ingredients: null,
steps: null,
tags: null,
totalCookingTime: 30,
activeCookTime: 15,
servings: 2,
energyPerServing: 200,
);
when(
() => mockService.updateRecipe(
slug: slug,
formData: any(named: 'formData'),
),
).thenAnswer((_) async => Future.value(mockHttpResponse));
await repository.saveAsDraft(recipe, true, slug);
verify(
() => mockService.updateRecipe(
slug: slug,
formData: any(named: 'formData'),
),
).called(1);
});
test('saveAsDraft - update=true без slug кидает исключение', () async {
final recipe = RecipeModel(
type: 'main',
title: 'Draft title',
description: 'Draft desc',
videoUrl: null,
image: recipeImage.path,
ingredients: null,
steps: null,
tags: null,
totalCookingTime: 30,
activeCookTime: 15,
servings: 2,
energyPerServing: 200,
);
// slug! должен упасть
expect(() => repository.saveAsDraft(recipe, true, null), throwsA(anything));
});
test('draftExistingRecipe - вызывает draftRecipe', () async {
const id = 123;
when(() => mockService.draftRecipe(id: id)).thenAnswer((_) async => Future.value());
await repository.draftExistingRecipe(id);
verify(() => mockService.draftRecipe(id: id)).called(1);
});
test('draftExistingRecipe - пробрасывает исключение при ошибке', () async {
const id = 123;
when(() => mockService.draftRecipe(id: id)).thenThrow(Exception('Error'));
expect(() => repository.draftExistingRecipe(id), throwsA(isA<Exception>()));
});
});
}