diff --git a/integration_test/1_dashboard.dart b/integration_test/1_dashboard.dart index 1e4486c3a..f5288c528 100644 --- a/integration_test/1_dashboard.dart +++ b/integration_test/1_dashboard.dart @@ -26,8 +26,10 @@ import 'package:wger/providers/auth_notifier.dart'; import 'package:wger/providers/auth_state.dart'; import 'package:wger/providers/body_weight_repository.dart'; import 'package:wger/providers/gallery.dart'; +import 'package:wger/providers/ingredient_repository.dart'; import 'package:wger/providers/measurement_repository.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/providers/routines.dart'; import 'package:wger/providers/user_profile_repository.dart'; import 'package:wger/screens/home_tabs_screen.dart'; @@ -58,12 +60,9 @@ Widget createDashboardScreen({Locale? locale}) { final mockGalleryProvider = MockGalleryProvider(); - final mockNutritionProvider = weight.MockNutritionPlansProvider(); - - when( - mockNutritionProvider.currentPlan, - ).thenAnswer((realInvocation) => getNutritionalPlanScreenshot()); - when(mockNutritionProvider.items).thenReturn([getNutritionalPlanScreenshot()]); + final mockNutritionRepo = weight.MockNutritionRepository(); + final mockIngredientRepo = weight.MockIngredientRepository(); + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); final mockBodyWeightRepository = MockBodyWeightRepository(); when( @@ -89,12 +88,20 @@ Widget createDashboardScreen({Locale? locale}) { measurementRepositoryProvider.overrideWithValue(mockMeasurementRepo), authProvider.overrideWith(() => _FakeAuthNotifier(loggedInAuth)), userProfileRepositoryProvider.overrideWithValue(mockUserProfileRepo), + nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), ], ); container.read(routinesRiverpodProvider.notifier).state = RoutinesState( routines: [getTestRoutine(exercises: getScreenshotExercises())], ); + // Seed the nutrition notifier with the screenshot plan so the dashboard can + // show it without going through the server. + container.read(nutritionProvider.notifier).state = riverpod.AsyncData([ + getNutritionalPlanScreenshot(), + ]); + return MediaQuery( data: MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first).copyWith( padding: EdgeInsets.zero, @@ -108,10 +115,6 @@ Widget createDashboardScreen({Locale? locale}) { ChangeNotifierProvider( create: (context) => mockGalleryProvider, ), - - ChangeNotifierProvider( - create: (context) => mockNutritionProvider, - ), ], child: MaterialApp( locale: locale, diff --git a/integration_test/5_nutritional_plan.dart b/integration_test/5_nutritional_plan.dart index aa8cbc09d..a0cbd5212 100644 --- a/integration_test/5_nutritional_plan.dart +++ b/integration_test/5_nutritional_plan.dart @@ -16,15 +16,13 @@ * along with this program. If not, see . */ -import 'package:drift/native.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; -import 'package:wger/database/ingredients/ingredients_database.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/body_weight_repository.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import 'package:wger/theme/theme.dart'; @@ -35,16 +33,12 @@ import '../test_data/nutritional_plans.dart'; Widget createNutritionalPlanScreen({Locale? locale}) { locale ??= const Locale('en'); - final mockBaseProvider = MockWgerBaseProvider(); final key = GlobalKey(); - // Create a NutritionPlansProvider (still ChangeNotifier) - final nutritionProvider = NutritionPlansProvider( - mockBaseProvider, - [], - database: IngredientDatabase.inMemory(NativeDatabase.memory()), - ); + final mockNutritionRepo = MockNutritionRepository(); + final mockIngredientRepo = MockIngredientRepository(); + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); final mockBodyWeightRepository = MockBodyWeightRepository(); when( @@ -57,32 +51,27 @@ Widget createNutritionalPlanScreen({Locale? locale}) { viewPadding: EdgeInsets.zero, viewInsets: EdgeInsets.zero, ), - child: riverpod.ProviderScope( + child: ProviderScope( overrides: [ bodyWeightRepositoryProvider.overrideWithValue(mockBodyWeightRepository), + nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), ], - child: MultiProvider( - providers: [ - ChangeNotifierProvider( - create: (context) => nutritionProvider, - ), - ], - child: MaterialApp( - locale: locale, - debugShowCheckedModeBanner: false, - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - theme: wgerLightTheme, - navigatorKey: key, - home: TextButton( - onPressed: () => key.currentState!.push( - MaterialPageRoute( - settings: RouteSettings(arguments: getNutritionalPlanScreenshot()), - builder: (_) => const NutritionalPlanScreen(), - ), + child: MaterialApp( + locale: locale, + debugShowCheckedModeBanner: false, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: wgerLightTheme, + navigatorKey: key, + home: TextButton( + onPressed: () => key.currentState!.push( + MaterialPageRoute( + settings: RouteSettings(arguments: getNutritionalPlanScreenshot()), + builder: (_) => const NutritionalPlanScreen(), ), - child: const SizedBox(), ), + child: const SizedBox(), ), ), ), diff --git a/integration_test/6_weight.dart b/integration_test/6_weight.dart index 8773fb0db..d59d42b2d 100644 --- a/integration_test/6_weight.dart +++ b/integration_test/6_weight.dart @@ -17,12 +17,13 @@ */ import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/body_weight_repository.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/providers/user_profile_repository.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/weight_screen.dart'; @@ -43,9 +44,20 @@ Widget createWeightScreen({Locale? locale}) { final mockUserProfileRepository = MockUserProfileRepository(); when(mockUserProfileRepository.fetchProfile()).thenAnswer((_) async => tProfile1); - final mockNutritionPlansProvider = MockNutritionPlansProvider(); - when(mockNutritionPlansProvider.currentPlan).thenReturn(null); - when(mockNutritionPlansProvider.items).thenReturn([getNutritionalPlan()]); + final mockNutritionRepo = MockNutritionRepository(); + final mockIngredientRepo = MockIngredientRepository(); + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); + + final container = ProviderContainer( + overrides: [ + bodyWeightRepositoryProvider.overrideWithValue(mockBodyWeightRepository), + userProfileRepositoryProvider.overrideWithValue(mockUserProfileRepository), + nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), + ], + ); + // Seed the nutrition notifier with a plan so the weight overview can show it. + container.read(nutritionProvider.notifier).state = AsyncData([getNutritionalPlan()]); return MediaQuery( data: MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first).copyWith( @@ -53,26 +65,16 @@ Widget createWeightScreen({Locale? locale}) { viewPadding: EdgeInsets.zero, viewInsets: EdgeInsets.zero, ), - child: riverpod.ProviderScope( - overrides: [ - bodyWeightRepositoryProvider.overrideWithValue(mockBodyWeightRepository), - userProfileRepositoryProvider.overrideWithValue(mockUserProfileRepository), - ], - child: MultiProvider( - providers: [ - ChangeNotifierProvider( - create: (context) => mockNutritionPlansProvider, - ), - ], - child: MaterialApp( - locale: locale, - debugShowCheckedModeBanner: false, - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - theme: wgerLightTheme, - home: const WeightScreen(), - routes: {FormScreen.routeName: (ctx) => const FormScreen()}, - ), + child: UncontrolledProviderScope( + container: container, + child: MaterialApp( + locale: locale, + debugShowCheckedModeBanner: false, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: wgerLightTheme, + home: const WeightScreen(), + routes: {FormScreen.routeName: (ctx) => const FormScreen()}, ), ), ); diff --git a/lib/core/locator.dart b/lib/core/locator.dart deleted file mode 100644 index 1d1c77420..000000000 --- a/lib/core/locator.dart +++ /dev/null @@ -1,37 +0,0 @@ -import 'dart:developer'; -import 'dart:io'; - -import 'package:drift/native.dart'; -import 'package:get_it/get_it.dart'; -import 'package:wger/database/ingredients/ingredients_database.dart'; - -final locator = GetIt.asNewInstance(); - -class ServiceLocator { - factory ServiceLocator() => _singleton; - - const ServiceLocator._internal(); - - static const ServiceLocator _singleton = ServiceLocator._internal(); - - Future _initDB() async { - IngredientDatabase ingredientDB; - - if (Platform.environment.containsKey('FLUTTER_TEST')) { - ingredientDB = IngredientDatabase.inMemory(NativeDatabase.memory()); - } else { - ingredientDB = IngredientDatabase(); - } - - locator.registerSingleton(ingredientDB); - } - - Future configure() async { - try { - await _initDB(); - } catch (e, _) { - log(e.toString()); - rethrow; - } - } -} diff --git a/lib/database/ingredients/ingredients_database.dart b/lib/database/ingredients/ingredients_database.dart deleted file mode 100644 index 0f325e62e..000000000 --- a/lib/database/ingredients/ingredients_database.dart +++ /dev/null @@ -1,64 +0,0 @@ -import 'package:drift/drift.dart'; -import 'package:drift_flutter/drift_flutter.dart'; -import 'package:logging/logging.dart'; - -part 'ingredients_database.g.dart'; - -@DataClassName('IngredientTable') -class Ingredients extends Table { - const Ingredients(); - - IntColumn get id => integer()(); - - TextColumn get data => text()(); - - /// The date when the ingredient was last fetched from the server - DateTimeColumn get lastFetched => dateTime()(); -} - -@DriftDatabase(tables: [Ingredients]) -class IngredientDatabase extends _$IngredientDatabase { - final _logger = Logger('IngredientDatabase'); - - IngredientDatabase() : super(_openConnection()); - - // Named constructor for creating in-memory database - IngredientDatabase.inMemory(super.e); - - /// Note that this needs to be bumped if the JSON response from the server changes - @override - int get schemaVersion => 2; - - /// There is not really a migration strategy. If we bump the version - /// number, delete everything and recreate the new tables. The nutrition provider - /// will fetch everything as needed from the server - @override - MigrationStrategy get migration => MigrationStrategy( - onUpgrade: (m, from, to) async { - // no-op, but needs to be defined - return; - }, - beforeOpen: (openingDetails) async { - if (openingDetails.hadUpgrade) { - final m = createMigrator(); - for (final table in allTables) { - await m.deleteTable(table.actualTableName); - await m.createTable(table); - } - } - }, - ); - - Future deleteEverything() { - return transaction(() async { - for (final table in allTables) { - _logger.info('Deleting db cache table ${table.actualTableName}'); - await delete(table).go(); - } - }); - } -} - -QueryExecutor _openConnection() { - return driftDatabase(name: 'ingredients'); -} diff --git a/lib/database/ingredients/ingredients_database.g.dart b/lib/database/ingredients/ingredients_database.g.dart deleted file mode 100644 index f4ea4650f..000000000 --- a/lib/database/ingredients/ingredients_database.g.dart +++ /dev/null @@ -1,447 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'ingredients_database.dart'; - -// ignore_for_file: type=lint -class $IngredientsTable extends Ingredients with TableInfo<$IngredientsTable, IngredientTable> { - @override - final GeneratedDatabase attachedDatabase; - final String? _alias; - $IngredientsTable(this.attachedDatabase, [this._alias]); - static const VerificationMeta _idMeta = const VerificationMeta('id'); - @override - late final GeneratedColumn id = GeneratedColumn( - 'id', - aliasedName, - false, - type: DriftSqlType.int, - requiredDuringInsert: true, - ); - static const VerificationMeta _dataMeta = const VerificationMeta('data'); - @override - late final GeneratedColumn data = GeneratedColumn( - 'data', - aliasedName, - false, - type: DriftSqlType.string, - requiredDuringInsert: true, - ); - static const VerificationMeta _lastFetchedMeta = const VerificationMeta( - 'lastFetched', - ); - @override - late final GeneratedColumn lastFetched = GeneratedColumn( - 'last_fetched', - aliasedName, - false, - type: DriftSqlType.dateTime, - requiredDuringInsert: true, - ); - @override - List get $columns => [id, data, lastFetched]; - @override - String get aliasedName => _alias ?? actualTableName; - @override - String get actualTableName => $name; - static const String $name = 'ingredients'; - @override - VerificationContext validateIntegrity( - Insertable instance, { - bool isInserting = false, - }) { - final context = VerificationContext(); - final data = instance.toColumns(true); - if (data.containsKey('id')) { - context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); - } else if (isInserting) { - context.missing(_idMeta); - } - if (data.containsKey('data')) { - context.handle( - _dataMeta, - this.data.isAcceptableOrUnknown(data['data']!, _dataMeta), - ); - } else if (isInserting) { - context.missing(_dataMeta); - } - if (data.containsKey('last_fetched')) { - context.handle( - _lastFetchedMeta, - lastFetched.isAcceptableOrUnknown( - data['last_fetched']!, - _lastFetchedMeta, - ), - ); - } else if (isInserting) { - context.missing(_lastFetchedMeta); - } - return context; - } - - @override - Set get $primaryKey => const {}; - @override - IngredientTable map(Map data, {String? tablePrefix}) { - final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; - return IngredientTable( - id: attachedDatabase.typeMapping.read( - DriftSqlType.int, - data['${effectivePrefix}id'], - )!, - data: attachedDatabase.typeMapping.read( - DriftSqlType.string, - data['${effectivePrefix}data'], - )!, - lastFetched: attachedDatabase.typeMapping.read( - DriftSqlType.dateTime, - data['${effectivePrefix}last_fetched'], - )!, - ); - } - - @override - $IngredientsTable createAlias(String alias) { - return $IngredientsTable(attachedDatabase, alias); - } -} - -class IngredientTable extends DataClass implements Insertable { - final int id; - final String data; - - /// The date when the ingredient was last fetched from the server - final DateTime lastFetched; - const IngredientTable({ - required this.id, - required this.data, - required this.lastFetched, - }); - @override - Map toColumns(bool nullToAbsent) { - final map = {}; - map['id'] = Variable(id); - map['data'] = Variable(data); - map['last_fetched'] = Variable(lastFetched); - return map; - } - - IngredientsCompanion toCompanion(bool nullToAbsent) { - return IngredientsCompanion( - id: Value(id), - data: Value(data), - lastFetched: Value(lastFetched), - ); - } - - factory IngredientTable.fromJson( - Map json, { - ValueSerializer? serializer, - }) { - serializer ??= driftRuntimeOptions.defaultSerializer; - return IngredientTable( - id: serializer.fromJson(json['id']), - data: serializer.fromJson(json['data']), - lastFetched: serializer.fromJson(json['lastFetched']), - ); - } - @override - Map toJson({ValueSerializer? serializer}) { - serializer ??= driftRuntimeOptions.defaultSerializer; - return { - 'id': serializer.toJson(id), - 'data': serializer.toJson(data), - 'lastFetched': serializer.toJson(lastFetched), - }; - } - - IngredientTable copyWith({int? id, String? data, DateTime? lastFetched}) => IngredientTable( - id: id ?? this.id, - data: data ?? this.data, - lastFetched: lastFetched ?? this.lastFetched, - ); - IngredientTable copyWithCompanion(IngredientsCompanion data) { - return IngredientTable( - id: data.id.present ? data.id.value : this.id, - data: data.data.present ? data.data.value : this.data, - lastFetched: data.lastFetched.present ? data.lastFetched.value : this.lastFetched, - ); - } - - @override - String toString() { - return (StringBuffer('IngredientTable(') - ..write('id: $id, ') - ..write('data: $data, ') - ..write('lastFetched: $lastFetched') - ..write(')')) - .toString(); - } - - @override - int get hashCode => Object.hash(id, data, lastFetched); - @override - bool operator ==(Object other) => - identical(this, other) || - (other is IngredientTable && - other.id == this.id && - other.data == this.data && - other.lastFetched == this.lastFetched); -} - -class IngredientsCompanion extends UpdateCompanion { - final Value id; - final Value data; - final Value lastFetched; - final Value rowid; - const IngredientsCompanion({ - this.id = const Value.absent(), - this.data = const Value.absent(), - this.lastFetched = const Value.absent(), - this.rowid = const Value.absent(), - }); - IngredientsCompanion.insert({ - required int id, - required String data, - required DateTime lastFetched, - this.rowid = const Value.absent(), - }) : id = Value(id), - data = Value(data), - lastFetched = Value(lastFetched); - static Insertable custom({ - Expression? id, - Expression? data, - Expression? lastFetched, - Expression? rowid, - }) { - return RawValuesInsertable({ - if (id != null) 'id': id, - if (data != null) 'data': data, - if (lastFetched != null) 'last_fetched': lastFetched, - if (rowid != null) 'rowid': rowid, - }); - } - - IngredientsCompanion copyWith({ - Value? id, - Value? data, - Value? lastFetched, - Value? rowid, - }) { - return IngredientsCompanion( - id: id ?? this.id, - data: data ?? this.data, - lastFetched: lastFetched ?? this.lastFetched, - rowid: rowid ?? this.rowid, - ); - } - - @override - Map toColumns(bool nullToAbsent) { - final map = {}; - if (id.present) { - map['id'] = Variable(id.value); - } - if (data.present) { - map['data'] = Variable(data.value); - } - if (lastFetched.present) { - map['last_fetched'] = Variable(lastFetched.value); - } - if (rowid.present) { - map['rowid'] = Variable(rowid.value); - } - return map; - } - - @override - String toString() { - return (StringBuffer('IngredientsCompanion(') - ..write('id: $id, ') - ..write('data: $data, ') - ..write('lastFetched: $lastFetched, ') - ..write('rowid: $rowid') - ..write(')')) - .toString(); - } -} - -abstract class _$IngredientDatabase extends GeneratedDatabase { - _$IngredientDatabase(QueryExecutor e) : super(e); - $IngredientDatabaseManager get managers => $IngredientDatabaseManager(this); - late final $IngredientsTable ingredients = $IngredientsTable(this); - @override - Iterable> get allTables => - allSchemaEntities.whereType>(); - @override - List get allSchemaEntities => [ingredients]; - @override - DriftDatabaseOptions get options => const DriftDatabaseOptions(storeDateTimeAsText: true); -} - -typedef $$IngredientsTableCreateCompanionBuilder = - IngredientsCompanion Function({ - required int id, - required String data, - required DateTime lastFetched, - Value rowid, - }); -typedef $$IngredientsTableUpdateCompanionBuilder = - IngredientsCompanion Function({ - Value id, - Value data, - Value lastFetched, - Value rowid, - }); - -class $$IngredientsTableFilterComposer extends Composer<_$IngredientDatabase, $IngredientsTable> { - $$IngredientsTableFilterComposer({ - required super.$db, - required super.$table, - super.joinBuilder, - super.$addJoinBuilderToRootComposer, - super.$removeJoinBuilderFromRootComposer, - }); - ColumnFilters get id => $composableBuilder( - column: $table.id, - builder: (column) => ColumnFilters(column), - ); - - ColumnFilters get data => $composableBuilder( - column: $table.data, - builder: (column) => ColumnFilters(column), - ); - - ColumnFilters get lastFetched => $composableBuilder( - column: $table.lastFetched, - builder: (column) => ColumnFilters(column), - ); -} - -class $$IngredientsTableOrderingComposer extends Composer<_$IngredientDatabase, $IngredientsTable> { - $$IngredientsTableOrderingComposer({ - required super.$db, - required super.$table, - super.joinBuilder, - super.$addJoinBuilderToRootComposer, - super.$removeJoinBuilderFromRootComposer, - }); - ColumnOrderings get id => $composableBuilder( - column: $table.id, - builder: (column) => ColumnOrderings(column), - ); - - ColumnOrderings get data => $composableBuilder( - column: $table.data, - builder: (column) => ColumnOrderings(column), - ); - - ColumnOrderings get lastFetched => $composableBuilder( - column: $table.lastFetched, - builder: (column) => ColumnOrderings(column), - ); -} - -class $$IngredientsTableAnnotationComposer - extends Composer<_$IngredientDatabase, $IngredientsTable> { - $$IngredientsTableAnnotationComposer({ - required super.$db, - required super.$table, - super.joinBuilder, - super.$addJoinBuilderToRootComposer, - super.$removeJoinBuilderFromRootComposer, - }); - GeneratedColumn get id => $composableBuilder(column: $table.id, builder: (column) => column); - - GeneratedColumn get data => - $composableBuilder(column: $table.data, builder: (column) => column); - - GeneratedColumn get lastFetched => $composableBuilder( - column: $table.lastFetched, - builder: (column) => column, - ); -} - -class $$IngredientsTableTableManager - extends - RootTableManager< - _$IngredientDatabase, - $IngredientsTable, - IngredientTable, - $$IngredientsTableFilterComposer, - $$IngredientsTableOrderingComposer, - $$IngredientsTableAnnotationComposer, - $$IngredientsTableCreateCompanionBuilder, - $$IngredientsTableUpdateCompanionBuilder, - ( - IngredientTable, - BaseReferences<_$IngredientDatabase, $IngredientsTable, IngredientTable>, - ), - IngredientTable, - PrefetchHooks Function() - > { - $$IngredientsTableTableManager( - _$IngredientDatabase db, - $IngredientsTable table, - ) : super( - TableManagerState( - db: db, - table: table, - createFilteringComposer: () => $$IngredientsTableFilterComposer($db: db, $table: table), - createOrderingComposer: () => $$IngredientsTableOrderingComposer($db: db, $table: table), - createComputedFieldComposer: () => - $$IngredientsTableAnnotationComposer($db: db, $table: table), - updateCompanionCallback: - ({ - Value id = const Value.absent(), - Value data = const Value.absent(), - Value lastFetched = const Value.absent(), - Value rowid = const Value.absent(), - }) => IngredientsCompanion( - id: id, - data: data, - lastFetched: lastFetched, - rowid: rowid, - ), - createCompanionCallback: - ({ - required int id, - required String data, - required DateTime lastFetched, - Value rowid = const Value.absent(), - }) => IngredientsCompanion.insert( - id: id, - data: data, - lastFetched: lastFetched, - rowid: rowid, - ), - withReferenceMapper: (p0) => - p0.map((e) => (e.readTable(table), BaseReferences(db, table, e))).toList(), - prefetchHooksCallback: null, - ), - ); -} - -typedef $$IngredientsTableProcessedTableManager = - ProcessedTableManager< - _$IngredientDatabase, - $IngredientsTable, - IngredientTable, - $$IngredientsTableFilterComposer, - $$IngredientsTableOrderingComposer, - $$IngredientsTableAnnotationComposer, - $$IngredientsTableCreateCompanionBuilder, - $$IngredientsTableUpdateCompanionBuilder, - ( - IngredientTable, - BaseReferences<_$IngredientDatabase, $IngredientsTable, IngredientTable>, - ), - IngredientTable, - PrefetchHooks Function() - >; - -class $IngredientDatabaseManager { - final _$IngredientDatabase _db; - $IngredientDatabaseManager(this._db); - $$IngredientsTableTableManager get ingredients => - $$IngredientsTableTableManager(_db, _db.ingredients); -} diff --git a/lib/helpers/shared_preferences.dart b/lib/helpers/shared_preferences.dart index cdab8a537..d45a97633 100644 --- a/lib/helpers/shared_preferences.dart +++ b/lib/helpers/shared_preferences.dart @@ -1,6 +1,6 @@ import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/util/legacy_to_async_migration_util.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_repository.dart'; /// A helper class that manages preferences using SharedPreferencesAsync /// and handles migration from the legacy SharedPreferences to diff --git a/lib/main.dart b/lib/main.dart index aec50771e..4dd39e14a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -22,7 +22,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart' hide Consumer, Provider; import 'package:logging/logging.dart'; import 'package:provider/provider.dart'; import 'package:wger/core/exceptions/http_exception.dart'; -import 'package:wger/core/locator.dart'; import 'package:wger/helpers/errors.dart'; import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -32,7 +31,6 @@ import 'package:wger/providers/auth_notifier.dart'; import 'package:wger/providers/auth_state.dart'; import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/gallery.dart'; -import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/wger_base_riverpod.dart'; import 'package:wger/screens/add_exercise_screen.dart'; import 'package:wger/screens/auth_screen.dart'; @@ -88,9 +86,6 @@ void main() async { final logger = Logger('main'); - // Locator to initialize exerciseDB - await ServiceLocator().configure(); - // SharedPreferences to SharedPreferencesAsync migration function await PreferenceHelper.instance.migrationSupportFunctionForSharedPreferences(); // Catch errors from Flutter itself (widget build, layout, paint, etc.) @@ -175,9 +170,6 @@ class MainApp extends ConsumerWidget { return MultiProvider( providers: [ Provider.value(value: base), - ChangeNotifierProvider( - create: (_) => NutritionPlansProvider(base, []), - ), ChangeNotifierProvider( create: (_) => GalleryProvider( serverUrl: base.serverUrl, diff --git a/lib/models/nutrition/ingredient_filters.dart b/lib/models/nutrition/ingredient_filters.dart index bb34415c1..7d3fa0146 100644 --- a/lib/models/nutrition/ingredient_filters.dart +++ b/lib/models/nutrition/ingredient_filters.dart @@ -1,5 +1,5 @@ //model is used to store ingredient filters values -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_repository.dart'; class IngredientFilters { final bool isVegan; diff --git a/lib/providers/nutrition.dart b/lib/providers/nutrition.dart deleted file mode 100644 index bb751d5be..000000000 --- a/lib/providers/nutrition.dart +++ /dev/null @@ -1,536 +0,0 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2026 wger Team - * - * wger Workout Manager is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import 'dart:convert'; - -import 'package:collection/collection.dart'; -import 'package:flutter/material.dart'; -import 'package:logging/logging.dart'; -import 'package:wger/core/exceptions/http_exception.dart'; -import 'package:wger/core/exceptions/no_such_entry_exception.dart'; -import 'package:wger/core/locator.dart'; -import 'package:wger/database/ingredients/ingredients_database.dart'; -import 'package:wger/helpers/consts.dart'; -import 'package:wger/models/nutrition/ingredient.dart'; -import 'package:wger/models/nutrition/ingredient_image.dart'; -import 'package:wger/models/nutrition/ingredient_weight_unit.dart'; -import 'package:wger/models/nutrition/log.dart'; -import 'package:wger/models/nutrition/meal.dart'; -import 'package:wger/models/nutrition/meal_item.dart'; -import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/base_provider.dart'; - -enum IngredientSearchLanguage { - current, - currentAndEnglish, - all, -} - -class NutritionPlansProvider with ChangeNotifier { - final _logger = Logger('NutritionPlansProvider'); - - static const _nutritionalPlansPath = 'nutritionplan'; - static const _nutritionalPlansInfoPath = 'nutritionplaninfo'; - static const _mealPath = 'meal'; - static const _mealItemPath = 'mealitem'; - static const _ingredientInfoPath = 'ingredientinfo'; - static const _nutritionDiaryPath = 'nutritiondiary'; - static const _ingredientWeightUnitPath = 'ingredientweightunit'; - - final WgerBaseProvider baseProvider; - late IngredientDatabase database; - List _plans = []; - List ingredients = []; - - NutritionPlansProvider( - this.baseProvider, - List entries, { - IngredientDatabase? database, - }) : _plans = entries { - this.database = database ?? locator(); - } - - List get items { - return [..._plans]; - } - - /// Clears all lists - void clear() { - _plans = []; - ingredients = []; - } - - /// Returns the current active nutritional plan. - /// A plan is considered active if: - /// - Its start date is before now - /// - Its end date is after now or not set - /// If multiple plans match these criteria, the one with the most recent creation date is returned. - NutritionalPlan? get currentPlan { - final now = DateTime.now(); - return _plans - .where( - (plan) => - plan.startDate.isBefore(now) && (plan.endDate == null || plan.endDate!.isAfter(now)), - ) - .toList() - .sorted((a, b) => b.creationDate.compareTo(a.creationDate)) - .firstOrNull; - } - - NutritionalPlan findById(int id) { - return _plans.firstWhere( - (plan) => plan.id == id, - orElse: () => throw const NoSuchEntryException(), - ); - } - - Meal? findMealById(int id) { - for (final plan in _plans) { - try { - final meal = plan.meals.firstWhere((plan) => plan.id == id); - return meal; - } on StateError {} - } - return null; - } - - /// Fetches and sets all plans sparsely, i.e. only with the data on the plan - /// object itself and no child attributes - Future fetchAndSetAllPlansSparse() async { - final data = await baseProvider.fetchPaginated( - baseProvider.makeUrl(_nutritionalPlansPath, query: {'limit': API_MAX_PAGE_SIZE}), - ); - _plans = []; - for (final planData in data) { - final plan = NutritionalPlan.fromJson(planData); - _plans.add(plan); - _plans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); - } - notifyListeners(); - } - - /// Fetches and sets all plans fully, i.e. with all corresponding child objects - Future fetchAndSetAllPlansFull() async { - final data = await baseProvider.fetchPaginated( - baseProvider.makeUrl(_nutritionalPlansPath, query: {'limit': API_MAX_PAGE_SIZE}), - ); - await Future.wait(data.map((e) => fetchAndSetPlanFull(e['id'])).toList()); - } - - /// Fetches and sets the given nutritional plan - /// - /// This method only loads the data on the nutritional plan object itself, - /// no meals, etc. - Future fetchAndSetPlanSparse(int planId) async { - final url = baseProvider.makeUrl(_nutritionalPlansPath, id: planId); - final planData = await baseProvider.fetch(url); - final plan = NutritionalPlan.fromJson(planData); - _plans.add(plan); - _plans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); - - notifyListeners(); - return plan; - } - - /// Fetches a plan fully, i.e. with all corresponding child objects - Future fetchAndSetPlanFull(int planId) async { - _logger.fine('Fetching full nutritional plan $planId'); - - NutritionalPlan plan; - try { - plan = findById(planId); - } on NoSuchEntryException { - // TODO: remove this useless call, because we will fetch all details below - plan = await fetchAndSetPlanSparse(planId); - } - - // Plan - final url = baseProvider.makeUrl(_nutritionalPlansInfoPath, id: planId); - final fullPlanData = await baseProvider.fetch(url); - - // Meals - final List meals = []; - for (final mealData in fullPlanData['meals']) { - final List mealItems = []; - final meal = Meal.fromJson(mealData); - - // TODO: we should add these ingredients to the ingredient cache - for (final mealItemData in mealData['meal_items']) { - final mealItem = MealItem.fromJson(mealItemData); - - final ingredient = Ingredient.fromJson(mealItemData['ingredient_obj']); - if (mealItemData['image'] != null) { - final image = IngredientImage.fromJson(mealItemData['image']); - ingredient.image = image; - } - mealItem.ingredient = ingredient; - mealItems.add(mealItem); - } - meal.mealItems = mealItems; - meals.add(meal); - } - plan.meals = meals; - - // Logs - await fetchAndSetLogs(plan); - for (final meal in meals) { - meal.diaryEntries = plan.diaryEntries.where((e) => e.mealId == meal.id).toList(); - } - - // ... and done - notifyListeners(); - return plan; - } - - Future addPlan(NutritionalPlan planData) async { - final data = await baseProvider.post( - planData.toJson(), - baseProvider.makeUrl(_nutritionalPlansPath), - ); - final plan = NutritionalPlan.fromJson(data); - _plans.add(plan); - _plans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); - notifyListeners(); - return plan; - } - - Future editPlan(NutritionalPlan plan) async { - await baseProvider.patch( - plan.toJson(), - baseProvider.makeUrl(_nutritionalPlansPath, id: plan.id), - ); - notifyListeners(); - } - - Future deletePlan(int id) async { - final existingPlanIndex = _plans.indexWhere((element) => element.id == id); - final existingPlan = _plans[existingPlanIndex]; - _plans.removeAt(existingPlanIndex); - notifyListeners(); - - final response = await baseProvider.deleteRequest(_nutritionalPlansPath, id); - - if (response.statusCode >= 400) { - _plans.insert(existingPlanIndex, existingPlan); - notifyListeners(); - throw WgerHttpException(response); - } - //existingPlan = null; - } - - /// Adds a meal to a plan - Future addMeal(Meal meal, int planId) async { - final plan = findById(planId); - final data = await baseProvider.post(meal.toJson(), baseProvider.makeUrl(_mealPath)); - - meal = Meal.fromJson(data); - plan.meals.add(meal); - notifyListeners(); - - return meal; - } - - /// Edits an existing meal - Future editMeal(Meal meal) async { - final data = await baseProvider.patch( - meal.toJson(), - baseProvider.makeUrl(_mealPath, id: meal.id), - ); - meal = Meal.fromJson(data); - - notifyListeners(); - return meal; - } - - /// Deletes a meal - Future deleteMeal(Meal meal) async { - // Get the meal - final plan = findById(meal.planId); - final mealIndex = plan.meals.indexWhere((e) => e.id == meal.id); - final existingMeal = plan.meals[mealIndex]; - plan.meals.removeAt(mealIndex); - notifyListeners(); - - // Try to delete - final response = await baseProvider.deleteRequest(_mealPath, meal.id!); - if (response.statusCode >= 400) { - plan.meals.insert(mealIndex, existingMeal); - notifyListeners(); - throw WgerHttpException(response); - } - } - - /// Adds a meal item to a meal - Future addMealItem(MealItem mealItem, Meal meal) async { - final data = await baseProvider.post(mealItem.toJson(), baseProvider.makeUrl(_mealItemPath)); - - mealItem = MealItem.fromJson(data); - mealItem.ingredient = await fetchIngredient(mealItem.ingredientId); - meal.mealItems.add(mealItem); - notifyListeners(); - - return mealItem; - } - - /// Deletes a meal - Future deleteMealItem(MealItem mealItem) async { - // Get the meal - final meal = findMealById(mealItem.mealId)!; - final mealItemIndex = meal.mealItems.indexWhere((e) => e.id == mealItem.id); - final existingMealItem = meal.mealItems[mealItemIndex]; - meal.mealItems.removeAt(mealItemIndex); - notifyListeners(); - - // Try to delete - final response = await baseProvider.deleteRequest(_mealItemPath, mealItem.id!); - if (response.statusCode >= 400) { - meal.mealItems.insert(mealItemIndex, existingMealItem); - notifyListeners(); - throw WgerHttpException(response); - } - } - - Future clearIngredientCache() async { - ingredients = []; - await database.deleteEverything(); - } - - /// Saves an ingredient to the cache - Future cacheIngredient(Ingredient ingredient, {IngredientDatabase? database}) async { - database ??= this.database; - - if (!ingredients.any((e) => e.id == ingredient.id)) { - ingredients.add(ingredient); - } - - final ingredientDb = await (database.select( - database.ingredients, - )..where((e) => e.id.equals(ingredient.id))).getSingleOrNull(); - - if (ingredientDb == null) { - final data = ingredient.toJson(); - try { - await database - .into(database.ingredients) - .insert( - IngredientsCompanion.insert( - id: ingredient.id, - data: jsonEncode(data), - lastFetched: DateTime.now(), - ), - ); - _logger.finer("Saved ingredient '${ingredient.name}' to db cache"); - } catch (e) { - _logger.finer("Error caching ingredient '${ingredient.name}': $e"); - } - } - } - - /// Fetch and return an ingredient - /// - /// If the ingredient is not known locally, it is fetched from the server - Future fetchIngredient(int ingredientId, {IngredientDatabase? database}) async { - database ??= this.database; - Ingredient ingredient; - - try { - ingredient = ingredients.firstWhere((e) => e.id == ingredientId); - } on StateError { - final ingredientDb = await (database.select( - database.ingredients, - )..where((e) => e.id.equals(ingredientId))).getSingleOrNull(); - - // Try to fetch from local db - if (ingredientDb != null) { - ingredient = Ingredient.fromJson(jsonDecode(ingredientDb.data)); - ingredients.add(ingredient); - _logger.info("Loaded ingredient '${ingredient.name}' from db cache"); - - // Prune old entries - if (DateTime.now().isAfter( - ingredientDb.lastFetched.add(const Duration(days: DAYS_TO_CACHE)), - )) { - (database.delete(database.ingredients)..where((i) => i.id.equals(ingredientId))).go(); - } - } else { - _logger.info("Fetching ingredient ID $ingredientId from server"); - final data = await baseProvider.fetch( - baseProvider.makeUrl(_ingredientInfoPath, id: ingredientId), - ); - ingredient = Ingredient.fromJson(data); - - // Cache the ingredient - await cacheIngredient(ingredient, database: database); - } - } - - return ingredient; - } - - /// Fetch the available weight units for an ingredient - Future> fetchWeightUnits(int ingredientId) async { - final data = await baseProvider.fetchPaginated( - baseProvider.makeUrl( - _ingredientWeightUnitPath, - query: {'ingredient': ingredientId.toString()}, - ), - ); - return data.map((e) => IngredientWeightUnit.fromJson(e)).toList(); - } - - /// Loads the available ingredients from the local cache - Future fetchIngredientsFromCache() async { - final ingredientDb = await database.select(database.ingredients).get(); - _logger.info('Read ${ingredientDb.length} ingredients from db cache'); - if (ingredientDb.isNotEmpty) { - ingredients = ingredientDb.map((e) => Ingredient.fromJson(jsonDecode(e.data))).toList(); - } - } - - /// Searches for an ingredient - Future> searchIngredient( - String name, { - String languageCode = 'en', - IngredientSearchLanguage searchLanguage = IngredientSearchLanguage.current, - bool isVegan = false, - bool isVegetarian = false, - }) async { - if (name.length <= 1) { - return []; - } - final List languages = []; - - switch (searchLanguage) { - case IngredientSearchLanguage.current: - languages.add(languageCode); - break; - case IngredientSearchLanguage.currentAndEnglish: - languages.add(languageCode); - if (languageCode != LANGUAGE_SHORT_ENGLISH) { - languages.add(LANGUAGE_SHORT_ENGLISH); - } - break; - case IngredientSearchLanguage.all: - // Don't add any language code to search in all languages - break; - } - - final query = { - 'name__search': name, - 'limit': API_RESULTS_PAGE_SIZE, - }; - - if (languages.isNotEmpty) { - query['language__code'] = languages.join(','); - } - - if (isVegan) { - query['is_vegan'] = 'true'; - } - - if (isVegetarian) { - query['is_vegetarian'] = 'true'; - } - - // Send the request - _logger.info('Fetching ingredients from server'); - final response = await baseProvider.fetch( - baseProvider.makeUrl( - _ingredientInfoPath, - query: query, - ), - timeout: const Duration(seconds: 20), - ); - - return (response['results'] as List) - .map((ingredientData) => Ingredient.fromJson(ingredientData as Map)) - .toList(); - } - - /// Searches for an ingredient with bar code - Future searchIngredientWithBarcode(String barcode) async { - if (barcode.isEmpty) { - return null; - } - - // Send the request - final data = await baseProvider.fetch( - baseProvider.makeUrl(_ingredientInfoPath, query: {'code': barcode}), - ); - - if (data['count'] == 0) { - return null; - } - - // TODO we should probably add it to ingredient cache. - return Ingredient.fromJson(data['results'][0]); - } - - /// Log meal to nutrition diary - Future logMealToDiary(Meal meal, DateTime mealDateTime) async { - for (final item in meal.mealItems) { - final plan = findById(meal.planId); - final Log log = Log.fromMealItem(item, plan.id!, meal.id, mealDateTime); - - final data = await baseProvider.post(log.toJson(), baseProvider.makeUrl(_nutritionDiaryPath)); - log.id = data['id']; - plan.diaryEntries.add(log); - } - notifyListeners(); - } - - /// Log custom ingredient to nutrition diary - Future logIngredientToDiary(MealItem mealItem, int planId, [DateTime? dateTime]) async { - final plan = findById(planId); - mealItem.ingredient = await fetchIngredient(mealItem.ingredientId); - final log = Log.fromMealItem(mealItem, plan.id!, null, dateTime); - - final data = await baseProvider.post(log.toJson(), baseProvider.makeUrl(_nutritionDiaryPath)); - log.id = data['id']; - plan.diaryEntries.add(log); - notifyListeners(); - } - - /// Deletes a log entry - Future deleteLog(int logId, int planId) async { - await baseProvider.deleteRequest(_nutritionDiaryPath, logId); - - final plan = findById(planId); - plan.diaryEntries.removeWhere((element) => element.id == logId); - notifyListeners(); - } - - /// Load nutrition diary entries for plan - Future fetchAndSetLogs(NutritionalPlan plan) async { - final data = await baseProvider.fetchPaginated( - baseProvider.makeUrl( - _nutritionDiaryPath, - query: {'plan': plan.id?.toString(), 'limit': API_MAX_PAGE_SIZE, 'ordering': 'datetime'}, - ), - ); - - plan.diaryEntries = []; - for (final logData in data) { - final log = Log.fromJson(logData); - final ingredient = await fetchIngredient(log.ingredientId); - log.ingredient = ingredient; - plan.diaryEntries.add(log); - } - notifyListeners(); - } -} diff --git a/lib/providers/nutrition_ingredient_filters_riverpod.dart b/lib/providers/nutrition_ingredient_filters_riverpod.dart index f95de5647..38a43ef53 100644 --- a/lib/providers/nutrition_ingredient_filters_riverpod.dart +++ b/lib/providers/nutrition_ingredient_filters_riverpod.dart @@ -20,7 +20,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart' show Provider; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/models/nutrition/ingredient_filters.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_repository.dart'; part 'nutrition_ingredient_filters_riverpod.g.dart'; diff --git a/lib/providers/nutrition_notifier.dart b/lib/providers/nutrition_notifier.dart new file mode 100644 index 000000000..832a63f8f --- /dev/null +++ b/lib/providers/nutrition_notifier.dart @@ -0,0 +1,347 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2020 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:collection/collection.dart'; +import 'package:logging/logging.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:wger/core/exceptions/http_exception.dart'; +import 'package:wger/core/exceptions/no_such_entry_exception.dart'; +import 'package:wger/models/nutrition/ingredient.dart'; +import 'package:wger/models/nutrition/ingredient_image.dart'; +import 'package:wger/models/nutrition/ingredient_weight_unit.dart'; +import 'package:wger/models/nutrition/log.dart'; +import 'package:wger/models/nutrition/meal.dart'; +import 'package:wger/models/nutrition/meal_item.dart'; +import 'package:wger/models/nutrition/nutritional_plan.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_repository.dart'; + +part 'nutrition_notifier.g.dart'; + +@Riverpod(keepAlive: true) +class NutritionNotifier extends _$NutritionNotifier { + final _logger = Logger('NutritionNotifier'); + + late IngredientRepository _ingredientRepo; + late NutritionRepository _nutritionRepo; + + @override + Future> build() async { + _nutritionRepo = ref.read(nutritionRepositoryProvider); + _ingredientRepo = ref.read(ingredientRepositoryProvider); + return []; + } + + List get _plans => state.asData?.value ?? []; + + void _setPlans(List plans) { + state = AsyncData(List.of(plans)); + } + + /// Notifies listeners after in-place mutation on the plans list (e.g. when + /// meals or logs on a plan are mutated via object references). Equivalent to + /// the old `notifyListeners()`. + void _notifyAfterInPlaceMutation() { + _setPlans(_plans); + } + + /// Returns the current active nutritional plan. + /// + /// A plan is considered active if its start date is before now and its end + /// date is after now (or not set). With multiple matches, the most recently + /// created plan wins. + NutritionalPlan? get currentPlan { + final now = DateTime.now(); + return _plans + .where( + (plan) => + plan.startDate.isBefore(now) && (plan.endDate == null || plan.endDate!.isAfter(now)), + ) + .toList() + .sorted((a, b) => b.creationDate.compareTo(a.creationDate)) + .firstOrNull; + } + + NutritionalPlan findById(int id) { + return _plans.firstWhere( + (plan) => plan.id == id, + orElse: () => throw const NoSuchEntryException(), + ); + } + + Meal? findMealById(int id) { + for (final plan in _plans) { + final meal = plan.meals.firstWhereOrNull((m) => m.id == id); + if (meal != null) { + return meal; + } + } + return null; + } + + /// Clears all plans. Called on logout. + void clear() { + _setPlans([]); + } + + // --- Plans --- + + /// Fetches all plans sparsely (no meals, items or logs). + Future fetchAndSetAllPlansSparse() async { + final data = await _nutritionRepo.fetchAllPlans(); + final plans = data.map((e) => NutritionalPlan.fromJson(e)).toList() + ..sort((a, b) => b.creationDate.compareTo(a.creationDate)); + _setPlans(plans); + } + + Future fetchAndSetAllPlansFull() async { + final data = await _nutritionRepo.fetchAllPlans(); + await Future.wait(data.map((e) => fetchAndSetPlanFull(e['id'])).toList()); + } + + Future fetchAndSetPlanSparse(int planId) async { + final data = await _nutritionRepo.fetchPlanSparse(planId); + final plan = NutritionalPlan.fromJson(data); + final plans = List.of(_plans)..add(plan); + plans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); + _setPlans(plans); + return plan; + } + + /// Fetches a plan with meals, meal items, and log entries. + Future fetchAndSetPlanFull(int planId) async { + _logger.fine('Fetching full nutritional plan $planId'); + + NutritionalPlan plan; + try { + plan = findById(planId); + } on NoSuchEntryException { + plan = await fetchAndSetPlanSparse(planId); + } + + final fullPlanData = await _nutritionRepo.fetchPlanFull(planId); + + // Meals + final List meals = []; + for (final mealData in fullPlanData['meals']) { + final List mealItems = []; + final meal = Meal.fromJson(mealData); + + for (final mealItemData in mealData['meal_items']) { + final mealItem = MealItem.fromJson(mealItemData); + + final ingredient = Ingredient.fromJson(mealItemData['ingredient_obj']); + if (mealItemData['image'] != null) { + ingredient.image = IngredientImage.fromJson(mealItemData['image']); + } + mealItem.ingredient = ingredient; + mealItems.add(mealItem); + } + meal.mealItems = mealItems; + meals.add(meal); + } + plan.meals = meals; + + // Logs + await fetchAndSetLogs(plan); + for (final meal in meals) { + meal.diaryEntries = plan.diaryEntries.where((e) => e.mealId == meal.id).toList(); + } + + _notifyAfterInPlaceMutation(); + return plan; + } + + Future addPlan(NutritionalPlan planData) async { + final data = await _nutritionRepo.createPlan(planData.toJson()); + final plan = NutritionalPlan.fromJson(data); + final plans = List.of(_plans)..add(plan); + plans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); + _setPlans(plans); + return plan; + } + + Future editPlan(NutritionalPlan plan) async { + await _nutritionRepo.updatePlan(plan.id!, plan.toJson()); + _notifyAfterInPlaceMutation(); + } + + Future deletePlan(int id) async { + final plans = List.of(_plans); + final index = plans.indexWhere((element) => element.id == id); + final existing = plans[index]; + plans.removeAt(index); + _setPlans(plans); + + final response = await _nutritionRepo.deletePlan(id); + + if (response.statusCode >= 400) { + plans.insert(index, existing); + _setPlans(plans); + throw WgerHttpException(response); + } + } + + // --- Meals --- + + Future addMeal(Meal meal, int planId) async { + final plan = findById(planId); + meal.planId = planId; + final data = await _nutritionRepo.createMeal(meal.toJson()); + final saved = Meal.fromJson(data); + plan.meals.add(saved); + _notifyAfterInPlaceMutation(); + return saved; + } + + Future editMeal(Meal meal) async { + final data = await _nutritionRepo.updateMeal(meal.id!, meal.toJson()); + final updated = Meal.fromJson(data); + _notifyAfterInPlaceMutation(); + return updated; + } + + Future deleteMeal(Meal meal) async { + final plan = findById(meal.planId); + final mealIndex = plan.meals.indexWhere((e) => e.id == meal.id); + final existing = plan.meals[mealIndex]; + plan.meals.removeAt(mealIndex); + _notifyAfterInPlaceMutation(); + + final response = await _nutritionRepo.deleteMeal(meal.id!); + if (response.statusCode >= 400) { + plan.meals.insert(mealIndex, existing); + _notifyAfterInPlaceMutation(); + throw WgerHttpException(response); + } + } + + // --- Meal items --- + + Future addMealItem(MealItem mealItem, Meal meal) async { + final data = await _nutritionRepo.createMealItem(mealItem.toJson()); + final saved = MealItem.fromJson(data); + saved.ingredient = await fetchIngredient(saved.ingredientId); + meal.mealItems.add(saved); + _notifyAfterInPlaceMutation(); + return saved; + } + + Future deleteMealItem(MealItem mealItem) async { + final meal = findMealById(mealItem.mealId)!; + final mealItemIndex = meal.mealItems.indexWhere((e) => e.id == mealItem.id); + final existing = meal.mealItems[mealItemIndex]; + meal.mealItems.removeAt(mealItemIndex); + _notifyAfterInPlaceMutation(); + + final response = await _nutritionRepo.deleteMealItem(mealItem.id!); + if (response.statusCode >= 400) { + meal.mealItems.insert(mealItemIndex, existing); + _notifyAfterInPlaceMutation(); + throw WgerHttpException(response); + } + } + + // --- Ingredients --- + + /// Looks up an ingredient by id. + /// + /// Tries PowerSync-backed local storage first and only hits the server if the + /// ingredient has not been synced yet. + Future fetchIngredient(int ingredientId) async { + final local = await _ingredientRepo.getById(ingredientId); + if (local != null) { + _logger.finer("Loaded ingredient '${local.name}' from PowerSync"); + return local; + } + return _nutritionRepo.fetchIngredient(ingredientId); + } + + Future> searchIngredient( + String name, { + String languageCode = 'en', + IngredientSearchLanguage searchLanguage = IngredientSearchLanguage.current, + bool isVegan = false, + bool isVegetarian = false, + }) { + return _nutritionRepo.searchIngredient( + name, + languageCode: languageCode, + searchLanguage: searchLanguage, + isVegan: isVegan, + isVegetarian: isVegetarian, + ); + } + + Future searchIngredientWithBarcode(String barcode) { + return _nutritionRepo.searchIngredientWithBarcode(barcode); + } + + Future> fetchWeightUnits(int ingredientId) { + return _nutritionRepo.fetchWeightUnits(ingredientId); + } + + // --- Logs (nutrition diary) --- + + Future logMealToDiary(Meal meal, DateTime mealDateTime) async { + final plan = findById(meal.planId); + for (final item in meal.mealItems) { + final log = Log.fromMealItem(item, plan.id!, meal.id, mealDateTime); + final data = await _nutritionRepo.createLog(log.toJson()); + log.id = data['id']; + plan.diaryEntries.add(log); + } + _notifyAfterInPlaceMutation(); + } + + Future logIngredientToDiary( + MealItem mealItem, + int planId, [ + DateTime? dateTime, + ]) async { + final plan = findById(planId); + mealItem.ingredient = await fetchIngredient(mealItem.ingredientId); + final log = Log.fromMealItem(mealItem, plan.id!, null, dateTime); + + final data = await _nutritionRepo.createLog(log.toJson()); + log.id = data['id']; + plan.diaryEntries.add(log); + _notifyAfterInPlaceMutation(); + } + + Future deleteLog(int logId, int planId) async { + await _nutritionRepo.deleteLog(logId); + final plan = findById(planId); + plan.diaryEntries.removeWhere((element) => element.id == logId); + _notifyAfterInPlaceMutation(); + } + + /// Loads nutrition diary entries for the given plan and resolves ingredient + /// references. + Future fetchAndSetLogs(NutritionalPlan plan) async { + final data = await _nutritionRepo.fetchLogsForPlan(plan.id!); + + plan.diaryEntries = []; + for (final logData in data) { + final log = Log.fromJson(logData); + log.ingredient = await fetchIngredient(log.ingredientId); + plan.diaryEntries.add(log); + } + _notifyAfterInPlaceMutation(); + } +} diff --git a/lib/providers/nutrition_notifier.g.dart b/lib/providers/nutrition_notifier.g.dart new file mode 100644 index 000000000..f0338cf37 --- /dev/null +++ b/lib/providers/nutrition_notifier.g.dart @@ -0,0 +1,54 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'nutrition_notifier.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(NutritionNotifier) +final nutritionProvider = NutritionNotifierProvider._(); + +final class NutritionNotifierProvider + extends $AsyncNotifierProvider> { + NutritionNotifierProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'nutritionProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$nutritionNotifierHash(); + + @$internal + @override + NutritionNotifier create() => NutritionNotifier(); +} + +String _$nutritionNotifierHash() => r'01b80c30e88543c31604bbae3f57b29173f1022d'; + +abstract class _$NutritionNotifier extends $AsyncNotifier> { + FutureOr> build(); + @$mustCallSuper + @override + void runBuild() { + final ref = this.ref as $Ref>, List>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier>, List>, + AsyncValue>, + Object?, + Object? + >; + element.handleCreate(ref, build); + } +} diff --git a/lib/providers/nutrition_repository.dart b/lib/providers/nutrition_repository.dart new file mode 100644 index 000000000..81dac04f7 --- /dev/null +++ b/lib/providers/nutrition_repository.dart @@ -0,0 +1,216 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2020 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:http/http.dart' as http; +import 'package:logging/logging.dart'; +import 'package:wger/helpers/consts.dart'; +import 'package:wger/models/nutrition/ingredient.dart'; +import 'package:wger/models/nutrition/ingredient_weight_unit.dart'; +import 'package:wger/providers/base_provider.dart'; +import 'package:wger/providers/wger_base_riverpod.dart'; + +enum IngredientSearchLanguage { + current, + currentAndEnglish, + all, +} + +final nutritionRepositoryProvider = Provider((ref) { + final base = ref.read(wgerBaseProvider); + return NutritionRepository(base); +}); + +/// HTTP-only data access for nutrition-related API endpoints. +/// +/// Local ingredient lookups are handled by [IngredientRepository] (PowerSync). +class NutritionRepository { + final _logger = Logger('NutritionRepository'); + final WgerBaseProvider _base; + + static const plansPath = 'nutritionplan'; + static const plansInfoPath = 'nutritionplaninfo'; + static const mealPath = 'meal'; + static const mealItemPath = 'mealitem'; + static const ingredientInfoPath = 'ingredientinfo'; + static const nutritionDiaryPath = 'nutritiondiary'; + static const ingredientWeightUnitPath = 'ingredientweightunit'; + + NutritionRepository(this._base); + + // --- Plans --- + + Future> fetchAllPlans() async { + _logger.fine('Fetching all plans (sparse)'); + return _base.fetchPaginated( + _base.makeUrl(plansPath, query: {'limit': API_MAX_PAGE_SIZE}), + ); + } + + Future> fetchPlanSparse(int planId) async { + _logger.fine('Fetching plan $planId (sparse)'); + final data = await _base.fetch(_base.makeUrl(plansPath, id: planId)); + return data as Map; + } + + Future> fetchPlanFull(int planId) async { + _logger.fine('Fetching plan $planId (full)'); + final data = await _base.fetch(_base.makeUrl(plansInfoPath, id: planId)); + return data as Map; + } + + Future> createPlan(Map data) async { + return _base.post(data, _base.makeUrl(plansPath)); + } + + Future updatePlan(int id, Map data) async { + await _base.patch(data, _base.makeUrl(plansPath, id: id)); + } + + Future deletePlan(int id) async { + return _base.deleteRequest(plansPath, id); + } + + // --- Meals --- + + Future> createMeal(Map data) async { + return _base.post(data, _base.makeUrl(mealPath)); + } + + Future> updateMeal(int id, Map data) async { + return _base.patch(data, _base.makeUrl(mealPath, id: id)); + } + + Future deleteMeal(int id) async { + return _base.deleteRequest(mealPath, id); + } + + // --- Meal items --- + + Future> createMealItem(Map data) async { + return _base.post(data, _base.makeUrl(mealItemPath)); + } + + Future deleteMealItem(int id) async { + return _base.deleteRequest(mealItemPath, id); + } + + // --- Ingredients --- + + Future fetchIngredient(int id) async { + _logger.info('Fetching ingredient $id from server'); + final data = await _base.fetch(_base.makeUrl(ingredientInfoPath, id: id)); + return Ingredient.fromJson(data); + } + + Future> searchIngredient( + String name, { + String languageCode = 'en', + IngredientSearchLanguage searchLanguage = IngredientSearchLanguage.current, + bool isVegan = false, + bool isVegetarian = false, + }) async { + if (name.length <= 1) { + return []; + } + final List languages = []; + + switch (searchLanguage) { + case IngredientSearchLanguage.current: + languages.add(languageCode); + case IngredientSearchLanguage.currentAndEnglish: + languages.add(languageCode); + if (languageCode != LANGUAGE_SHORT_ENGLISH) { + languages.add(LANGUAGE_SHORT_ENGLISH); + } + case IngredientSearchLanguage.all: + // Don't add any language code to search in all languages + break; + } + + final query = { + 'name__search': name, + 'limit': API_RESULTS_PAGE_SIZE, + }; + if (languages.isNotEmpty) { + query['language__code'] = languages.join(','); + } + if (isVegan) { + query['is_vegan'] = 'true'; + } + if (isVegetarian) { + query['is_vegetarian'] = 'true'; + } + + _logger.info('Searching ingredients from server'); + final response = await _base.fetch( + _base.makeUrl(ingredientInfoPath, query: query), + timeout: const Duration(seconds: 20), + ); + + return (response['results'] as List) + .map((data) => Ingredient.fromJson(data as Map)) + .toList(); + } + + Future searchIngredientWithBarcode(String barcode) async { + if (barcode.isEmpty) { + return null; + } + final data = await _base.fetch( + _base.makeUrl(ingredientInfoPath, query: {'code': barcode}), + ); + if (data['count'] == 0) { + return null; + } + return Ingredient.fromJson(data['results'][0]); + } + + Future> fetchWeightUnits(int ingredientId) async { + final data = await _base.fetchPaginated( + _base.makeUrl( + ingredientWeightUnitPath, + query: {'ingredient': ingredientId.toString()}, + ), + ); + return data.map((e) => IngredientWeightUnit.fromJson(e)).toList(); + } + + // --- Nutrition diary (logs) --- + + Future> fetchLogsForPlan(int planId) async { + return _base.fetchPaginated( + _base.makeUrl( + nutritionDiaryPath, + query: { + 'plan': planId.toString(), + 'limit': API_MAX_PAGE_SIZE, + 'ordering': 'datetime', + }, + ), + ); + } + + Future> createLog(Map data) async { + return _base.post(data, _base.makeUrl(nutritionDiaryPath)); + } + + Future deleteLog(int id) async { + return _base.deleteRequest(nutritionDiaryPath, id); + } +} diff --git a/lib/screens/home_tabs_screen.dart b/lib/screens/home_tabs_screen.dart index 264180824..7b4ded3e3 100644 --- a/lib/screens/home_tabs_screen.dart +++ b/lib/screens/home_tabs_screen.dart @@ -27,7 +27,7 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/auth_notifier.dart'; import 'package:wger/providers/exercise_state_notifier.dart'; import 'package:wger/providers/gallery.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/providers/routines.dart'; import 'package:wger/providers/trophies.dart'; import 'package:wger/providers/user_profile_notifier.dart'; @@ -119,7 +119,7 @@ class _HomeTabsScreenState extends ConsumerState final trophyNotifier = ref.read(trophyStateProvider.notifier); if (authState != null && !authState.dataInit) { - final nutritionPlansProvider = context.read(); + final nutritionNotifier = ref.read(nutritionProvider.notifier); final galleryProvider = context.read(); // ref.watch(routinesRiverpodProvider); @@ -135,7 +135,6 @@ class _HomeTabsScreenState extends ConsumerState await Future.wait([ authNotifier.setServerVersion(), ref.read(userProfileProvider.future), - nutritionPlansProvider.fetchIngredientsFromCache(), ]); // await ref.read(routineWeightUnitProvider.future); // await ref.read(exerciseStateReadyProvider.future); @@ -155,7 +154,7 @@ class _HomeTabsScreenState extends ConsumerState widget._logger.info('Loading routines, weight, measurements and gallery'); await Future.wait([ galleryProvider.fetchAndSetGallery(), - nutritionPlansProvider.fetchAndSetAllPlansSparse(), + nutritionNotifier.fetchAndSetAllPlansSparse(), routinesProvider.fetchAllRoutinesSparse(), trophyNotifier.fetchAll(language: languageCode), ]); @@ -163,9 +162,9 @@ class _HomeTabsScreenState extends ConsumerState // // Current nutritional plan widget._logger.info('Loading current nutritional plan'); - if (nutritionPlansProvider.currentPlan != null) { - final plan = nutritionPlansProvider.currentPlan!; - await nutritionPlansProvider.fetchAndSetPlanFull(plan.id!); + if (nutritionNotifier.currentPlan != null) { + final plan = nutritionNotifier.currentPlan!; + await nutritionNotifier.fetchAndSetPlanFull(plan.id!); } // diff --git a/lib/screens/log_meal_screen.dart b/lib/screens/log_meal_screen.dart index a333c96c0..6e98396dd 100644 --- a/lib/screens/log_meal_screen.dart +++ b/lib/screens/log_meal_screen.dart @@ -17,12 +17,12 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; -import 'package:provider/provider.dart'; import 'package:wger/helpers/json.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/meal.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/widgets/nutrition/meal.dart'; import 'package:wger/widgets/nutrition/nutrition_tiles.dart'; @@ -33,16 +33,16 @@ class LogMealArguments { const LogMealArguments(this.meal, this.popTwice); } -class LogMealScreen extends StatefulWidget { +class LogMealScreen extends ConsumerStatefulWidget { const LogMealScreen(); static const routeName = '/log-meal'; @override - State createState() => _LogMealScreenState(); + ConsumerState createState() => _LogMealScreenState(); } -class _LogMealScreenState extends State { +class _LogMealScreenState extends ConsumerState { double portionPct = 100; final _dateController = TextEditingController(text: ''); final _timeController = TextEditingController(); @@ -80,138 +80,140 @@ class _LogMealScreenState extends State { return Scaffold( appBar: AppBar(title: Text(i18n.logMeal)), - body: Consumer( - builder: (context, nutritionProvider, child) => SingleChildScrollView( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), - child: Column( - children: [ - Text( - meal.name, - style: Theme.of(context).textTheme.headlineSmall, - ), - if (meal.mealItems.isEmpty) - ListTile(title: Text(i18n.noIngredientsDefined)) - else - Column( + body: Consumer( + builder: (context, ref, child) { + ref.watch(nutritionProvider); + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), + child: Column( + children: [ + Text( + meal.name, + style: Theme.of(context).textTheme.headlineSmall, + ), + if (meal.mealItems.isEmpty) + ListTile(title: Text(i18n.noIngredientsDefined)) + else + Column( + children: [ + const DiaryheaderTile(), + ...meal.mealItems.map( + (item) => MealItemEditableFullTile(item, viewMode.withAllDetails, false), + ), + const SizedBox(height: 32), + Text( + 'Portion: ${portionPct.round()} %', + style: Theme.of(context).textTheme.bodyLarge, + ), + Slider.adaptive( + min: 0, + max: 150, + divisions: 30, + onChanged: (value) => setState(() => portionPct = value), + value: portionPct, + ), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ - const DiaryheaderTile(), - ...meal.mealItems.map( - (item) => MealItemEditableFullTile(item, viewMode.withAllDetails, false), + const Padding(padding: EdgeInsets.symmetric(horizontal: 12)), + Expanded( + child: TextFormField( + key: const ValueKey('field-date'), + readOnly: true, + decoration: InputDecoration(labelText: i18n.date), + enableInteractiveSelection: false, + controller: _dateController, + onTap: () async { + final pickedDate = await showDatePicker( + context: context, + initialDate: DateTime.now(), + firstDate: DateTime.now().subtract(const Duration(days: 3000)), + lastDate: DateTime.now(), + ); + + if (pickedDate != null) { + _dateController.text = dateFormat.format(pickedDate); + } + }, + onSaved: (newValue) { + _dateController.text = newValue!; + }, + ), ), - const SizedBox(height: 32), - Text( - 'Portion: ${portionPct.round()} %', - style: Theme.of(context).textTheme.bodyLarge, + const Padding(padding: EdgeInsets.symmetric(horizontal: 12)), + Expanded( + child: TextFormField( + key: const ValueKey('field-time'), + readOnly: true, + decoration: InputDecoration(labelText: i18n.time), + controller: _timeController, + onTap: () async { + // Open time picker + final pickedTime = await showTimePicker( + context: context, + initialTime: TimeOfDay.fromDateTime(DateTime.now()), + ); + + if (pickedTime != null) { + _timeController.text = timeToString(pickedTime)!; + } + }, + onSaved: (newValue) { + _timeController.text = newValue!; + }, + ), ), - Slider.adaptive( - min: 0, - max: 150, - divisions: 30, - onChanged: (value) => setState(() => portionPct = value), - value: portionPct, + const Padding(padding: EdgeInsets.symmetric(horizontal: 12)), + ], + ), + const Padding(padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8)), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + if (meal.mealItems.isNotEmpty) + TextButton( + child: Text(i18n.save), + onPressed: () async { + final loggedDate = dateTimeFormat.parse( + '${_dateController.text} ${_timeController.text}', + ); + await ref + .read(nutritionProvider.notifier) + .logMealToDiary(meal, loggedDate); + + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + i18n.mealLogged, + textAlign: TextAlign.center, + ), + ), + ); + + Navigator.of(context).pop(); + if (args.popTwice) { + Navigator.of(context).pop(); + } + } + }, + ), + TextButton( + child: Text( + MaterialLocalizations.of(context).cancelButtonLabel, + ), + onPressed: () => Navigator.of(context).pop(), ), ], ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - const Padding(padding: EdgeInsets.symmetric(horizontal: 12)), - Expanded( - child: TextFormField( - key: const ValueKey('field-date'), - readOnly: true, - decoration: InputDecoration(labelText: i18n.date), - enableInteractiveSelection: false, - controller: _dateController, - onTap: () async { - final pickedDate = await showDatePicker( - context: context, - initialDate: DateTime.now(), - firstDate: DateTime.now().subtract(const Duration(days: 3000)), - lastDate: DateTime.now(), - ); - - if (pickedDate != null) { - _dateController.text = dateFormat.format(pickedDate); - } - }, - onSaved: (newValue) { - _dateController.text = newValue!; - }, - ), - ), - const Padding(padding: EdgeInsets.symmetric(horizontal: 12)), - Expanded( - child: TextFormField( - key: const ValueKey('field-time'), - readOnly: true, - decoration: InputDecoration(labelText: i18n.time), - controller: _timeController, - onTap: () async { - // Open time picker - final pickedTime = await showTimePicker( - context: context, - initialTime: TimeOfDay.fromDateTime(DateTime.now()), - ); - - if (pickedTime != null) { - _timeController.text = timeToString(pickedTime)!; - } - }, - onSaved: (newValue) { - _timeController.text = newValue!; - }, - ), - ), - const Padding(padding: EdgeInsets.symmetric(horizontal: 12)), - ], - ), - const Padding(padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8)), - Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - if (meal.mealItems.isNotEmpty) - TextButton( - child: Text(i18n.save), - onPressed: () async { - final loggedDate = dateTimeFormat.parse( - '${_dateController.text} ${_timeController.text}', - ); - await Provider.of( - context, - listen: false, - ).logMealToDiary(meal, loggedDate); - - if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - i18n.mealLogged, - textAlign: TextAlign.center, - ), - ), - ); - - Navigator.of(context).pop(); - if (args.popTwice) { - Navigator.of(context).pop(); - } - } - }, - ), - TextButton( - child: Text( - MaterialLocalizations.of(context).cancelButtonLabel, - ), - onPressed: () => Navigator.of(context).pop(), - ), - ], - ), - ], + ], + ), ), - ), - ), + ); + }, ), ); } diff --git a/lib/screens/nutritional_diary_screen.dart b/lib/screens/nutritional_diary_screen.dart index 11ad28a0e..a51a247b8 100644 --- a/lib/screens/nutritional_diary_screen.dart +++ b/lib/screens/nutritional_diary_screen.dart @@ -17,11 +17,11 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; -import 'package:provider/provider.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/widgets/nutrition/nutritional_diary_detail.dart'; /// Arguments passed to the form screen @@ -48,13 +48,16 @@ class NutritionalDiaryScreen extends StatelessWidget { title: Text(DateFormat.yMd(Localizations.localeOf(context).languageCode).format(args.date)), ), body: WidescreenWrapper( - child: Consumer( - builder: (context, nutritionProvider, child) => SingleChildScrollView( - child: Padding( - padding: const EdgeInsets.all(8.0), - child: NutritionalDiaryDetailWidget(args.plan, args.date), - ), - ), + child: Consumer( + builder: (context, ref, child) { + ref.watch(nutritionProvider); + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(8.0), + child: NutritionalDiaryDetailWidget(args.plan, args.date), + ), + ); + }, ), ), ); diff --git a/lib/screens/nutritional_plan_screen.dart b/lib/screens/nutritional_plan_screen.dart index 980243ec5..3d43773c7 100644 --- a/lib/screens/nutritional_plan_screen.dart +++ b/lib/screens/nutritional_plan_screen.dart @@ -17,11 +17,11 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg_icons/flutter_svg_icons.dart'; -import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/log_meals_screen.dart'; import 'package:wger/widgets/core/progress_indicator.dart'; @@ -33,16 +33,16 @@ enum NutritionalPlanOptions { delete, } -class NutritionalPlanScreen extends StatefulWidget { +class NutritionalPlanScreen extends ConsumerStatefulWidget { const NutritionalPlanScreen(); static const routeName = '/nutritional-plan-detail'; @override - State createState() => _NutritionalPlanScreenState(); + ConsumerState createState() => _NutritionalPlanScreenState(); } -class _NutritionalPlanScreenState extends State { +class _NutritionalPlanScreenState extends ConsumerState { Future? _planFuture; late NutritionalPlan _nutritionalPlan; @@ -51,10 +51,7 @@ class _NutritionalPlanScreenState extends State { super.didChangeDependencies(); if (_planFuture == null) { _nutritionalPlan = ModalRoute.of(context)!.settings.arguments as NutritionalPlan; - _planFuture = Provider.of( - context, - listen: false, - ).fetchAndSetPlanFull(_nutritionalPlan.id!); + _planFuture = ref.read(nutritionProvider.notifier).fetchAndSetPlanFull(_nutritionalPlan.id!); } } @@ -141,10 +138,7 @@ class _NutritionalPlanScreenState extends State { ); break; case NutritionalPlanOptions.delete: - Provider.of( - context, - listen: false, - ).deletePlan(_nutritionalPlan.id!); + ref.read(nutritionProvider.notifier).deletePlan(_nutritionalPlan.id!); Navigator.of(context).pop(); break; } @@ -189,9 +183,11 @@ class _NutritionalPlanScreenState extends State { ], ), ) - : Consumer( - builder: (context, value, child) => - NutritionalPlanDetailWidget(_nutritionalPlan), + : Consumer( + builder: (context, ref, child) { + ref.watch(nutritionProvider); + return NutritionalPlanDetailWidget(_nutritionalPlan); + }, ), ), ], diff --git a/lib/screens/nutritional_plans_screen.dart b/lib/screens/nutritional_plans_screen.dart index d070b1c0c..b84b665ce 100644 --- a/lib/screens/nutritional_plans_screen.dart +++ b/lib/screens/nutritional_plans_screen.dart @@ -17,10 +17,8 @@ */ import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/providers/nutrition.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/core/app_bar.dart'; import 'package:wger/widgets/nutrition/forms.dart'; @@ -49,11 +47,7 @@ class NutritionalPlansScreen extends StatelessWidget { ); }, ), - body: WidescreenWrapper( - child: Consumer( - builder: (context, nutritionProvider, child) => NutritionalPlansList(nutritionProvider), - ), - ), + body: const WidescreenWrapper(child: NutritionalPlansList()), ); } } diff --git a/lib/widgets/core/app_bar.dart b/lib/widgets/core/app_bar.dart index 3acb2de12..783bd9d76 100644 --- a/lib/widgets/core/app_bar.dart +++ b/lib/widgets/core/app_bar.dart @@ -24,7 +24,7 @@ import 'package:wger/database/powersync/powersync.dart' show syncStatus; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/auth_notifier.dart'; import 'package:wger/providers/gallery.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/providers/user_profile_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/settings_dashboard_widgets_screen.dart'; @@ -156,7 +156,7 @@ class MainSettingsDialog extends ConsumerWidget { onTap: () { ref.read(authProvider.notifier).logout(); // context.read().clear(); - context.read().clear(); + ref.read(nutritionProvider.notifier).clear(); // context.read().clear(); context.read().clear(); ref.read(userProfileProvider.notifier).clear(); diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index ed0ee757a..4821713ff 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -20,7 +20,6 @@ import 'package:flutter/material.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/screens/settings_plates_screen.dart'; -import 'package:wger/widgets/core/settings/ingredient_cache.dart'; import 'package:wger/widgets/core/settings/theme.dart'; class SettingsPage extends StatelessWidget { @@ -37,13 +36,6 @@ class SettingsPage extends StatelessWidget { body: WidescreenWrapper( child: ListView( children: [ - ListTile( - title: Text( - i18n.settingsCacheTitle, - style: Theme.of(context).textTheme.headlineSmall, - ), - ), - const SettingsIngredientCache(), ListTile(title: Text(i18n.others, style: Theme.of(context).textTheme.headlineSmall)), const SettingsTheme(), ListTile( diff --git a/lib/widgets/core/settings/ingredient_cache.dart b/lib/widgets/core/settings/ingredient_cache.dart deleted file mode 100644 index c183fd979..000000000 --- a/lib/widgets/core/settings/ingredient_cache.dart +++ /dev/null @@ -1,32 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; -import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/providers/nutrition.dart'; - -class SettingsIngredientCache extends StatelessWidget { - const SettingsIngredientCache({super.key}); - - @override - Widget build(BuildContext context) { - final i18n = AppLocalizations.of(context); - final nutritionProvider = Provider.of(context, listen: false); - - return ListTile( - title: Text(i18n.settingsIngredientCacheDescription), - subtitle: Text('${nutritionProvider.ingredients.length} cached ingredients'), - trailing: IconButton( - key: const ValueKey('cacheIconIngredients'), - icon: const Icon(Icons.delete), - onPressed: () async { - await nutritionProvider.clearIngredientCache(); - - if (context.mounted) { - final snackBar = SnackBar(content: Text(i18n.settingsCacheDeletedSnackbar)); - - ScaffoldMessenger.of(context).showSnackBar(snackBar); - } - }, - ), - ); - } -} diff --git a/lib/widgets/dashboard/calendar.dart b/lib/widgets/dashboard/calendar.dart index 6703e65ee..63c08b36a 100644 --- a/lib/widgets/dashboard/calendar.dart +++ b/lib/widgets/dashboard/calendar.dart @@ -19,7 +19,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; import 'package:intl/intl.dart'; -import 'package:provider/provider.dart'; import 'package:table_calendar/table_calendar.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/date.dart'; @@ -29,7 +28,7 @@ import 'package:wger/models/body_weight/weight_entry.dart'; import 'package:wger/models/measurements/measurement_category.dart'; import 'package:wger/providers/body_weight.dart'; import 'package:wger/providers/measurement_notifier.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/providers/routines.dart'; import 'package:wger/theme/theme.dart'; @@ -99,7 +98,7 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState(); - for (final plan in nutritionProvider.items) { + final plans = ref.read(nutritionProvider).value ?? const []; + for (final plan in plans) { for (final entry in plan.logEntriesValues.entries) { final date = DateFormatLists.format(entry.key); if (!newEvents.containsKey(date)) { diff --git a/lib/widgets/dashboard/widgets/nutrition.dart b/lib/widgets/dashboard/widgets/nutrition.dart index 08f875c83..3b0df8603 100644 --- a/lib/widgets/dashboard/widgets/nutrition.dart +++ b/lib/widgets/dashboard/widgets/nutrition.dart @@ -17,12 +17,12 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg_icons/flutter_svg_icons.dart'; import 'package:intl/intl.dart'; -import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/log_meals_screen.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; @@ -30,21 +30,21 @@ import 'package:wger/widgets/dashboard/widgets/nothing_found.dart'; import 'package:wger/widgets/nutrition/charts.dart'; import 'package:wger/widgets/nutrition/forms.dart'; -class DashboardNutritionWidget extends StatefulWidget { +class DashboardNutritionWidget extends ConsumerStatefulWidget { const DashboardNutritionWidget(); @override - _DashboardNutritionWidgetState createState() => _DashboardNutritionWidgetState(); + ConsumerState createState() => _DashboardNutritionWidgetState(); } -class _DashboardNutritionWidgetState extends State { +class _DashboardNutritionWidgetState extends ConsumerState { NutritionalPlan? _plan; bool _hasContent = false; @override void initState() { super.initState(); - _plan = Provider.of(context, listen: false).currentPlan; + _plan = ref.read(nutritionProvider.notifier).currentPlan; _hasContent = _plan != null; } diff --git a/lib/widgets/measurements/entries.dart b/lib/widgets/measurements/entries.dart index f788f9d98..c6b0f6827 100644 --- a/lib/widgets/measurements/entries.dart +++ b/lib/widgets/measurements/entries.dart @@ -19,11 +19,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; -import 'package:provider/provider.dart' as legacy_provider; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/measurements/measurement_category.dart'; import 'package:wger/providers/measurement_notifier.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/measurements/charts.dart'; import 'package:wger/widgets/measurements/helpers.dart'; @@ -37,7 +36,7 @@ class EntriesList extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final plans = legacy_provider.Provider.of(context, listen: false).items; + final plans = ref.watch(nutritionProvider).value ?? const []; final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); final provider = ref.read(measurementProvider.notifier); diff --git a/lib/widgets/nutrition/forms.dart b/lib/widgets/nutrition/forms.dart index 4921525b9..a6b42617e 100644 --- a/lib/widgets/nutrition/forms.dart +++ b/lib/widgets/nutrition/forms.dart @@ -17,8 +17,8 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; -import 'package:provider/provider.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/json.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -28,13 +28,13 @@ import 'package:wger/models/nutrition/log.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import 'package:wger/widgets/nutrition/helpers.dart'; import 'package:wger/widgets/nutrition/nutrition_tiles.dart'; import 'package:wger/widgets/nutrition/widgets.dart'; -class MealForm extends StatelessWidget { +class MealForm extends ConsumerWidget { late final Meal _meal; final int _planId; @@ -49,7 +49,7 @@ class MealForm extends StatelessWidget { } @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { return Container( margin: const EdgeInsets.all(20), child: Form( @@ -95,15 +95,8 @@ class MealForm extends StatelessWidget { } _form.currentState!.save(); - _meal.id == null - ? Provider.of( - context, - listen: false, - ).addMeal(_meal, _planId) - : Provider.of( - context, - listen: false, - ).editMeal(_meal); + final notifier = ref.read(nutritionProvider.notifier); + _meal.id == null ? notifier.addMeal(_meal, _planId) : notifier.editMeal(_meal); Navigator.of(context).pop(); }, @@ -124,9 +117,9 @@ Widget getMealItemForm( return IngredientForm( // TODO we use planId 0 here cause we don't have one and we don't need it I think? recent: recent.map((e) => Log.fromMealItem(e, 0, e.mealId)).toList(), - onSave: (BuildContext context, MealItem mealItem, DateTime? dt) { + onSave: (BuildContext context, WidgetRef ref, MealItem mealItem, DateTime? dt) { mealItem.mealId = meal.id!; - Provider.of(context, listen: false).addMealItem(mealItem, meal); + ref.read(nutritionProvider.notifier).addMealItem(mealItem, meal); }, barcode: barcode ?? '', test: test ?? false, @@ -137,11 +130,8 @@ Widget getMealItemForm( Widget getIngredientLogForm(NutritionalPlan plan) { return IngredientForm( recent: plan.dedupDiaryEntries, - onSave: (BuildContext context, MealItem mealItem, DateTime? dt) { - Provider.of( - context, - listen: false, - ).logIngredientToDiary(mealItem, plan.id!, dt); + onSave: (BuildContext context, WidgetRef ref, MealItem mealItem, DateTime? dt) { + ref.read(nutritionProvider.notifier).logIngredientToDiary(mealItem, plan.id!, dt); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( @@ -157,8 +147,8 @@ Widget getIngredientLogForm(NutritionalPlan plan) { /// IngredientForm is a form that lets the user pick an ingredient (and amount) to /// log to the diary or to add to a meal. -class IngredientForm extends StatefulWidget { - final Function(BuildContext context, MealItem mealItem, DateTime? dt) onSave; +class IngredientForm extends ConsumerStatefulWidget { + final Function(BuildContext context, WidgetRef ref, MealItem mealItem, DateTime? dt) onSave; final List recent; final bool withDate; final String barcode; @@ -173,10 +163,10 @@ class IngredientForm extends StatefulWidget { }); @override - State createState() => IngredientFormState(); + ConsumerState createState() => IngredientFormState(); } -class IngredientFormState extends State { +class IngredientFormState extends ConsumerState { final _form = GlobalKey(); final _ingredientController = TextEditingController(); final _ingredientIdController = TextEditingController(); @@ -217,7 +207,7 @@ class IngredientFormState extends State { }); // Load weight units for this ingredient - Provider.of(context, listen: false).fetchWeightUnits(id).then((units) { + ref.read(nutritionProvider.notifier).fetchWeightUnits(id).then((units) { setState(() { _weightUnits = units; }); @@ -416,10 +406,9 @@ class IngredientFormState extends State { style: Theme.of(context).textTheme.titleMedium, ), FutureBuilder( - future: Provider.of( - context, - listen: false, - ).fetchIngredient(_mealItem.ingredientId), + future: ref + .read(nutritionProvider.notifier) + .fetchIngredient(_mealItem.ingredientId), builder: ( BuildContext context, @@ -463,7 +452,7 @@ class IngredientFormState extends State { final loggedDate = dateTimeFormat.parse( '${_dateController.text} ${_timeController.text}', ); - widget.onSave(context, _mealItem, loggedDate); + widget.onSave(context, ref, _mealItem, loggedDate); Navigator.of(context).pop(); }, @@ -509,6 +498,7 @@ class IngredientFormState extends State { onPressed: () { showIngredientDetails( context, + ref, suggestions[index].ingredient.id, select: select, ); @@ -552,7 +542,7 @@ enum GoalType { } } -class PlanForm extends StatefulWidget { +class PlanForm extends ConsumerStatefulWidget { late NutritionalPlan _plan; PlanForm([NutritionalPlan? plan]) { @@ -560,10 +550,10 @@ class PlanForm extends StatefulWidget { } @override - State createState() => _PlanFormState(); + ConsumerState createState() => _PlanFormState(); } -class _PlanFormState extends State { +class _PlanFormState extends ConsumerState { final _form = GlobalKey(); GoalType _goalType = GoalType.meals; @@ -805,19 +795,14 @@ class _PlanFormState extends State { _form.currentState!.save(); // Save to DB + final notifier = ref.read(nutritionProvider.notifier); if (widget._plan.id != null) { - await Provider.of( - context, - listen: false, - ).editPlan(widget._plan); + await notifier.editPlan(widget._plan); if (context.mounted) { Navigator.of(context).pop(); } } else { - widget._plan = await Provider.of( - context, - listen: false, - ).addPlan(widget._plan); + widget._plan = await notifier.addPlan(widget._plan); if (context.mounted) { Navigator.of(context).pushReplacementNamed( NutritionalPlanScreen.routeName, diff --git a/lib/widgets/nutrition/helpers.dart b/lib/widgets/nutrition/helpers.dart index 95cd543a4..656f6c26c 100644 --- a/lib/widgets/nutrition/helpers.dart +++ b/lib/widgets/nutrition/helpers.dart @@ -17,12 +17,12 @@ */ import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/ingredient.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/nutritional_values.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/widgets/core/core.dart'; import 'package:wger/widgets/nutrition/ingredient_dialogs.dart'; @@ -103,11 +103,16 @@ String getKcalConsumedVsPlanned(Meal meal, BuildContext context) { return '${consumed.toStringAsFixed(0)} / ${planned.toStringAsFixed(0)} ${loc.kcal}'; } -void showIngredientDetails(BuildContext context, int id, {void Function()? select}) { +void showIngredientDetails( + BuildContext context, + WidgetRef ref, + int id, { + void Function()? select, +}) { showDialog( context: context, builder: (context) => FutureBuilder( - future: Provider.of(context, listen: false).fetchIngredient(id), + future: ref.read(nutritionProvider.notifier).fetchIngredient(id), builder: (BuildContext context, AsyncSnapshot snapshot) { return IngredientDetails(snapshot, onSelect: select); }, diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index f155975ca..9f501d35f 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -17,13 +17,13 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg_icons/flutter_svg_icons.dart'; -import 'package:provider/provider.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/log_meal_screen.dart'; import 'package:wger/widgets/nutrition/charts.dart'; @@ -39,7 +39,7 @@ enum viewMode { withAllDetails, // + nutritional breakdown of ingredients, + logged today } -class MealWidget extends StatefulWidget { +class MealWidget extends ConsumerStatefulWidget { final Meal _meal; final List _recentMealItems; final bool popTwice; @@ -53,10 +53,10 @@ class MealWidget extends StatefulWidget { ); @override - _MealWidgetState createState() => _MealWidgetState(); + ConsumerState createState() => _MealWidgetState(); } -class _MealWidgetState extends State { +class _MealWidgetState extends ConsumerState { var _viewMode = viewMode.base; bool _editing = false; @@ -139,10 +139,7 @@ class _MealWidgetState extends State { TextButton.icon( onPressed: () { // Delete the meal - Provider.of( - context, - listen: false, - ).deleteMeal(widget._meal); + ref.read(nutritionProvider.notifier).deleteMeal(widget._meal); // and inform the user ScaffoldMessenger.of(context).showSnackBar( @@ -220,7 +217,7 @@ class _MealWidgetState extends State { } /// An editable NutritionTile showing the avatar, name, nutritional values -class MealItemEditableFullTile extends StatelessWidget { +class MealItemEditableFullTile extends ConsumerWidget { final bool _editing; final viewMode _viewMode; final MealItem _item; @@ -228,7 +225,7 @@ class MealItemEditableFullTile extends StatelessWidget { const MealItemEditableFullTile(this._item, this._viewMode, this._editing); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { final values = _item.nutritionalValues; final i18n = AppLocalizations.of(context); @@ -253,7 +250,7 @@ class MealItemEditableFullTile extends StatelessWidget { iconSize: ICON_SIZE_SMALL, onPressed: () { // Delete the meal item - Provider.of(context, listen: false).deleteMealItem(_item); + ref.read(nutritionProvider.notifier).deleteMealItem(_item); // and inform the user ScaffoldMessenger.of(context).showSnackBar( diff --git a/lib/widgets/nutrition/nutrition_tiles.dart b/lib/widgets/nutrition/nutrition_tiles.dart index a9ea2d3a3..94d578718 100644 --- a/lib/widgets/nutrition/nutrition_tiles.dart +++ b/lib/widgets/nutrition/nutrition_tiles.dart @@ -1,20 +1,20 @@ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; -import 'package:provider/provider.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/ingredient.dart'; import 'package:wger/models/nutrition/log.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; import 'package:wger/models/nutrition/nutritional_values.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/widgets/nutrition/helpers.dart'; import 'package:wger/widgets/nutrition/nutrition_tile.dart'; import 'package:wger/widgets/nutrition/widgets.dart'; /// a NutritionTitle showing an ingredient, with its /// avatar, nutritional values and button to popup its details -class MealItemValuesTile extends StatelessWidget { +class MealItemValuesTile extends ConsumerWidget { final Ingredient ingredient; final NutritionalValues nutritionalValues; @@ -25,14 +25,14 @@ class MealItemValuesTile extends StatelessWidget { }); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { return NutritionTile( leading: IngredientAvatar(ingredient: ingredient), title: Text(getShortNutritionValues(nutritionalValues, context)), trailing: IconButton( icon: const Icon(Icons.info_outline), onPressed: () { - showIngredientDetails(context, ingredient.id); + showIngredientDetails(context, ref, ingredient.id); }, ), ); @@ -52,7 +52,7 @@ class DiaryheaderTile extends StatelessWidget { } /// a NutritionTitle showing diary entries -class DiaryEntryTile extends StatelessWidget { +class DiaryEntryTile extends ConsumerWidget { const DiaryEntryTile({ super.key, required this.diaryEntry, @@ -63,7 +63,7 @@ class DiaryEntryTile extends StatelessWidget { final NutritionalPlan? nutritionalPlan; @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { return NutritionTile( leading: Text( DateFormat.Hm(Localizations.localeOf(context).languageCode).format(diaryEntry.datetime), @@ -84,10 +84,9 @@ class DiaryEntryTile extends StatelessWidget { : IconButton( tooltip: AppLocalizations.of(context).delete, onPressed: () { - Provider.of( - context, - listen: false, - ).deleteLog(diaryEntry.id!, nutritionalPlan!.id!); + ref + .read(nutritionProvider.notifier) + .deleteLog(diaryEntry.id!, nutritionalPlan!.id!); }, icon: const Icon(Icons.delete_outline), iconSize: ICON_SIZE_SMALL, diff --git a/lib/widgets/nutrition/nutritional_plans_list.dart b/lib/widgets/nutrition/nutritional_plans_list.dart index d4d81c316..d66273f2e 100644 --- a/lib/widgets/nutrition/nutritional_plans_list.dart +++ b/lib/widgets/nutrition/nutritional_plans_list.dart @@ -22,16 +22,14 @@ import 'package:intl/intl.dart'; import 'package:wger/helpers/measurements.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/body_weight.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/providers/user_profile_notifier.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import 'package:wger/widgets/core/text_prompt.dart'; import 'package:wger/widgets/measurements/charts.dart'; class NutritionalPlansList extends riverpod.ConsumerWidget { - final NutritionPlansProvider _nutritionProvider; - - const NutritionalPlansList(this._nutritionProvider); + const NutritionalPlansList({super.key}); /// Builds the weight change information for a nutritional plan period Widget _buildWeightChangeInfo( @@ -93,15 +91,18 @@ class NutritionalPlansList extends riverpod.ConsumerWidget { @override Widget build(BuildContext context, riverpod.WidgetRef ref) { + final plans = ref.watch(nutritionProvider).value ?? const []; + final notifier = ref.read(nutritionProvider.notifier); + return RefreshIndicator( - onRefresh: () => _nutritionProvider.fetchAndSetAllPlansSparse(), - child: _nutritionProvider.items.isEmpty + onRefresh: () => notifier.fetchAndSetAllPlansSparse(), + child: plans.isEmpty ? const TextPrompt() : ListView.builder( padding: const EdgeInsets.all(10.0), - itemCount: _nutritionProvider.items.length, + itemCount: plans.length, itemBuilder: (context, index) { - final currentPlan = _nutritionProvider.items[index]; + final currentPlan = plans[index]; return Card( child: ListTile( onTap: () { @@ -167,7 +168,7 @@ class NutritionalPlansList extends riverpod.ConsumerWidget { ), onPressed: () { // Confirmed, delete the plan - _nutritionProvider.deletePlan(currentPlan.id!); + notifier.deletePlan(currentPlan.id!); // Close the popup Navigator.of(contextDialog).pop(); diff --git a/lib/widgets/nutrition/widgets.dart b/lib/widgets/nutrition/widgets.dart index 446614da0..a8df9af1f 100644 --- a/lib/widgets/nutrition/widgets.dart +++ b/lib/widgets/nutrition/widgets.dart @@ -23,14 +23,14 @@ import 'package:flutter_typeahead/flutter_typeahead.dart'; import 'package:flutter_zxing/flutter_zxing.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:logging/logging.dart'; -import 'package:provider/provider.dart' as legacy_provider; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/misc.dart'; import 'package:wger/helpers/platform.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/ingredient.dart'; -import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/nutrition_ingredient_filters_riverpod.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/widgets/core/core.dart'; import 'package:wger/widgets/nutrition/helpers.dart'; import 'package:wger/widgets/nutrition/ingredient_dialogs.dart'; @@ -154,16 +154,15 @@ class _IngredientTypeaheadState extends ConsumerState { widget.onUpdateSearchQuery(pattern); widget.onDeselectIngredient(); - return legacy_provider.Provider.of( - context, - listen: false, - ).searchIngredient( - pattern, - languageCode: Localizations.localeOf(context).languageCode, - searchLanguage: filters.searchLanguage, - isVegan: filters.isVegan, - isVegetarian: filters.isVegetarian, - ); + return ref + .read(nutritionProvider.notifier) + .searchIngredient( + pattern, + languageCode: Localizations.localeOf(context).languageCode, + searchLanguage: filters.searchLanguage, + isVegan: filters.isVegan, + isVegetarian: filters.isVegetarian, + ); }, itemBuilder: (context, ingredient) { final i18n = AppLocalizations.of(context); @@ -220,6 +219,7 @@ class _IngredientTypeaheadState extends ConsumerState { onPressed: () { showIngredientDetails( context, + ref, ingredient.id, select: () { widget.selectIngredient(ingredient.id, ingredient.name, null); @@ -234,12 +234,6 @@ class _IngredientTypeaheadState extends ConsumerState { child: child, ), onSelected: (suggestion) async { - // Cache selected ingredient - final provider = legacy_provider.Provider.of( - context, - listen: false, - ); - await provider.cacheIngredient(suggestion); widget.selectIngredient(suggestion.id, suggestion.name, null); }, ), @@ -262,10 +256,7 @@ class _IngredientTypeaheadState extends ConsumerState { showDialog( context: context, builder: (context) => FutureBuilder( - future: legacy_provider.Provider.of( - context, - listen: false, - ).searchIngredientWithBarcode(barcode), + future: ref.read(nutritionProvider.notifier).searchIngredientWithBarcode(barcode), builder: (BuildContext context, AsyncSnapshot snapshot) { return IngredientScanResultDialog(snapshot, barcode, widget.selectIngredient); }, diff --git a/lib/widgets/weight/weight_overview.dart b/lib/widgets/weight/weight_overview.dart index e2f8cc1ed..1993b46ff 100644 --- a/lib/widgets/weight/weight_overview.dart +++ b/lib/widgets/weight/weight_overview.dart @@ -19,10 +19,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; import 'package:intl/intl.dart'; -import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/body_weight.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; import 'package:wger/providers/user_profile_notifier.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/widgets/core/error.dart'; @@ -38,7 +37,7 @@ class WeightOverview extends riverpod.ConsumerWidget { Widget build(BuildContext context, riverpod.WidgetRef ref) { final profile = ref.read(userProfileProvider).value; final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); - final plans = context.read().items; + final plans = ref.watch(nutritionProvider).value ?? const []; final entries = ref.watch(weightEntryProvider); return entries.when( diff --git a/pubspec.lock b/pubspec.lock index e38009ac0..eed2a9539 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -591,14 +591,6 @@ packages: description: flutter source: sdk version: "0.0.0" - get_it: - dependency: "direct main" - description: - name: get_it - sha256: ae78de7c3f2304b8d81f2bb6e320833e5e81de942188542328f074978cc0efa9 - url: "https://pub.dev" - source: hosted - version: "8.3.0" glob: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index b972aab96..ac49e7b39 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -48,7 +48,6 @@ dependencies: flutter_zxing: ^2.2.1 font_awesome_flutter: ^11.0.0 freezed_annotation: ^3.0.0 - get_it: ^8.3.0 http: ^1.6.0 image_picker: ^1.2.1 intl: ^0.20.0 diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index 07a81865f..cc1752f60 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -21,23 +21,18 @@ import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/app_settings_notifier.dart'; -import 'package:wger/providers/nutrition.dart'; import 'package:wger/widgets/core/settings.dart'; -import '../../test_data/nutritional_plans.dart'; import 'settings_test.mocks.dart'; @GenerateMocks([ - NutritionPlansProvider, SharedPreferencesAsync, ]) void main() { - final mockNutritionProvider = MockNutritionPlansProvider(); final mockSharedPreferences = MockSharedPreferencesAsync(); setUp(() { @@ -49,7 +44,6 @@ void main() { when( mockSharedPreferences.remove(any), ).thenAnswer((_) async {}); - when(mockNutritionProvider.ingredients).thenReturn([ingredient1, ingredient2]); }); Widget createSettingsScreen({locale = 'en'}) { @@ -57,32 +51,15 @@ void main() { overrides: [ appSettingsPrefsProvider.overrideWithValue(mockSharedPreferences), ], - child: MultiProvider( - providers: [ - ChangeNotifierProvider( - create: (context) => mockNutritionProvider, - ), - ], - child: MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: const SettingsPage(), - ), + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const SettingsPage(), ), ); } - group('Cache', () { - testWidgets('Test resetting the ingredient cache', (WidgetTester tester) async { - await tester.pumpWidget(createSettingsScreen()); - await tester.tap(find.byKey(const ValueKey('cacheIconIngredients'))); - await tester.pumpAndSettle(); - - verify(mockNutritionProvider.clearIngredientCache()); - }); - }); - group('Theme settings (AppSettingsNotifier)', () { test('default theme is system', () async { when( diff --git a/test/core/settings_test.mocks.dart b/test/core/settings_test.mocks.dart index aaf39f2ef..72b1f8d84 100644 --- a/test/core/settings_test.mocks.dart +++ b/test/core/settings_test.mocks.dart @@ -3,19 +3,10 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i9; -import 'dart:ui' as _i11; +import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; -import 'package:shared_preferences/src/shared_preferences_async.dart' as _i12; -import 'package:wger/database/ingredients/ingredients_database.dart' as _i3; -import 'package:wger/models/nutrition/ingredient.dart' as _i7; -import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i10; -import 'package:wger/models/nutrition/meal.dart' as _i5; -import 'package:wger/models/nutrition/meal_item.dart' as _i6; -import 'package:wger/models/nutrition/nutritional_plan.dart' as _i4; -import 'package:wger/providers/base_provider.dart' as _i2; -import 'package:wger/providers/nutrition.dart' as _i8; +import 'package:shared_preferences/src/shared_preferences_async.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -32,552 +23,141 @@ import 'package:wger/providers/nutrition.dart' as _i8; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeIngredientDatabase_1 extends _i1.SmartFake implements _i3.IngredientDatabase { - _FakeIngredientDatabase_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeNutritionalPlan_2 extends _i1.SmartFake implements _i4.NutritionalPlan { - _FakeNutritionalPlan_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeMeal_3 extends _i1.SmartFake implements _i5.Meal { - _FakeMeal_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeMealItem_4 extends _i1.SmartFake implements _i6.MealItem { - _FakeMealItem_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeIngredient_5 extends _i1.SmartFake implements _i7.Ingredient { - _FakeIngredient_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -/// A class which mocks [NutritionPlansProvider]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockNutritionPlansProvider extends _i1.Mock implements _i8.NutritionPlansProvider { - MockNutritionPlansProvider() { - _i1.throwOnMissingStub(this); - } - - @override - _i2.WgerBaseProvider get baseProvider => - (super.noSuchMethod( - Invocation.getter(#baseProvider), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#baseProvider), - ), - ) - as _i2.WgerBaseProvider); - - @override - _i3.IngredientDatabase get database => - (super.noSuchMethod( - Invocation.getter(#database), - returnValue: _FakeIngredientDatabase_1( - this, - Invocation.getter(#database), - ), - ) - as _i3.IngredientDatabase); - - @override - List<_i7.Ingredient> get ingredients => - (super.noSuchMethod( - Invocation.getter(#ingredients), - returnValue: <_i7.Ingredient>[], - ) - as List<_i7.Ingredient>); - - @override - List<_i4.NutritionalPlan> get items => - (super.noSuchMethod( - Invocation.getter(#items), - returnValue: <_i4.NutritionalPlan>[], - ) - as List<_i4.NutritionalPlan>); - - @override - set database(_i3.IngredientDatabase? value) => super.noSuchMethod( - Invocation.setter(#database, value), - returnValueForMissingStub: null, - ); - - @override - set ingredients(List<_i7.Ingredient>? value) => super.noSuchMethod( - Invocation.setter(#ingredients, value), - returnValueForMissingStub: null, - ); - - @override - bool get hasListeners => - (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); - - @override - void clear() => super.noSuchMethod( - Invocation.method(#clear, []), - returnValueForMissingStub: null, - ); - - @override - _i4.NutritionalPlan findById(int? id) => - (super.noSuchMethod( - Invocation.method(#findById, [id]), - returnValue: _FakeNutritionalPlan_2( - this, - Invocation.method(#findById, [id]), - ), - ) - as _i4.NutritionalPlan); - - @override - _i5.Meal? findMealById(int? id) => - (super.noSuchMethod(Invocation.method(#findMealById, [id])) as _i5.Meal?); - - @override - _i9.Future fetchAndSetAllPlansSparse() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansSparse, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future fetchAndSetAllPlansFull() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansFull, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanSparse, [planId]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanSparse, [planId]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanFull, [planId]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanFull, [planId]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future<_i4.NutritionalPlan> addPlan(_i4.NutritionalPlan? planData) => - (super.noSuchMethod( - Invocation.method(#addPlan, [planData]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#addPlan, [planData]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future editPlan(_i4.NutritionalPlan? plan) => - (super.noSuchMethod( - Invocation.method(#editPlan, [plan]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future deletePlan(int? id) => - (super.noSuchMethod( - Invocation.method(#deletePlan, [id]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i5.Meal> addMeal(_i5.Meal? meal, int? planId) => - (super.noSuchMethod( - Invocation.method(#addMeal, [meal, planId]), - returnValue: _i9.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#addMeal, [meal, planId])), - ), - ) - as _i9.Future<_i5.Meal>); - - @override - _i9.Future<_i5.Meal> editMeal(_i5.Meal? meal) => - (super.noSuchMethod( - Invocation.method(#editMeal, [meal]), - returnValue: _i9.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#editMeal, [meal])), - ), - ) - as _i9.Future<_i5.Meal>); - - @override - _i9.Future deleteMeal(_i5.Meal? meal) => - (super.noSuchMethod( - Invocation.method(#deleteMeal, [meal]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i6.MealItem> addMealItem( - _i6.MealItem? mealItem, - _i5.Meal? meal, - ) => - (super.noSuchMethod( - Invocation.method(#addMealItem, [mealItem, meal]), - returnValue: _i9.Future<_i6.MealItem>.value( - _FakeMealItem_4( - this, - Invocation.method(#addMealItem, [mealItem, meal]), - ), - ), - ) - as _i9.Future<_i6.MealItem>); - - @override - _i9.Future deleteMealItem(_i6.MealItem? mealItem) => - (super.noSuchMethod( - Invocation.method(#deleteMealItem, [mealItem]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future clearIngredientCache() => - (super.noSuchMethod( - Invocation.method(#clearIngredientCache, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future cacheIngredient( - _i7.Ingredient? ingredient, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #cacheIngredient, - [ingredient], - {#database: database}, - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i7.Ingredient> fetchIngredient( - int? ingredientId, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - returnValue: _i9.Future<_i7.Ingredient>.value( - _FakeIngredient_5( - this, - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - ), - ), - ) - as _i9.Future<_i7.Ingredient>); - - @override - _i9.Future> fetchWeightUnits( - int? ingredientId, - ) => - (super.noSuchMethod( - Invocation.method(#fetchWeightUnits, [ingredientId]), - returnValue: _i9.Future>.value( - <_i10.IngredientWeightUnit>[], - ), - ) - as _i9.Future>); - - @override - _i9.Future fetchIngredientsFromCache() => - (super.noSuchMethod( - Invocation.method(#fetchIngredientsFromCache, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future> searchIngredient( - String? name, { - String? languageCode = 'en', - _i8.IngredientSearchLanguage? searchLanguage = _i8.IngredientSearchLanguage.current, - bool? isVegan = false, - bool? isVegetarian = false, - }) => - (super.noSuchMethod( - Invocation.method( - #searchIngredient, - [name], - { - #languageCode: languageCode, - #searchLanguage: searchLanguage, - #isVegan: isVegan, - #isVegetarian: isVegetarian, - }, - ), - returnValue: _i9.Future>.value( - <_i7.Ingredient>[], - ), - ) - as _i9.Future>); - - @override - _i9.Future<_i7.Ingredient?> searchIngredientWithBarcode(String? barcode) => - (super.noSuchMethod( - Invocation.method(#searchIngredientWithBarcode, [barcode]), - returnValue: _i9.Future<_i7.Ingredient?>.value(), - ) - as _i9.Future<_i7.Ingredient?>); - - @override - _i9.Future logMealToDiary(_i5.Meal? meal, DateTime? mealDateTime) => - (super.noSuchMethod( - Invocation.method(#logMealToDiary, [meal, mealDateTime]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future logIngredientToDiary( - _i6.MealItem? mealItem, - int? planId, [ - DateTime? dateTime, - ]) => - (super.noSuchMethod( - Invocation.method(#logIngredientToDiary, [ - mealItem, - planId, - dateTime, - ]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future deleteLog(int? logId, int? planId) => - (super.noSuchMethod( - Invocation.method(#deleteLog, [logId, planId]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future fetchAndSetLogs(_i4.NutritionalPlan? plan) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetLogs, [plan]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - void addListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#addListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void removeListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#removeListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); - - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method(#notifyListeners, []), - returnValueForMissingStub: null, - ); -} - /// A class which mocks [SharedPreferencesAsync]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable -class MockSharedPreferencesAsync extends _i1.Mock implements _i12.SharedPreferencesAsync { +class MockSharedPreferencesAsync extends _i1.Mock implements _i2.SharedPreferencesAsync { MockSharedPreferencesAsync() { _i1.throwOnMissingStub(this); } @override - _i9.Future> getKeys({Set? allowList}) => + _i3.Future> getKeys({Set? allowList}) => (super.noSuchMethod( Invocation.method(#getKeys, [], {#allowList: allowList}), - returnValue: _i9.Future>.value({}), + returnValue: _i3.Future>.value({}), ) - as _i9.Future>); + as _i3.Future>); @override - _i9.Future> getAll({Set? allowList}) => + _i3.Future> getAll({Set? allowList}) => (super.noSuchMethod( Invocation.method(#getAll, [], {#allowList: allowList}), - returnValue: _i9.Future>.value( + returnValue: _i3.Future>.value( {}, ), ) - as _i9.Future>); + as _i3.Future>); @override - _i9.Future getBool(String? key) => + _i3.Future getBool(String? key) => (super.noSuchMethod( Invocation.method(#getBool, [key]), - returnValue: _i9.Future.value(), + returnValue: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future getInt(String? key) => + _i3.Future getInt(String? key) => (super.noSuchMethod( Invocation.method(#getInt, [key]), - returnValue: _i9.Future.value(), + returnValue: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future getDouble(String? key) => + _i3.Future getDouble(String? key) => (super.noSuchMethod( Invocation.method(#getDouble, [key]), - returnValue: _i9.Future.value(), + returnValue: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future getString(String? key) => + _i3.Future getString(String? key) => (super.noSuchMethod( Invocation.method(#getString, [key]), - returnValue: _i9.Future.value(), + returnValue: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future?> getStringList(String? key) => + _i3.Future?> getStringList(String? key) => (super.noSuchMethod( Invocation.method(#getStringList, [key]), - returnValue: _i9.Future?>.value(), + returnValue: _i3.Future?>.value(), ) - as _i9.Future?>); + as _i3.Future?>); @override - _i9.Future containsKey(String? key) => + _i3.Future containsKey(String? key) => (super.noSuchMethod( Invocation.method(#containsKey, [key]), - returnValue: _i9.Future.value(false), + returnValue: _i3.Future.value(false), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future setBool(String? key, bool? value) => + _i3.Future setBool(String? key, bool? value) => (super.noSuchMethod( Invocation.method(#setBool, [key, value]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future setInt(String? key, int? value) => + _i3.Future setInt(String? key, int? value) => (super.noSuchMethod( Invocation.method(#setInt, [key, value]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future setDouble(String? key, double? value) => + _i3.Future setDouble(String? key, double? value) => (super.noSuchMethod( Invocation.method(#setDouble, [key, value]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future setString(String? key, String? value) => + _i3.Future setString(String? key, String? value) => (super.noSuchMethod( Invocation.method(#setString, [key, value]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future setStringList(String? key, List? value) => + _i3.Future setStringList(String? key, List? value) => (super.noSuchMethod( Invocation.method(#setStringList, [key, value]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future remove(String? key) => + _i3.Future remove(String? key) => (super.noSuchMethod( Invocation.method(#remove, [key]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); @override - _i9.Future clear({Set? allowList}) => + _i3.Future clear({Set? allowList}) => (super.noSuchMethod( Invocation.method(#clear, [], {#allowList: allowList}), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), ) - as _i9.Future); + as _i3.Future); } diff --git a/test/measurements/measurement_entries_screen_test.dart b/test/measurements/measurement_entries_screen_test.dart index e22b46ac2..ff5c93374 100644 --- a/test/measurements/measurement_entries_screen_test.dart +++ b/test/measurements/measurement_entries_screen_test.dart @@ -21,20 +21,21 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/measurements/measurement_category.dart'; +import 'package:wger/providers/ingredient_repository.dart'; import 'package:wger/providers/measurement_repository.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/screens/measurement_entries_screen.dart'; import '../../test_data/measurements.dart'; import 'measurement_entries_screen_test.mocks.dart'; -@GenerateMocks([MeasurementRepository, NutritionPlansProvider]) +@GenerateMocks([MeasurementRepository, NutritionRepository, IngredientRepository]) void main() { late MockMeasurementRepository mockMeasurementRepo; - late MockNutritionPlansProvider mockNutritionPlansProvider; + late MockNutritionRepository mockNutritionRepo; + late MockIngredientRepository mockIngredientRepo; setUp(() { mockMeasurementRepo = MockMeasurementRepository(); @@ -42,9 +43,9 @@ void main() { mockMeasurementRepo.watchLocalDriftCategoryById(any), ).thenAnswer((_) => Stream.value(getMeasurementCategories()[0])); - mockNutritionPlansProvider = MockNutritionPlansProvider(); - when(mockNutritionPlansProvider.currentPlan).thenReturn(null); - when(mockNutritionPlansProvider.items).thenReturn([]); + mockNutritionRepo = MockNutritionRepository(); + mockIngredientRepo = MockIngredientRepository(); + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); }); Widget createEntriesScreen({locale = 'en'}) { @@ -53,23 +54,22 @@ void main() { return ProviderScope( overrides: [ measurementRepositoryProvider.overrideWithValue(mockMeasurementRepo), + nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), ], - child: ChangeNotifierProvider( - create: (context) => mockNutritionPlansProvider, - child: MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - navigatorKey: key, - home: TextButton( - onPressed: () => key.currentState!.push( - MaterialPageRoute( - settings: const RouteSettings(arguments: '1'), - builder: (_) => const MeasurementEntriesScreen(), - ), + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + navigatorKey: key, + home: TextButton( + onPressed: () => key.currentState!.push( + MaterialPageRoute( + settings: const RouteSettings(arguments: '1'), + builder: (_) => const MeasurementEntriesScreen(), ), - child: Container(), ), + child: Container(), ), ), ); diff --git a/test/measurements/measurement_entries_screen_test.mocks.dart b/test/measurements/measurement_entries_screen_test.mocks.dart index 4a5c89280..f1cb7acc5 100644 --- a/test/measurements/measurement_entries_screen_test.mocks.dart +++ b/test/measurements/measurement_entries_screen_test.mocks.dart @@ -3,21 +3,17 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i9; -import 'dart:ui' as _i14; +import 'dart:async' as _i5; +import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; -import 'package:wger/database/ingredients/ingredients_database.dart' as _i3; -import 'package:wger/models/measurements/measurement_category.dart' as _i10; -import 'package:wger/models/measurements/measurement_entry.dart' as _i11; -import 'package:wger/models/nutrition/ingredient.dart' as _i7; -import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i13; -import 'package:wger/models/nutrition/meal.dart' as _i5; -import 'package:wger/models/nutrition/meal_item.dart' as _i6; -import 'package:wger/models/nutrition/nutritional_plan.dart' as _i4; -import 'package:wger/providers/base_provider.dart' as _i2; -import 'package:wger/providers/measurement_repository.dart' as _i8; -import 'package:wger/providers/nutrition.dart' as _i12; +import 'package:wger/models/measurements/measurement_category.dart' as _i6; +import 'package:wger/models/measurements/measurement_entry.dart' as _i7; +import 'package:wger/models/nutrition/ingredient.dart' as _i3; +import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i9; +import 'package:wger/providers/ingredient_repository.dart' as _i10; +import 'package:wger/providers/measurement_repository.dart' as _i4; +import 'package:wger/providers/nutrition_repository.dart' as _i8; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -34,403 +30,233 @@ import 'package:wger/providers/nutrition.dart' as _i12; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); +class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { + _FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeIngredientDatabase_1 extends _i1.SmartFake implements _i3.IngredientDatabase { - _FakeIngredientDatabase_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeNutritionalPlan_2 extends _i1.SmartFake implements _i4.NutritionalPlan { - _FakeNutritionalPlan_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeMeal_3 extends _i1.SmartFake implements _i5.Meal { - _FakeMeal_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeMealItem_4 extends _i1.SmartFake implements _i6.MealItem { - _FakeMealItem_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeIngredient_5 extends _i1.SmartFake implements _i7.Ingredient { - _FakeIngredient_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +class _FakeIngredient_1 extends _i1.SmartFake implements _i3.Ingredient { + _FakeIngredient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [MeasurementRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockMeasurementRepository extends _i1.Mock implements _i8.MeasurementRepository { +class MockMeasurementRepository extends _i1.Mock implements _i4.MeasurementRepository { MockMeasurementRepository() { _i1.throwOnMissingStub(this); } @override - _i9.Stream> watchAll() => + _i5.Stream> watchAll() => (super.noSuchMethod( Invocation.method(#watchAll, []), - returnValue: _i9.Stream>.empty(), + returnValue: _i5.Stream>.empty(), ) - as _i9.Stream>); + as _i5.Stream>); @override - _i9.Stream<_i10.MeasurementCategory?> watchLocalDriftCategoryById( + _i5.Stream<_i6.MeasurementCategory?> watchLocalDriftCategoryById( String? id, ) => (super.noSuchMethod( Invocation.method(#watchLocalDriftCategoryById, [id]), - returnValue: _i9.Stream<_i10.MeasurementCategory?>.empty(), + returnValue: _i5.Stream<_i6.MeasurementCategory?>.empty(), ) - as _i9.Stream<_i10.MeasurementCategory?>); + as _i5.Stream<_i6.MeasurementCategory?>); @override - _i9.Future deleteLocalDrift(String? id) => + _i5.Future deleteLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDrift, [id]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i9.Future); + as _i5.Future); @override - _i9.Future updateLocalDrift(_i11.MeasurementEntry? entry) => + _i5.Future updateLocalDrift(_i7.MeasurementEntry? entry) => (super.noSuchMethod( Invocation.method(#updateLocalDrift, [entry]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i9.Future); + as _i5.Future); @override - _i9.Future addLocalDrift(_i11.MeasurementEntry? entry) => + _i5.Future addLocalDrift(_i7.MeasurementEntry? entry) => (super.noSuchMethod( Invocation.method(#addLocalDrift, [entry]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i9.Future); + as _i5.Future); @override - _i9.Future deleteLocalDriftCategory(String? id) => + _i5.Future deleteLocalDriftCategory(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDriftCategory, [id]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i9.Future); + as _i5.Future); @override - _i9.Future updateLocalDriftCategory( - _i10.MeasurementCategory? category, + _i5.Future updateLocalDriftCategory( + _i6.MeasurementCategory? category, ) => (super.noSuchMethod( Invocation.method(#updateLocalDriftCategory, [category]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i9.Future); + as _i5.Future); @override - _i9.Future addLocalDriftCategory(_i10.MeasurementCategory? category) => + _i5.Future addLocalDriftCategory(_i6.MeasurementCategory? category) => (super.noSuchMethod( Invocation.method(#addLocalDriftCategory, [category]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i9.Future); + as _i5.Future); } -/// A class which mocks [NutritionPlansProvider]. +/// A class which mocks [NutritionRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockNutritionPlansProvider extends _i1.Mock implements _i12.NutritionPlansProvider { - MockNutritionPlansProvider() { +class MockNutritionRepository extends _i1.Mock implements _i8.NutritionRepository { + MockNutritionRepository() { _i1.throwOnMissingStub(this); } @override - _i2.WgerBaseProvider get baseProvider => + _i5.Future> fetchAllPlans() => (super.noSuchMethod( - Invocation.getter(#baseProvider), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#baseProvider), + Invocation.method(#fetchAllPlans, []), + returnValue: _i5.Future>.value([]), + ) + as _i5.Future>); + + @override + _i5.Future> fetchPlanSparse(int? planId) => + (super.noSuchMethod( + Invocation.method(#fetchPlanSparse, [planId]), + returnValue: _i5.Future>.value( + {}, ), ) - as _i2.WgerBaseProvider); + as _i5.Future>); @override - _i3.IngredientDatabase get database => + _i5.Future> fetchPlanFull(int? planId) => (super.noSuchMethod( - Invocation.getter(#database), - returnValue: _FakeIngredientDatabase_1( - this, - Invocation.getter(#database), + Invocation.method(#fetchPlanFull, [planId]), + returnValue: _i5.Future>.value( + {}, ), ) - as _i3.IngredientDatabase); + as _i5.Future>); @override - List<_i7.Ingredient> get ingredients => + _i5.Future> createPlan(Map? data) => (super.noSuchMethod( - Invocation.getter(#ingredients), - returnValue: <_i7.Ingredient>[], - ) - as List<_i7.Ingredient>); - - @override - List<_i4.NutritionalPlan> get items => - (super.noSuchMethod( - Invocation.getter(#items), - returnValue: <_i4.NutritionalPlan>[], - ) - as List<_i4.NutritionalPlan>); - - @override - set database(_i3.IngredientDatabase? value) => super.noSuchMethod( - Invocation.setter(#database, value), - returnValueForMissingStub: null, - ); - - @override - set ingredients(List<_i7.Ingredient>? value) => super.noSuchMethod( - Invocation.setter(#ingredients, value), - returnValueForMissingStub: null, - ); - - @override - bool get hasListeners => - (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); - - @override - void clear() => super.noSuchMethod( - Invocation.method(#clear, []), - returnValueForMissingStub: null, - ); - - @override - _i4.NutritionalPlan findById(int? id) => - (super.noSuchMethod( - Invocation.method(#findById, [id]), - returnValue: _FakeNutritionalPlan_2( - this, - Invocation.method(#findById, [id]), + Invocation.method(#createPlan, [data]), + returnValue: _i5.Future>.value( + {}, ), ) - as _i4.NutritionalPlan); + as _i5.Future>); @override - _i5.Meal? findMealById(int? id) => - (super.noSuchMethod(Invocation.method(#findMealById, [id])) as _i5.Meal?); - - @override - _i9.Future fetchAndSetAllPlansSparse() => + _i5.Future updatePlan(int? id, Map? data) => (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansSparse, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#updatePlan, [id, data]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i9.Future); + as _i5.Future); @override - _i9.Future fetchAndSetAllPlansFull() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansFull, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanSparse, [planId]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanSparse, [planId]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanFull, [planId]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanFull, [planId]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future<_i4.NutritionalPlan> addPlan(_i4.NutritionalPlan? planData) => - (super.noSuchMethod( - Invocation.method(#addPlan, [planData]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#addPlan, [planData]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future editPlan(_i4.NutritionalPlan? plan) => - (super.noSuchMethod( - Invocation.method(#editPlan, [plan]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future deletePlan(int? id) => + _i5.Future<_i2.Response> deletePlan(int? id) => (super.noSuchMethod( Invocation.method(#deletePlan, [id]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i5.Meal> addMeal(_i5.Meal? meal, int? planId) => - (super.noSuchMethod( - Invocation.method(#addMeal, [meal, planId]), - returnValue: _i9.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#addMeal, [meal, planId])), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deletePlan, [id])), ), ) - as _i9.Future<_i5.Meal>); + as _i5.Future<_i2.Response>); @override - _i9.Future<_i5.Meal> editMeal(_i5.Meal? meal) => + _i5.Future> createMeal(Map? data) => (super.noSuchMethod( - Invocation.method(#editMeal, [meal]), - returnValue: _i9.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#editMeal, [meal])), + Invocation.method(#createMeal, [data]), + returnValue: _i5.Future>.value( + {}, ), ) - as _i9.Future<_i5.Meal>); + as _i5.Future>); @override - _i9.Future deleteMeal(_i5.Meal? meal) => - (super.noSuchMethod( - Invocation.method(#deleteMeal, [meal]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i6.MealItem> addMealItem( - _i6.MealItem? mealItem, - _i5.Meal? meal, + _i5.Future> updateMeal( + int? id, + Map? data, ) => (super.noSuchMethod( - Invocation.method(#addMealItem, [mealItem, meal]), - returnValue: _i9.Future<_i6.MealItem>.value( - _FakeMealItem_4( + Invocation.method(#updateMeal, [id, data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i2.Response> deleteMeal(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMeal, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMeal, [id])), + ), + ) + as _i5.Future<_i2.Response>); + + @override + _i5.Future> createMealItem(Map? data) => + (super.noSuchMethod( + Invocation.method(#createMealItem, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i2.Response> deleteMealItem(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMealItem, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMealItem, [id])), + ), + ) + as _i5.Future<_i2.Response>); + + @override + _i5.Future<_i3.Ingredient> fetchIngredient(int? id) => + (super.noSuchMethod( + Invocation.method(#fetchIngredient, [id]), + returnValue: _i5.Future<_i3.Ingredient>.value( + _FakeIngredient_1( this, - Invocation.method(#addMealItem, [mealItem, meal]), + Invocation.method(#fetchIngredient, [id]), ), ), ) - as _i9.Future<_i6.MealItem>); + as _i5.Future<_i3.Ingredient>); @override - _i9.Future deleteMealItem(_i6.MealItem? mealItem) => - (super.noSuchMethod( - Invocation.method(#deleteMealItem, [mealItem]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future clearIngredientCache() => - (super.noSuchMethod( - Invocation.method(#clearIngredientCache, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future cacheIngredient( - _i7.Ingredient? ingredient, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #cacheIngredient, - [ingredient], - {#database: database}, - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i7.Ingredient> fetchIngredient( - int? ingredientId, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - returnValue: _i9.Future<_i7.Ingredient>.value( - _FakeIngredient_5( - this, - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - ), - ), - ) - as _i9.Future<_i7.Ingredient>); - - @override - _i9.Future> fetchWeightUnits( - int? ingredientId, - ) => - (super.noSuchMethod( - Invocation.method(#fetchWeightUnits, [ingredientId]), - returnValue: _i9.Future>.value( - <_i13.IngredientWeightUnit>[], - ), - ) - as _i9.Future>); - - @override - _i9.Future fetchIngredientsFromCache() => - (super.noSuchMethod( - Invocation.method(#fetchIngredientsFromCache, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future> searchIngredient( + _i5.Future> searchIngredient( String? name, { String? languageCode = 'en', - _i12.IngredientSearchLanguage? searchLanguage = _i12.IngredientSearchLanguage.current, + _i8.IngredientSearchLanguage? searchLanguage = _i8.IngredientSearchLanguage.current, bool? isVegan = false, bool? isVegetarian = false, }) => @@ -445,85 +271,82 @@ class MockNutritionPlansProvider extends _i1.Mock implements _i12.NutritionPlans #isVegetarian: isVegetarian, }, ), - returnValue: _i9.Future>.value( - <_i7.Ingredient>[], + returnValue: _i5.Future>.value( + <_i3.Ingredient>[], ), ) - as _i9.Future>); + as _i5.Future>); @override - _i9.Future<_i7.Ingredient?> searchIngredientWithBarcode(String? barcode) => + _i5.Future<_i3.Ingredient?> searchIngredientWithBarcode(String? barcode) => (super.noSuchMethod( Invocation.method(#searchIngredientWithBarcode, [barcode]), - returnValue: _i9.Future<_i7.Ingredient?>.value(), + returnValue: _i5.Future<_i3.Ingredient?>.value(), ) - as _i9.Future<_i7.Ingredient?>); + as _i5.Future<_i3.Ingredient?>); @override - _i9.Future logMealToDiary(_i5.Meal? meal, DateTime? mealDateTime) => + _i5.Future> fetchWeightUnits( + int? ingredientId, + ) => (super.noSuchMethod( - Invocation.method(#logMealToDiary, [meal, mealDateTime]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#fetchWeightUnits, [ingredientId]), + returnValue: _i5.Future>.value( + <_i9.IngredientWeightUnit>[], + ), ) - as _i9.Future); + as _i5.Future>); @override - _i9.Future logIngredientToDiary( - _i6.MealItem? mealItem, - int? planId, [ - DateTime? dateTime, - ]) => + _i5.Future> fetchLogsForPlan(int? planId) => (super.noSuchMethod( - Invocation.method(#logIngredientToDiary, [ - mealItem, - planId, - dateTime, - ]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#fetchLogsForPlan, [planId]), + returnValue: _i5.Future>.value([]), ) - as _i9.Future); + as _i5.Future>); @override - _i9.Future deleteLog(int? logId, int? planId) => + _i5.Future> createLog(Map? data) => (super.noSuchMethod( - Invocation.method(#deleteLog, [logId, planId]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#createLog, [data]), + returnValue: _i5.Future>.value( + {}, + ), ) - as _i9.Future); + as _i5.Future>); @override - _i9.Future fetchAndSetLogs(_i4.NutritionalPlan? plan) => + _i5.Future<_i2.Response> deleteLog(int? id) => (super.noSuchMethod( - Invocation.method(#fetchAndSetLogs, [plan]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#deleteLog, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteLog, [id])), + ), ) - as _i9.Future); - - @override - void addListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#addListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void removeListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#removeListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); - - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method(#notifyListeners, []), - returnValueForMissingStub: null, - ); + as _i5.Future<_i2.Response>); +} + +/// A class which mocks [IngredientRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockIngredientRepository extends _i1.Mock implements _i10.IngredientRepository { + MockIngredientRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i5.Stream<_i3.Ingredient?> watchById(int? id) => + (super.noSuchMethod( + Invocation.method(#watchById, [id]), + returnValue: _i5.Stream<_i3.Ingredient?>.empty(), + ) + as _i5.Stream<_i3.Ingredient?>); + + @override + _i5.Future<_i3.Ingredient?> getById(int? id) => + (super.noSuchMethod( + Invocation.method(#getById, [id]), + returnValue: _i5.Future<_i3.Ingredient?>.value(), + ) + as _i5.Future<_i3.Ingredient?>); } diff --git a/test/nutrition/ingredient_filters_provider_test.dart b/test/nutrition/ingredient_filters_provider_test.dart index ba36ecd82..91fcfd777 100644 --- a/test/nutrition/ingredient_filters_provider_test.dart +++ b/test/nutrition/ingredient_filters_provider_test.dart @@ -21,8 +21,8 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:wger/helpers/shared_preferences.dart'; -import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/nutrition_ingredient_filters_riverpod.dart'; +import 'package:wger/providers/nutrition_repository.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/test/nutrition/ingredient_typeahead_test.dart b/test/nutrition/ingredient_typeahead_test.dart index 16f17789d..c5384d352 100644 --- a/test/nutrition/ingredient_typeahead_test.dart +++ b/test/nutrition/ingredient_typeahead_test.dart @@ -21,29 +21,33 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/ingredient.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/widgets/nutrition/widgets.dart'; import '../../test_data/nutritional_plans.dart'; import 'nutritional_plan_form_test.mocks.dart'; void main() { - late MockNutritionPlansProvider mockNutrition; + late MockNutritionRepository mockRepo; + late MockIngredientRepository mockIngredientRepo; setUp(() async { SharedPreferences.setMockInitialValues({}); SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); await PreferenceHelper.instance.migrationSupportFunctionForSharedPreferences(); - mockNutrition = MockNutritionPlansProvider(); + mockRepo = MockNutritionRepository(); + mockIngredientRepo = MockIngredientRepository(); + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); + when( - mockNutrition.searchIngredient( + mockRepo.searchIngredient( any, languageCode: anyNamed('languageCode'), searchLanguage: anyNamed('searchLanguage'), @@ -71,26 +75,24 @@ void main() { ), ]), ); - - // Mock cacheIngredient as it might be called - when(mockNutrition.cacheIngredient(any)).thenAnswer((_) => Future.value()); }); Widget createWidgetUnderTest() { return ProviderScope( - child: ChangeNotifierProvider.value( - value: mockNutrition, - child: MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold( - body: IngredientTypeahead( - TextEditingController(), - TextEditingController(), - selectIngredient: (id, name, amount) {}, - onDeselectIngredient: () {}, - onUpdateSearchQuery: (query) {}, - ), + overrides: [ + nutritionRepositoryProvider.overrideWithValue(mockRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: IngredientTypeahead( + TextEditingController(), + TextEditingController(), + selectIngredient: (id, name, amount) {}, + onDeselectIngredient: () {}, + onUpdateSearchQuery: (query) {}, ), ), ), @@ -129,7 +131,7 @@ void main() { testWidgets('Shows only Vegan chip when ingredient is vegan', (WidgetTester tester) async { // ingredient1 (Water) is vegan + vegetarian when( - mockNutrition.searchIngredient( + mockRepo.searchIngredient( any, languageCode: anyNamed('languageCode'), searchLanguage: anyNamed('searchLanguage'), @@ -152,7 +154,7 @@ void main() { ) async { // milk is vegetarian but not vegan when( - mockNutrition.searchIngredient( + mockRepo.searchIngredient( any, languageCode: anyNamed('languageCode'), searchLanguage: anyNamed('searchLanguage'), @@ -173,7 +175,7 @@ void main() { testWidgets('Shows no dietary chips when ingredient has no info', (WidgetTester tester) async { // ingredient2 (Burger soup) has no dietary info when( - mockNutrition.searchIngredient( + mockRepo.searchIngredient( any, languageCode: anyNamed('languageCode'), searchLanguage: anyNamed('searchLanguage'), @@ -216,7 +218,7 @@ void main() { // Assert verify( - mockNutrition.searchIngredient( + mockRepo.searchIngredient( 'Apple', languageCode: 'en', searchLanguage: IngredientSearchLanguage.current, diff --git a/test/nutrition/nutrition_provider_test.dart b/test/nutrition/nutrition_provider_test.dart index d2f0ab18a..3004203ae 100644 --- a/test/nutrition/nutrition_provider_test.dart +++ b/test/nutrition/nutrition_provider_test.dart @@ -1,123 +1,104 @@ import 'dart:convert'; -import 'package:drift/native.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:wger/database/ingredients/ingredients_database.dart'; import 'package:wger/models/nutrition/ingredient.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/base_provider.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import '../fixtures/fixture_reader.dart'; import 'nutrition_provider_test.mocks.dart'; -@GenerateMocks([WgerBaseProvider]) +@GenerateMocks([NutritionRepository, IngredientRepository]) void main() { final now = DateTime.now(); - late NutritionPlansProvider nutritionProvider; - late MockWgerBaseProvider mockWgerBaseProvider; - late IngredientDatabase database; - late Map ingredient59887Response; + late MockNutritionRepository mockRepo; + late MockIngredientRepository mockIngredientRepo; + + late Map nutritionalPlanInfoResponse; + late Map nutritionalPlanDetailResponse; + late List nutritionDiaryResponse; + late Map ingredient10065Response; + + ProviderContainer makeContainer() { + final container = ProviderContainer( + overrides: [ + nutritionRepositoryProvider.overrideWithValue(mockRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), + ], + ); + addTearDown(container.dispose); + return container; + } + + /// Creates a container whose [nutritionProvider] is seeded with [plans]. + Future containerWithPlans(List plans) async { + when(mockRepo.fetchAllPlans()).thenAnswer( + (_) async => plans.map((p) => p.toJson()).toList(), + ); + final container = makeContainer(); + // Ensure the async build() has run so state is AsyncData(...) + await container.read(nutritionProvider.future); + await container.read(nutritionProvider.notifier).fetchAndSetAllPlansSparse(); + return container; + } setUp(() { - database = IngredientDatabase.inMemory(NativeDatabase.memory()); - mockWgerBaseProvider = MockWgerBaseProvider(); - nutritionProvider = NutritionPlansProvider( - mockWgerBaseProvider, - [], - database: database, - ); + mockRepo = MockNutritionRepository(); + mockIngredientRepo = MockIngredientRepository(); - const String planInfoUrl = 'nutritionplaninfo'; - const String planUrl = 'nutritionplan'; - const String diaryUrl = 'nutritiondiary'; - const String ingredientInfoUrl = 'ingredientinfo'; - - final Map nutritionalPlanInfoResponse = jsonDecode( + nutritionalPlanInfoResponse = jsonDecode( fixture('nutrition/nutritional_plan_info_detail_response.json'), ); - final Map nutritionalPlanDetailResponse = jsonDecode( + nutritionalPlanDetailResponse = jsonDecode( fixture('nutrition/nutritional_plan_detail_response.json'), ); - final List nutritionDiaryResponse = jsonDecode( + nutritionDiaryResponse = jsonDecode( fixture('nutrition/nutrition_diary_response.json'), )['results']; - ingredient59887Response = jsonDecode( - fixture('nutrition/ingredientinfo_59887.json'), - ); - final Map ingredient10065Response = jsonDecode( + ingredient10065Response = jsonDecode( fixture('nutrition/ingredientinfo_10065.json'), ); - final Map ingredient58300Response = jsonDecode( - fixture('nutrition/ingredientinfo_58300.json'), - ); - final ingredientList = [ - Ingredient.fromJson(ingredient59887Response), - Ingredient.fromJson(ingredient10065Response), - Ingredient.fromJson(ingredient58300Response), - ]; - - nutritionProvider.ingredients = ingredientList; - - final Uri planInfoUri = Uri( - scheme: 'http', - host: 'localhost', - path: 'api/v2/$planInfoUrl/1', - ); - final Uri planUri = Uri( - scheme: 'http', - host: 'localhost', - path: 'api/v2/$planUrl', - ); - final Uri diaryUri = Uri( - scheme: 'http', - host: 'localhost', - path: 'api/v2/$diaryUrl', - ); - final Uri ingredientUri = Uri( - scheme: 'http', - host: 'localhost', - path: 'api/v2/$ingredientInfoUrl', - ); - when(mockWgerBaseProvider.makeUrl(planInfoUrl, id: anyNamed('id'))).thenReturn(planInfoUri); - when(mockWgerBaseProvider.makeUrl(planUrl, id: anyNamed('id'))).thenReturn(planUri); - when(mockWgerBaseProvider.makeUrl(diaryUrl, query: anyNamed('query'))).thenReturn(diaryUri); - when( - mockWgerBaseProvider.makeUrl(ingredientInfoUrl, id: anyNamed('id')), - ).thenReturn(ingredientUri); - when(mockWgerBaseProvider.fetch(planInfoUri)).thenAnswer( - (realInvocation) => Future.value(nutritionalPlanInfoResponse), - ); - when(mockWgerBaseProvider.fetch(planUri)).thenAnswer( - (realInvocation) => Future.value(nutritionalPlanDetailResponse), - ); - when(mockWgerBaseProvider.fetchPaginated(diaryUri)).thenAnswer( - (realInvocation) => Future.value(nutritionDiaryResponse), - ); - when(mockWgerBaseProvider.fetch(ingredientUri)).thenAnswer( - (realInvocation) => Future.value(ingredient10065Response), - ); - }); - - tearDown(() async { - await database.close(); + // By default the local ingredient repo has no data - fall back to HTTP. + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); }); group('fetchAndSetPlanFull', () { test('should correctly load a full nutritional plan', () async { // arrange - await nutritionProvider.fetchAndSetPlanFull(1); + when(mockRepo.fetchPlanSparse(1)).thenAnswer( + (_) async => nutritionalPlanDetailResponse, + ); + when(mockRepo.fetchPlanFull(1)).thenAnswer( + (_) async => nutritionalPlanInfoResponse, + ); + when(mockRepo.fetchLogsForPlan(any)).thenAnswer( + (_) async => nutritionDiaryResponse, + ); + when(mockRepo.fetchIngredient(any)).thenAnswer( + (_) async => Ingredient.fromJson(ingredient10065Response), + ); + + final container = makeContainer(); + await container.read(nutritionProvider.future); + + // act + await container.read(nutritionProvider.notifier).fetchAndSetPlanFull(1); // assert - expect(nutritionProvider.items.isEmpty, false); + final plans = container.read(nutritionProvider).value ?? const []; + expect(plans.isEmpty, false); }); }); group('currentPlan', () { - test('gibt den aktiven Plan zurück, wenn nur einer aktiv ist', () { + test('gibt den aktiven Plan zurück, wenn nur einer aktiv ist', () async { final plan = NutritionalPlan( id: 1, description: 'Aktiver Plan', @@ -125,11 +106,14 @@ void main() { endDate: now.add(const Duration(days: 1)), creationDate: now.subtract(const Duration(days: 2)), ); - nutritionProvider = NutritionPlansProvider(mockWgerBaseProvider, [plan], database: database); - expect(nutritionProvider.currentPlan, equals(plan)); + final container = await containerWithPlans([plan]); + expect( + container.read(nutritionProvider.notifier).currentPlan?.id, + equals(plan.id), + ); }); - test('gibt den neuesten aktiven Plan zurück, wenn mehrere aktiv sind', () { + test('gibt den neuesten aktiven Plan zurück, wenn mehrere aktiv sind', () async { final olderPlan = NutritionalPlan( id: 1, description: 'Älterer aktiver Plan', @@ -144,21 +128,21 @@ void main() { endDate: now.add(const Duration(days: 5)), creationDate: now.subtract(const Duration(days: 2)), ); - nutritionProvider = NutritionPlansProvider(mockWgerBaseProvider, [ - olderPlan, - newerPlan, - ], database: database); - expect(nutritionProvider.currentPlan, equals(newerPlan)); + final container = await containerWithPlans([olderPlan, newerPlan]); + expect( + container.read(nutritionProvider.notifier).currentPlan?.id, + equals(newerPlan.id), + ); }); }); group('currentPlan correctly returns the active plan', () { - test('no plans available -> null', () { - nutritionProvider = NutritionPlansProvider(mockWgerBaseProvider, [], database: database); - expect(nutritionProvider.currentPlan, isNull); + test('no plans available -> null', () async { + final container = await containerWithPlans([]); + expect(container.read(nutritionProvider.notifier).currentPlan, isNull); }); - test('no active plan -> null', () { + test('no active plan -> null', () async { final plans = [ NutritionalPlan( id: 1, @@ -173,117 +157,85 @@ void main() { endDate: now.add(const Duration(days: 50)), ), ]; - nutritionProvider = NutritionPlansProvider(mockWgerBaseProvider, plans, database: database); - expect(nutritionProvider.currentPlan, isNull); + final container = await containerWithPlans(plans); + expect(container.read(nutritionProvider.notifier).currentPlan, isNull); }); - test('active plan exists -> return it', () { + test('active plan exists -> return it', () async { final plan = NutritionalPlan( + id: 42, description: 'Active plan', startDate: now.subtract(const Duration(days: 10)), endDate: now.add(const Duration(days: 10)), ); - nutritionProvider = NutritionPlansProvider(mockWgerBaseProvider, [plan], database: database); - expect(nutritionProvider.currentPlan, equals(plan)); + final container = await containerWithPlans([plan]); + expect( + container.read(nutritionProvider.notifier).currentPlan?.id, + equals(plan.id), + ); }); - test('inactive plans are ignored', () { + test('inactive plans are ignored', () async { final inactivePlan = NutritionalPlan( + id: 10, description: 'Inactive plan', startDate: now.subtract(const Duration(days: 10)), - endDate: now.add(const Duration(days: 5)), + endDate: now.subtract(const Duration(days: 5)), ); final plan = NutritionalPlan( + id: 11, description: 'Active plan', startDate: now.subtract(const Duration(days: 10)), endDate: now.add(const Duration(days: 10)), ); - nutritionProvider = NutritionPlansProvider(mockWgerBaseProvider, [ - plan, - inactivePlan, - ], database: database); - expect(nutritionProvider.currentPlan, equals(plan)); + final container = await containerWithPlans([plan, inactivePlan]); + expect( + container.read(nutritionProvider.notifier).currentPlan?.id, + equals(plan.id), + ); }); - test('several active plans exists -> return newest', () { + test('several active plans exists -> return newest', () async { final olderPlan = NutritionalPlan( + id: 100, description: 'Old active plan', startDate: now.subtract(const Duration(days: 10)), endDate: now.add(const Duration(days: 10)), creationDate: now.subtract(const Duration(days: 10)), ); final newerPlan = NutritionalPlan( + id: 101, description: 'Newer active plan', startDate: now.subtract(const Duration(days: 5)), endDate: now.add(const Duration(days: 5)), creationDate: now.subtract(const Duration(days: 1)), ); - nutritionProvider = NutritionPlansProvider(mockWgerBaseProvider, [ - olderPlan, - newerPlan, - ], database: database); - expect(nutritionProvider.currentPlan, equals(newerPlan)); + final container = await containerWithPlans([olderPlan, newerPlan]); + expect( + container.read(nutritionProvider.notifier).currentPlan?.id, + equals(newerPlan.id), + ); }); }); - group('Ingredient cache DB', () { - test('cacheIngredient saves to both in-memory and database cache', () async { - nutritionProvider.ingredients = []; - final ingredient = Ingredient.fromJson(ingredient59887Response); + group('deletePlan', () { + test('removes the plan locally on success', () async { + final plan = NutritionalPlan( + id: 1, + description: 'to delete', + startDate: now, + creationDate: now, + ); + final container = await containerWithPlans([plan]); - await nutritionProvider.cacheIngredient(ingredient, database: database); + when(mockRepo.deletePlan(1)).thenAnswer( + (_) async => http.Response('', 204), + ); - expect(nutritionProvider.ingredients.length, 1); - expect(nutritionProvider.ingredients.first.id, 59887); + await container.read(nutritionProvider.notifier).deletePlan(1); - final rows = await database.select(database.ingredients).get(); - expect(rows.length, 1); - expect(rows.first.id, ingredient.id); - }); - test('that if there is already valid data in the DB, the API is not hit', () async { - // Arrange - nutritionProvider.ingredients = []; - await database - .into(database.ingredients) - .insert( - IngredientsCompanion.insert( - id: ingredient59887Response['id'], - data: json.encode(ingredient59887Response), - lastFetched: DateTime.now(), - ), - ); - - // Act - await nutritionProvider.fetchIngredient(59887, database: database); - - // Assert - expect(nutritionProvider.ingredients.length, 1); - expect(nutritionProvider.ingredients.first.id, 59887); - expect(nutritionProvider.ingredients.first.name, 'Baked Beans'); - verifyNever(mockWgerBaseProvider.fetchPaginated(any)); - }); - - test('fetching an ingredient not present in the DB, the API is hit', () async { - // Arrange - nutritionProvider.ingredients = []; - await database - .into(database.ingredients) - .insert( - IngredientsCompanion.insert( - id: ingredient59887Response['id'], - data: json.encode(ingredient59887Response), - lastFetched: DateTime.now(), - ), - ); - - // Act - await nutritionProvider.fetchIngredient(10065, database: database); - - // Assert - expect(nutritionProvider.ingredients.length, 1); - expect(nutritionProvider.ingredients.first.id, 10065); - expect(nutritionProvider.ingredients.first.name, "'Old Times' Orange Fine Cut Marmalade"); - verify(mockWgerBaseProvider.fetch(any)); + final plans = container.read(nutritionProvider).value ?? const []; + expect(plans, isEmpty); }); }); } diff --git a/test/nutrition/nutrition_provider_test.mocks.dart b/test/nutrition/nutrition_provider_test.mocks.dart index 7ac39b341..ef6abe637 100644 --- a/test/nutrition/nutrition_provider_test.mocks.dart +++ b/test/nutrition/nutrition_provider_test.mocks.dart @@ -7,8 +7,10 @@ import 'dart:async' as _i5; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i4; -import 'package:wger/providers/base_provider.dart' as _i3; +import 'package:wger/models/nutrition/ingredient.dart' as _i3; +import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i6; +import 'package:wger/providers/ingredient_repository.dart' as _i7; +import 'package:wger/providers/nutrition_repository.dart' as _i4; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -25,132 +27,34 @@ import 'package:wger/providers/base_provider.dart' as _i3; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeClient_0 extends _i1.SmartFake implements _i2.Client { - _FakeClient_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { + _FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeUri_1 extends _i1.SmartFake implements Uri { - _FakeUri_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +class _FakeIngredient_1 extends _i1.SmartFake implements _i3.Ingredient { + _FakeIngredient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeResponse_2 extends _i1.SmartFake implements _i2.Response { - _FakeResponse_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -/// A class which mocks [WgerBaseProvider]. +/// A class which mocks [NutritionRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { - MockWgerBaseProvider() { +class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepository { + MockNutritionRepository() { _i1.throwOnMissingStub(this); } @override - _i2.Client get client => + _i5.Future> fetchAllPlans() => (super.noSuchMethod( - Invocation.getter(#client), - returnValue: _FakeClient_0(this, Invocation.getter(#client)), - ) - as _i2.Client); - - @override - set client(_i2.Client? value) => super.noSuchMethod( - Invocation.setter(#client, value), - returnValueForMissingStub: null, - ); - - @override - String getAppNameHeaderValue() => - (super.noSuchMethod( - Invocation.method(#getAppNameHeaderValue, []), - returnValue: _i4.dummyValue( - this, - Invocation.method(#getAppNameHeaderValue, []), - ), - ) - as String); - - @override - Map getDefaultHeaders({ - bool? includeAuth = false, - String? language, - }) => - (super.noSuchMethod( - Invocation.method(#getDefaultHeaders, [], { - #includeAuth: includeAuth, - #language: language, - }), - returnValue: {}, - ) - as Map); - - @override - Uri makeUrl( - String? path, { - int? id, - String? objectMethod, - Map? query, - }) => - (super.noSuchMethod( - Invocation.method( - #makeUrl, - [path], - {#id: id, #objectMethod: objectMethod, #query: query}, - ), - returnValue: _FakeUri_1( - this, - Invocation.method( - #makeUrl, - [path], - {#id: id, #objectMethod: objectMethod, #query: query}, - ), - ), - ) - as Uri); - - @override - _i5.Future fetch( - Uri? uri, { - int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 250), - Duration? timeout = const Duration(seconds: 15), - String? language, - }) => - (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], - { - #maxRetries: maxRetries, - #initialDelay: initialDelay, - #timeout: timeout, - #language: language, - }, - ), - returnValue: _i5.Future.value(), - ) - as _i5.Future); - - @override - _i5.Future> fetchPaginated( - Uri? uri, { - String? language, - Duration? timeout = const Duration(seconds: 15), - }) => - (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - {#language: language, #timeout: timeout}, - ), + Invocation.method(#fetchAllPlans, []), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post(Map? data, Uri? uri) => + _i5.Future> fetchPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method(#post, [data, uri]), + Invocation.method(#fetchPlanSparse, [planId]), returnValue: _i5.Future>.value( {}, ), @@ -158,12 +62,61 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { as _i5.Future>); @override - _i5.Future> patch( + _i5.Future> fetchPlanFull(int? planId) => + (super.noSuchMethod( + Invocation.method(#fetchPlanFull, [planId]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future> createPlan(Map? data) => + (super.noSuchMethod( + Invocation.method(#createPlan, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future updatePlan(int? id, Map? data) => + (super.noSuchMethod( + Invocation.method(#updatePlan, [id, data]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future<_i2.Response> deletePlan(int? id) => + (super.noSuchMethod( + Invocation.method(#deletePlan, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deletePlan, [id])), + ), + ) + as _i5.Future<_i2.Response>); + + @override + _i5.Future> createMeal(Map? data) => + (super.noSuchMethod( + Invocation.method(#createMeal, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future> updateMeal( + int? id, Map? data, - Uri? uri, ) => (super.noSuchMethod( - Invocation.method(#patch, [data, uri]), + Invocation.method(#updateMeal, [id, data]), returnValue: _i5.Future>.value( {}, ), @@ -171,15 +124,143 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { as _i5.Future>); @override - _i5.Future<_i2.Response> deleteRequest(String? url, int? id) => + _i5.Future<_i2.Response> deleteMeal(int? id) => (super.noSuchMethod( - Invocation.method(#deleteRequest, [url, id]), + Invocation.method(#deleteMeal, [id]), returnValue: _i5.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0(this, Invocation.method(#deleteMeal, [id])), + ), + ) + as _i5.Future<_i2.Response>); + + @override + _i5.Future> createMealItem(Map? data) => + (super.noSuchMethod( + Invocation.method(#createMealItem, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i2.Response> deleteMealItem(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMealItem, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMealItem, [id])), + ), + ) + as _i5.Future<_i2.Response>); + + @override + _i5.Future<_i3.Ingredient> fetchIngredient(int? id) => + (super.noSuchMethod( + Invocation.method(#fetchIngredient, [id]), + returnValue: _i5.Future<_i3.Ingredient>.value( + _FakeIngredient_1( this, - Invocation.method(#deleteRequest, [url, id]), + Invocation.method(#fetchIngredient, [id]), ), ), ) + as _i5.Future<_i3.Ingredient>); + + @override + _i5.Future> searchIngredient( + String? name, { + String? languageCode = 'en', + _i4.IngredientSearchLanguage? searchLanguage = _i4.IngredientSearchLanguage.current, + bool? isVegan = false, + bool? isVegetarian = false, + }) => + (super.noSuchMethod( + Invocation.method( + #searchIngredient, + [name], + { + #languageCode: languageCode, + #searchLanguage: searchLanguage, + #isVegan: isVegan, + #isVegetarian: isVegetarian, + }, + ), + returnValue: _i5.Future>.value( + <_i3.Ingredient>[], + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i3.Ingredient?> searchIngredientWithBarcode(String? barcode) => + (super.noSuchMethod( + Invocation.method(#searchIngredientWithBarcode, [barcode]), + returnValue: _i5.Future<_i3.Ingredient?>.value(), + ) + as _i5.Future<_i3.Ingredient?>); + + @override + _i5.Future> fetchWeightUnits( + int? ingredientId, + ) => + (super.noSuchMethod( + Invocation.method(#fetchWeightUnits, [ingredientId]), + returnValue: _i5.Future>.value( + <_i6.IngredientWeightUnit>[], + ), + ) + as _i5.Future>); + + @override + _i5.Future> fetchLogsForPlan(int? planId) => + (super.noSuchMethod( + Invocation.method(#fetchLogsForPlan, [planId]), + returnValue: _i5.Future>.value([]), + ) + as _i5.Future>); + + @override + _i5.Future> createLog(Map? data) => + (super.noSuchMethod( + Invocation.method(#createLog, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i2.Response> deleteLog(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteLog, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteLog, [id])), + ), + ) as _i5.Future<_i2.Response>); } + +/// A class which mocks [IngredientRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockIngredientRepository extends _i1.Mock implements _i7.IngredientRepository { + MockIngredientRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i5.Stream<_i3.Ingredient?> watchById(int? id) => + (super.noSuchMethod( + Invocation.method(#watchById, [id]), + returnValue: _i5.Stream<_i3.Ingredient?>.empty(), + ) + as _i5.Stream<_i3.Ingredient?>); + + @override + _i5.Future<_i3.Ingredient?> getById(int? id) => + (super.noSuchMethod( + Invocation.method(#getById, [id]), + returnValue: _i5.Future<_i3.Ingredient?>.value(), + ) + as _i5.Future<_i3.Ingredient?>); +} diff --git a/test/nutrition/nutritional_meal_form_test.dart b/test/nutrition/nutritional_meal_form_test.dart index 82daa7d8e..eb9526e1a 100644 --- a/test/nutrition/nutritional_meal_form_test.dart +++ b/test/nutrition/nutritional_meal_form_test.dart @@ -18,43 +18,60 @@ import 'package:clock/clock.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/json.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import 'package:wger/widgets/nutrition/forms.dart'; import '../../test_data/nutritional_plans.dart'; -import 'nutritional_meal_form_test.mocks.dart'; +import 'nutritional_plan_form_test.mocks.dart'; -@GenerateMocks([NutritionPlansProvider]) void main() { - var mockNutrition = MockNutritionPlansProvider(); + late MockNutritionRepository mockRepo; + late MockIngredientRepository mockIngredientRepo; + late ProviderContainer container; var plan1 = NutritionalPlan.empty(); var meal1 = Meal(); - setUp(() { + setUp(() async { plan1 = getNutritionalPlan(); meal1 = plan1.meals.first; - mockNutrition = MockNutritionPlansProvider(); + mockRepo = MockNutritionRepository(); + mockIngredientRepo = MockIngredientRepository(); - when(mockNutrition.editMeal(any)).thenAnswer((_) => Future.value(Meal())); - when(mockNutrition.addMeal(any, any)).thenAnswer((_) => Future.value(Meal())); + when(mockRepo.updateMeal(any, any)).thenAnswer((_) async => Meal(id: 1, plan: 1).toJson()); + when(mockRepo.createMeal(any)).thenAnswer((_) async => Meal(id: 99, plan: 1).toJson()); + + container = ProviderContainer( + overrides: [ + nutritionRepositoryProvider.overrideWithValue(mockRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), + ], + ); + // Initialize the notifier so build() runs, then seed plans. + await container.read(nutritionProvider.future); + container.read(nutritionProvider.notifier).state = AsyncData([plan1]); + }); + + tearDown(() { + container.dispose(); }); Widget createFormScreen(Meal meal, {locale = 'en'}) { final key = GlobalKey(); - return ChangeNotifierProvider( - create: (context) => mockNutrition, + return UncontrolledProviderScope( + container: container, child: MaterialApp( locale: Locale(locale), localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -98,8 +115,8 @@ void main() { await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); // Correct method was called - verify(mockNutrition.editMeal(any)); - verifyNever(mockNutrition.addMeal(any, any)); + verify(mockRepo.updateMeal(any, any)); + verifyNever(mockRepo.createMeal(any)); }); testWidgets('Test creating a new nutritional plan', (WidgetTester tester) async { @@ -137,8 +154,8 @@ void main() { await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); // Correct method was called - verifyNever(mockNutrition.editMeal(any)); - verify(mockNutrition.addMeal(any, any)); + verifyNever(mockRepo.updateMeal(any, any)); + verify(mockRepo.createMeal(any)); }); // Detail page diff --git a/test/nutrition/nutritional_meal_form_test.mocks.dart b/test/nutrition/nutritional_meal_form_test.mocks.dart deleted file mode 100644 index 42a82a330..000000000 --- a/test/nutrition/nutritional_meal_form_test.mocks.dart +++ /dev/null @@ -1,443 +0,0 @@ -// Mocks generated by Mockito 5.4.6 from annotations -// in wger/test/nutrition/nutritional_meal_form_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i9; -import 'dart:ui' as _i11; - -import 'package:mockito/mockito.dart' as _i1; -import 'package:wger/database/ingredients/ingredients_database.dart' as _i3; -import 'package:wger/models/nutrition/ingredient.dart' as _i7; -import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i10; -import 'package:wger/models/nutrition/meal.dart' as _i5; -import 'package:wger/models/nutrition/meal_item.dart' as _i6; -import 'package:wger/models/nutrition/nutritional_plan.dart' as _i4; -import 'package:wger/providers/base_provider.dart' as _i2; -import 'package:wger/providers/nutrition.dart' as _i8; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: must_be_immutable -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class -// ignore_for_file: invalid_use_of_internal_member - -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeIngredientDatabase_1 extends _i1.SmartFake implements _i3.IngredientDatabase { - _FakeIngredientDatabase_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeNutritionalPlan_2 extends _i1.SmartFake implements _i4.NutritionalPlan { - _FakeNutritionalPlan_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeMeal_3 extends _i1.SmartFake implements _i5.Meal { - _FakeMeal_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeMealItem_4 extends _i1.SmartFake implements _i6.MealItem { - _FakeMealItem_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeIngredient_5 extends _i1.SmartFake implements _i7.Ingredient { - _FakeIngredient_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -/// A class which mocks [NutritionPlansProvider]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockNutritionPlansProvider extends _i1.Mock implements _i8.NutritionPlansProvider { - MockNutritionPlansProvider() { - _i1.throwOnMissingStub(this); - } - - @override - _i2.WgerBaseProvider get baseProvider => - (super.noSuchMethod( - Invocation.getter(#baseProvider), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#baseProvider), - ), - ) - as _i2.WgerBaseProvider); - - @override - _i3.IngredientDatabase get database => - (super.noSuchMethod( - Invocation.getter(#database), - returnValue: _FakeIngredientDatabase_1( - this, - Invocation.getter(#database), - ), - ) - as _i3.IngredientDatabase); - - @override - List<_i7.Ingredient> get ingredients => - (super.noSuchMethod( - Invocation.getter(#ingredients), - returnValue: <_i7.Ingredient>[], - ) - as List<_i7.Ingredient>); - - @override - List<_i4.NutritionalPlan> get items => - (super.noSuchMethod( - Invocation.getter(#items), - returnValue: <_i4.NutritionalPlan>[], - ) - as List<_i4.NutritionalPlan>); - - @override - set database(_i3.IngredientDatabase? value) => super.noSuchMethod( - Invocation.setter(#database, value), - returnValueForMissingStub: null, - ); - - @override - set ingredients(List<_i7.Ingredient>? value) => super.noSuchMethod( - Invocation.setter(#ingredients, value), - returnValueForMissingStub: null, - ); - - @override - bool get hasListeners => - (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); - - @override - void clear() => super.noSuchMethod( - Invocation.method(#clear, []), - returnValueForMissingStub: null, - ); - - @override - _i4.NutritionalPlan findById(int? id) => - (super.noSuchMethod( - Invocation.method(#findById, [id]), - returnValue: _FakeNutritionalPlan_2( - this, - Invocation.method(#findById, [id]), - ), - ) - as _i4.NutritionalPlan); - - @override - _i5.Meal? findMealById(int? id) => - (super.noSuchMethod(Invocation.method(#findMealById, [id])) as _i5.Meal?); - - @override - _i9.Future fetchAndSetAllPlansSparse() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansSparse, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future fetchAndSetAllPlansFull() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansFull, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanSparse, [planId]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanSparse, [planId]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanFull, [planId]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanFull, [planId]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future<_i4.NutritionalPlan> addPlan(_i4.NutritionalPlan? planData) => - (super.noSuchMethod( - Invocation.method(#addPlan, [planData]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#addPlan, [planData]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future editPlan(_i4.NutritionalPlan? plan) => - (super.noSuchMethod( - Invocation.method(#editPlan, [plan]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future deletePlan(int? id) => - (super.noSuchMethod( - Invocation.method(#deletePlan, [id]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i5.Meal> addMeal(_i5.Meal? meal, int? planId) => - (super.noSuchMethod( - Invocation.method(#addMeal, [meal, planId]), - returnValue: _i9.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#addMeal, [meal, planId])), - ), - ) - as _i9.Future<_i5.Meal>); - - @override - _i9.Future<_i5.Meal> editMeal(_i5.Meal? meal) => - (super.noSuchMethod( - Invocation.method(#editMeal, [meal]), - returnValue: _i9.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#editMeal, [meal])), - ), - ) - as _i9.Future<_i5.Meal>); - - @override - _i9.Future deleteMeal(_i5.Meal? meal) => - (super.noSuchMethod( - Invocation.method(#deleteMeal, [meal]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i6.MealItem> addMealItem( - _i6.MealItem? mealItem, - _i5.Meal? meal, - ) => - (super.noSuchMethod( - Invocation.method(#addMealItem, [mealItem, meal]), - returnValue: _i9.Future<_i6.MealItem>.value( - _FakeMealItem_4( - this, - Invocation.method(#addMealItem, [mealItem, meal]), - ), - ), - ) - as _i9.Future<_i6.MealItem>); - - @override - _i9.Future deleteMealItem(_i6.MealItem? mealItem) => - (super.noSuchMethod( - Invocation.method(#deleteMealItem, [mealItem]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future clearIngredientCache() => - (super.noSuchMethod( - Invocation.method(#clearIngredientCache, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future cacheIngredient( - _i7.Ingredient? ingredient, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #cacheIngredient, - [ingredient], - {#database: database}, - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i7.Ingredient> fetchIngredient( - int? ingredientId, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - returnValue: _i9.Future<_i7.Ingredient>.value( - _FakeIngredient_5( - this, - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - ), - ), - ) - as _i9.Future<_i7.Ingredient>); - - @override - _i9.Future> fetchWeightUnits( - int? ingredientId, - ) => - (super.noSuchMethod( - Invocation.method(#fetchWeightUnits, [ingredientId]), - returnValue: _i9.Future>.value( - <_i10.IngredientWeightUnit>[], - ), - ) - as _i9.Future>); - - @override - _i9.Future fetchIngredientsFromCache() => - (super.noSuchMethod( - Invocation.method(#fetchIngredientsFromCache, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future> searchIngredient( - String? name, { - String? languageCode = 'en', - _i8.IngredientSearchLanguage? searchLanguage = _i8.IngredientSearchLanguage.current, - bool? isVegan = false, - bool? isVegetarian = false, - }) => - (super.noSuchMethod( - Invocation.method( - #searchIngredient, - [name], - { - #languageCode: languageCode, - #searchLanguage: searchLanguage, - #isVegan: isVegan, - #isVegetarian: isVegetarian, - }, - ), - returnValue: _i9.Future>.value( - <_i7.Ingredient>[], - ), - ) - as _i9.Future>); - - @override - _i9.Future<_i7.Ingredient?> searchIngredientWithBarcode(String? barcode) => - (super.noSuchMethod( - Invocation.method(#searchIngredientWithBarcode, [barcode]), - returnValue: _i9.Future<_i7.Ingredient?>.value(), - ) - as _i9.Future<_i7.Ingredient?>); - - @override - _i9.Future logMealToDiary(_i5.Meal? meal, DateTime? mealDateTime) => - (super.noSuchMethod( - Invocation.method(#logMealToDiary, [meal, mealDateTime]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future logIngredientToDiary( - _i6.MealItem? mealItem, - int? planId, [ - DateTime? dateTime, - ]) => - (super.noSuchMethod( - Invocation.method(#logIngredientToDiary, [ - mealItem, - planId, - dateTime, - ]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future deleteLog(int? logId, int? planId) => - (super.noSuchMethod( - Invocation.method(#deleteLog, [logId, planId]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future fetchAndSetLogs(_i4.NutritionalPlan? plan) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetLogs, [plan]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - void addListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#addListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void removeListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#removeListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); - - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method(#notifyListeners, []), - returnValueForMissingStub: null, - ); -} diff --git a/test/nutrition/nutritional_meal_item_form_test.dart b/test/nutrition/nutritional_meal_item_form_test.dart index bfb18bd5e..c57b60465 100644 --- a/test/nutrition/nutritional_meal_item_form_test.dart +++ b/test/nutrition/nutritional_meal_item_form_test.dart @@ -26,7 +26,6 @@ import 'package:flutter_typeahead/flutter_typeahead.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:network_image_mock/network_image_mock.dart'; -import 'package:provider/provider.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:wger/helpers/consts.dart'; @@ -35,7 +34,9 @@ import 'package:wger/models/nutrition/ingredient.dart'; import 'package:wger/models/nutrition/meal.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import 'package:wger/widgets/nutrition/forms.dart'; @@ -63,7 +64,10 @@ void main() { sodium: 0.5, ); - var mockNutrition = MockNutritionPlansProvider(); + late MockNutritionRepository mockRepo; + late MockIngredientRepository mockIngredientRepo; + late ProviderContainer container; + final client = MockClient(); var plan1 = NutritionalPlan.empty(); @@ -85,57 +89,81 @@ void main() { (_) => Future.value(http.Response(fixture('nutrition/ingredientinfo_wrong_code.json'), 200)), ); - setUp(() { + setUp(() async { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); plan1 = getNutritionalPlan(); meal1 = plan1.meals.first; - final MealItem mealItem = MealItem(ingredientId: ingredient.id, amount: 2); - mockNutrition = MockNutritionPlansProvider(); + final MealItem mealItem = MealItem( + id: 10, + mealId: 1, + ingredientId: ingredient.id, + amount: 2, + ); + + mockRepo = MockNutritionRepository(); + mockIngredientRepo = MockIngredientRepository(); + + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); when( - mockNutrition.searchIngredientWithBarcode('123'), + mockRepo.searchIngredientWithBarcode('123'), ).thenAnswer((_) => Future.value(ingredient)); - when(mockNutrition.searchIngredientWithBarcode('')).thenAnswer((_) => Future.value(null)); - when(mockNutrition.searchIngredientWithBarcode('222')).thenAnswer((_) => Future.value(null)); + when(mockRepo.searchIngredientWithBarcode('')).thenAnswer((_) => Future.value(null)); + when(mockRepo.searchIngredientWithBarcode('222')).thenAnswer((_) => Future.value(null)); when( - mockNutrition.searchIngredient( + mockRepo.searchIngredient( any, languageCode: anyNamed('languageCode'), searchLanguage: anyNamed('searchLanguage'), + isVegan: anyNamed('isVegan'), + isVegetarian: anyNamed('isVegetarian'), ), ).thenAnswer( (_) => Future.value([ingredient1, ingredient2]), ); - when(mockNutrition.addMealItem(any, meal1)).thenAnswer((_) => Future.value(mealItem)); - when(mockNutrition.fetchWeightUnits(1)).thenAnswer((_) => Future.value([])); - when(mockNutrition.fetchWeightUnits(2)).thenAnswer((_) => Future.value([])); + when(mockRepo.createMealItem(any)).thenAnswer((_) async => mealItem.toJson()); + when(mockRepo.fetchIngredient(any)).thenAnswer((_) async => ingredient); + when(mockRepo.fetchWeightUnits(1)).thenAnswer((_) => Future.value([])); + when(mockRepo.fetchWeightUnits(2)).thenAnswer((_) => Future.value([])); + + container = ProviderContainer( + overrides: [ + nutritionRepositoryProvider.overrideWithValue(mockRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), + ], + ); + // Initialize the nutrition notifier and seed with plan1 so that + // addMealItem can look up the meal/plan. + await container.read(nutritionProvider.future); + container.read(nutritionProvider.notifier).state = AsyncData([plan1]); + }); + + tearDown(() { + container.dispose(); }); Widget createMealItemFormScreen(Meal meal, String code, bool test, {locale = 'en'}) { final key = GlobalKey(); - return ProviderScope( - child: ChangeNotifierProvider( - create: (context) => mockNutrition, - child: MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - navigatorKey: key, - home: Scaffold( - body: Scrollable( - viewportBuilder: (BuildContext context, ViewportOffset position) => - getMealItemForm(meal, const [], code, test), - ), + return UncontrolledProviderScope( + container: container, + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + navigatorKey: key, + home: Scaffold( + body: Scrollable( + viewportBuilder: (BuildContext context, ViewportOffset position) => + getMealItemForm(meal, const [], code, test), ), - routes: { - NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), - }, ), + routes: { + NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), + }, ), ); - // ProviderScope closes here } testWidgets('Test the widgets on the meal item form', (WidgetTester tester) async { @@ -183,26 +211,6 @@ void main() { }); }); - /* - group('Test searchIngredientWithCode() function', () { - test('with correct code', () async { - final Ingredient? ingredient = await mockNutritionWithClient.searchIngredientWithCode('123'); - expect(ingredient!.id, 9436); - }); - - test('with incorrect code', () async { - final Ingredient? ingredient = await mockNutritionWithClient.searchIngredientWithCode('222'); - expect(ingredient, null); - }); - - test('with empty code', () async { - final Ingredient? ingredient = await mockNutritionWithClient.searchIngredientWithCode(''); - expect(ingredient, null); - }); - }); - - */ - group('Test weight formfield', () { testWidgets('add empty weight', (WidgetTester tester) async { await tester.pumpWidget(createMealItemFormScreen(meal1, '123', true)); @@ -322,7 +330,7 @@ void main() { await tester.enterText(find.byKey(const Key('field-weight')), '2'); // once ID and weight are set, it'll fetchIngredient and show macros preview and ingredient image - when(mockNutrition.fetchIngredient(1)).thenAnswer( + when(mockRepo.fetchIngredient(1)).thenAnswer( (_) => Future.value( Ingredient.fromJson(jsonDecode(fixture('nutrition/ingredientinfo_59887.json'))), ), @@ -336,38 +344,8 @@ void main() { expect(formState.mealItem.amount, 2); - verify(mockNutrition.addMealItem(any, meal1)); + verify(mockRepo.createMealItem(any)); }, ); - - testWidgets('selecting ingredient from autocomplete calls cacheIngredient', ( - WidgetTester tester, - ) async { - await tester.pumpWidget(createMealItemFormScreen(meal1, '', true)); - await tester.pumpAndSettle(); - - clearInteractions(mockNutrition); - - when( - mockNutrition.searchIngredient( - any, - languageCode: anyNamed('languageCode'), - searchLanguage: anyNamed('searchLanguage'), - ), - ).thenAnswer((_) => Future.value([ingredient1])); - - when( - mockNutrition.cacheIngredient(any), - ).thenAnswer((_) => Future.value(null)); - - await tester.enterText(find.byType(TextFormField).first, 'Water'); - await tester.pumpAndSettle(const Duration(milliseconds: 600)); - await tester.pumpAndSettle(); - - await tester.tap(find.byType(ListTile).first); - await tester.pumpAndSettle(); - - verify(mockNutrition.cacheIngredient(ingredient1)).called(1); - }); }); } diff --git a/test/nutrition/nutritional_plan_form_test.dart b/test/nutrition/nutritional_plan_form_test.dart index 73f26084d..c3a1601db 100644 --- a/test/nutrition/nutritional_plan_form_test.dart +++ b/test/nutrition/nutritional_plan_form_test.dart @@ -17,22 +17,24 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import 'package:wger/widgets/nutrition/forms.dart'; import './nutritional_plan_form_test.mocks.dart'; -@GenerateMocks([NutritionPlansProvider]) +@GenerateMocks([NutritionRepository, IngredientRepository]) void main() { - var mockNutrition = MockNutritionPlansProvider(); + late MockNutritionRepository mockRepo; + late MockIngredientRepository mockIngredientRepo; final plan1 = NutritionalPlan( id: 1, @@ -44,17 +46,21 @@ void main() { final plan2 = NutritionalPlan.empty(); setUp(() { - mockNutrition = MockNutritionPlansProvider(); + mockRepo = MockNutritionRepository(); + mockIngredientRepo = MockIngredientRepository(); - when(mockNutrition.editPlan(any)).thenAnswer((_) => Future.value(plan1)); - when(mockNutrition.addPlan(any)).thenAnswer((_) => Future.value(plan1)); + when(mockRepo.updatePlan(any, any)).thenAnswer((_) async {}); + when(mockRepo.createPlan(any)).thenAnswer((_) async => plan1.toJson()); }); Widget createHomeScreen(NutritionalPlan plan, {locale = 'en'}) { final key = GlobalKey(); - return ChangeNotifierProvider( - create: (context) => mockNutrition, + return ProviderScope( + overrides: [ + nutritionRepositoryProvider.overrideWithValue(mockRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), + ], child: MaterialApp( locale: Locale(locale), localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -89,21 +95,8 @@ void main() { await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); // Correct method was called - verify(mockNutrition.editPlan(any)); - verifyNever(mockNutrition.addPlan(any)); - - // TODO(x): edit calls Navigator.pop(), since the form can only be reached from the - // detail page. The test needs to add the detail page to the stack so that - // this can be checked. - // https://stackoverflow.com/questions/50704647/how-to-test-navigation-via-navigator-in-flutter - - // Detail page - // await tester.pumpAndSettle(); - //expect( - // find.text(('New description')), - //findsOneWidget, - //reason: 'Nutritional plan detail page', - //); + verify(mockRepo.updatePlan(any, any)); + verifyNever(mockRepo.createPlan(any)); }); testWidgets('Test creating a new nutritional plan', (WidgetTester tester) async { @@ -120,11 +113,7 @@ void main() { await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); // Correct method was called - verifyNever(mockNutrition.editPlan(any)); - verify(mockNutrition.addPlan(any)); - - // TODO: detail page - // await tester.pumpAndSettle(); - // expect(find.text('New cool plan'), findsOneWidget, reason: 'Nutritional plan detail page'); + verifyNever(mockRepo.updatePlan(any, any)); + verify(mockRepo.createPlan(any)); }); } diff --git a/test/nutrition/nutritional_plan_form_test.mocks.dart b/test/nutrition/nutritional_plan_form_test.mocks.dart index 161cacdee..816c57435 100644 --- a/test/nutrition/nutritional_plan_form_test.mocks.dart +++ b/test/nutrition/nutritional_plan_form_test.mocks.dart @@ -3,18 +3,14 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i9; -import 'dart:ui' as _i11; +import 'dart:async' as _i5; +import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; -import 'package:wger/database/ingredients/ingredients_database.dart' as _i3; -import 'package:wger/models/nutrition/ingredient.dart' as _i7; -import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i10; -import 'package:wger/models/nutrition/meal.dart' as _i5; -import 'package:wger/models/nutrition/meal_item.dart' as _i6; -import 'package:wger/models/nutrition/nutritional_plan.dart' as _i4; -import 'package:wger/providers/base_provider.dart' as _i2; -import 'package:wger/providers/nutrition.dart' as _i8; +import 'package:wger/models/nutrition/ingredient.dart' as _i3; +import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i6; +import 'package:wger/providers/ingredient_repository.dart' as _i7; +import 'package:wger/providers/nutrition_repository.dart' as _i4; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -31,320 +27,150 @@ import 'package:wger/providers/nutrition.dart' as _i8; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); +class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { + _FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeIngredientDatabase_1 extends _i1.SmartFake implements _i3.IngredientDatabase { - _FakeIngredientDatabase_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); +class _FakeIngredient_1 extends _i1.SmartFake implements _i3.Ingredient { + _FakeIngredient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeNutritionalPlan_2 extends _i1.SmartFake implements _i4.NutritionalPlan { - _FakeNutritionalPlan_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeMeal_3 extends _i1.SmartFake implements _i5.Meal { - _FakeMeal_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeMealItem_4 extends _i1.SmartFake implements _i6.MealItem { - _FakeMealItem_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeIngredient_5 extends _i1.SmartFake implements _i7.Ingredient { - _FakeIngredient_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -/// A class which mocks [NutritionPlansProvider]. +/// A class which mocks [NutritionRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockNutritionPlansProvider extends _i1.Mock implements _i8.NutritionPlansProvider { - MockNutritionPlansProvider() { +class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepository { + MockNutritionRepository() { _i1.throwOnMissingStub(this); } @override - _i2.WgerBaseProvider get baseProvider => + _i5.Future> fetchAllPlans() => (super.noSuchMethod( - Invocation.getter(#baseProvider), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#baseProvider), + Invocation.method(#fetchAllPlans, []), + returnValue: _i5.Future>.value([]), + ) + as _i5.Future>); + + @override + _i5.Future> fetchPlanSparse(int? planId) => + (super.noSuchMethod( + Invocation.method(#fetchPlanSparse, [planId]), + returnValue: _i5.Future>.value( + {}, ), ) - as _i2.WgerBaseProvider); + as _i5.Future>); @override - _i3.IngredientDatabase get database => + _i5.Future> fetchPlanFull(int? planId) => (super.noSuchMethod( - Invocation.getter(#database), - returnValue: _FakeIngredientDatabase_1( - this, - Invocation.getter(#database), + Invocation.method(#fetchPlanFull, [planId]), + returnValue: _i5.Future>.value( + {}, ), ) - as _i3.IngredientDatabase); + as _i5.Future>); @override - List<_i7.Ingredient> get ingredients => + _i5.Future> createPlan(Map? data) => (super.noSuchMethod( - Invocation.getter(#ingredients), - returnValue: <_i7.Ingredient>[], - ) - as List<_i7.Ingredient>); - - @override - List<_i4.NutritionalPlan> get items => - (super.noSuchMethod( - Invocation.getter(#items), - returnValue: <_i4.NutritionalPlan>[], - ) - as List<_i4.NutritionalPlan>); - - @override - set database(_i3.IngredientDatabase? value) => super.noSuchMethod( - Invocation.setter(#database, value), - returnValueForMissingStub: null, - ); - - @override - set ingredients(List<_i7.Ingredient>? value) => super.noSuchMethod( - Invocation.setter(#ingredients, value), - returnValueForMissingStub: null, - ); - - @override - bool get hasListeners => - (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); - - @override - void clear() => super.noSuchMethod( - Invocation.method(#clear, []), - returnValueForMissingStub: null, - ); - - @override - _i4.NutritionalPlan findById(int? id) => - (super.noSuchMethod( - Invocation.method(#findById, [id]), - returnValue: _FakeNutritionalPlan_2( - this, - Invocation.method(#findById, [id]), + Invocation.method(#createPlan, [data]), + returnValue: _i5.Future>.value( + {}, ), ) - as _i4.NutritionalPlan); + as _i5.Future>); @override - _i5.Meal? findMealById(int? id) => - (super.noSuchMethod(Invocation.method(#findMealById, [id])) as _i5.Meal?); - - @override - _i9.Future fetchAndSetAllPlansSparse() => + _i5.Future updatePlan(int? id, Map? data) => (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansSparse, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#updatePlan, [id, data]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i9.Future); + as _i5.Future); @override - _i9.Future fetchAndSetAllPlansFull() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansFull, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanSparse, [planId]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanSparse, [planId]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanFull, [planId]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanFull, [planId]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future<_i4.NutritionalPlan> addPlan(_i4.NutritionalPlan? planData) => - (super.noSuchMethod( - Invocation.method(#addPlan, [planData]), - returnValue: _i9.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#addPlan, [planData]), - ), - ), - ) - as _i9.Future<_i4.NutritionalPlan>); - - @override - _i9.Future editPlan(_i4.NutritionalPlan? plan) => - (super.noSuchMethod( - Invocation.method(#editPlan, [plan]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future deletePlan(int? id) => + _i5.Future<_i2.Response> deletePlan(int? id) => (super.noSuchMethod( Invocation.method(#deletePlan, [id]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i5.Meal> addMeal(_i5.Meal? meal, int? planId) => - (super.noSuchMethod( - Invocation.method(#addMeal, [meal, planId]), - returnValue: _i9.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#addMeal, [meal, planId])), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deletePlan, [id])), ), ) - as _i9.Future<_i5.Meal>); + as _i5.Future<_i2.Response>); @override - _i9.Future<_i5.Meal> editMeal(_i5.Meal? meal) => + _i5.Future> createMeal(Map? data) => (super.noSuchMethod( - Invocation.method(#editMeal, [meal]), - returnValue: _i9.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#editMeal, [meal])), + Invocation.method(#createMeal, [data]), + returnValue: _i5.Future>.value( + {}, ), ) - as _i9.Future<_i5.Meal>); + as _i5.Future>); @override - _i9.Future deleteMeal(_i5.Meal? meal) => - (super.noSuchMethod( - Invocation.method(#deleteMeal, [meal]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i6.MealItem> addMealItem( - _i6.MealItem? mealItem, - _i5.Meal? meal, + _i5.Future> updateMeal( + int? id, + Map? data, ) => (super.noSuchMethod( - Invocation.method(#addMealItem, [mealItem, meal]), - returnValue: _i9.Future<_i6.MealItem>.value( - _FakeMealItem_4( + Invocation.method(#updateMeal, [id, data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i2.Response> deleteMeal(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMeal, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMeal, [id])), + ), + ) + as _i5.Future<_i2.Response>); + + @override + _i5.Future> createMealItem(Map? data) => + (super.noSuchMethod( + Invocation.method(#createMealItem, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i2.Response> deleteMealItem(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMealItem, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMealItem, [id])), + ), + ) + as _i5.Future<_i2.Response>); + + @override + _i5.Future<_i3.Ingredient> fetchIngredient(int? id) => + (super.noSuchMethod( + Invocation.method(#fetchIngredient, [id]), + returnValue: _i5.Future<_i3.Ingredient>.value( + _FakeIngredient_1( this, - Invocation.method(#addMealItem, [mealItem, meal]), + Invocation.method(#fetchIngredient, [id]), ), ), ) - as _i9.Future<_i6.MealItem>); + as _i5.Future<_i3.Ingredient>); @override - _i9.Future deleteMealItem(_i6.MealItem? mealItem) => - (super.noSuchMethod( - Invocation.method(#deleteMealItem, [mealItem]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future clearIngredientCache() => - (super.noSuchMethod( - Invocation.method(#clearIngredientCache, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future cacheIngredient( - _i7.Ingredient? ingredient, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #cacheIngredient, - [ingredient], - {#database: database}, - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future<_i7.Ingredient> fetchIngredient( - int? ingredientId, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - returnValue: _i9.Future<_i7.Ingredient>.value( - _FakeIngredient_5( - this, - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - ), - ), - ) - as _i9.Future<_i7.Ingredient>); - - @override - _i9.Future> fetchWeightUnits( - int? ingredientId, - ) => - (super.noSuchMethod( - Invocation.method(#fetchWeightUnits, [ingredientId]), - returnValue: _i9.Future>.value( - <_i10.IngredientWeightUnit>[], - ), - ) - as _i9.Future>); - - @override - _i9.Future fetchIngredientsFromCache() => - (super.noSuchMethod( - Invocation.method(#fetchIngredientsFromCache, []), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) - as _i9.Future); - - @override - _i9.Future> searchIngredient( + _i5.Future> searchIngredient( String? name, { String? languageCode = 'en', - _i8.IngredientSearchLanguage? searchLanguage = _i8.IngredientSearchLanguage.current, + _i4.IngredientSearchLanguage? searchLanguage = _i4.IngredientSearchLanguage.current, bool? isVegan = false, bool? isVegetarian = false, }) => @@ -359,85 +185,82 @@ class MockNutritionPlansProvider extends _i1.Mock implements _i8.NutritionPlansP #isVegetarian: isVegetarian, }, ), - returnValue: _i9.Future>.value( - <_i7.Ingredient>[], + returnValue: _i5.Future>.value( + <_i3.Ingredient>[], ), ) - as _i9.Future>); + as _i5.Future>); @override - _i9.Future<_i7.Ingredient?> searchIngredientWithBarcode(String? barcode) => + _i5.Future<_i3.Ingredient?> searchIngredientWithBarcode(String? barcode) => (super.noSuchMethod( Invocation.method(#searchIngredientWithBarcode, [barcode]), - returnValue: _i9.Future<_i7.Ingredient?>.value(), + returnValue: _i5.Future<_i3.Ingredient?>.value(), ) - as _i9.Future<_i7.Ingredient?>); + as _i5.Future<_i3.Ingredient?>); @override - _i9.Future logMealToDiary(_i5.Meal? meal, DateTime? mealDateTime) => + _i5.Future> fetchWeightUnits( + int? ingredientId, + ) => (super.noSuchMethod( - Invocation.method(#logMealToDiary, [meal, mealDateTime]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#fetchWeightUnits, [ingredientId]), + returnValue: _i5.Future>.value( + <_i6.IngredientWeightUnit>[], + ), ) - as _i9.Future); + as _i5.Future>); @override - _i9.Future logIngredientToDiary( - _i6.MealItem? mealItem, - int? planId, [ - DateTime? dateTime, - ]) => + _i5.Future> fetchLogsForPlan(int? planId) => (super.noSuchMethod( - Invocation.method(#logIngredientToDiary, [ - mealItem, - planId, - dateTime, - ]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#fetchLogsForPlan, [planId]), + returnValue: _i5.Future>.value([]), ) - as _i9.Future); + as _i5.Future>); @override - _i9.Future deleteLog(int? logId, int? planId) => + _i5.Future> createLog(Map? data) => (super.noSuchMethod( - Invocation.method(#deleteLog, [logId, planId]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#createLog, [data]), + returnValue: _i5.Future>.value( + {}, + ), ) - as _i9.Future); + as _i5.Future>); @override - _i9.Future fetchAndSetLogs(_i4.NutritionalPlan? plan) => + _i5.Future<_i2.Response> deleteLog(int? id) => (super.noSuchMethod( - Invocation.method(#fetchAndSetLogs, [plan]), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), + Invocation.method(#deleteLog, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteLog, [id])), + ), ) - as _i9.Future); - - @override - void addListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#addListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void removeListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#removeListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); - - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method(#notifyListeners, []), - returnValueForMissingStub: null, - ); + as _i5.Future<_i2.Response>); +} + +/// A class which mocks [IngredientRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockIngredientRepository extends _i1.Mock implements _i7.IngredientRepository { + MockIngredientRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i5.Stream<_i3.Ingredient?> watchById(int? id) => + (super.noSuchMethod( + Invocation.method(#watchById, [id]), + returnValue: _i5.Stream<_i3.Ingredient?>.empty(), + ) + as _i5.Stream<_i3.Ingredient?>); + + @override + _i5.Future<_i3.Ingredient?> getById(int? id) => + (super.noSuchMethod( + Invocation.method(#getById, [id]), + returnValue: _i5.Future<_i3.Ingredient?>.value(), + ) + as _i5.Future<_i3.Ingredient?>); } diff --git a/test/nutrition/nutritional_plan_screen_test.dart b/test/nutrition/nutritional_plan_screen_test.dart index aa5fbed12..3e67286e2 100644 --- a/test/nutrition/nutritional_plan_screen_test.dart +++ b/test/nutrition/nutritional_plan_screen_test.dart @@ -17,77 +17,107 @@ */ import 'dart:async'; +import 'dart:convert'; import 'dart:io'; -import 'package:drift/native.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; -import 'package:wger/database/ingredients/ingredients_database.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/models/nutrition/nutritional_plan.dart'; -import 'package:wger/providers/base_provider.dart'; +import 'package:wger/models/nutrition/ingredient.dart'; import 'package:wger/providers/body_weight_repository.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/screens/nutritional_plan_screen.dart'; import '../../test_data/body_weight.dart'; import '../../test_data/nutritional_plans.dart'; +import '../fixtures/fixture_reader.dart'; import 'nutritional_plan_screen_test.mocks.dart'; -@GenerateMocks([WgerBaseProvider, http.Client, BodyWeightRepository]) +@GenerateMocks([ + NutritionRepository, + IngredientRepository, + http.Client, + BodyWeightRepository, +]) void main() { - late IngredientDatabase database; - late BodyWeightRepository mockRepository; + late BodyWeightRepository mockBodyWeightRepository; + late MockNutritionRepository mockNutritionRepo; + late MockIngredientRepository mockIngredientRepo; + + late Map nutritionalPlanInfoResponse; + late Map nutritionalPlanDetailResponse; + late List nutritionDiaryResponse; + late Ingredient fetchedIngredient; setUp(() { - mockRepository = MockBodyWeightRepository(); - when(mockRepository.watchAllDrift()).thenAnswer((_) => Stream.value([testWeightEntry1])); - database = IngredientDatabase.inMemory(NativeDatabase.memory()); + mockBodyWeightRepository = MockBodyWeightRepository(); + when( + mockBodyWeightRepository.watchAllDrift(), + ).thenAnswer((_) => Stream.value([testWeightEntry1])); + + mockNutritionRepo = MockNutritionRepository(); + mockIngredientRepo = MockIngredientRepository(); + + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); + + nutritionalPlanInfoResponse = jsonDecode( + fixture('nutrition/nutritional_plan_info_detail_response.json'), + ); + nutritionalPlanDetailResponse = jsonDecode( + fixture('nutrition/nutritional_plan_detail_response.json'), + ); + nutritionDiaryResponse = jsonDecode( + fixture('nutrition/nutrition_diary_response.json'), + )['results']; + fetchedIngredient = Ingredient.fromJson( + jsonDecode(fixture('nutrition/ingredientinfo_10065.json')), + ); + + when( + mockNutritionRepo.fetchPlanSparse(any), + ).thenAnswer((_) async => nutritionalPlanDetailResponse); + when(mockNutritionRepo.fetchPlanFull(any)).thenAnswer((_) async => nutritionalPlanInfoResponse); + when(mockNutritionRepo.fetchLogsForPlan(any)).thenAnswer((_) async => nutritionDiaryResponse); + when(mockNutritionRepo.fetchIngredient(any)).thenAnswer((_) async => fetchedIngredient); }); - tearDown(() { - database.close(); - }); + ProviderContainer makeContainer() { + final container = ProviderContainer( + overrides: [ + bodyWeightRepositoryProvider.overrideWithValue(mockBodyWeightRepository), + nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), + ], + ); + addTearDown(container.dispose); + return container; + } - Widget createNutritionalPlan({locale = 'en', MockWgerBaseProvider? baseProvider}) { + Widget createNutritionalPlan({locale = 'en', required ProviderContainer container}) { final key = GlobalKey(); - final mockBaseProvider = baseProvider ?? MockWgerBaseProvider(); final plan = getNutritionalPlan(); - return riverpod.ProviderScope( - overrides: [ - bodyWeightRepositoryProvider.overrideWithValue(mockRepository), - ], - child: MultiProvider( - providers: [ - ChangeNotifierProvider( - create: (context) => NutritionPlansProvider( - mockBaseProvider, - [], - database: database, + return UncontrolledProviderScope( + container: container, + child: MaterialApp( + key: GlobalKey(), + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + navigatorKey: key, + home: TextButton( + onPressed: () => key.currentState!.push( + MaterialPageRoute( + settings: RouteSettings(arguments: plan), + builder: (_) => const NutritionalPlanScreen(), ), ), - ], - child: MaterialApp( - key: GlobalKey(), - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - navigatorKey: key, - home: TextButton( - onPressed: () => key.currentState!.push( - MaterialPageRoute( - settings: RouteSettings(arguments: plan), - builder: (_) => const NutritionalPlanScreen(), - ), - ), - child: const SizedBox(), - ), + child: const SizedBox(), ), ), ); @@ -99,7 +129,8 @@ void main() { tester.view.physicalSize = const Size(500, 1000); tester.view.devicePixelRatio = 1.0; // Ensure correct pixel ratio - await tester.pumpWidget(createNutritionalPlan()); + final container = makeContainer(); + await tester.pumpWidget(createNutritionalPlan(container: container)); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); @@ -170,7 +201,8 @@ void main() { ); testWidgets('Tests the localization of times - EN', (WidgetTester tester) async { - await tester.pumpWidget(createNutritionalPlan()); + final container = makeContainer(); + await tester.pumpWidget(createNutritionalPlan(container: container)); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); @@ -178,7 +210,8 @@ void main() { }); testWidgets('Tests the localization of times - DE', (WidgetTester tester) async { - await tester.pumpWidget(createNutritionalPlan(locale: 'de')); + final container = makeContainer(); + await tester.pumpWidget(createNutritionalPlan(locale: 'de', container: container)); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); @@ -188,16 +221,13 @@ void main() { testWidgets( 'loading indicator does not reappear after popup menu tap', (WidgetTester tester) async { - final completer = Completer(); - final mockBaseProvider = MockWgerBaseProvider(); + final completer = Completer>(); - // When fetch is called, return our controlled future - when( - mockBaseProvider.makeUrl(any, id: anyNamed('id')), - ).thenReturn(Uri.parse('http://fake.url')); - when(mockBaseProvider.fetch(any)).thenAnswer((_) => completer.future); + // Override the fetchPlanFull behavior so we can control when it completes + when(mockNutritionRepo.fetchPlanFull(any)).thenAnswer((_) => completer.future); - await tester.pumpWidget(createNutritionalPlan(baseProvider: mockBaseProvider)); + final container = makeContainer(); + await tester.pumpWidget(createNutritionalPlan(container: container)); await tester.tap(find.byType(TextButton)); // Two pumps: first for route transition, second for FutureBuilder waiting state @@ -208,7 +238,7 @@ void main() { expect(find.byType(CircularProgressIndicator), findsOneWidget); // Now resolve the future — simulates network response - completer.complete(getNutritionalPlan()); + completer.complete(nutritionalPlanInfoResponse); await tester.pumpAndSettle(); // Spinner gone after successful load diff --git a/test/nutrition/nutritional_plan_screen_test.mocks.dart b/test/nutrition/nutritional_plan_screen_test.mocks.dart index 30fae3bb8..8d5d1b01d 100644 --- a/test/nutrition/nutritional_plan_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plan_screen_test.mocks.dart @@ -4,15 +4,18 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i5; -import 'dart:convert' as _i6; -import 'dart:typed_data' as _i7; +import 'dart:convert' as _i8; +import 'dart:typed_data' as _i10; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i4; -import 'package:wger/models/body_weight/weight_entry.dart' as _i9; -import 'package:wger/providers/base_provider.dart' as _i3; -import 'package:wger/providers/body_weight_repository.dart' as _i8; +import 'package:mockito/src/dummies.dart' as _i9; +import 'package:wger/models/body_weight/weight_entry.dart' as _i12; +import 'package:wger/models/nutrition/ingredient.dart' as _i3; +import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i6; +import 'package:wger/providers/body_weight_repository.dart' as _i11; +import 'package:wger/providers/ingredient_repository.dart' as _i7; +import 'package:wger/providers/nutrition_repository.dart' as _i4; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -29,137 +32,39 @@ import 'package:wger/providers/body_weight_repository.dart' as _i8; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeClient_0 extends _i1.SmartFake implements _i2.Client { - _FakeClient_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { + _FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeUri_1 extends _i1.SmartFake implements Uri { - _FakeUri_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +class _FakeIngredient_1 extends _i1.SmartFake implements _i3.Ingredient { + _FakeIngredient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeResponse_2 extends _i1.SmartFake implements _i2.Response { - _FakeResponse_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeStreamedResponse_3 extends _i1.SmartFake implements _i2.StreamedResponse { - _FakeStreamedResponse_3(Object parent, Invocation parentInvocation) +class _FakeStreamedResponse_2 extends _i1.SmartFake implements _i2.StreamedResponse { + _FakeStreamedResponse_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -/// A class which mocks [WgerBaseProvider]. +/// A class which mocks [NutritionRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { - MockWgerBaseProvider() { +class MockNutritionRepository extends _i1.Mock implements _i4.NutritionRepository { + MockNutritionRepository() { _i1.throwOnMissingStub(this); } @override - _i2.Client get client => + _i5.Future> fetchAllPlans() => (super.noSuchMethod( - Invocation.getter(#client), - returnValue: _FakeClient_0(this, Invocation.getter(#client)), - ) - as _i2.Client); - - @override - set client(_i2.Client? value) => super.noSuchMethod( - Invocation.setter(#client, value), - returnValueForMissingStub: null, - ); - - @override - String getAppNameHeaderValue() => - (super.noSuchMethod( - Invocation.method(#getAppNameHeaderValue, []), - returnValue: _i4.dummyValue( - this, - Invocation.method(#getAppNameHeaderValue, []), - ), - ) - as String); - - @override - Map getDefaultHeaders({ - bool? includeAuth = false, - String? language, - }) => - (super.noSuchMethod( - Invocation.method(#getDefaultHeaders, [], { - #includeAuth: includeAuth, - #language: language, - }), - returnValue: {}, - ) - as Map); - - @override - Uri makeUrl( - String? path, { - int? id, - String? objectMethod, - Map? query, - }) => - (super.noSuchMethod( - Invocation.method( - #makeUrl, - [path], - {#id: id, #objectMethod: objectMethod, #query: query}, - ), - returnValue: _FakeUri_1( - this, - Invocation.method( - #makeUrl, - [path], - {#id: id, #objectMethod: objectMethod, #query: query}, - ), - ), - ) - as Uri); - - @override - _i5.Future fetch( - Uri? uri, { - int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 250), - Duration? timeout = const Duration(seconds: 15), - String? language, - }) => - (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], - { - #maxRetries: maxRetries, - #initialDelay: initialDelay, - #timeout: timeout, - #language: language, - }, - ), - returnValue: _i5.Future.value(), - ) - as _i5.Future); - - @override - _i5.Future> fetchPaginated( - Uri? uri, { - String? language, - Duration? timeout = const Duration(seconds: 15), - }) => - (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - {#language: language, #timeout: timeout}, - ), + Invocation.method(#fetchAllPlans, []), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post(Map? data, Uri? uri) => + _i5.Future> fetchPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method(#post, [data, uri]), + Invocation.method(#fetchPlanSparse, [planId]), returnValue: _i5.Future>.value( {}, ), @@ -167,12 +72,9 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { as _i5.Future>); @override - _i5.Future> patch( - Map? data, - Uri? uri, - ) => + _i5.Future> fetchPlanFull(int? planId) => (super.noSuchMethod( - Invocation.method(#patch, [data, uri]), + Invocation.method(#fetchPlanFull, [planId]), returnValue: _i5.Future>.value( {}, ), @@ -180,17 +82,197 @@ class MockWgerBaseProvider extends _i1.Mock implements _i3.WgerBaseProvider { as _i5.Future>); @override - _i5.Future<_i2.Response> deleteRequest(String? url, int? id) => + _i5.Future> createPlan(Map? data) => (super.noSuchMethod( - Invocation.method(#deleteRequest, [url, id]), + Invocation.method(#createPlan, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future updatePlan(int? id, Map? data) => + (super.noSuchMethod( + Invocation.method(#updatePlan, [id, data]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future<_i2.Response> deletePlan(int? id) => + (super.noSuchMethod( + Invocation.method(#deletePlan, [id]), returnValue: _i5.Future<_i2.Response>.value( - _FakeResponse_2( - this, - Invocation.method(#deleteRequest, [url, id]), - ), + _FakeResponse_0(this, Invocation.method(#deletePlan, [id])), ), ) as _i5.Future<_i2.Response>); + + @override + _i5.Future> createMeal(Map? data) => + (super.noSuchMethod( + Invocation.method(#createMeal, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future> updateMeal( + int? id, + Map? data, + ) => + (super.noSuchMethod( + Invocation.method(#updateMeal, [id, data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i2.Response> deleteMeal(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMeal, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMeal, [id])), + ), + ) + as _i5.Future<_i2.Response>); + + @override + _i5.Future> createMealItem(Map? data) => + (super.noSuchMethod( + Invocation.method(#createMealItem, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i2.Response> deleteMealItem(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMealItem, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMealItem, [id])), + ), + ) + as _i5.Future<_i2.Response>); + + @override + _i5.Future<_i3.Ingredient> fetchIngredient(int? id) => + (super.noSuchMethod( + Invocation.method(#fetchIngredient, [id]), + returnValue: _i5.Future<_i3.Ingredient>.value( + _FakeIngredient_1( + this, + Invocation.method(#fetchIngredient, [id]), + ), + ), + ) + as _i5.Future<_i3.Ingredient>); + + @override + _i5.Future> searchIngredient( + String? name, { + String? languageCode = 'en', + _i4.IngredientSearchLanguage? searchLanguage = _i4.IngredientSearchLanguage.current, + bool? isVegan = false, + bool? isVegetarian = false, + }) => + (super.noSuchMethod( + Invocation.method( + #searchIngredient, + [name], + { + #languageCode: languageCode, + #searchLanguage: searchLanguage, + #isVegan: isVegan, + #isVegetarian: isVegetarian, + }, + ), + returnValue: _i5.Future>.value( + <_i3.Ingredient>[], + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i3.Ingredient?> searchIngredientWithBarcode(String? barcode) => + (super.noSuchMethod( + Invocation.method(#searchIngredientWithBarcode, [barcode]), + returnValue: _i5.Future<_i3.Ingredient?>.value(), + ) + as _i5.Future<_i3.Ingredient?>); + + @override + _i5.Future> fetchWeightUnits( + int? ingredientId, + ) => + (super.noSuchMethod( + Invocation.method(#fetchWeightUnits, [ingredientId]), + returnValue: _i5.Future>.value( + <_i6.IngredientWeightUnit>[], + ), + ) + as _i5.Future>); + + @override + _i5.Future> fetchLogsForPlan(int? planId) => + (super.noSuchMethod( + Invocation.method(#fetchLogsForPlan, [planId]), + returnValue: _i5.Future>.value([]), + ) + as _i5.Future>); + + @override + _i5.Future> createLog(Map? data) => + (super.noSuchMethod( + Invocation.method(#createLog, [data]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i2.Response> deleteLog(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteLog, [id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteLog, [id])), + ), + ) + as _i5.Future<_i2.Response>); +} + +/// A class which mocks [IngredientRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockIngredientRepository extends _i1.Mock implements _i7.IngredientRepository { + MockIngredientRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i5.Stream<_i3.Ingredient?> watchById(int? id) => + (super.noSuchMethod( + Invocation.method(#watchById, [id]), + returnValue: _i5.Stream<_i3.Ingredient?>.empty(), + ) + as _i5.Stream<_i3.Ingredient?>); + + @override + _i5.Future<_i3.Ingredient?> getById(int? id) => + (super.noSuchMethod( + Invocation.method(#getById, [id]), + returnValue: _i5.Future<_i3.Ingredient?>.value(), + ) + as _i5.Future<_i3.Ingredient?>); } /// A class which mocks [Client]. @@ -206,7 +288,7 @@ class MockClient extends _i1.Mock implements _i2.Client { (super.noSuchMethod( Invocation.method(#head, [url], {#headers: headers}), returnValue: _i5.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method(#head, [url], {#headers: headers}), ), @@ -219,7 +301,7 @@ class MockClient extends _i1.Mock implements _i2.Client { (super.noSuchMethod( Invocation.method(#get, [url], {#headers: headers}), returnValue: _i5.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method(#get, [url], {#headers: headers}), ), @@ -232,7 +314,7 @@ class MockClient extends _i1.Mock implements _i2.Client { Uri? url, { Map? headers, Object? body, - _i6.Encoding? encoding, + _i8.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( @@ -241,7 +323,7 @@ class MockClient extends _i1.Mock implements _i2.Client { {#headers: headers, #body: body, #encoding: encoding}, ), returnValue: _i5.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method( #post, @@ -258,7 +340,7 @@ class MockClient extends _i1.Mock implements _i2.Client { Uri? url, { Map? headers, Object? body, - _i6.Encoding? encoding, + _i8.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( @@ -267,7 +349,7 @@ class MockClient extends _i1.Mock implements _i2.Client { {#headers: headers, #body: body, #encoding: encoding}, ), returnValue: _i5.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method( #put, @@ -284,7 +366,7 @@ class MockClient extends _i1.Mock implements _i2.Client { Uri? url, { Map? headers, Object? body, - _i6.Encoding? encoding, + _i8.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( @@ -293,7 +375,7 @@ class MockClient extends _i1.Mock implements _i2.Client { {#headers: headers, #body: body, #encoding: encoding}, ), returnValue: _i5.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method( #patch, @@ -310,7 +392,7 @@ class MockClient extends _i1.Mock implements _i2.Client { Uri? url, { Map? headers, Object? body, - _i6.Encoding? encoding, + _i8.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( @@ -319,7 +401,7 @@ class MockClient extends _i1.Mock implements _i2.Client { {#headers: headers, #body: body, #encoding: encoding}, ), returnValue: _i5.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method( #delete, @@ -336,7 +418,7 @@ class MockClient extends _i1.Mock implements _i2.Client { (super.noSuchMethod( Invocation.method(#read, [url], {#headers: headers}), returnValue: _i5.Future.value( - _i4.dummyValue( + _i9.dummyValue( this, Invocation.method(#read, [url], {#headers: headers}), ), @@ -345,22 +427,22 @@ class MockClient extends _i1.Mock implements _i2.Client { as _i5.Future); @override - _i5.Future<_i7.Uint8List> readBytes( + _i5.Future<_i10.Uint8List> readBytes( Uri? url, { Map? headers, }) => (super.noSuchMethod( Invocation.method(#readBytes, [url], {#headers: headers}), - returnValue: _i5.Future<_i7.Uint8List>.value(_i7.Uint8List(0)), + returnValue: _i5.Future<_i10.Uint8List>.value(_i10.Uint8List(0)), ) - as _i5.Future<_i7.Uint8List>); + as _i5.Future<_i10.Uint8List>); @override _i5.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method(#send, [request]), returnValue: _i5.Future<_i2.StreamedResponse>.value( - _FakeStreamedResponse_3( + _FakeStreamedResponse_2( this, Invocation.method(#send, [request]), ), @@ -378,18 +460,18 @@ class MockClient extends _i1.Mock implements _i2.Client { /// A class which mocks [BodyWeightRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockBodyWeightRepository extends _i1.Mock implements _i8.BodyWeightRepository { +class MockBodyWeightRepository extends _i1.Mock implements _i11.BodyWeightRepository { MockBodyWeightRepository() { _i1.throwOnMissingStub(this); } @override - _i5.Stream> watchAllDrift() => + _i5.Stream> watchAllDrift() => (super.noSuchMethod( Invocation.method(#watchAllDrift, []), - returnValue: _i5.Stream>.empty(), + returnValue: _i5.Stream>.empty(), ) - as _i5.Stream>); + as _i5.Stream>); @override _i5.Future deleteLocalDrift(String? id) => @@ -401,7 +483,7 @@ class MockBodyWeightRepository extends _i1.Mock implements _i8.BodyWeightReposit as _i5.Future); @override - _i5.Future updateLocalDrift(_i9.WeightEntry? entry) => + _i5.Future updateLocalDrift(_i12.WeightEntry? entry) => (super.noSuchMethod( Invocation.method(#updateLocalDrift, [entry]), returnValue: _i5.Future.value(), @@ -410,7 +492,7 @@ class MockBodyWeightRepository extends _i1.Mock implements _i8.BodyWeightReposit as _i5.Future); @override - _i5.Future addLocalDrift(_i9.WeightEntry? entry) => + _i5.Future addLocalDrift(_i12.WeightEntry? entry) => (super.noSuchMethod( Invocation.method(#addLocalDrift, [entry]), returnValue: _i5.Future.value(), diff --git a/test/nutrition/nutritional_plans_screen_test.dart b/test/nutrition/nutritional_plans_screen_test.dart index 16bcc187c..8bb9ef7f3 100644 --- a/test/nutrition/nutritional_plans_screen_test.dart +++ b/test/nutrition/nutritional_plans_screen_test.dart @@ -16,21 +16,19 @@ * along with this program. If not, see . */ -import 'package:drift/native.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; -import 'package:wger/database/ingredients/ingredients_database.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/nutrition/nutritional_plan.dart'; import 'package:wger/models/user/profile.dart'; -import 'package:wger/providers/base_provider.dart'; import 'package:wger/providers/body_weight_repository.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_notifier.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/providers/user_profile_repository.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/nutritional_plans_screen.dart'; @@ -38,12 +36,18 @@ import 'package:wger/widgets/nutrition/forms.dart'; import 'nutritional_plans_screen_test.mocks.dart'; -@GenerateMocks([WgerBaseProvider, http.Client, BodyWeightRepository, UserProfileRepository]) +@GenerateMocks([ + NutritionRepository, + IngredientRepository, + http.Client, + BodyWeightRepository, + UserProfileRepository, +]) void main() { - final mockBaseProvider = MockWgerBaseProvider(); - final client = MockClient(); - late IngredientDatabase database; + late MockNutritionRepository mockNutritionRepo; + late MockIngredientRepository mockIngredientRepo; late MockUserProfileRepository mockUserProfileRepository; + late ProviderContainer container; final testProfile = Profile( username: 'test', @@ -53,63 +57,59 @@ void main() { weightUnitStr: 'kg', ); - setUp(() { - database = IngredientDatabase.inMemory(NativeDatabase.memory()); + final plans = [ + NutritionalPlan( + id: 1, + description: 'test plan 1', + creationDate: DateTime(2021, 01, 01), + startDate: DateTime(2021, 01, 01), + ), + NutritionalPlan( + id: 2, + description: 'test plan 2', + creationDate: DateTime(2021, 01, 10), + startDate: DateTime(2021, 01, 10), + ), + ]; + + setUp(() async { + mockNutritionRepo = MockNutritionRepository(); + mockIngredientRepo = MockIngredientRepository(); mockUserProfileRepository = MockUserProfileRepository(); + when(mockUserProfileRepository.fetchProfile()).thenAnswer((_) async => testProfile); - }); + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); - tearDown(() { - database.close(); - }); - - Widget createHomeScreen({locale = 'en'}) { - when( - client.delete(any, headers: anyNamed('headers')), - ).thenAnswer((_) async => http.Response('', 200)); - - when(mockBaseProvider.deleteRequest(any, any)).thenAnswer( + when(mockNutritionRepo.deletePlan(any)).thenAnswer( (_) async => http.Response('', 200), ); - when(mockBaseProvider.token).thenReturn('1234'); - when(mockBaseProvider.serverUrl).thenReturn('http://localhost'); - - return riverpod.ProviderScope( + container = ProviderContainer( overrides: [ bodyWeightRepositoryProvider.overrideWithValue(MockBodyWeightRepository()), userProfileRepositoryProvider.overrideWithValue(mockUserProfileRepository), + nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), ], - child: MultiProvider( - providers: [ - ChangeNotifierProvider( - create: (context) => NutritionPlansProvider( - mockBaseProvider, - [ - NutritionalPlan( - id: 1, - description: 'test plan 1', - creationDate: DateTime(2021, 01, 01), - startDate: DateTime(2021, 01, 01), - ), - NutritionalPlan( - id: 2, - description: 'test plan 2', - creationDate: DateTime(2021, 01, 10), - startDate: DateTime(2021, 01, 10), - ), - ], - database: database, - ), - ), - ], - child: MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: const NutritionalPlansScreen(), - routes: {FormScreen.routeName: (ctx) => const FormScreen()}, - ), + ); + // Seed the notifier state with the two test plans. + await container.read(nutritionProvider.future); + container.read(nutritionProvider.notifier).state = AsyncData(plans); + }); + + tearDown(() { + container.dispose(); + }); + + Widget createHomeScreen({locale = 'en'}) { + return UncontrolledProviderScope( + container: container, + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const NutritionalPlansScreen(), + routes: {FormScreen.routeName: (ctx) => const FormScreen()}, ), ); } diff --git a/test/nutrition/nutritional_plans_screen_test.mocks.dart b/test/nutrition/nutritional_plans_screen_test.mocks.dart index 67371511a..9299ba3ab 100644 --- a/test/nutrition/nutritional_plans_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plans_screen_test.mocks.dart @@ -4,17 +4,20 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i6; -import 'dart:convert' as _i7; -import 'dart:typed_data' as _i8; +import 'dart:convert' as _i9; +import 'dart:typed_data' as _i11; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i5; -import 'package:wger/models/body_weight/weight_entry.dart' as _i10; -import 'package:wger/models/user/profile.dart' as _i3; -import 'package:wger/providers/base_provider.dart' as _i4; -import 'package:wger/providers/body_weight_repository.dart' as _i9; -import 'package:wger/providers/user_profile_repository.dart' as _i11; +import 'package:mockito/src/dummies.dart' as _i10; +import 'package:wger/models/body_weight/weight_entry.dart' as _i13; +import 'package:wger/models/nutrition/ingredient.dart' as _i3; +import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i7; +import 'package:wger/models/user/profile.dart' as _i4; +import 'package:wger/providers/body_weight_repository.dart' as _i12; +import 'package:wger/providers/ingredient_repository.dart' as _i8; +import 'package:wger/providers/nutrition_repository.dart' as _i5; +import 'package:wger/providers/user_profile_repository.dart' as _i14; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -31,141 +34,43 @@ import 'package:wger/providers/user_profile_repository.dart' as _i11; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeClient_0 extends _i1.SmartFake implements _i2.Client { - _FakeClient_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { + _FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeUri_1 extends _i1.SmartFake implements Uri { - _FakeUri_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +class _FakeIngredient_1 extends _i1.SmartFake implements _i3.Ingredient { + _FakeIngredient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeResponse_2 extends _i1.SmartFake implements _i2.Response { - _FakeResponse_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeStreamedResponse_3 extends _i1.SmartFake implements _i2.StreamedResponse { - _FakeStreamedResponse_3(Object parent, Invocation parentInvocation) +class _FakeStreamedResponse_2 extends _i1.SmartFake implements _i2.StreamedResponse { + _FakeStreamedResponse_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeProfile_4 extends _i1.SmartFake implements _i3.Profile { - _FakeProfile_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +class _FakeProfile_3 extends _i1.SmartFake implements _i4.Profile { + _FakeProfile_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -/// A class which mocks [WgerBaseProvider]. +/// A class which mocks [NutritionRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { - MockWgerBaseProvider() { +class MockNutritionRepository extends _i1.Mock implements _i5.NutritionRepository { + MockNutritionRepository() { _i1.throwOnMissingStub(this); } @override - _i2.Client get client => + _i6.Future> fetchAllPlans() => (super.noSuchMethod( - Invocation.getter(#client), - returnValue: _FakeClient_0(this, Invocation.getter(#client)), - ) - as _i2.Client); - - @override - set client(_i2.Client? value) => super.noSuchMethod( - Invocation.setter(#client, value), - returnValueForMissingStub: null, - ); - - @override - String getAppNameHeaderValue() => - (super.noSuchMethod( - Invocation.method(#getAppNameHeaderValue, []), - returnValue: _i5.dummyValue( - this, - Invocation.method(#getAppNameHeaderValue, []), - ), - ) - as String); - - @override - Map getDefaultHeaders({ - bool? includeAuth = false, - String? language, - }) => - (super.noSuchMethod( - Invocation.method(#getDefaultHeaders, [], { - #includeAuth: includeAuth, - #language: language, - }), - returnValue: {}, - ) - as Map); - - @override - Uri makeUrl( - String? path, { - int? id, - String? objectMethod, - Map? query, - }) => - (super.noSuchMethod( - Invocation.method( - #makeUrl, - [path], - {#id: id, #objectMethod: objectMethod, #query: query}, - ), - returnValue: _FakeUri_1( - this, - Invocation.method( - #makeUrl, - [path], - {#id: id, #objectMethod: objectMethod, #query: query}, - ), - ), - ) - as Uri); - - @override - _i6.Future fetch( - Uri? uri, { - int? maxRetries = 3, - Duration? initialDelay = const Duration(milliseconds: 250), - Duration? timeout = const Duration(seconds: 15), - String? language, - }) => - (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], - { - #maxRetries: maxRetries, - #initialDelay: initialDelay, - #timeout: timeout, - #language: language, - }, - ), - returnValue: _i6.Future.value(), - ) - as _i6.Future); - - @override - _i6.Future> fetchPaginated( - Uri? uri, { - String? language, - Duration? timeout = const Duration(seconds: 15), - }) => - (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - {#language: language, #timeout: timeout}, - ), + Invocation.method(#fetchAllPlans, []), returnValue: _i6.Future>.value([]), ) as _i6.Future>); @override - _i6.Future> post(Map? data, Uri? uri) => + _i6.Future> fetchPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method(#post, [data, uri]), + Invocation.method(#fetchPlanSparse, [planId]), returnValue: _i6.Future>.value( {}, ), @@ -173,12 +78,9 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as _i6.Future>); @override - _i6.Future> patch( - Map? data, - Uri? uri, - ) => + _i6.Future> fetchPlanFull(int? planId) => (super.noSuchMethod( - Invocation.method(#patch, [data, uri]), + Invocation.method(#fetchPlanFull, [planId]), returnValue: _i6.Future>.value( {}, ), @@ -186,17 +88,197 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as _i6.Future>); @override - _i6.Future<_i2.Response> deleteRequest(String? url, int? id) => + _i6.Future> createPlan(Map? data) => (super.noSuchMethod( - Invocation.method(#deleteRequest, [url, id]), + Invocation.method(#createPlan, [data]), + returnValue: _i6.Future>.value( + {}, + ), + ) + as _i6.Future>); + + @override + _i6.Future updatePlan(int? id, Map? data) => + (super.noSuchMethod( + Invocation.method(#updatePlan, [id, data]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) + as _i6.Future); + + @override + _i6.Future<_i2.Response> deletePlan(int? id) => + (super.noSuchMethod( + Invocation.method(#deletePlan, [id]), returnValue: _i6.Future<_i2.Response>.value( - _FakeResponse_2( - this, - Invocation.method(#deleteRequest, [url, id]), - ), + _FakeResponse_0(this, Invocation.method(#deletePlan, [id])), ), ) as _i6.Future<_i2.Response>); + + @override + _i6.Future> createMeal(Map? data) => + (super.noSuchMethod( + Invocation.method(#createMeal, [data]), + returnValue: _i6.Future>.value( + {}, + ), + ) + as _i6.Future>); + + @override + _i6.Future> updateMeal( + int? id, + Map? data, + ) => + (super.noSuchMethod( + Invocation.method(#updateMeal, [id, data]), + returnValue: _i6.Future>.value( + {}, + ), + ) + as _i6.Future>); + + @override + _i6.Future<_i2.Response> deleteMeal(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMeal, [id]), + returnValue: _i6.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMeal, [id])), + ), + ) + as _i6.Future<_i2.Response>); + + @override + _i6.Future> createMealItem(Map? data) => + (super.noSuchMethod( + Invocation.method(#createMealItem, [data]), + returnValue: _i6.Future>.value( + {}, + ), + ) + as _i6.Future>); + + @override + _i6.Future<_i2.Response> deleteMealItem(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMealItem, [id]), + returnValue: _i6.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMealItem, [id])), + ), + ) + as _i6.Future<_i2.Response>); + + @override + _i6.Future<_i3.Ingredient> fetchIngredient(int? id) => + (super.noSuchMethod( + Invocation.method(#fetchIngredient, [id]), + returnValue: _i6.Future<_i3.Ingredient>.value( + _FakeIngredient_1( + this, + Invocation.method(#fetchIngredient, [id]), + ), + ), + ) + as _i6.Future<_i3.Ingredient>); + + @override + _i6.Future> searchIngredient( + String? name, { + String? languageCode = 'en', + _i5.IngredientSearchLanguage? searchLanguage = _i5.IngredientSearchLanguage.current, + bool? isVegan = false, + bool? isVegetarian = false, + }) => + (super.noSuchMethod( + Invocation.method( + #searchIngredient, + [name], + { + #languageCode: languageCode, + #searchLanguage: searchLanguage, + #isVegan: isVegan, + #isVegetarian: isVegetarian, + }, + ), + returnValue: _i6.Future>.value( + <_i3.Ingredient>[], + ), + ) + as _i6.Future>); + + @override + _i6.Future<_i3.Ingredient?> searchIngredientWithBarcode(String? barcode) => + (super.noSuchMethod( + Invocation.method(#searchIngredientWithBarcode, [barcode]), + returnValue: _i6.Future<_i3.Ingredient?>.value(), + ) + as _i6.Future<_i3.Ingredient?>); + + @override + _i6.Future> fetchWeightUnits( + int? ingredientId, + ) => + (super.noSuchMethod( + Invocation.method(#fetchWeightUnits, [ingredientId]), + returnValue: _i6.Future>.value( + <_i7.IngredientWeightUnit>[], + ), + ) + as _i6.Future>); + + @override + _i6.Future> fetchLogsForPlan(int? planId) => + (super.noSuchMethod( + Invocation.method(#fetchLogsForPlan, [planId]), + returnValue: _i6.Future>.value([]), + ) + as _i6.Future>); + + @override + _i6.Future> createLog(Map? data) => + (super.noSuchMethod( + Invocation.method(#createLog, [data]), + returnValue: _i6.Future>.value( + {}, + ), + ) + as _i6.Future>); + + @override + _i6.Future<_i2.Response> deleteLog(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteLog, [id]), + returnValue: _i6.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteLog, [id])), + ), + ) + as _i6.Future<_i2.Response>); +} + +/// A class which mocks [IngredientRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockIngredientRepository extends _i1.Mock implements _i8.IngredientRepository { + MockIngredientRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i6.Stream<_i3.Ingredient?> watchById(int? id) => + (super.noSuchMethod( + Invocation.method(#watchById, [id]), + returnValue: _i6.Stream<_i3.Ingredient?>.empty(), + ) + as _i6.Stream<_i3.Ingredient?>); + + @override + _i6.Future<_i3.Ingredient?> getById(int? id) => + (super.noSuchMethod( + Invocation.method(#getById, [id]), + returnValue: _i6.Future<_i3.Ingredient?>.value(), + ) + as _i6.Future<_i3.Ingredient?>); } /// A class which mocks [Client]. @@ -212,7 +294,7 @@ class MockClient extends _i1.Mock implements _i2.Client { (super.noSuchMethod( Invocation.method(#head, [url], {#headers: headers}), returnValue: _i6.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method(#head, [url], {#headers: headers}), ), @@ -225,7 +307,7 @@ class MockClient extends _i1.Mock implements _i2.Client { (super.noSuchMethod( Invocation.method(#get, [url], {#headers: headers}), returnValue: _i6.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method(#get, [url], {#headers: headers}), ), @@ -238,7 +320,7 @@ class MockClient extends _i1.Mock implements _i2.Client { Uri? url, { Map? headers, Object? body, - _i7.Encoding? encoding, + _i9.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( @@ -247,7 +329,7 @@ class MockClient extends _i1.Mock implements _i2.Client { {#headers: headers, #body: body, #encoding: encoding}, ), returnValue: _i6.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method( #post, @@ -264,7 +346,7 @@ class MockClient extends _i1.Mock implements _i2.Client { Uri? url, { Map? headers, Object? body, - _i7.Encoding? encoding, + _i9.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( @@ -273,7 +355,7 @@ class MockClient extends _i1.Mock implements _i2.Client { {#headers: headers, #body: body, #encoding: encoding}, ), returnValue: _i6.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method( #put, @@ -290,7 +372,7 @@ class MockClient extends _i1.Mock implements _i2.Client { Uri? url, { Map? headers, Object? body, - _i7.Encoding? encoding, + _i9.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( @@ -299,7 +381,7 @@ class MockClient extends _i1.Mock implements _i2.Client { {#headers: headers, #body: body, #encoding: encoding}, ), returnValue: _i6.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method( #patch, @@ -316,7 +398,7 @@ class MockClient extends _i1.Mock implements _i2.Client { Uri? url, { Map? headers, Object? body, - _i7.Encoding? encoding, + _i9.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( @@ -325,7 +407,7 @@ class MockClient extends _i1.Mock implements _i2.Client { {#headers: headers, #body: body, #encoding: encoding}, ), returnValue: _i6.Future<_i2.Response>.value( - _FakeResponse_2( + _FakeResponse_0( this, Invocation.method( #delete, @@ -342,7 +424,7 @@ class MockClient extends _i1.Mock implements _i2.Client { (super.noSuchMethod( Invocation.method(#read, [url], {#headers: headers}), returnValue: _i6.Future.value( - _i5.dummyValue( + _i10.dummyValue( this, Invocation.method(#read, [url], {#headers: headers}), ), @@ -351,22 +433,22 @@ class MockClient extends _i1.Mock implements _i2.Client { as _i6.Future); @override - _i6.Future<_i8.Uint8List> readBytes( + _i6.Future<_i11.Uint8List> readBytes( Uri? url, { Map? headers, }) => (super.noSuchMethod( Invocation.method(#readBytes, [url], {#headers: headers}), - returnValue: _i6.Future<_i8.Uint8List>.value(_i8.Uint8List(0)), + returnValue: _i6.Future<_i11.Uint8List>.value(_i11.Uint8List(0)), ) - as _i6.Future<_i8.Uint8List>); + as _i6.Future<_i11.Uint8List>); @override _i6.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( Invocation.method(#send, [request]), returnValue: _i6.Future<_i2.StreamedResponse>.value( - _FakeStreamedResponse_3( + _FakeStreamedResponse_2( this, Invocation.method(#send, [request]), ), @@ -384,18 +466,18 @@ class MockClient extends _i1.Mock implements _i2.Client { /// A class which mocks [BodyWeightRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockBodyWeightRepository extends _i1.Mock implements _i9.BodyWeightRepository { +class MockBodyWeightRepository extends _i1.Mock implements _i12.BodyWeightRepository { MockBodyWeightRepository() { _i1.throwOnMissingStub(this); } @override - _i6.Stream> watchAllDrift() => + _i6.Stream> watchAllDrift() => (super.noSuchMethod( Invocation.method(#watchAllDrift, []), - returnValue: _i6.Stream>.empty(), + returnValue: _i6.Stream>.empty(), ) - as _i6.Stream>); + as _i6.Stream>); @override _i6.Future deleteLocalDrift(String? id) => @@ -407,7 +489,7 @@ class MockBodyWeightRepository extends _i1.Mock implements _i9.BodyWeightReposit as _i6.Future); @override - _i6.Future updateLocalDrift(_i10.WeightEntry? entry) => + _i6.Future updateLocalDrift(_i13.WeightEntry? entry) => (super.noSuchMethod( Invocation.method(#updateLocalDrift, [entry]), returnValue: _i6.Future.value(), @@ -416,7 +498,7 @@ class MockBodyWeightRepository extends _i1.Mock implements _i9.BodyWeightReposit as _i6.Future); @override - _i6.Future addLocalDrift(_i10.WeightEntry? entry) => + _i6.Future addLocalDrift(_i13.WeightEntry? entry) => (super.noSuchMethod( Invocation.method(#addLocalDrift, [entry]), returnValue: _i6.Future.value(), @@ -428,23 +510,23 @@ class MockBodyWeightRepository extends _i1.Mock implements _i9.BodyWeightReposit /// A class which mocks [UserProfileRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockUserProfileRepository extends _i1.Mock implements _i11.UserProfileRepository { +class MockUserProfileRepository extends _i1.Mock implements _i14.UserProfileRepository { MockUserProfileRepository() { _i1.throwOnMissingStub(this); } @override - _i6.Future<_i3.Profile> fetchProfile() => + _i6.Future<_i4.Profile> fetchProfile() => (super.noSuchMethod( Invocation.method(#fetchProfile, []), - returnValue: _i6.Future<_i3.Profile>.value( - _FakeProfile_4(this, Invocation.method(#fetchProfile, [])), + returnValue: _i6.Future<_i4.Profile>.value( + _FakeProfile_3(this, Invocation.method(#fetchProfile, [])), ), ) - as _i6.Future<_i3.Profile>); + as _i6.Future<_i4.Profile>); @override - _i6.Future saveProfile(_i3.Profile? profile) => + _i6.Future saveProfile(_i4.Profile? profile) => (super.noSuchMethod( Invocation.method(#saveProfile, [profile]), returnValue: _i6.Future.value(), diff --git a/test/weight/weight_screen_test.dart b/test/weight/weight_screen_test.dart index 017e363cd..19ea49f64 100644 --- a/test/weight/weight_screen_test.dart +++ b/test/weight/weight_screen_test.dart @@ -17,14 +17,14 @@ */ import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/body_weight_repository.dart'; -import 'package:wger/providers/nutrition.dart'; +import 'package:wger/providers/ingredient_repository.dart'; +import 'package:wger/providers/nutrition_repository.dart'; import 'package:wger/providers/user_profile_repository.dart'; import 'package:wger/screens/form_screen.dart'; import 'package:wger/screens/weight_screen.dart'; @@ -35,16 +35,22 @@ import '../../test_data/body_weight.dart'; import '../../test_data/profile.dart'; import 'weight_screen_test.mocks.dart'; -@GenerateMocks([NutritionPlansProvider, BodyWeightRepository, UserProfileRepository]) +@GenerateMocks([ + NutritionRepository, + IngredientRepository, + BodyWeightRepository, + UserProfileRepository, +]) void main() { - late MockNutritionPlansProvider mockNutritionPlansProvider; + late MockNutritionRepository mockNutritionRepo; + late MockIngredientRepository mockIngredientRepo; late MockUserProfileRepository mockUserProfileRepository; MockBodyWeightRepository mockBodyWeightRepository = MockBodyWeightRepository(); setUp(() { - mockNutritionPlansProvider = MockNutritionPlansProvider(); - when(mockNutritionPlansProvider.currentPlan).thenReturn(null); - when(mockNutritionPlansProvider.items).thenReturn([]); + mockNutritionRepo = MockNutritionRepository(); + mockIngredientRepo = MockIngredientRepository(); + when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null); mockUserProfileRepository = MockUserProfileRepository(); when(mockUserProfileRepository.fetchProfile()).thenAnswer((_) async => tProfile1); @@ -59,24 +65,19 @@ void main() { }); Widget createWeightScreen({locale = 'en'}) { - return riverpod.ProviderScope( + return ProviderScope( overrides: [ bodyWeightRepositoryProvider.overrideWithValue(mockBodyWeightRepository), userProfileRepositoryProvider.overrideWithValue(mockUserProfileRepository), + nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo), + ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo), ], - child: MultiProvider( - providers: [ - ChangeNotifierProvider( - create: (ctx) => mockNutritionPlansProvider, - ), - ], - child: MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: const WeightScreen(), - routes: {FormScreen.routeName: (_) => const FormScreen()}, - ), + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const WeightScreen(), + routes: {FormScreen.routeName: (_) => const FormScreen()}, ), ); } diff --git a/test/weight/weight_screen_test.mocks.dart b/test/weight/weight_screen_test.mocks.dart index 29efb8582..996cbca9c 100644 --- a/test/weight/weight_screen_test.mocks.dart +++ b/test/weight/weight_screen_test.mocks.dart @@ -3,22 +3,18 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i10; -import 'dart:ui' as _i12; +import 'dart:async' as _i6; +import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; -import 'package:wger/database/ingredients/ingredients_database.dart' as _i3; -import 'package:wger/models/body_weight/weight_entry.dart' as _i14; -import 'package:wger/models/nutrition/ingredient.dart' as _i7; -import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i11; -import 'package:wger/models/nutrition/meal.dart' as _i5; -import 'package:wger/models/nutrition/meal_item.dart' as _i6; -import 'package:wger/models/nutrition/nutritional_plan.dart' as _i4; -import 'package:wger/models/user/profile.dart' as _i8; -import 'package:wger/providers/base_provider.dart' as _i2; -import 'package:wger/providers/body_weight_repository.dart' as _i13; -import 'package:wger/providers/nutrition.dart' as _i9; -import 'package:wger/providers/user_profile_repository.dart' as _i15; +import 'package:wger/models/body_weight/weight_entry.dart' as _i10; +import 'package:wger/models/nutrition/ingredient.dart' as _i3; +import 'package:wger/models/nutrition/ingredient_weight_unit.dart' as _i7; +import 'package:wger/models/user/profile.dart' as _i4; +import 'package:wger/providers/body_weight_repository.dart' as _i9; +import 'package:wger/providers/ingredient_repository.dart' as _i8; +import 'package:wger/providers/nutrition_repository.dart' as _i5; +import 'package:wger/providers/user_profile_repository.dart' as _i11; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -35,324 +31,154 @@ import 'package:wger/providers/user_profile_repository.dart' as _i15; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); +class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { + _FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeIngredientDatabase_1 extends _i1.SmartFake implements _i3.IngredientDatabase { - _FakeIngredientDatabase_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); +class _FakeIngredient_1 extends _i1.SmartFake implements _i3.Ingredient { + _FakeIngredient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeNutritionalPlan_2 extends _i1.SmartFake implements _i4.NutritionalPlan { - _FakeNutritionalPlan_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); +class _FakeProfile_2 extends _i1.SmartFake implements _i4.Profile { + _FakeProfile_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeMeal_3 extends _i1.SmartFake implements _i5.Meal { - _FakeMeal_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeMealItem_4 extends _i1.SmartFake implements _i6.MealItem { - _FakeMealItem_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeIngredient_5 extends _i1.SmartFake implements _i7.Ingredient { - _FakeIngredient_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeProfile_6 extends _i1.SmartFake implements _i8.Profile { - _FakeProfile_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -/// A class which mocks [NutritionPlansProvider]. +/// A class which mocks [NutritionRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockNutritionPlansProvider extends _i1.Mock implements _i9.NutritionPlansProvider { - MockNutritionPlansProvider() { +class MockNutritionRepository extends _i1.Mock implements _i5.NutritionRepository { + MockNutritionRepository() { _i1.throwOnMissingStub(this); } @override - _i2.WgerBaseProvider get baseProvider => + _i6.Future> fetchAllPlans() => (super.noSuchMethod( - Invocation.getter(#baseProvider), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#baseProvider), + Invocation.method(#fetchAllPlans, []), + returnValue: _i6.Future>.value([]), + ) + as _i6.Future>); + + @override + _i6.Future> fetchPlanSparse(int? planId) => + (super.noSuchMethod( + Invocation.method(#fetchPlanSparse, [planId]), + returnValue: _i6.Future>.value( + {}, ), ) - as _i2.WgerBaseProvider); + as _i6.Future>); @override - _i3.IngredientDatabase get database => + _i6.Future> fetchPlanFull(int? planId) => (super.noSuchMethod( - Invocation.getter(#database), - returnValue: _FakeIngredientDatabase_1( - this, - Invocation.getter(#database), + Invocation.method(#fetchPlanFull, [planId]), + returnValue: _i6.Future>.value( + {}, ), ) - as _i3.IngredientDatabase); + as _i6.Future>); @override - List<_i7.Ingredient> get ingredients => + _i6.Future> createPlan(Map? data) => (super.noSuchMethod( - Invocation.getter(#ingredients), - returnValue: <_i7.Ingredient>[], - ) - as List<_i7.Ingredient>); - - @override - List<_i4.NutritionalPlan> get items => - (super.noSuchMethod( - Invocation.getter(#items), - returnValue: <_i4.NutritionalPlan>[], - ) - as List<_i4.NutritionalPlan>); - - @override - set database(_i3.IngredientDatabase? value) => super.noSuchMethod( - Invocation.setter(#database, value), - returnValueForMissingStub: null, - ); - - @override - set ingredients(List<_i7.Ingredient>? value) => super.noSuchMethod( - Invocation.setter(#ingredients, value), - returnValueForMissingStub: null, - ); - - @override - bool get hasListeners => - (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); - - @override - void clear() => super.noSuchMethod( - Invocation.method(#clear, []), - returnValueForMissingStub: null, - ); - - @override - _i4.NutritionalPlan findById(int? id) => - (super.noSuchMethod( - Invocation.method(#findById, [id]), - returnValue: _FakeNutritionalPlan_2( - this, - Invocation.method(#findById, [id]), + Invocation.method(#createPlan, [data]), + returnValue: _i6.Future>.value( + {}, ), ) - as _i4.NutritionalPlan); + as _i6.Future>); @override - _i5.Meal? findMealById(int? id) => - (super.noSuchMethod(Invocation.method(#findMealById, [id])) as _i5.Meal?); - - @override - _i10.Future fetchAndSetAllPlansSparse() => + _i6.Future updatePlan(int? id, Map? data) => (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansSparse, []), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + Invocation.method(#updatePlan, [id, data]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), ) - as _i10.Future); + as _i6.Future); @override - _i10.Future fetchAndSetAllPlansFull() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllPlansFull, []), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) - as _i10.Future); - - @override - _i10.Future<_i4.NutritionalPlan> fetchAndSetPlanSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanSparse, [planId]), - returnValue: _i10.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanSparse, [planId]), - ), - ), - ) - as _i10.Future<_i4.NutritionalPlan>); - - @override - _i10.Future<_i4.NutritionalPlan> fetchAndSetPlanFull(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetPlanFull, [planId]), - returnValue: _i10.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#fetchAndSetPlanFull, [planId]), - ), - ), - ) - as _i10.Future<_i4.NutritionalPlan>); - - @override - _i10.Future<_i4.NutritionalPlan> addPlan(_i4.NutritionalPlan? planData) => - (super.noSuchMethod( - Invocation.method(#addPlan, [planData]), - returnValue: _i10.Future<_i4.NutritionalPlan>.value( - _FakeNutritionalPlan_2( - this, - Invocation.method(#addPlan, [planData]), - ), - ), - ) - as _i10.Future<_i4.NutritionalPlan>); - - @override - _i10.Future editPlan(_i4.NutritionalPlan? plan) => - (super.noSuchMethod( - Invocation.method(#editPlan, [plan]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) - as _i10.Future); - - @override - _i10.Future deletePlan(int? id) => + _i6.Future<_i2.Response> deletePlan(int? id) => (super.noSuchMethod( Invocation.method(#deletePlan, [id]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) - as _i10.Future); - - @override - _i10.Future<_i5.Meal> addMeal(_i5.Meal? meal, int? planId) => - (super.noSuchMethod( - Invocation.method(#addMeal, [meal, planId]), - returnValue: _i10.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#addMeal, [meal, planId])), + returnValue: _i6.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deletePlan, [id])), ), ) - as _i10.Future<_i5.Meal>); + as _i6.Future<_i2.Response>); @override - _i10.Future<_i5.Meal> editMeal(_i5.Meal? meal) => + _i6.Future> createMeal(Map? data) => (super.noSuchMethod( - Invocation.method(#editMeal, [meal]), - returnValue: _i10.Future<_i5.Meal>.value( - _FakeMeal_3(this, Invocation.method(#editMeal, [meal])), + Invocation.method(#createMeal, [data]), + returnValue: _i6.Future>.value( + {}, ), ) - as _i10.Future<_i5.Meal>); + as _i6.Future>); @override - _i10.Future deleteMeal(_i5.Meal? meal) => - (super.noSuchMethod( - Invocation.method(#deleteMeal, [meal]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) - as _i10.Future); - - @override - _i10.Future<_i6.MealItem> addMealItem( - _i6.MealItem? mealItem, - _i5.Meal? meal, + _i6.Future> updateMeal( + int? id, + Map? data, ) => (super.noSuchMethod( - Invocation.method(#addMealItem, [mealItem, meal]), - returnValue: _i10.Future<_i6.MealItem>.value( - _FakeMealItem_4( + Invocation.method(#updateMeal, [id, data]), + returnValue: _i6.Future>.value( + {}, + ), + ) + as _i6.Future>); + + @override + _i6.Future<_i2.Response> deleteMeal(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMeal, [id]), + returnValue: _i6.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMeal, [id])), + ), + ) + as _i6.Future<_i2.Response>); + + @override + _i6.Future> createMealItem(Map? data) => + (super.noSuchMethod( + Invocation.method(#createMealItem, [data]), + returnValue: _i6.Future>.value( + {}, + ), + ) + as _i6.Future>); + + @override + _i6.Future<_i2.Response> deleteMealItem(int? id) => + (super.noSuchMethod( + Invocation.method(#deleteMealItem, [id]), + returnValue: _i6.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteMealItem, [id])), + ), + ) + as _i6.Future<_i2.Response>); + + @override + _i6.Future<_i3.Ingredient> fetchIngredient(int? id) => + (super.noSuchMethod( + Invocation.method(#fetchIngredient, [id]), + returnValue: _i6.Future<_i3.Ingredient>.value( + _FakeIngredient_1( this, - Invocation.method(#addMealItem, [mealItem, meal]), + Invocation.method(#fetchIngredient, [id]), ), ), ) - as _i10.Future<_i6.MealItem>); + as _i6.Future<_i3.Ingredient>); @override - _i10.Future deleteMealItem(_i6.MealItem? mealItem) => - (super.noSuchMethod( - Invocation.method(#deleteMealItem, [mealItem]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) - as _i10.Future); - - @override - _i10.Future clearIngredientCache() => - (super.noSuchMethod( - Invocation.method(#clearIngredientCache, []), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) - as _i10.Future); - - @override - _i10.Future cacheIngredient( - _i7.Ingredient? ingredient, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #cacheIngredient, - [ingredient], - {#database: database}, - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) - as _i10.Future); - - @override - _i10.Future<_i7.Ingredient> fetchIngredient( - int? ingredientId, { - _i3.IngredientDatabase? database, - }) => - (super.noSuchMethod( - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - returnValue: _i10.Future<_i7.Ingredient>.value( - _FakeIngredient_5( - this, - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, - ), - ), - ), - ) - as _i10.Future<_i7.Ingredient>); - - @override - _i10.Future> fetchWeightUnits( - int? ingredientId, - ) => - (super.noSuchMethod( - Invocation.method(#fetchWeightUnits, [ingredientId]), - returnValue: _i10.Future>.value( - <_i11.IngredientWeightUnit>[], - ), - ) - as _i10.Future>); - - @override - _i10.Future fetchIngredientsFromCache() => - (super.noSuchMethod( - Invocation.method(#fetchIngredientsFromCache, []), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) - as _i10.Future); - - @override - _i10.Future> searchIngredient( + _i6.Future> searchIngredient( String? name, { String? languageCode = 'en', - _i9.IngredientSearchLanguage? searchLanguage = _i9.IngredientSearchLanguage.current, + _i5.IngredientSearchLanguage? searchLanguage = _i5.IngredientSearchLanguage.current, bool? isVegan = false, bool? isVegetarian = false, }) => @@ -367,166 +193,163 @@ class MockNutritionPlansProvider extends _i1.Mock implements _i9.NutritionPlansP #isVegetarian: isVegetarian, }, ), - returnValue: _i10.Future>.value( - <_i7.Ingredient>[], + returnValue: _i6.Future>.value( + <_i3.Ingredient>[], ), ) - as _i10.Future>); + as _i6.Future>); @override - _i10.Future<_i7.Ingredient?> searchIngredientWithBarcode(String? barcode) => + _i6.Future<_i3.Ingredient?> searchIngredientWithBarcode(String? barcode) => (super.noSuchMethod( Invocation.method(#searchIngredientWithBarcode, [barcode]), - returnValue: _i10.Future<_i7.Ingredient?>.value(), + returnValue: _i6.Future<_i3.Ingredient?>.value(), ) - as _i10.Future<_i7.Ingredient?>); + as _i6.Future<_i3.Ingredient?>); @override - _i10.Future logMealToDiary(_i5.Meal? meal, DateTime? mealDateTime) => + _i6.Future> fetchWeightUnits( + int? ingredientId, + ) => (super.noSuchMethod( - Invocation.method(#logMealToDiary, [meal, mealDateTime]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + Invocation.method(#fetchWeightUnits, [ingredientId]), + returnValue: _i6.Future>.value( + <_i7.IngredientWeightUnit>[], + ), ) - as _i10.Future); + as _i6.Future>); @override - _i10.Future logIngredientToDiary( - _i6.MealItem? mealItem, - int? planId, [ - DateTime? dateTime, - ]) => + _i6.Future> fetchLogsForPlan(int? planId) => (super.noSuchMethod( - Invocation.method(#logIngredientToDiary, [ - mealItem, - planId, - dateTime, - ]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + Invocation.method(#fetchLogsForPlan, [planId]), + returnValue: _i6.Future>.value([]), ) - as _i10.Future); + as _i6.Future>); @override - _i10.Future deleteLog(int? logId, int? planId) => + _i6.Future> createLog(Map? data) => (super.noSuchMethod( - Invocation.method(#deleteLog, [logId, planId]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + Invocation.method(#createLog, [data]), + returnValue: _i6.Future>.value( + {}, + ), ) - as _i10.Future); + as _i6.Future>); @override - _i10.Future fetchAndSetLogs(_i4.NutritionalPlan? plan) => + _i6.Future<_i2.Response> deleteLog(int? id) => (super.noSuchMethod( - Invocation.method(#fetchAndSetLogs, [plan]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + Invocation.method(#deleteLog, [id]), + returnValue: _i6.Future<_i2.Response>.value( + _FakeResponse_0(this, Invocation.method(#deleteLog, [id])), + ), ) - as _i10.Future); + as _i6.Future<_i2.Response>); +} + +/// A class which mocks [IngredientRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockIngredientRepository extends _i1.Mock implements _i8.IngredientRepository { + MockIngredientRepository() { + _i1.throwOnMissingStub(this); + } @override - void addListener(_i12.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#addListener, [listener]), - returnValueForMissingStub: null, - ); + _i6.Stream<_i3.Ingredient?> watchById(int? id) => + (super.noSuchMethod( + Invocation.method(#watchById, [id]), + returnValue: _i6.Stream<_i3.Ingredient?>.empty(), + ) + as _i6.Stream<_i3.Ingredient?>); @override - void removeListener(_i12.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#removeListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); - - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method(#notifyListeners, []), - returnValueForMissingStub: null, - ); + _i6.Future<_i3.Ingredient?> getById(int? id) => + (super.noSuchMethod( + Invocation.method(#getById, [id]), + returnValue: _i6.Future<_i3.Ingredient?>.value(), + ) + as _i6.Future<_i3.Ingredient?>); } /// A class which mocks [BodyWeightRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockBodyWeightRepository extends _i1.Mock implements _i13.BodyWeightRepository { +class MockBodyWeightRepository extends _i1.Mock implements _i9.BodyWeightRepository { MockBodyWeightRepository() { _i1.throwOnMissingStub(this); } @override - _i10.Stream> watchAllDrift() => + _i6.Stream> watchAllDrift() => (super.noSuchMethod( Invocation.method(#watchAllDrift, []), - returnValue: _i10.Stream>.empty(), + returnValue: _i6.Stream>.empty(), ) - as _i10.Stream>); + as _i6.Stream>); @override - _i10.Future deleteLocalDrift(String? id) => + _i6.Future deleteLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDrift, [id]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), ) - as _i10.Future); + as _i6.Future); @override - _i10.Future updateLocalDrift(_i14.WeightEntry? entry) => + _i6.Future updateLocalDrift(_i10.WeightEntry? entry) => (super.noSuchMethod( Invocation.method(#updateLocalDrift, [entry]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), ) - as _i10.Future); + as _i6.Future); @override - _i10.Future addLocalDrift(_i14.WeightEntry? entry) => + _i6.Future addLocalDrift(_i10.WeightEntry? entry) => (super.noSuchMethod( Invocation.method(#addLocalDrift, [entry]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), ) - as _i10.Future); + as _i6.Future); } /// A class which mocks [UserProfileRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockUserProfileRepository extends _i1.Mock implements _i15.UserProfileRepository { +class MockUserProfileRepository extends _i1.Mock implements _i11.UserProfileRepository { MockUserProfileRepository() { _i1.throwOnMissingStub(this); } @override - _i10.Future<_i8.Profile> fetchProfile() => + _i6.Future<_i4.Profile> fetchProfile() => (super.noSuchMethod( Invocation.method(#fetchProfile, []), - returnValue: _i10.Future<_i8.Profile>.value( - _FakeProfile_6(this, Invocation.method(#fetchProfile, [])), + returnValue: _i6.Future<_i4.Profile>.value( + _FakeProfile_2(this, Invocation.method(#fetchProfile, [])), ), ) - as _i10.Future<_i8.Profile>); + as _i6.Future<_i4.Profile>); @override - _i10.Future saveProfile(_i8.Profile? profile) => + _i6.Future saveProfile(_i4.Profile? profile) => (super.noSuchMethod( Invocation.method(#saveProfile, [profile]), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), ) - as _i10.Future); + as _i6.Future); @override - _i10.Future verifyEmail() => + _i6.Future verifyEmail() => (super.noSuchMethod( Invocation.method(#verifyEmail, []), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), ) - as _i10.Future); + as _i6.Future); }