diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml index 60aebe4f..b42ece1a 100644 --- a/.gitea/workflows/test.yml +++ b/.gitea/workflows/test.yml @@ -3,7 +3,7 @@ name: Eatvio App Android Test on: [ pull_request ] env: - flutter_version: "3.35.1" + flutter_version: "3.38.1" java_version: "21.x" flutter_channel: "stable" my_local_cache_dir: "/opt/hostedtoolcache/" @@ -71,7 +71,7 @@ jobs: - name: Install utils for Android SDK run: | apt-get update - apt-get install -y openjdk-11-jdk wget jq clang cmake ninja-build libgtk-3-dev + apt-get install -y openjdk-17-jdk wget jq clang cmake ninja-build libgtk-3-dev - name: Install Android SDK if: steps.cache-sdk.outputs.cache-hit != 'true' @@ -145,8 +145,27 @@ jobs: - name: Test coverage run: | awk -F: ' - /^LF:/ { total += $2 } - /^LH:/ { covered += $2 } + /^SF:/ { + file = $0 + sub(/^SF:/, "", file) + sub(/^[[:space:]]+/, "", file) + is_generated = 0 + if (file ~ /\.(g|freezed|gr|mocks)\.dart$/) { + is_generated = 1 + } else if (file ~ /\/(build|\.dart_tool)\//) { + is_generated = 1 + } + } + /^LF:/ { + if (!is_generated) { + total += $2 + } + } + /^LH:/ { + if (!is_generated) { + covered += $2 + } + } END { if (total == 0) { print "Coverage: 0%" diff --git a/.gitignore b/.gitignore index afeb23f8..530ea713 100644 --- a/.gitignore +++ b/.gitignore @@ -19,4 +19,5 @@ ios/XCBuildData/ env/.env .env android/key.properties -app/upload-keystore.jks \ No newline at end of file +app/upload-keystore.jks +coverage/ \ No newline at end of file diff --git a/android/build/reports/problems/problems-report.html b/android/build/reports/problems/problems-report.html index ce07f9e3..746fadde 100644 --- a/android/build/reports/problems/problems-report.html +++ b/android/build/reports/problems/problems-report.html @@ -650,7 +650,7 @@ code + .copy-button { diff --git a/lib/core/image_compressing/image_compress_utility.dart b/lib/core/image_compressing/image_compress_utility.dart index e3c5fa65..b9cbeb18 100644 --- a/lib/core/image_compressing/image_compress_utility.dart +++ b/lib/core/image_compressing/image_compress_utility.dart @@ -1,4 +1,7 @@ import 'dart:io'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/locator_service.dart'; import 'package:flutter_image_compress/flutter_image_compress.dart'; import 'package:image/image.dart' as img; import 'package:path/path.dart' as p; @@ -27,6 +30,17 @@ abstract class ImageCompressUtility { } static Future compressFile(File file) async { + // Skip compression in test environment to avoid hangs + try { + final appConfig = sl(); + if (appConfig.buildType == AppBuildType.tests) { + // In tests, return the original file without compression + return file; + } + } catch (_) { + // If AppConfig is not available, proceed with compression + } + final image = img.decodeImage(file.readAsBytesSync())!; int width = image.width; int height = image.height; diff --git a/lib/features/blog_post/presentation/pages/blog_post_screen.dart b/lib/features/blog_post/presentation/pages/blog_post_screen.dart index f10bb742..08312aeb 100644 --- a/lib/features/blog_post/presentation/pages/blog_post_screen.dart +++ b/lib/features/blog_post/presentation/pages/blog_post_screen.dart @@ -19,6 +19,7 @@ import 'package:flutter_html/flutter_html.dart'; import 'package:go_router/go_router.dart'; import 'package:share_plus/share_plus.dart'; import 'package:markdown/markdown.dart' as md; +import 'package:url_launcher/url_launcher.dart'; class BlogPostScreen extends StatefulWidget { final int id; @@ -233,33 +234,103 @@ class _BlogPostScreenState extends State { if (blogPostState.blogPostModel?.description.isNotEmpty ?? false) Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Html( - data: md.markdownToHtml(blogPostState.blogPostModel!.description.replaceAll('\n', '
')), - style: { - "body": Style(margin: Margins.zero, padding: HtmlPaddings.zero, fontSize: FontSize(16), lineHeight: const LineHeight(1.5)), - "p": Style(margin: Margins.only(bottom: 12), color: Colors.black87), - "h1, h2, h3, h4, h5, h6": Style(margin: Margins.only(top: 16, bottom: 8), color: Colors.black, fontWeight: FontWeight.bold), - "h1": Style(fontSize: FontSize(24)), - "h2": Style(fontSize: FontSize(20)), - "h3": Style(fontSize: FontSize(18)), - "ul, ol": Style(margin: Margins.only(bottom: 12), padding: HtmlPaddings.only(left: 16)), - "li": Style(margin: Margins.only(bottom: 4), color: Colors.black87), - "strong, b": Style(fontWeight: FontWeight.bold, color: Colors.black), - "em, i": Style(fontStyle: FontStyle.italic), - "code": Style( - backgroundColor: Colors.grey.shade100, - padding: HtmlPaddings.symmetric(horizontal: 4, vertical: 2), - fontFamily: 'monospace', - ), - "pre": Style(backgroundColor: Colors.grey.shade100, padding: HtmlPaddings.all(12), margin: Margins.only(bottom: 12)), - "blockquote": Style( - padding: HtmlPaddings.only(left: 16), - margin: Margins.only(left: 8, bottom: 12), - fontStyle: FontStyle.italic, - color: Colors.grey.shade700, - ), - "a": Style(color: Colors.blue, textDecoration: TextDecoration.underline), - "img": Style(width: Width(MediaQuery.of(context).size.width - 32)), + child: Builder( + builder: (context) { + // Автоматически преобразуем URL в markdown ссылки + String description = blogPostState.blogPostModel!.description; + + // Сначала исправляем неправильный синтаксис markdown ссылок, где URL в тексте, а не в href + // Например: [http://example.com](url) -> [http://example.com](http://example.com) + final wrongLinkRegex = RegExp(r'\[(https?://[^\]]+|www\.[^\]]+)\]\(([^\)]+)\)'); + description = description.replaceAllMapped(wrongLinkRegex, (match) { + final urlInText = match.group(1)!; + // Если текст ссылки является URL, используем его как href + if (!urlInText.startsWith('http://') && !urlInText.startsWith('https://') && !urlInText.startsWith('www.')) { + return match.group(0)!; // Оставляем как есть, если это не URL + } + final fullUrl = urlInText.startsWith('www.') ? 'https://$urlInText' : urlInText; + // Используем URL как href, а текст ссылки - это сам URL + return '[$urlInText]($fullUrl)'; + }); + + // Теперь находим все существующие markdown ссылки и их позиции + final linkRegex = RegExp(r'\[([^\]]+)\]\(([^\)]+)\)'); + final existingLinks = <_LinkRange>[]; + + for (final linkMatch in linkRegex.allMatches(description)) { + existingLinks.add(_LinkRange(linkMatch.start, linkMatch.end)); + } + + // Регулярное выражение для поиска URL (http://, https://, www.) + final urlRegex = RegExp(r'(https?://[^\s\)]+|www\.[^\s\)]+)', caseSensitive: false); + + // Заменяем URL на markdown ссылки, если они еще не являются ссылками + String result = description; + int offset = 0; + + for (final urlMatch in urlRegex.allMatches(description)) { + // Проверяем, не находится ли URL внутри существующей markdown ссылки + bool isInsideLink = existingLinks.any((link) => urlMatch.start >= link.start && urlMatch.end <= link.end); + + if (!isInsideLink) { + final url = urlMatch.group(0)!; + final fullUrl = url.startsWith('www.') ? 'https://$url' : url; + final replacement = '[$url]($fullUrl)'; + result = result.replaceRange(urlMatch.start + offset, urlMatch.end + offset, replacement); + offset += replacement.length - url.length; + } + } + + description = result; + + final htmlData = md.markdownToHtml(description.replaceAll('\n', '
'), extensionSet: md.ExtensionSet.commonMark); + debugPrint('Markdown input: ${blogPostState.blogPostModel!.description}'); + debugPrint('Processed markdown: $description'); + debugPrint('HTML output: $htmlData'); + return Html( + data: htmlData, + style: { + "body": Style(margin: Margins.zero, padding: HtmlPaddings.zero, fontSize: FontSize(16), lineHeight: const LineHeight(1.5)), + "p": Style(margin: Margins.only(bottom: 12), color: Colors.black87), + "h1, h2, h3, h4, h5, h6": Style(margin: Margins.only(top: 16, bottom: 8), color: Colors.black, fontWeight: FontWeight.bold), + "h1": Style(fontSize: FontSize(24)), + "h2": Style(fontSize: FontSize(20)), + "h3": Style(fontSize: FontSize(18)), + "ul, ol": Style(margin: Margins.only(bottom: 12), padding: HtmlPaddings.only(left: 16)), + "li": Style(margin: Margins.only(bottom: 4), color: Colors.black87), + "strong, b": Style(fontWeight: FontWeight.bold, color: Colors.black), + "em, i": Style(fontStyle: FontStyle.italic), + "code": Style( + backgroundColor: Colors.grey.shade100, + padding: HtmlPaddings.symmetric(horizontal: 4, vertical: 2), + fontFamily: 'monospace', + ), + "pre": Style(backgroundColor: Colors.grey.shade100, padding: HtmlPaddings.all(12), margin: Margins.only(bottom: 12)), + "blockquote": Style( + padding: HtmlPaddings.only(left: 16), + margin: Margins.only(left: 8, bottom: 12), + fontStyle: FontStyle.italic, + color: Colors.grey.shade700, + ), + "a": Style(color: Colors.blue, textDecoration: TextDecoration.underline), + "img": Style(width: Width(MediaQuery.of(context).size.width - 32)), + }, + onLinkTap: (url, attributes, element) async { + debugPrint('Link tapped: $url'); + if (url != null) { + try { + final uri = Uri.parse(url); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } else { + debugPrint('Cannot launch URL: $url'); + } + } catch (e) { + debugPrint('Error launching URL: $e'); + } + } + }, + ); }, ), ), @@ -363,3 +434,10 @@ class _BlogPostScreenState extends State { ); } } + +class _LinkRange { + final int start; + final int end; + + _LinkRange(this.start, this.end); +} diff --git a/lib/features/consultant/become_consultant/models/consultant_cert_photo_model.dart b/lib/features/consultant/become_consultant/models/consultant_cert_photo_model.dart new file mode 100644 index 00000000..6fdcc1e8 --- /dev/null +++ b/lib/features/consultant/become_consultant/models/consultant_cert_photo_model.dart @@ -0,0 +1,27 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'consultant_cert_photo_model.freezed.dart'; +part 'consultant_cert_photo_model.g.dart'; + +@freezed +abstract class ConsultantCertPhotoModel with _$ConsultantCertPhotoModel { + const factory ConsultantCertPhotoModel({ + required int id, + @JsonKey(name: 'user_id') int? userId, + required String group, + @JsonKey(name: 'original_name') required String originalName, + required String path, + required int size, + Map? specs, + required String url, + }) = _ConsultantCertPhotoModel; + + const ConsultantCertPhotoModel._(); + + factory ConsultantCertPhotoModel.fromJson(Map json) => _$ConsultantCertPhotoModelFromJson(json); + + static const String visibleGroup = 'user_certs'; + static const String hiddenGroup = 'hidden_user_certs'; + + bool get isHidden => group == hiddenGroup; +} diff --git a/lib/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart b/lib/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart index 84961990..3c6f487c 100644 --- a/lib/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart +++ b/lib/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart @@ -1,59 +1,33 @@ import 'dart:io'; import 'package:eatvio_app/core/image_compressing/image_compress_utility.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_profile_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:http/http.dart' as http; -import 'package:path_provider/path_provider.dart'; class RegisterConsultantCubit extends Cubit { final ConsultantRepository consultantRepository; bool _update = false; - RegisterConsultantCubit({ - required this.consultantRepository, - }) : super( - const RegisterConsultantState( - consultant: ConsultantProfileModel( - socialLinks: SocialLinksModel(), - hasMedicalEducation: true, - ), - loading: true, - acceptOffer: false, - ), - ); - - Future downloadImageAsFile(String imageUrl) async { - final response = await http.get(Uri.parse(imageUrl)); - - if (response.statusCode == 200) { - final tempDir = await getTemporaryDirectory(); - final filePath = '${tempDir.path}/${imageUrl.split('/').last}'; - final file = File(filePath); - return await file.writeAsBytes(response.bodyBytes); - } else { - throw Exception('Не удалось загрузить изображение'); - } - } + RegisterConsultantCubit({required this.consultantRepository}) + : super( + const RegisterConsultantState( + consultant: ConsultantProfileModel(socialLinks: SocialLinksModel(), hasMedicalEducation: true), + loading: true, + acceptOffer: false, + ), + ); Future getMyRequestStatus(String slug) async { _update = true; final myRequestStatus = await consultantRepository.getMyRequestStatus(slug); - - final List photos = await Future.wait( - myRequestStatus.photos.map( - (e) async => (await downloadImageAsFile(e.url)).path, - ), - ); + final certPhotos = await _fetchVisibleCertPhotos(); List? certificates = myRequestStatus.educationModel.completedCourses?.map((courseMap) { final course = courseMap.values.first; - return CertificatesModel( - title: course.title, - date: course.date, - ); + return CertificatesModel(title: course.title, date: course.date); }).toList(); String? sanitizeLink(String? link) { @@ -63,7 +37,6 @@ class RegisterConsultantCubit extends Cubit { emit( RegisterConsultantState( consultant: ConsultantProfileModel( - photos: photos, certificates: certificates, socialLinks: SocialLinksModel( vkLink: sanitizeLink(myRequestStatus.educationModel.vkLink), @@ -77,38 +50,44 @@ class RegisterConsultantCubit extends Cubit { acceptOffer: false, loading: false, requestModel: myRequestStatus, + certPhotos: certPhotos, ), ); } - void disableLoading() { - emit(state.copyWith(loading: false)); + Future disableLoading() async { + final certPhotos = await _fetchVisibleCertPhotos(); + emit(state.copyWith(loading: false, certPhotos: certPhotos)); } void updateConsultantProfileModel(ConsultantProfileModel consultant, [bool acceptOffer = false]) { - emit( - state.copyWith( - consultant: consultant, - acceptOffer: acceptOffer, - loading: false, - ), - ); + emit(state.copyWith(consultant: consultant, acceptOffer: acceptOffer, loading: false)); } Future registerConsultant() async { - if (state.consultant.photos != null) { - updateConsultantProfileModel( - state.consultant.copyWith( - photos: await uploadPhotos( - state.consultant.photos!.map((e) => File(e)).toList(), - ), - ), - ); - } await consultantRepository.registerConsultant(consultant: state.consultant, update: _update); } - Future> uploadPhotos(List files) async { - return await consultantRepository.uploadPhotos(files: await ImageCompressUtility.compressFilesList(files)); + Future uploadCertPhotos(List files) async { + if (files.isEmpty) { + return; + } + final compressedFiles = await ImageCompressUtility.compressFilesList(files); + final uploaded = await consultantRepository.storeConsultantCertPhotos(files: compressedFiles); + emit(state.copyWith(certPhotos: _onlyVisible(uploaded))); + } + + Future removeCertPhoto(int id) async { + await consultantRepository.hideConsultantCertPhoto(id); + emit(state.copyWith(certPhotos: state.certPhotos.where((photo) => photo.id != id).toList())); + } + + Future> _fetchVisibleCertPhotos() async { + final photos = await consultantRepository.getConsultantCertPhotos(); + return _onlyVisible(photos); + } + + List _onlyVisible(List photos) { + return photos.where((photo) => !photo.isHidden).toList(); } } diff --git a/lib/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart b/lib/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart index 5f613821..ee6644a9 100644 --- a/lib/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart +++ b/lib/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_profile_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -11,5 +12,6 @@ abstract class RegisterConsultantState with _$RegisterConsultantState { required bool acceptOffer, required bool loading, ConsultationRequestModel? requestModel, + @Default([]) List certPhotos, }) = _RegisterConsultantState; } diff --git a/lib/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen.dart b/lib/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen.dart index 234e3d74..4ad6db76 100644 --- a/lib/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen.dart +++ b/lib/features/consultant/become_consultant/presentation/pages/photo_or_scans_screen.dart @@ -1,9 +1,11 @@ import 'dart:io'; import 'package:dismissible_page/dismissible_page.dart'; -import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; -import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_state.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:image_picker/image_picker.dart'; @@ -16,14 +18,7 @@ class PhotoOrScansScreen extends StatefulWidget { } class _PhotoOrScansScreenState extends State { - List imagesPaths = []; - - @override - void initState() { - super.initState(); - imagesPaths = - context.read().state.consultant.photos != null ? [...context.read().state.consultant.photos!] : []; - } + bool isUploading = false; @override Widget build(BuildContext context) { @@ -34,125 +29,121 @@ class _PhotoOrScansScreenState extends State { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - const Text( - 'Загрузите фото или сканы дипломов и сертификатов', - style: TextStyle( - fontSize: 24, - fontWeight: FontWeight.w700, - height: 1.1, - ), - ), + const Text('Загрузите фото или сканы дипломов и сертификатов', style: TextStyle(fontSize: 24, fontWeight: FontWeight.w700, height: 1.1)), const SizedBox(height: 16), - GridView.builder( - shrinkWrap: true, - physics: const NeverScrollableScrollPhysics(), - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 3, - childAspectRatio: 3 / 4, - crossAxisSpacing: 8, - mainAxisSpacing: 8, - ), - itemBuilder: (BuildContext context, int index) { - if (index == imagesPaths.length) { - return InkWell( - borderRadius: BorderRadius.circular(20), - onTap: () async { - final picker = ImagePicker(); - List? newImages = await picker.pickMultiImage(); - List newImagesPaths = newImages.map((e) => e.path).toList(); - setState(() { - imagesPaths = [...imagesPaths, ...newImagesPaths]; - }); - _saveState(); - }, - child: Ink( - decoration: BoxDecoration( - color: const Color(0xFFF6F6F6), - borderRadius: BorderRadius.circular(20), + BlocBuilder( + builder: (context, state) { + final photos = state.certPhotos; + return Column( + children: [ + if (isUploading) ...[const LinearProgressIndicator(), const SizedBox(height: 16)], + GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + childAspectRatio: 3 / 4, + crossAxisSpacing: 8, + mainAxisSpacing: 8, ), - child: Icon( - Icons.add, - color: appTheme.blueA400, - ), - ), - ); - } else { - return Hero( - tag: imagesPaths[index], - child: Material( - borderRadius: BorderRadius.circular(20), - child: InkWell( - onTap: () { - context.pushTransparentRoute( - rootNavigator: true, - PhotoViewScreen( - imageUrls: imagesPaths, - isLocal: true, - index: index, + itemBuilder: (BuildContext context, int index) { + if (index == photos.length) { + return InkWell( + borderRadius: BorderRadius.circular(20), + onTap: () => _pickAndUploadPhotos(), + child: Ink( + decoration: BoxDecoration(color: const Color(0xFFF6F6F6), borderRadius: BorderRadius.circular(20)), + child: Icon(Icons.add, color: appTheme.blueA400), ), ); - }, - borderRadius: BorderRadius.circular(20), - child: Stack( - clipBehavior: Clip.none, - children: [ - Ink( - decoration: BoxDecoration( - borderRadius: const BorderRadius.all( - Radius.circular(20), - ), - image: DecorationImage( - fit: BoxFit.fitHeight, - image: FileImage( - File(imagesPaths[index]), - ), - ), - ), - ), - Positioned( - right: -12, - top: -12, - child: InkWell( - onTap: () { - setState(() { - imagesPaths.removeAt(index); - }); - _saveState(); - }, - customBorder: const CircleBorder(), - child: Ink( - padding: const EdgeInsets.all(4), - decoration: const BoxDecoration( - color: Color(0xFFF1F2F6), - shape: BoxShape.circle, - ), - child: const Icon( - size: 20, - Icons.close, - color: Colors.black, - ), - ), - ), - ), - ], - ), - ), + } else { + return _CertPhotoCard(photo: photos[index], allPhotos: photos, onRemove: () => _removePhoto(photos[index].id)); + } + }, + itemCount: photos.length + 1, ), - ); - } + ], + ); }, - itemCount: imagesPaths.length + 1, ), ], ), ); } - void _saveState() { - context.read().updateConsultantProfileModel( - context.read().state.consultant.copyWith( - photos: imagesPaths, - ), - ); + Future _pickAndUploadPhotos() async { + final picker = ImagePicker(); + final newImages = await picker.pickMultiImage(); + if (newImages.isEmpty) { + return; + } + setState(() { + isUploading = true; + }); + try { + // ignore: use_build_context_synchronously + await context.read().uploadCertPhotos(newImages.map((file) => File(file.path)).toList()); + } finally { + if (mounted) { + setState(() { + isUploading = false; + }); + } + } + } + + Future _removePhoto(int id) async { + await context.read().removeCertPhoto(id); + } +} + +class _CertPhotoCard extends StatelessWidget { + final ConsultantCertPhotoModel photo; + final List allPhotos; + final VoidCallback onRemove; + + const _CertPhotoCard({required this.photo, required this.allPhotos, required this.onRemove}); + + @override + Widget build(BuildContext context) { + return Hero( + tag: photo.id, + child: Material( + borderRadius: BorderRadius.circular(20), + child: InkWell( + onTap: () { + context.pushTransparentRoute( + rootNavigator: true, + PhotoViewScreen(imageUrls: allPhotos.map((e) => e.url).toList(), isLocal: false, index: allPhotos.indexOf(photo)), + ); + }, + borderRadius: BorderRadius.circular(20), + child: Stack( + clipBehavior: Clip.none, + children: [ + Ink( + decoration: BoxDecoration( + borderRadius: const BorderRadius.all(Radius.circular(20)), + image: DecorationImage(fit: BoxFit.cover, image: NetworkImage(photo.url)), + ), + ), + Positioned( + right: -12, + top: -12, + child: InkWell( + onTap: onRemove, + customBorder: const CircleBorder(), + child: Ink( + padding: const EdgeInsets.all(4), + decoration: const BoxDecoration(color: Color(0xFFF1F2F6), shape: BoxShape.circle), + child: const Icon(size: 20, Icons.close, color: Colors.black), + ), + ), + ), + ], + ), + ), + ), + ); } } diff --git a/lib/features/consultant/become_consultant/repositories/consultant_repository.dart b/lib/features/consultant/become_consultant/repositories/consultant_repository.dart index 89eef1c8..05f357c3 100644 --- a/lib/features/consultant/become_consultant/repositories/consultant_repository.dart +++ b/lib/features/consultant/become_consultant/repositories/consultant_repository.dart @@ -1,62 +1,28 @@ import 'dart:io'; +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_profile_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/services/consultant_service.dart'; import 'package:http_parser/http_parser.dart'; -import 'package:dio/dio.dart'; class ConsultantRepository { final ConsultantService consultantService; - const ConsultantRepository({ - required this.consultantService, - }); + const ConsultantRepository({required this.consultantService}); - Future registerConsultant({ - required ConsultantProfileModel consultant, - bool update = false, - }) async { + Future registerConsultant({required ConsultantProfileModel consultant, bool update = false}) async { try { if (update) { - return await consultantService.consultantUpdate( - consultantModel: consultant, - ); + return await consultantService.consultantUpdate(consultantModel: consultant); } else { - return await consultantService.consultantRegistration( - consultantModel: consultant, - ); + return await consultantService.consultantRegistration(consultantModel: consultant); } } catch (e) { rethrow; } } - Future> uploadPhotos({ - required List files, - }) async { - try { - final multipartFiles = []; - - for (final file in files) { - final fileBytes = await file.readAsBytes(); - final multipartFile = MultipartFile.fromBytes( - fileBytes, - filename: file.path - .split('/') - .last, - contentType: MediaType('application', 'octet-stream'), - ); - multipartFiles.add(multipartFile); - } - - return await consultantService.uploadPhotos( - photos: multipartFiles.isEmpty ? null : multipartFiles, - ); - } catch (e) { - rethrow; - } - } - Future getConsultantRequestStatus(String slug) async { try { return await consultantService.getConsultantRequestStatus(slug: slug); @@ -72,4 +38,48 @@ class ConsultantRepository { rethrow; } } + + Future> getConsultantCertPhotos() async { + try { + return await consultantService.getConsultantCertPhotos(); + } catch (e) { + rethrow; + } + } + + Future> storeConsultantCertPhotos({required List files}) async { + try { + final multipartFiles = []; + + for (final file in files) { + final fileBytes = await file.readAsBytes(); + final multipartFile = MultipartFile.fromBytes(fileBytes, filename: file.path.split('/').last, contentType: MediaType('application', 'octet-stream')); + multipartFiles.add(multipartFile); + } + + if (multipartFiles.isEmpty) { + return []; + } + + return await consultantService.storeConsultantCertPhotos(photos: multipartFiles); + } catch (e) { + rethrow; + } + } + + Future hideConsultantCertPhoto(int id) async { + try { + await consultantService.hideConsultantCertPhoto(payload: {'cert_photo_id': id}); + } catch (e) { + rethrow; + } + } + + Future unHideConsultantCertPhoto(int id) async { + try { + await consultantService.unHideConsultantCertPhoto(payload: {'cert_photo_id': id}); + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/consultant/become_consultant/services/consultant_service.dart b/lib/features/consultant/become_consultant/services/consultant_service.dart index bfde5a92..d7171b8e 100644 --- a/lib/features/consultant/become_consultant/services/consultant_service.dart +++ b/lib/features/consultant/become_consultant/services/consultant_service.dart @@ -1,4 +1,5 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_profile_model.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; import 'package:retrofit/retrofit.dart'; @@ -10,28 +11,33 @@ abstract class ConsultantService { factory ConsultantService(Dio dio, {String baseUrl}) = _ConsultantService; @POST('/api/consultant_request/registration') - Future consultantRegistration({ - @Body() required ConsultantProfileModel consultantModel, - }); + Future consultantRegistration({@Body() required ConsultantProfileModel consultantModel}); @POST('/api/consultant_request/photos/upload') @MultiPart() - Future> uploadPhotos({ - @Part(name: 'photos[]', contentType: 'multipart/form-data') List? photos, - }); + Future> uploadPhotos({@Part(name: 'photos[]', contentType: 'multipart/form-data') List? photos}); @GET('/api/profile/consultant/{slug}/status') - Future getConsultantRequestStatus({ - @Path() required String slug, - }); + Future getConsultantRequestStatus({@Path() required String slug}); @GET('/api/consultant_request/{slug}/status') - Future getMyRequestStatus({ - @Path() required String slug, - }); + Future getMyRequestStatus({@Path() required String slug}); @PUT('/api/consultant_request/update') - Future consultantUpdate({ - @Body() required ConsultantProfileModel consultantModel, + Future consultantUpdate({@Body() required ConsultantProfileModel consultantModel}); + + @GET('/api/v2/consultant_request/cert_photos') + Future> getConsultantCertPhotos(); + + @POST('/api/v2/consultant_request/cert_photos/store') + @MultiPart() + Future> storeConsultantCertPhotos({ + @Part(name: 'photos[]', contentType: 'multipart/form-data') required List photos, }); + + @POST('/api/v2/consultant_request/cert_photos/hide') + Future hideConsultantCertPhoto({@Body() required Map payload}); + + @POST('/api/v2/consultant_request/cert_photos/un_hide') + Future unHideConsultantCertPhoto({@Body() required Map payload}); } diff --git a/lib/features/diary/presentation/pages/barcode_scanner_screen.dart b/lib/features/diary/presentation/pages/barcode_scanner_screen.dart new file mode 100644 index 00000000..19994568 --- /dev/null +++ b/lib/features/diary/presentation/pages/barcode_scanner_screen.dart @@ -0,0 +1,87 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_scanner/mobile_scanner.dart'; + +class BarcodeScannerScreen extends StatefulWidget { + const BarcodeScannerScreen({super.key}); + + @override + State createState() => _BarcodeScannerScreenState(); +} + +class _BarcodeScannerScreenState extends State { + final MobileScannerController _controller = MobileScannerController(); + String? _detectedBarcode; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Сканирование штрихкода'), + centerTitle: true, + ), + body: Column( + children: [ + Expanded( + child: MobileScanner( + controller: _controller, + onDetect: (capture) { + final List barcodes = capture.barcodes; + if (barcodes.isEmpty) return; + final rawValue = barcodes.first.rawValue; + if (rawValue == null || rawValue == _detectedBarcode) return; + setState(() { + _detectedBarcode = rawValue; + }); + }, + ), + ), + Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: const BoxDecoration( + color: Color(0xFFF6F6F6), + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text( + 'Найденный штрихкод', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500), + ), + const SizedBox(height: 8), + Text( + _detectedBarcode ?? 'Наведите камеру на штрихкод', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: _detectedBarcode == null ? Colors.grey : Colors.black, + ), + ), + const SizedBox(height: 16), + if (_detectedBarcode != null) + SizedBox( + width: double.infinity, + child: ElevatedButton( + onPressed: () { + Navigator.of(context).pop(_detectedBarcode); + }, + child: const Text('Использовать штрихкод'), + ), + ), + ], + ), + ), + ], + ), + ); + } +} + diff --git a/lib/features/diary/presentation/widgets/add_product_modal.dart b/lib/features/diary/presentation/widgets/add_product_modal.dart index 4b0a3806..9d77249e 100644 --- a/lib/features/diary/presentation/widgets/add_product_modal.dart +++ b/lib/features/diary/presentation/widgets/add_product_modal.dart @@ -5,9 +5,11 @@ import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/features/diary/models/diary_day_model.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; +import 'package:eatvio_app/features/diary/presentation/pages/barcode_scanner_screen.dart'; import 'package:eatvio_app/features/diary/presentation/widgets/glossary_moderation_request_modal_widget.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/material_symbols_icons.dart'; class AddProductModal extends StatefulWidget { final PortionModel? portion; @@ -62,9 +64,25 @@ class _AddProductModalState extends State { crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - const Text( - 'Добавление блюда', - style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: Color(0xFF323F4B)), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Добавление блюда', + style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: Color(0xFF323F4B)), + ), + IconButton( + onPressed: () async { + final barcode = await Navigator.of(context).push(MaterialPageRoute(builder: (context) => const BarcodeScannerScreen())); + if (barcode != null && barcode.isNotEmpty) { + productNameController.text = barcode; + setState(() {}); + } + }, + splashRadius: 20, + icon: const Icon(Symbols.barcode_scanner, color: Color(0xFF323F4B)), + ), + ], ), const SizedBox(height: 16), Row( diff --git a/lib/features/feed/presentation/widgets/diets_widget.dart b/lib/features/feed/presentation/widgets/diets_widget.dart index 257811bf..095de75c 100644 --- a/lib/features/feed/presentation/widgets/diets_widget.dart +++ b/lib/features/feed/presentation/widgets/diets_widget.dart @@ -18,6 +18,7 @@ import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; import 'package:share_plus/share_plus.dart'; import 'package:markdown/markdown.dart' as md; +import 'package:url_launcher/url_launcher.dart'; class DietsWidget extends StatefulWidget { final Diet diet; @@ -111,12 +112,52 @@ class _DietsWidgetState extends State { const SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), - child: Html( - data: md.markdownToHtml( - widget.diet.details.length > 200 - ? '${widget.diet.details.substring(0, 200).replaceAll('\n', '
')}...' - : widget.diet.details.replaceAll('\n', '
'), - ), + child: Builder( + builder: (context) { + String details = widget.diet.details.length > 200 + ? '${widget.diet.details.substring(0, 200)}...' + : widget.diet.details; + // Автоматически преобразуем URL в markdown ссылки + // Сначала исправляем неправильный синтаксис markdown ссылок + final wrongLinkRegex = RegExp(r'\[(https?://[^\]]+|www\.[^\]]+)\]\(([^\)]+)\)'); + details = details.replaceAllMapped(wrongLinkRegex, (match) { + final urlInText = match.group(1)!; + if (!urlInText.startsWith('http://') && !urlInText.startsWith('https://') && !urlInText.startsWith('www.')) { + return match.group(0)!; + } + final fullUrl = urlInText.startsWith('www.') ? 'https://$urlInText' : urlInText; + return '[$urlInText]($fullUrl)'; + }); + + final linkRegex = RegExp(r'\[([^\]]+)\]\(([^\)]+)\)'); + final existingLinks = <_LinkRange>[]; + for (final linkMatch in linkRegex.allMatches(details)) { + existingLinks.add(_LinkRange(linkMatch.start, linkMatch.end)); + } + final urlRegex = RegExp(r'(https?://[^\s\)]+|www\.[^\s\)]+)', caseSensitive: false); + String result = details; + int offset = 0; + for (final urlMatch in urlRegex.allMatches(details)) { + bool isInsideLink = existingLinks.any((link) => + urlMatch.start >= link.start && urlMatch.end <= link.end); + if (!isInsideLink) { + final url = urlMatch.group(0)!; + final fullUrl = url.startsWith('www.') ? 'https://$url' : url; + final replacement = '[$url]($fullUrl)'; + result = result.replaceRange( + urlMatch.start + offset, + urlMatch.end + offset, + replacement, + ); + offset += replacement.length - url.length; + } + } + details = result; + return Html( + data: md.markdownToHtml( + details.replaceAll('\n', '
'), + extensionSet: md.ExtensionSet.commonMark, + ), style: { "body": Style( margin: Margins.zero, @@ -148,6 +189,16 @@ class _DietsWidgetState extends State { "a": Style(color: Colors.blue, textDecoration: TextDecoration.underline), "img": Style(width: Width(MediaQuery.of(context).size.width - 32)), }, + onLinkTap: (url, attributes, element) async { + if (url != null) { + final uri = Uri.parse(url); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } + }, + ); + }, ), ), ], @@ -215,3 +266,9 @@ class _DietsWidgetState extends State { ); } } + +class _LinkRange { + final int start; + final int end; + _LinkRange(this.start, this.end); +} diff --git a/lib/features/feed/presentation/widgets/plan_widget.dart b/lib/features/feed/presentation/widgets/plan_widget.dart index dae66fbf..054cee40 100644 --- a/lib/features/feed/presentation/widgets/plan_widget.dart +++ b/lib/features/feed/presentation/widgets/plan_widget.dart @@ -20,6 +20,7 @@ import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; import 'package:share_plus/share_plus.dart'; import 'package:markdown/markdown.dart' as md; +import 'package:url_launcher/url_launcher.dart'; class PlanWidget extends StatefulWidget { final PlanModel plan; @@ -116,12 +117,52 @@ class _PlanWidgetState extends State { const SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), - child: Html( - data: md.markdownToHtml( - widget.plan.details.length > 200 - ? '${widget.plan.details.substring(0, 200).replaceAll('\n', '
')}...' - : widget.plan.details.replaceAll('\n', '
'), - ), + child: Builder( + builder: (context) { + String details = widget.plan.details.length > 200 + ? '${widget.plan.details.substring(0, 200)}...' + : widget.plan.details; + // Автоматически преобразуем URL в markdown ссылки + // Сначала исправляем неправильный синтаксис markdown ссылок + final wrongLinkRegex = RegExp(r'\[(https?://[^\]]+|www\.[^\]]+)\]\(([^\)]+)\)'); + details = details.replaceAllMapped(wrongLinkRegex, (match) { + final urlInText = match.group(1)!; + if (!urlInText.startsWith('http://') && !urlInText.startsWith('https://') && !urlInText.startsWith('www.')) { + return match.group(0)!; + } + final fullUrl = urlInText.startsWith('www.') ? 'https://$urlInText' : urlInText; + return '[$urlInText]($fullUrl)'; + }); + + final linkRegex = RegExp(r'\[([^\]]+)\]\(([^\)]+)\)'); + final existingLinks = <_LinkRange>[]; + for (final linkMatch in linkRegex.allMatches(details)) { + existingLinks.add(_LinkRange(linkMatch.start, linkMatch.end)); + } + final urlRegex = RegExp(r'(https?://[^\s\)]+|www\.[^\s\)]+)', caseSensitive: false); + String result = details; + int offset = 0; + for (final urlMatch in urlRegex.allMatches(details)) { + bool isInsideLink = existingLinks.any((link) => + urlMatch.start >= link.start && urlMatch.end <= link.end); + if (!isInsideLink) { + final url = urlMatch.group(0)!; + final fullUrl = url.startsWith('www.') ? 'https://$url' : url; + final replacement = '[$url]($fullUrl)'; + result = result.replaceRange( + urlMatch.start + offset, + urlMatch.end + offset, + replacement, + ); + offset += replacement.length - url.length; + } + } + details = result; + return Html( + data: md.markdownToHtml( + details.replaceAll('\n', '
'), + extensionSet: md.ExtensionSet.commonMark, + ), style: { "body": Style(margin: Margins.zero, padding: HtmlPaddings.zero, fontSize: FontSize(16), lineHeight: const LineHeight(1.5)), "p": Style(margin: Margins.only(bottom: 12), color: appTheme.black), @@ -148,6 +189,16 @@ class _PlanWidgetState extends State { "a": Style(color: Colors.blue, textDecoration: TextDecoration.underline), "img": Style(width: Width(MediaQuery.of(context).size.width - 32)), }, + onLinkTap: (url, attributes, element) async { + if (url != null) { + final uri = Uri.parse(url); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } + }, + ); + }, ), ), if (widget.plan.details.length > 200) @@ -261,3 +312,9 @@ class _PlanWidgetState extends State { ); } } + +class _LinkRange { + final int start; + final int end; + _LinkRange(this.start, this.end); +} diff --git a/lib/features/feed/presentation/widgets/recipes_widget.dart b/lib/features/feed/presentation/widgets/recipes_widget.dart index 349fdb7d..347ab8cd 100644 --- a/lib/features/feed/presentation/widgets/recipes_widget.dart +++ b/lib/features/feed/presentation/widgets/recipes_widget.dart @@ -21,6 +21,7 @@ import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; import 'package:share_plus/share_plus.dart'; import 'package:markdown/markdown.dart' as md; +import 'package:url_launcher/url_launcher.dart'; class RecipesWidget extends StatefulWidget { final int index; @@ -149,12 +150,54 @@ class _RecipesWidgetState extends State { if (widget.recipe.description.isNotEmpty) Padding( padding: const EdgeInsets.symmetric(horizontal: 16), - child: Html( - data: md.markdownToHtml( - widget.recipe.description.length > 200 - ? widget.recipe.description.substring(0, 200).replaceAll('\n', '
') - : widget.recipe.description.replaceAll('\n', '
'), - ), + child: Builder( + builder: (context) { + String description = widget.recipe.description.length > 200 + ? widget.recipe.description.substring(0, 200) + : widget.recipe.description; + // Автоматически преобразуем URL в markdown ссылки + // Сначала исправляем неправильный синтаксис markdown ссылок + final wrongLinkRegex = RegExp(r'\[(https?://[^\]]+|www\.[^\]]+)\]\(([^\)]+)\)'); + description = description.replaceAllMapped(wrongLinkRegex, (match) { + final urlInText = match.group(1)!; + if (!urlInText.startsWith('http://') && !urlInText.startsWith('https://') && !urlInText.startsWith('www.')) { + return match.group(0)!; + } + final fullUrl = urlInText.startsWith('www.') ? 'https://$urlInText' : urlInText; + return '[$urlInText]($fullUrl)'; + }); + + // Находим все существующие markdown ссылки и их позиции + final linkRegex = RegExp(r'\[([^\]]+)\]\(([^\)]+)\)'); + final existingLinks = <_LinkRange>[]; + for (final linkMatch in linkRegex.allMatches(description)) { + existingLinks.add(_LinkRange(linkMatch.start, linkMatch.end)); + } + + final urlRegex = RegExp(r'(https?://[^\s\)]+|www\.[^\s\)]+)', caseSensitive: false); + String result = description; + int offset = 0; + for (final urlMatch in urlRegex.allMatches(description)) { + bool isInsideLink = existingLinks.any((link) => + urlMatch.start >= link.start && urlMatch.end <= link.end); + if (!isInsideLink) { + final url = urlMatch.group(0)!; + final fullUrl = url.startsWith('www.') ? 'https://$url' : url; + final replacement = '[$url]($fullUrl)'; + result = result.replaceRange( + urlMatch.start + offset, + urlMatch.end + offset, + replacement, + ); + offset += replacement.length - url.length; + } + } + description = result; + return Html( + data: md.markdownToHtml( + description.replaceAll('\n', '
'), + extensionSet: md.ExtensionSet.commonMark, + ), style: { "body": Style( margin: Margins.zero, @@ -186,6 +229,16 @@ class _RecipesWidgetState extends State { "a": Style(color: Colors.blue, textDecoration: TextDecoration.underline), "img": Style(width: Width(MediaQuery.of(context).size.width - 32)), }, + onLinkTap: (url, attributes, element) async { + if (url != null) { + final uri = Uri.parse(url); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } + }, + ); + }, ), ), if (widget.recipe.description.length > 200) @@ -276,3 +329,9 @@ class _RecipesWidgetState extends State { ); } } + +class _LinkRange { + final int start; + final int end; + _LinkRange(this.start, this.end); +} diff --git a/lib/features/my_diets/presentation/widgets/my_diet_widget.dart b/lib/features/my_diets/presentation/widgets/my_diet_widget.dart index 190f7834..a3b8fced 100644 --- a/lib/features/my_diets/presentation/widgets/my_diet_widget.dart +++ b/lib/features/my_diets/presentation/widgets/my_diet_widget.dart @@ -26,6 +26,7 @@ import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; import 'package:share_plus/share_plus.dart'; import 'package:markdown/markdown.dart' as md; +import 'package:url_launcher/url_launcher.dart'; class MyDietWidget extends StatefulWidget { final Diet diet; @@ -80,12 +81,52 @@ class _MyDietWidgetState extends State { const SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), - child: Html( - data: md.markdownToHtml( - widget.diet.details.length > 200 - ? '${widget.diet.details.substring(0, 200).replaceAll('\n', '
')}...' - : widget.diet.details.replaceAll('\n', '
'), - ), + child: Builder( + builder: (context) { + String details = widget.diet.details.length > 200 + ? '${widget.diet.details.substring(0, 200)}...' + : widget.diet.details; + // Автоматически преобразуем URL в markdown ссылки + // Сначала исправляем неправильный синтаксис markdown ссылок + final wrongLinkRegex = RegExp(r'\[(https?://[^\]]+|www\.[^\]]+)\]\(([^\)]+)\)'); + details = details.replaceAllMapped(wrongLinkRegex, (match) { + final urlInText = match.group(1)!; + if (!urlInText.startsWith('http://') && !urlInText.startsWith('https://') && !urlInText.startsWith('www.')) { + return match.group(0)!; + } + final fullUrl = urlInText.startsWith('www.') ? 'https://$urlInText' : urlInText; + return '[$urlInText]($fullUrl)'; + }); + + final linkRegex = RegExp(r'\[([^\]]+)\]\(([^\)]+)\)'); + final existingLinks = <_LinkRange>[]; + for (final linkMatch in linkRegex.allMatches(details)) { + existingLinks.add(_LinkRange(linkMatch.start, linkMatch.end)); + } + final urlRegex = RegExp(r'(https?://[^\s\)]+|www\.[^\s\)]+)', caseSensitive: false); + String result = details; + int offset = 0; + for (final urlMatch in urlRegex.allMatches(details)) { + bool isInsideLink = existingLinks.any((link) => + urlMatch.start >= link.start && urlMatch.end <= link.end); + if (!isInsideLink) { + final url = urlMatch.group(0)!; + final fullUrl = url.startsWith('www.') ? 'https://$url' : url; + final replacement = '[$url]($fullUrl)'; + result = result.replaceRange( + urlMatch.start + offset, + urlMatch.end + offset, + replacement, + ); + offset += replacement.length - url.length; + } + } + details = result; + return Html( + data: md.markdownToHtml( + details.replaceAll('\n', '
'), + extensionSet: md.ExtensionSet.commonMark, + ), style: { "body": Style( margin: Margins.zero, @@ -117,6 +158,16 @@ class _MyDietWidgetState extends State { "a": Style(color: Colors.blue, textDecoration: TextDecoration.underline), "img": Style(width: Width(MediaQuery.of(context).size.width - 32)), }, + onLinkTap: (url, attributes, element) async { + if (url != null) { + final uri = Uri.parse(url); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } + }, + ); + }, ), ), ], @@ -271,3 +322,9 @@ class _MyDietWidgetState extends State { ); } } + +class _LinkRange { + final int start; + final int end; + _LinkRange(this.start, this.end); +} diff --git a/lib/features/my_plans/presentation/widgets/my_plan_widget.dart b/lib/features/my_plans/presentation/widgets/my_plan_widget.dart index 14a2567f..f9ee70d2 100644 --- a/lib/features/my_plans/presentation/widgets/my_plan_widget.dart +++ b/lib/features/my_plans/presentation/widgets/my_plan_widget.dart @@ -19,6 +19,7 @@ import 'package:flutter_html/flutter_html.dart'; import 'package:go_router/go_router.dart'; import 'package:share_plus/share_plus.dart'; import 'package:markdown/markdown.dart' as md; +import 'package:url_launcher/url_launcher.dart'; class MyPlanWidget extends StatefulWidget { final PlanModel plan; @@ -72,12 +73,52 @@ class _MyPlanWidgetState extends State { const SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), - child: Html( - data: md.markdownToHtml( - widget.plan.details.length > 200 - ? '${widget.plan.details.substring(0, 200).replaceAll('\n', '
')}...' - : widget.plan.details.replaceAll('\n', '
'), - ), + child: Builder( + builder: (context) { + String details = widget.plan.details.length > 200 + ? '${widget.plan.details.substring(0, 200)}...' + : widget.plan.details; + // Автоматически преобразуем URL в markdown ссылки + // Сначала исправляем неправильный синтаксис markdown ссылок + final wrongLinkRegex = RegExp(r'\[(https?://[^\]]+|www\.[^\]]+)\]\(([^\)]+)\)'); + details = details.replaceAllMapped(wrongLinkRegex, (match) { + final urlInText = match.group(1)!; + if (!urlInText.startsWith('http://') && !urlInText.startsWith('https://') && !urlInText.startsWith('www.')) { + return match.group(0)!; + } + final fullUrl = urlInText.startsWith('www.') ? 'https://$urlInText' : urlInText; + return '[$urlInText]($fullUrl)'; + }); + + final linkRegex = RegExp(r'\[([^\]]+)\]\(([^\)]+)\)'); + final existingLinks = <_LinkRange>[]; + for (final linkMatch in linkRegex.allMatches(details)) { + existingLinks.add(_LinkRange(linkMatch.start, linkMatch.end)); + } + final urlRegex = RegExp(r'(https?://[^\s\)]+|www\.[^\s\)]+)', caseSensitive: false); + String result = details; + int offset = 0; + for (final urlMatch in urlRegex.allMatches(details)) { + bool isInsideLink = existingLinks.any((link) => + urlMatch.start >= link.start && urlMatch.end <= link.end); + if (!isInsideLink) { + final url = urlMatch.group(0)!; + final fullUrl = url.startsWith('www.') ? 'https://$url' : url; + final replacement = '[$url]($fullUrl)'; + result = result.replaceRange( + urlMatch.start + offset, + urlMatch.end + offset, + replacement, + ); + offset += replacement.length - url.length; + } + } + details = result; + return Html( + data: md.markdownToHtml( + details.replaceAll('\n', '
'), + extensionSet: md.ExtensionSet.commonMark, + ), style: { "body": Style( margin: Margins.zero, @@ -109,6 +150,16 @@ class _MyPlanWidgetState extends State { "a": Style(color: Colors.blue, textDecoration: TextDecoration.underline), "img": Style(width: Width(MediaQuery.of(context).size.width - 32)), }, + onLinkTap: (url, attributes, element) async { + if (url != null) { + final uri = Uri.parse(url); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } + }, + ); + }, ), ), ], @@ -216,3 +267,9 @@ class _MyPlanWidgetState extends State { ); } } + +class _LinkRange { + final int start; + final int end; + _LinkRange(this.start, this.end); +} diff --git a/lib/features/recipe/presentation/widgets/my_recipe_widget.dart b/lib/features/recipe/presentation/widgets/my_recipe_widget.dart index 3e73b7cc..71e2da04 100644 --- a/lib/features/recipe/presentation/widgets/my_recipe_widget.dart +++ b/lib/features/recipe/presentation/widgets/my_recipe_widget.dart @@ -17,6 +17,7 @@ import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; import 'package:markdown/markdown.dart' as md; import 'package:share_plus/share_plus.dart'; +import 'package:url_launcher/url_launcher.dart'; class MyRecipeWidget extends StatefulWidget { final MyRecipeModel recipe; @@ -94,12 +95,52 @@ class _MyRecipeWidgetState extends State { const SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), - child: Html( - data: md.markdownToHtml( - widget.recipe.description.length > 200 - ? '${widget.recipe.description.substring(0, 200).replaceAll('\n', '
')}...' - : widget.recipe.description.replaceAll('\n', '
'), - ), + child: Builder( + builder: (context) { + String description = widget.recipe.description.length > 200 + ? '${widget.recipe.description.substring(0, 200)}...' + : widget.recipe.description; + // Автоматически преобразуем URL в markdown ссылки + // Сначала исправляем неправильный синтаксис markdown ссылок + final wrongLinkRegex = RegExp(r'\[(https?://[^\]]+|www\.[^\]]+)\]\(([^\)]+)\)'); + description = description.replaceAllMapped(wrongLinkRegex, (match) { + final urlInText = match.group(1)!; + if (!urlInText.startsWith('http://') && !urlInText.startsWith('https://') && !urlInText.startsWith('www.')) { + return match.group(0)!; + } + final fullUrl = urlInText.startsWith('www.') ? 'https://$urlInText' : urlInText; + return '[$urlInText]($fullUrl)'; + }); + + final linkRegex = RegExp(r'\[([^\]]+)\]\(([^\)]+)\)'); + final existingLinks = <_LinkRange>[]; + for (final linkMatch in linkRegex.allMatches(description)) { + existingLinks.add(_LinkRange(linkMatch.start, linkMatch.end)); + } + final urlRegex = RegExp(r'(https?://[^\s\)]+|www\.[^\s\)]+)', caseSensitive: false); + String result = description; + int offset = 0; + for (final urlMatch in urlRegex.allMatches(description)) { + bool isInsideLink = existingLinks.any((link) => + urlMatch.start >= link.start && urlMatch.end <= link.end); + if (!isInsideLink) { + final url = urlMatch.group(0)!; + final fullUrl = url.startsWith('www.') ? 'https://$url' : url; + final replacement = '[$url]($fullUrl)'; + result = result.replaceRange( + urlMatch.start + offset, + urlMatch.end + offset, + replacement, + ); + offset += replacement.length - url.length; + } + } + description = result; + return Html( + data: md.markdownToHtml( + description.replaceAll('\n', '
'), + extensionSet: md.ExtensionSet.commonMark, + ), style: { "body": Style( margin: Margins.zero, @@ -131,6 +172,16 @@ class _MyRecipeWidgetState extends State { "a": Style(color: Colors.blue, textDecoration: TextDecoration.underline), "img": Style(width: Width(MediaQuery.of(context).size.width - 32)), }, + onLinkTap: (url, attributes, element) async { + if (url != null) { + final uri = Uri.parse(url); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } + }, + ); + }, ), ), ], @@ -218,3 +269,9 @@ class _MyRecipeWidgetState extends State { ); } } + +class _LinkRange { + final int start; + final int end; + _LinkRange(this.start, this.end); +} diff --git a/test/core/app_config_test.dart b/test/core/app_config_test.dart new file mode 100644 index 00000000..146a6262 --- /dev/null +++ b/test/core/app_config_test.dart @@ -0,0 +1,74 @@ +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppConfig', () { + setUp(() async { + // Инициализируем dotenv для тестов + dotenv.loadFromString(envString: ''' +BASE_URL=https://api.example.com +DEV_BASE_URL=https://dev-api.example.com +'''); + }); + + test('создание с buildType.prod - использует baseUrl', () { + final config = AppConfig(buildType: AppBuildType.prod); + + expect(config.buildType, AppBuildType.prod); + expect(config.baseUrl, isNotEmpty); + }); + + test('создание с buildType.dev - использует devBaseUrl', () { + final config = AppConfig(buildType: AppBuildType.dev); + + expect(config.buildType, AppBuildType.dev); + expect(config.baseUrl, isNotEmpty); + }); + + test('создание с buildType.tests - использует devBaseUrl', () { + final config = AppConfig(buildType: AppBuildType.tests); + + expect(config.buildType, AppBuildType.tests); + expect(config.baseUrl, isNotEmpty); + }); + + test('setBaseUrl - изменяет baseUrl', () { + final config = AppConfig(buildType: AppBuildType.tests); + const newUrl = 'http://test.example.com'; + + config.setBaseUrl(newUrl); + + expect(config.baseUrl, newUrl); + }); + + test('globalBlocProviders - возвращает список провайдеров', () { + final config = AppConfig(buildType: AppBuildType.tests); + + final providers = config.globalBlocProviders; + + expect(providers, isNotEmpty); + expect(providers.length, greaterThan(0)); + }); + + test('localizationDelegates - возвращает список делегатов', () { + final config = AppConfig(buildType: AppBuildType.tests); + + final delegates = config.localizationDelegates; + + expect(delegates, isNotEmpty); + expect(delegates.length, greaterThan(0)); + }); + + test('supportedLocales - возвращает список локалей', () { + final config = AppConfig(buildType: AppBuildType.tests); + + final locales = config.supportedLocales; + + expect(locales, isNotEmpty); + expect(locales.length, greaterThan(0)); + }); + }); +} + diff --git a/test/core/comments/comments_cubit/comments_cubit_test.dart b/test/core/comments/comments_cubit/comments_cubit_test.dart new file mode 100644 index 00000000..5dfba4b7 --- /dev/null +++ b/test/core/comments/comments_cubit/comments_cubit_test.dart @@ -0,0 +1,419 @@ +import 'package:eatvio_app/core/comments/comments_cubit/comments_cubit.dart'; +import 'package:eatvio_app/core/comments/comments_cubit/comments_state.dart'; +import 'package:eatvio_app/core/comments/repositories/comments_repository.dart'; +import 'package:eatvio_app/core/models/pagination_model.dart'; +import 'package:eatvio_app/features/feed/models/comment_model.dart'; +import 'package:eatvio_app/features/feed/presentation/widgets/comments_widget.dart'; +import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'comments_cubit_test.mocks.dart'; + +@GenerateNiceMocks([ + MockSpec(), + MockSpec(), +]) +void main() { + group('CommentsCubit', () { + CommentsCubit? commentsCubit; + late MockFeedRepository mockFeedRepository; + late MockCommentsRepository mockCommentsRepository; + late CommentModel testCommentModel; + + setUp(() { + mockFeedRepository = MockFeedRepository(); + mockCommentsRepository = MockCommentsRepository(); + + testCommentModel = const CommentModel( + data: [], + links: Links(first: '', last: '', prev: null, next: null), + meta: Meta( + currentPage: 1, + from: null, + lastPage: 1, + links: [], + path: null, + perPage: 10, + to: null, + total: 0, + totalMinPrice: null, + totalMaxPrice: null, + ), + ); + }); + + tearDown(() async { + if (commentsCubit != null && !commentsCubit!.isClosed) { + await Future.delayed(const Duration(milliseconds: 100)); + commentsCubit!.close(); + commentsCubit = null; + } + }); + + test('начальное состояние - CommentsState', () { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + expect(commentsCubit!.state, const CommentsState()); + }); + + test('getComments - успешная загрузка комментариев для blogPost', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const postId = '1'; + + when(mockFeedRepository.getBlogPostComments(id: postId)) + .thenAnswer((_) async => testCommentModel); + + await commentsCubit!.getComments(postId, CommentSourceType.blogPost, true); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(commentsCubit!.state, isA()); + final loadedState = commentsCubit!.state as CommentsStateLoaded; + expect(loadedState.comment, testCommentModel); + verify(mockFeedRepository.getBlogPostComments(id: postId)).called(1); + }); + + test('getComments - успешная загрузка комментариев для diet', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const dietId = '1'; + + when(mockFeedRepository.getDietsComments(id: dietId)) + .thenAnswer((_) async => testCommentModel); + + await commentsCubit!.getComments(dietId, CommentSourceType.diet, true); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(commentsCubit!.state, isA()); + verify(mockFeedRepository.getDietsComments(id: dietId)).called(1); + }); + + test('getComments - успешная загрузка комментариев для recipe', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const recipeId = 'recipe-slug'; + + when(mockFeedRepository.getRecipesComments(id: recipeId)) + .thenAnswer((_) async => testCommentModel); + + await commentsCubit!.getComments(recipeId, CommentSourceType.recipe, true); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(commentsCubit!.state, isA()); + verify(mockFeedRepository.getRecipesComments(id: recipeId)).called(1); + }); + + test('getComments - успешная загрузка комментариев для plan', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const planSlug = 'plan-slug'; + + when(mockFeedRepository.getPlansComments(slug: planSlug)) + .thenAnswer((_) async => testCommentModel); + + await commentsCubit!.getComments(planSlug, CommentSourceType.plan, true); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(commentsCubit!.state, isA()); + verify(mockFeedRepository.getPlansComments(slug: planSlug)).called(1); + }); + + test('getComments - переход в состояние loading при первом запросе', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const postId = '1'; + + when(mockFeedRepository.getBlogPostComments(id: postId)) + .thenAnswer((_) async { + await Future.delayed(const Duration(milliseconds: 50)); + return testCommentModel; + }); + + final future = commentsCubit!.getComments(postId, CommentSourceType.blogPost, true); + await Future.delayed(const Duration(milliseconds: 10)); + + expect(commentsCubit!.state, const CommentsState.loading()); + await future; + }); + + test('getComments - обработка ошибки', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const postId = '1'; + + when(mockFeedRepository.getBlogPostComments(id: postId)) + .thenThrow(Exception('Ошибка загрузки')); + + await commentsCubit!.getComments(postId, CommentSourceType.blogPost, true); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(commentsCubit!.state, isA()); + final errorState = commentsCubit!.state as CommentsStateError; + expect(errorState.errorMessage, contains('Exception')); + }); + + test('sendComment - успешная отправка комментария для blogPost', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const postId = '1'; + const commentText = 'Тестовый комментарий'; + + // Устанавливаем начальное состояние + commentsCubit!.emit(CommentsState.loaded(comment: testCommentModel)); + + when(mockFeedRepository.sendBlogPostComment( + id: postId, + commentText: commentText, + parentCommentId: null, + )).thenAnswer((_) async => Future.value()); + + when(mockFeedRepository.getBlogPostComments(id: postId)) + .thenAnswer((_) async => testCommentModel); + + await commentsCubit!.sendComment( + id: postId, + commentText: commentText, + commentSourceType: CommentSourceType.blogPost, + ); + + verify(mockFeedRepository.sendBlogPostComment( + id: postId, + commentText: commentText, + parentCommentId: null, + )).called(1); + verify(mockFeedRepository.getBlogPostComments(id: postId)).called(1); + }); + + test('sendComment - обработка ошибки при отправке', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const postId = '1'; + const commentText = 'Тестовый комментарий'; + + commentsCubit!.emit(CommentsState.loaded(comment: testCommentModel)); + + when(mockFeedRepository.sendBlogPostComment( + id: postId, + commentText: commentText, + parentCommentId: null, + )).thenThrow(Exception('Ошибка отправки')); + + await commentsCubit!.sendComment( + id: postId, + commentText: commentText, + commentSourceType: CommentSourceType.blogPost, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(commentsCubit!.state, isA()); + }); + + test('deleteComment - успешное удаление комментария', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const commentId = 1; + + final commentWithData = testCommentModel.copyWith( + data: [ + Comment( + id: commentId, + body: 'Комментарий для удаления', + authorName: 'Автор', + authorSlug: 'author-slug', + authorProfileIcon: 'https://example.com/photo.jpg', + createdAt: DateTime.now(), + childrenComments: [], + ), + ], + ); + + commentsCubit!.emit(CommentsState.loaded(comment: commentWithData)); + + when(mockCommentsRepository.deleteComment(id: commentId)) + .thenAnswer((_) async => Future.value()); + + final result = await commentsCubit!.deleteComment(id: commentId); + + expect(result, true); + expect(commentsCubit!.state, isA()); + final loadedState = commentsCubit!.state as CommentsStateLoaded; + expect(loadedState.comment.data, isEmpty); + verify(mockCommentsRepository.deleteComment(id: commentId)).called(1); + }); + + test('deleteComment - возвращает false если состояние не loaded', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const commentId = 1; + + commentsCubit!.emit(const CommentsState()); + + final result = await commentsCubit!.deleteComment(id: commentId); + + expect(result, false); + verifyNever(mockCommentsRepository.deleteComment(id: commentId)); + }); + + test('deleteComment - обработка ошибки при удалении', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const commentId = 1; + + final commentWithData = testCommentModel.copyWith( + data: [ + Comment( + id: commentId, + body: 'Комментарий', + authorName: 'Автор', + authorSlug: 'author-slug', + authorProfileIcon: 'https://example.com/photo.jpg', + createdAt: DateTime.now(), + childrenComments: [], + ), + ], + ); + + commentsCubit!.emit(CommentsState.loaded(comment: commentWithData)); + + when(mockCommentsRepository.deleteComment(id: commentId)) + .thenThrow(Exception('Ошибка удаления')); + + final result = await commentsCubit!.deleteComment(id: commentId); + + expect(result, false); + // Состояние должно вернуться к исходному + final loadedState = commentsCubit!.state as CommentsStateLoaded; + expect(loadedState.comment.data.length, 1); + }); + + test('updateComment - успешное обновление комментария', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const commentId = 1; + const newBody = 'Обновлённый комментарий'; + + final commentWithData = testCommentModel.copyWith( + data: [ + Comment( + id: commentId, + body: 'Старый комментарий', + authorName: 'Автор', + authorSlug: 'author-slug', + authorProfileIcon: 'https://example.com/photo.jpg', + createdAt: DateTime.now(), + childrenComments: [], + ), + ], + ); + + commentsCubit!.emit(CommentsState.loaded(comment: commentWithData)); + + when(mockCommentsRepository.updateComment(id: commentId, body: newBody)) + .thenAnswer((_) async => Future.value()); + + final result = await commentsCubit!.updateComment(id: commentId, body: newBody); + + expect(result, true); + expect(commentsCubit!.state, isA()); + final loadedState = commentsCubit!.state as CommentsStateLoaded; + expect(loadedState.comment.data.first.body, newBody); + verify(mockCommentsRepository.updateComment(id: commentId, body: newBody)).called(1); + }); + + test('updateComment - обработка ошибки при обновлении', () async { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const commentId = 1; + const newBody = 'Обновлённый комментарий'; + const oldBody = 'Старый комментарий'; + + final commentWithData = testCommentModel.copyWith( + data: [ + Comment( + id: commentId, + body: oldBody, + authorName: 'Автор', + authorSlug: 'author-slug', + authorProfileIcon: 'https://example.com/photo.jpg', + createdAt: DateTime.now(), + childrenComments: [], + ), + ], + ); + + commentsCubit!.emit(CommentsState.loaded(comment: commentWithData)); + + when(mockCommentsRepository.updateComment(id: commentId, body: newBody)) + .thenThrow(Exception('Ошибка обновления')); + + final result = await commentsCubit!.updateComment(id: commentId, body: newBody); + + expect(result, false); + // Состояние должно вернуться к исходному + final loadedState = commentsCubit!.state as CommentsStateLoaded; + expect(loadedState.comment.data.first.body, oldBody); + }); + + test('setReplyId - устанавливает ID ответа', () { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + const replyId = 5; + + commentsCubit!.emit(CommentsState.loaded(comment: testCommentModel)); + + commentsCubit!.setReplyId(replyId); + + expect(commentsCubit!.state, isA()); + final loadedState = commentsCubit!.state as CommentsStateLoaded; + expect(loadedState.replyId, replyId); + }); + + test('setReplyId - сбрасывает ID ответа', () { + commentsCubit = CommentsCubit( + feedRepository: mockFeedRepository, + commentsRepository: mockCommentsRepository, + ); + + commentsCubit!.emit(CommentsState.loaded(comment: testCommentModel, replyId: 5)); + + commentsCubit!.setReplyId(null); + + expect(commentsCubit!.state, isA()); + final loadedState = commentsCubit!.state as CommentsStateLoaded; + expect(loadedState.replyId, isNull); + }); + }); +} + diff --git a/test/core/comments/models/comment_update_model_test.dart b/test/core/comments/models/comment_update_model_test.dart new file mode 100644 index 00000000..d4e19f02 --- /dev/null +++ b/test/core/comments/models/comment_update_model_test.dart @@ -0,0 +1,36 @@ +import 'package:eatvio_app/core/comments/models/comment_update_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('CommentUpdateModel', () { + test('создание модели через конструктор', () { + final model = CommentUpdateModel(body: 'Обновлённый текст комментария'); + + expect(model.body, 'Обновлённый текст комментария'); + }); + + test('создание модели из JSON', () { + final json = {'body': 'Текст комментария'}; + final model = CommentUpdateModel.fromJson(json); + + expect(model.body, 'Текст комментария'); + }); + + test('преобразование модели в JSON', () { + final model = CommentUpdateModel(body: 'Текст комментария'); + final json = model.toJson(); + + expect(json['body'], 'Текст комментария'); + }); + + test('равенство моделей', () { + final model1 = CommentUpdateModel(body: 'Текст комментария'); + final model2 = CommentUpdateModel(body: 'Текст комментария'); + final model3 = CommentUpdateModel(body: 'Другой текст'); + + expect(model1, equals(model2)); + expect(model1, isNot(equals(model3))); + }); + }); +} + diff --git a/test/core/comments/repositories/comments_repository_test.dart b/test/core/comments/repositories/comments_repository_test.dart new file mode 100644 index 00000000..6b984404 --- /dev/null +++ b/test/core/comments/repositories/comments_repository_test.dart @@ -0,0 +1,80 @@ +import 'package:eatvio_app/core/comments/models/comment_update_model.dart'; +import 'package:eatvio_app/core/comments/repositories/comments_repository.dart'; +import 'package:eatvio_app/core/comments/services/comments_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'comments_repository_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('CommentsRepository', () { + late CommentsRepository commentsRepository; + late MockCommentsService mockCommentsService; + + setUp(() { + mockCommentsService = MockCommentsService(); + commentsRepository = CommentsRepository(service: mockCommentsService); + }); + + test('deleteComment - успешное удаление комментария', () async { + const commentId = 1; + + when(mockCommentsService.deleteComment(commentId)) + .thenAnswer((_) async => Future.value()); + + await commentsRepository.deleteComment(id: commentId); + + verify(mockCommentsService.deleteComment(commentId)).called(1); + }); + + test('deleteComment - пробрасывает исключение', () async { + const commentId = 1; + + when(mockCommentsService.deleteComment(commentId)) + .thenThrow(Exception('Ошибка удаления')); + + expect( + () => commentsRepository.deleteComment(id: commentId), + throwsException, + ); + }); + + test('updateComment - успешное обновление комментария', () async { + const commentId = 1; + const newBody = 'Обновлённый текст комментария'; + final updateModel = CommentUpdateModel(body: newBody); + + when(mockCommentsService.updateComment(commentId, updateModel)) + .thenAnswer((_) async => Future.value()); + + await commentsRepository.updateComment(id: commentId, body: newBody); + + verify(mockCommentsService.updateComment( + commentId, + argThat( + predicate( + (m) => m.body == newBody, + ), + ), + )).called(1); + }); + + test('updateComment - пробрасывает исключение', () async { + const commentId = 1; + const newBody = 'Обновлённый текст'; + + when(mockCommentsService.updateComment( + commentId, + any, + )).thenThrow(Exception('Ошибка обновления')); + + expect( + () => commentsRepository.updateComment(id: commentId, body: newBody), + throwsException, + ); + }); + }); +} + diff --git a/test/core/cubit/base_cubit_test.dart b/test/core/cubit/base_cubit_test.dart new file mode 100644 index 00000000..52b581fb --- /dev/null +++ b/test/core/cubit/base_cubit_test.dart @@ -0,0 +1,73 @@ +import 'package:eatvio_app/core/cubit/base_cubit.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// Простой тестовый cubit для проверки BaseCubit +class TestState { + final String? value; + TestState({this.value}); +} + +class TestCubit extends BaseCubit { + TestCubit() : super(TestState()); + + void testHandleError(Object error, [StackTrace? stackTrace]) { + handleError(error, stackTrace); + } + + Future testSafeExecute() async { + return await safeExecute(() async => 'success'); + } + + Future testSafeExecuteWithError() async { + return await safeExecute(() async => throw Exception('Test error')); + } + + Future testSafeExecuteWithState() async { + return await safeExecuteWithState( + () async => 'result', + loadingState: TestState(value: 'loading'), + successState: (result) => TestState(value: result), + errorState: (error) => TestState(value: 'error'), + ); + } +} + +void main() { + group('BaseCubit', () { + late TestCubit testCubit; + + setUp(() { + testCubit = TestCubit(); + }); + + tearDown(() async { + if (!testCubit.isClosed) { + await testCubit.close(); + } + }); + + test('handleError - обрабатывает ошибку без исключений', () { + expect(() => testCubit.testHandleError(Exception('Test error')), returnsNormally); + }); + + test('safeExecute - успешно выполняет операцию', () async { + final result = await testCubit.testSafeExecute(); + + expect(result, 'success'); + }); + + test('safeExecute - возвращает null при ошибке', () async { + final result = await testCubit.testSafeExecuteWithError(); + + expect(result, isNull); + }); + + test('safeExecuteWithState - устанавливает состояния правильно', () async { + final result = await testCubit.testSafeExecuteWithState(); + + expect(result, 'result'); + expect(testCubit.state.value, 'result'); + }); + }); +} + diff --git a/test/core/cubit/marketing/marketing_cubit_test.dart b/test/core/cubit/marketing/marketing_cubit_test.dart new file mode 100644 index 00000000..859fb4e4 --- /dev/null +++ b/test/core/cubit/marketing/marketing_cubit_test.dart @@ -0,0 +1,98 @@ +import 'package:eatvio_app/core/cubit/marketing/marketing_cubit.dart'; +import 'package:eatvio_app/core/cubit/marketing/marketing_cubit_state.dart'; +import 'package:eatvio_app/core/prefs.dart'; +import 'package:eatvio_app/core/prefs_keys.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'marketing_cubit_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('MarketingCubit', () { + late MarketingCubit marketingCubit; + late MockPrefs mockPrefs; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + mockPrefs = MockPrefs(); + marketingCubit = MarketingCubit(mockPrefs); + }); + + tearDown(() async { + if (!marketingCubit.isClosed) { + await marketingCubit.close(); + } + }); + + test('начальное состояние - MarketingCubitState', () { + expect(marketingCubit.state, const MarketingCubitState()); + }); + + test('checkRegistrationDate - возвращает false если registrationDate отсутствует', () async { + when(mockPrefs.getInt(PrefsKeys.registrationDate)).thenReturn(null); + + final result = await marketingCubit.checkRegistrationDate(); + + expect(result, isFalse); + verify(mockPrefs.getInt(PrefsKeys.registrationDate)).called(1); + }); + + test('checkRegistrationDate - возвращает false если маркетинговый bottom sheet уже был показан', () async { + when(mockPrefs.getInt(PrefsKeys.registrationDate)).thenReturn(DateTime.now().millisecondsSinceEpoch); + when(mockPrefs.getBool(PrefsKeys.marketingBottomSheetHasBeenShown)).thenReturn(true); + + final result = await marketingCubit.checkRegistrationDate(); + + expect(result, isFalse); + verify(mockPrefs.getInt(PrefsKeys.registrationDate)).called(1); + verify(mockPrefs.getBool(PrefsKeys.marketingBottomSheetHasBeenShown)).called(1); + }); + + test('checkRegistrationDate - возвращает false если прошло менее 14 дней', () async { + final registrationDate = DateTime.now().subtract(const Duration(days: 10)); + when(mockPrefs.getInt(PrefsKeys.registrationDate)).thenReturn(registrationDate.millisecondsSinceEpoch); + when(mockPrefs.getBool(PrefsKeys.marketingBottomSheetHasBeenShown)).thenReturn(false); + + final result = await marketingCubit.checkRegistrationDate(); + + expect(result, isFalse); + verify(mockPrefs.getInt(PrefsKeys.registrationDate)).called(1); + verify(mockPrefs.getBool(PrefsKeys.marketingBottomSheetHasBeenShown)).called(1); + verifyNever(mockPrefs.setBool(any, any)); + }); + + test('checkRegistrationDate - возвращает true если прошло 14 дней или больше', () async { + final registrationDate = DateTime.now().subtract(const Duration(days: 14)); + when(mockPrefs.getInt(PrefsKeys.registrationDate)).thenReturn(registrationDate.millisecondsSinceEpoch); + when(mockPrefs.getBool(PrefsKeys.marketingBottomSheetHasBeenShown)).thenReturn(false); + when(mockPrefs.setBool(PrefsKeys.marketingBottomSheetHasBeenShown, true)).thenAnswer((_) async => Future.value()); + + final result = await marketingCubit.checkRegistrationDate(); + + expect(result, isTrue); + verify(mockPrefs.getInt(PrefsKeys.registrationDate)).called(1); + verify(mockPrefs.getBool(PrefsKeys.marketingBottomSheetHasBeenShown)).called(1); + verify(mockPrefs.setBool(PrefsKeys.marketingBottomSheetHasBeenShown, true)).called(1); + }); + + test('checkRegistrationDate - устанавливает флаг после показа bottom sheet', () async { + final registrationDate = DateTime.now().subtract(const Duration(days: 15)); + when(mockPrefs.getInt(PrefsKeys.registrationDate)).thenReturn(registrationDate.millisecondsSinceEpoch); + when(mockPrefs.getBool(PrefsKeys.marketingBottomSheetHasBeenShown)).thenReturn(false); + when(mockPrefs.setBool(PrefsKeys.marketingBottomSheetHasBeenShown, true)).thenAnswer((_) async => Future.value()); + + await marketingCubit.checkRegistrationDate(); + + verify(mockPrefs.setBool(PrefsKeys.marketingBottomSheetHasBeenShown, true)).called(1); + }); + + test('checkRegistrationDate - пробрасывает исключение', () async { + when(mockPrefs.getInt(PrefsKeys.registrationDate)).thenThrow(Exception('Ошибка чтения')); + + expect(() => marketingCubit.checkRegistrationDate(), throwsException); + }); + }); +} diff --git a/test/core/internet_connection_cubit/internet_connection_cubit_test.dart b/test/core/internet_connection_cubit/internet_connection_cubit_test.dart new file mode 100644 index 00000000..946eefd2 --- /dev/null +++ b/test/core/internet_connection_cubit/internet_connection_cubit_test.dart @@ -0,0 +1,104 @@ +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:flutter/services.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('InternetConnectionCubit', () { + late InternetConnectionCubit cubit; + const MethodChannel connectivityChannel = MethodChannel('dev.fluttercommunity.plus/connectivity'); + + setUp(() async { + // Инициализируем dotenv для тестов + dotenv.loadFromString(envString: ''' +BASE_URL=https://api.example.com +DEV_BASE_URL=https://dev-api.example.com +GOOGLE_CHECK_URL=https://www.google.com +YANDEX_CHECK_URL=https://ya.ru +'''); + + // Мокируем MethodChannel для connectivity + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + connectivityChannel, + (MethodCall methodCall) async { + if (methodCall.method == 'check') { + return ['wifi']; // ConnectivityResult.wifi как строка + } + if (methodCall.method == 'onConnectivityChanged') { + return null; + } + return null; + }, + ); + }); + + tearDown(() async { + // Очищаем моки + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + connectivityChannel, + null, + ); + if (!cubit.isClosed) { + await cubit.close(); + } + }); + + test('начальное состояние - isInternetAvailable = true', () async { + cubit = InternetConnectionCubit(); + + // Ждем завершения асинхронных операций, запущенных в конструкторе + await Future.delayed(const Duration(milliseconds: 500)); + + expect(cubit.state.isInternetAvailable, isTrue); + }); + + test('checkConnection - успешная проверка с интернетом', () async { + cubit = InternetConnectionCubit(); + + // Ждем завершения асинхронных операций, запущенных в конструкторе + await Future.delayed(const Duration(milliseconds: 500)); + + // Проверяем, что метод checkConnection не выбрасывает исключений + await cubit.checkConnection(); + + // Ждем завершения обновления состояния + await Future.delayed(const Duration(milliseconds: 500)); + + // Состояние должно быть определено (true или false в зависимости от реального состояния) + expect(cubit.state, isA()); + }); + + test('checkConnection - обработка PlatformException', () async { + // Этот тест сложно выполнить без реального мока Connectivity, + // так как Connectivity создается внутри cubit + // Оставим базовую проверку, что метод не падает + cubit = InternetConnectionCubit(); + + // Ждем завершения асинхронных операций, запущенных в конструкторе + await Future.delayed(const Duration(milliseconds: 500)); + + // Просто проверяем, что метод выполняется без ошибок + await cubit.checkConnection(); + + // Ждем завершения обновления состояния + await Future.delayed(const Duration(milliseconds: 500)); + + expect(cubit.state, isA()); + }); + + test('close - корректно закрывает cubit и освобождает ресурсы', () async { + cubit = InternetConnectionCubit(); + + // Ждем завершения асинхронных операций, запущенных в конструкторе + await Future.delayed(const Duration(milliseconds: 500)); + + await cubit.close(); + + expect(cubit.isClosed, isTrue); + }); + }); +} + diff --git a/test/core/prefs_test.dart b/test/core/prefs_test.dart new file mode 100644 index 00000000..a9166f70 --- /dev/null +++ b/test/core/prefs_test.dart @@ -0,0 +1,85 @@ +import 'package:eatvio_app/core/prefs.dart'; +import 'package:eatvio_app/core/prefs_keys.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + group('Prefs', () { + late Prefs prefs; + late SharedPreferences sharedPreferences; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + sharedPreferences = await SharedPreferences.getInstance(); + prefs = Prefs(sharedPreferences); + }); + + test('setString и getString - сохранение и получение строки', () async { + await prefs.setString(PrefsKeys.registrationDate, '2024-01-01'); + + final value = prefs.getString(PrefsKeys.registrationDate); + expect(value, '2024-01-01'); + }); + + test('getString - возвращает null если значение не установлено', () { + final value = prefs.getString(PrefsKeys.registrationDate); + expect(value, isNull); + }); + + test('setInt и getInt - сохранение и получение числа', () async { + // Используем registrationDate как строку, но можно протестировать setInt с любым ключом + // Для теста используем setString, так как в PrefsKeys нет числовых ключей + await prefs.setString(PrefsKeys.registrationDate, '42'); + + final value = prefs.getString(PrefsKeys.registrationDate); + expect(value, '42'); + }); + + test('getInt - возвращает null если значение не установлено', () { + // Тестируем getInt с любым ключом + final value = prefs.getInt(PrefsKeys.registrationDate); + expect(value, isNull); + }); + + test('setBool и getBool - сохранение и получение булева значения', () async { + await prefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true); + + final value = prefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent); + expect(value, isTrue); + }); + + test('getBool - возвращает null если значение не установлено', () { + final value = prefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent); + expect(value, isNull); + }); + + test('remove - удаление значения', () async { + await prefs.setString(PrefsKeys.registrationDate, 'test_value'); + await prefs.remove(PrefsKeys.registrationDate); + + final value = prefs.getString(PrefsKeys.registrationDate); + expect(value, isNull); + }); + + test('clear - очистка всех значений', () async { + await prefs.setString(PrefsKeys.registrationDate, 'test_value'); + await prefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true); + await prefs.setBool(PrefsKeys.welcomeScreenWasShowed, false); + + await prefs.clear(); + + expect(prefs.getString(PrefsKeys.registrationDate), isNull); + expect(prefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent), isNull); + expect(prefs.getBool(PrefsKeys.welcomeScreenWasShowed), isNull); + }); + + test('перезапись значения', () async { + await prefs.setString(PrefsKeys.registrationDate, 'old_value'); + await prefs.setString(PrefsKeys.registrationDate, 'new_value'); + + final value = prefs.getString(PrefsKeys.registrationDate); + expect(value, 'new_value'); + }); + }); +} + diff --git a/test/core/token_storage_test.dart b/test/core/token_storage_test.dart new file mode 100644 index 00000000..d839ba85 --- /dev/null +++ b/test/core/token_storage_test.dart @@ -0,0 +1,112 @@ +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + group('TokenStorage', () { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + }); + + test('haveTokenInStorage - возвращает false если токен отсутствует', () async { + final result = await TokenStorage.haveTokenInStorage(); + + expect(result, isFalse); + }); + + test('haveTokenInStorage - возвращает true если токен присутствует', () async { + SharedPreferences.setMockInitialValues({'token': 'test_token_123'}); + + final result = await TokenStorage.haveTokenInStorage(); + + expect(result, isTrue); + }); + + test('getTokenFromStorage - возвращает null если токен отсутствует', () async { + final result = await TokenStorage.getTokenFromStorage(); + + expect(result, isNull); + }); + + test('getTokenFromStorage - возвращает токен если он присутствует', () async { + const testToken = 'test_token_123'; + SharedPreferences.setMockInitialValues({'token': testToken}); + + final result = await TokenStorage.getTokenFromStorage(); + + expect(result, testToken); + }); + + test('saveTokenInStorage - сохраняет токен', () async { + const testToken = 'new_token_456'; + + await TokenStorage.saveTokenInStorage(testToken); + + final savedToken = await TokenStorage.getTokenFromStorage(); + expect(savedToken, testToken); + }); + + test('removeTokenInStorage - удаляет токен', () async { + SharedPreferences.setMockInitialValues({'token': 'test_token_123'}); + + await TokenStorage.removeTokenInStorage(); + + final result = await TokenStorage.getTokenFromStorage(); + expect(result, isNull); + }); + }); + + group('SocketIdStorage', () { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + }); + + test('haveSocketIdInStorage - возвращает false если socketId отсутствует', () async { + final result = await SocketIdStorage.haveSocketIdInStorage(); + + expect(result, isFalse); + }); + + test('haveSocketIdInStorage - возвращает true если socketId присутствует', () async { + SharedPreferences.setMockInitialValues({'socketId': 'socket_id_123'}); + + final result = await SocketIdStorage.haveSocketIdInStorage(); + + expect(result, isTrue); + }); + + test('getSocketIdFromStorage - возвращает null если socketId отсутствует', () async { + final result = await SocketIdStorage.getSocketIdFromStorage(); + + expect(result, isNull); + }); + + test('getSocketIdFromStorage - возвращает socketId если он присутствует', () async { + const testSocketId = 'socket_id_123'; + SharedPreferences.setMockInitialValues({'socketId': testSocketId}); + + final result = await SocketIdStorage.getSocketIdFromStorage(); + + expect(result, testSocketId); + }); + + test('saveSocketIdInStorage - сохраняет socketId', () async { + const testSocketId = 'new_socket_id_456'; + + await SocketIdStorage.saveSocketIdInStorage(testSocketId); + + final savedSocketId = await SocketIdStorage.getSocketIdFromStorage(); + expect(savedSocketId, testSocketId); + }); + + test('removeSocketIdInStorage - удаляет socketId', () async { + SharedPreferences.setMockInitialValues({'socketId': 'socket_id_123'}); + + await SocketIdStorage.removeSocketIdInStorage(); + + final result = await SocketIdStorage.getSocketIdFromStorage(); + expect(result, isNull); + }); + }); +} + diff --git a/test/core/utils/toasts_test.dart b/test/core/utils/toasts_test.dart new file mode 100644 index 00000000..635cc253 --- /dev/null +++ b/test/core/utils/toasts_test.dart @@ -0,0 +1,59 @@ +import 'package:eatvio_app/core/utils/toasts.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('Toasts', () { + setUp(() { + // Mock Fluttertoast plugin + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + return null; + }, + ); + }); + + tearDown(() { + // Clear mock handlers + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); + }); + + test('showInfoToast - вызывает Fluttertoast без ошибок', () { + expect(() => showInfoToast('Информационное сообщение'), returnsNormally); + }); + + test('showErrorToast - вызывает Fluttertoast без ошибок', () { + expect(() => showErrorToast('Сообщение об ошибке'), returnsNormally); + }); + + test('showSuccessToast - вызывает Fluttertoast без ошибок', () { + expect(() => showSuccessToast('Успешное сообщение'), returnsNormally); + }); + + test('showInternetConnectionToast - вызывает Fluttertoast без ошибок', () { + expect(() => showInternetConnectionToast(), returnsNormally); + }); + + test('showInfoToast - работает с пустой строкой', () { + expect(() => showInfoToast(''), returnsNormally); + }); + + test('showErrorToast - работает с длинным сообщением', () { + final longMessage = 'Очень длинное сообщение об ошибке ' * 10; + expect(() => showErrorToast(longMessage), returnsNormally); + }); + + test('showSuccessToast - работает с различными сообщениями', () { + expect(() => showSuccessToast('Операция выполнена успешно'), returnsNormally); + expect(() => showSuccessToast('Данные сохранены'), returnsNormally); + expect(() => showSuccessToast('Загрузка завершена'), returnsNormally); + }); + }); +} + diff --git a/test/core/views/cubit/views_cubit_test.dart b/test/core/views/cubit/views_cubit_test.dart new file mode 100644 index 00000000..512a589a --- /dev/null +++ b/test/core/views/cubit/views_cubit_test.dart @@ -0,0 +1,154 @@ +import 'package:eatvio_app/core/views/cubit/views_cubit.dart'; +import 'package:eatvio_app/core/views/cubit/views_state.dart'; +import 'package:eatvio_app/core/views/repository/views_repository.dart'; +import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'views_cubit_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('ViewsCubit', () { + late ViewsCubit cubit; + late MockViewsRepository mockViewsRepository; + + setUp(() { + mockViewsRepository = MockViewsRepository(); + cubit = ViewsCubit(viewsRepository: mockViewsRepository); + }); + + tearDown(() async { + if (!cubit.isClosed) { + await cubit.close(); + } + }); + + test('начальное состояние - ViewsCubitState', () { + expect(cubit.state, isA()); + }); + + test('handleVisibility - добавляет ID при visibleFraction >= 0.5', () async { + when(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))).thenAnswer((_) async => Future.value()); + + cubit.handleVisibility(visibleFraction: 0.6, id: 1, type: ViewableContentType.posts); + + // Ждем выполнения таймера (1 секунда) + await Future.delayed(const Duration(milliseconds: 1100)); + + expect(cubit.postsIds, contains(1)); + }); + + test('handleVisibility - не добавляет ID при visibleFraction < 0.5', () async { + cubit.handleVisibility(visibleFraction: 0.3, id: 1, type: ViewableContentType.posts); + + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.postsIds, isEmpty); + }); + + test('handleVisibility - отменяет таймер при уменьшении visibleFraction', () async { + when(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))).thenAnswer((_) async => Future.value()); + + // Сначала видимость >= 0.5 + cubit.handleVisibility(visibleFraction: 0.6, id: 1, type: ViewableContentType.posts); + + await Future.delayed(const Duration(milliseconds: 500)); + + // Затем видимость < 0.5 + cubit.handleVisibility(visibleFraction: 0.3, id: 1, type: ViewableContentType.posts); + + await Future.delayed(const Duration(milliseconds: 700)); + + // ID не должен быть добавлен, так как таймер был отменен + expect(cubit.postsIds, isEmpty); + }); + + test('handleVisibility - не добавляет уже отправленный ID', () async { + when(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))).thenAnswer((_) async => Future.value()); + + // Добавляем и отправляем ID + cubit.handleVisibility(visibleFraction: 0.6, id: 1, type: ViewableContentType.posts); + + await Future.delayed(const Duration(milliseconds: 1100)); + await Future.delayed(const Duration(milliseconds: 4100)); // Ждем debounce и отправку + + // Пытаемся добавить тот же ID снова + cubit.handleVisibility(visibleFraction: 0.6, id: 1, type: ViewableContentType.posts); + + await Future.delayed(const Duration(milliseconds: 100)); + + // Таймер не должен быть создан, так как ID уже отправлен + expect(cubit.postsIds, isEmpty); + }); + + test('handleVisibility - работает для разных типов контента', () async { + when(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))).thenAnswer((_) async => Future.value()); + + cubit.handleVisibility(visibleFraction: 0.6, id: 1, type: ViewableContentType.posts); + cubit.handleVisibility(visibleFraction: 0.6, id: 2, type: ViewableContentType.plans); + cubit.handleVisibility(visibleFraction: 0.6, id: 3, type: ViewableContentType.diets); + cubit.handleVisibility(visibleFraction: 0.6, id: 4, type: ViewableContentType.recipes); + + await Future.delayed(const Duration(milliseconds: 1100)); + + expect(cubit.postsIds, contains(1)); + expect(cubit.plansIds, contains(2)); + expect(cubit.dietsIds, contains(3)); + expect(cubit.recipesIds, contains(4)); + }); + + test('_sendViews - отправляет просмотры через repository', () async { + when(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))).thenAnswer((_) async => Future.value()); + + // Добавляем ID для разных типов + cubit.handleVisibility(visibleFraction: 0.6, id: 1, type: ViewableContentType.posts); + cubit.handleVisibility(visibleFraction: 0.6, id: 2, type: ViewableContentType.plans); + + await Future.delayed(const Duration(milliseconds: 1100)); + await Future.delayed(const Duration(milliseconds: 4100)); // Ждем debounce и отправку + + // Проверяем, что repository был вызван минимум 2 раза (для posts и plans) + verify(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))).called(greaterThanOrEqualTo(2)); + }); + + test('close - отправляет оставшиеся просмотры и освобождает ресурсы', () async { + when(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))).thenAnswer((_) async => Future.value()); + + // Добавляем ID + cubit.handleVisibility(visibleFraction: 0.6, id: 1, type: ViewableContentType.posts); + await Future.delayed(const Duration(milliseconds: 1100)); + + // Очищаем предыдущие взаимодействия перед проверкой + clearInteractions(mockViewsRepository); + + // Закрываем cubit + await cubit.close(); + + // Проверяем, что repository был вызван для отправки оставшихся просмотров + verify(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))).called(greaterThanOrEqualTo(1)); + expect(cubit.isClosed, isTrue); + }); + + test('_sendViews - не отправляет уже отправленные ID', () async { + when(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))).thenAnswer((_) async => Future.value()); + + // Добавляем и отправляем ID + cubit.handleVisibility(visibleFraction: 0.6, id: 1, type: ViewableContentType.posts); + await Future.delayed(const Duration(milliseconds: 1100)); + await Future.delayed(const Duration(milliseconds: 4100)); + + // Очищаем моки + clearInteractions(mockViewsRepository); + + // Закрываем cubit + await cubit.close(); + + // Repository не должен быть вызван, так как все ID уже отправлены + verifyNever(mockViewsRepository.viewContent(viewModel: anyNamed('viewModel'))); + }); + }); +} diff --git a/test/core/views/repository/views_repository_test.dart b/test/core/views/repository/views_repository_test.dart new file mode 100644 index 00000000..11a5748c --- /dev/null +++ b/test/core/views/repository/views_repository_test.dart @@ -0,0 +1,71 @@ +import 'package:eatvio_app/core/views/repository/views_repository.dart'; +import 'package:eatvio_app/core/views/service/views_service.dart'; +import 'package:eatvio_app/features/feed/models/view_model.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'views_repository_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('ViewsRepository', () { + late ViewsRepository viewsRepository; + late MockViewsService mockViewsService; + + setUp(() { + mockViewsService = MockViewsService(); + viewsRepository = ViewsRepository(viewsService: mockViewsService); + }); + + test('viewContent - успешная отправка просмотров', () async { + final viewModel = ViewModel( + type: 'blog_posts', + ids: [1, 2, 3], + ); + + when(mockViewsService.viewContent(viewModel: viewModel)) + .thenAnswer((_) async => Future.value()); + + await viewsRepository.viewContent(viewModel: viewModel); + + verify(mockViewsService.viewContent(viewModel: viewModel)).called(1); + }); + + test('viewContent - пробрасывает исключение', () async { + final viewModel = ViewModel( + type: 'blog_posts', + ids: [1, 2, 3], + ); + + when(mockViewsService.viewContent(viewModel: viewModel)) + .thenThrow(Exception('Ошибка отправки')); + + expect( + () => viewsRepository.viewContent(viewModel: viewModel), + throwsException, + ); + }); + + test('viewContent - работает с разными типами контента', () async { + final postsModel = ViewModel(type: 'blog_posts', ids: [1]); + final plansModel = ViewModel(type: 'plans', ids: [2]); + final dietsModel = ViewModel(type: 'diets', ids: [3]); + final recipesModel = ViewModel(type: 'recipes', ids: [4]); + + when(mockViewsService.viewContent(viewModel: anyNamed('viewModel'))) + .thenAnswer((_) async => Future.value()); + + await viewsRepository.viewContent(viewModel: postsModel); + await viewsRepository.viewContent(viewModel: plansModel); + await viewsRepository.viewContent(viewModel: dietsModel); + await viewsRepository.viewContent(viewModel: recipesModel); + + verify(mockViewsService.viewContent(viewModel: postsModel)).called(1); + verify(mockViewsService.viewContent(viewModel: plansModel)).called(1); + verify(mockViewsService.viewContent(viewModel: dietsModel)).called(1); + verify(mockViewsService.viewContent(viewModel: recipesModel)).called(1); + }); + }); +} + diff --git a/test/features/auth/models/credentials_model_test.dart b/test/features/auth/models/credentials_model_test.dart new file mode 100644 index 00000000..8ecabe61 --- /dev/null +++ b/test/features/auth/models/credentials_model_test.dart @@ -0,0 +1,62 @@ +import 'package:eatvio_app/features/auth/models/credentials_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../../fixtures/fixture_reader.dart'; + +void main() { + group('CredentialsModel', () { + late Map credentialsFixture; + + setUp(() { + credentialsFixture = FixtureReader.readAsMap('auth/login_credentials.json'); + }); + + test('создание модели из JSON', () { + final model = CredentialsModel.fromJson(credentialsFixture); + + expect(model.email, credentialsFixture['email']); + expect(model.password, credentialsFixture['password']); + }); + + test('создание модели через конструктор', () { + const model = CredentialsModel( + email: 'test@example.com', + password: 'password123', + ); + + expect(model.email, 'test@example.com'); + expect(model.password, 'password123'); + }); + + test('преобразование модели в JSON', () { + const model = CredentialsModel( + email: 'test@example.com', + password: 'password123', + ); + + final json = model.toJson(); + + expect(json['email'], 'test@example.com'); + expect(json['password'], 'password123'); + }); + + test('равенство моделей', () { + const model1 = CredentialsModel( + email: 'test@example.com', + password: 'password123', + ); + const model2 = CredentialsModel( + email: 'test@example.com', + password: 'password123', + ); + const model3 = CredentialsModel( + email: 'other@example.com', + password: 'password123', + ); + + expect(model1, equals(model2)); + expect(model1, isNot(equals(model3))); + }); + }); +} + diff --git a/test/features/auth/models/oauth_login_request_test.dart b/test/features/auth/models/oauth_login_request_test.dart new file mode 100644 index 00000000..32b362c7 --- /dev/null +++ b/test/features/auth/models/oauth_login_request_test.dart @@ -0,0 +1,78 @@ +import 'package:eatvio_app/features/auth/models/oauth_login_request.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../../fixtures/fixture_reader.dart'; + +void main() { + group('OAuthLoginRequest', () { + late Map oauthSignInFixture; + + setUp(() { + oauthSignInFixture = FixtureReader.readAsMap('auth/oauth_signin_request.json'); + }); + + test('создание модели из JSON', () { + final model = OAuthLoginRequest.fromJson(oauthSignInFixture); + + expect(model.provider, oauthSignInFixture['provider']); + expect(model.accessToken, oauthSignInFixture['access_token']); + expect(model.refreshToken, oauthSignInFixture['refresh_token']); + expect(model.clientId, oauthSignInFixture['client_id']); + }); + + test('создание модели через конструктор', () { + const model = OAuthLoginRequest( + provider: 'vk', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + clientId: 'client_id_123', + ); + + expect(model.provider, 'vk'); + expect(model.accessToken, 'access_token_123'); + expect(model.refreshToken, 'refresh_token_123'); + expect(model.clientId, 'client_id_123'); + }); + + test('преобразование модели в JSON с правильными ключами', () { + const model = OAuthLoginRequest( + provider: 'vk', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + clientId: 'client_id_123', + ); + + final json = model.toJson(); + + expect(json['provider'], 'vk'); + expect(json['access_token'], 'access_token_123'); + expect(json['refresh_token'], 'refresh_token_123'); + expect(json['client_id'], 'client_id_123'); + }); + + test('равенство моделей', () { + const model1 = OAuthLoginRequest( + provider: 'vk', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + clientId: 'client_id_123', + ); + const model2 = OAuthLoginRequest( + provider: 'vk', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + clientId: 'client_id_123', + ); + const model3 = OAuthLoginRequest( + provider: 'google', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + clientId: 'client_id_123', + ); + + expect(model1, equals(model2)); + expect(model1, isNot(equals(model3))); + }); + }); +} + diff --git a/test/features/auth/models/oauth_model_test.dart b/test/features/auth/models/oauth_model_test.dart new file mode 100644 index 00000000..79673626 --- /dev/null +++ b/test/features/auth/models/oauth_model_test.dart @@ -0,0 +1,142 @@ +import 'package:eatvio_app/features/auth/models/oauth_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../../fixtures/fixture_reader.dart'; + +void main() { + group('OAuthModel', () { + late Map oauthSignUpFixture; + + setUp(() { + oauthSignUpFixture = FixtureReader.readAsMap('auth/oauth_signup_request.json'); + }); + + test('создание модели из JSON', () { + final model = OAuthModel.fromJson(oauthSignUpFixture); + + expect(model.provider, oauthSignUpFixture['provider']); + expect(model.accessToken, oauthSignUpFixture['access_token']); + expect(model.refreshToken, oauthSignUpFixture['refresh_token']); + expect(model.id, oauthSignUpFixture['id']); + expect(model.firstName, oauthSignUpFixture['first_name']); + expect(model.lastName, oauthSignUpFixture['last_name']); + expect(model.email, oauthSignUpFixture['email']); + expect(model.phone, oauthSignUpFixture['phone']); + expect(model.dateOfBirth, oauthSignUpFixture['date_of_birth']); + expect(model.gender, oauthSignUpFixture['gender']); + expect(model.weight, oauthSignUpFixture['weight']); + expect(model.height, oauthSignUpFixture['height']); + expect(model.clientId, oauthSignUpFixture['client_id']); + }); + + test('создание модели через конструктор', () { + const model = OAuthModel( + provider: 'vk', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + id: 'user_id_123', + firstName: 'Иван', + lastName: 'Иванов', + email: 'ivan@example.com', + phone: '+79001234567', + dateOfBirth: '1990-01-01', + gender: 'male', + weight: 75, + height: 180, + clientId: 'client_id_123', + ); + + expect(model.provider, 'vk'); + expect(model.email, 'ivan@example.com'); + expect(model.gender, 'male'); + expect(model.weight, 75); + expect(model.height, 180); + }); + + test('преобразование модели в JSON с правильными ключами', () { + const model = OAuthModel( + provider: 'vk', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + id: 'user_id_123', + firstName: 'Иван', + lastName: 'Иванов', + email: 'ivan@example.com', + phone: '+79001234567', + dateOfBirth: '1990-01-01', + gender: 'male', + weight: 75, + height: 180, + clientId: 'client_id_123', + ); + + final json = model.toJson(); + + expect(json['provider'], 'vk'); + expect(json['access_token'], 'access_token_123'); + expect(json['refresh_token'], 'refresh_token_123'); + expect(json['id'], 'user_id_123'); + expect(json['first_name'], 'Иван'); + expect(json['last_name'], 'Иванов'); + expect(json['email'], 'ivan@example.com'); + expect(json['phone'], '+79001234567'); + expect(json['date_of_birth'], '1990-01-01'); + expect(json['gender'], 'male'); + expect(json['weight'], 75); + expect(json['height'], 180); + expect(json['client_id'], 'client_id_123'); + }); + + test('равенство моделей', () { + const model1 = OAuthModel( + provider: 'vk', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + id: 'user_id_123', + firstName: 'Иван', + lastName: 'Иванов', + email: 'ivan@example.com', + phone: '+79001234567', + dateOfBirth: '1990-01-01', + gender: 'male', + weight: 75, + height: 180, + clientId: 'client_id_123', + ); + const model2 = OAuthModel( + provider: 'vk', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + id: 'user_id_123', + firstName: 'Иван', + lastName: 'Иванов', + email: 'ivan@example.com', + phone: '+79001234567', + dateOfBirth: '1990-01-01', + gender: 'male', + weight: 75, + height: 180, + clientId: 'client_id_123', + ); + const model3 = OAuthModel( + provider: 'google', + accessToken: 'access_token_123', + refreshToken: 'refresh_token_123', + id: 'user_id_123', + firstName: 'Иван', + lastName: 'Иванов', + email: 'ivan@example.com', + phone: '+79001234567', + dateOfBirth: '1990-01-01', + gender: 'male', + weight: 75, + height: 180, + clientId: 'client_id_123', + ); + + expect(model1, equals(model2)); + expect(model1, isNot(equals(model3))); + }); + }); +} + diff --git a/test/features/auth/presentation/bloc/auth_cubit_test.dart b/test/features/auth/presentation/bloc/auth_cubit_test.dart new file mode 100644 index 00000000..ecb53502 --- /dev/null +++ b/test/features/auth/presentation/bloc/auth_cubit_test.dart @@ -0,0 +1,153 @@ +import 'package:eatvio_app/features/auth/models/token_model.dart'; +import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart'; +import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_state.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../../../fixtures/doubles/auth_doubles.dart'; +import '../../../../fixtures/fixture_reader.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('AuthCubit', () { + AuthCubit? authCubit; + late FixtureAuthRepository authRepository; + late Map credentialsFixture; + + late TokenModel tokenFixture; + + setUp(() async { + tokenFixture = TokenModel.fromJson(FixtureReader.readAsMap('auth/token_response.json')); + credentialsFixture = FixtureReader.readAsMap('auth/login_credentials.json'); + authRepository = FixtureAuthRepository(tokenFixture: tokenFixture); + SharedPreferences.setMockInitialValues({}); + + // Mock Fluttertoast plugin + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + return null; + }, + ); + }); + + tearDown(() async { + if (authCubit != null && !authCubit!.isClosed) { + await Future.delayed(const Duration(milliseconds: 100)); + authCubit!.close(); + authCubit = null; + } + + // Clear mock handlers + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); + }); + + test('начальное состояние - AuthState', () { + authCubit = AuthCubit(authRepository: authRepository); + expect(authCubit!.state, const AuthState()); + }); + + test('getTokenByCredentials - успешная авторизация', () async { + authCubit = AuthCubit(authRepository: authRepository); + + final result = await authCubit!.getTokenByCredentials( + credentialsFixture['email'] as String, + credentialsFixture['password'] as String, + ); + + expect(result, true); + await Future.delayed(const Duration(milliseconds: 100)); + expect(authCubit!.state, isA()); + final loadedState = authCubit!.state as AuthStateLoaded; + expect(loadedState.token, tokenFixture.token); + expect( + authRepository.credentialPayloads.single, + credentialsFixture.map((key, value) => MapEntry(key, value.toString())), + ); + }); + + test('getTokenByCredentials - переход в состояние loading', () async { + authCubit = AuthCubit(authRepository: authRepository); + authRepository.responseDelay = const Duration(milliseconds: 50); + + final future = authCubit!.getTokenByCredentials( + credentialsFixture['email'] as String, + credentialsFixture['password'] as String, + ); + await Future.delayed(const Duration(milliseconds: 10)); + + expect(authCubit!.state, isA()); + await future; + }); + + test('getTokenByCredentials - обработка ошибки авторизации', () async { + authCubit = AuthCubit(authRepository: authRepository); + authRepository.error = Exception('Неверный адрес электронной почты или пароль'); + + final result = await authCubit!.getTokenByCredentials('wrong@example.com', 'wrongpassword'); + + expect(result, false); + await Future.delayed(const Duration(milliseconds: 100)); + expect(authCubit!.state, isA()); + final errorState = authCubit!.state as AuthStateError; + expect(errorState.errorMessage, contains('Exception')); + expect( + authRepository.credentialPayloads.single, + {'email': 'wrong@example.com', 'password': 'wrongpassword'}, + ); + }); + + test('getTokenByCredentials - обработка различных типов ошибок', () async { + authCubit = AuthCubit(authRepository: authRepository); + authRepository.error = const FormatException('Invalid credentials format'); + + final result = await authCubit!.getTokenByCredentials('invalid', 'pass'); + + expect(result, false); + await Future.delayed(const Duration(milliseconds: 100)); + expect(authCubit!.state, isA()); + final errorState = authCubit!.state as AuthStateError; + expect(errorState.errorMessage, contains('FormatException')); + }); + + test('getTokenByCredentials - проверка вызова с правильными параметрами', () async { + authCubit = AuthCubit(authRepository: authRepository); + + await authCubit!.getTokenByCredentials('user@test.com', 'securePassword123'); + + expect( + authRepository.credentialPayloads.single, + {'email': 'user@test.com', 'password': 'securePassword123'}, + ); + expect( + authRepository.credentialPayloads.where((call) => call['email'] == 'other@test.com'), + isEmpty, + ); + }); + + test('getTokenByCredentials - множественные вызовы', () async { + authCubit = AuthCubit(authRepository: authRepository); + + await authCubit!.getTokenByCredentials('first@test.com', 'password1'); + await Future.delayed(const Duration(milliseconds: 100)); + await authCubit!.getTokenByCredentials('second@test.com', 'password2'); + + expect(authRepository.credentialPayloads.length, 2); + expect( + authRepository.credentialPayloads, + [ + {'email': 'first@test.com', 'password': 'password1'}, + {'email': 'second@test.com', 'password': 'password2'}, + ], + ); + }); + }); +} + diff --git a/test/features/auth/presentation/bloc/oauth_cubit/oauth_cubit_test.dart b/test/features/auth/presentation/bloc/oauth_cubit/oauth_cubit_test.dart new file mode 100644 index 00000000..ea30de0c --- /dev/null +++ b/test/features/auth/presentation/bloc/oauth_cubit/oauth_cubit_test.dart @@ -0,0 +1,189 @@ +import 'package:eatvio_app/core/prefs.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/features/auth/models/token_model.dart'; +import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_cubit.dart'; +import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart'; +import 'package:eatvio_app/features/auth/repositories/auth_repository.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../../../../fixtures/fixture_reader.dart'; +import 'oauth_cubit_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec(), MockSpec()]) +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('OAuthCubit', () { + OAuthCubit? oauthCubit; + late MockAuthRepository mockAuthRepository; + late MockPrefs mockPrefs; + late TokenModel tokenFixture; + late Map signInRequestFixture; + late Map signUpRequestFixture; + + setUp(() async { + tokenFixture = TokenModel.fromJson(FixtureReader.readAsMap('auth/token_response.json')); + signInRequestFixture = FixtureReader.readAsMap('auth/oauth_signin_request.json'); + signUpRequestFixture = FixtureReader.readAsMap('auth/oauth_signup_request.json'); + + mockAuthRepository = MockAuthRepository(); + mockPrefs = MockPrefs(); + + SharedPreferences.setMockInitialValues({}); + + // Mock Fluttertoast plugin + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('PonnamKarthik/fluttertoast'), ( + MethodCall methodCall, + ) async { + return null; + }); + }); + + tearDown(() async { + if (oauthCubit != null && !oauthCubit!.isClosed) { + await Future.delayed(const Duration(milliseconds: 100)); + oauthCubit!.close(); + oauthCubit = null; + } + + // Clear mock handlers + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('PonnamKarthik/fluttertoast'), null); + }); + + test('начальное состояние - OAuthState', () { + oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + expect(oauthCubit!.state, const OAuthState()); + }); + + test('signInViaSocialMedia - успешный вход через соцсеть', () async { + oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + + when( + mockAuthRepository.signInViaSocialMedia( + provider: signInRequestFixture['provider'] as String, + accessToken: signInRequestFixture['access_token'] as String, + refreshToken: signInRequestFixture['refresh_token'] as String, + clientId: signInRequestFixture['client_id'] as String, + ), + ).thenAnswer((_) async => tokenFixture); + + await oauthCubit!.signInViaSocialMedia( + provider: signInRequestFixture['provider'] as String, + accessToken: signInRequestFixture['access_token'] as String, + refreshToken: signInRequestFixture['refresh_token'] as String, + clientId: signInRequestFixture['client_id'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(oauthCubit!.state, isA()); + final loadedState = oauthCubit!.state as OAuthStateLoaded; + expect(loadedState.token, tokenFixture.token); + + // Проверяем, что токен сохранён + final savedToken = await TokenStorage.getTokenFromStorage(); + expect(savedToken, tokenFixture.token); + }); + + test('signInViaSocialMedia - переход в состояние loading', () async { + oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + + when( + mockAuthRepository.signInViaSocialMedia( + provider: anyNamed('provider'), + accessToken: anyNamed('accessToken'), + refreshToken: anyNamed('refreshToken'), + clientId: anyNamed('clientId'), + ), + ).thenAnswer((_) async { + await Future.delayed(const Duration(milliseconds: 50)); + return tokenFixture; + }); + + final future = oauthCubit!.signInViaSocialMedia( + provider: signInRequestFixture['provider'] as String, + accessToken: signInRequestFixture['access_token'] as String, + refreshToken: signInRequestFixture['refresh_token'] as String, + clientId: signInRequestFixture['client_id'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 10)); + expect(oauthCubit!.state, isA()); + await future; + }); + + test('signInViaSocialMedia - обработка ошибки', () async { + oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + + when( + mockAuthRepository.signInViaSocialMedia( + provider: anyNamed('provider'), + accessToken: anyNamed('accessToken'), + refreshToken: anyNamed('refreshToken'), + clientId: anyNamed('clientId'), + ), + ).thenThrow(Exception('Ошибка авторизации')); + + await oauthCubit!.signInViaSocialMedia( + provider: signInRequestFixture['provider'] as String, + accessToken: signInRequestFixture['access_token'] as String, + refreshToken: signInRequestFixture['refresh_token'] as String, + clientId: signInRequestFixture['client_id'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(oauthCubit!.state, isA()); + final errorState = oauthCubit!.state as OAuthStateError; + expect(errorState.errorMessage, contains('Exception')); + }); + + test('signUpViaSocialMedia - успешная регистрация через соцсеть', () async { + oauthCubit = OAuthCubit(authRepository: mockAuthRepository, prefs: mockPrefs); + + when( + mockAuthRepository.signUpViaSocialMedia( + provider: anyNamed('provider'), + accessToken: anyNamed('accessToken'), + id: anyNamed('id'), + refreshToken: anyNamed('refreshToken'), + firstName: anyNamed('firstName'), + lastName: anyNamed('lastName'), + email: anyNamed('email'), + phone: anyNamed('phone'), + dateOfBirth: anyNamed('dateOfBirth'), + gender: anyNamed('gender'), + weight: anyNamed('weight'), + height: anyNamed('height'), + clientId: anyNamed('clientId'), + ), + ).thenAnswer((_) async => tokenFixture.token); + + when(mockPrefs.setString(any, any)).thenAnswer((_) async => Future.value()); + + final result = await oauthCubit!.signUpViaSocialMedia( + provider: signUpRequestFixture['provider'] as String, + accessToken: signUpRequestFixture['access_token'] as String, + id: signUpRequestFixture['id'] as String, + refreshToken: signUpRequestFixture['refresh_token'] as String, + firstName: signUpRequestFixture['first_name'] as String, + lastName: signUpRequestFixture['last_name'] as String, + email: signUpRequestFixture['email'] as String, + phone: signUpRequestFixture['phone'] as String, + dateOfBirth: signUpRequestFixture['date_of_birth'] as String, + gender: signUpRequestFixture['gender'] as String, + weight: signUpRequestFixture['weight'] as int, + height: signUpRequestFixture['height'] as int, + clientId: signUpRequestFixture['client_id'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(result, isNull); // Нет ошибок валидации + expect(oauthCubit!.state, isA()); + final loadedState = oauthCubit!.state as OAuthStateLoaded; + expect(loadedState.token, tokenFixture.token); + }); + }); +} diff --git a/test/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit_test.dart b/test/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit_test.dart new file mode 100644 index 00000000..6359d579 --- /dev/null +++ b/test/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit_test.dart @@ -0,0 +1,216 @@ +import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit.dart'; +import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_state.dart'; +import 'package:eatvio_app/features/auth/repositories/reset_password_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import '../../../../../fixtures/fixture_reader.dart'; +import 'reset_password_cubit_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('ResetPasswordCubit', () { + ResetPasswordCubit? resetPasswordCubit; + late MockResetPasswordRepository mockResetPasswordRepository; + late Map resetPasswordFixture; + + setUp(() { + resetPasswordFixture = FixtureReader.readAsMap('auth/reset_password_request.json'); + mockResetPasswordRepository = MockResetPasswordRepository(); + }); + + tearDown(() async { + if (resetPasswordCubit != null && !resetPasswordCubit!.isClosed) { + await Future.delayed(const Duration(milliseconds: 100)); + resetPasswordCubit!.close(); + resetPasswordCubit = null; + } + }); + + test('начальное состояние - ResetPasswordState.empty', () { + resetPasswordCubit = ResetPasswordCubit( + resetPasswordRepository: mockResetPasswordRepository, + ); + expect(resetPasswordCubit!.state, const ResetPasswordState.empty()); + }); + + test('trySendEmailCode - успешная отправка кода', () async { + resetPasswordCubit = ResetPasswordCubit( + resetPasswordRepository: mockResetPasswordRepository, + ); + + when(mockResetPasswordRepository.sendEmailCodeForPasswordChange( + resetPasswordFixture['email'] as String, + )).thenAnswer((_) async => true); + + await resetPasswordCubit!.trySendEmailCode( + resetPasswordFixture['email'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(resetPasswordCubit!.state, const ResetPasswordState.codeSendSuccess()); + verify(mockResetPasswordRepository.sendEmailCodeForPasswordChange( + resetPasswordFixture['email'] as String, + )).called(1); + }); + + test('trySendEmailCode - переход в состояние loading', () async { + resetPasswordCubit = ResetPasswordCubit( + resetPasswordRepository: mockResetPasswordRepository, + ); + + when(mockResetPasswordRepository.sendEmailCodeForPasswordChange( + any, + )).thenAnswer((_) async { + await Future.delayed(const Duration(milliseconds: 50)); + return true; + }); + + final future = resetPasswordCubit!.trySendEmailCode( + resetPasswordFixture['email'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 10)); + expect(resetPasswordCubit!.state, const ResetPasswordState.loadingSendEmailCode()); + await future; + }); + + test('trySendEmailCode - ошибка отправки кода', () async { + resetPasswordCubit = ResetPasswordCubit( + resetPasswordRepository: mockResetPasswordRepository, + ); + + when(mockResetPasswordRepository.sendEmailCodeForPasswordChange( + resetPasswordFixture['email'] as String, + )).thenAnswer((_) async => false); + + await resetPasswordCubit!.trySendEmailCode( + resetPasswordFixture['email'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(resetPasswordCubit!.state, const ResetPasswordState.codeSendError()); + }); + + test('trySendEmailCode - обработка исключения', () async { + resetPasswordCubit = ResetPasswordCubit( + resetPasswordRepository: mockResetPasswordRepository, + ); + + when(mockResetPasswordRepository.sendEmailCodeForPasswordChange( + resetPasswordFixture['email'] as String, + )).thenThrow(Exception('Ошибка сети')); + + await resetPasswordCubit!.trySendEmailCode( + resetPasswordFixture['email'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(resetPasswordCubit!.state, const ResetPasswordState.codeSendError()); + }); + + test('tryResetPassword - успешный сброс пароля', () async { + resetPasswordCubit = ResetPasswordCubit( + resetPasswordRepository: mockResetPasswordRepository, + ); + + when(mockResetPasswordRepository.confirmPasswordChange( + resetPasswordFixture['code'] as String, + resetPasswordFixture['password'] as String, + resetPasswordFixture['passwordConfirmation'] as String, + resetPasswordFixture['email'] as String, + )).thenAnswer((_) async => true); + + await resetPasswordCubit!.tryResetPassword( + resetPasswordFixture['email'] as String, + resetPasswordFixture['code'] as String, + resetPasswordFixture['password'] as String, + resetPasswordFixture['passwordConfirmation'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(resetPasswordCubit!.state, const ResetPasswordState.resetPasswordSuccess()); + verify(mockResetPasswordRepository.confirmPasswordChange( + resetPasswordFixture['code'] as String, + resetPasswordFixture['password'] as String, + resetPasswordFixture['passwordConfirmation'] as String, + resetPasswordFixture['email'] as String, + )).called(1); + }); + + test('tryResetPassword - переход в состояние loading', () async { + resetPasswordCubit = ResetPasswordCubit( + resetPasswordRepository: mockResetPasswordRepository, + ); + + when(mockResetPasswordRepository.confirmPasswordChange( + any, + any, + any, + any, + )).thenAnswer((_) async { + await Future.delayed(const Duration(milliseconds: 50)); + return true; + }); + + final future = resetPasswordCubit!.tryResetPassword( + resetPasswordFixture['email'] as String, + resetPasswordFixture['code'] as String, + resetPasswordFixture['password'] as String, + resetPasswordFixture['passwordConfirmation'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 10)); + expect(resetPasswordCubit!.state, const ResetPasswordState.loadingResetPassword()); + await future; + }); + + test('tryResetPassword - ошибка сброса пароля', () async { + resetPasswordCubit = ResetPasswordCubit( + resetPasswordRepository: mockResetPasswordRepository, + ); + + when(mockResetPasswordRepository.confirmPasswordChange( + resetPasswordFixture['code'] as String, + resetPasswordFixture['password'] as String, + resetPasswordFixture['passwordConfirmation'] as String, + resetPasswordFixture['email'] as String, + )).thenAnswer((_) async => false); + + await resetPasswordCubit!.tryResetPassword( + resetPasswordFixture['email'] as String, + resetPasswordFixture['code'] as String, + resetPasswordFixture['password'] as String, + resetPasswordFixture['passwordConfirmation'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(resetPasswordCubit!.state, const ResetPasswordState.resetPasswordError()); + }); + + test('tryResetPassword - обработка исключения', () async { + resetPasswordCubit = ResetPasswordCubit( + resetPasswordRepository: mockResetPasswordRepository, + ); + + when(mockResetPasswordRepository.confirmPasswordChange( + any, + any, + any, + any, + )).thenThrow(Exception('Неверный код')); + + await resetPasswordCubit!.tryResetPassword( + resetPasswordFixture['email'] as String, + resetPasswordFixture['code'] as String, + resetPasswordFixture['password'] as String, + resetPasswordFixture['passwordConfirmation'] as String, + ); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(resetPasswordCubit!.state, const ResetPasswordState.resetPasswordError()); + }); + }); +} + diff --git a/test/features/auth/presentation/widgets/basic_widget_test.dart b/test/features/auth/presentation/widgets/basic_widget_test.dart new file mode 100644 index 00000000..8ee51486 --- /dev/null +++ b/test/features/auth/presentation/widgets/basic_widget_test.dart @@ -0,0 +1,416 @@ +// ignore_for_file: deprecated_member_use + +import 'package:eatvio_app/app_keys.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/auth/models/token_model.dart'; +import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../../../fixtures/doubles/auth_doubles.dart'; +import '../../../../fixtures/fixture_reader.dart'; + +void main() { + group('Auth Basic Widget Tests', () { + late FixtureAuthRepository authRepository; + late AuthCubit authCubit; + late Map credentialsFixture; + + setUp(() { + credentialsFixture = FixtureReader.readAsMap('auth/login_credentials.json'); + authRepository = FixtureAuthRepository( + tokenFixture: TokenModel.fromJson(FixtureReader.readAsMap('auth/token_response.json')), + ); + authCubit = AuthCubit(authRepository: authRepository); + }); + + tearDown(() { + authCubit.close(); + }); + + Widget createTestWidget(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + home: BlocProvider( + create: (context) => authCubit, + child: Scaffold(body: SingleChildScrollView(child: child)), + ), + ); + } + + testWidgets('should create AuthCubit successfully', (WidgetTester tester) async { + // Arrange & Act + final cubit = AuthCubit(authRepository: authRepository); + + // Assert + expect(cubit, isA()); + + cubit.close(); + }); + + testWidgets('should display email text field', (WidgetTester tester) async { + // Arrange + Widget emailWidget = TextFormField( + key: AppKeys.emailTextFieldAuthScreen, + decoration: const InputDecoration(labelText: 'Email', hintText: 'Введите email'), + keyboardType: TextInputType.emailAddress, + ); + + // Act + await tester.pumpWidget(createTestWidget(emailWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byKey(AppKeys.emailTextFieldAuthScreen), findsOneWidget); + }); + + testWidgets('should display password text field', (WidgetTester tester) async { + // Arrange + Widget passwordWidget = TextFormField( + key: AppKeys.passwordTextFieldAuthScreen, + decoration: const InputDecoration(labelText: 'Пароль', hintText: 'Введите пароль'), + obscureText: true, + ); + + // Act + await tester.pumpWidget(createTestWidget(passwordWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byKey(AppKeys.passwordTextFieldAuthScreen), findsOneWidget); + }); + + testWidgets('should display sign in button', (WidgetTester tester) async { + // Arrange + Widget buttonWidget = FloatingActionButton.extended( + key: AppKeys.signInButtonAuthScreen, + onPressed: () {}, + label: const Text('Войти'), + ); + + // Act + await tester.pumpWidget(createTestWidget(buttonWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byKey(AppKeys.signInButtonAuthScreen), findsOneWidget); + expect(find.text('Войти'), findsOneWidget); + }); + + testWidgets('should update email when user types in email field', (WidgetTester tester) async { + // Arrange + Widget emailWidget = TextFormField( + key: AppKeys.emailTextFieldAuthScreen, + decoration: const InputDecoration(labelText: 'Email', hintText: 'Введите email'), + keyboardType: TextInputType.emailAddress, + ); + + await tester.pumpWidget(createTestWidget(emailWidget)); + await tester.pumpAndSettle(); + + final testEmail = credentialsFixture['email'] as String; + + // Act + await tester.enterText(find.byKey(AppKeys.emailTextFieldAuthScreen), testEmail); + await tester.pump(); + + // Assert + expect(find.text(testEmail), findsOneWidget); + }); + + testWidgets('should update password when user types in password field', (WidgetTester tester) async { + // Arrange + Widget passwordWidget = TextFormField( + key: AppKeys.passwordTextFieldAuthScreen, + decoration: const InputDecoration(labelText: 'Пароль', hintText: 'Введите пароль'), + obscureText: true, + ); + + await tester.pumpWidget(createTestWidget(passwordWidget)); + await tester.pumpAndSettle(); + + final testPassword = credentialsFixture['password'] as String; + + // Act + await tester.enterText(find.byKey(AppKeys.passwordTextFieldAuthScreen), testPassword); + await tester.pump(); + + // Assert + expect(find.text(testPassword), findsOneWidget); + }); + + testWidgets('should display complete auth form', (WidgetTester tester) async { + // Arrange + Widget completeForm = Column( + children: [ + TextFormField( + key: AppKeys.emailTextFieldAuthScreen, + decoration: const InputDecoration(labelText: 'Email', hintText: 'Введите email'), + keyboardType: TextInputType.emailAddress, + ), + const SizedBox(height: 16), + TextFormField( + key: AppKeys.passwordTextFieldAuthScreen, + decoration: const InputDecoration(labelText: 'Пароль', hintText: 'Введите пароль'), + obscureText: true, + ), + const SizedBox(height: 16), + FloatingActionButton.extended( + key: AppKeys.signInButtonAuthScreen, + onPressed: () {}, + label: const Text('Войти'), + ), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(completeForm)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byKey(AppKeys.emailTextFieldAuthScreen), findsOneWidget); + expect(find.byKey(AppKeys.passwordTextFieldAuthScreen), findsOneWidget); + expect(find.byKey(AppKeys.signInButtonAuthScreen), findsOneWidget); + }); + + testWidgets('should display loading state', (WidgetTester tester) async { + // Arrange + Widget loadingWidget = const Center(child: CircularProgressIndicator()); + + // Act + await tester.pumpWidget(createTestWidget(loadingWidget)); + await tester.pump(); + + // Assert + expect(find.byType(CircularProgressIndicator), findsOneWidget); + }); + + testWidgets('should display error message', (WidgetTester tester) async { + // Arrange + Widget errorWidget = const Center(child: Text('Неверный адрес электронной почты или пароль')); + + // Act + await tester.pumpWidget(createTestWidget(errorWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Неверный адрес электронной почты или пароль'), findsOneWidget); + }); + + testWidgets('should handle sign in button tap', (WidgetTester tester) async { + // Arrange + bool buttonPressed = false; + Widget buttonWidget = FloatingActionButton.extended( + key: AppKeys.signInButtonAuthScreen, + onPressed: () { + buttonPressed = true; + }, + label: const Text('Войти'), + ); + + await tester.pumpWidget(createTestWidget(buttonWidget)); + await tester.pumpAndSettle(); + + // Act + await tester.tap(find.byKey(AppKeys.signInButtonAuthScreen)); + await tester.pump(); + + // Assert + expect(buttonPressed, isTrue); + }); + + testWidgets('should display password visibility toggle', (WidgetTester tester) async { + // Arrange + Widget passwordWidget = TextFormField( + key: AppKeys.passwordTextFieldAuthScreen, + decoration: const InputDecoration( + labelText: 'Пароль', + hintText: 'Введите пароль', + suffix: IconButton( + onPressed: null, + icon: Icon(Icons.visibility_outlined), + ), + ), + obscureText: true, + ); + + await tester.pumpWidget(createTestWidget(passwordWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byIcon(Icons.visibility_outlined), findsOneWidget); + }); + + testWidgets('should display "Забыли пароль?" link', (WidgetTester tester) async { + // Arrange + Widget forgotPasswordWidget = GestureDetector( + onTap: () {}, + child: const Text( + 'Забыли пароль?', + style: TextStyle(decoration: TextDecoration.underline), + ), + ); + + // Act + await tester.pumpWidget(createTestWidget(forgotPasswordWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Забыли пароль?'), findsOneWidget); + }); + + testWidgets('should display registration link', (WidgetTester tester) async { + // Arrange + Widget registrationLinkWidget = Row( + children: [ + const Text('Нет аккаунта? '), + GestureDetector( + onTap: () {}, + child: const Text( + 'Зарегистрироваться', + style: TextStyle(decoration: TextDecoration.underline), + ), + ), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(registrationLinkWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Нет аккаунта? '), findsOneWidget); + expect(find.text('Зарегистрироваться'), findsOneWidget); + }); + + testWidgets('should display social auth buttons', (WidgetTester tester) async { + // Arrange + Widget socialButtonsWidget = Column( + children: [ + const Text('Авторизация через'), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + InkWell( + onTap: () {}, + child: Container( + height: 48, + width: 80, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + border: Border.all(color: const Color(0xFFDBDBDB), width: 1), + ), + child: const Center(child: Text('VK')), + ), + ), + InkWell( + onTap: () {}, + child: Container( + height: 48, + width: 80, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + border: Border.all(color: const Color(0xFFDBDBDB), width: 1), + ), + child: const Center(child: Text('OK')), + ), + ), + ], + ), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(socialButtonsWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Авторизация через'), findsOneWidget); + expect(find.text('VK'), findsOneWidget); + expect(find.text('OK'), findsOneWidget); + }); + + testWidgets('should validate email format', (WidgetTester tester) async { + // Arrange + Widget emailWidget = TextFormField( + key: AppKeys.emailTextFieldAuthScreen, + decoration: const InputDecoration( + labelText: 'Email', + hintText: 'Введите email', + errorText: 'Введите корректный email', + ), + keyboardType: TextInputType.emailAddress, + ); + + // Act + await tester.pumpWidget(createTestWidget(emailWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Введите корректный email'), findsOneWidget); + }); + + testWidgets('should disable sign in button when loading', (WidgetTester tester) async { + // Arrange + Widget buttonWidget = const FloatingActionButton.extended( + key: AppKeys.signInButtonAuthScreen, + onPressed: null, // Disabled + label: Text('Войти'), + ); + + // Act + await tester.pumpWidget(createTestWidget(buttonWidget)); + await tester.pumpAndSettle(); + + // Assert + final button = tester.widget(find.byKey(AppKeys.signInButtonAuthScreen)); + expect(button, isA()); + }); + + testWidgets('should display form labels correctly', (WidgetTester tester) async { + // Arrange + Widget formWidget = const Column( + children: [ + Text('Email'), + Text('Пароль'), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(formWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Email'), findsOneWidget); + expect(find.text('Пароль'), findsOneWidget); + }); + + testWidgets('should display placeholder text in fields', (WidgetTester tester) async { + // Arrange + Widget formWidget = Column( + children: [ + TextFormField( + key: AppKeys.emailTextFieldAuthScreen, + decoration: const InputDecoration(labelText: 'Email', hintText: 'Введите email'), + ), + const SizedBox(height: 16), + TextFormField( + key: AppKeys.passwordTextFieldAuthScreen, + decoration: const InputDecoration(labelText: 'Пароль', hintText: 'Введите пароль'), + ), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(formWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Введите email'), findsOneWidget); + expect(find.text('Введите пароль'), findsOneWidget); + }); + }); +} + diff --git a/test/features/auth/repositories/auth_repository_test.dart b/test/features/auth/repositories/auth_repository_test.dart new file mode 100644 index 00000000..b62fea26 --- /dev/null +++ b/test/features/auth/repositories/auth_repository_test.dart @@ -0,0 +1,237 @@ +import 'package:eatvio_app/features/auth/models/credentials_model.dart'; +import 'package:eatvio_app/features/auth/models/oauth_login_request.dart'; +import 'package:eatvio_app/features/auth/models/oauth_model.dart'; +import 'package:eatvio_app/features/auth/models/token_model.dart'; +import 'package:eatvio_app/features/auth/repositories/auth_repository.dart'; +import 'package:eatvio_app/features/auth/services/auth_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import '../../../fixtures/fixture_reader.dart'; +import 'auth_repository_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('AuthRepository', () { + late AuthRepository authRepository; + late MockAuthService mockAuthService; + late TokenModel tokenFixture; + late Map credentialsFixture; + late Map oauthSignInFixture; + late Map oauthSignUpFixture; + + setUp(() { + tokenFixture = TokenModel.fromJson(FixtureReader.readAsMap('auth/token_response.json')); + credentialsFixture = FixtureReader.readAsMap('auth/login_credentials.json'); + oauthSignInFixture = FixtureReader.readAsMap('auth/oauth_signin_request.json'); + oauthSignUpFixture = FixtureReader.readAsMap('auth/oauth_signup_request.json'); + + mockAuthService = MockAuthService(); + authRepository = AuthRepository(authService: mockAuthService); + }); + + test('getTokenByCredentials - успешное получение токена', () async { + final credentials = CredentialsModel( + email: credentialsFixture['email'] as String, + password: credentialsFixture['password'] as String, + ); + + when(mockAuthService.getTokenByCredentials(credentials: credentials)) + .thenAnswer((_) async => tokenFixture); + + final result = await authRepository.getTokenByCredentials( + credentialsFixture['email'] as String, + credentialsFixture['password'] as String, + ); + + expect(result, isA()); + expect(result.token, tokenFixture.token); + verify(mockAuthService.getTokenByCredentials(credentials: credentials)).called(1); + }); + + test('getTokenByCredentials - пробрасывает исключение', () async { + final credentials = CredentialsModel( + email: credentialsFixture['email'] as String, + password: credentialsFixture['password'] as String, + ); + + when(mockAuthService.getTokenByCredentials(credentials: credentials)) + .thenThrow(Exception('Ошибка авторизации')); + + expect( + () => authRepository.getTokenByCredentials( + credentialsFixture['email'] as String, + credentialsFixture['password'] as String, + ), + throwsException, + ); + }); + + test('signInViaSocialMedia - успешный вход через соцсеть', () async { + final oauthRequest = OAuthLoginRequest( + provider: oauthSignInFixture['provider'] as String, + accessToken: oauthSignInFixture['access_token'] as String, + refreshToken: oauthSignInFixture['refresh_token'] as String, + clientId: oauthSignInFixture['client_id'] as String, + ); + + when(mockAuthService.signInViaSocialMedia(body: oauthRequest)) + .thenAnswer((_) async => tokenFixture); + + final result = await authRepository.signInViaSocialMedia( + provider: oauthSignInFixture['provider'] as String, + accessToken: oauthSignInFixture['access_token'] as String, + refreshToken: oauthSignInFixture['refresh_token'] as String, + clientId: oauthSignInFixture['client_id'] as String, + ); + + expect(result, isA()); + expect(result.token, tokenFixture.token); + verify(mockAuthService.signInViaSocialMedia(body: oauthRequest)).called(1); + }); + + test('signInViaSocialMedia - пробрасывает исключение', () async { + final oauthRequest = OAuthLoginRequest( + provider: oauthSignInFixture['provider'] as String, + accessToken: oauthSignInFixture['access_token'] as String, + refreshToken: oauthSignInFixture['refresh_token'] as String, + clientId: oauthSignInFixture['client_id'] as String, + ); + + when(mockAuthService.signInViaSocialMedia(body: oauthRequest)) + .thenThrow(Exception('Ошибка OAuth')); + + expect( + () => authRepository.signInViaSocialMedia( + provider: oauthSignInFixture['provider'] as String, + accessToken: oauthSignInFixture['access_token'] as String, + refreshToken: oauthSignInFixture['refresh_token'] as String, + clientId: oauthSignInFixture['client_id'] as String, + ), + throwsException, + ); + }); + + test('signUpViaSocialMedia - успешная регистрация через соцсеть', () async { + final oauthModel = OAuthModel( + provider: oauthSignUpFixture['provider'] as String, + accessToken: oauthSignUpFixture['access_token'] as String, + id: oauthSignUpFixture['id'] as String, + refreshToken: oauthSignUpFixture['refresh_token'] as String, + firstName: oauthSignUpFixture['first_name'] as String, + lastName: oauthSignUpFixture['last_name'] as String, + email: oauthSignUpFixture['email'] as String, + phone: oauthSignUpFixture['phone'] as String, + dateOfBirth: oauthSignUpFixture['date_of_birth'] as String, + gender: 'male', // Преобразуется из 'М' + weight: oauthSignUpFixture['weight'] as int, + height: oauthSignUpFixture['height'] as int, + clientId: oauthSignUpFixture['client_id'] as String, + ); + + when(mockAuthService.signUpViaSocialMedia(body: oauthModel)) + .thenAnswer((_) async => {'token': tokenFixture.token}); + + final result = await authRepository.signUpViaSocialMedia( + provider: oauthSignUpFixture['provider'] as String, + accessToken: oauthSignUpFixture['access_token'] as String, + id: oauthSignUpFixture['id'] as String, + refreshToken: oauthSignUpFixture['refresh_token'] as String, + firstName: oauthSignUpFixture['first_name'] as String, + lastName: oauthSignUpFixture['last_name'] as String, + email: oauthSignUpFixture['email'] as String, + phone: oauthSignUpFixture['phone'] as String, + dateOfBirth: oauthSignUpFixture['date_of_birth'] as String, + gender: oauthSignUpFixture['gender'] as String, + weight: oauthSignUpFixture['weight'] as int, + height: oauthSignUpFixture['height'] as int, + clientId: oauthSignUpFixture['client_id'] as String, + ); + + expect(result, tokenFixture.token); + verify(mockAuthService.signUpViaSocialMedia(body: oauthModel)).called(1); + }); + + test('signUpViaSocialMedia - преобразует женский пол', () async { + final oauthModel = OAuthModel( + provider: oauthSignUpFixture['provider'] as String, + accessToken: oauthSignUpFixture['access_token'] as String, + id: oauthSignUpFixture['id'] as String, + refreshToken: oauthSignUpFixture['refresh_token'] as String, + firstName: oauthSignUpFixture['first_name'] as String, + lastName: oauthSignUpFixture['last_name'] as String, + email: oauthSignUpFixture['email'] as String, + phone: oauthSignUpFixture['phone'] as String, + dateOfBirth: oauthSignUpFixture['date_of_birth'] as String, + gender: 'female', // Преобразуется из 'Ж' + weight: oauthSignUpFixture['weight'] as int, + height: oauthSignUpFixture['height'] as int, + clientId: oauthSignUpFixture['client_id'] as String, + ); + + when(mockAuthService.signUpViaSocialMedia(body: oauthModel)) + .thenAnswer((_) async => {'token': tokenFixture.token}); + + final result = await authRepository.signUpViaSocialMedia( + provider: oauthSignUpFixture['provider'] as String, + accessToken: oauthSignUpFixture['access_token'] as String, + id: oauthSignUpFixture['id'] as String, + refreshToken: oauthSignUpFixture['refresh_token'] as String, + firstName: oauthSignUpFixture['first_name'] as String, + lastName: oauthSignUpFixture['last_name'] as String, + email: oauthSignUpFixture['email'] as String, + phone: oauthSignUpFixture['phone'] as String, + dateOfBirth: oauthSignUpFixture['date_of_birth'] as String, + gender: 'Ж', + weight: oauthSignUpFixture['weight'] as int, + height: oauthSignUpFixture['height'] as int, + clientId: oauthSignUpFixture['client_id'] as String, + ); + + expect(result, tokenFixture.token); + verify(mockAuthService.signUpViaSocialMedia(body: oauthModel)).called(1); + }); + + test('signUpViaSocialMedia - пробрасывает исключение', () async { + final oauthModel = OAuthModel( + provider: oauthSignUpFixture['provider'] as String, + accessToken: oauthSignUpFixture['access_token'] as String, + id: oauthSignUpFixture['id'] as String, + refreshToken: oauthSignUpFixture['refresh_token'] as String, + firstName: oauthSignUpFixture['first_name'] as String, + lastName: oauthSignUpFixture['last_name'] as String, + email: oauthSignUpFixture['email'] as String, + phone: oauthSignUpFixture['phone'] as String, + dateOfBirth: oauthSignUpFixture['date_of_birth'] as String, + gender: 'male', // Преобразуется из 'М' + weight: oauthSignUpFixture['weight'] as int, + height: oauthSignUpFixture['height'] as int, + clientId: oauthSignUpFixture['client_id'] as String, + ); + + when(mockAuthService.signUpViaSocialMedia(body: oauthModel)) + .thenThrow(Exception('Ошибка регистрации')); + + expect( + () => authRepository.signUpViaSocialMedia( + provider: oauthSignUpFixture['provider'] as String, + accessToken: oauthSignUpFixture['access_token'] as String, + id: oauthSignUpFixture['id'] as String, + refreshToken: oauthSignUpFixture['refresh_token'] as String, + firstName: oauthSignUpFixture['first_name'] as String, + lastName: oauthSignUpFixture['last_name'] as String, + email: oauthSignUpFixture['email'] as String, + phone: oauthSignUpFixture['phone'] as String, + dateOfBirth: oauthSignUpFixture['date_of_birth'] as String, + gender: oauthSignUpFixture['gender'] as String, + weight: oauthSignUpFixture['weight'] as int, + height: oauthSignUpFixture['height'] as int, + clientId: oauthSignUpFixture['client_id'] as String, + ), + throwsException, + ); + }); + }); +} + diff --git a/test/features/auth/repositories/reset_password_repository_test.dart b/test/features/auth/repositories/reset_password_repository_test.dart new file mode 100644 index 00000000..f4c702da --- /dev/null +++ b/test/features/auth/repositories/reset_password_repository_test.dart @@ -0,0 +1,182 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/auth/repositories/reset_password_repository.dart'; +import 'package:eatvio_app/features/auth/services/reset_password_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:retrofit/retrofit.dart'; + +import '../../../fixtures/fixture_reader.dart'; +import 'reset_password_repository_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('ResetPasswordRepository', () { + late ResetPasswordRepository resetPasswordRepository; + late MockResetPasswordService mockResetPasswordService; + late Map resetPasswordFixture; + + setUp(() { + resetPasswordFixture = FixtureReader.readAsMap('auth/reset_password_request.json'); + mockResetPasswordService = MockResetPasswordService(); + resetPasswordRepository = ResetPasswordRepository( + resetPasswordService: mockResetPasswordService, + ); + }); + + test('sendEmailCodeForPasswordChange - успешная отправка кода (200)', () async { + final email = resetPasswordFixture['email'] as String; + final response = HttpResponse( + {'success': true}, + Response( + statusCode: 200, + requestOptions: RequestOptions(path: '/api/send_password_reset_code'), + ), + ); + + when(mockResetPasswordService.sendEmailCodeForPasswordChange( + data: {'email': email}, + )).thenAnswer((_) async => response); + + final result = await resetPasswordRepository.sendEmailCodeForPasswordChange(email); + + expect(result, isTrue); + verify(mockResetPasswordService.sendEmailCodeForPasswordChange( + data: {'email': email}, + )).called(1); + }); + + test('sendEmailCodeForPasswordChange - ошибка отправки кода (400)', () async { + final email = resetPasswordFixture['email'] as String; + final response = HttpResponse( + {'error': 'Invalid email'}, + Response( + statusCode: 400, + requestOptions: RequestOptions(path: '/api/send_password_reset_code'), + ), + ); + + when(mockResetPasswordService.sendEmailCodeForPasswordChange( + data: {'email': email}, + )).thenAnswer((_) async => response); + + final result = await resetPasswordRepository.sendEmailCodeForPasswordChange(email); + + expect(result, isFalse); + }); + + test('sendEmailCodeForPasswordChange - пробрасывает исключение', () async { + final email = resetPasswordFixture['email'] as String; + + when(mockResetPasswordService.sendEmailCodeForPasswordChange( + data: {'email': email}, + )).thenThrow(Exception('Ошибка сети')); + + expect( + () => resetPasswordRepository.sendEmailCodeForPasswordChange(email), + throwsException, + ); + }); + + test('confirmPasswordChange - успешный сброс пароля (200)', () async { + final code = resetPasswordFixture['code'] as String; + final password = resetPasswordFixture['password'] as String; + final passwordConfirmation = resetPasswordFixture['passwordConfirmation'] as String; + final email = resetPasswordFixture['email'] as String; + + final response = HttpResponse( + {'success': true}, + Response( + statusCode: 200, + requestOptions: RequestOptions(path: '/api/confirm_password_reset_code'), + ), + ); + + when(mockResetPasswordService.confirmPasswordChange( + data: { + 'code': code, + 'password': password, + 'password_confirmation': passwordConfirmation, + 'email': email, + }, + )).thenAnswer((_) async => response); + + final result = await resetPasswordRepository.confirmPasswordChange( + code, + password, + passwordConfirmation, + email, + ); + + expect(result, isTrue); + verify(mockResetPasswordService.confirmPasswordChange( + data: { + 'code': code, + 'password': password, + 'password_confirmation': passwordConfirmation, + 'email': email, + }, + )).called(1); + }); + + test('confirmPasswordChange - ошибка сброса пароля (400)', () async { + final code = resetPasswordFixture['code'] as String; + final password = resetPasswordFixture['password'] as String; + final passwordConfirmation = resetPasswordFixture['passwordConfirmation'] as String; + final email = resetPasswordFixture['email'] as String; + + final response = HttpResponse( + {'error': 'Invalid code'}, + Response( + statusCode: 400, + requestOptions: RequestOptions(path: '/api/confirm_password_reset_code'), + ), + ); + + when(mockResetPasswordService.confirmPasswordChange( + data: { + 'code': code, + 'password': password, + 'password_confirmation': passwordConfirmation, + 'email': email, + }, + )).thenAnswer((_) async => response); + + final result = await resetPasswordRepository.confirmPasswordChange( + code, + password, + passwordConfirmation, + email, + ); + + expect(result, isFalse); + }); + + test('confirmPasswordChange - пробрасывает исключение', () async { + final code = resetPasswordFixture['code'] as String; + final password = resetPasswordFixture['password'] as String; + final passwordConfirmation = resetPasswordFixture['passwordConfirmation'] as String; + final email = resetPasswordFixture['email'] as String; + + when(mockResetPasswordService.confirmPasswordChange( + data: { + 'code': code, + 'password': password, + 'password_confirmation': passwordConfirmation, + 'email': email, + }, + )).thenThrow(Exception('Ошибка сети')); + + expect( + () => resetPasswordRepository.confirmPasswordChange( + code, + password, + passwordConfirmation, + email, + ), + throwsException, + ); + }); + }); +} + diff --git a/test/features/blog_post_create/advanced_widget_test.dart b/test/features/blog_post_create/advanced_widget_test.dart index 381a1075..e052fa3c 100644 --- a/test/features/blog_post_create/advanced_widget_test.dart +++ b/test/features/blog_post_create/advanced_widget_test.dart @@ -2,26 +2,29 @@ import 'package:eatvio_app/app_keys.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_cubit.dart'; import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_state.dart'; -import 'package:eatvio_app/features/blog_post_create/repositories/blog_post_repository.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; -import 'advanced_widget_test.mocks.dart'; +import '../../fixtures/doubles/blog_post_doubles.dart'; +import '../../fixtures/fixture_reader.dart'; -@GenerateMocks([BlogPostRepository]) void main() { group('Blog Post Creation Advanced Widget Tests', () { - late MockBlogPostRepository mockBlogPostRepository; + late FixtureBlogPostRepository blogPostRepository; late BlogPostCreateCubit blogPostCreateCubit; + late Map fullCreateFixture; + late Map updateFixture; + late Map deleteFixture; setUp(() { - mockBlogPostRepository = MockBlogPostRepository(); - blogPostCreateCubit = BlogPostCreateCubit(blogPostRepository: mockBlogPostRepository); + blogPostRepository = FixtureBlogPostRepository(); + blogPostCreateCubit = BlogPostCreateCubit(blogPostRepository: blogPostRepository); + fullCreateFixture = FixtureReader.readAsMap('blog_post_create/create_request_full.json'); + updateFixture = FixtureReader.readAsMap('blog_post_create/update_request.json'); + deleteFixture = FixtureReader.readAsMap('blog_post_create/delete_request.json'); }); tearDown(() { @@ -40,8 +43,6 @@ void main() { testWidgets('should handle blog post creation with all fields', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenAnswer((_) async {}); - Widget formWidget = Column( children: [ TextFormField( @@ -65,9 +66,9 @@ void main() { key: AppKeys.blogPostCreateScreenCreateButton, onPressed: () async { await blogPostCreateCubit.createBlogPost( - title: 'Test Title', - description: 'Test Description', - videoUrl: 'https://youtube.com/watch?v=test', + title: fullCreateFixture['title'] as String?, + description: fullCreateFixture['description_md'] as String?, + videoUrl: fullCreateFixture['video_url'] as String?, image: null, ); }, @@ -80,21 +81,25 @@ void main() { await tester.pumpWidget(createTestWidget(formWidget)); await tester.pumpAndSettle(); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), 'Test Title'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), 'Test Description'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), 'https://youtube.com/watch?v=test'); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), fullCreateFixture['title'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), fullCreateFixture['description_md'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), fullCreateFixture['video_url'] as String); await tester.pump(); await tester.tap(find.byKey(AppKeys.blogPostCreateScreenCreateButton)); await tester.pump(); // Assert - verify(mockBlogPostRepository.createBlogPost('Test Title', 'https://youtube.com/watch?v=test', 'Test Description', null)).called(1); + expect( + blogPostRepository.createPayloads.single.toJson(), + fullCreateFixture, + ); }); testWidgets('should handle blog post creation with image', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenAnswer((_) async {}); + final expectedPayload = Map.from(fullCreateFixture); + expectedPayload['video_url'] = null; Widget formWidget = Column( children: [ @@ -137,8 +142,8 @@ void main() { key: AppKeys.blogPostCreateScreenCreateButton, onPressed: () async { await blogPostCreateCubit.createBlogPost( - title: 'Test Title', - description: 'Test Description', + title: fullCreateFixture['title'] as String?, + description: fullCreateFixture['description_md'] as String?, videoUrl: null, image: null, // В реальном тесте здесь был бы XFile ); @@ -152,21 +157,19 @@ void main() { await tester.pumpWidget(createTestWidget(formWidget)); await tester.pumpAndSettle(); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), 'Test Title'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), 'Test Description'); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), fullCreateFixture['title'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), fullCreateFixture['description_md'] as String); await tester.pump(); await tester.tap(find.byKey(AppKeys.blogPostCreateScreenCreateButton)); await tester.pump(); // Assert - verify(mockBlogPostRepository.createBlogPost('Test Title', null, 'Test Description', null)).called(1); + expect(blogPostRepository.createPayloads.single.toJson(), expectedPayload); }); testWidgets('should handle blog post update', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.updateBlogPost(any, any, any, any, any, any)).thenAnswer((_) async {}); - final testBlogPost = FeedBlogPostModel( id: 1, state: 'published', @@ -209,12 +212,12 @@ void main() { key: AppKeys.blogPostCreateScreenCreateButton, onPressed: () async { await blogPostCreateCubit.updateBlogPost( - id: testBlogPost.id, - title: 'Updated Title', - description: 'Updated Description', - videoUrl: 'https://youtube.com/watch?v=updated', + id: updateFixture['id'] as int, + title: updateFixture['title'] as String?, + description: updateFixture['description_md'] as String?, + videoUrl: updateFixture['video_url'] as String?, image: null, - oldImageUrl: testBlogPost.image, + oldImageUrl: updateFixture['old_image_url'] as String?, ); }, child: const Text('Обновить'), @@ -226,24 +229,20 @@ void main() { await tester.pumpWidget(createTestWidget(formWidget)); await tester.pumpAndSettle(); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), 'Updated Title'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), 'Updated Description'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), 'https://youtube.com/watch?v=updated'); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), updateFixture['title'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), updateFixture['description_md'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), updateFixture['video_url'] as String); await tester.pump(); await tester.tap(find.byKey(AppKeys.blogPostCreateScreenCreateButton)); await tester.pump(); // Assert - verify( - mockBlogPostRepository.updateBlogPost(1, 'Updated Title', 'https://youtube.com/watch?v=updated', 'Updated Description', null, 'original_image.jpg'), - ).called(1); + expect(blogPostRepository.updatePayloads.single.toJson(), updateFixture); }); testWidgets('should handle blog post deletion', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.deleteBlogPost(any)).thenAnswer((_) async {}); - Widget deleteWidget = ElevatedButton( key: const Key('deleteBlogPostButton'), onPressed: () async { @@ -260,14 +259,12 @@ void main() { await tester.pump(); // Assert - verify(mockBlogPostRepository.deleteBlogPost(1)).called(1); + expect(blogPostRepository.deleteCalls.single, deleteFixture['id']); }); testWidgets('should handle loading state during blog post creation', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenAnswer((_) async { - await Future.delayed(const Duration(milliseconds: 50)); - }); + blogPostRepository.createDelay = const Duration(milliseconds: 50); Widget loadingWidget = BlocBuilder( builder: (context, state) { @@ -283,7 +280,12 @@ void main() { await tester.pumpAndSettle(); // Trigger loading state - blogPostCreateCubit.createBlogPost(title: 'Test Title', videoUrl: null, description: 'Test Description', image: null); + blogPostCreateCubit.createBlogPost( + title: fullCreateFixture['title'] as String?, + videoUrl: null, + description: fullCreateFixture['description_md'] as String?, + image: null, + ); await tester.pump(); await tester.pump(); // Need to pump twice to get the loading state @@ -297,7 +299,7 @@ void main() { testWidgets('should handle error state during blog post creation', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenThrow(Exception('Network error')); + blogPostRepository.createError = Exception('Network error'); Widget errorWidget = BlocBuilder( builder: (context, state) { @@ -313,7 +315,12 @@ void main() { await tester.pumpAndSettle(); // Trigger error state - blogPostCreateCubit.createBlogPost(title: 'Test Title', videoUrl: null, description: 'Test Description', image: null); + blogPostCreateCubit.createBlogPost( + title: fullCreateFixture['title'] as String?, + videoUrl: null, + description: fullCreateFixture['description_md'] as String?, + image: null, + ); await tester.pump(); await tester.pump(); // Need to pump twice to get the error state @@ -323,8 +330,6 @@ void main() { testWidgets('should handle success state after blog post creation', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenAnswer((_) async {}); - Widget successWidget = BlocBuilder( builder: (context, state) { if (state is BlogPostCreateStateLoaded) { @@ -339,7 +344,12 @@ void main() { await tester.pumpAndSettle(); // Trigger success state - blogPostCreateCubit.createBlogPost(title: 'Test Title', videoUrl: null, description: 'Test Description', image: null); + blogPostCreateCubit.createBlogPost( + title: fullCreateFixture['title'] as String?, + videoUrl: null, + description: fullCreateFixture['description_md'] as String?, + image: null, + ); await tester.pump(); await tester.pump(); // Need to pump twice to get the success state @@ -470,7 +480,10 @@ void main() { await tester.pump(); // Assert - verify(mockBlogPostRepository.createBlogPost('', '', '', null)).called(1); + expect( + blogPostRepository.createPayloads.single.toJson(), + {'title': '', 'description_md': '', 'video_url': '', 'image_name': null}, + ); }); testWidgets('should handle blog post creation with long content', (WidgetTester tester) async { @@ -480,8 +493,6 @@ void main() { 'Оно может содержать несколько абзацев и различные форматирования. ' 'Пользователи должны иметь возможность создавать подробные и информативные посты.'; - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenAnswer((_) async {}); - Widget longContentWidget = Column( children: [ TextFormField( @@ -518,7 +529,15 @@ void main() { await tester.pump(); // Assert - verify(mockBlogPostRepository.createBlogPost('Test Title', null, longContent, null)).called(1); + expect( + blogPostRepository.createPayloads.single.toJson(), + { + 'title': 'Test Title', + 'description_md': longContent, + 'video_url': null, + 'image_name': null, + }, + ); }); }); } diff --git a/test/features/blog_post_create/basic_widget_test.dart b/test/features/blog_post_create/basic_widget_test.dart index 85850466..1e91998f 100644 --- a/test/features/blog_post_create/basic_widget_test.dart +++ b/test/features/blog_post_create/basic_widget_test.dart @@ -1,23 +1,20 @@ import 'package:eatvio_app/app_keys.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_cubit.dart'; -import 'package:eatvio_app/features/blog_post_create/repositories/blog_post_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'basic_widget_test.mocks.dart'; +import '../../fixtures/doubles/blog_post_doubles.dart'; -@GenerateMocks([BlogPostRepository]) void main() { group('Blog Post Creation Basic Widget Tests', () { - late MockBlogPostRepository mockBlogPostRepository; + late FixtureBlogPostRepository blogPostRepository; late BlogPostCreateCubit blogPostCreateCubit; setUp(() { - mockBlogPostRepository = MockBlogPostRepository(); - blogPostCreateCubit = BlogPostCreateCubit(blogPostRepository: mockBlogPostRepository); + blogPostRepository = FixtureBlogPostRepository(); + blogPostCreateCubit = BlogPostCreateCubit(blogPostRepository: blogPostRepository); }); tearDown(() { @@ -36,7 +33,7 @@ void main() { testWidgets('should create BlogPostCreateCubit successfully', (WidgetTester tester) async { // Arrange & Act - final cubit = BlogPostCreateCubit(blogPostRepository: mockBlogPostRepository); + final cubit = BlogPostCreateCubit(blogPostRepository: blogPostRepository); // Assert expect(cubit, isA()); diff --git a/test/features/blog_post_create/integration_widget_test.dart b/test/features/blog_post_create/integration_widget_test.dart index 40827f21..d4fd63f8 100644 --- a/test/features/blog_post_create/integration_widget_test.dart +++ b/test/features/blog_post_create/integration_widget_test.dart @@ -2,34 +2,29 @@ import 'package:eatvio_app/app_keys.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_cubit.dart'; import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_state.dart'; -import 'package:eatvio_app/features/blog_post_create/repositories/blog_post_repository.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; -import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; -import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; -import 'integration_widget_test.mocks.dart'; +import '../../fixtures/doubles/blog_post_doubles.dart'; +import '../../fixtures/fixture_reader.dart'; -@GenerateMocks([BlogPostRepository, FeedCubit]) void main() { group('Blog Post Creation Integration Widget Tests', () { - late MockBlogPostRepository mockBlogPostRepository; - late MockFeedCubit mockFeedCubit; + late FixtureBlogPostRepository blogPostRepository; late BlogPostCreateCubit blogPostCreateCubit; + late FeedReloadProbe feedProbe; + late Map fullCreateFixture; + late Map updateFixture; setUp(() { - mockBlogPostRepository = MockBlogPostRepository(); - mockFeedCubit = MockFeedCubit(); - blogPostCreateCubit = BlogPostCreateCubit(blogPostRepository: mockBlogPostRepository); - - // Setup mock stubs for FeedCubit - when(mockFeedCubit.stream).thenAnswer((_) => Stream.value(const FeedState.loading())); - when(mockFeedCubit.close()).thenAnswer((_) async {}); + blogPostRepository = FixtureBlogPostRepository(); + blogPostCreateCubit = BlogPostCreateCubit(blogPostRepository: blogPostRepository); + feedProbe = FeedReloadProbe(); + fullCreateFixture = FixtureReader.readAsMap('blog_post_create/create_request_full.json'); + updateFixture = FixtureReader.readAsMap('blog_post_create/update_request.json'); }); tearDown(() { @@ -39,11 +34,8 @@ void main() { Widget createTestWidget(Widget child) { return MaterialApp( theme: ThemeHelper().themeData(), - home: MultiBlocProvider( - providers: [ - BlocProvider(create: (context) => blogPostCreateCubit), - BlocProvider(create: (context) => mockFeedCubit), - ], + home: BlocProvider.value( + value: blogPostCreateCubit, child: Scaffold(body: SingleChildScrollView(child: child)), ), ); @@ -51,13 +43,10 @@ void main() { testWidgets('should complete full blog post creation flow', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenAnswer((_) async {}); - when(mockFeedCubit.loadFeedBlogPostList()).thenAnswer((_) async {}); - Widget fullFlowWidget = BlocListener( listener: (context, state) { if (state is BlogPostCreateStateLoaded) { - context.read().loadFeedBlogPostList(); + feedProbe.loadFeedBlogPostList(); } }, child: Column( @@ -106,9 +95,9 @@ void main() { key: AppKeys.blogPostCreateScreenCreateButton, onPressed: () async { await blogPostCreateCubit.createBlogPost( - title: 'Integration Test Title', - videoUrl: 'https://youtube.com/watch?v=integration', - description: 'Integration Test Description', + title: fullCreateFixture['title'] as String?, + videoUrl: fullCreateFixture['video_url'] as String?, + description: fullCreateFixture['description_md'] as String?, image: null, ); }, @@ -122,26 +111,21 @@ void main() { await tester.pumpWidget(createTestWidget(fullFlowWidget)); await tester.pumpAndSettle(); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), 'Integration Test Title'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), 'Integration Test Description'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), 'https://youtube.com/watch?v=integration'); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), fullCreateFixture['title'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), fullCreateFixture['description_md'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), fullCreateFixture['video_url'] as String); await tester.pump(); await tester.tap(find.byKey(AppKeys.blogPostCreateScreenCreateButton)); await tester.pump(); // Assert - verify( - mockBlogPostRepository.createBlogPost('Integration Test Title', 'https://youtube.com/watch?v=integration', 'Integration Test Description', null), - ).called(1); - verify(mockFeedCubit.loadFeedBlogPostList()).called(1); + expect(blogPostRepository.createPayloads.single.toJson(), fullCreateFixture); + expect(feedProbe.loadRequests, 1); }); testWidgets('should handle blog post update flow', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.updateBlogPost(any, any, any, any, any, any)).thenAnswer((_) async {}); - when(mockFeedCubit.loadFeedBlogPostList()).thenAnswer((_) async {}); - final existingBlogPost = FeedBlogPostModel( id: 1, state: 'published', @@ -161,7 +145,7 @@ void main() { Widget updateFlowWidget = BlocListener( listener: (context, state) { if (state is BlogPostCreateStateLoaded) { - context.read().loadFeedBlogPostList(); + feedProbe.loadFeedBlogPostList(); } }, child: Column( @@ -190,12 +174,12 @@ void main() { key: AppKeys.blogPostCreateScreenCreateButton, onPressed: () async { await blogPostCreateCubit.updateBlogPost( - id: existingBlogPost.id, - title: 'Updated Title', - videoUrl: 'https://youtube.com/watch?v=updated', - description: 'Updated Description', + id: updateFixture['id'] as int, + title: updateFixture['title'] as String?, + videoUrl: updateFixture['video_url'] as String?, + description: updateFixture['description_md'] as String?, image: null, - oldImageUrl: existingBlogPost.image, + oldImageUrl: updateFixture['old_image_url'] as String?, ); }, child: const Text('Обновить'), @@ -208,26 +192,21 @@ void main() { await tester.pumpWidget(createTestWidget(updateFlowWidget)); await tester.pumpAndSettle(); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), 'Updated Title'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), 'Updated Description'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), 'https://youtube.com/watch?v=updated'); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), updateFixture['title'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), updateFixture['description_md'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), updateFixture['video_url'] as String); await tester.pump(); await tester.tap(find.byKey(AppKeys.blogPostCreateScreenCreateButton)); await tester.pump(); // Assert - verify( - mockBlogPostRepository.updateBlogPost(1, 'Updated Title', 'https://youtube.com/watch?v=updated', 'Updated Description', null, 'original_image.jpg'), - ).called(1); - verify(mockFeedCubit.loadFeedBlogPostList()).called(1); + expect(blogPostRepository.updatePayloads.single.toJson(), updateFixture); + expect(feedProbe.loadRequests, 1); }); testWidgets('should handle blog post deletion flow', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.deleteBlogPost(any)).thenAnswer((_) async {}); - when(mockFeedCubit.loadFeedBlogPostList()).thenAnswer((_) async {}); - Widget deleteFlowWidget = Column( children: [ const Text('Удалить блог пост?'), @@ -236,7 +215,7 @@ void main() { key: const Key('deleteBlogPostButton'), onPressed: () async { await blogPostCreateCubit.deleteBlogPost(1); - mockFeedCubit.loadFeedBlogPostList(); + feedProbe.loadFeedBlogPostList(); }, child: const Text('Удалить'), ), @@ -251,13 +230,14 @@ void main() { await tester.pump(); // Assert - verify(mockBlogPostRepository.deleteBlogPost(1)).called(1); - verify(mockFeedCubit.loadFeedBlogPostList()).called(1); + final deleteFixture = FixtureReader.readAsMap('blog_post_create/delete_request.json'); + expect(blogPostRepository.deleteCalls.single, deleteFixture['id']); + expect(feedProbe.loadRequests, 1); }); testWidgets('should handle error flow during blog post creation', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenThrow(Exception('Network error')); + blogPostRepository.createError = Exception('Network error'); Widget errorFlowWidget = BlocBuilder( builder: (context, state) { @@ -285,7 +265,12 @@ void main() { await tester.pumpAndSettle(); // Trigger error - await blogPostCreateCubit.createBlogPost(title: 'Test Title', videoUrl: null, description: 'Test Description', image: null); + await blogPostCreateCubit.createBlogPost( + title: fullCreateFixture['title'] as String?, + videoUrl: null, + description: fullCreateFixture['description_md'] as String?, + image: null, + ); await tester.pump(); // Assert @@ -295,9 +280,7 @@ void main() { testWidgets('should handle loading state during blog post creation', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenAnswer((_) async { - await Future.delayed(const Duration(milliseconds: 50)); - }); + blogPostRepository.createDelay = const Duration(milliseconds: 50); Widget loadingFlowWidget = BlocBuilder( builder: (context, state) { @@ -313,7 +296,12 @@ void main() { await tester.pumpAndSettle(); // Trigger loading - blogPostCreateCubit.createBlogPost(title: 'Test Title', videoUrl: null, description: 'Test Description', image: null); + blogPostCreateCubit.createBlogPost( + title: fullCreateFixture['title'] as String?, + videoUrl: null, + description: fullCreateFixture['description_md'] as String?, + image: null, + ); await tester.pump(); await tester.pump(); // Need to pump twice to get the loading state @@ -328,13 +316,10 @@ void main() { testWidgets('should handle success state after blog post creation', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenAnswer((_) async {}); - when(mockFeedCubit.loadFeedBlogPostList()).thenAnswer((_) async {}); - Widget successFlowWidget = BlocListener( listener: (context, state) { if (state is BlogPostCreateStateLoaded) { - context.read().loadFeedBlogPostList(); + feedProbe.loadFeedBlogPostList(); } }, child: BlocBuilder( @@ -358,13 +343,18 @@ void main() { await tester.pumpAndSettle(); // Trigger success - await blogPostCreateCubit.createBlogPost(title: 'Test Title', videoUrl: null, description: 'Test Description', image: null); + await blogPostCreateCubit.createBlogPost( + title: fullCreateFixture['title'] as String?, + videoUrl: null, + description: fullCreateFixture['description_md'] as String?, + image: null, + ); await tester.pump(); // Assert expect(find.byIcon(Icons.check_circle), findsOneWidget); expect(find.text('Блог пост успешно создан!'), findsOneWidget); - verify(mockFeedCubit.loadFeedBlogPostList()).called(1); + expect(feedProbe.loadRequests, 1); }); testWidgets('should handle form validation flow', (WidgetTester tester) async { @@ -462,13 +452,10 @@ void main() { testWidgets('should handle complete blog post creation with all features', (WidgetTester tester) async { // Arrange - when(mockBlogPostRepository.createBlogPost(any, any, any, any)).thenAnswer((_) async {}); - when(mockFeedCubit.loadFeedBlogPostList()).thenAnswer((_) async {}); - Widget completeFlowWidget = BlocListener( listener: (context, state) { if (state is BlogPostCreateStateLoaded) { - context.read().loadFeedBlogPostList(); + feedProbe.loadFeedBlogPostList(); } }, child: Column( @@ -517,9 +504,9 @@ void main() { key: AppKeys.blogPostCreateScreenCreateButton, onPressed: () async { await blogPostCreateCubit.createBlogPost( - title: 'Complete Test Title', - videoUrl: 'https://youtube.com/watch?v=complete', - description: 'Complete Test Description', + title: fullCreateFixture['title'] as String?, + videoUrl: fullCreateFixture['video_url'] as String?, + description: fullCreateFixture['description_md'] as String?, image: null, ); }, @@ -533,9 +520,9 @@ void main() { await tester.pumpWidget(createTestWidget(completeFlowWidget)); await tester.pumpAndSettle(); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), 'Complete Test Title'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), 'Complete Test Description'); - await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), 'https://youtube.com/watch?v=complete'); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenTitleTextField), fullCreateFixture['title'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenContentTextField), fullCreateFixture['description_md'] as String); + await tester.enterText(find.byKey(AppKeys.blogPostCreateScreenVideoLinkTextField), fullCreateFixture['video_url'] as String); await tester.pump(); // Scroll to make sure the button is visible @@ -546,8 +533,8 @@ void main() { await tester.pump(); // Assert - verify(mockBlogPostRepository.createBlogPost('Complete Test Title', 'https://youtube.com/watch?v=complete', 'Complete Test Description', null)).called(1); - verify(mockFeedCubit.loadFeedBlogPostList()).called(1); + expect(blogPostRepository.createPayloads.single.toJson(), fullCreateFixture); + expect(feedProbe.loadRequests, 1); }); }); } diff --git a/test/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit_test.dart b/test/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit_test.dart new file mode 100644 index 00000000..c17e05bf --- /dev/null +++ b/test/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit_test.dart @@ -0,0 +1,42 @@ +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('NewMessagesCubit', () { + late NewMessagesCubit newMessagesCubit; + + setUp(() { + newMessagesCubit = NewMessagesCubit(); + }); + + tearDown(() async { + if (!newMessagesCubit.isClosed) { + await newMessagesCubit.close(); + } + }); + + test('начальное состояние - NewMessagesState.empty', () { + expect(newMessagesCubit.state, const NewMessagesState.empty()); + }); + + test('incrementCounter - увеличивает счётчик сообщений', () { + newMessagesCubit.incrementCounter(); + + expect(newMessagesCubit.state, isA()); + final loadedState = newMessagesCubit.state as NewMessagesStateLoaded; + expect(loadedState.messagesCount, 1); + }); + + test('incrementCounter - увеличивает счётчик несколько раз', () { + newMessagesCubit.incrementCounter(); + newMessagesCubit.incrementCounter(); + newMessagesCubit.incrementCounter(); + + expect(newMessagesCubit.state, isA()); + final loadedState = newMessagesCubit.state as NewMessagesStateLoaded; + expect(loadedState.messagesCount, 3); + }); + }); +} + diff --git a/test/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit_test.dart b/test/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit_test.dart new file mode 100644 index 00000000..a27f0bef --- /dev/null +++ b/test/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit_test.dart @@ -0,0 +1,130 @@ +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_profile_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +import '../../../../../fixtures/fixture_reader.dart'; + +class MockConsultantRepository extends Mock implements ConsultantRepository {} + +void main() { + setUpAll(() { + registerFallbackValue(const ConsultantProfileModel()); + registerFallbackValue(''); + registerFallbackValue(false); + registerFallbackValue(0); + }); + + group('RegisterConsultantCubit', () { + late MockConsultantRepository repository; + late RegisterConsultantCubit cubit; + late ConsultationRequestModel requestModel; + late List certPhotosFromFixture; + late ConsultantProfileModel consultantProfile; + + setUp(() { + repository = MockConsultantRepository(); + cubit = RegisterConsultantCubit(consultantRepository: repository); + requestModel = ConsultationRequestModel.fromJson(FixtureReader.readAsMap('consultant/consultation_request.json')); + certPhotosFromFixture = FixtureReader.readAsList( + 'consultant/consultant_cert_photos.json', + ).map((item) => ConsultantCertPhotoModel.fromJson(item as Map)).toList(); + consultantProfile = ConsultantProfileModel.fromJson(FixtureReader.readAsMap('consultant/consultant_profile_request.json')); + }); + + tearDown(() async { + await cubit.close(); + }); + + test('initial state has loading=true and default consultant model', () { + expect(cubit.state.loading, isTrue); + expect(cubit.state.consultant.hasMedicalEducation, isTrue); + expect(cubit.state.acceptOffer, isFalse); + expect(cubit.state.requestModel, isNull); + }); + + test('getMyRequestStatus hydrates state with backend data and visible certificates only', () async { + when(() => repository.getMyRequestStatus(any())).thenAnswer((_) async => requestModel); + when(() => repository.getConsultantCertPhotos()).thenAnswer((_) async => certPhotosFromFixture); + + await cubit.getMyRequestStatus('my-consultant-slug'); + + final state = cubit.state; + expect(state.loading, isFalse); + expect(state.requestModel, equals(requestModel)); + expect(state.consultant.certificates, isNotNull); + expect(state.consultant.certificates, hasLength(2)); + expect(state.consultant.certificates!.first.title, 'Нутрициология PRO'); + expect(state.consultant.socialLinks?.instaLink, isNull, reason: 'empty links are sanitized'); + expect(state.consultant.socialLinks?.vkLink, 'https://vk.com/consultant'); + expect(state.certPhotos, hasLength(2)); + expect(state.certPhotos.map((e) => e.id), containsAll([101, 103])); + verify(() => repository.getMyRequestStatus('my-consultant-slug')).called(1); + verify(() => repository.getConsultantCertPhotos()).called(1); + }); + + test('disableLoading stops spinner and loads visible cert photos', () async { + when(() => repository.getConsultantCertPhotos()).thenAnswer((_) async => certPhotosFromFixture); + + await cubit.disableLoading(); + + expect(cubit.state.loading, isFalse); + expect(cubit.state.certPhotos, hasLength(2)); + verify(() => repository.getConsultantCertPhotos()).called(1); + }); + + test('updateConsultantProfileModel replaces consultant data and offer flag', () { + cubit.updateConsultantProfileModel(consultantProfile, true); + + expect(cubit.state.consultant, consultantProfile); + expect(cubit.state.acceptOffer, isTrue); + expect(cubit.state.loading, isFalse); + }); + + test('registerConsultant forwards payload with update=false by default', () async { + when( + () => repository.registerConsultant( + consultant: any(named: 'consultant'), + update: any(named: 'update'), + ), + ).thenAnswer((_) async {}); + + await cubit.registerConsultant(); + + verify(() => repository.registerConsultant(consultant: cubit.state.consultant, update: false)).called(1); + }); + + test('registerConsultant sends update=true after getMyRequestStatus call', () async { + when(() => repository.getMyRequestStatus(any())).thenAnswer((_) async => requestModel); + when(() => repository.getConsultantCertPhotos()).thenAnswer((_) async => certPhotosFromFixture); + when( + () => repository.registerConsultant( + consultant: any(named: 'consultant'), + update: any(named: 'update'), + ), + ).thenAnswer((_) async {}); + + await cubit.getMyRequestStatus('my-consultant-slug'); + await cubit.registerConsultant(); + + verify(() => repository.registerConsultant(consultant: cubit.state.consultant, update: true)).called(1); + }); + + test('removeCertPhoto hides cert locally after repository call', () async { + when(() => repository.getMyRequestStatus(any())).thenAnswer((_) async => requestModel); + when(() => repository.getConsultantCertPhotos()).thenAnswer((_) async => certPhotosFromFixture); + when(() => repository.hideConsultantCertPhoto(any())).thenAnswer((_) async {}); + + await cubit.getMyRequestStatus('my-consultant-slug'); + expect(cubit.state.certPhotos, hasLength(2)); + + await cubit.removeCertPhoto(101); + + verify(() => repository.hideConsultantCertPhoto(101)).called(1); + expect(cubit.state.certPhotos.any((photo) => photo.id == 101), isFalse); + }); + }); +} diff --git a/test/features/consultant/become_consultant/repositories/consultant_repository_test.dart b/test/features/consultant/become_consultant/repositories/consultant_repository_test.dart new file mode 100644 index 00000000..c695cc5b --- /dev/null +++ b/test/features/consultant/become_consultant/repositories/consultant_repository_test.dart @@ -0,0 +1,129 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_profile_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/services/consultant_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +import '../../../../fixtures/fixture_reader.dart'; + +class MockConsultantService extends Mock implements ConsultantService {} + +class MockFile extends Mock implements File {} + +void main() { + setUpAll(() { + registerFallbackValue(const ConsultantProfileModel()); + registerFallbackValue([]); + registerFallbackValue({}); + registerFallbackValue(''); + registerFallbackValue(false); + registerFallbackValue(0); + }); + + group('ConsultantRepository', () { + late ConsultantRepository repository; + late MockConsultantService mockService; + late ConsultantProfileModel consultantProfile; + late ConsultationRequestModel consultationRequest; + late List certPhotos; + + setUp(() { + mockService = MockConsultantService(); + repository = ConsultantRepository(consultantService: mockService); + consultantProfile = ConsultantProfileModel.fromJson(FixtureReader.readAsMap('consultant/consultant_profile_request.json')); + consultationRequest = ConsultationRequestModel.fromJson(FixtureReader.readAsMap('consultant/consultation_request.json')); + certPhotos = FixtureReader.readAsList('consultant/consultant_cert_photos.json') + .map((item) => ConsultantCertPhotoModel.fromJson(item as Map)) + .toList(); + }); + + test('registerConsultant delegates to consultantRegistration when update=false', () async { + when(() => mockService.consultantRegistration(consultantModel: any(named: 'consultantModel'))).thenAnswer((_) async {}); + + await repository.registerConsultant(consultant: consultantProfile); + + verify(() => mockService.consultantRegistration(consultantModel: consultantProfile)).called(1); + verifyNever(() => mockService.consultantUpdate(consultantModel: any(named: 'consultantModel'))); + }); + + test('registerConsultant delegates to consultantUpdate when update=true', () async { + when(() => mockService.consultantUpdate(consultantModel: any(named: 'consultantModel'))).thenAnswer((_) async {}); + + await repository.registerConsultant(consultant: consultantProfile, update: true); + + verify(() => mockService.consultantUpdate(consultantModel: consultantProfile)).called(1); + verifyNever(() => mockService.consultantRegistration(consultantModel: any(named: 'consultantModel'))); + }); + + test('getConsultantRequestStatus returns request from service', () async { + when(() => mockService.getConsultantRequestStatus(slug: any(named: 'slug'))).thenAnswer((_) async => consultationRequest); + + final result = await repository.getConsultantRequestStatus('user-slug'); + + expect(result, equals(consultationRequest)); + verify(() => mockService.getConsultantRequestStatus(slug: 'user-slug')).called(1); + }); + + test('getMyRequestStatus returns request from service', () async { + when(() => mockService.getMyRequestStatus(slug: any(named: 'slug'))).thenAnswer((_) async => consultationRequest); + + final result = await repository.getMyRequestStatus('my-slug'); + + expect(result, equals(consultationRequest)); + verify(() => mockService.getMyRequestStatus(slug: 'my-slug')).called(1); + }); + + test('getConsultantCertPhotos returns photos from service', () async { + when(() => mockService.getConsultantCertPhotos()).thenAnswer((_) async => certPhotos); + + final result = await repository.getConsultantCertPhotos(); + + expect(result, certPhotos); + verify(() => mockService.getConsultantCertPhotos()).called(1); + }); + + test('storeConsultantCertPhotos returns empty list when no files provided', () async { + final result = await repository.storeConsultantCertPhotos(files: []); + + expect(result, isEmpty); + verifyNever(() => mockService.storeConsultantCertPhotos(photos: any>(named: 'photos'))); + }); + + test('storeConsultantCertPhotos uploads prepared files and returns response', () async { + final mockFile = MockFile(); + when(() => mockFile.readAsBytes()).thenAnswer((_) async => Uint8List.fromList([1, 2, 3])); + when(() => mockFile.path).thenReturn('/tmp/certificate.png'); + when(() => mockService.storeConsultantCertPhotos(photos: any>(named: 'photos'))).thenAnswer((_) async => certPhotos); + + final result = await repository.storeConsultantCertPhotos(files: [mockFile]); + + expect(result, certPhotos); + final capturedArgument = verify(() => mockService.storeConsultantCertPhotos(photos: captureAny>(named: 'photos'))).captured.single as List; + expect(capturedArgument, hasLength(1)); + expect(capturedArgument.first.filename, 'certificate.png'); + }); + + test('hideConsultantCertPhoto sends payload to service', () async { + when(() => mockService.hideConsultantCertPhoto(payload: any>(named: 'payload'))).thenAnswer((_) async {}); + + await repository.hideConsultantCertPhoto(42); + + verify(() => mockService.hideConsultantCertPhoto(payload: {'cert_photo_id': 42})).called(1); + }); + + test('unHideConsultantCertPhoto sends payload to service', () async { + when(() => mockService.unHideConsultantCertPhoto(payload: any>(named: 'payload'))).thenAnswer((_) async {}); + + await repository.unHideConsultantCertPhoto(7); + + verify(() => mockService.unHideConsultantCertPhoto(payload: {'cert_photo_id': 7})).called(1); + }); + }); +} + diff --git a/test/features/create_diet/basic_widget_test.dart b/test/features/create_diet/basic_widget_test.dart index c027b90e..27dd8faf 100644 --- a/test/features/create_diet/basic_widget_test.dart +++ b/test/features/create_diet/basic_widget_test.dart @@ -1,31 +1,34 @@ +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_cubit.dart'; -import 'package:eatvio_app/features/create_diet/repositories/create_diet_repository.dart'; -import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; -import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'basic_widget_test.mocks.dart'; +import '../../fixtures/doubles/create_diet_doubles.dart'; -@GenerateMocks([CreateDietRepository, ProfileRepository, GlossaryRepository]) void main() { group('Diet Creation Basic Widget Tests', () { - late MockCreateDietRepository mockCreateDietRepository; - late MockProfileRepository mockProfileRepository; - late MockGlossaryRepository mockGlossaryRepository; + late FixtureCreateDietRepository createDietRepository; + late FixtureProfileRepository profileRepository; + late FixtureGlossaryRepository glossaryRepository; late CreateDietCubit createDietCubit; - setUp(() { - mockCreateDietRepository = MockCreateDietRepository(); - mockProfileRepository = MockProfileRepository(); - mockGlossaryRepository = MockGlossaryRepository(); + setUp(() async { + // Initialize AppConfig for tests to enable compression bypass + await sl.reset(); + dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); + sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + createDietRepository = FixtureCreateDietRepository(); + profileRepository = FixtureProfileRepository(); + glossaryRepository = FixtureGlossaryRepository(); createDietCubit = CreateDietCubit( - createDietRepository: mockCreateDietRepository, - profileRepository: mockProfileRepository, - glossaryRepository: mockGlossaryRepository, + createDietRepository: createDietRepository, + profileRepository: profileRepository, + glossaryRepository: glossaryRepository, ); }); @@ -46,9 +49,9 @@ void main() { testWidgets('should create CreateDietCubit successfully', (WidgetTester tester) async { // Arrange & Act final cubit = CreateDietCubit( - createDietRepository: mockCreateDietRepository, - profileRepository: mockProfileRepository, - glossaryRepository: mockGlossaryRepository, + createDietRepository: createDietRepository, + profileRepository: profileRepository, + glossaryRepository: glossaryRepository, ); // Assert @@ -480,5 +483,6 @@ void main() { expect(find.text('• 21 день - трехнедельная диета'), findsOneWidget); expect(find.text('• 30 дней - месячная диета'), findsOneWidget); }); + }); } diff --git a/test/features/create_plan/advanced_widget_test.dart b/test/features/create_plan/advanced_widget_test.dart index 3a5a9c43..2a0530a7 100644 --- a/test/features/create_plan/advanced_widget_test.dart +++ b/test/features/create_plan/advanced_widget_test.dart @@ -9,26 +9,20 @@ import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_c import 'package:eatvio_app/features/create_plan/presentation/widgets/plan_duration_drop_down_widget.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/plan_type_choice_widget.dart'; import 'package:eatvio_app/features/create_plan/presentation/widgets/option_widget.dart'; -import 'package:eatvio_app/features/create_plan/repositories/create_plan_repository.dart'; -import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; -import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'advanced_widget_test.mocks.dart'; +import '../../fixtures/doubles/create_plan_doubles.dart'; -@GenerateMocks([CreatePlanRepository, ProfileRepository, GlossaryRepository]) void main() { group('Meal Plan Creation Advanced Widget Tests', () { - late MockCreatePlanRepository mockCreatePlanRepository; + late FixtureCreatePlanRepository createPlanRepository; late CreatePlanCubit createPlanCubit; - setUp(() async { await sl.reset(); - mockCreatePlanRepository = MockCreatePlanRepository(); - createPlanCubit = CreatePlanCubit(createPlanRepository: mockCreatePlanRepository); + createPlanRepository = FixtureCreatePlanRepository(); + createPlanCubit = CreatePlanCubit(createPlanRepository: createPlanRepository); sl.registerLazySingleton(() => createPlanCubit); AppConfigRegistration.registerAppConfig(buildType: AppBuildType.tests); }); diff --git a/test/features/create_plan/basic_widget_test.dart b/test/features/create_plan/basic_widget_test.dart index 80399e9b..1c33d588 100644 --- a/test/features/create_plan/basic_widget_test.dart +++ b/test/features/create_plan/basic_widget_test.dart @@ -1,24 +1,22 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_cubit.dart'; -import 'package:eatvio_app/features/create_plan/repositories/create_plan_repository.dart'; -import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; -import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'basic_widget_test.mocks.dart'; +import '../../fixtures/doubles/create_plan_doubles.dart'; +import '../../fixtures/fixture_reader.dart'; -@GenerateMocks([CreatePlanRepository, ProfileRepository, GlossaryRepository]) void main() { group('Meal Plan Creation Basic Widget Tests', () { - late MockCreatePlanRepository mockCreatePlanRepository; + late FixtureCreatePlanRepository createPlanRepository; late CreatePlanCubit createPlanCubit; + late Map planFixture; setUp(() { - mockCreatePlanRepository = MockCreatePlanRepository(); - createPlanCubit = CreatePlanCubit(createPlanRepository: mockCreatePlanRepository); + planFixture = FixtureReader.readAsMap('create_plan/create_plan_request.json'); + createPlanRepository = FixtureCreatePlanRepository(); + createPlanCubit = CreatePlanCubit(createPlanRepository: createPlanRepository); }); tearDown(() { @@ -37,7 +35,7 @@ void main() { testWidgets('should create CreatePlanCubit successfully', (WidgetTester tester) async { // Arrange & Act - final cubit = CreatePlanCubit(createPlanRepository: mockCreatePlanRepository); + final cubit = CreatePlanCubit(createPlanRepository: createPlanRepository); // Assert expect(cubit, isA()); @@ -98,7 +96,7 @@ void main() { await tester.pumpWidget(createTestWidget(formWidget)); await tester.pumpAndSettle(); - const testName = 'Тестовый план питания'; + final testName = planFixture['name'] as String; // Act await tester.enterText(find.byKey(const Key('planNameField')), testName); @@ -119,7 +117,7 @@ void main() { await tester.pumpWidget(createTestWidget(formWidget)); await tester.pumpAndSettle(); - const testDescription = 'Это тестовое описание плана питания для здорового образа жизни'; + final testDescription = planFixture['description'] as String; // Act await tester.enterText(find.byKey(const Key('planDescriptionField')), testDescription); @@ -583,5 +581,6 @@ void main() { expect(find.byKey(const Key('basicOptionContainer')), findsOneWidget); expect(find.byKey(const Key('premiumOptionContainer')), findsOneWidget); }); + }); } diff --git a/test/features/create_plan/integration_widget_test.dart b/test/features/create_plan/integration_widget_test.dart index 5a9e09b7..9ec3b2ad 100644 --- a/test/features/create_plan/integration_widget_test.dart +++ b/test/features/create_plan/integration_widget_test.dart @@ -1,11 +1,8 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/create_plan/presentation/cubit/create_plan_cubit.dart'; import 'package:eatvio_app/features/create_plan/presentation/create_plan_screen.dart'; -import 'package:eatvio_app/features/create_plan/repositories/create_plan_repository.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; -import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; -import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:eatvio_app/generated/l10n.dart'; @@ -13,20 +10,18 @@ import 'package:eatvio_app/core/locator_service.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'integration_widget_test.mocks.dart'; +import '../../fixtures/doubles/create_plan_doubles.dart'; -@GenerateMocks([CreatePlanRepository, ProfileRepository, GlossaryRepository]) void main() { group('Meal Plan Creation Integration Widget Tests', () { - late MockCreatePlanRepository mockCreatePlanRepository; + late FixtureCreatePlanRepository createPlanRepository; late CreatePlanCubit createPlanCubit; setUp(() async { await sl.reset(); - mockCreatePlanRepository = MockCreatePlanRepository(); - createPlanCubit = CreatePlanCubit(createPlanRepository: mockCreatePlanRepository); + createPlanRepository = FixtureCreatePlanRepository(); + createPlanCubit = CreatePlanCubit(createPlanRepository: createPlanRepository); sl.registerLazySingleton(() => createPlanCubit); }); diff --git a/test/features/feed/presentation/bloc/consultants_cubit/consultants_cubit_test.dart b/test/features/feed/presentation/bloc/consultants_cubit/consultants_cubit_test.dart new file mode 100644 index 00000000..a2abb430 --- /dev/null +++ b/test/features/feed/presentation/bloc/consultants_cubit/consultants_cubit_test.dart @@ -0,0 +1,103 @@ +import 'package:eatvio_app/features/feed/models/feed_consultant_model.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/consultants_cubit/consultants_cubit.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/consultants_cubit/consultants_state.dart'; +import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'consultants_cubit_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('ConsultantsCubit', () { + late ConsultantsCubit consultantsCubit; + late MockFeedRepository mockFeedRepository; + + setUp(() { + mockFeedRepository = MockFeedRepository(); + consultantsCubit = ConsultantsCubit(feedRepository: mockFeedRepository); + }); + + tearDown(() async { + if (!consultantsCubit.isClosed) { + await consultantsCubit.close(); + } + }); + + test('начальное состояние - ConsultantsState', () { + expect(consultantsCubit.state, const ConsultantsState()); + }); + + test('getConsultants - успешная загрузка консультантов', () async { + final testConsultants = [ + const FeedConsultantModel( + slug: 'consultant-1', + name: 'Консультант 1', + description: 'Описание консультанта 1', + totalScores: 100, + photo: 'https://example.com/icon1.jpg', + badges: [], + ratingPlace: 1, + ), + const FeedConsultantModel( + slug: 'consultant-2', + name: 'Консультант 2', + description: 'Описание консультанта 2', + totalScores: 200, + photo: 'https://example.com/icon2.jpg', + badges: [], + ratingPlace: 2, + ), + ]; + + when(mockFeedRepository.getConsultants()).thenAnswer((_) async => testConsultants); + + await consultantsCubit.getConsultants(); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(consultantsCubit.state, isA()); + final loadedState = consultantsCubit.state as ConsultantsStateLoaded; + expect(loadedState.consultantsList.length, 2); + expect(loadedState.isLoading, false); + verify(mockFeedRepository.getConsultants()).called(1); + }); + + test('getConsultants - переход в состояние loading', () async { + when(mockFeedRepository.getConsultants()).thenAnswer((_) async { + await Future.delayed(const Duration(milliseconds: 50)); + return []; + }); + + final future = consultantsCubit.getConsultants(); + await Future.delayed(const Duration(milliseconds: 10)); + + expect(consultantsCubit.state, const ConsultantsState.loading()); + await future; + }); + + test('getConsultants - обработка ошибки', () async { + when(mockFeedRepository.getConsultants()).thenThrow(Exception('Ошибка загрузки')); + + await consultantsCubit.getConsultants(); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(consultantsCubit.state, isA()); + final errorState = consultantsCubit.state as ConsultantsStateError; + expect(errorState.errorMessage, contains('Exception')); + }); + + test('getConsultants - загрузка с пустым списком', () async { + when(mockFeedRepository.getConsultants()).thenAnswer((_) async => []); + + await consultantsCubit.getConsultants(); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(consultantsCubit.state, isA()); + final loadedState = consultantsCubit.state as ConsultantsStateLoaded; + expect(loadedState.consultantsList, isEmpty); + expect(loadedState.isLoading, false); + }); + }); +} + diff --git a/test/features/feed/presentation/bloc/feed_cubit/feed_cubit_test.dart b/test/features/feed/presentation/bloc/feed_cubit/feed_cubit_test.dart new file mode 100644 index 00000000..15cfaa79 --- /dev/null +++ b/test/features/feed/presentation/bloc/feed_cubit/feed_cubit_test.dart @@ -0,0 +1,223 @@ +import 'package:eatvio_app/core/models/pagination_model.dart'; +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; +import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:eatvio_app/features/feed/models/feed_blog_post_settings_model.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart'; +import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'feed_cubit_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('FeedCubit', () { + FeedCubit? feedCubit; + late MockFeedRepository mockFeedRepository; + late FeedBlogPostSettingsModel feedBlogPostsFixture; + + setUp(() { + mockFeedRepository = MockFeedRepository(); + + // Создаём тестовые данные + final testPosts = [ + FeedBlogPostModel( + id: 1, + state: 'published', + image: 'https://example.com/image1.jpg', + description: 'Описание поста 1', + author: const Author( + authorSlug: 'author-1', + authorName: 'Автор 1', + authorProfileIcon: 'https://example.com/photo1.jpg', + authorIsMe: false, + isEntitySubscribedByMe: null, + authorPlaceInRating: null, + ), + videoUrl: '', + createdAt: DateTime.now(), + updatedAt: DateTime.now(), + title: 'Тестовый пост 1', + totalLikes: 10, + totalViews: 100, + totalComments: 5, + wasLikedByMe: false, + ), + FeedBlogPostModel( + id: 2, + state: 'published', + image: 'https://example.com/image2.jpg', + description: 'Описание поста 2', + author: const Author( + authorSlug: 'author-2', + authorName: 'Автор 2', + authorProfileIcon: 'https://example.com/photo2.jpg', + authorIsMe: false, + isEntitySubscribedByMe: null, + authorPlaceInRating: null, + ), + videoUrl: '', + createdAt: DateTime.now(), + updatedAt: DateTime.now(), + title: 'Тестовый пост 2', + totalLikes: 20, + totalViews: 200, + totalComments: 10, + wasLikedByMe: true, + ), + ]; + + feedBlogPostsFixture = FeedBlogPostSettingsModel( + feedBlogPostList: testPosts, + meta: const Meta( + currentPage: 1, + from: null, + lastPage: 3, + links: [], + path: null, + perPage: 10, + to: null, + total: 25, + totalMinPrice: null, + totalMaxPrice: null, + ), + ); + }); + + tearDown(() async { + if (feedCubit != null && !feedCubit!.isClosed) { + await Future.delayed(const Duration(milliseconds: 100)); + feedCubit!.close(); + feedCubit = null; + } + }); + + test('начальное состояние - FeedStateLoading', () { + feedCubit = FeedCubit(feedRepository: mockFeedRepository); + expect(feedCubit!.state, const FeedState.loading()); + }); + + test('loadFeedBlogPostList - успешная загрузка постов', () async { + feedCubit = FeedCubit(feedRepository: mockFeedRepository); + + when(mockFeedRepository.getFeedBlogPosts(query: null)) + .thenAnswer((_) async => feedBlogPostsFixture); + + await feedCubit!.loadFeedBlogPostList(); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(feedCubit!.state, isA()); + final loadedState = feedCubit!.state as FeedStateLoaded; + expect(loadedState.feedBlogPostList.length, 2); + expect(loadedState.isLoading, false); + expect(feedCubit!.lastPage, 3); + }); + + test('loadFeedBlogPostList - загрузка с запросом', () async { + feedCubit = FeedCubit(feedRepository: mockFeedRepository); + const query = 'тест'; + + when(mockFeedRepository.getFeedBlogPosts(query: query)) + .thenAnswer((_) async => feedBlogPostsFixture); + + await feedCubit!.loadFeedBlogPostList(query: query); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(feedCubit!.state, isA()); + verify(mockFeedRepository.getFeedBlogPosts(query: query)).called(1); + }); + + test('loadFeedBlogPostList - обработка ошибки', () async { + feedCubit = FeedCubit(feedRepository: mockFeedRepository); + + when(mockFeedRepository.getFeedBlogPosts(query: anyNamed('query'))) + .thenThrow(Exception('Ошибка загрузки')); + + await feedCubit!.loadFeedBlogPostList(); + + await Future.delayed(const Duration(milliseconds: 100)); + expect(feedCubit!.state, isA()); + final errorState = feedCubit!.state as FeedStateError; + expect(errorState.errorMessage, contains('Exception')); + }); + + test('updateFeedBlogPostList - обновление лайка поста', () { + feedCubit = FeedCubit(feedRepository: mockFeedRepository); + + // Сначала загружаем посты + when(mockFeedRepository.getFeedBlogPosts(query: anyNamed('query'))) + .thenAnswer((_) async => feedBlogPostsFixture); + + // Устанавливаем состояние loaded вручную для теста + feedCubit!.emit(FeedState.loaded( + feedBlogPostList: feedBlogPostsFixture.feedBlogPostList, + isLoading: false, + )); + feedCubit!.lastPage = 3; + + final postToUpdate = feedBlogPostsFixture.feedBlogPostList.first; + feedCubit!.updateFeedBlogPostList(postToUpdate, true); + + expect(feedCubit!.state, isA()); + final loadedState = feedCubit!.state as FeedStateLoaded; + final updatedPost = loadedState.feedBlogPostList.firstWhere((p) => p.id == postToUpdate.id); + expect(updatedPost.wasLikedByMe, true); + expect(updatedPost.totalLikes, postToUpdate.totalLikes + 1); + }); + + test('updateFeedBlogPostList - снятие лайка', () { + feedCubit = FeedCubit(feedRepository: mockFeedRepository); + + feedCubit!.emit(FeedState.loaded( + feedBlogPostList: feedBlogPostsFixture.feedBlogPostList, + isLoading: false, + )); + feedCubit!.lastPage = 3; + + final postToUpdate = feedBlogPostsFixture.feedBlogPostList[1]; // У этого wasLikedByMe = true + final initialLikes = postToUpdate.totalLikes; + + feedCubit!.updateFeedBlogPostList(postToUpdate, false); + + expect(feedCubit!.state, isA()); + final loadedState = feedCubit!.state as FeedStateLoaded; + final updatedPost = loadedState.feedBlogPostList.firstWhere((p) => p.id == postToUpdate.id); + expect(updatedPost.wasLikedByMe, false); + expect(updatedPost.totalLikes, initialLikes - 1); + }); + + test('updateFeedBlogPostList - игнорирует обновление если состояние не loaded', () { + feedCubit = FeedCubit(feedRepository: mockFeedRepository); + + // Состояние loading + feedCubit!.emit(const FeedState.loading()); + + final postToUpdate = feedBlogPostsFixture.feedBlogPostList.first; + feedCubit!.updateFeedBlogPostList(postToUpdate, true); + + // Состояние не должно измениться + expect(feedCubit!.state, const FeedState.loading()); + }); + + test('updateFeedBlogPostList - игнорирует обновление если пост не найден', () { + feedCubit = FeedCubit(feedRepository: mockFeedRepository); + + feedCubit!.emit(FeedState.loaded( + feedBlogPostList: feedBlogPostsFixture.feedBlogPostList, + isLoading: false, + )); + feedCubit!.lastPage = 3; + + // Создаём пост с несуществующим ID + final nonExistentPost = feedBlogPostsFixture.feedBlogPostList.first.copyWith(id: 999); + feedCubit!.updateFeedBlogPostList(nonExistentPost, true); + + // Список не должен измениться + final loadedState = feedCubit!.state as FeedStateLoaded; + expect(loadedState.feedBlogPostList.length, 2); + }); + }); +} + diff --git a/test/features/feed/repositories/feed_repository_test.dart b/test/features/feed/repositories/feed_repository_test.dart index b5ffb85f..f9f44f8f 100644 --- a/test/features/feed/repositories/feed_repository_test.dart +++ b/test/features/feed/repositories/feed_repository_test.dart @@ -13,6 +13,7 @@ import 'package:eatvio_app/features/feed/services/feed_service.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; + import 'feed_repository_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) @@ -26,37 +27,44 @@ void main() { feedRepository = FeedRepository(feedService: mockFeedService); }); - test('getFeedBlogPosts - возвращает список постов блога', () async { - const page = 1; - const query = 'test query'; - final expectedSettings = FeedBlogPostSettingsModel( - feedBlogPostList: [ - FeedBlogPostModel( - id: 1, - title: 'Test Post', - description: 'Test description', - image: 'https://example.com/image.jpg', - state: 'published', - author: const Author(authorSlug: 'author-1', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false), - videoUrl: 'https://example.com/video.mp4', - createdAt: DateTime(2024, 1, 15), - updatedAt: DateTime(2024, 1, 15), - totalLikes: 10, - totalViews: 100, - totalComments: 5, - wasLikedByMe: false, - ), - ], - meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null), + test('getFeedBlogPosts - успешное получение постов', () async { + const expectedModel = FeedBlogPostSettingsModel( + feedBlogPostList: [], + meta: Meta(currentPage: 1, from: null, lastPage: 1, links: [], path: null, perPage: 10, to: null, total: 0, totalMinPrice: null, totalMaxPrice: null), ); - when(mockFeedService.getBlogPostList(page: page, query: query)).thenAnswer((_) async => expectedSettings); + when(mockFeedService.getBlogPostList(page: 1, query: null)).thenAnswer((_) async => expectedModel); + + final result = await feedRepository.getFeedBlogPosts(); + + expect(result, isA()); + verify(mockFeedService.getBlogPostList(page: 1, query: null)).called(1); + }); + + test('getFeedBlogPosts - с запросом и страницей', () async { + const query = 'тест'; + const page = 2; + const expectedModel = FeedBlogPostSettingsModel( + feedBlogPostList: [], + meta: Meta( + currentPage: page, + from: null, + lastPage: 2, + links: [], + path: null, + perPage: 10, + to: null, + total: 15, + totalMinPrice: null, + totalMaxPrice: null, + ), + ); + + when(mockFeedService.getBlogPostList(page: page, query: query)).thenAnswer((_) async => expectedModel); final result = await feedRepository.getFeedBlogPosts(query: query, page: page); expect(result, isA()); - expect(result.feedBlogPostList.length, 1); - expect(result.feedBlogPostList.first.id, 1); verify(mockFeedService.getBlogPostList(page: page, query: query)).called(1); }); @@ -76,31 +84,38 @@ void main() { verify(mockFeedService.getBlogPostList(page: page, query: null)).called(1); }); - test('getBlogPost - возвращает пост блога по ID', () async { - const id = 1; + test('getBlogPost - успешное получение поста', () async { + const postId = 1; final expectedPost = FeedBlogPostModel( - id: id, - title: 'Test Post', - description: 'Test description', - image: 'https://example.com/image.jpg', + id: postId, state: 'published', - author: const Author(authorSlug: 'author-1', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false), - videoUrl: 'https://example.com/video.mp4', - createdAt: DateTime(2024, 1, 15), - updatedAt: DateTime(2024, 1, 15), + image: 'https://example.com/image.jpg', + description: 'Описание', + author: const Author( + authorSlug: 'author-slug', + authorName: 'Автор', + authorProfileIcon: 'https://example.com/photo.jpg', + authorIsMe: false, + isEntitySubscribedByMe: null, + authorPlaceInRating: null, + ), + videoUrl: '', + createdAt: DateTime.now(), + updatedAt: DateTime.now(), + title: 'Заголовок', totalLikes: 10, totalViews: 100, totalComments: 5, wasLikedByMe: false, ); - when(mockFeedService.getBlogPost(postId: id)).thenAnswer((_) async => expectedPost); + when(mockFeedService.getBlogPost(postId: postId)).thenAnswer((_) async => expectedPost); - final result = await feedRepository.getBlogPost(id: id); + final result = await feedRepository.getBlogPost(id: postId); expect(result, isA()); - expect(result.id, id); - verify(mockFeedService.getBlogPost(postId: id)).called(1); + expect(result.id, postId); + verify(mockFeedService.getBlogPost(postId: postId)).called(1); }); test('getRecipes - возвращает список рецептов', () async { @@ -568,8 +583,8 @@ void main() { verify(mockFeedService.viewPlan(slug: slug)).called(1); }); - test('viewContent - отправляет просмотр контента', () async { - final viewModel = ViewModel(type: 'recipe', slugs: ['recipe-1']); + test('viewContent - успешный просмотр контента', () async { + final viewModel = ViewModel(type: 'blog_post', ids: [1], slugs: null); when(mockFeedService.viewContent(viewModel: viewModel)).thenAnswer((_) async => Future.value()); @@ -588,22 +603,10 @@ void main() { verify(mockFeedService.viewContent(viewModel: viewModel)).called(1); }); - test('getFeedBlogPosts - пробрасывает исключение при ошибке', () async { - const page = 1; - final exception = Exception('Network error'); + test('getFeedBlogPosts - пробрасывает исключение', () async { + when(mockFeedService.getBlogPostList(page: 1, query: null)).thenThrow(Exception('Ошибка сети')); - when(mockFeedService.getBlogPostList(page: page, query: null)).thenThrow(exception); - - expect(() => feedRepository.getFeedBlogPosts(page: page), throwsA(isA())); - }); - - test('getBlogPost - пробрасывает исключение при ошибке', () async { - const id = 1; - final exception = Exception('Not found'); - - when(mockFeedService.getBlogPost(postId: id)).thenThrow(exception); - - expect(() => feedRepository.getBlogPost(id: id), throwsA(isA())); + expect(() => feedRepository.getFeedBlogPosts(), throwsException); }); }); } diff --git a/test/features/menu/presentation/bloc/blocked_users_cubit_test.dart b/test/features/menu/presentation/bloc/blocked_users_cubit_test.dart new file mode 100644 index 00000000..886a9f6c --- /dev/null +++ b/test/features/menu/presentation/bloc/blocked_users_cubit_test.dart @@ -0,0 +1,111 @@ +import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_cubit.dart'; +import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_state.dart'; +import 'package:eatvio_app/features/menu/presentation/repositories/blocked_users_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import '../../../../fixtures/menu_fixtures.dart'; +import 'blocked_users_cubit_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('BlockedUsersCubit', () { + BlockedUsersCubit? blockedUsersCubit; + late MockBlockedUsersRepository mockBlockedUsersRepository; + + setUp(() { + mockBlockedUsersRepository = MockBlockedUsersRepository(); + }); + + tearDown(() async { + if (blockedUsersCubit != null && !blockedUsersCubit!.isClosed) { + await Future.delayed(const Duration(milliseconds: 100)); + blockedUsersCubit!.close(); + blockedUsersCubit = null; + } + }); + + test('начальное состояние - BlockedUsersState', () { + blockedUsersCubit = BlockedUsersCubit( + blockedUsersRepository: mockBlockedUsersRepository, + ); + expect(blockedUsersCubit!.state, const BlockedUsersState()); + }); + + test('getBlockedUsers - успешно загружает список заблокированных пользователей', () async { + blockedUsersCubit = BlockedUsersCubit( + blockedUsersRepository: mockBlockedUsersRepository, + ); + final profilesList = MenuFixtures.blockedUsersList(); + + when(mockBlockedUsersRepository.getBlockedUsers()) + .thenAnswer((_) async => profilesList); + + await blockedUsersCubit!.getBlockedUsers(); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(blockedUsersCubit!.state, isA()); + final loadedState = blockedUsersCubit!.state as BlockedUsersStateLoaded; + expect(loadedState.profilesList.length, 2); + expect(loadedState.profilesList.first.id, 1); + verify(mockBlockedUsersRepository.getBlockedUsers()).called(1); + }); + + test('getBlockedUsers - обрабатывает ошибку', () async { + blockedUsersCubit = BlockedUsersCubit( + blockedUsersRepository: mockBlockedUsersRepository, + ); + + when(mockBlockedUsersRepository.getBlockedUsers()) + .thenThrow(Exception('Ошибка загрузки')); + + await blockedUsersCubit!.getBlockedUsers(); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(blockedUsersCubit!.state, isA()); + final errorState = blockedUsersCubit!.state as BlockedUsersStateError; + expect(errorState.errorMessage, contains('Ошибка загрузки')); + }); + + test('blockUser - блокирует пользователя и обновляет список', () async { + blockedUsersCubit = BlockedUsersCubit( + blockedUsersRepository: mockBlockedUsersRepository, + ); + final blockedUser = MenuFixtures.blockedUser(); + final slug = blockedUser.slug; + final profilesList = MenuFixtures.blockedUsersList(); + + when(mockBlockedUsersRepository.blockUserBySlug(slug)) + .thenAnswer((_) async => Future.value()); + when(mockBlockedUsersRepository.getBlockedUsers()) + .thenAnswer((_) async => profilesList); + + await blockedUsersCubit!.blockUser(slug); + await Future.delayed(const Duration(milliseconds: 100)); + + verify(mockBlockedUsersRepository.blockUserBySlug(slug)).called(1); + verify(mockBlockedUsersRepository.getBlockedUsers()).called(1); + }); + + test('unblockUser - разблокирует пользователя и обновляет список', () async { + blockedUsersCubit = BlockedUsersCubit( + blockedUsersRepository: mockBlockedUsersRepository, + ); + final blockedUser = MenuFixtures.blockedUser(); + final slug = blockedUser.slug; + final profilesList = MenuFixtures.blockedUsersEmptyList(); + + when(mockBlockedUsersRepository.unblockUserBySlug(slug)) + .thenAnswer((_) async => Future.value()); + when(mockBlockedUsersRepository.getBlockedUsers()) + .thenAnswer((_) async => profilesList); + + await blockedUsersCubit!.unblockUser(slug); + await Future.delayed(const Duration(milliseconds: 100)); + + verify(mockBlockedUsersRepository.unblockUserBySlug(slug)).called(1); + verify(mockBlockedUsersRepository.getBlockedUsers()).called(1); + }); + }); +} + diff --git a/test/features/menu/presentation/bloc/menu_cubit_test.dart b/test/features/menu/presentation/bloc/menu_cubit_test.dart new file mode 100644 index 00000000..9cdf18d3 --- /dev/null +++ b/test/features/menu/presentation/bloc/menu_cubit_test.dart @@ -0,0 +1,68 @@ +import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart'; +import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'menu_cubit_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('MenuCubit', () { + MenuCubit? menuCubit; + late MockProfileRepository mockProfileRepository; + + setUp(() { + mockProfileRepository = MockProfileRepository(); + }); + + tearDown(() async { + if (menuCubit != null && !menuCubit!.isClosed) { + await Future.delayed(const Duration(milliseconds: 100)); + menuCubit!.close(); + menuCubit = null; + } + }); + + test('начальное состояние - MenuState', () { + menuCubit = MenuCubit(mockProfileRepository); + expect(menuCubit!.state, isA()); + }); + + test('makePassKey - успешно создает passKey', () async { + menuCubit = MenuCubit(mockProfileRepository); + const expectedPassKey = 'test-pass-key'; + + when(mockProfileRepository.getPassKey( + routeName: 'product_nutritional_value.index', + routeParams: {}, + )).thenAnswer((_) async => expectedPassKey); + + final result = await menuCubit!.makePassKey(); + + expect(result, expectedPassKey); + verify(mockProfileRepository.getPassKey( + routeName: 'product_nutritional_value.index', + routeParams: {}, + )).called(1); + }); + + test('makePassKey - возвращает null при ошибке', () async { + menuCubit = MenuCubit(mockProfileRepository); + + when(mockProfileRepository.getPassKey( + routeName: 'product_nutritional_value.index', + routeParams: {}, + )).thenThrow(Exception('Ошибка получения passKey')); + + final result = await menuCubit!.makePassKey(); + + expect(result, isNull); + verify(mockProfileRepository.getPassKey( + routeName: 'product_nutritional_value.index', + routeParams: {}, + )).called(1); + }); + }); +} + diff --git a/test/features/menu/presentation/bloc/notification_settings_cubit_test.dart b/test/features/menu/presentation/bloc/notification_settings_cubit_test.dart new file mode 100644 index 00000000..4fc65ffb --- /dev/null +++ b/test/features/menu/presentation/bloc/notification_settings_cubit_test.dart @@ -0,0 +1,108 @@ +import 'package:eatvio_app/features/menu/presentation/bloc/notification_settings_cubit/notification_settings_cubit.dart'; +import 'package:eatvio_app/features/menu/presentation/bloc/notification_settings_cubit/notification_settings_state.dart'; +import 'package:eatvio_app/features/menu/repositories/notification_settings_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import '../../../../fixtures/menu_fixtures.dart'; +import 'notification_settings_cubit_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('NotificationSettingsCubit', () { + NotificationSettingsCubit? notificationSettingsCubit; + late MockNotificationSettingsRepository mockNotificationSettingsRepository; + + setUp(() { + mockNotificationSettingsRepository = MockNotificationSettingsRepository(); + }); + + tearDown(() async { + if (notificationSettingsCubit != null && !notificationSettingsCubit!.isClosed) { + await Future.delayed(const Duration(milliseconds: 100)); + notificationSettingsCubit!.close(); + notificationSettingsCubit = null; + } + }); + + test('начальное состояние - loading', () { + notificationSettingsCubit = NotificationSettingsCubit( + notificationSettingsRepository: mockNotificationSettingsRepository, + ); + expect(notificationSettingsCubit!.state, const NotificationSettingsStateLoading()); + }); + + test('getNotificationSettings - успешно загружает настройки уведомлений', () async { + notificationSettingsCubit = NotificationSettingsCubit( + notificationSettingsRepository: mockNotificationSettingsRepository, + ); + + when(mockNotificationSettingsRepository.getNotificationSettings()) + .thenAnswer((_) async => MenuFixtures.notificationSettingsModel()); + + await notificationSettingsCubit!.getNotificationSettings(); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(notificationSettingsCubit!.state, isA()); + final loadedState = notificationSettingsCubit!.state as NotificationSettingsStateLoaded; + expect(loadedState.notificationSettings.newUpdatesNotification, true); + verify(mockNotificationSettingsRepository.getNotificationSettings()).called(1); + }); + + test('getNotificationSettings - обрабатывает ошибку', () async { + notificationSettingsCubit = NotificationSettingsCubit( + notificationSettingsRepository: mockNotificationSettingsRepository, + ); + + when(mockNotificationSettingsRepository.getNotificationSettings()) + .thenThrow(Exception('Ошибка загрузки')); + + await notificationSettingsCubit!.getNotificationSettings(); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(notificationSettingsCubit!.state, isA()); + final errorState = notificationSettingsCubit!.state as NotificationSettingsStateError; + expect(errorState.errorMessage, contains('Ошибка загрузки')); + }); + + test('updateNotificationSettings - успешно обновляет настройки', () async { + notificationSettingsCubit = NotificationSettingsCubit( + notificationSettingsRepository: mockNotificationSettingsRepository, + ); + final data = { + 'new_updates_notification': false, + 'weight_measurements_notification': true, + }; + final updatedSettings = MenuFixtures.notificationSettingsUpdatedModel(); + + when(mockNotificationSettingsRepository.updateNotificationSettings(data)) + .thenAnswer((_) async => updatedSettings); + + await notificationSettingsCubit!.updateNotificationSettings(data); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(notificationSettingsCubit!.state, isA()); + final loadedState = notificationSettingsCubit!.state as NotificationSettingsStateLoaded; + expect(loadedState.notificationSettings.newUpdatesNotification, false); + verify(mockNotificationSettingsRepository.updateNotificationSettings(data)).called(1); + }); + + test('updateNotificationSettings - обрабатывает ошибку при обновлении', () async { + notificationSettingsCubit = NotificationSettingsCubit( + notificationSettingsRepository: mockNotificationSettingsRepository, + ); + final data = {'new_updates_notification': false}; + + when(mockNotificationSettingsRepository.updateNotificationSettings(data)) + .thenThrow(Exception('Ошибка обновления')); + + await notificationSettingsCubit!.updateNotificationSettings(data); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(notificationSettingsCubit!.state, isA()); + final errorState = notificationSettingsCubit!.state as NotificationSettingsStateError; + expect(errorState.errorMessage, contains('Ошибка обновления')); + }); + }); +} + diff --git a/test/features/menu/repositories/blocked_users_repository_test.dart b/test/features/menu/repositories/blocked_users_repository_test.dart new file mode 100644 index 00000000..6fba2382 --- /dev/null +++ b/test/features/menu/repositories/blocked_users_repository_test.dart @@ -0,0 +1,78 @@ +import 'package:eatvio_app/features/menu/presentation/repositories/blocked_users_repository.dart'; +import 'package:eatvio_app/features/menu/services/blocked_users_service.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import '../../../fixtures/menu_fixtures.dart'; +import 'blocked_users_repository_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('BlockedUsersRepository', () { + late BlockedUsersRepository blockedUsersRepository; + late MockBlockedUserService mockBlockedUserService; + + setUp(() { + mockBlockedUserService = MockBlockedUserService(); + blockedUsersRepository = BlockedUsersRepository( + blockedUserService: mockBlockedUserService, + ); + }); + + test('getBlockedUsers - возвращает список заблокированных пользователей', () async { + final blockedUsersModel = MenuFixtures.blockedUsersModel(); + + when(mockBlockedUserService.getBlockedUsers()) + .thenAnswer((_) async => blockedUsersModel); + + final result = await blockedUsersRepository.getBlockedUsers(); + + expect(result, isA>()); + expect(result.length, 2); + expect(result.first.id, 1); + expect(result.last.id, 2); + verify(mockBlockedUserService.getBlockedUsers()).called(1); + }); + + test('blockUserBySlug - блокирует пользователя по slug', () async { + final blockedUser = MenuFixtures.blockedUser(); + final slug = blockedUser.slug; + final data = {'slug': slug}; + + when(mockBlockedUserService.blockUser(data: data)) + .thenAnswer((_) async => Future.value()); + + await blockedUsersRepository.blockUserBySlug(slug); + + verify(mockBlockedUserService.blockUser(data: data)).called(1); + }); + + test('unblockUserBySlug - разблокирует пользователя по slug', () async { + final blockedUser = MenuFixtures.blockedUser(); + final slug = blockedUser.slug; + final data = {'slug': slug}; + + when(mockBlockedUserService.unblockUser(data: data)) + .thenAnswer((_) async => Future.value()); + + await blockedUsersRepository.unblockUserBySlug(slug); + + verify(mockBlockedUserService.unblockUser(data: data)).called(1); + }); + + test('getBlockedUsers - обрабатывает пустой список', () async { + final blockedUsersModel = MenuFixtures.blockedUsersEmptyModel(); + + when(mockBlockedUserService.getBlockedUsers()) + .thenAnswer((_) async => blockedUsersModel); + + final result = await blockedUsersRepository.getBlockedUsers(); + + expect(result, isA>()); + expect(result.isEmpty, true); + verify(mockBlockedUserService.getBlockedUsers()).called(1); + }); + }); +} + diff --git a/test/features/menu/repositories/notification_settings_repository_test.dart b/test/features/menu/repositories/notification_settings_repository_test.dart new file mode 100644 index 00000000..c3de8fe4 --- /dev/null +++ b/test/features/menu/repositories/notification_settings_repository_test.dart @@ -0,0 +1,58 @@ +import 'package:eatvio_app/features/menu/models/notification_settings_model.dart'; +import 'package:eatvio_app/features/menu/repositories/notification_settings_repository.dart'; +import 'package:eatvio_app/features/menu/services/notification_settings_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import '../../../fixtures/menu_fixtures.dart'; +import 'notification_settings_repository_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('NotificationSettingsRepository', () { + late NotificationSettingsRepository notificationSettingsRepository; + late MockNotificationSettingsService mockNotificationSettingsService; + + setUp(() { + mockNotificationSettingsService = MockNotificationSettingsService(); + notificationSettingsRepository = NotificationSettingsRepository( + mockNotificationSettingsService, + ); + }); + + test('getNotificationSettings - возвращает настройки уведомлений', () async { + final expectedSettings = MenuFixtures.notificationSettingsModel(); + + when(mockNotificationSettingsService.getNotificationSettings()) + .thenAnswer((_) async => expectedSettings); + + final result = await notificationSettingsRepository.getNotificationSettings(); + + expect(result, isA()); + expect(result.newUpdatesNotification, true); + expect(result.diaryReminderNotifications.firstReminder.enabled, true); + verify(mockNotificationSettingsService.getNotificationSettings()).called(1); + }); + + test('updateNotificationSettings - обновляет настройки уведомлений', () async { + final data = { + 'new_updates_notification': false, + 'weight_measurements_notification': true, + 'is_email_notifications_enabled': true, + 'is_push_notifications_enabled': false, + }; + final expectedSettings = MenuFixtures.notificationSettingsUpdatedModel(); + + when(mockNotificationSettingsService.updateNotificationSettings(data: data)) + .thenAnswer((_) async => expectedSettings); + + final result = await notificationSettingsRepository.updateNotificationSettings(data); + + expect(result, isA()); + expect(result.newUpdatesNotification, false); + expect(result.isPushNotificationsEnabled, false); + verify(mockNotificationSettingsService.updateNotificationSettings(data: data)).called(1); + }); + }); +} + diff --git a/test/features/menu/services/blocked_users_service_test.dart b/test/features/menu/services/blocked_users_service_test.dart new file mode 100644 index 00000000..cd183ee4 --- /dev/null +++ b/test/features/menu/services/blocked_users_service_test.dart @@ -0,0 +1,57 @@ +import 'package:eatvio_app/features/menu/models/blocked_users_model.dart'; +import 'package:eatvio_app/features/menu/services/blocked_users_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import '../../../fixtures/menu_fixtures.dart'; +import 'blocked_users_service_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('BlockedUserService', () { + late MockBlockedUserService mockBlockedUserService; + + setUp(() { + mockBlockedUserService = MockBlockedUserService(); + }); + + test('getBlockedUsers - возвращает список заблокированных пользователей', () async { + final expectedBlockedUsers = MenuFixtures.blockedUsersModel(); + + when(mockBlockedUserService.getBlockedUsers()) + .thenAnswer((_) async => expectedBlockedUsers); + + final result = await mockBlockedUserService.getBlockedUsers(); + + expect(result, isA()); + expect(result.profilesList.length, 2); + expect(result.profilesList.first.id, 1); + verify(mockBlockedUserService.getBlockedUsers()).called(1); + }); + + test('blockUser - блокирует пользователя', () async { + final blockedUser = MenuFixtures.blockedUser(); + final data = {'slug': blockedUser.slug}; + + when(mockBlockedUserService.blockUser(data: data)) + .thenAnswer((_) async => Future.value()); + + await mockBlockedUserService.blockUser(data: data); + + verify(mockBlockedUserService.blockUser(data: data)).called(1); + }); + + test('unblockUser - разблокирует пользователя', () async { + final blockedUser = MenuFixtures.blockedUser(); + final data = {'slug': blockedUser.slug}; + + when(mockBlockedUserService.unblockUser(data: data)) + .thenAnswer((_) async => Future.value()); + + await mockBlockedUserService.unblockUser(data: data); + + verify(mockBlockedUserService.unblockUser(data: data)).called(1); + }); + }); +} + diff --git a/test/features/menu/services/notification_settings_service_test.dart b/test/features/menu/services/notification_settings_service_test.dart new file mode 100644 index 00000000..6cd81364 --- /dev/null +++ b/test/features/menu/services/notification_settings_service_test.dart @@ -0,0 +1,53 @@ +import 'package:eatvio_app/features/menu/models/notification_settings_model.dart'; +import 'package:eatvio_app/features/menu/services/notification_settings_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import '../../../fixtures/menu_fixtures.dart'; +import 'notification_settings_service_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('NotificationSettingsService', () { + late MockNotificationSettingsService mockNotificationSettingsService; + + setUp(() { + mockNotificationSettingsService = MockNotificationSettingsService(); + }); + + test('getNotificationSettings - возвращает настройки уведомлений', () async { + final expectedSettings = MenuFixtures.notificationSettingsModel(); + + when(mockNotificationSettingsService.getNotificationSettings()) + .thenAnswer((_) async => expectedSettings); + + final result = await mockNotificationSettingsService.getNotificationSettings(); + + expect(result, isA()); + expect(result.newUpdatesNotification, true); + expect(result.isEmailNotificationsEnabled, true); + verify(mockNotificationSettingsService.getNotificationSettings()).called(1); + }); + + test('updateNotificationSettings - обновляет настройки уведомлений', () async { + final data = { + 'new_updates_notification': false, + 'weight_measurements_notification': true, + 'is_email_notifications_enabled': true, + 'is_push_notifications_enabled': false, + }; + final expectedSettings = MenuFixtures.notificationSettingsUpdatedModel(); + + when(mockNotificationSettingsService.updateNotificationSettings(data: data)) + .thenAnswer((_) async => expectedSettings); + + final result = await mockNotificationSettingsService.updateNotificationSettings(data: data); + + expect(result, isA()); + expect(result.newUpdatesNotification, false); + expect(result.isPushNotificationsEnabled, false); + verify(mockNotificationSettingsService.updateNotificationSettings(data: data)).called(1); + }); + }); +} + diff --git a/test/features/my_finance/models/card_model_test.dart b/test/features/my_finance/models/card_model_test.dart new file mode 100644 index 00000000..36e84d94 --- /dev/null +++ b/test/features/my_finance/models/card_model_test.dart @@ -0,0 +1,85 @@ +import 'package:eatvio_app/features/my_finance/models/card_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('CardModel', () { + test('fromJson - успешная десериализация', () { + final json = { + 'id': 1, + 'bank_pan': '1234567890123456', + 'is_default': true, + }; + + final card = CardModel.fromJson(json); + + expect(card.id, equals(1)); + expect(card.cardNumber, equals('1234567890123456')); + expect(card.isDefault, isTrue); + }); + + test('fromJson - is_default как int', () { + final json = { + 'id': 1, + 'bank_pan': '1234567890123456', + 'is_default': 1, + }; + + final card = CardModel.fromJson(json); + + expect(card.isDefault, isTrue); + }); + + test('fromJson - is_default как строка "1"', () { + final json = { + 'id': 1, + 'bank_pan': '1234567890123456', + 'is_default': '1', + }; + + final card = CardModel.fromJson(json); + + expect(card.isDefault, isTrue); + }); + + test('fromJson - is_default как false', () { + final json = { + 'id': 1, + 'bank_pan': '1234567890123456', + 'is_default': false, + }; + + final card = CardModel.fromJson(json); + + expect(card.isDefault, isFalse); + }); + + test('toJson - успешная сериализация', () { + final card = CardModel( + id: 1, + cardNumber: '1234567890123456', + isDefault: true, + ); + + final json = card.toJson(); + + expect(json['id'], equals(1)); + expect(json['bank_pan'], equals('1234567890123456')); + expect(json['is_default'], isTrue); + }); + + test('copyWith - создание копии с изменениями', () { + final card = CardModel( + id: 1, + cardNumber: '1234567890123456', + isDefault: false, + ); + + final updatedCard = card.copyWith(isDefault: true); + + expect(updatedCard.id, equals(1)); + expect(updatedCard.cardNumber, equals('1234567890123456')); + expect(updatedCard.isDefault, isTrue); + }); + }); +} + diff --git a/test/features/my_finance/models/payment_url_model_test.dart b/test/features/my_finance/models/payment_url_model_test.dart new file mode 100644 index 00000000..e1f3a121 --- /dev/null +++ b/test/features/my_finance/models/payment_url_model_test.dart @@ -0,0 +1,39 @@ +import 'package:eatvio_app/features/my_finance/models/payment_url_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('PaymentUrlModel', () { + test('fromJson - успешная десериализация', () { + final json = { + 'paymentUrl': 'https://payment.example.com/checkout', + }; + + final model = PaymentUrlModel.fromJson(json); + + expect(model.paymentUrl, equals('https://payment.example.com/checkout')); + }); + + test('toJson - успешная сериализация', () { + final model = PaymentUrlModel( + paymentUrl: 'https://payment.example.com/checkout', + ); + + final json = model.toJson(); + + expect(json['paymentUrl'], equals('https://payment.example.com/checkout')); + }); + + test('copyWith - создание копии с изменениями', () { + final model = PaymentUrlModel( + paymentUrl: 'https://payment.example.com/checkout', + ); + + final updatedModel = model.copyWith( + paymentUrl: 'https://payment.example.com/new', + ); + + expect(updatedModel.paymentUrl, equals('https://payment.example.com/new')); + }); + }); +} + diff --git a/test/features/my_finance/presentation/cubit/user_cards_cubit/user_cards_cubit_test.dart b/test/features/my_finance/presentation/cubit/user_cards_cubit/user_cards_cubit_test.dart new file mode 100644 index 00000000..3c972d13 --- /dev/null +++ b/test/features/my_finance/presentation/cubit/user_cards_cubit/user_cards_cubit_test.dart @@ -0,0 +1,154 @@ +import 'package:eatvio_app/core/enums/base_state.dart'; +import 'package:eatvio_app/features/my_finance/models/card_model.dart'; +import 'package:eatvio_app/features/my_finance/models/payment_url_model.dart'; +import 'package:eatvio_app/features/my_finance/presentation/cubit/user_cards_cubit/user_cards_cubit.dart'; +import 'package:eatvio_app/features/my_finance/repositories/cards_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'user_cards_cubit_test.mocks.dart'; + +@GenerateMocks([CardsRepository]) +void main() { + group('UserCardsCubit', () { + late UserCardsCubit cubit; + late MockCardsRepository mockCardsRepository; + + setUp(() { + mockCardsRepository = MockCardsRepository(); + cubit = UserCardsCubit(cardsRepository: mockCardsRepository); + }); + + tearDown(() { + cubit.close(); + }); + + test('начальное состояние', () { + expect(cubit.state.cards, isEmpty); + expect(cubit.state.error, isNull); + expect(cubit.state.state, BaseState.initial); + }); + + test('getCards - успешная загрузка карт', () async { + final cards = [ + CardModel(id: 1, cardNumber: '1234', isDefault: true), + CardModel(id: 2, cardNumber: '5678', isDefault: false), + ]; + + when(mockCardsRepository.getCards()).thenAnswer((_) async => cards); + + await cubit.getCards(); + + expect(cubit.state.cards, equals(cards)); + expect(cubit.state.state, BaseState.success); + expect(cubit.state.error, isNull); + verify(mockCardsRepository.getCards()).called(1); + }); + + test('getCards - ошибка при загрузке', () async { + final error = Exception('Ошибка загрузки'); + when(mockCardsRepository.getCards()).thenThrow(error); + + await cubit.getCards(); + + expect(cubit.state.cards, isEmpty); + expect(cubit.state.state, BaseState.error); + expect(cubit.state.error, equals(error.toString())); + verify(mockCardsRepository.getCards()).called(1); + }); + + test('addCard - успешное добавление карты', () async { + final paymentUrl = PaymentUrlModel(paymentUrl: 'https://payment.url'); + when(mockCardsRepository.addCard()).thenAnswer((_) async => paymentUrl); + + final result = await cubit.addCard(); + + expect(result, equals(paymentUrl)); + verify(mockCardsRepository.addCard()).called(1); + }); + + test('addCard - ошибка при добавлении', () async { + when(mockCardsRepository.addCard()).thenThrow(Exception('Ошибка')); + + final result = await cubit.addCard(); + + expect(result, isNull); + verify(mockCardsRepository.addCard()).called(1); + }); + + test('markAsDefault - успешное изменение карты по умолчанию', () async { + final cards = [ + CardModel(id: 1, cardNumber: '1234', isDefault: true), + CardModel(id: 2, cardNumber: '5678', isDefault: false), + ]; + + when(mockCardsRepository.getCards()).thenAnswer((_) async => cards); + when(mockCardsRepository.markAsDefault(id: 2)).thenAnswer((_) async {}); + + await cubit.getCards(); + await cubit.markAsDefault(id: 2); + + expect(cubit.state.cards[0].isDefault, isFalse); + expect(cubit.state.cards[1].isDefault, isTrue); + + // Ждем завершения debounce + await Future.delayed(const Duration(milliseconds: 100)); + + verify(mockCardsRepository.markAsDefault(id: 2)).called(1); + }); + + test('deleteCard - успешное удаление карты', () async { + final cards = [ + CardModel(id: 1, cardNumber: '1234', isDefault: true), + CardModel(id: 2, cardNumber: '5678', isDefault: false), + ]; + + when(mockCardsRepository.getCards()).thenAnswer((_) async => cards); + when(mockCardsRepository.deleteCard(id: 2)).thenAnswer((_) async {}); + + await cubit.getCards(); + await cubit.deleteCard(id: 2); + + expect(cubit.state.cards.length, equals(1)); + expect(cubit.state.cards[0].id, equals(1)); + verify(mockCardsRepository.deleteCard(id: 2)).called(1); + }); + + test('deleteCard - ошибка при удалении', () async { + final cards = [ + CardModel(id: 1, cardNumber: '1234', isDefault: true), + ]; + + when(mockCardsRepository.getCards()).thenAnswer((_) async => cards); + when(mockCardsRepository.deleteCard(id: 1)).thenThrow(Exception('Ошибка')); + + await cubit.getCards(); + await cubit.deleteCard(id: 1); + + // Карта должна вернуться обратно + expect(cubit.state.cards.length, equals(1)); + expect(cubit.state.state, BaseState.error); + verify(mockCardsRepository.deleteCard(id: 1)).called(1); + }); + + test('collectCharge - успешный сбор платежа', () async { + when(mockCardsRepository.collectCharge(chosenPlaId: 1)).thenAnswer((_) async {}); + + final result = await cubit.collectCharge(chosenPlaId: 1); + + expect(result, isTrue); + verify(mockCardsRepository.collectCharge(chosenPlaId: 1)).called(1); + }); + + test('collectCharge - ошибка при сборе платежа', () async { + when(mockCardsRepository.collectCharge(chosenPlaId: 1)).thenThrow(Exception('Ошибка')); + + final result = await cubit.collectCharge(chosenPlaId: 1); + + expect(result, isFalse); + verify(mockCardsRepository.collectCharge(chosenPlaId: 1)).called(1); + }); + }); +} + diff --git a/test/features/my_finance/repositories/cards_repository_test.dart b/test/features/my_finance/repositories/cards_repository_test.dart new file mode 100644 index 00000000..5a657586 --- /dev/null +++ b/test/features/my_finance/repositories/cards_repository_test.dart @@ -0,0 +1,111 @@ +import 'package:eatvio_app/features/my_finance/models/card_model.dart'; +import 'package:eatvio_app/features/my_finance/models/payment_url_model.dart'; +import 'package:eatvio_app/features/my_finance/repositories/cards_repository.dart'; +import 'package:eatvio_app/features/my_finance/services/cards_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'cards_repository_test.mocks.dart'; + +@GenerateMocks([CardsService]) +void main() { + group('CardsRepository', () { + late CardsRepository repository; + late MockCardsService mockCardsService; + + setUp(() { + mockCardsService = MockCardsService(); + repository = CardsRepository(cardsService: mockCardsService); + }); + + test('addCard - успешное добавление карты', () async { + final paymentUrl = PaymentUrlModel(paymentUrl: 'https://payment.url'); + when(mockCardsService.addCard()).thenAnswer((_) async => paymentUrl); + + final result = await repository.addCard(); + + expect(result, equals(paymentUrl)); + verify(mockCardsService.addCard()).called(1); + }); + + test('addCard - проброс ошибки', () async { + final error = Exception('Ошибка'); + when(mockCardsService.addCard()).thenThrow(error); + + expect(() => repository.addCard(), throwsA(error)); + verify(mockCardsService.addCard()).called(1); + }); + + test('getCards - успешная загрузка карт', () async { + final cards = [ + CardModel(id: 1, cardNumber: '1234', isDefault: true), + CardModel(id: 2, cardNumber: '5678', isDefault: false), + ]; + + when(mockCardsService.getCards()).thenAnswer((_) async => cards); + + final result = await repository.getCards(); + + expect(result, equals(cards)); + verify(mockCardsService.getCards()).called(1); + }); + + test('getCards - проброс ошибки', () async { + final error = Exception('Ошибка'); + when(mockCardsService.getCards()).thenThrow(error); + + expect(() => repository.getCards(), throwsA(error)); + verify(mockCardsService.getCards()).called(1); + }); + + test('markAsDefault - успешное изменение карты по умолчанию', () async { + when(mockCardsService.markAsDefault(id: 1)).thenAnswer((_) async {}); + + await repository.markAsDefault(id: 1); + + verify(mockCardsService.markAsDefault(id: 1)).called(1); + }); + + test('markAsDefault - проброс ошибки', () async { + final error = Exception('Ошибка'); + when(mockCardsService.markAsDefault(id: 1)).thenThrow(error); + + expect(() => repository.markAsDefault(id: 1), throwsA(error)); + verify(mockCardsService.markAsDefault(id: 1)).called(1); + }); + + test('deleteCard - успешное удаление карты', () async { + when(mockCardsService.deleteCard(id: 1)).thenAnswer((_) async {}); + + await repository.deleteCard(id: 1); + + verify(mockCardsService.deleteCard(id: 1)).called(1); + }); + + test('deleteCard - проброс ошибки', () async { + final error = Exception('Ошибка'); + when(mockCardsService.deleteCard(id: 1)).thenThrow(error); + + expect(() => repository.deleteCard(id: 1), throwsA(error)); + verify(mockCardsService.deleteCard(id: 1)).called(1); + }); + + test('collectCharge - успешный сбор платежа', () async { + when(mockCardsService.collectCharge(chosenPlanId: 1)).thenAnswer((_) async {}); + + await repository.collectCharge(chosenPlaId: 1); + + verify(mockCardsService.collectCharge(chosenPlanId: 1)).called(1); + }); + + test('collectCharge - проброс ошибки', () async { + final error = Exception('Ошибка'); + when(mockCardsService.collectCharge(chosenPlanId: 1)).thenThrow(error); + + expect(() => repository.collectCharge(chosenPlaId: 1), throwsA(error)); + verify(mockCardsService.collectCharge(chosenPlanId: 1)).called(1); + }); + }); +} + diff --git a/test/features/notifications/presentation/notifications_cubit/notifications_cubit_test.dart b/test/features/notifications/presentation/notifications_cubit/notifications_cubit_test.dart new file mode 100644 index 00000000..4d930b1b --- /dev/null +++ b/test/features/notifications/presentation/notifications_cubit/notifications_cubit_test.dart @@ -0,0 +1,194 @@ +import 'package:eatvio_app/core/websockets/ws_manager.dart'; +import 'package:eatvio_app/features/notifications/models/notification_model.dart'; +import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart'; +import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_state.dart'; +import 'package:eatvio_app/features/notifications/repository/notifications_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'notifications_cubit_test.mocks.dart'; + +@GenerateMocks([WsManager, NotificationsRepository]) +void main() { + group('NotificationsCubit', () { + late NotificationsCubit cubit; + late MockWsManager mockWsManager; + late MockNotificationsRepository mockNotificationsRepository; + + setUp(() { + mockWsManager = MockWsManager(); + mockNotificationsRepository = MockNotificationsRepository(); + + // Мокируем stream как null, чтобы избежать проблем с подписками в тестах + when(mockWsManager.newNotificationsStream).thenAnswer((_) => null); + + cubit = NotificationsCubit( + wsManager: mockWsManager, + notificationsRepository: mockNotificationsRepository, + ); + }); + + tearDown(() async { + await cubit.close(); + }); + + test('начальное состояние - empty', () { + expect(cubit.state, isA()); + }); + + test('getNotifications - успешная загрузка уведомлений', () async { + final notifications = [ + ChosenPlanStartedToClientNotification( + type: NotificationType.chosenPlanStartedToClientNotification, + planName: 'Test Plan', + planId: 1, + isRead: false, + createdAt: DateTime.now(), + ), + ]; + + final result = { + 'notifications': notifications, + 'pagination': { + 'current_page': 1, + 'last_page': 1, + }, + }; + + when(mockNotificationsRepository.getNotifications(page: 1)) + .thenAnswer((_) async => result); + + await cubit.getNotifications(); + + final state = cubit.state; + expect(state, isA()); + if (state is NotificationsStateLoaded) { + expect(state.notifications.length, 1); + expect(state.currentPage, 1); + expect(state.hasNextPage, false); + } + verify(mockNotificationsRepository.getNotifications(page: 1)).called(1); + }); + + test('getNotifications - обработка ошибки', () async { + when(mockNotificationsRepository.getNotifications(page: 1)) + .thenThrow(Exception('Ошибка загрузки')); + + await cubit.getNotifications(); + + // Состояние должно остаться empty при ошибке + expect(cubit.state, isA()); + }); + + test('loadMoreNotifications - успешная загрузка следующей страницы', () async { + final firstPageNotifications = [ + ChosenPlanStartedToClientNotification( + type: NotificationType.chosenPlanStartedToClientNotification, + planName: 'Plan 1', + planId: 1, + isRead: false, + createdAt: DateTime.now(), + ), + ]; + + final secondPageNotifications = [ + ChosenPlanStartedToClientNotification( + type: NotificationType.chosenPlanStartedToClientNotification, + planName: 'Plan 2', + planId: 2, + isRead: false, + createdAt: DateTime.now(), + ), + ]; + + when(mockNotificationsRepository.getNotifications(page: 1)) + .thenAnswer((_) async => { + 'notifications': firstPageNotifications, + 'pagination': {'current_page': 1, 'last_page': 2}, + }); + + when(mockNotificationsRepository.getNotifications(page: 2)) + .thenAnswer((_) async => { + 'notifications': secondPageNotifications, + 'pagination': {'current_page': 2, 'last_page': 2}, + }); + + await cubit.getNotifications(); + + final firstState = cubit.state; + expect(firstState, isA()); + if (firstState is NotificationsStateLoaded) { + expect(firstState.hasNextPage, true); + + await cubit.loadMoreNotifications(); + + final secondState = cubit.state; + expect(secondState, isA()); + if (secondState is NotificationsStateLoaded) { + expect(secondState.notifications.length, 2); + expect(secondState.currentPage, 2); + expect(secondState.hasNextPage, false); + } + } + }); + + test('loadMoreNotifications - не загружает, если нет следующей страницы', () async { + final notifications = [ + ChosenPlanStartedToClientNotification( + type: NotificationType.chosenPlanStartedToClientNotification, + planName: 'Plan 1', + planId: 1, + isRead: false, + createdAt: DateTime.now(), + ), + ]; + + when(mockNotificationsRepository.getNotifications(page: 1)) + .thenAnswer((_) async => { + 'notifications': notifications, + 'pagination': {'current_page': 1, 'last_page': 1}, + }); + + await cubit.getNotifications(); + await cubit.loadMoreNotifications(); + + verify(mockNotificationsRepository.getNotifications(page: 1)).called(1); + verifyNever(mockNotificationsRepository.getNotifications(page: 2)); + }); + + test('markNotificationsAsRead - успешная пометка как прочитанных', () async { + final notifications = [ + ChosenPlanStartedToClientNotification( + type: NotificationType.chosenPlanStartedToClientNotification, + planName: 'Plan 1', + planId: 1, + isRead: false, + createdAt: DateTime.now(), + ), + ]; + + when(mockNotificationsRepository.getNotifications(page: 1)) + .thenAnswer((_) async => { + 'notifications': notifications, + 'pagination': {'current_page': 1, 'last_page': 1}, + }); + + when(mockNotificationsRepository.markNotificationsAsRead()) + .thenAnswer((_) async => {}); + + await cubit.getNotifications(); + await cubit.markNotificationsAsRead(); + + verify(mockNotificationsRepository.markNotificationsAsRead()).called(1); + verify(mockNotificationsRepository.getNotifications(page: 1)).called(2); // Один раз при getNotifications, второй раз после markNotificationsAsRead + }); + + test('connectToWebSocket - подключается к WebSocket', () async { + await cubit.connectToWebSocket(); + + verify(mockWsManager.newNotificationsStream).called(1); + }); + }); +} + diff --git a/test/features/notifications/repository/notifications_repository_test.dart b/test/features/notifications/repository/notifications_repository_test.dart new file mode 100644 index 00000000..a80b3fb8 --- /dev/null +++ b/test/features/notifications/repository/notifications_repository_test.dart @@ -0,0 +1,77 @@ +import 'package:eatvio_app/features/notifications/models/notification_model.dart'; +import 'package:eatvio_app/features/notifications/repository/notifications_repository.dart'; +import 'package:eatvio_app/features/notifications/service/notifications_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'notifications_repository_test.mocks.dart'; + +@GenerateMocks([NotificationsService]) +void main() { + group('NotificationsRepository', () { + late NotificationsRepository repository; + late MockNotificationsService mockNotificationsService; + + setUp(() { + mockNotificationsService = MockNotificationsService(); + repository = NotificationsRepository(notificationsService: mockNotificationsService); + }); + + test('getNotifications - успешная загрузка уведомлений', () async { + final notifications = [ + ChosenPlanStartedToClientNotification( + type: NotificationType.chosenPlanStartedToClientNotification, + planName: 'Test Plan', + planId: 1, + isRead: false, + createdAt: DateTime.now(), + ), + ]; + + final result = { + 'notifications': notifications, + 'pagination': { + 'current_page': 1, + 'last_page': 1, + }, + }; + + when(mockNotificationsService.getNotifications(page: 1)) + .thenAnswer((_) async => result); + + final response = await repository.getNotifications(page: 1); + + expect(response, equals(result)); + verify(mockNotificationsService.getNotifications(page: 1)).called(1); + }); + + test('getNotifications - проброс ошибки', () async { + final error = Exception('Ошибка загрузки'); + when(mockNotificationsService.getNotifications(page: 1)) + .thenThrow(error); + + expect(() => repository.getNotifications(page: 1), throwsA(error)); + verify(mockNotificationsService.getNotifications(page: 1)).called(1); + }); + + test('markNotificationsAsRead - успешная пометка как прочитанных', () async { + when(mockNotificationsService.markNotificationsAsRead()) + .thenAnswer((_) async => {}); + + await repository.markNotificationsAsRead(); + + verify(mockNotificationsService.markNotificationsAsRead()).called(1); + }); + + test('markNotificationsAsRead - проброс ошибки', () async { + final error = Exception('Ошибка'); + when(mockNotificationsService.markNotificationsAsRead()) + .thenThrow(error); + + expect(() => repository.markNotificationsAsRead(), throwsA(error)); + verify(mockNotificationsService.markNotificationsAsRead()).called(1); + }); + }); +} + diff --git a/test/features/order_info/cubit/order_info_cubit_test.dart b/test/features/order_info/cubit/order_info_cubit_test.dart new file mode 100644 index 00000000..de00ad94 --- /dev/null +++ b/test/features/order_info/cubit/order_info_cubit_test.dart @@ -0,0 +1,266 @@ +import 'package:eatvio_app/features/chat/models/payment_model.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart'; +import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'order_info_cubit_test.mocks.dart'; + +@GenerateMocks([ChatRepository, ProfileRepository]) +void main() { + group('OrderInfoCubit', () { + late OrderInfoCubit cubit; + late MockChatRepository mockChatRepository; + late MockProfileRepository mockProfileRepository; + + setUp(() { + mockChatRepository = MockChatRepository(); + mockProfileRepository = MockProfileRepository(); + cubit = OrderInfoCubit( + chatRepository: mockChatRepository, + profileRepository: mockProfileRepository, + ); + }); + + tearDown(() { + cubit.close(); + }); + + test('начальное состояние', () { + expect(cubit.state.isLoading, isTrue); + expect(cubit.state.chosenPlan, isNull); + expect(cubit.state.customerProfile, isNull); + }); + + test('getChosenPlan - успешная загрузка плана', () async { + final chosenPlan = ChosenPlanModel( + id: 1, + optionType: 'options1', + startDate: DateTime.now(), + chosenPlanState: ChosenPlanStateEnum.stateStarted, + chatId: 'chat-1', + consultantId: 1, + plan: const PlanModel( + id: 1, + slug: 'test-plan', + name: 'Test Plan', + image: '', + duration: 30, + state: 'active', + type: PlanType(fit: false, slim: false, behavior: false, wellness: false), + details: '', + packetsCount: 1, + author: Author( + authorSlug: 'author-slug', + authorName: 'Author Name', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + isFavorite: false, + minPriceOfOptions: 0, + maxPriceOfOptions: 0, + wasLikedByMe: false, + ), + ); + + when(mockChatRepository.getChosenPlan(id: 1)) + .thenAnswer((_) async => chosenPlan); + + await cubit.getChosenPlan(id: 1); + + expect(cubit.state.isLoading, isFalse); + expect(cubit.state.chosenPlan, equals(chosenPlan)); + verify(mockChatRepository.getChosenPlan(id: 1)).called(1); + }); + + test('getChosenPlan - загрузка плана с профилем клиента', () async { + final chosenPlan = ChosenPlanModel( + id: 1, + optionType: 'options1', + startDate: DateTime.now(), + chosenPlanState: ChosenPlanStateEnum.stateStarted, + chatId: 'chat-1', + consultantId: 1, + plan: const PlanModel( + id: 1, + slug: 'test-plan', + name: 'Test Plan', + image: '', + duration: 30, + state: 'active', + type: PlanType(fit: false, slim: false, behavior: false, wellness: false), + details: '', + packetsCount: 1, + author: Author( + authorSlug: 'author-slug', + authorName: 'Author Name', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + isFavorite: false, + minPriceOfOptions: 0, + maxPriceOfOptions: 0, + wasLikedByMe: false, + ), + ); + + const customerProfile = ProfileModel( + id: 1, + name: 'Test User', + email: 'test@example.com', + phoneConfirmationState: 'confirmed', + isPublicProfile: true, + isBlockedByMe: false, + isBlockedByAuthor: false, + isBlockedByUser: false, + isEntitySubscribedByMe: false, + slug: 'test-user', + profilePhotoUrl: '', + roles: [], + badges: [], + subscriptions: [], + subscribers: [], + ); + + when(mockChatRepository.getChosenPlan(id: 1)) + .thenAnswer((_) async => chosenPlan); + + when(mockProfileRepository.getProfileBySlug('test-user')) + .thenAnswer((_) async => customerProfile); + + await cubit.getChosenPlan(id: 1, customerSlug: 'test-user'); + + expect(cubit.state.isLoading, isFalse); + expect(cubit.state.chosenPlan, equals(chosenPlan)); + expect(cubit.state.customerProfile, equals(customerProfile)); + verify(mockChatRepository.getChosenPlan(id: 1)).called(1); + verify(mockProfileRepository.getProfileBySlug('test-user')).called(1); + }); + + test('getChosenPlan - обработка ошибки', () async { + when(mockChatRepository.getChosenPlan(id: 1)) + .thenThrow(Exception('Ошибка загрузки')); + + await cubit.getChosenPlan(id: 1); + + expect(cubit.state.isLoading, isFalse); + expect(cubit.state.chosenPlan, isNull); + }); + + test('getPaymentLink - успешное получение ссылки на оплату', () async { + final chosenPlan = ChosenPlanModel( + id: 1, + optionType: 'options1', + startDate: DateTime.now(), + chosenPlanState: ChosenPlanStateEnum.stateStarted, + chatId: 'chat-1', + consultantId: 1, + plan: const PlanModel( + id: 1, + slug: 'test-plan', + name: 'Test Plan', + image: '', + duration: 30, + state: 'active', + type: PlanType(fit: false, slim: false, behavior: false, wellness: false), + details: '', + packetsCount: 1, + author: Author( + authorSlug: 'author-slug', + authorName: 'Author Name', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + isFavorite: false, + minPriceOfOptions: 0, + maxPriceOfOptions: 0, + wasLikedByMe: false, + ), + ); + final paymentModel = PaymentModel(paymentUrl: 'https://payment.url'); + + // Сначала устанавливаем план в состояние + when(mockChatRepository.getChosenPlan(id: 1)) + .thenAnswer((_) async => chosenPlan); + await cubit.getChosenPlan(id: 1); + + when(mockChatRepository.getPaymentLink(id: 1)) + .thenAnswer((_) async => paymentModel); + + final result = await cubit.getPaymentLink(); + + expect(result, equals('https://payment.url')); + verify(mockChatRepository.getPaymentLink(id: 1)).called(1); + }); + + test('getPaymentLink - возвращает null, если план не выбран', () async { + final result = await cubit.getPaymentLink(); + + expect(result, isNull); + verifyNever(mockChatRepository.getPaymentLink(id: anyNamed('id'))); + }); + + test('getPaymentLink - обработка ошибки', () async { + final chosenPlan = ChosenPlanModel( + id: 1, + optionType: 'options1', + startDate: DateTime.now(), + chosenPlanState: ChosenPlanStateEnum.stateStarted, + chatId: 'chat-1', + consultantId: 1, + plan: const PlanModel( + id: 1, + slug: 'test-plan', + name: 'Test Plan', + image: '', + duration: 30, + state: 'active', + type: PlanType(fit: false, slim: false, behavior: false, wellness: false), + details: '', + packetsCount: 1, + author: Author( + authorSlug: 'author-slug', + authorName: 'Author Name', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + isFavorite: false, + minPriceOfOptions: 0, + maxPriceOfOptions: 0, + wasLikedByMe: false, + ), + ); + + when(mockChatRepository.getChosenPlan(id: 1)) + .thenAnswer((_) async => chosenPlan); + await cubit.getChosenPlan(id: 1); + + when(mockChatRepository.getPaymentLink(id: 1)) + .thenThrow(Exception('Ошибка')); + + final result = await cubit.getPaymentLink(); + + expect(result, isNull); + }); + }); +} + diff --git a/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit_test.dart b/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit_test.dart new file mode 100644 index 00000000..82df287b --- /dev/null +++ b/test/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit_test.dart @@ -0,0 +1,271 @@ +import 'package:eatvio_app/features/consultations/models/consultation_model.dart'; +import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; +import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart'; +import 'package:eatvio_app/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'personal_diet_suggestion_cubit_test.mocks.dart'; + +@GenerateMocks([DietRepository, PersonalDietSuggestionRepository]) +void main() { + group('PersonalDietSuggestionCubit', () { + late PersonalDietSuggestionCubit cubit; + late MockDietRepository mockDietRepository; + late MockPersonalDietSuggestionRepository mockPersonalDietSuggestionRepository; + + setUp(() { + mockDietRepository = MockDietRepository(); + mockPersonalDietSuggestionRepository = MockPersonalDietSuggestionRepository(); + cubit = PersonalDietSuggestionCubit( + dietRepository: mockDietRepository, + personalDietSuggestionService: mockPersonalDietSuggestionRepository, + ); + }); + + tearDown(() { + cubit.close(); + }); + + test('начальное состояние', () { + expect(cubit.state.consultationsWithDiet, isEmpty); + expect(cubit.state.consultationsWithoutDiet, isEmpty); + expect(cubit.state.dietName, isEmpty); + expect(cubit.state.isLoading, isFalse); + expect(cubit.state.error, isNull); + }); + + test('setDietName - успешная установка названия диеты', () async { + const dietId = 1; + const dietName = 'Test Diet'; + const diet = Diet( + id: dietId, + name: dietName, + slug: 'test-diet', + image: '', + duration: 30, + state: DietState.active, + type: DietType(light: false, veg: false, carb: false, meat: false), + details: '', + dailySchedule: {}, + dailyNutrition: [], + author: Author( + authorSlug: 'author-slug', + authorName: 'Author Name', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + isFavorite: false, + wasLikedByMe: false, + ); + + when(mockDietRepository.getDiet(dietId)) + .thenAnswer((_) async => diet); + + await cubit.setDietName(dietId); + + expect(cubit.state.dietName, equals(dietName)); + expect(cubit.state.isLoading, isFalse); + verify(mockDietRepository.getDiet(dietId)).called(1); + }); + + test('setDietName - обработка ошибки', () async { + const dietId = 1; + final error = Exception('Ошибка загрузки'); + + when(mockDietRepository.getDiet(dietId)) + .thenThrow(error); + + await cubit.setDietName(dietId); + + expect(cubit.state.isLoading, isFalse); + expect(cubit.state.error, equals(error.toString())); + }); + + test('getConsultationWithPersonalDiets - успешная загрузка консультаций', () async { + const dietId = 1; + const dietName = 'Test Diet'; + const diet = Diet( + id: dietId, + name: dietName, + slug: 'test-diet', + image: '', + duration: 30, + state: DietState.active, + type: DietType(light: false, veg: false, carb: false, meat: false), + details: '', + dailySchedule: {}, + dailyNutrition: [], + author: Author( + authorSlug: 'author-slug', + authorName: 'Author Name', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + isFavorite: false, + wasLikedByMe: false, + ); + + final consultations = [ + ConsultationModel( + id: 1, + chosenPlanState: ChosenPlanStateEnum.stateStarted, + planTitle: 'Plan 1', + userName: 'User 1', + userSlug: 'user-1', + consultantPayment: 100.0, + duration: 30, + currentDiaryDay: 1, + userProfilePhotoUrl: '', + consultationOptionPrice: 100, + startDate: DateTime.now(), + endDate: DateTime.now().add(const Duration(days: 30)), + consultantId: 1, + diaries: [], + personalDietId: 1, // С диетой + ), + ConsultationModel( + id: 2, + chosenPlanState: ChosenPlanStateEnum.stateStarted, + planTitle: 'Plan 2', + userName: 'User 2', + userSlug: 'user-2', + consultantPayment: 100.0, + duration: 30, + currentDiaryDay: 1, + userProfilePhotoUrl: '', + consultationOptionPrice: 100, + startDate: DateTime.now(), + endDate: DateTime.now().add(const Duration(days: 30)), + consultantId: 1, + diaries: [], + personalDietId: null, // Без диеты + ), + ]; + + when(mockDietRepository.getDiet(dietId)) + .thenAnswer((_) async => diet); + + when(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()) + .thenAnswer((_) async => consultations); + + await cubit.getConsultationWithPersonalDiets(dietId); + + expect(cubit.state.dietName, equals(dietName)); + expect(cubit.state.consultationsWithDiet.length, 1); + expect(cubit.state.consultationsWithoutDiet.length, 1); + expect(cubit.state.isLoading, isFalse); + verify(mockDietRepository.getDiet(dietId)).called(1); + verify(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()).called(1); + }); + + test('attachDietToConsultation - успешное прикрепление диеты', () async { + const dietId = 1; + const consultationId = 1; + + when(mockPersonalDietSuggestionRepository.attachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + )).thenAnswer((_) async => {}); + + // Устанавливаем dietId через getConsultationWithPersonalDiets + const diet = Diet( + id: dietId, + name: 'Test Diet', + slug: 'test-diet', + image: '', + duration: 30, + state: DietState.active, + type: DietType(light: false, veg: false, carb: false, meat: false), + details: '', + dailySchedule: {}, + dailyNutrition: [], + author: Author( + authorSlug: 'author-slug', + authorName: 'Author Name', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + isFavorite: false, + wasLikedByMe: false, + ); + + when(mockDietRepository.getDiet(dietId)) + .thenAnswer((_) async => diet); + + when(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()) + .thenAnswer((_) async => []); + + await cubit.getConsultationWithPersonalDiets(dietId); + final result = await cubit.attachDietToConsultation(consultationId: consultationId); + + expect(result, isTrue); + verify(mockPersonalDietSuggestionRepository.attachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + )).called(1); + }); + + test('reattachDietToConsultation - успешное переприкрепление диеты', () async { + const dietId = 1; + const consultationId = 1; + + const diet = Diet( + id: dietId, + name: 'Test Diet', + slug: 'test-diet', + image: '', + duration: 30, + state: DietState.active, + type: DietType(light: false, veg: false, carb: false, meat: false), + details: '', + dailySchedule: {}, + dailyNutrition: [], + author: Author( + authorSlug: 'author-slug', + authorName: 'Author Name', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + isFavorite: false, + wasLikedByMe: false, + ); + + when(mockDietRepository.getDiet(dietId)) + .thenAnswer((_) async => diet); + + when(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()) + .thenAnswer((_) async => []); + + when(mockPersonalDietSuggestionRepository.reattachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + )).thenAnswer((_) async => {}); + + await cubit.getConsultationWithPersonalDiets(dietId); + final result = await cubit.reattachDietToConsultation(consultationId: consultationId); + + expect(result, isTrue); + verify(mockPersonalDietSuggestionRepository.reattachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + )).called(1); + }); + }); +} + diff --git a/test/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository_test.dart b/test/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository_test.dart new file mode 100644 index 00000000..914732d4 --- /dev/null +++ b/test/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository_test.dart @@ -0,0 +1,109 @@ +import 'package:eatvio_app/features/consultations/models/consultation_model.dart'; +import 'package:eatvio_app/features/personal_diet_suggestion/repository/personal_diet_suggestion_repository.dart'; +import 'package:eatvio_app/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'personal_diet_suggestion_repository_test.mocks.dart'; + +@GenerateMocks([PersonalDietSuggestionService]) +void main() { + group('PersonalDietSuggestionRepository', () { + late PersonalDietSuggestionRepository repository; + late MockPersonalDietSuggestionService mockService; + + setUp(() { + mockService = MockPersonalDietSuggestionService(); + repository = PersonalDietSuggestionRepository( + personalDietSuggestionService: mockService, + ); + }); + + test('getConsultationWithPersonalDiets - успешная загрузка консультаций', () async { + final consultations = [ + ConsultationModel( + id: 1, + chosenPlanState: ChosenPlanStateEnum.stateStarted, + planTitle: 'Plan 1', + userName: 'User 1', + userSlug: 'user-1', + consultantPayment: 100.0, + duration: 30, + currentDiaryDay: 1, + userProfilePhotoUrl: '', + consultationOptionPrice: 100, + startDate: DateTime.now(), + endDate: DateTime.now().add(const Duration(days: 30)), + consultantId: 1, + diaries: [], + personalDietId: 1, + ), + ]; + + final paginationModel = ConsultationPaginationModel(data: consultations); + + when(mockService.getConsultationWithPersonalDiets()) + .thenAnswer((_) async => paginationModel); + + final result = await repository.getConsultationWithPersonalDiets(); + + expect(result, equals(consultations)); + verify(mockService.getConsultationWithPersonalDiets()).called(1); + }); + + test('getConsultationWithPersonalDiets - проброс ошибки', () async { + final error = Exception('Ошибка загрузки'); + when(mockService.getConsultationWithPersonalDiets()) + .thenThrow(error); + + expect( + () => repository.getConsultationWithPersonalDiets(), + throwsA(error), + ); + verify(mockService.getConsultationWithPersonalDiets()).called(1); + }); + + test('attachPersonalDiet - успешное прикрепление диеты', () async { + const consultationId = 1; + const dietId = 2; + + when(mockService.attachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + )).thenAnswer((_) async => {}); + + await repository.attachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + ); + + verify(mockService.attachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + )).called(1); + }); + + test('reattachPersonalDiet - успешное переприкрепление диеты', () async { + const consultationId = 1; + const dietId = 2; + + when(mockService.reattachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + )).thenAnswer((_) async => {}); + + await repository.reattachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + ); + + verify(mockService.reattachPersonalDiet( + consultationId: consultationId, + dietId: dietId, + )).called(1); + }); + }); +} + diff --git a/test/features/profile/presentation/basic_widget_test.dart b/test/features/profile/presentation/basic_widget_test.dart new file mode 100644 index 00000000..e92f2906 --- /dev/null +++ b/test/features/profile/presentation/basic_widget_test.dart @@ -0,0 +1,447 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../../fixtures/doubles/profile_doubles.dart'; +import '../../../fixtures/fixture_reader.dart'; + +void main() { + group('Profile Basic Widget Tests', () { + late FixtureProfileRepository profileRepository; + late FixtureChatRepository chatRepository; + late FixtureConsultantRepository consultantRepository; + late ProfileCubit profileCubit; + late Map weightFixture; + late Map circumferenceFixture; + + setUp(() { + weightFixture = FixtureReader.readAsMap('profile/add_weight_request.json'); + circumferenceFixture = FixtureReader.readAsMap('profile/add_circumference_request.json'); + profileRepository = FixtureProfileRepository(); + chatRepository = FixtureChatRepository(); + consultantRepository = FixtureConsultantRepository(); + profileCubit = ProfileCubit(profileRepository: profileRepository, chatRepository: chatRepository, consultantRepository: consultantRepository); + }); + + tearDown(() { + profileCubit.close(); + }); + + Widget createTestWidget(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + home: BlocProvider( + create: (context) => profileCubit, + child: Scaffold(body: SingleChildScrollView(child: child)), + ), + ); + } + + testWidgets('should create ProfileCubit successfully', (WidgetTester tester) async { + // Arrange & Act + final cubit = ProfileCubit(profileRepository: profileRepository, chatRepository: chatRepository, consultantRepository: consultantRepository); + + // Assert + expect(cubit, isA()); + expect(cubit.state, isA()); + + cubit.close(); + }); + + testWidgets('should display weight input field', (WidgetTester tester) async { + // Arrange + Widget weightWidget = TextFormField( + key: const Key('weightField'), + decoration: const InputDecoration(labelText: 'Вес', hintText: 'Введите вес в кг'), + keyboardType: TextInputType.number, + ); + + // Act + await tester.pumpWidget(createTestWidget(weightWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byKey(const Key('weightField')), findsOneWidget); + expect(find.text('Вес'), findsOneWidget); + expect(find.text('Введите вес в кг'), findsOneWidget); + }); + + testWidgets('should update weight when user types in weight field', (WidgetTester tester) async { + // Arrange + Widget weightWidget = TextFormField( + key: const Key('weightField'), + decoration: const InputDecoration(labelText: 'Вес'), + keyboardType: TextInputType.number, + ); + + await tester.pumpWidget(createTestWidget(weightWidget)); + await tester.pumpAndSettle(); + + final testWeight = weightFixture['weight'] as double; + final testWeightString = testWeight.toString(); + + // Act + await tester.enterText(find.byKey(const Key('weightField')), testWeightString); + await tester.pump(); + + // Assert + expect(find.text(testWeightString), findsOneWidget); + }); + + testWidgets('should display circumference input fields', (WidgetTester tester) async { + // Arrange + Widget circumferenceWidget = Column( + children: [ + TextFormField( + key: const Key('chestCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват груди (см)'), + keyboardType: TextInputType.number, + ), + const SizedBox(height: 16), + TextFormField( + key: const Key('waistCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват талии (см)'), + keyboardType: TextInputType.number, + ), + const SizedBox(height: 16), + TextFormField( + key: const Key('hipCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват бедер (см)'), + keyboardType: TextInputType.number, + ), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(circumferenceWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byKey(const Key('chestCircumferenceField')), findsOneWidget); + expect(find.byKey(const Key('waistCircumferenceField')), findsOneWidget); + expect(find.byKey(const Key('hipCircumferenceField')), findsOneWidget); + expect(find.text('Обхват груди (см)'), findsOneWidget); + expect(find.text('Обхват талии (см)'), findsOneWidget); + expect(find.text('Обхват бедер (см)'), findsOneWidget); + }); + + testWidgets('should update circumference values when user types', (WidgetTester tester) async { + // Arrange + Widget circumferenceWidget = Column( + children: [ + TextFormField( + key: const Key('chestCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват груди (см)'), + keyboardType: TextInputType.number, + ), + TextFormField( + key: const Key('waistCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват талии (см)'), + keyboardType: TextInputType.number, + ), + TextFormField( + key: const Key('hipCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват бедер (см)'), + keyboardType: TextInputType.number, + ), + ], + ); + + await tester.pumpWidget(createTestWidget(circumferenceWidget)); + await tester.pumpAndSettle(); + + final chestValue = (circumferenceFixture['chest_circumference'] as int).toString(); + final waistValue = (circumferenceFixture['waist_circumference'] as int).toString(); + final hipValue = (circumferenceFixture['hip_circumference'] as int).toString(); + + // Act + await tester.enterText(find.byKey(const Key('chestCircumferenceField')), chestValue); + await tester.enterText(find.byKey(const Key('waistCircumferenceField')), waistValue); + await tester.enterText(find.byKey(const Key('hipCircumferenceField')), hipValue); + await tester.pump(); + + // Assert + expect(find.text(chestValue), findsOneWidget); + expect(find.text(waistValue), findsOneWidget); + expect(find.text(hipValue), findsOneWidget); + }); + + testWidgets('should display save weight button', (WidgetTester tester) async { + // Arrange + Widget buttonWidget = ElevatedButton(key: const Key('saveWeightButton'), onPressed: () {}, child: const Text('Сохранить вес')); + + // Act + await tester.pumpWidget(createTestWidget(buttonWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byKey(const Key('saveWeightButton')), findsOneWidget); + expect(find.text('Сохранить вес'), findsOneWidget); + }); + + testWidgets('should display save circumference button', (WidgetTester tester) async { + // Arrange + Widget buttonWidget = ElevatedButton(key: const Key('saveCircumferenceButton'), onPressed: () {}, child: const Text('Сохранить замеры')); + + // Act + await tester.pumpWidget(createTestWidget(buttonWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byKey(const Key('saveCircumferenceButton')), findsOneWidget); + expect(find.text('Сохранить замеры'), findsOneWidget); + }); + + testWidgets('should handle save weight button tap', (WidgetTester tester) async { + // Arrange + bool buttonPressed = false; + Widget buttonWidget = ElevatedButton( + key: const Key('saveWeightButton'), + onPressed: () { + buttonPressed = true; + }, + child: const Text('Сохранить вес'), + ); + + await tester.pumpWidget(createTestWidget(buttonWidget)); + await tester.pumpAndSettle(); + + // Act + await tester.tap(find.byKey(const Key('saveWeightButton'))); + await tester.pump(); + + // Assert + expect(buttonPressed, isTrue); + }); + + testWidgets('should handle save circumference button tap', (WidgetTester tester) async { + // Arrange + bool buttonPressed = false; + Widget buttonWidget = ElevatedButton( + key: const Key('saveCircumferenceButton'), + onPressed: () { + buttonPressed = true; + }, + child: const Text('Сохранить замеры'), + ); + + await tester.pumpWidget(createTestWidget(buttonWidget)); + await tester.pumpAndSettle(); + + // Act + await tester.tap(find.byKey(const Key('saveCircumferenceButton'))); + await tester.pump(); + + // Assert + expect(buttonPressed, isTrue); + }); + + testWidgets('should display profile information fields', (WidgetTester tester) async { + // Arrange + Widget profileWidget = const Column(children: [Text('Имя: Анна'), Text('Email: anna@example.com'), Text('Вес: 65.0 кг'), Text('Рост: 170 см')]); + + // Act + await tester.pumpWidget(createTestWidget(profileWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Имя: Анна'), findsOneWidget); + expect(find.text('Email: anna@example.com'), findsOneWidget); + expect(find.text('Вес: 65.0 кг'), findsOneWidget); + expect(find.text('Рост: 170 см'), findsOneWidget); + }); + + testWidgets('should display weight chart section', (WidgetTester tester) async { + // Arrange + Widget chartWidget = Column( + children: [ + const Text('График веса'), + Container( + key: const Key('weightChartContainer'), + height: 200, + color: Colors.grey[200], + child: const Center(child: Text('График веса')), + ), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(chartWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('График веса'), findsNWidgets(2)); + expect(find.byKey(const Key('weightChartContainer')), findsOneWidget); + }); + + testWidgets('should display circumference chart section', (WidgetTester tester) async { + // Arrange + Widget chartWidget = Column( + children: [ + const Text('График замеров'), + Container( + key: const Key('circumferenceChartContainer'), + height: 200, + color: Colors.grey[200], + child: const Center(child: Text('График замеров')), + ), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(chartWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('График замеров'), findsNWidgets(2)); + expect(find.byKey(const Key('circumferenceChartContainer')), findsOneWidget); + }); + + testWidgets('should send correct request when adding weight', (WidgetTester tester) async { + // Arrange + final testWeight = weightFixture['weight'] as double; + + // Act + await profileCubit.addWeight(weight: testWeight); + await tester.pumpAndSettle(); + + // Assert + expect(profileRepository.addWeightRequests.length, 1); + final request = profileRepository.addWeightRequests.single; + expect(request['weight'], testWeight); + }); + + testWidgets('should send correct request when adding circumference', (WidgetTester tester) async { + // Arrange + final chest = circumferenceFixture['chest_circumference'] as int; + final waist = circumferenceFixture['waist_circumference'] as int; + final hip = circumferenceFixture['hip_circumference'] as int; + + // Act + await profileCubit.addCircumference(chestCircumference: chest, waistCircumference: waist, hipCircumference: hip); + await tester.pumpAndSettle(); + + // Assert + expect(profileRepository.addCircumferenceRequests.length, 1); + final request = profileRepository.addCircumferenceRequests.single; + expect(request['chest_circumference'], chest); + expect(request['waist_circumference'], waist); + expect(request['hip_circumference'], hip); + }); + + testWidgets('should display loading state', (WidgetTester tester) async { + // Arrange + Widget loadingWidget = const Center(child: CircularProgressIndicator()); + + // Act + await tester.pumpWidget(createTestWidget(loadingWidget)); + await tester.pump(); + + // Assert + expect(find.byType(CircularProgressIndicator), findsOneWidget); + }); + + testWidgets('should display error message', (WidgetTester tester) async { + // Arrange + Widget errorWidget = const Center(child: Text('Произошла ошибка при загрузке профиля')); + + // Act + await tester.pumpWidget(createTestWidget(errorWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Произошла ошибка при загрузке профиля'), findsOneWidget); + }); + + testWidgets('should validate weight input', (WidgetTester tester) async { + // Arrange + Widget validationWidget = TextFormField( + key: const Key('weightField'), + decoration: const InputDecoration(labelText: 'Вес', errorText: 'Введите корректное значение веса'), + ); + + // Act + await tester.pumpWidget(createTestWidget(validationWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Введите корректное значение веса'), findsOneWidget); + }); + + testWidgets('should validate circumference inputs', (WidgetTester tester) async { + // Arrange + Widget validationWidget = Column( + children: [ + TextFormField( + key: const Key('chestCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват груди (см)', errorText: 'Введите корректное значение'), + ), + TextFormField( + key: const Key('waistCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват талии (см)', errorText: 'Введите корректное значение'), + ), + TextFormField( + key: const Key('hipCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват бедер (см)', errorText: 'Введите корректное значение'), + ), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(validationWidget)); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Введите корректное значение'), findsNWidgets(3)); + }); + + testWidgets('should display complete profile form', (WidgetTester tester) async { + // Arrange + Widget completeForm = Column( + children: [ + TextFormField( + key: const Key('weightField'), + decoration: const InputDecoration(labelText: 'Вес'), + keyboardType: TextInputType.number, + ), + const SizedBox(height: 16), + TextFormField( + key: const Key('chestCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват груди (см)'), + keyboardType: TextInputType.number, + ), + const SizedBox(height: 16), + TextFormField( + key: const Key('waistCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват талии (см)'), + keyboardType: TextInputType.number, + ), + const SizedBox(height: 16), + TextFormField( + key: const Key('hipCircumferenceField'), + decoration: const InputDecoration(labelText: 'Обхват бедер (см)'), + keyboardType: TextInputType.number, + ), + const SizedBox(height: 32), + ElevatedButton(key: const Key('saveWeightButton'), onPressed: () {}, child: const Text('Сохранить вес')), + ElevatedButton(key: const Key('saveCircumferenceButton'), onPressed: () {}, child: const Text('Сохранить замеры')), + ], + ); + + // Act + await tester.pumpWidget(createTestWidget(completeForm)); + await tester.pumpAndSettle(); + + // Assert + expect(find.byKey(const Key('weightField')), findsOneWidget); + expect(find.byKey(const Key('chestCircumferenceField')), findsOneWidget); + expect(find.byKey(const Key('waistCircumferenceField')), findsOneWidget); + expect(find.byKey(const Key('hipCircumferenceField')), findsOneWidget); + expect(find.byKey(const Key('saveWeightButton')), findsOneWidget); + expect(find.byKey(const Key('saveCircumferenceButton')), findsOneWidget); + }); + }); +} diff --git a/test/features/registration_v2/cubit/registration_cubit_v2_test.dart b/test/features/registration_v2/cubit/registration_cubit_v2_test.dart new file mode 100644 index 00000000..cec3aa9a --- /dev/null +++ b/test/features/registration_v2/cubit/registration_cubit_v2_test.dart @@ -0,0 +1,241 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart'; +import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'registration_cubit_v2_test.mocks.dart'; + +@GenerateMocks([RegistrationRepositoryV2]) +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('RegistrationCubitV2', () { + late RegistrationCubitV2 cubit; + late MockRegistrationRepositoryV2 mockRepository; + const MethodChannel passwordGeneratorChannel = MethodChannel('flutter_password_generator'); + + setUp(() { + mockRepository = MockRegistrationRepositoryV2(); + cubit = RegistrationCubitV2(registrationRepository: mockRepository); + + // Инициализируем SharedPreferences для тестов + SharedPreferences.setMockInitialValues({}); + + // Мокируем MethodChannel для flutter_password_generator + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + passwordGeneratorChannel, + (MethodCall methodCall) async { + if (methodCall.method == 'generateSecureRandomData') { + // Возвращаем Uint8List для генерации пароля + // MethodChannel автоматически преобразует Uint8List в List + return Uint8List.fromList(List.generate(32, (i) => i % 256)); + } + return null; + }, + ); + }); + + tearDown(() { + cubit.close(); + // Очищаем моки + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + passwordGeneratorChannel, + null, + ); + }); + + test('начальное состояние', () { + expect(cubit.state.firstName, isEmpty); + expect(cubit.state.lastName, isEmpty); + expect(cubit.state.email, isEmpty); + expect(cubit.state.phone, isEmpty); + expect(cubit.state.gender, isEmpty); + expect(cubit.state.step, 0); + }); + + test('setFirstName - устанавливает имя и валидирует', () { + cubit.setFirstName('John'); + + expect(cubit.state.firstName, equals('John')); + expect(cubit.state.isFirstNameValid, isTrue); + }); + + test('setFirstName - валидация пустого имени', () { + cubit.setFirstName(''); + + expect(cubit.state.isFirstNameValid, isFalse); + }); + + test('setLastName - устанавливает фамилию и валидирует', () { + cubit.setLastName('Doe'); + + expect(cubit.state.lastName, equals('Doe')); + expect(cubit.state.isLastNameValid, isTrue); + }); + + test('setEmail - устанавливает email и валидирует', () { + cubit.setEmail('test@example.com'); + + expect(cubit.state.email, equals('test@example.com')); + expect(cubit.state.isEmailValid, isTrue); + }); + + test('setPhone - устанавливает телефон и валидирует', () { + cubit.setPhone('+1234567890'); + + expect(cubit.state.phone, equals('+1234567890')); + expect(cubit.state.isPhoneValid, isTrue); + }); + + test('setGender - устанавливает пол и валидирует', () { + cubit.setGender('male'); + + expect(cubit.state.gender, equals('male')); + expect(cubit.state.isGenderValid, isTrue); + }); + + test('setWeight - устанавливает вес и валидирует', () { + cubit.setWeight(70); + + expect(cubit.state.weight, equals(70)); + expect(cubit.state.isWeightValid, isTrue); + }); + + test('setWeight - валидация нулевого веса', () { + cubit.setWeight(0); + + expect(cubit.state.isWeightValid, isFalse); + }); + + test('setHeight - устанавливает рост и валидирует', () { + cubit.setHeight(175); + + expect(cubit.state.height, equals(175)); + expect(cubit.state.isHeightValid, isTrue); + }); + + test('setActivityCoefficient - устанавливает коэффициент активности', () { + cubit.setActivityCoefficient(1.5); + + expect(cubit.state.activityCoefficient, equals(1.5)); + expect(cubit.state.isActivityCoefficientValid, isTrue); + }); + + test('setBirthday - устанавливает дату рождения и валидирует', () { + final birthday = DateTime(1990, 1, 1); + cubit.setBirthday(birthday); + + expect(cubit.state.birthday, equals(birthday)); + expect(cubit.state.isBirthdayValid, isTrue); + }); + + test('nextStep - переходит на следующий шаг', () { + cubit.nextStep(); + + expect(cubit.state.step, equals(1)); + }); + + test('prevStep - возвращается на предыдущий шаг', () { + cubit.nextStep(); + cubit.prevStep(); + + expect(cubit.state.step, equals(0)); + }); + + test('validateAllFields - возвращает true, если все поля валидны', () { + cubit.setFirstName('John'); + cubit.setLastName('Doe'); + cubit.setEmail('test@example.com'); + cubit.setPhone('+1234567890'); + cubit.setGender('male'); + cubit.setWeight(70); + cubit.setHeight(175); + cubit.setActivityCoefficient(1.5); + cubit.setBirthday(DateTime(1990, 1, 1)); + + final result = cubit.validateAllFields(); + + expect(result, isTrue); + }); + + test('validateAllFields - возвращает false, если есть невалидные поля', () { + cubit.setFirstName(''); // Пустое имя + + final result = cubit.validateAllFields(); + + expect(result, isFalse); + }); + + test('register - успешная регистрация', () async { + cubit.setFirstName('John'); + cubit.setLastName('Doe'); + cubit.setEmail('test@example.com'); + cubit.setPhone('+1234567890'); + cubit.setGender('male'); + cubit.setWeight(70); + cubit.setHeight(175); + cubit.setActivityCoefficient(1.5); + cubit.setBirthday(DateTime(1990, 1, 1)); + + const token = 'test-token'; + when(mockRepository.register(registrationModel: anyNamed('registrationModel'))) + .thenAnswer((_) async => token); + + final result = await cubit.register(); + + expect(result.$1, isTrue); + expect(result.$2, isFalse); + verify(mockRepository.register(registrationModel: anyNamed('registrationModel'))).called(1); + }); + + test('register - возвращает false при невалидных полях', () async { + cubit.setFirstName(''); // Пустое имя + + final result = await cubit.register(); + + expect(result.$1, isFalse); + expect(result.$2, isTrue); + verifyNever(mockRepository.register(registrationModel: anyNamed('registrationModel'))); + }); + + test('register - обработка ошибки валидации email', () async { + cubit.setFirstName('John'); + cubit.setLastName('Doe'); + cubit.setEmail('test@example.com'); + cubit.setPhone('+1234567890'); + cubit.setGender('male'); + cubit.setWeight(70); + cubit.setHeight(175); + cubit.setActivityCoefficient(1.5); + cubit.setBirthday(DateTime(1990, 1, 1)); + + final dioException = DioException( + requestOptions: RequestOptions(path: '/'), + response: Response( + requestOptions: RequestOptions(path: '/'), + statusCode: 422, + data: { + 'errors': { + 'email': ['Некорректный формат email'], + }, + }, + ), + ); + + when(mockRepository.register(registrationModel: anyNamed('registrationModel'))) + .thenThrow(dioException); + + final result = await cubit.register(); + + expect(result.$1, isFalse); + expect(result.$2, isTrue); + expect(cubit.state.isEmailValid, isFalse); + expect(cubit.state.emailDisplayError, equals('Некорректный формат email')); + }); + }); +} + diff --git a/test/features/registration_v2/repositories/registration_repository_v2_test.dart b/test/features/registration_v2/repositories/registration_repository_v2_test.dart new file mode 100644 index 00000000..2d8f618b --- /dev/null +++ b/test/features/registration_v2/repositories/registration_repository_v2_test.dart @@ -0,0 +1,73 @@ +import 'package:eatvio_app/features/registration_v2/models/registration_model.dart'; +import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart'; +import 'package:eatvio_app/features/registration_v2/services/registration_service_v2.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'registration_repository_v2_test.mocks.dart'; + +@GenerateMocks([RegistrationServiceV2]) +void main() { + group('RegistrationRepositoryV2', () { + late RegistrationRepositoryV2 repository; + late MockRegistrationServiceV2 mockService; + + setUp(() { + mockService = MockRegistrationServiceV2(); + repository = RegistrationRepositoryV2(registrationService: mockService); + }); + + test('register - успешная регистрация', () async { + final registrationModel = RegistrationModel( + firstName: 'John', + lastName: 'Doe', + email: 'test@example.com', + phone: '+1234567890', + gender: 'male', + password: 'password123', + confirmPassword: 'password123', + weight: 70, + height: 175, + activityCoefficient: 1.5, + birthday: '1990-01-01', + ); + + const token = 'test-token'; + when(mockService.register(model: anyNamed('model'))) + .thenAnswer((_) async => {'token': token}); + + final result = await repository.register(registrationModel: registrationModel); + + expect(result, equals(token)); + verify(mockService.register(model: anyNamed('model'))).called(1); + }); + + test('register - проброс ошибки', () async { + final registrationModel = RegistrationModel( + firstName: 'John', + lastName: 'Doe', + email: 'test@example.com', + phone: '+1234567890', + gender: 'male', + password: 'password123', + confirmPassword: 'password123', + weight: 70, + height: 175, + activityCoefficient: 1.5, + birthday: '1990-01-01', + ); + + final error = Exception('Ошибка регистрации'); + when(mockService.register(model: anyNamed('model'))) + .thenThrow(error); + + expect( + () => repository.register(registrationModel: registrationModel), + throwsA(error), + ); + verify(mockService.register(model: anyNamed('model'))).called(1); + }); + }); +} + diff --git a/test/features/settings/presentation/bloc/settings_cubit_test.dart b/test/features/settings/presentation/bloc/settings_cubit_test.dart new file mode 100644 index 00000000..2733bd07 --- /dev/null +++ b/test/features/settings/presentation/bloc/settings_cubit_test.dart @@ -0,0 +1,273 @@ +import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; +import 'package:eatvio_app/features/consultations/repositories/consultations_repository.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; +import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; +import 'package:eatvio_app/features/settings/repositories/service_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import '../../../../fixtures/settings_fixtures.dart'; +import 'settings_cubit_test.mocks.dart'; + +@GenerateNiceMocks([ + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), +]) +void main() { + group('SettingsCubit', () { + SettingsCubit? settingsCubit; + late MockProfileRepository mockProfileRepository; + late MockSettingsRepository mockSettingsRepository; + late MockConsultantRepository mockConsultantRepository; + late MockConsultationsRepository mockConsultationsRepository; + + + setUp(() { + mockProfileRepository = MockProfileRepository(); + mockSettingsRepository = MockSettingsRepository(); + mockConsultantRepository = MockConsultantRepository(); + mockConsultationsRepository = MockConsultationsRepository(); + }); + + tearDown(() async { + if (settingsCubit != null && !settingsCubit!.isClosed) { + await Future.delayed(const Duration(milliseconds: 100)); + settingsCubit!.close(); + settingsCubit = null; + } + }); + + test('начальное состояние - loading', () { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + ); + expect(settingsCubit!.state, const SettingsState.loading()); + }); + + test('init - успешно инициализирует состояние', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + ); + + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + when(mockProfileRepository.getMyProfileDetails()) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(settingsCubit!.state, isA()); + final loadedState = settingsCubit!.state as SettingsStateLoaded; + expect(loadedState.profile.id, SettingsFixtures.profileModel().id); + expect(loadedState.profileSettings.isMoodFillable, true); + }); + + test('init - обрабатывает ошибку при загрузке настроек', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + ); + + // Ошибка происходит при загрузке настроек профиля (внутри try-catch блока) + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenThrow(Exception('Ошибка загрузки настроек')); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 200)); + + expect(settingsCubit!.state, isA()); + final errorState = settingsCubit!.state as SettingsStateError; + expect(errorState.errorMessage, contains('Ошибка загрузки настроек')); + }); + + test('updateProfileDetails - обновляет детали профиля', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + ); + + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + when(mockProfileRepository.getMyProfileDetails()) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + when(mockSettingsRepository.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 100)); + await settingsCubit!.updateProfileDetails(profileDetailsModel: SettingsFixtures.profileDetailsModel()); + await Future.delayed(const Duration(milliseconds: 100)); + + verify(mockSettingsRepository.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).called(1); + }); + + test('updateProfileSettings - обновляет настройки профиля', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + ); + + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + when(mockProfileRepository.getMyProfileDetails()) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + when(mockSettingsRepository.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 100)); + await settingsCubit!.updateProfileSettings(profileSettingsModel: SettingsFixtures.profileSettingsModel()); + await Future.delayed(const Duration(milliseconds: 100)); + + verify(mockSettingsRepository.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).called(1); + }); + + test('deleteAccount - удаляет аккаунт', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + ); + + when(mockProfileRepository.deleteAccount()) + .thenAnswer((_) async => Future.value()); + + final result = await settingsCubit!.deleteAccount(); + + expect(result, true); + verify(mockProfileRepository.deleteAccount()).called(1); + }); + + test('deleteAccount - возвращает false при ошибке', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + ); + + when(mockProfileRepository.deleteAccount()) + .thenThrow(Exception('Ошибка удаления')); + + final result = await settingsCubit!.deleteAccount(); + + expect(result, false); + }); + + test('linkOAuthAccount - привязывает OAuth аккаунт', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + ); + + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + when(mockProfileRepository.getMyProfileDetails()) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + when(mockSettingsRepository.linkOAuthAccount(request: anyNamed('request'))) + .thenAnswer((_) async => Future.value()); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 100)); + await settingsCubit!.linkOAuthAccount( + provider: 'vk', + accessToken: 'access_token', + refreshToken: 'refresh_token', + ); + await Future.delayed(const Duration(milliseconds: 100)); + + verify(mockSettingsRepository.linkOAuthAccount(request: anyNamed('request'))).called(1); + }); + + test('unlinkOAuthAccount - отвязывает OAuth аккаунт', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + ); + + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + when(mockProfileRepository.getMyProfileDetails()) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + when(mockSettingsRepository.unlinkOAuthAccount(provider: anyNamed('provider'))) + .thenAnswer((_) async => Future.value()); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 100)); + await settingsCubit!.unlinkOAuthAccount(provider: 'vk'); + await Future.delayed(const Duration(milliseconds: 100)); + + verify(mockSettingsRepository.unlinkOAuthAccount(provider: anyNamed('provider'))).called(1); + }); + }); +} + diff --git a/test/features/settings/repositories/service_repository_test.dart b/test/features/settings/repositories/service_repository_test.dart new file mode 100644 index 00000000..bba546aa --- /dev/null +++ b/test/features/settings/repositories/service_repository_test.dart @@ -0,0 +1,110 @@ +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_account_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_attach_request.dart'; +import 'package:eatvio_app/features/settings/models/profile_settings_model.dart'; +import 'package:eatvio_app/features/settings/repositories/service_repository.dart'; +import 'package:eatvio_app/features/settings/services/settings_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import '../../../fixtures/settings_fixtures.dart'; +import 'service_repository_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('SettingsRepository', () { + late SettingsRepository settingsRepository; + late MockSettingsService mockSettingsService; + + setUp(() { + mockSettingsService = MockSettingsService(); + settingsRepository = SettingsRepository(settingsService: mockSettingsService); + }); + + test('getProfileSettings - возвращает настройки профиля', () async { + final expectedSettings = SettingsFixtures.profileSettingsModel(); + + when(mockSettingsService.getProfileSettings()) + .thenAnswer((_) async => expectedSettings); + + final result = await settingsRepository.getProfileSettings(); + + expect(result, isA()); + expect(result.isMoodFillable, true); + verify(mockSettingsService.getProfileSettings()).called(1); + }); + + test('updateProfileSettings - обновляет настройки профиля', () async { + final profileSettingsModel = SettingsFixtures.profileSettingsUpdatedModel(); + final expectedSettings = SettingsFixtures.profileSettingsUpdatedModel(); + + when(mockSettingsService.updateProfileSettings(data: anyNamed('data'))) + .thenAnswer((_) async => expectedSettings); + + final result = await settingsRepository.updateProfileSettings( + profileSettingsModel: profileSettingsModel, + ); + + expect(result, isA()); + expect(result.isMoodFillable, false); + verify(mockSettingsService.updateProfileSettings(data: anyNamed('data'))).called(1); + }); + + test('updateProfileDetails - обновляет детали профиля', () async { + final profileDetailsModel = SettingsFixtures.profileDetailsModel(); + final expectedDetails = SettingsFixtures.profileDetailsModel(); + + when(mockSettingsService.updateProfileDetails(data: anyNamed('data'))) + .thenAnswer((_) async => expectedDetails); + + final result = await settingsRepository.updateProfileDetails( + profileDetailsModel: profileDetailsModel, + ); + + expect(result, isA()); + expect(result.firstName, expectedDetails.firstName); + verify(mockSettingsService.updateProfileDetails(data: anyNamed('data'))).called(1); + }); + + test('getOAuthAccounts - возвращает список OAuth аккаунтов', () async { + final expectedResponse = SettingsFixtures.oauthAccountsResponseModel(); + + when(mockSettingsService.getOAuthAccounts()) + .thenAnswer((_) async => expectedResponse); + + final result = await settingsRepository.getOAuthAccounts(); + + expect(result, isA()); + expect(result.success, true); + verify(mockSettingsService.getOAuthAccounts()).called(1); + }); + + test('linkOAuthAccount - привязывает OAuth аккаунт', () async { + const request = OAuthAttachRequest( + provider: 'vk', + accessToken: 'access_token', + refreshToken: 'refresh_token', + clientId: 'client_id', + ); + + when(mockSettingsService.linkOAuthAccount(request)) + .thenAnswer((_) async => Future.value()); + + await settingsRepository.linkOAuthAccount(request: request); + + verify(mockSettingsService.linkOAuthAccount(request)).called(1); + }); + + test('unlinkOAuthAccount - отвязывает OAuth аккаунт', () async { + const provider = 'vk'; + + when(mockSettingsService.unlinkOAuthAccount(provider)) + .thenAnswer((_) async => Future.value()); + + await settingsRepository.unlinkOAuthAccount(provider: provider); + + verify(mockSettingsService.unlinkOAuthAccount(provider)).called(1); + }); + }); +} + diff --git a/test/features/settings/services/settings_service_test.dart b/test/features/settings/services/settings_service_test.dart new file mode 100644 index 00000000..9faa255d --- /dev/null +++ b/test/features/settings/services/settings_service_test.dart @@ -0,0 +1,114 @@ +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_account_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_attach_request.dart'; +import 'package:eatvio_app/features/settings/models/profile_settings_model.dart'; +import 'package:eatvio_app/features/settings/services/settings_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import '../../../fixtures/settings_fixtures.dart'; +import 'settings_service_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec()]) +void main() { + group('SettingsService', () { + late MockSettingsService mockSettingsService; + + setUp(() { + mockSettingsService = MockSettingsService(); + }); + + test('getProfileSettings - возвращает настройки профиля', () async { + final expectedSettings = SettingsFixtures.profileSettingsModel(); + + when(mockSettingsService.getProfileSettings()) + .thenAnswer((_) async => expectedSettings); + + final result = await mockSettingsService.getProfileSettings(); + + expect(result, isA()); + expect(result.isMoodFillable, true); + expect(result.isPublicProfile, true); + verify(mockSettingsService.getProfileSettings()).called(1); + }); + + test('updateProfileSettings - обновляет настройки профиля', () async { + final data = { + 'is_mood_fillable': false, + 'is_bedtime_fillable': false, + 'is_public_profile': false, + }; + final expectedSettings = SettingsFixtures.profileSettingsUpdatedModel(); + + when(mockSettingsService.updateProfileSettings(data: data)) + .thenAnswer((_) async => expectedSettings); + + final result = await mockSettingsService.updateProfileSettings(data: data); + + expect(result, isA()); + expect(result.isMoodFillable, false); + expect(result.isPublicProfile, false); + verify(mockSettingsService.updateProfileSettings(data: data)).called(1); + }); + + test('updateProfileDetails - обновляет детали профиля', () async { + final data = { + 'first_name': 'John', + 'last_name': 'Doe', + 'weight': 75.0, + }; + final expectedDetails = SettingsFixtures.profileDetailsModel(); + + when(mockSettingsService.updateProfileDetails(data: data)) + .thenAnswer((_) async => expectedDetails); + + final result = await mockSettingsService.updateProfileDetails(data: data); + + expect(result, isA()); + expect(result.firstName, expectedDetails.firstName); + expect(result.weight, expectedDetails.weight); + verify(mockSettingsService.updateProfileDetails(data: data)).called(1); + }); + + test('getOAuthAccounts - возвращает список OAuth аккаунтов', () async { + final expectedResponse = SettingsFixtures.oauthAccountsResponseModel(); + + when(mockSettingsService.getOAuthAccounts()) + .thenAnswer((_) async => expectedResponse); + + final result = await mockSettingsService.getOAuthAccounts(); + + expect(result, isA()); + expect(result.success, true); + verify(mockSettingsService.getOAuthAccounts()).called(1); + }); + + test('linkOAuthAccount - привязывает OAuth аккаунт', () async { + const request = OAuthAttachRequest( + provider: 'vk', + accessToken: 'access_token', + refreshToken: 'refresh_token', + clientId: 'client_id', + ); + + when(mockSettingsService.linkOAuthAccount(request)) + .thenAnswer((_) async => Future.value()); + + await mockSettingsService.linkOAuthAccount(request); + + verify(mockSettingsService.linkOAuthAccount(request)).called(1); + }); + + test('unlinkOAuthAccount - отвязывает OAuth аккаунт', () async { + const provider = 'vk'; + + when(mockSettingsService.unlinkOAuthAccount(provider)) + .thenAnswer((_) async => Future.value()); + + await mockSettingsService.unlinkOAuthAccount(provider); + + verify(mockSettingsService.unlinkOAuthAccount(provider)).called(1); + }); + }); +} + diff --git a/test/features/user_details/presentation/cubit/user_details_cubit_test.dart b/test/features/user_details/presentation/cubit/user_details_cubit_test.dart new file mode 100644 index 00000000..e12fa8f2 --- /dev/null +++ b/test/features/user_details/presentation/cubit/user_details_cubit_test.dart @@ -0,0 +1,193 @@ +import 'package:eatvio_app/features/profile/models/circumference_model.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/models/weight_model.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'user_details_cubit_test.mocks.dart'; + +@GenerateMocks([ProfileRepository]) +void main() { + group('UserDetailsCubit', () { + late UserDetailsCubit cubit; + late MockProfileRepository mockProfileRepository; + + setUp(() { + mockProfileRepository = MockProfileRepository(); + cubit = UserDetailsCubit(profileRepository: mockProfileRepository); + }); + + tearDown(() { + cubit.close(); + }); + + test('начальное состояние', () { + expect(cubit.state.isLoading, isFalse); + expect(cubit.state.error, isNull); + expect(cubit.state.profileDetails, isNull); + expect(cubit.state.weightPoints, isNull); + expect(cubit.state.circumferencePoints, isNull); + }); + + test('getUserDetails - успешная загрузка деталей пользователя', () async { + const slug = 'test-user'; + const profileDetails = ProfileDetailsModel( + firstName: 'Test', + lastName: 'User', + birthdate: '1990-01-01', + gender: 'male', + country: 'Russia', + city: 'Moscow', + lang: 'ru', + weight: 70.0, + height: 175, + chestCircumference: 100, + waistCircumference: 80, + hipCircumference: 90, + bloodPressureUp: 120, + bloodPressureDown: 80, + hasHypo: false, + hasHyper: false, + aboutAlergy: '', + aboutTakingPils: '', + aboutSportHobbies: '', + favoriteFoods: '', + unfavoriteFoods: '', + additionalInfo: '', + isMoodFillable: false, + isBedtimeFillable: false, + activityCoefficient: 1.5, + ); + + final weightPoints = [ + WeightModel( + id: 1, + userId: 1, + weight: 70, + createdAt: DateTime.now(), + updatedAt: DateTime.now(), + bmi: 22.9, + ), + ]; + + final circumferencePoints = [ + CircumferenceModel( + id: 1, + userId: 1, + chestCircumference: 100, + waistCircumference: 80, + hipCircumference: 90, + createdAt: DateTime.now(), + updatedAt: DateTime.now(), + ), + ]; + + when(mockProfileRepository.getProfileDetailsBySlug(slug)) + .thenAnswer((_) async => profileDetails); + + when(mockProfileRepository.getWeight(period: '1', slug: slug)) + .thenAnswer((_) async => weightPoints); + + when(mockProfileRepository.getCircumferences(period: '1', slug: slug)) + .thenAnswer((_) async => circumferencePoints); + + cubit.getUserDetails(slug); + + // Ждем завершения асинхронных операций + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.state.profileDetails, equals(profileDetails)); + expect(cubit.state.isLoading, isFalse); + verify(mockProfileRepository.getProfileDetailsBySlug(slug)).called(1); + }); + + test('getUserDetails - обработка ошибки', () async { + const slug = 'test-user'; + final error = Exception('Ошибка загрузки'); + + when(mockProfileRepository.getProfileDetailsBySlug(slug)) + .thenThrow(error); + + cubit.getUserDetails(slug); + + // Ждем завершения асинхронных операций + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.state.error, equals(error.toString())); + expect(cubit.state.isLoading, isFalse); + }); + + test('getChartData - успешная загрузка данных графика', () async { + const slug = 'test-user'; + const period = '1'; + + final weightPoints = [ + WeightModel( + id: 1, + userId: 1, + weight: 70, + createdAt: DateTime.now(), + updatedAt: DateTime.now(), + bmi: 22.9, + ), + WeightModel( + id: 2, + userId: 1, + weight: 71, + createdAt: DateTime.now().add(const Duration(days: 1)), + updatedAt: DateTime.now().add(const Duration(days: 1)), + bmi: 23.2, + ), + ]; + + final circumferencePoints = [ + CircumferenceModel( + id: 1, + userId: 1, + chestCircumference: 100, + waistCircumference: 80, + hipCircumference: 90, + createdAt: DateTime.now(), + updatedAt: DateTime.now(), + ), + ]; + + when(mockProfileRepository.getWeight(period: period, slug: slug)) + .thenAnswer((_) async => weightPoints); + + when(mockProfileRepository.getCircumferences(period: period, slug: slug)) + .thenAnswer((_) async => circumferencePoints); + + cubit.getChartData(period: period, slug: slug); + + // Ждем завершения асинхронных операций + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.state.weightPoints, equals(weightPoints)); + expect(cubit.state.circumferencePoints, equals(circumferencePoints)); + verify(mockProfileRepository.getWeight(period: period, slug: slug)).called(1); + verify(mockProfileRepository.getCircumferences(period: period, slug: slug)).called(1); + }); + + test('getChartData - обработка ошибки', () async { + const slug = 'test-user'; + const period = '1'; + final error = Exception('Ошибка загрузки'); + + when(mockProfileRepository.getWeight(period: period, slug: slug)) + .thenThrow(error); + + cubit.getChartData(period: period, slug: slug); + + // Ждем завершения асинхронных операций + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.state.error, equals(error.toString())); + expect(cubit.state.isLoading, isFalse); + }); + }); +} + diff --git a/test/fixtures/auth/login_credentials.json b/test/fixtures/auth/login_credentials.json new file mode 100644 index 00000000..cee16e0f --- /dev/null +++ b/test/fixtures/auth/login_credentials.json @@ -0,0 +1,5 @@ +{ + "email": "test@example.com", + "password": "password123" +} + diff --git a/test/fixtures/auth/oauth_signin_request.json b/test/fixtures/auth/oauth_signin_request.json new file mode 100644 index 00000000..04cdc7f0 --- /dev/null +++ b/test/fixtures/auth/oauth_signin_request.json @@ -0,0 +1,7 @@ +{ + "provider": "vk", + "access_token": "vk_access_token_123", + "refresh_token": "vk_refresh_token_123", + "client_id": "vk_client_id_123" +} + diff --git a/test/fixtures/auth/oauth_signup_request.json b/test/fixtures/auth/oauth_signup_request.json new file mode 100644 index 00000000..70d70714 --- /dev/null +++ b/test/fixtures/auth/oauth_signup_request.json @@ -0,0 +1,16 @@ +{ + "provider": "vk", + "access_token": "vk_access_token_123", + "id": "vk_user_id_123", + "refresh_token": "vk_refresh_token_123", + "first_name": "Иван", + "last_name": "Иванов", + "email": "ivan@example.com", + "phone": "+79001234567", + "date_of_birth": "1990-01-01", + "gender": "М", + "weight": 75, + "height": 180, + "client_id": "vk_client_id_123" +} + diff --git a/test/fixtures/auth/reset_password_request.json b/test/fixtures/auth/reset_password_request.json new file mode 100644 index 00000000..ef60f635 --- /dev/null +++ b/test/fixtures/auth/reset_password_request.json @@ -0,0 +1,7 @@ +{ + "email": "user@example.com", + "code": "123456", + "password": "newPassword123", + "passwordConfirmation": "newPassword123" +} + diff --git a/test/fixtures/auth/token_response.json b/test/fixtures/auth/token_response.json new file mode 100644 index 00000000..86119d5c --- /dev/null +++ b/test/fixtures/auth/token_response.json @@ -0,0 +1,4 @@ +{ + "token": "test_token_12345" +} + diff --git a/test/fixtures/blog_post_create/create_request_full.json b/test/fixtures/blog_post_create/create_request_full.json new file mode 100644 index 00000000..d329141e --- /dev/null +++ b/test/fixtures/blog_post_create/create_request_full.json @@ -0,0 +1,7 @@ +{ + "title": "Complete Test Title", + "description_md": "Complete Test Description", + "video_url": "https://youtube.com/watch?v=complete", + "image_name": null +} + diff --git a/test/fixtures/blog_post_create/delete_request.json b/test/fixtures/blog_post_create/delete_request.json new file mode 100644 index 00000000..8240ed62 --- /dev/null +++ b/test/fixtures/blog_post_create/delete_request.json @@ -0,0 +1,4 @@ +{ + "id": 1 +} + diff --git a/test/fixtures/blog_post_create/update_request.json b/test/fixtures/blog_post_create/update_request.json new file mode 100644 index 00000000..c3185f69 --- /dev/null +++ b/test/fixtures/blog_post_create/update_request.json @@ -0,0 +1,9 @@ +{ + "id": 1, + "title": "Updated Title", + "description_md": "Updated Description", + "video_url": "https://youtube.com/watch?v=updated", + "old_image_url": "original_image.jpg", + "image_name": null +} + diff --git a/test/fixtures/consultant/consultant_cert_photos.json b/test/fixtures/consultant/consultant_cert_photos.json new file mode 100644 index 00000000..38004bd5 --- /dev/null +++ b/test/fixtures/consultant/consultant_cert_photos.json @@ -0,0 +1,42 @@ +[ + { + "id": 101, + "user_id": 1, + "group": "user_certs", + "original_name": "degree.jpg", + "path": "certs/degree.jpg", + "size": 24576, + "specs": { + "width": 1024, + "height": 768 + }, + "url": "https://cdn.eatvio.app/certs/degree.jpg" + }, + { + "id": 102, + "user_id": 1, + "group": "hidden_user_certs", + "original_name": "old_degree.jpg", + "path": "certs/old_degree.jpg", + "size": 20480, + "specs": { + "width": 800, + "height": 600 + }, + "url": "https://cdn.eatvio.app/certs/old_degree.jpg" + }, + { + "id": 103, + "user_id": 1, + "group": "user_certs", + "original_name": "advanced_course.jpg", + "path": "certs/advanced_course.jpg", + "size": 31000, + "specs": { + "width": 900, + "height": 900 + }, + "url": "https://cdn.eatvio.app/certs/advanced_course.jpg" + } +] + diff --git a/test/fixtures/consultant/consultant_profile_request.json b/test/fixtures/consultant/consultant_profile_request.json new file mode 100644 index 00000000..fc05c731 --- /dev/null +++ b/test/fixtures/consultant/consultant_profile_request.json @@ -0,0 +1,25 @@ +{ + "has_medical_education": true, + "social_links": { + "vk_link": "https://vk.com/eatvio_consultant", + "tg_link": "https://t.me/eatvio_consultant", + "fb_link": "https://facebook.com/eatvio_consultant", + "insta_link": "https://instagram.com/eatvio_consultant", + "personal_site_link": "https://eatvio.consultant" + }, + "cert_photos": [ + "certificates/cert1.jpg", + "certificates/cert2.jpg" + ], + "completed_courses": [ + { + "title": "Основы нутрициологии", + "date": "2024-01-10" + }, + { + "title": "Психология питания", + "date": "2023-06-05" + } + ] +} + diff --git a/test/fixtures/consultant/consultation_request.json b/test/fixtures/consultant/consultation_request.json new file mode 100644 index 00000000..f4065e15 --- /dev/null +++ b/test/fixtures/consultant/consultation_request.json @@ -0,0 +1,43 @@ +{ + "rating_place": 12, + "education_resource": { + "has_medical_education": 1, + "completed_courses": [ + { + "nutriology": { + "title": "Нутрициология PRO", + "date": "2024-02-01" + } + }, + { + "coaching": { + "title": "Здоровый коучинг", + "date": "2023-09-15" + } + } + ], + "vk_link": "https://vk.com/consultant", + "insta_link": "", + "fb_link": null, + "tg_link": "https://t.me/consultant", + "personal_site_link": "https://consultant.eatvio.app", + "request_state": "approved" + }, + "cert_photos": [ + { + "url": "https://cdn.eatvio.app/certificates/visible.jpg" + }, + { + "url": "https://cdn.eatvio.app/certificates/hidden.jpg" + } + ], + "canceled_moderation": { + "title": "Документы нечитабельны", + "status": "canceled", + "additional": [ + "Перезагрузите документы", + "Используйте формат JPG" + ] + } +} + diff --git a/test/fixtures/create_diet/create_diet_request.json b/test/fixtures/create_diet/create_diet_request.json new file mode 100644 index 00000000..0909e926 --- /dev/null +++ b/test/fixtures/create_diet/create_diet_request.json @@ -0,0 +1,13 @@ +{ + "name": "Легкий рацион", + "duration": 7, + "details": "Балансированный рацион на неделю", + "state": "draft", + "types": { + "meat": true, + "carb": false, + "veg": true, + "light": true + } +} + diff --git a/test/fixtures/create_diet/created_diet_response.json b/test/fixtures/create_diet/created_diet_response.json new file mode 100644 index 00000000..8240ed62 --- /dev/null +++ b/test/fixtures/create_diet/created_diet_response.json @@ -0,0 +1,4 @@ +{ + "id": 1 +} + diff --git a/test/fixtures/create_diet/glossary_search_response.json b/test/fixtures/create_diet/glossary_search_response.json new file mode 100644 index 00000000..8a7fc90f --- /dev/null +++ b/test/fixtures/create_diet/glossary_search_response.json @@ -0,0 +1,30 @@ +{ + "results": [ + { + "id": 10, + "name": "Авокадо", + "portion_mass_gr": 100, + "energy_on_100gr": 160.0, + "proteins_on_100gr": 2.0, + "fats_on_100gr": 14.0, + "carbohydrates_on_100gr": 9.0, + "energy_on_portion": 160.0, + "proteins_on_portion": 2.0, + "fats_on_portion": 14.0, + "carbohydrates_on_portion": 9.0 + }, + { + "id": 11, + "name": "Лосось", + "portion_mass_gr": 150, + "energy_on_100gr": 208.0, + "proteins_on_100gr": 20.0, + "fats_on_100gr": 13.0, + "carbohydrates_on_100gr": 0.0, + "energy_on_portion": 312.0, + "proteins_on_portion": 30.0, + "fats_on_portion": 19.5, + "carbohydrates_on_portion": 0.0 + } + ] +} diff --git a/test/fixtures/create_diet/nutrition_response.json b/test/fixtures/create_diet/nutrition_response.json new file mode 100644 index 00000000..6dd2119e --- /dev/null +++ b/test/fixtures/create_diet/nutrition_response.json @@ -0,0 +1,13 @@ +{ + "1": { + "1": { + "0": { + "name": "Авокадо", + "portion": "grams", + "quantity": 100, + "product_nutritional_value_id": "501" + } + } + } +} + diff --git a/test/fixtures/create_diet/update_request.json b/test/fixtures/create_diet/update_request.json new file mode 100644 index 00000000..745f02fa --- /dev/null +++ b/test/fixtures/create_diet/update_request.json @@ -0,0 +1,15 @@ +{ + "id": 1, + "name": "Обновленный рацион", + "duration": 14, + "details": "Обновленное описание диеты", + "state": "active", + "types": { + "meat": false, + "carb": true, + "veg": true, + "light": false + } +} + + diff --git a/test/fixtures/create_plan/create_plan_request.json b/test/fixtures/create_plan/create_plan_request.json new file mode 100644 index 00000000..decc5148 --- /dev/null +++ b/test/fixtures/create_plan/create_plan_request.json @@ -0,0 +1,14 @@ +{ + "name": "План для похудения", + "description": "Описание плана питания для снижения веса", + "duration": 14, + "status": "draft", + "options": [ + { + "title": "Базовый план", + "price": 1500, + "description": "Меню + чат с консультантом" + } + ] +} + diff --git a/test/fixtures/doubles/auth_doubles.dart b/test/fixtures/doubles/auth_doubles.dart new file mode 100644 index 00000000..d8ba584f --- /dev/null +++ b/test/fixtures/doubles/auth_doubles.dart @@ -0,0 +1,66 @@ +import 'package:eatvio_app/features/auth/models/credentials_model.dart'; +import 'package:eatvio_app/features/auth/models/oauth_login_request.dart'; +import 'package:eatvio_app/features/auth/models/oauth_model.dart'; +import 'package:eatvio_app/features/auth/models/token_model.dart'; +import 'package:eatvio_app/features/auth/repositories/auth_repository.dart'; +import 'package:eatvio_app/features/auth/services/auth_service.dart'; +/// Fixture-based replacement for [AuthRepository]. +/// +/// - Records every credential payload that would be sent to the backend. +/// - 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()); + + final TokenModel tokenFixture; + + final List credentialCalls = []; + List> get credentialPayloads => credentialCalls.map((call) => call.toJson()).toList(growable: false); + + Duration responseDelay = Duration.zero; + Object? error; + + @override + Future getTokenByCredentials(String email, String password) async { + credentialCalls.add(CredentialsCall(email: email, password: password)); + if (responseDelay > Duration.zero) { + await Future.delayed(responseDelay); + } + if (error != null) { + throw error!; + } + return tokenFixture; + } +} + +class CredentialsCall { + const CredentialsCall({required this.email, required this.password}); + + final String email; + final String password; + + Map toJson() => { + 'email': email, + 'password': password, + }; +} + +class _NoopAuthService implements AuthService { + @override + Future getTokenByCredentials({required CredentialsModel credentials}) { + throw UnimplementedError('Use FixtureAuthRepository override instead.'); + } + + @override + Future signInViaSocialMedia({required OAuthLoginRequest body}) { + throw UnimplementedError('Not implemented in fixture.'); + } + + @override + Future> signUpViaSocialMedia({required OAuthModel body}) { + throw UnimplementedError('Not implemented in fixture.'); + } +} + diff --git a/test/fixtures/doubles/blog_post_doubles.dart b/test/fixtures/doubles/blog_post_doubles.dart new file mode 100644 index 00000000..bb1df7c6 --- /dev/null +++ b/test/fixtures/doubles/blog_post_doubles.dart @@ -0,0 +1,143 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/blog_post_create/repositories/blog_post_repository.dart'; +import 'package:eatvio_app/features/blog_post_create/services/blog_post_service.dart'; +import 'package:flutter_image_compress/flutter_image_compress.dart'; + +class FixtureBlogPostRepository extends BlogPostRepository { + FixtureBlogPostRepository() : super(blogPostService: _NoopBlogPostService()); + + final List createPayloads = []; + final List updatePayloads = []; + final List deleteCalls = []; + + Duration createDelay = Duration.zero; + Duration updateDelay = Duration.zero; + Duration deleteDelay = Duration.zero; + + Object? createError; + Object? updateError; + Object? deleteError; + + @override + Future createBlogPost(String? title, String? videoUrl, String? description, XFile? image) async { + createPayloads.add( + BlogPostCreatePayload( + title: title, + description: description, + videoUrl: videoUrl, + imageName: image?.name, + ), + ); + if (createDelay > Duration.zero) { + await Future.delayed(createDelay); + } + if (createError != null) { + throw createError!; + } + } + + @override + Future updateBlogPost(int id, String? title, String? videoUrl, String? description, XFile? image, String? oldImageUrl) async { + updatePayloads.add( + BlogPostUpdatePayload( + id: id, + title: title, + description: description, + videoUrl: videoUrl, + imageName: image?.name, + oldImageUrl: oldImageUrl, + ), + ); + if (updateDelay > Duration.zero) { + await Future.delayed(updateDelay); + } + if (updateError != null) { + throw updateError!; + } + } + + @override + Future deleteBlogPost(int id) async { + deleteCalls.add(id); + if (deleteDelay > Duration.zero) { + await Future.delayed(deleteDelay); + } + if (deleteError != null) { + throw deleteError!; + } + } +} + +class BlogPostCreatePayload { + BlogPostCreatePayload({ + required this.title, + required this.description, + required this.videoUrl, + required this.imageName, + }); + + final String? title; + final String? description; + final String? videoUrl; + final String? imageName; + + Map toJson() => { + 'title': title, + 'description_md': description, + 'video_url': videoUrl, + 'image_name': imageName, + }; +} + +class BlogPostUpdatePayload { + BlogPostUpdatePayload({ + required this.id, + required this.title, + required this.description, + required this.videoUrl, + required this.imageName, + required this.oldImageUrl, + }); + + final int id; + final String? title; + final String? description; + final String? videoUrl; + final String? imageName; + final String? oldImageUrl; + + Map toJson() => { + 'id': id, + 'title': title, + 'description_md': description, + 'video_url': videoUrl, + 'image_name': imageName, + 'old_image_url': oldImageUrl, + }; +} + +class _NoopBlogPostService implements BlogPostService { + @override + Future createBlogPost({required FormData formData}) { + throw UnimplementedError('Fixture overrides repository methods directly.'); + } + + @override + Future deleteBlogPost({required int id}) { + throw UnimplementedError('Fixture overrides repository methods directly.'); + } + + @override + Future updateBlogPost({required int id, required FormData formData}) { + throw UnimplementedError('Fixture overrides repository methods directly.'); + } +} + +class FeedReloadProbe { + int loadRequests = 0; + + Future loadFeedBlogPostList() async { + loadRequests += 1; + } +} + diff --git a/test/fixtures/doubles/create_diet_doubles.dart b/test/fixtures/doubles/create_diet_doubles.dart new file mode 100644 index 00000000..f4ed17bc --- /dev/null +++ b/test/fixtures/doubles/create_diet_doubles.dart @@ -0,0 +1,201 @@ +import 'dart:io'; + +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/create_diet/repositories/create_diet_repository.dart'; +import 'package:eatvio_app/features/create_diet/services/create_diet_service.dart'; +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; +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:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/profile/services/profile_service.dart'; +import 'package:retrofit/dio.dart' show HttpResponse; + +import '../../fixtures/fixture_reader.dart'; + +class FixtureCreateDietRepository extends CreateDietRepository { + FixtureCreateDietRepository() : super(createDietService: _NoopCreateDietService()); + + final List> createRequests = >[]; + final List> updateRequests = >[]; + + Map>> get nutritionFixture { + final nutritionData = FixtureReader.readAsMap('create_diet/nutrition_response.json'); + final result = >>{}; + + for (final dayEntry in nutritionData.entries) { + final dayIndex = int.parse(dayEntry.key); + final dayData = dayEntry.value as Map; + final dayMap = >{}; + + for (final mealEntry in dayData.entries) { + final mealIndex = int.parse(mealEntry.key); + final mealData = mealEntry.value as Map; + final mealMap = {}; + + for (final portionEntry in mealData.entries) { + final portionIndex = int.parse(portionEntry.key); + final portionData = portionEntry.value as Map; + + // Convert portion string to Portion enum + final portionStr = portionData['portion'] as String; + Portion portion; + switch (portionStr) { + case 'gr': + case 'grams': + portion = Portion.grams; + break; + case 'milliliters': + portion = Portion.milliliters; + break; + case 'pcs': + portion = Portion.pcs; + break; + default: + portion = Portion.grams; + } + + mealMap[portionIndex] = DailySchedule( + name: portionData['name'] as String, + portion: portion, + quantity: portionData['quantity'] as int, + productNutritionalValueId: portionData['product_nutritional_value_id'] as String?, + ); + } + + dayMap[mealIndex] = mealMap; + } + + result[dayIndex] = dayMap; + } + + return result; + } + + @override + Future createDiet({ + required String name, + required int duration, + required DietState state, + required String meatType, + required String carbType, + required String vegType, + required String lightType, + required String details, + required File image, + required List>> dailySchedule, + }) async { + createRequests.add({ + 'name': name, + 'duration': duration, + 'details': details, + 'state': state.toString(), + 'types': {'meat': meatType == '1', 'carb': carbType == '1', 'veg': vegType == '1', 'light': lightType == '1'}, + }); + final createdDietFixture = FixtureReader.readAsMap('create_diet/created_diet_response.json'); + return CreatedDiet.fromJson(createdDietFixture); + } + + @override + Future>>> getDietPortionsNutrition(int dietId) async { + return nutritionFixture; + } + + @override + Future updateDiet({ + required int dietId, + required DietState state, + String? name, + int? duration, + String? meatType, + String? carbType, + String? vegType, + String? lightType, + String? details, + File? image, + List>>? dailySchedule, + }) async { + updateRequests.add({ + 'id': dietId, + 'name': name, + 'duration': duration, + 'details': details, + 'state': state.toString(), + if (meatType != null || carbType != null || vegType != null || lightType != null) + 'types': { + if (meatType != null) 'meat': meatType == '1', + if (carbType != null) 'carb': carbType == '1', + if (vegType != null) 'veg': vegType == '1', + if (lightType != null) 'light': lightType == '1', + }, + }); + } +} + +class FixtureProfileRepository extends ProfileRepository { + FixtureProfileRepository() : super(profileService: _NoopProfileService()); + + @override + Future getMyProfile() async { + final profileFixture = FixtureReader.readAsMap('profile/my_profile_response.json'); + return ProfileModel.fromJson(profileFixture); + } +} + +class FixtureGlossaryRepository extends GlossaryRepository { + FixtureGlossaryRepository() : super(glossaryService: _NoopGlossaryService()); + + @override + Future> getGlossaryListByQuery(String query) async { + final results = FixtureReader.readAsMap('create_diet/glossary_search_response.json')['results'] as List; + return results.map((item) => GlossaryModel.fromJson(item as Map)).toList(); + } +} + +class _NoopCreateDietService implements CreateDietService { + @override + Future createDraftedDiet({required FormData formData}) { + throw UnimplementedError(); + } + + @override + Future createPersonalDiet({required FormData formData}) { + throw UnimplementedError(); + } + + @override + Future createPublishedDiet({required FormData formData}) { + throw UnimplementedError(); + } + + @override + Future getDietPortionsNutrition({required int diet}) { + throw UnimplementedError(); + } + + @override + Future updateDrafted({required int diet, required FormData formData}) { + throw UnimplementedError(); + } + + @override + Future updatePersonal({required int diet, required FormData formData}) { + throw UnimplementedError(); + } + + @override + Future updatePublished({required int diet, required FormData formData}) { + throw UnimplementedError(); + } +} + +class _NoopProfileService implements ProfileService { + @override + noSuchMethod(Invocation invocation) => throw UnimplementedError('ProfileService call ${invocation.memberName}'); +} + +class _NoopGlossaryService implements GlossaryService { + @override + noSuchMethod(Invocation invocation) => throw UnimplementedError('GlossaryService call ${invocation.memberName}'); +} diff --git a/test/fixtures/doubles/create_plan_doubles.dart b/test/fixtures/doubles/create_plan_doubles.dart new file mode 100644 index 00000000..6c32d0bb --- /dev/null +++ b/test/fixtures/doubles/create_plan_doubles.dart @@ -0,0 +1,50 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/create_plan/repositories/create_plan_repository.dart'; +import 'package:eatvio_app/features/create_plan/services/create_plan_service.dart'; + +class FixtureCreatePlanRepository extends CreatePlanRepository { + FixtureCreatePlanRepository() : super(createPlanService: _NoopCreatePlanService()); + + final List> createPlanRequests = >[]; + + @override + Future createPlan({required Map model}) async { + // Normalize request to match fixture format + final normalized = { + 'name': model['name'], + 'description': model['description_md'], + 'duration': model['duration'], + 'status': model['state'] == 'active' ? 'active' : 'draft', + }; + + // Extract options if present + if (model.containsKey('packets_count')) { + final options = >[]; + final packetsCount = model['packets_count'] as int; + for (int i = 1; i <= packetsCount; i++) { + final packetKey = 'packet${i}_options'; + if (model.containsKey(packetKey)) { + final packet = model[packetKey] as Map; + options.add({ + 'title': packet['short'], + 'price': packet['price'], + 'description': packet['description_md'], + }); + } + } + if (options.isNotEmpty) { + normalized['options'] = options; + } + } + + createPlanRequests.add(normalized); + } +} + +class _NoopCreatePlanService implements CreatePlanService { + @override + Future createPlan({required FormData formData}) { + throw UnimplementedError('Not used in fixture tests'); + } +} + diff --git a/test/fixtures/doubles/profile_doubles.dart b/test/fixtures/doubles/profile_doubles.dart new file mode 100644 index 00000000..d3b98791 --- /dev/null +++ b/test/fixtures/doubles/profile_doubles.dart @@ -0,0 +1,106 @@ +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/features/chat/services/chat_service.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/services/consultant_service.dart'; +import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:eatvio_app/features/profile/models/circumference_model.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/models/weight_model.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/profile/services/profile_service.dart'; + +import '../fixture_reader.dart'; + +class FixtureProfileRepository extends ProfileRepository { + FixtureProfileRepository() : super(profileService: _NoopProfileService()); + + final List> addWeightRequests = >[]; + final List> addCircumferenceRequests = >[]; + + @override + Future getMyProfile() async { + final profileFixture = FixtureReader.readAsMap('profile/my_profile_response.json'); + return ProfileModel.fromJson(profileFixture); + } + + @override + Future getMyProfileDetails() async { + final detailsFixture = FixtureReader.readAsMap('profile/profile_details_response.json'); + return ProfileDetailsModel.fromJson(detailsFixture); + } + + @override + Future addWeight({required double weight}) async { + addWeightRequests.add({'weight': weight}); + } + + @override + Future addCircumference({required int chestCircumference, required int waistCircumference, required int hipCircumference}) async { + addCircumferenceRequests.add({'chest_circumference': chestCircumference, 'waist_circumference': waistCircumference, 'hip_circumference': hipCircumference}); + } + + @override + Future> getWeight({required String period, String? slug}) async { + final weightListFixture = FixtureReader.readAsList('profile/weight_list_response.json'); + return weightListFixture.map((item) => WeightModel.fromJson(item as Map)).toList(); + } + + @override + Future> getCircumferences({required String period, String? slug}) async { + final circumferenceListFixture = FixtureReader.readAsList('profile/circumference_list_response.json'); + return circumferenceListFixture.map((item) => CircumferenceModel.fromJson(item as Map)).toList(); + } + + @override + Future> getBlogPostsByAuthorSlug({required String slug}) async { + return []; + } +} + +class _NoopProfileService implements ProfileService { + @override + noSuchMethod(Invocation invocation) => throw UnimplementedError('ProfileService call ${invocation.memberName}'); +} + +class FixtureChatRepository extends ChatRepository { + FixtureChatRepository() : super(chatService: _NoopChatService()); + + @override + Future getChatByUserSlug(String slug) async { + return 'chat-uuid-123'; + } +} + +class _NoopChatService implements ChatService { + @override + noSuchMethod(Invocation invocation) => throw UnimplementedError('ChatService call ${invocation.memberName}'); +} + +class FixtureConsultantRepository extends ConsultantRepository { + FixtureConsultantRepository() : super(consultantService: _NoopConsultantService()); + + @override + Future getConsultantRequestStatus(String slug) async { + return const ConsultationRequestModel( + educationModel: EducationModel( + hasMedicalEducation: 1, + completedCourses: null, + vkLink: null, + instaLink: null, + fbLink: null, + tgLink: null, + personalSiteLink: null, + requestState: ModerationStatus.approved, + ), + photos: [], + ratingPlace: null, + canceledModeration: null, + ); + } +} + +class _NoopConsultantService implements ConsultantService { + @override + noSuchMethod(Invocation invocation) => throw UnimplementedError('ConsultantService call ${invocation.memberName}'); +} diff --git a/test/fixtures/feed/feed_blog_posts_response.json b/test/fixtures/feed/feed_blog_posts_response.json new file mode 100644 index 00000000..ee9955c8 --- /dev/null +++ b/test/fixtures/feed/feed_blog_posts_response.json @@ -0,0 +1,33 @@ +{ + "feedBlogPostList": [ + { + "id": 1, + "title": "Тестовый пост", + "content": "Содержимое поста", + "author": "Автор", + "createdAt": "2024-01-01T00:00:00Z", + "totalLikes": 10, + "wasLikedByMe": false, + "totalComments": 5, + "totalViews": 100 + }, + { + "id": 2, + "title": "Второй пост", + "content": "Еще одно содержимое", + "author": "Другой автор", + "createdAt": "2024-01-02T00:00:00Z", + "totalLikes": 20, + "wasLikedByMe": true, + "totalComments": 10, + "totalViews": 200 + } + ], + "meta": { + "currentPage": 1, + "lastPage": 3, + "perPage": 10, + "total": 25 + } +} + diff --git a/test/fixtures/fixture_reader.dart b/test/fixtures/fixture_reader.dart new file mode 100644 index 00000000..17d2324e --- /dev/null +++ b/test/fixtures/fixture_reader.dart @@ -0,0 +1,30 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as p; + +/// Utility that reads JSON fixtures from `test/fixtures`. +/// +/// Using files instead of inline maps makes it explicit which payloads +/// are exchanged with the backend. +class FixtureReader { + const FixtureReader._(); + + static String readAsString(String relativePath) { + final file = File(_resolve(relativePath)); + return file.readAsStringSync(); + } + + static Map readAsMap(String relativePath) { + return jsonDecode(readAsString(relativePath)) as Map; + } + + static List readAsList(String relativePath) { + return jsonDecode(readAsString(relativePath)) as List; + } + + static String _resolve(String relativePath) { + return p.normalize(p.join('test', 'fixtures', relativePath)); + } +} + diff --git a/test/fixtures/menu/blocked_users_empty_response.json b/test/fixtures/menu/blocked_users_empty_response.json new file mode 100644 index 00000000..a9ebf62d --- /dev/null +++ b/test/fixtures/menu/blocked_users_empty_response.json @@ -0,0 +1,4 @@ +{ + "data": [] +} + diff --git a/test/fixtures/menu/blocked_users_response.json b/test/fixtures/menu/blocked_users_response.json new file mode 100644 index 00000000..ff4fa2c4 --- /dev/null +++ b/test/fixtures/menu/blocked_users_response.json @@ -0,0 +1,39 @@ +{ + "data": [ + { + "id": 1, + "name": "Test User 1", + "email": "test1@example.com", + "phone_confirmation_state": "confirmed", + "is_public_profile": true, + "is_blocked_by_me": true, + "is_blocked_by_author": false, + "is_blocked_by_user": false, + "is_entity_subscribed_by_me": false, + "slug": "test-user-1", + "profile_photo_url": "", + "roles": ["user"], + "badges": [], + "subscriptions": [], + "subscribers": [] + }, + { + "id": 2, + "name": "Test User 2", + "email": "test2@example.com", + "phone_confirmation_state": "confirmed", + "is_public_profile": true, + "is_blocked_by_me": true, + "is_blocked_by_author": false, + "is_blocked_by_user": false, + "is_entity_subscribed_by_me": false, + "slug": "test-user-2", + "profile_photo_url": "", + "roles": ["user"], + "badges": [], + "subscriptions": [], + "subscribers": [] + } + ] +} + diff --git a/test/fixtures/menu/notification_settings_response.json b/test/fixtures/menu/notification_settings_response.json new file mode 100644 index 00000000..fc5e31ca --- /dev/null +++ b/test/fixtures/menu/notification_settings_response.json @@ -0,0 +1,24 @@ +{ + "new_updates_notification": true, + "weight_measurements_notification": true, + "is_email_notifications_enabled": true, + "is_push_notifications_enabled": true, + "diary_reminder_notifications": { + "first_reminder": { + "enabled": true, + "local_time_hours": 9, + "local_time_mins": 0 + }, + "second_reminder": { + "enabled": true, + "local_time_hours": 13, + "local_time_mins": 0 + }, + "third_reminder": { + "enabled": false, + "local_time_hours": 18, + "local_time_mins": 0 + } + } +} + diff --git a/test/fixtures/menu/notification_settings_updated_response.json b/test/fixtures/menu/notification_settings_updated_response.json new file mode 100644 index 00000000..afa7cc7f --- /dev/null +++ b/test/fixtures/menu/notification_settings_updated_response.json @@ -0,0 +1,24 @@ +{ + "new_updates_notification": false, + "weight_measurements_notification": true, + "is_email_notifications_enabled": true, + "is_push_notifications_enabled": false, + "diary_reminder_notifications": { + "first_reminder": { + "enabled": true, + "local_time_hours": 9, + "local_time_mins": 0 + }, + "second_reminder": { + "enabled": true, + "local_time_hours": 13, + "local_time_mins": 0 + }, + "third_reminder": { + "enabled": false, + "local_time_hours": 18, + "local_time_mins": 0 + } + } +} + diff --git a/test/fixtures/menu_fixtures.dart b/test/fixtures/menu_fixtures.dart new file mode 100644 index 00000000..64ed88e6 --- /dev/null +++ b/test/fixtures/menu_fixtures.dart @@ -0,0 +1,45 @@ +import 'package:eatvio_app/features/menu/models/blocked_users_model.dart'; +import 'package:eatvio_app/features/menu/models/notification_settings_model.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'fixture_reader.dart'; + +class MenuFixtures { + MenuFixtures._(); + + static BlockedUsersModel blockedUsersModel() { + return BlockedUsersModel.fromJson( + FixtureReader.readAsMap('menu/blocked_users_response.json'), + ); + } + + static BlockedUsersModel blockedUsersEmptyModel() { + return BlockedUsersModel.fromJson( + FixtureReader.readAsMap('menu/blocked_users_empty_response.json'), + ); + } + + static List blockedUsersList() { + return blockedUsersModel().profilesList; + } + + static List blockedUsersEmptyList() { + return blockedUsersEmptyModel().profilesList; + } + + static ProfileModel blockedUser() { + return blockedUsersList().first; + } + + static NotificationSettingsModel notificationSettingsModel() { + return NotificationSettingsModel.fromJson( + FixtureReader.readAsMap('menu/notification_settings_response.json'), + ); + } + + static NotificationSettingsModel notificationSettingsUpdatedModel() { + return NotificationSettingsModel.fromJson( + FixtureReader.readAsMap('menu/notification_settings_updated_response.json'), + ); + } +} + diff --git a/test/fixtures/profile/add_circumference_request.json b/test/fixtures/profile/add_circumference_request.json new file mode 100644 index 00000000..c645ed0d --- /dev/null +++ b/test/fixtures/profile/add_circumference_request.json @@ -0,0 +1,6 @@ +{ + "chest_circumference": 100, + "waist_circumference": 80, + "hip_circumference": 90 +} + diff --git a/test/fixtures/profile/add_weight_request.json b/test/fixtures/profile/add_weight_request.json new file mode 100644 index 00000000..9f588499 --- /dev/null +++ b/test/fixtures/profile/add_weight_request.json @@ -0,0 +1,4 @@ +{ + "weight": 75.5 +} + diff --git a/test/fixtures/profile/circumference_list_response.json b/test/fixtures/profile/circumference_list_response.json new file mode 100644 index 00000000..c9750086 --- /dev/null +++ b/test/fixtures/profile/circumference_list_response.json @@ -0,0 +1,30 @@ +[ + { + "id": 1, + "user_id": 99, + "chest_circumference": 100, + "waist_circumference": 80, + "hip_circumference": 90, + "created_at": "2024-01-15T10:00:00Z", + "updated_at": "2024-01-15T10:00:00Z" + }, + { + "id": 2, + "user_id": 99, + "chest_circumference": 98, + "waist_circumference": 78, + "hip_circumference": 88, + "created_at": "2024-01-22T10:00:00Z", + "updated_at": "2024-01-22T10:00:00Z" + }, + { + "id": 3, + "user_id": 99, + "chest_circumference": 96, + "waist_circumference": 76, + "hip_circumference": 86, + "created_at": "2024-01-29T10:00:00Z", + "updated_at": "2024-01-29T10:00:00Z" + } +] + diff --git a/test/fixtures/profile/my_profile_response.json b/test/fixtures/profile/my_profile_response.json new file mode 100644 index 00000000..0f91454b --- /dev/null +++ b/test/fixtures/profile/my_profile_response.json @@ -0,0 +1,17 @@ +{ + "id": 99, + "name": "Анна Нутрициолог", + "email": "anna@example.com", + "phone_confirmation_state": "verified", + "is_public_profile": true, + "is_blocked_by_me": false, + "is_blocked_by_author": false, + "is_blocked_by_user": false, + "is_entity_subscribed_by_me": false, + "slug": "diet-author", + "profile_photo_url": "avatars/anna.png", + "roles": ["author"], + "badges": [], + "subscriptions": [], + "subscribers": [] +} diff --git a/test/fixtures/profile/profile_details_response.json b/test/fixtures/profile/profile_details_response.json new file mode 100644 index 00000000..6c14bac9 --- /dev/null +++ b/test/fixtures/profile/profile_details_response.json @@ -0,0 +1,30 @@ +{ + "first_name": "Анна", + "last_name": "Нутрициолог", + "birthdate": "1990-05-15", + "gender": "female", + "country": "Россия", + "city": "Москва", + "lang": "ru", + "weight": 65.0, + "height": 170, + "chest_circumference": 90, + "waist_circumference": 70, + "hip_circumference": 95, + "blood_pressure_up": 120, + "blood_pressure_down": 80, + "has_hypo": false, + "has_hyper": false, + "about_alergy": "Нет аллергий", + "about_taking_pils": "Не принимаю лекарства", + "about_sport_hobbies": "Йога, бег", + "favorite_foods": "Овощи, фрукты", + "unfavorite_foods": "Жареное", + "additional_info": "Веду здоровый образ жизни", + "created_at": "2024-01-01T00:00:00Z", + "updated_at": "2024-01-15T10:00:00Z", + "is_mood_fillable": true, + "is_bedtime_fillable": true, + "activity_coefficient": 1.5 +} + diff --git a/test/fixtures/profile/weight_list_response.json b/test/fixtures/profile/weight_list_response.json new file mode 100644 index 00000000..3aeae8bb --- /dev/null +++ b/test/fixtures/profile/weight_list_response.json @@ -0,0 +1,27 @@ +[ + { + "id": 1, + "user_id": 99, + "weight": 75, + "created_at": "2024-01-15T10:00:00Z", + "updated_at": "2024-01-15T10:00:00Z", + "bmi": 23.5 + }, + { + "id": 2, + "user_id": 99, + "weight": 74, + "created_at": "2024-01-22T10:00:00Z", + "updated_at": "2024-01-22T10:00:00Z", + "bmi": 23.2 + }, + { + "id": 3, + "user_id": 99, + "weight": 73, + "created_at": "2024-01-29T10:00:00Z", + "updated_at": "2024-01-29T10:00:00Z", + "bmi": 22.9 + } +] + diff --git a/test/fixtures/settings/oauth_accounts_response.json b/test/fixtures/settings/oauth_accounts_response.json new file mode 100644 index 00000000..9cd7b090 --- /dev/null +++ b/test/fixtures/settings/oauth_accounts_response.json @@ -0,0 +1,8 @@ +{ + "success": true, + "data": { + "vk": null, + "yandex": null + } +} + diff --git a/test/fixtures/settings/oauth_accounts_with_data_response.json b/test/fixtures/settings/oauth_accounts_with_data_response.json new file mode 100644 index 00000000..bf1ed4e1 --- /dev/null +++ b/test/fixtures/settings/oauth_accounts_with_data_response.json @@ -0,0 +1,14 @@ +{ + "success": true, + "data": { + "vk": { + "oauth_id": "123456", + "name": "Test User", + "email": "test@example.com", + "phone": "+79991234567", + "linked_at": "2024-01-01T00:00:00Z" + }, + "yandex": null + } +} + diff --git a/test/fixtures/settings/profile_settings_response.json b/test/fixtures/settings/profile_settings_response.json new file mode 100644 index 00000000..9b6dd687 --- /dev/null +++ b/test/fixtures/settings/profile_settings_response.json @@ -0,0 +1,8 @@ +{ + "new_updates_notifications": null, + "diary_reminder_notifications": null, + "is_mood_fillable": true, + "is_bedtime_fillable": true, + "is_public_profile": true +} + diff --git a/test/fixtures/settings/profile_settings_updated_response.json b/test/fixtures/settings/profile_settings_updated_response.json new file mode 100644 index 00000000..fd5763f4 --- /dev/null +++ b/test/fixtures/settings/profile_settings_updated_response.json @@ -0,0 +1,8 @@ +{ + "new_updates_notifications": null, + "diary_reminder_notifications": null, + "is_mood_fillable": false, + "is_bedtime_fillable": false, + "is_public_profile": false +} + diff --git a/test/fixtures/settings_fixtures.dart b/test/fixtures/settings_fixtures.dart new file mode 100644 index 00000000..c9dc44c2 --- /dev/null +++ b/test/fixtures/settings_fixtures.dart @@ -0,0 +1,45 @@ +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_account_model.dart'; +import 'package:eatvio_app/features/settings/models/profile_settings_model.dart'; +import 'fixture_reader.dart'; + +class SettingsFixtures { + SettingsFixtures._(); + + static ProfileSettingsModel profileSettingsModel() { + return ProfileSettingsModel.fromJson( + FixtureReader.readAsMap('settings/profile_settings_response.json'), + ); + } + + static ProfileSettingsModel profileSettingsUpdatedModel() { + return ProfileSettingsModel.fromJson( + FixtureReader.readAsMap('settings/profile_settings_updated_response.json'), + ); + } + + static ProfileDetailsModel profileDetailsModel() { + return ProfileDetailsModel.fromJson( + FixtureReader.readAsMap('profile/profile_details_response.json'), + ); + } + + static ProfileModel profileModel() { + return ProfileModel.fromJson( + FixtureReader.readAsMap('profile/my_profile_response.json'), + ); + } + + static OAuthAccountsResponseModel oauthAccountsResponseModel() { + return OAuthAccountsResponseModel.fromJson( + FixtureReader.readAsMap('settings/oauth_accounts_response.json'), + ); + } + + static OAuthAccountsResponseModel oauthAccountsWithDataResponseModel() { + return OAuthAccountsResponseModel.fromJson( + FixtureReader.readAsMap('settings/oauth_accounts_with_data_response.json'), + ); + } +} +