diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index e33bf89ba..9b3375276 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -17,6 +17,7 @@ android:label="talawa" android:icon="@mipmap/ic_launcher" android:allowBackup="false" + android:enableOnBackInvokedCallback="true" tools:replace="android:label"> (); ///GetIt for Connectivity. final connectivity = locator(); +///GetIt for ConnectivityService. +final connectivityService = locator(); + ///GetIt for OrganizationService. final organizationService = locator(); @@ -84,7 +89,7 @@ final sessionManager = locator(); /// /// **returns**: /// None -void setupLocator() { +Future setupLocator() async { //services locator.registerSingleton(NavigationService()); @@ -117,9 +122,13 @@ void setupLocator() { //databaseMutationFunction locator.registerSingleton(DataBaseMutationFunctions()); + locator.registerSingleton(ConnectivityService()); + //queries locator.registerSingleton(Queries()); + locator.registerFactory(() => AppConnectivity()); + //Page viewModels locator.registerFactory(() => DemoViewModel()); // locator.registerFactory(() => OrganizationFeedViewModel()); diff --git a/lib/main.dart b/lib/main.dart index 2237cf4d7..990efb31a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -7,7 +7,6 @@ import 'package:hive/hive.dart'; import 'package:path_provider/path_provider.dart' as path; import 'package:provider/provider.dart'; import 'package:quick_actions/quick_actions.dart'; -import 'package:talawa/constants/custom_theme.dart'; import 'package:talawa/constants/quick_actions.dart'; import 'package:talawa/locator.dart'; import 'package:talawa/models/asymetric_keys/asymetric_keys.dart'; @@ -17,6 +16,7 @@ import 'package:talawa/plugins/fetch_plugin_list.dart'; import 'package:talawa/router.dart' as router; import 'package:talawa/utils/app_localization.dart'; import 'package:talawa/view_model/base_view_model.dart'; +import 'package:talawa/view_model/connectivity_view_model.dart'; import 'package:talawa/view_model/lang_view_model.dart'; import 'package:talawa/view_model/theme_view_model.dart'; import 'package:talawa/views/base_view.dart'; @@ -39,6 +39,7 @@ Future main() async { await Hive.openBox('url'); setupLocator(); + // The runApp() function takes the given Widget and makes it the root of the widget tree. runApp(MyApp()); } @@ -118,55 +119,46 @@ class _MyAppState extends State { return BaseView( onModelReady: (model) => model.initialize(), builder: (context, model, child) { - return MaterialApp( - locale: langModel.appLocal, - supportedLocales: [ - const Locale('en', 'US'), - const Locale('es', 'ES'), - const Locale('fr', 'FR'), - const Locale('hi', 'IN'), - const Locale('zh', 'CN'), - const Locale('de', 'DE'), - const Locale('ja', 'JP'), - const Locale('pt', 'PT'), - ], - localizationsDelegates: [ - AppLocalizations.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - title: 'Talawa', - theme: Provider.of(context).isdarkTheme - ? TalawaTheme.darkTheme - : TalawaTheme.lightTheme, - debugShowCheckedModeBanner: false, - navigatorKey: navigationService.navigatorKey, - onGenerateRoute: router.generateRoute, - localeResolutionCallback: - (Locale? locale, Iterable supportedLocales) { - if (locale == null) { - debugPrint("*language locale is null!!!"); - return supportedLocales.first; - } - for (final Locale supportedLocale in supportedLocales) { - if (supportedLocale.languageCode == locale.languageCode || - supportedLocale.countryCode == locale.countryCode) { - return supportedLocale; - } - } - return supportedLocales.first; - }, - initialRoute: '/', - onGenerateInitialRoutes: (String initialRouteName) { - return [ - router.generateRoute( - RouteSettings( - name: '/', - arguments: mainScreenQuickActionindex, - ), - ), - ]; + return BaseView( + onModelReady: (connectivityModel) => + connectivityModel.initialise(), + builder: (context, connectivityModel, child) { + return MaterialApp( + locale: langModel.appLocal, + supportedLocales: [ + const Locale('en', 'US'), + const Locale('es', 'ES'), + const Locale('fr', 'FR'), + const Locale('hi', 'IN'), + const Locale('zh', 'CN'), + const Locale('de', 'DE'), + const Locale('ja', 'JP'), + const Locale('pt', 'PT'), + ], + localizationsDelegates: [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + title: 'Talawa', + theme: Provider.of(context).theme, + debugShowCheckedModeBanner: false, + navigatorKey: navigationService.navigatorKey, + onGenerateRoute: router.generateRoute, + localeResolutionCallback: langModel.localeResoultion, + initialRoute: '/', + onGenerateInitialRoutes: (String initialRouteName) { + return [ + router.generateRoute( + RouteSettings( + name: '/', + arguments: mainScreenQuickActionindex, + ), + ), + ]; + }, + ); }, ); }, diff --git a/lib/models/events/event_venue.dart b/lib/models/events/event_venue.dart new file mode 100644 index 000000000..0edc779be --- /dev/null +++ b/lib/models/events/event_venue.dart @@ -0,0 +1,54 @@ +/// The `Venue` class represents a venue for events. +class Venue { + /// Constructs a `Venue` instance. + /// + /// [id] is the unique identifier of the venue. + /// [capacity] is the maximum number of people the venue can accommodate. + /// [description] provides additional details about the venue. + /// [imageUrl] is the URL of the venue's image. + /// [name] is the name of the venue. + /// [organizationId] is the identifier of the organization to which the venue belongs. + Venue({ + this.id, + this.capacity, + this.description, + this.imageUrl, + this.name, + this.organizationId, + }); + + /// Creates a `Venue` instance from a JSON object. + /// + /// The [json] parameter is a map containing the venue data. + /// + /// Returns an instance of `Venue`. + factory Venue.fromJson(Map json) { + return Venue( + id: json['_id'] as String?, + capacity: json['capacity'] as int?, + description: json['description'] as String?, + imageUrl: json['imageUrl'] as String? ?? '', + name: json['name'] as String?, + organizationId: + (json['organization'] as Map?)?['_id'] as String?, + ); + } + + /// The unique identifier of the venue. + final String? id; + + /// The maximum number of people the venue can accommodate. + final int? capacity; + + /// Provides additional details about the venue. + final String? description; + + /// The URL of the venue's image. + final String? imageUrl; + + /// The name of the venue. + final String? name; + + /// The identifier of the organization to which the venue belongs. + final String? organizationId; +} diff --git a/lib/services/database_mutation_functions.dart b/lib/services/database_mutation_functions.dart index 5760616c2..2a35606bc 100644 --- a/lib/services/database_mutation_functions.dart +++ b/lib/services/database_mutation_functions.dart @@ -5,6 +5,7 @@ import 'package:talawa/enums/enums.dart'; import 'package:talawa/locator.dart'; import 'package:talawa/models/organization/org_info.dart'; import 'package:talawa/utils/queries.dart'; +import 'package:talawa/view_model/connectivity_view_model.dart'; /// DataBaseMutationFunctions class provides different services that are under the context of graphQL mutations and queries. /// @@ -34,8 +35,10 @@ class DataBaseMutationFunctions { /// **returns**: /// None void init() { + graphqlConfig.getOrgUrl(); clientNonAuth = graphqlConfig.clientToQuery(); clientAuth = graphqlConfig.authClient(); + print('ajkjkdjkjkdjieiejie'); _query = Queries(); } @@ -104,10 +107,7 @@ class DataBaseMutationFunctions { debugPrint(exception.linkException.toString()); if (showSnackBar) { WidgetsBinding.instance.addPostFrameCallback( - (_) => navigationService.showTalawaErrorSnackBar( - "Server not running/wrong url", - MessageType.info, - ), + (_) => AppConnectivity.showSnackbar(isOnline: false), ); } return false; diff --git a/lib/services/event_service.dart b/lib/services/event_service.dart index 6b3146ec8..75bbff897 100644 --- a/lib/services/event_service.dart +++ b/lib/services/event_service.dart @@ -24,6 +24,7 @@ import 'package:talawa/widgets/custom_progress_dialog.dart'; class EventService { EventService() { _eventStream = _eventStreamController.stream.asBroadcastStream(); + print(_eventStream); _currentOrg = _userConfig.currentOrg; _userConfig.initialiseStream(); setOrgStreamSubscription(); diff --git a/lib/services/third_party_service/connectivity_service.dart b/lib/services/third_party_service/connectivity_service.dart new file mode 100644 index 000000000..d1e95ff5d --- /dev/null +++ b/lib/services/third_party_service/connectivity_service.dart @@ -0,0 +1,116 @@ +import 'dart:async'; + +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:http/http.dart' as http; +import 'package:talawa/locator.dart'; + +/// This class provides services related to network connectivity monitoring and handling. +/// +/// It includes methods for: +/// * Initializing the network service - [initConnectivity] +/// * Monitoring connectivity changes - [enableSubscription] +/// * Handling online and offline states - [handleOnline], [handleOffline] +/// * Checking reachability of a given URI - [isReachable] +/// * Handling the device's connectivity status - [handleConnection] +/// * Checking if the device has any type of network connection - [hasConnection] +class ConnectivityService { + /// Stream controller for network status changes. + late StreamController connectionStatusController; + + /// Getter for the stream of connection status changes. + Stream get connectionStream => + connectionStatusController.stream; + + /// Checks the current internet connectivity status of the device. + /// + /// **params**: + /// None + /// + /// **returns**: + /// * `Future`: indicates if the url is reachable. + Future getConnectionType() async { + final result = await connectivity.checkConnectivity(); + return result; + } + + /// Client to access internet. + late final http.Client _client; + + /// This function initializes connectivity monitoring. + /// + /// **params**: + /// * `client`: An instance of `http.Client` to make the HTTP request. + /// + /// **returns**: + /// None + Future initConnectivity({required http.Client client}) async { + _client = client; + connectionStatusController = StreamController(); + + /// Listen for future changes in connectivity + enableSubscription(); + } + + /// This function enables the subscription to connectivity changes. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None + Future enableSubscription() async { + connectivity.onConnectivityChanged.listen( + (ConnectivityResult result) { + print(result); + connectionStatusController.add(result); + }, + onError: (error) { + // Handle errors during listening for changes + print('Error listening for connectivity changes: $error'); + }, + ); + } + + /// This function checks if a given URI is reachable within a specified timeout period. + /// + /// Specifically designed to + /// + /// **params**: + /// * `client`: An instance of `http.Client` to make the HTTP request. + /// * `uriString`: An optional `String` specifying the URI to check. + /// Defaults to 'org link' if not provided. + /// + /// **returns**: + /// * `Future`: indicates if the url is reachable. + Future isReachable({ + http.Client? client, + String? uriString, + }) async { + try { + client ??= _client; + await client + .get(Uri.parse(uriString ?? graphqlConfig.httpLink.uri.toString())) + .timeout(const Duration(seconds: 30)); + return true; + } catch (e) { + print('Timeout while checking reachability: $e'); + return false; + } + } + + /// This function checks if the device currently has any type of network connection. + /// + /// **params**: + /// None + /// + /// **returns**: + /// * `Future`: indicating whether the device has a network connection. + Future hasConnection() async { + try { + final result = await getConnectionType(); + return result != ConnectivityResult.none; + } catch (e) { + return false; + } + } +} diff --git a/lib/services/user_config.dart b/lib/services/user_config.dart index 047159587..796399238 100644 --- a/lib/services/user_config.dart +++ b/lib/services/user_config.dart @@ -89,7 +89,7 @@ class UserConfig { _currentUser = User(id: 'null', authToken: 'null'); return false; } - databaseFunctions.initClientNonAuth(); + databaseFunctions.init(); await sessionManager.refreshSession(); // generate access token graphqlConfig.getToken().then((value) async { diff --git a/lib/utils/queries.dart b/lib/utils/queries.dart index 942490911..7fc4783a5 100644 --- a/lib/utils/queries.dart +++ b/lib/utils/queries.dart @@ -589,4 +589,28 @@ query { } '''; } + + /// Query to get the list of Venues in an organisation. + /// + /// **params**: + /// None + /// + /// **returns**: + /// * `String`: Query in string form, to be passed to graphql client. + String venueListQuery() { + return """ + query GetVenueByOrgId(\$orgId: ID!, \$first: Int, \$orderBy: VenueOrderByInput, \$where: VenueWhereInput) { + getVenueByOrgId(orgId: \$orgId, first: \$first, orderBy: \$orderBy, where: \$where) { + _id + capacity + name + description + imageUrl + organization { + _id + } + } + } + """; + } } diff --git a/lib/view_model/after_auth_view_models/event_view_models/create_event_view_model.dart b/lib/view_model/after_auth_view_models/event_view_models/create_event_view_model.dart index dd2ec28dd..1a6d69b5e 100644 --- a/lib/view_model/after_auth_view_models/event_view_models/create_event_view_model.dart +++ b/lib/view_model/after_auth_view_models/event_view_models/create_event_view_model.dart @@ -1,8 +1,10 @@ import 'dart:io'; import 'package:flutter/material.dart'; +import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:intl/intl.dart'; import 'package:talawa/constants/recurrence_values.dart'; import 'package:talawa/locator.dart'; +import 'package:talawa/models/events/event_venue.dart'; import 'package:talawa/models/organization/org_info.dart'; import 'package:talawa/models/user/user_info.dart'; import 'package:talawa/services/event_service.dart'; @@ -357,4 +359,33 @@ class CreateEventViewModel extends BaseModel { eventEndDate = selectedEndDate; notifyListeners(); } + + /// Fetches the list of venues registered to an organisation. + /// + /// **params**: + /// None + /// + /// **returns**: + /// * `Future>`: Returns the list of venues in an organisation. + Future> fetchVenues() async { + final String query = queries.venueListQuery(); + final QueryResult result = await databaseFunctions.gqlAuthQuery( + query, + variables: { + "orgId": _currentOrg.id, + }, + ) as QueryResult; + + if (result.data == null) { + return []; + } + final data = result.data!; + final List venuesList = data['getVenueByOrgId'] as List; + + final List venues = venuesList.map((venue) { + return Venue.fromJson(venue as Map); + }).toList(); + + return venues; + } } diff --git a/lib/view_model/after_auth_view_models/event_view_models/explore_events_view_model.dart b/lib/view_model/after_auth_view_models/event_view_models/explore_events_view_model.dart index 7b792d7be..a694ab781 100644 --- a/lib/view_model/after_auth_view_models/event_view_models/explore_events_view_model.dart +++ b/lib/view_model/after_auth_view_models/event_view_models/explore_events_view_model.dart @@ -21,7 +21,7 @@ class ExploreEventsViewModel extends BaseModel { bool demoMode; final _eventService = locator(); - late StreamSubscription _eventStreamSubscription; + StreamSubscription? _eventStreamSubscription; String _chosenValue = 'All Events'; String _emptyListMessage = "Looks like there aren't any events."; @@ -91,6 +91,7 @@ class ExploreEventsViewModel extends BaseModel { Future initialise() async { setState(ViewState.busy); if (!demoMode) { + print(demoMode); _currentOrganizationStreamSubscription = userConfig.currentOrgInfoStream .listen((updatedOrganization) => refreshEvents()); await _eventService.getEvents(); @@ -249,7 +250,7 @@ class ExploreEventsViewModel extends BaseModel { @override void dispose() { - _eventStreamSubscription.cancel(); + _eventStreamSubscription?.cancel(); _currentOrganizationStreamSubscription.cancel(); super.dispose(); } diff --git a/lib/view_model/connectivity_view_model.dart b/lib/view_model/connectivity_view_model.dart new file mode 100644 index 000000000..143e6c069 --- /dev/null +++ b/lib/view_model/connectivity_view_model.dart @@ -0,0 +1,156 @@ +import 'dart:async'; + +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:talawa/locator.dart'; +import 'package:talawa/view_model/base_view_model.dart'; +import 'package:talawa/view_model/main_screen_view_model.dart'; + +/// This class provides services related to network connectivity monitoring and handling. +/// +/// It leverages the `connectivity` package to track the device's internet connection status. +/// It offers methods to: +/// +/// * Initialize the AppConnectivity: [initialise] +/// * Subscribe to connectivity changes: [enableSubscription] +/// * Handle online and offline states: [handleOnline], [handleOffline] +/// * Handle the device's overall connectivity status: [handleConnection] +/// * Triggers the snackbar UI to show online status.: [showSnackbar] +class AppConnectivity extends BaseModel { + /// Stream from [ConnectivityService]. + late final Stream connectivityStream; + + /// Subscription of the [connectivityStream] + StreamSubscription? _subscription; + + /// Initializes the [AppConnectivity]. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None + Future initialise() async { + await connectivityService.initConnectivity(client: http.Client()); + connectivityStream = connectivityService.connectionStream; + enableSubscription(); + } + + /// Subscribes to [connectivityStream] of [ConnectivityService]. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None + void enableSubscription() { + try { + _subscription = connectivityStream.listen((ConnectivityResult result) { + handleConnection(result); + }); + } catch (e) { + print("Error subscribing to connectivity stream: $e"); + } + } + + /// This function handles the device's connectivity status based on the provided [ConnectivityResult]. + /// + /// **params**: + /// * `result`: A [ConnectivityResult] indicating the current connectivity status. + /// + /// **returns**: + /// None + Future handleConnection(ConnectivityResult result) async { + if (MainScreenViewModel.demoMode) { + handleOffline(); + return; + } + if (result != ConnectivityResult.none && + await connectivityService.isReachable()) { + handleOnline(); + } else { + handleOffline(); + } + } + + /// This function handles the actions to be taken when the device is online. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None + Future handleOnline() async { + showSnackbar(isOnline: true); + databaseFunctions.init(); + } + + /// This function handles the actions to be taken when the device is offline. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None + Future handleOffline() async { + showSnackbar(isOnline: false); + databaseFunctions.init(); + } + + /// Triggers the snackbar UI to show online status. + /// + /// **params**: + /// * `isOnline`: online status of the device. + /// + /// **returns**: + /// None + static void showSnackbar({required bool isOnline}) { + final context = navigationService.navigatorKey.currentContext; + if (context != null) { + final TextStyle customStyle = Theme.of(context).textTheme.bodyMedium!; + if (isOnline) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + duration: const Duration(seconds: 5), + backgroundColor: Colors.green, + content: Text( + 'You are back online!', + style: customStyle, + ), + ), + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + duration: const Duration(seconds: 5), + backgroundColor: const Color.fromRGBO(65, 65, 66, 1), + content: RichText( + text: TextSpan( + children: [ + TextSpan( + text: 'You are ', + style: Theme.of(context) + .textTheme + .bodySmall! + .copyWith(color: Colors.white), + ), + TextSpan( + text: 'Offline!', + style: customStyle.copyWith(color: Colors.green), + ), + ], + ), + ), + ), + ); + } + } + } + + @override + void dispose() { + _subscription?.cancel(); + super.dispose(); + } +} diff --git a/lib/view_model/lang_view_model.dart b/lib/view_model/lang_view_model.dart index 061cf63e6..53911ad04 100644 --- a/lib/view_model/lang_view_model.dart +++ b/lib/view_model/lang_view_model.dart @@ -62,6 +62,29 @@ class AppLanguage extends BaseModel { notifyListeners(); } + /// This function fetches the appropriate locale for the user's app based on the provided locale and supported locales. + /// + /// **params**: + /// * `locale`: (`Locale?`): The locale to be resolved. Can be null. + /// * `supportedLocales`: (`Iterable`): The list of supported locales in the app. + /// + /// **returns**: + /// * `Locale`: The resolved locale that matches either the language code or the country code of the provided locale. + /// If no match is found or the provided locale is null, the first supported locale is returned. + Locale localeResoultion(Locale? locale, Iterable supportedLocales) { + if (locale == null) { + debugPrint("*language locale is null!!!"); + return supportedLocales.first; + } + for (final Locale supportedLocale in supportedLocales) { + if (supportedLocale.languageCode == locale.languageCode || + supportedLocale.countryCode == locale.countryCode) { + return supportedLocale; + } + } + return supportedLocales.first; + } + /// This function change the app default language. /// /// **params**: diff --git a/lib/view_model/main_screen_view_model.dart b/lib/view_model/main_screen_view_model.dart index 2cb601310..44830316f 100644 --- a/lib/view_model/main_screen_view_model.dart +++ b/lib/view_model/main_screen_view_model.dart @@ -150,7 +150,7 @@ class MainScreenViewModel extends BaseModel { final List targets = []; /// flag to represent if app is in demoMode. - bool demoMode = false; + static bool demoMode = false; /// flag to represent if app is in testMode. bool testMode = false; @@ -174,7 +174,7 @@ class MainScreenViewModel extends BaseModel { bool testMode = false, }) { this.testMode = testMode; - this.demoMode = demoMode; + MainScreenViewModel.demoMode = demoMode; currentPageIndex = mainScreenIndex; showAppTour = fromSignUp || demoMode; context = ctx; diff --git a/lib/view_model/theme_view_model.dart b/lib/view_model/theme_view_model.dart index af40c9a34..67378ceb0 100644 --- a/lib/view_model/theme_view_model.dart +++ b/lib/view_model/theme_view_model.dart @@ -1,21 +1,33 @@ -// ignore_for_file: talawa_api_doc -// ignore_for_file: talawa_good_doc_comments - +import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:talawa/constants/custom_theme.dart'; import 'package:talawa/view_model/base_view_model.dart'; -/// AppTheme class is a type of View Model to serve data from modal to views in the context of App Themes. +/// AppTheme class is a type of ViewModel to serve data from model to views in the context of App Themes. /// /// Methods include: /// * `switchTheme` class AppTheme extends BaseModel { + /// Key for dynamic theme. final String key = "DynamicTheme"; late SharedPreferences _pref; late bool _isDarkMode; + + /// flag to check darkMode. bool get isdarkTheme => _isDarkMode; - // initializer + /// getter to fetch current theme. + ThemeData get theme => + isdarkTheme ? TalawaTheme.darkTheme : TalawaTheme.lightTheme; + + /// Initializes the theme settings. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None void initialize() { _isDarkMode = true; _loadFromPrefs(); @@ -23,24 +35,48 @@ class AppTheme extends BaseModel { /// This function switches the app theme. /// - /// * `Dart` -> `Light` - /// * `Light` -> `Dark` + /// **params**: + /// * `isOn`: `bool` type, the state to switch the theme to (true for Dark, false for Light). + /// + /// **returns**: + /// None void switchTheme({required bool isOn}) { _isDarkMode = isOn; _saveToPrefs(); notifyListeners(); } + /// Initializes the SharedPreferences instance. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None Future _initPrefs() async { _pref = await SharedPreferences.getInstance(); } + /// Loads the theme preference from SharedPreferences. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None Future _loadFromPrefs() async { await _initPrefs(); _isDarkMode = _pref.getBool(key) ?? true; notifyListeners(); } + /// Saves the theme preference to SharedPreferences. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None Future _saveToPrefs() async { await _initPrefs(); _pref.setBool(key, _isDarkMode); diff --git a/lib/views/after_auth_screens/events/create_event_page.dart b/lib/views/after_auth_screens/events/create_event_page.dart index 99cd94457..878e31a48 100644 --- a/lib/views/after_auth_screens/events/create_event_page.dart +++ b/lib/views/after_auth_screens/events/create_event_page.dart @@ -2,6 +2,8 @@ import 'package:flutter/material.dart'; import 'package:talawa/constants/recurrence_values.dart'; import 'package:talawa/enums/enums.dart'; import 'package:talawa/locator.dart'; +import 'package:talawa/models/events/event_venue.dart'; +import 'package:talawa/services/graphql_config.dart'; import 'package:talawa/services/navigation_service.dart'; import 'package:talawa/services/size_config.dart'; import 'package:talawa/utils/app_localization.dart'; @@ -9,6 +11,7 @@ import 'package:talawa/utils/validators.dart'; import 'package:talawa/view_model/after_auth_view_models/event_view_models/create_event_view_model.dart'; import 'package:talawa/view_model/main_screen_view_model.dart'; import 'package:talawa/views/after_auth_screens/events/create_event_form.dart'; +import 'package:talawa/views/after_auth_screens/events/venue_bottom_sheet.dart'; import 'package:talawa/views/base_view.dart'; import 'package:talawa/widgets/add_members_bottom_sheet.dart'; import 'package:talawa/widgets/date_time_picker.dart'; @@ -26,6 +29,9 @@ class CreateEventPage extends StatefulWidget { /// _CreateEventPageState returns a widget for a Page to Creatxe the Event in the Organization. class _CreateEventPageState extends State { + /// venue selected by the user. + Venue? selectedVenue; + @override Widget build(BuildContext context) { final TextStyle subtitleTextStyle = @@ -133,6 +139,104 @@ class _CreateEventPageState extends State { ), SizedBox(height: SizeConfig.screenHeight! * 0.013), const Divider(), + GestureDetector( + onTap: () async { + final List venues = await model.fetchVenues(); + if (!context.mounted) return; + final Venue? selected = + await showModalBottomSheet( + context: context, + isScrollControlled: true, + builder: (context) { + return VenueBottomSheet(venues: venues); + }, + ); + if (selected != null) { + setState(() { + selectedVenue = selected; + }); + } + }, + child: selectedVenue == null + ? Container( + height: 50.0, + padding: + const EdgeInsets.symmetric(horizontal: 16.0), + child: Row( + children: [ + const Icon(Icons.add_location), + const SizedBox(width: 10.0), + Text( + AppLocalizations.of(context)! + .strictTranslate('Add Venue'), + style: + Theme.of(context).textTheme.titleMedium, + ), + ], + ), + ) + : Container( + height: 100.0, + padding: + const EdgeInsets.symmetric(horizontal: 16.0), + child: Row( + children: [ + if (selectedVenue!.imageUrl!.isNotEmpty) + Image.network( + selectedVenue!.imageUrl!.replaceAll( + 'http://localhost:4000', + GraphqlConfig.orgURI! + .replaceFirst('/graphql', ''), + ), + ) + else + Image.asset( + 'assets/images/defaultImg.png', + width: 50, + height: 50, + fit: BoxFit.cover, + ), + const SizedBox(width: 10.0), + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + Text( + selectedVenue!.name!, + style: Theme.of(context) + .textTheme + .titleMedium, + ), + Text( + 'Capacity: ${selectedVenue!.capacity}', + style: Theme.of(context) + .textTheme + .bodySmall, + ), + ], + ), + ), + Column( + children: [ + IconButton( + onPressed: () { + setState(() { + selectedVenue = null; + }); + }, + icon: const Icon(Icons.cancel), + ), + const Icon(Icons.edit), + ], + ), + ], + ), + ), + ), + const Divider(), SizedBox( width: SizeConfig.screenWidth, child: Wrap( diff --git a/lib/views/after_auth_screens/events/venue_bottom_sheet.dart b/lib/views/after_auth_screens/events/venue_bottom_sheet.dart new file mode 100644 index 000000000..293f186c6 --- /dev/null +++ b/lib/views/after_auth_screens/events/venue_bottom_sheet.dart @@ -0,0 +1,158 @@ +import 'package:flutter/material.dart'; +import 'package:talawa/models/events/event_venue.dart'; +import 'package:talawa/utils/app_localization.dart'; +import 'package:talawa/widgets/venue_card.dart'; + +/// a_line_ending_with_end_punctuation. +class VenueBottomSheet extends StatefulWidget { + const VenueBottomSheet({super.key, required this.venues}); + + /// a_line_ending_with_end_punctuation. + final List venues; + + @override + _VenueBottomSheetState createState() => _VenueBottomSheetState(); +} + +class _VenueBottomSheetState extends State { + /// Controller for the search text field. + TextEditingController searchController = TextEditingController(); + + /// The list of venues filtered based on the search query. + List filteredVenues = []; + + /// Whether the search field is currently active. + bool isSearching = false; + + /// The venue that is currently selected by the user. + Venue? selectedVenue; + + @override + void initState() { + super.initState(); + filteredVenues = widget.venues; + } + + /// Filters the venues based on the search query. + /// + /// **params**: + /// * `query`: The search query entered by the user. + /// + /// **returns**: + /// None + void _searchVenue(String query) { + setState(() { + filteredVenues = widget.venues + .where( + (venue) => venue.name!.toLowerCase().contains(query.toLowerCase()), + ) + .toList(); + }); + } + + /// Toggles the search field on and off. + /// + /// **params**: + /// None + /// + /// **returns**: + /// None + void _toggleSearch() { + setState(() { + isSearching = !isSearching; + if (!isSearching) { + searchController.clear(); + filteredVenues = widget.venues; + } + }); + } + + /// Selects a venue and marks it as the currently selected venue. + /// + /// **params**: + /// * `venue`: The venue to select. + /// + /// **returns**: + /// None + void _selectVenue(Venue venue) { + setState(() { + selectedVenue = venue; + }); + } + + @override + Widget build(BuildContext context) { + return GestureDetector( + key: const Key('gestureDetector1'), + onTap: () { + FocusScope.of(context).unfocus(); + }, + child: Container( + height: MediaQuery.of(context).size.height * 0.95, + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + if (!isSearching) + Expanded( + child: Center( + child: Text( + AppLocalizations.of(context)! + .strictTranslate('Add Venue'), + style: Theme.of(context).textTheme.headlineMedium, + ), + ), + ), + if (isSearching) + Expanded( + child: TextField( + controller: searchController, + onChanged: _searchVenue, + decoration: const InputDecoration( + hintText: 'Search Venue', + prefixIcon: Icon(Icons.search), + ), + ), + ), + if (selectedVenue != null) + IconButton( + icon: const Icon(Icons.check), + onPressed: () { + Navigator.of(context).pop(selectedVenue); + }, + ), + IconButton( + icon: Icon(isSearching ? Icons.close : Icons.search), + onPressed: _toggleSearch, + ), + ], + ), + const SizedBox(height: 16.0), + if (widget.venues.isEmpty) + const Center(child: Text('No Venues added yet')) + else if (filteredVenues.isEmpty) + const Center(child: Text('No venues available')) + else + Expanded( + child: ListView.builder( + itemCount: filteredVenues.length, + itemBuilder: (context, index) { + final venue = filteredVenues[index]; + return GestureDetector( + onTap: () => _selectVenue(venue), + child: VenueCard( + venue: venue, + isSelected: selectedVenue == venue, + ), + ); + }, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/venue_card.dart b/lib/widgets/venue_card.dart new file mode 100644 index 000000000..7d2a1e685 --- /dev/null +++ b/lib/widgets/venue_card.dart @@ -0,0 +1,130 @@ +import 'package:flutter/material.dart'; +import 'package:talawa/models/events/event_venue.dart'; +import 'package:talawa/services/graphql_config.dart'; +import 'package:talawa/services/size_config.dart'; + +/// This class returns the VenueCard widget. +class VenueCard extends StatelessWidget { + const VenueCard({ + super.key, + required this.venue, + this.isSelected = false, + }); + + /// The venue object containing details about the venue. + final Venue venue; + + /// Indicates whether the venue card is selected. + /// + /// When true, the venue card will visually indicate that it is selected. + final bool isSelected; + + @override + Widget build(BuildContext context) { + final orgURI = GraphqlConfig.orgURI!.replaceFirst('/graphql', ''); + final imageURl = + venue.imageUrl!.replaceAll('http://localhost:4000', orgURI); + + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Stack( + children: [ + Card( + surfaceTintColor: Theme.of(context).colorScheme.secondaryContainer, + shape: const RoundedRectangleBorder( + side: BorderSide.none, + ), + elevation: 3, + color: isSelected + ? Colors.blue.withOpacity(0.3) + : Theme.of(context).primaryColor, + child: Column( + children: [ + AspectRatio( + aspectRatio: 2.5, + child: Container( + key: const Key('image_container'), + height: SizeConfig.screenHeight! * 0.11, + width: double.infinity, + decoration: BoxDecoration( + color: Colors.grey.withOpacity(0.3), + image: DecorationImage( + fit: BoxFit.fitWidth, + alignment: FractionalOffset.topCenter, + image: venue.imageUrl!.isNotEmpty + ? NetworkImage(imageURl) + : const AssetImage('assets/images/defaultImg.png') + as ImageProvider, + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.all(10), + child: Column( + children: [ + Row( + children: [ + SizedBox( + width: SizeConfig.screenWidth! * 0.48, + child: Text( + venue.name!, + style: Theme.of(context).textTheme.headlineSmall, + ), + ), + const Icon( + Icons.people, + size: 22, + ), + Padding( + padding: const EdgeInsets.only(left: 8), + child: Text( + 'Capacity: ${venue.capacity}', + style: Theme.of(context).textTheme.bodyMedium, + ), + ), + ], + ), + SizedBox( + height: SizeConfig.screenHeight! * 0.006, + ), + Row( + children: [ + const Icon( + Icons.description, + size: 12, + ), + SizedBox( + width: SizeConfig.screenWidth! * 0.015, + ), + Expanded( + child: Text( + venue.description!, + style: Theme.of(context).textTheme.bodySmall, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.left, + maxLines: 3, + ), + ), + ], + ), + ], + ), + ), + ], + ), + ), + if (isSelected) + const Positioned( + top: 10, + right: 10, + child: Icon( + Icons.check_circle, + color: Colors.green, + ), + ), + ], + ), + ); + } +} diff --git a/test/constants/quick_actions_test.dart b/test/constants/quick_actions_test.dart new file mode 100644 index 000000000..44e69b3a2 --- /dev/null +++ b/test/constants/quick_actions_test.dart @@ -0,0 +1,32 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:quick_actions/quick_actions.dart'; +import 'package:talawa/constants/quick_actions.dart'; + +void main() { + const eventAction = ShortcutItem( + type: "events_action", + localizedTitle: "Events", + icon: "event_icon", + ); + + const feedAction = ShortcutItem( + type: "feed_action", + localizedTitle: "NewsFeed", + icon: "newsfeed_icon", + ); + + const chatAction = ShortcutItem( + type: "chat_action", + localizedTitle: "Messages", + icon: "chat_icon", + ); + + final desiredActions = [ + eventAction, + feedAction, + chatAction, + ]; + test('ShortcutMenu', () { + expect(ShortCutMenu.quickActionsList, desiredActions); + }); +} diff --git a/test/helpers/test_helpers.dart b/test/helpers/test_helpers.dart index dfdae1de6..13fa5a84a 100644 --- a/test/helpers/test_helpers.dart +++ b/test/helpers/test_helpers.dart @@ -27,6 +27,7 @@ import 'package:talawa/services/org_service.dart'; import 'package:talawa/services/post_service.dart'; import 'package:talawa/services/session_manager.dart'; import 'package:talawa/services/size_config.dart'; +import 'package:talawa/services/third_party_service/connectivity_service.dart'; import 'package:talawa/services/third_party_service/multi_media_pick_service.dart'; import 'package:talawa/services/user_config.dart'; import 'package:talawa/utils/event_queries.dart'; @@ -50,6 +51,7 @@ import 'package:talawa/view_model/widgets_view_models/like_button_view_model.dar import 'package:talawa/view_model/widgets_view_models/progress_dialog_view_model.dart'; import '../service_tests/image_service_test.dart'; +import '../service_tests/third_party_service_test.dart/connectivity_service_test.dart'; import '../service_tests/user_config_test.dart'; import '../views/main_screen_test.dart'; import 'test_helpers.mocks.dart'; @@ -68,7 +70,6 @@ import 'test_helpers.mocks.dart'; MockSpec(onMissingStub: OnMissingStub.returnDefault), MockSpec(onMissingStub: OnMissingStub.returnDefault), MockSpec(onMissingStub: OnMissingStub.returnDefault), - MockSpec(onMissingStub: OnMissingStub.returnDefault), MockSpec( onMissingStub: OnMissingStub.returnDefault, ), @@ -650,20 +651,35 @@ EventService getAndRegisterEventService() { return service; } -/// `getAndRegisterConnectivityService` returns a mock instance of the `Connectivity` class. +/// `getAndRegisterConnectivity` returns a mock instance of the `Connectivity` class. /// /// **params**: /// None /// /// **returns**: /// * `Connectivity`: A mock instance of the `Connectivity` class. -Connectivity getAndRegisterConnectivityService() { +Connectivity getAndRegisterConnectivity() { _removeRegistrationIfExists(); final service = MockConnectivity(); locator.registerSingleton(service); return service; } +/// `getAndRegisterConnectivityService` returns a mock instance of the `ConnectivityService` class. +/// +/// **params**: +/// None +/// +/// **returns**: +/// * `ConnectivityService`: A mock instance of the `ConnectivityService` class. +ConnectivityService getAndRegisterConnectivityService() { + _removeRegistrationIfExists(); + final service = MockConnectivityService(); + locator.registerSingleton(service); + // when(service.) + return service; +} + /// `getPostMockModel` returns a mock instance of the `Post` class. /// /// **params**: @@ -862,6 +878,7 @@ void registerServices() { getAndRegisterPostService(); getAndRegisterEventService(); getAndRegisterMultiMediaPickerService(); + getAndRegisterConnectivity(); getAndRegisterConnectivityService(); getAndRegisterDatabaseMutationFunctions(); getAndRegisterOrganizationService(); @@ -886,6 +903,7 @@ void unregisterServices() { locator.unregister(); locator.unregister(); locator.unregister(); + locator.unregister(); locator.unregister(); locator.unregister(); locator.unregister(); diff --git a/test/helpers/test_helpers.mocks.dart b/test/helpers/test_helpers.mocks.dart index 017b54648..15fb06f8f 100644 --- a/test/helpers/test_helpers.mocks.dart +++ b/test/helpers/test_helpers.mocks.dart @@ -7,20 +7,17 @@ import 'dart:async' as _i5; import 'dart:io' as _i19; import 'dart:ui' as _i10; -import 'package:connectivity_plus/connectivity_plus.dart' as _i27; -import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart' - as _i28; import 'package:flutter/material.dart' as _i1; import 'package:graphql_flutter/graphql_flutter.dart' as _i3; -import 'package:image_cropper/src/cropper.dart' as _i41; +import 'package:image_cropper/src/cropper.dart' as _i39; import 'package:image_cropper_platform_interface/image_cropper_platform_interface.dart' - as _i42; + as _i40; import 'package:image_picker/image_picker.dart' as _i13; import 'package:mockito/mockito.dart' as _i2; import 'package:mockito/src/dummies.dart' as _i25; -import 'package:qr_code_scanner/src/qr_code_scanner.dart' as _i34; -import 'package:qr_code_scanner/src/types/barcode.dart' as _i35; -import 'package:qr_code_scanner/src/types/camera.dart' as _i36; +import 'package:qr_code_scanner/src/qr_code_scanner.dart' as _i32; +import 'package:qr_code_scanner/src/types/barcode.dart' as _i33; +import 'package:qr_code_scanner/src/types/camera.dart' as _i34; import 'package:qr_code_scanner/src/types/features.dart' as _i12; import 'package:talawa/enums/enums.dart' as _i14; import 'package:talawa/models/chats/chat_list_tile_data_model.dart' as _i22; @@ -30,29 +27,29 @@ import 'package:talawa/models/organization/org_info.dart' as _i6; import 'package:talawa/models/post/post_model.dart' as _i17; import 'package:talawa/models/user/user_info.dart' as _i7; import 'package:talawa/services/chat_service.dart' as _i21; -import 'package:talawa/services/comment_service.dart' as _i37; +import 'package:talawa/services/comment_service.dart' as _i35; import 'package:talawa/services/database_mutation_functions.dart' as _i9; import 'package:talawa/services/event_service.dart' as _i11; import 'package:talawa/services/graphql_config.dart' as _i15; import 'package:talawa/services/navigation_service.dart' as _i8; -import 'package:talawa/services/org_service.dart' as _i30; +import 'package:talawa/services/org_service.dart' as _i28; import 'package:talawa/services/post_service.dart' as _i16; import 'package:talawa/services/third_party_service/multi_media_pick_service.dart' as _i18; import 'package:talawa/services/user_config.dart' as _i24; -import 'package:talawa/utils/validators.dart' as _i33; +import 'package:talawa/utils/validators.dart' as _i31; import 'package:talawa/view_model/after_auth_view_models/chat_view_models/direct_chat_view_model.dart' - as _i40; + as _i38; import 'package:talawa/view_model/after_auth_view_models/event_view_models/create_event_view_model.dart' - as _i39; + as _i37; import 'package:talawa/view_model/after_auth_view_models/event_view_models/explore_events_view_model.dart' - as _i31; + as _i29; import 'package:talawa/view_model/after_auth_view_models/feed_view_models/organization_feed_view_model.dart' - as _i32; + as _i30; import 'package:talawa/view_model/lang_view_model.dart' as _i26; import 'package:talawa/view_model/pre_auth_view_models/signup_details_view_model.dart' - as _i29; -import 'package:talawa/view_model/theme_view_model.dart' as _i38; + as _i27; +import 'package:talawa/view_model/theme_view_model.dart' as _i36; import 'package:talawa/widgets/custom_alert_dialog.dart' as _i4; // ignore_for_file: type=lint @@ -1736,37 +1733,11 @@ class MockAppLanguage extends _i2.Mock implements _i26.AppLanguage { ); } -/// A class which mocks [Connectivity]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockConnectivity extends _i2.Mock implements _i27.Connectivity { - @override - _i5.Stream<_i28.ConnectivityResult> get onConnectivityChanged => - (super.noSuchMethod( - Invocation.getter(#onConnectivityChanged), - returnValue: _i5.Stream<_i28.ConnectivityResult>.empty(), - returnValueForMissingStub: _i5.Stream<_i28.ConnectivityResult>.empty(), - ) as _i5.Stream<_i28.ConnectivityResult>); - - @override - _i5.Future<_i28.ConnectivityResult> checkConnectivity() => - (super.noSuchMethod( - Invocation.method( - #checkConnectivity, - [], - ), - returnValue: _i5.Future<_i28.ConnectivityResult>.value( - _i28.ConnectivityResult.bluetooth), - returnValueForMissingStub: _i5.Future<_i28.ConnectivityResult>.value( - _i28.ConnectivityResult.bluetooth), - ) as _i5.Future<_i28.ConnectivityResult>); -} - /// A class which mocks [SignupDetailsViewModel]. /// /// See the documentation for Mockito's code generation for more information. class MockSignupDetailsViewModel extends _i2.Mock - implements _i29.SignupDetailsViewModel { + implements _i27.SignupDetailsViewModel { @override _i1.GlobalKey<_i1.FormState> get formKey => (super.noSuchMethod( Invocation.getter(#formKey), @@ -2557,7 +2528,7 @@ class MockDataBaseMutationFunctions extends _i2.Mock /// /// See the documentation for Mockito's code generation for more information. class MockOrganizationService extends _i2.Mock - implements _i30.OrganizationService { + implements _i28.OrganizationService { @override _i5.Future> getOrgMembersList(String? orgId) => (super.noSuchMethod( @@ -2575,7 +2546,7 @@ class MockOrganizationService extends _i2.Mock /// /// See the documentation for Mockito's code generation for more information. class MockExploreEventsViewModel extends _i2.Mock - implements _i31.ExploreEventsViewModel { + implements _i29.ExploreEventsViewModel { @override bool get demoMode => (super.noSuchMethod( Invocation.getter(#demoMode), @@ -2779,7 +2750,7 @@ class MockExploreEventsViewModel extends _i2.Mock /// /// See the documentation for Mockito's code generation for more information. class MockOrganizationFeedViewModel extends _i2.Mock - implements _i32.OrganizationFeedViewModel { + implements _i30.OrganizationFeedViewModel { @override bool get istest => (super.noSuchMethod( Invocation.getter(#istest), @@ -3009,7 +2980,7 @@ class MockOrganizationFeedViewModel extends _i2.Mock /// A class which mocks [Validator]. /// /// See the documentation for Mockito's code generation for more information. -class MockValidator extends _i2.Mock implements _i33.Validator { +class MockValidator extends _i2.Mock implements _i31.Validator { @override _i5.Future validateUrlExistence(String? url) => (super.noSuchMethod( Invocation.method( @@ -3024,13 +2995,13 @@ class MockValidator extends _i2.Mock implements _i33.Validator { /// A class which mocks [QRViewController]. /// /// See the documentation for Mockito's code generation for more information. -class MockQRViewController extends _i2.Mock implements _i34.QRViewController { +class MockQRViewController extends _i2.Mock implements _i32.QRViewController { @override - _i5.Stream<_i35.Barcode> get scannedDataStream => (super.noSuchMethod( + _i5.Stream<_i33.Barcode> get scannedDataStream => (super.noSuchMethod( Invocation.getter(#scannedDataStream), - returnValue: _i5.Stream<_i35.Barcode>.empty(), - returnValueForMissingStub: _i5.Stream<_i35.Barcode>.empty(), - ) as _i5.Stream<_i35.Barcode>); + returnValue: _i5.Stream<_i33.Barcode>.empty(), + returnValueForMissingStub: _i5.Stream<_i33.Barcode>.empty(), + ) as _i5.Stream<_i33.Barcode>); @override bool get hasPermissions => (super.noSuchMethod( @@ -3040,28 +3011,28 @@ class MockQRViewController extends _i2.Mock implements _i34.QRViewController { ) as bool); @override - _i5.Future<_i36.CameraFacing> getCameraInfo() => (super.noSuchMethod( + _i5.Future<_i34.CameraFacing> getCameraInfo() => (super.noSuchMethod( Invocation.method( #getCameraInfo, [], ), returnValue: - _i5.Future<_i36.CameraFacing>.value(_i36.CameraFacing.back), + _i5.Future<_i34.CameraFacing>.value(_i34.CameraFacing.back), returnValueForMissingStub: - _i5.Future<_i36.CameraFacing>.value(_i36.CameraFacing.back), - ) as _i5.Future<_i36.CameraFacing>); + _i5.Future<_i34.CameraFacing>.value(_i34.CameraFacing.back), + ) as _i5.Future<_i34.CameraFacing>); @override - _i5.Future<_i36.CameraFacing> flipCamera() => (super.noSuchMethod( + _i5.Future<_i34.CameraFacing> flipCamera() => (super.noSuchMethod( Invocation.method( #flipCamera, [], ), returnValue: - _i5.Future<_i36.CameraFacing>.value(_i36.CameraFacing.back), + _i5.Future<_i34.CameraFacing>.value(_i34.CameraFacing.back), returnValueForMissingStub: - _i5.Future<_i36.CameraFacing>.value(_i36.CameraFacing.back), - ) as _i5.Future<_i36.CameraFacing>); + _i5.Future<_i34.CameraFacing>.value(_i34.CameraFacing.back), + ) as _i5.Future<_i34.CameraFacing>); @override _i5.Future getFlashStatus() => (super.noSuchMethod( @@ -3160,7 +3131,7 @@ class MockQRViewController extends _i2.Mock implements _i34.QRViewController { /// A class which mocks [CommentService]. /// /// See the documentation for Mockito's code generation for more information. -class MockCommentService extends _i2.Mock implements _i37.CommentService { +class MockCommentService extends _i2.Mock implements _i35.CommentService { @override _i5.Future createComments( String? postId, @@ -3193,7 +3164,7 @@ class MockCommentService extends _i2.Mock implements _i37.CommentService { /// A class which mocks [AppTheme]. /// /// See the documentation for Mockito's code generation for more information. -class MockAppTheme extends _i2.Mock implements _i38.AppTheme { +class MockAppTheme extends _i2.Mock implements _i36.AppTheme { @override String get key => (super.noSuchMethod( Invocation.getter(#key), @@ -3304,7 +3275,7 @@ class MockAppTheme extends _i2.Mock implements _i38.AppTheme { /// /// See the documentation for Mockito's code generation for more information. class MockCreateEventViewModel extends _i2.Mock - implements _i39.CreateEventViewModel { + implements _i37.CreateEventViewModel { @override _i1.TextEditingController get eventTitleTextController => (super.noSuchMethod( Invocation.getter(#eventTitleTextController), @@ -4025,7 +3996,7 @@ class MockCreateEventViewModel extends _i2.Mock /// /// See the documentation for Mockito's code generation for more information. class MockDirectChatViewModel extends _i2.Mock - implements _i40.DirectChatViewModel { + implements _i38.DirectChatViewModel { @override _i1.GlobalKey<_i1.AnimatedListState> get listKey => (super.noSuchMethod( Invocation.getter(#listKey), @@ -4204,24 +4175,24 @@ class MockDirectChatViewModel extends _i2.Mock /// A class which mocks [ImageCropper]. /// /// See the documentation for Mockito's code generation for more information. -class MockImageCropper extends _i2.Mock implements _i41.ImageCropper { +class MockImageCropper extends _i2.Mock implements _i39.ImageCropper { @override - _i5.Future<_i42.CroppedFile?> cropImage({ + _i5.Future<_i40.CroppedFile?> cropImage({ required String? sourcePath, int? maxWidth, int? maxHeight, - _i42.CropAspectRatio? aspectRatio, - List<_i42.CropAspectRatioPreset>? aspectRatioPresets = const [ - _i42.CropAspectRatioPreset.original, - _i42.CropAspectRatioPreset.square, - _i42.CropAspectRatioPreset.ratio3x2, - _i42.CropAspectRatioPreset.ratio4x3, - _i42.CropAspectRatioPreset.ratio16x9, + _i40.CropAspectRatio? aspectRatio, + List<_i40.CropAspectRatioPreset>? aspectRatioPresets = const [ + _i40.CropAspectRatioPreset.original, + _i40.CropAspectRatioPreset.square, + _i40.CropAspectRatioPreset.ratio3x2, + _i40.CropAspectRatioPreset.ratio4x3, + _i40.CropAspectRatioPreset.ratio16x9, ], - _i42.CropStyle? cropStyle = _i42.CropStyle.rectangle, - _i42.ImageCompressFormat? compressFormat = _i42.ImageCompressFormat.jpg, + _i40.CropStyle? cropStyle = _i40.CropStyle.rectangle, + _i40.ImageCompressFormat? compressFormat = _i40.ImageCompressFormat.jpg, int? compressQuality = 90, - List<_i42.PlatformUiSettings>? uiSettings, + List<_i40.PlatformUiSettings>? uiSettings, }) => (super.noSuchMethod( Invocation.method( @@ -4239,19 +4210,19 @@ class MockImageCropper extends _i2.Mock implements _i41.ImageCropper { #uiSettings: uiSettings, }, ), - returnValue: _i5.Future<_i42.CroppedFile?>.value(), - returnValueForMissingStub: _i5.Future<_i42.CroppedFile?>.value(), - ) as _i5.Future<_i42.CroppedFile?>); + returnValue: _i5.Future<_i40.CroppedFile?>.value(), + returnValueForMissingStub: _i5.Future<_i40.CroppedFile?>.value(), + ) as _i5.Future<_i40.CroppedFile?>); @override - _i5.Future<_i42.CroppedFile?> recoverImage() => (super.noSuchMethod( + _i5.Future<_i40.CroppedFile?> recoverImage() => (super.noSuchMethod( Invocation.method( #recoverImage, [], ), - returnValue: _i5.Future<_i42.CroppedFile?>.value(), - returnValueForMissingStub: _i5.Future<_i42.CroppedFile?>.value(), - ) as _i5.Future<_i42.CroppedFile?>); + returnValue: _i5.Future<_i40.CroppedFile?>.value(), + returnValueForMissingStub: _i5.Future<_i40.CroppedFile?>.value(), + ) as _i5.Future<_i40.CroppedFile?>); } /// A class which mocks [ImagePicker]. @@ -4289,8 +4260,8 @@ class MockImagePicker extends _i2.Mock implements _i13.ImagePicker { double? maxWidth, double? maxHeight, int? imageQuality, - bool? requestFullMetadata = true, int? limit, + bool? requestFullMetadata = true, }) => (super.noSuchMethod( Invocation.method( @@ -4300,8 +4271,8 @@ class MockImagePicker extends _i2.Mock implements _i13.ImagePicker { #maxWidth: maxWidth, #maxHeight: maxHeight, #imageQuality: imageQuality, - #requestFullMetadata: requestFullMetadata, #limit: limit, + #requestFullMetadata: requestFullMetadata, }, ), returnValue: _i5.Future>.value(<_i13.XFile>[]), @@ -4336,8 +4307,8 @@ class MockImagePicker extends _i2.Mock implements _i13.ImagePicker { double? maxWidth, double? maxHeight, int? imageQuality, - bool? requestFullMetadata = true, int? limit, + bool? requestFullMetadata = true, }) => (super.noSuchMethod( Invocation.method( @@ -4347,8 +4318,8 @@ class MockImagePicker extends _i2.Mock implements _i13.ImagePicker { #maxWidth: maxWidth, #maxHeight: maxHeight, #imageQuality: imageQuality, - #requestFullMetadata: requestFullMetadata, #limit: limit, + #requestFullMetadata: requestFullMetadata, }, ), returnValue: _i5.Future>.value(<_i13.XFile>[]), diff --git a/test/helpers/test_locator.dart b/test/helpers/test_locator.dart index 698696d44..3bded2546 100644 --- a/test/helpers/test_locator.dart +++ b/test/helpers/test_locator.dart @@ -1,6 +1,7 @@ // ignore_for_file: talawa_api_doc // ignore_for_file: talawa_good_doc_comments +import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:get_it/get_it.dart'; import 'package:image_cropper/image_cropper.dart'; import 'package:image_picker/image_picker.dart'; @@ -13,7 +14,9 @@ import 'package:talawa/services/image_service.dart'; import 'package:talawa/services/navigation_service.dart'; import 'package:talawa/services/org_service.dart'; import 'package:talawa/services/post_service.dart'; +import 'package:talawa/services/session_manager.dart'; import 'package:talawa/services/size_config.dart'; +import 'package:talawa/services/third_party_service/connectivity_service.dart'; import 'package:talawa/services/third_party_service/multi_media_pick_service.dart'; import 'package:talawa/services/user_config.dart'; import 'package:talawa/utils/queries.dart'; @@ -29,6 +32,7 @@ import 'package:talawa/view_model/after_auth_view_models/feed_view_models/organi import 'package:talawa/view_model/after_auth_view_models/profile_view_models/edit_profile_view_model.dart'; import 'package:talawa/view_model/after_auth_view_models/profile_view_models/profile_page_view_model.dart'; import 'package:talawa/view_model/after_auth_view_models/settings_view_models/app_setting_view_model.dart'; +import 'package:talawa/view_model/connectivity_view_model.dart'; import 'package:talawa/view_model/lang_view_model.dart'; import 'package:talawa/view_model/main_screen_view_model.dart'; import 'package:talawa/view_model/pre_auth_view_models/login_view_model.dart'; @@ -54,11 +58,14 @@ final multimediaPickerService = locator(); final organizationService = locator(); final eventService = locator(); final commentsService = locator(); +final connectivity = locator(); +final connectivityService = locator(); final postService = locator(); final mainScreenViewModel = locator(); final imageService = locator(); final imagePicker = locator(); final imageCropper = locator(); +final sessionManager = locator(); void testSetupLocator() { //services @@ -70,11 +77,14 @@ void testSetupLocator() { //userConfig locator.registerSingleton(UserConfig()); + locator.registerSingleton(SessionManager()); + //Services locator.registerLazySingleton(() => OrganizationService()); locator.registerLazySingleton(() => PostService()); locator.registerLazySingleton(() => EventService()); locator.registerLazySingleton(() => CommentService()); + locator.registerLazySingleton(() => Connectivity()); locator.registerLazySingleton(() => MultiMediaPickerService()); locator.registerLazySingleton(() => ImageService()); locator.registerLazySingleton(() => ImagePicker()); @@ -87,9 +97,13 @@ void testSetupLocator() { //databaseMutationFunction locator.registerSingleton(DataBaseMutationFunctions()); + locator.registerSingleton(ConnectivityService()); + //queries locator.registerSingleton(Queries()); + locator.registerFactory(() => AppConnectivity()); + //Page viewModels locator.registerFactory(() => DemoViewModel()); // locator.registerFactory(() => OrganizationFeedViewModel()); diff --git a/test/main_test.dart b/test/main_test.dart new file mode 100644 index 000000000..22570b11c --- /dev/null +++ b/test/main_test.dart @@ -0,0 +1,57 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:mockito/mockito.dart'; +import 'package:talawa/main.dart'; +import 'package:talawa/models/organization/org_info.dart'; +import 'package:talawa/models/user/user_info.dart'; +import 'package:talawa/view_model/connectivity_view_model.dart'; +import 'package:talawa/view_model/lang_view_model.dart'; +import 'package:talawa/view_model/theme_view_model.dart'; +import 'package:talawa/views/base_view.dart'; + +import 'helpers/test_helpers.dart'; +import 'helpers/test_locator.dart'; + +void main() async { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + + testSetupLocator(); + + getAndRegisterUserConfig(); + + final Directory dir = Directory('test/fixtures/core'); + + Hive + ..init(dir.path) + ..registerAdapter(UserAdapter()) + ..registerAdapter(OrgInfoAdapter()); + await Hive.openBox('currentUser'); + await Hive.openBox('url'); + await Hive.openBox('currentOrg'); + }); + + testWidgets('MyApp', (tester) async { + when(userConfig.userLoggedIn()).thenAnswer((_) => Future.value(false)); + + await tester.pumpWidget(MyApp()); + + final model = locator(); + + model.initialize(); + + expect(find.byType(BaseView), findsOne); + expect(find.byType(BaseView), findsOne); + expect(find.byType(BaseView), findsOne); + expect(find.byType(MaterialApp), findsOne); + + model.switchTheme(isOn: false); + + await tester.pumpAndSettle(); + + expect(model.isdarkTheme, false); + }); +} diff --git a/test/model_tests/app_tour_test.dart b/test/model_tests/app_tour_test.dart index f9009417a..f9985ee97 100644 --- a/test/model_tests/app_tour_test.dart +++ b/test/model_tests/app_tour_test.dart @@ -78,9 +78,10 @@ MaterialApp createMaterialApp({required Widget home}) { } void main() { - setupLocator(); - sizeConfig.test(); - // registerServices(); + setUpAll(() { + setupLocator(); + sizeConfig.test(); + }); group('Tests for FocusTarget', () { testWidgets('Test for first TargetContent builder in FocusTarget model.', diff --git a/test/model_tests/events/event_venue_test.dart b/test/model_tests/events/event_venue_test.dart new file mode 100644 index 000000000..b4803465b --- /dev/null +++ b/test/model_tests/events/event_venue_test.dart @@ -0,0 +1,35 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:talawa/models/events/event_venue.dart'; + +void main() { + group('Test Venue Model', () { + test('Test Venue fromJson and toJson', () { + final venue = Venue( + id: '1', + capacity: 100, + description: 'A nice place', + imageUrl: 'http://example.com/image.jpg', + name: 'Main Hall', + organizationId: 'org1', + ); + + final venueJson = { + '_id': '1', + 'capacity': 100, + 'description': 'A nice place', + 'imageUrl': 'http://example.com/image.jpg', + 'name': 'Main Hall', + 'organization': {'_id': 'org1'}, + }; + + final venueFromJson = Venue.fromJson(venueJson); + + expect(venue.id, venueFromJson.id); + expect(venue.capacity, venueFromJson.capacity); + expect(venue.description, venueFromJson.description); + expect(venue.imageUrl, venueFromJson.imageUrl); + expect(venue.name, venueFromJson.name); + expect(venue.organizationId, venueFromJson.organizationId); + }); + }); +} diff --git a/test/model_tests/organization/org_info_test.dart b/test/model_tests/organization/org_info_test.dart index 9f2b25296..9afada14a 100644 --- a/test/model_tests/organization/org_info_test.dart +++ b/test/model_tests/organization/org_info_test.dart @@ -5,13 +5,12 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:talawa/locator.dart'; import 'package:talawa/models/organization/org_info.dart'; -import '../../helpers/test_helpers.dart'; - void main() { - setupLocator(); - sizeConfig.test(); - setUp(() { - registerServices(); + TestWidgetsFlutterBinding.ensureInitialized(); + + setUpAll(() { + setupLocator(); + sizeConfig.test(); }); group('Test OrgInfo model', () { @@ -210,4 +209,23 @@ void main() { expect(res[2].admins![0].id, 'user_id'); }); }); + + group('Hive adapter test', () { + test('OrgInfoAdapter equality operator', () { + final adapter1 = OrgInfoAdapter(); + final adapter2 = OrgInfoAdapter(); + + // Test equality + expect( + adapter1 == adapter2, + isTrue, + reason: 'Two instances of OrgInfoAdapter should be equal', + ); + expect( + adapter1.hashCode == adapter2.hashCode, + isTrue, + reason: 'Hash codes should be equal', + ); + }); + }); } diff --git a/test/plugins/fetch_plugin_list_test.dart b/test/plugins/fetch_plugin_list_test.dart index f8dc27d93..3e590678d 100644 --- a/test/plugins/fetch_plugin_list_test.dart +++ b/test/plugins/fetch_plugin_list_test.dart @@ -19,15 +19,16 @@ import '../helpers/test_locator.dart'; /// **returns**: /// None void main() async { - testSetupLocator(); - locator().test(); late FetchPluginList fetchPluginList; final Directory dir = await Directory.systemTemp.createTemp('talawa_test'); Hive.init(dir.path); await Hive.openBox('pluginBox'); - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); registerServices(); locator.allowReassignment = true; diff --git a/test/plugins/talawa_plugin_provider_test.dart b/test/plugins/talawa_plugin_provider_test.dart index 940dd09c1..e4c5accee 100644 --- a/test/plugins/talawa_plugin_provider_test.dart +++ b/test/plugins/talawa_plugin_provider_test.dart @@ -19,8 +19,11 @@ import '../helpers/test_locator.dart'; /// **returns**: /// None void main() { - testSetupLocator(); - TestWidgetsFlutterBinding.ensureInitialized(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + + testSetupLocator(); + }); late Box box; final OrgInfo org = OrgInfo( diff --git a/test/router_test.dart b/test/router_test.dart index 748f8fa9f..8139d8b81 100644 --- a/test/router_test.dart +++ b/test/router_test.dart @@ -43,10 +43,15 @@ import 'package:talawa/views/pre_auth_screens/select_organization.dart'; import 'package:talawa/views/pre_auth_screens/set_url.dart'; import 'package:talawa/views/pre_auth_screens/waiting_screen.dart'; +import 'helpers/test_helpers.dart'; + class MockBuildContext extends Mock implements BuildContext {} void main() { - setupLocator(); + setUpAll(() { + setupLocator(); + getAndRegisterConnectivity(); + }); group('Tests for router', () { testWidgets('Test SplashScreen route', (WidgetTester tester) async { diff --git a/test/service_tests/database_mutations_function_test.dart b/test/service_tests/database_mutations_function_test.dart index 061924ee3..2815dd270 100644 --- a/test/service_tests/database_mutations_function_test.dart +++ b/test/service_tests/database_mutations_function_test.dart @@ -21,8 +21,6 @@ import '../helpers/test_locator.dart'; /// **returns**: /// None void main() async { - testSetupLocator(); - locator().test(); late DataBaseMutationFunctions functionsClass; final Directory dir = await Directory.systemTemp.createTemp('talawa_test'); Hive.init(dir.path); @@ -63,6 +61,9 @@ void main() async { }); setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); registerServices(); functionsClass = DataBaseMutationFunctions(); functionsClass.init(); diff --git a/test/service_tests/event_service_test.dart b/test/service_tests/event_service_test.dart index 9da3f0935..f6f09bb9f 100644 --- a/test/service_tests/event_service_test.dart +++ b/test/service_tests/event_service_test.dart @@ -12,9 +12,9 @@ import '../helpers/test_locator.dart'; import '../model_tests/user/user_info_test.dart'; void main() { - testSetupLocator(); - - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); registerServices(); }); group('Test EventService', () { diff --git a/test/service_tests/graphql_config_test.dart b/test/service_tests/graphql_config_test.dart index 201b1aafc..3294f3e18 100644 --- a/test/service_tests/graphql_config_test.dart +++ b/test/service_tests/graphql_config_test.dart @@ -5,9 +5,10 @@ import '../helpers/test_helpers.dart'; import '../helpers/test_locator.dart'; void main() { - testSetupLocator(); - setUp(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + registerServices(); }); group('Testing Graphql Config', () { diff --git a/test/service_tests/image_service_test.dart b/test/service_tests/image_service_test.dart index cce18ff63..c3826bd06 100644 --- a/test/service_tests/image_service_test.dart +++ b/test/service_tests/image_service_test.dart @@ -20,9 +20,9 @@ class MockImageService extends Mock implements ImageService { } void main() { - testSetupLocator(); - setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); registerServices(); }); diff --git a/test/service_tests/multi_media_pick_service_test.dart b/test/service_tests/multi_media_pick_service_test.dart index 1205bc509..10e93b76e 100644 --- a/test/service_tests/multi_media_pick_service_test.dart +++ b/test/service_tests/multi_media_pick_service_test.dart @@ -17,14 +17,17 @@ import '../helpers/test_helpers.dart'; import '../helpers/test_locator.dart'; void main() { - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + }); setUp(() { registerServices(); + SizeConfig().test(); }); tearDown(() { unregisterServices(); }); - SizeConfig().test(); group('MultiMediaPickerService test', () { test("test get photo from gallery method if camera option is false", () async { diff --git a/test/service_tests/session_manager_test.dart b/test/service_tests/session_manager_test.dart index 1834c561c..f5bace7a9 100644 --- a/test/service_tests/session_manager_test.dart +++ b/test/service_tests/session_manager_test.dart @@ -8,7 +8,12 @@ import 'package:talawa/services/session_manager.dart'; import '../helpers/test_helpers.dart'; void main() { - setupLocator(); + TestWidgetsFlutterBinding.ensureInitialized(); + + setUpAll(() { + setupLocator(); + }); + group('Test Session Manger', () { setUpAll(() { getAndRegisterDatabaseMutationFunctions(); diff --git a/test/service_tests/third_party_service_test.dart/connectivity_service_test.dart b/test/service_tests/third_party_service_test.dart/connectivity_service_test.dart new file mode 100644 index 000000000..0bca2232a --- /dev/null +++ b/test/service_tests/third_party_service_test.dart/connectivity_service_test.dart @@ -0,0 +1,133 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:mockito/mockito.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:talawa/locator.dart'; +import 'package:talawa/services/third_party_service/connectivity_service.dart'; + +import '../../helpers/test_helpers.dart'; +import '../../helpers/test_locator.dart' as testgetit; + +ConnectivityResult? connectivityStatus = ConnectivityResult.mobile; +bool internetAccessible = true; + +class MockConnectivityService extends Mock + with MockPlatformInterfaceMixin + implements ConnectivityService { + final controller = StreamController(); + + @override + // TODO: implement connectionStatusController + StreamController get connectionStatusController => + controller; + + @override + Future initConnectivity({required http.Client client}) { + // TODO: implement initConnectivity + return Future(() => null); + } + + @override + Stream get connectionStream => controller.stream; + + @override + Future getConnectionType() { + return Future.value(connectivityStatus); + } + + @override + Future isReachable({http.Client? client, String? uriString}) { + return Future.value(internetAccessible); + } +} + +class MockConnectivity extends Mock implements Connectivity { + final controller = StreamController(); + + StreamController get connectivityController => controller; + + @override + Stream get onConnectivityChanged => controller.stream; + + @override + Future checkConnectivity() async { + // TODO: implement checkConnectivity + if (connectivityStatus == null) { + throw const SocketException('socket exception'); + } + return connectivityStatus!; + } +} + +class MockClient extends Mock implements http.Client { + @override + Future get(Uri url, {Map? headers}) async { + if (url.toString() == 'https://timeout.com') { + throw TimeoutException('site took too long to respond'); + } + return http.Response('{}', 200); + } +} + +void main() { + late MockClient mockClient; + late ConnectivityService service; + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + mockClient = MockClient(); + getAndRegisterConnectivity(); + connectivityStatus = ConnectivityResult.mobile; + service = ConnectivityService(); + locator.registerSingleton(service); + connectivityService.initConnectivity(client: http.Client()); + }); + + group('connectivity', () { + test( + 'connectionStream getter', + () async { + expect(connectivityService, isA()); + expect( + connectivityService.connectionStream, + isA>(), + ); + }, + ); + + test('listener', () async { + final mockConnectivity = testgetit.connectivity as MockConnectivity; + mockConnectivity.connectivityController.add(ConnectivityResult.mobile); + + mockConnectivity.connectivityController + .addError(Exception("Something went wrong!")); + }); + + test('check has connection', () async { + connectivityStatus = ConnectivityResult.none; + expect(await service.hasConnection(), false); + + connectivityStatus = ConnectivityResult.mobile; + expect(await service.hasConnection(), true); + }); + + test('isReachable', () async { + final reached = + await service.isReachable(uriString: 'https://google.com'); + expect(reached, true); + }); + + test('isReachable throws TimeoutException on timeout', () async { + final isReachableResult = await service.isReachable( + client: mockClient, + uriString: 'https://timeout.com', + ); + + // Verify results (timeout should be thrown before verification) + expect(isReachableResult, false); + }); + }); +} diff --git a/test/service_tests/user_config_test.dart b/test/service_tests/user_config_test.dart index 74575c598..96e0e8a2e 100644 --- a/test/service_tests/user_config_test.dart +++ b/test/service_tests/user_config_test.dart @@ -41,7 +41,12 @@ class MockSessionManger extends Mock implements SessionManager { } void main() async { - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + getAndRegisterSessionManager(); + registerServices(); + }); final Directory dir = Directory('test/fixtures/core'); @@ -54,8 +59,6 @@ void main() async { final urlBox = await Hive.openBox('url'); final orgBox = await Hive.openBox('currentOrg'); - getAndRegisterSessionManager(); - final mockUser = User( adminFor: [ OrgInfo(id: 'org1', name: 'orga'), @@ -87,10 +90,6 @@ void main() async { ]; group('Test UserConfig service', () { - setUpAll(() { - registerServices(); - }); - test('Test for getters & setters.', () { final model = UserConfig(); diff --git a/test/utils_tests/queries_test.dart b/test/utils_tests/queries_test.dart index cdb43da4d..794891e19 100644 --- a/test/utils_tests/queries_test.dart +++ b/test/utils_tests/queries_test.dart @@ -221,5 +221,17 @@ void main() { } expect(mutation, true); }); + test("Check if venueListQuery works correctly", () { + var mutation = false; + expect(mutation, false); + + final fnData = Queries().venueListQuery(); + + if (fnData.contains('GetVenueByOrgId') && + fnData.contains('GetVenueByOrgId')) { + mutation = true; + } + expect(mutation, true); + }); }); } diff --git a/test/view_model_tests/access_request_view_model_test.dart b/test/view_model_tests/access_request_view_model_test.dart index e6a63d6a5..7dfbf9fcd 100644 --- a/test/view_model_tests/access_request_view_model_test.dart +++ b/test/view_model_tests/access_request_view_model_test.dart @@ -13,9 +13,9 @@ class MockCallbackFunction extends Mock { } void main() { - testSetupLocator(); - setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); registerServices(); }); diff --git a/test/view_model_tests/after_auth_view_model_tests/add_post_view_model_test.dart b/test/view_model_tests/after_auth_view_model_tests/add_post_view_model_test.dart index 2a00ad6dd..cbb9a9a31 100644 --- a/test/view_model_tests/after_auth_view_model_tests/add_post_view_model_test.dart +++ b/test/view_model_tests/after_auth_view_model_tests/add_post_view_model_test.dart @@ -45,7 +45,6 @@ final demoJson = { }; void main() { - testSetupLocator(); setUp(() { registerServices(); getAndRegisterImageService(); diff --git a/test/view_model_tests/after_auth_view_model_tests/chat_view_models_test/select_contact_view_model_test.dart b/test/view_model_tests/after_auth_view_model_tests/chat_view_models_test/select_contact_view_model_test.dart index e9bcc87d3..74e695ed3 100644 --- a/test/view_model_tests/after_auth_view_model_tests/chat_view_models_test/select_contact_view_model_test.dart +++ b/test/view_model_tests/after_auth_view_model_tests/chat_view_models_test/select_contact_view_model_test.dart @@ -12,9 +12,12 @@ import '../../../helpers/test_helpers.dart'; import '../../../helpers/test_locator.dart'; void main() { - testSetupLocator(); - locator().test(); - locator().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + locator().test(); + }); setUp(() { registerServices(); diff --git a/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/create_event_view_model_test.dart b/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/create_event_view_model_test.dart index cd683b6f8..26e20e78f 100644 --- a/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/create_event_view_model_test.dart +++ b/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/create_event_view_model_test.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:intl/intl.dart'; import 'package:mockito/mockito.dart'; import 'package:talawa/constants/recurrence_values.dart'; @@ -84,18 +85,19 @@ Widget createApp( } void main() { - testSetupLocator(); - locator().test(); - locator().test(); - setUp(() { registerServices(); - locator().test(); }); - tearDown(() { unregisterServices(); }); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + locator().test(); + locator().test(); + }); group('Create Event Tests', () { test("test getCurrentOrgUsersList with isAdmin false", () async { @@ -573,5 +575,63 @@ void main() { expect(model.eventEndDate, newDate); verify(notifyListenerCallback()).called(1); }); + test('check if fetchVenues method work properly when null is thrown', () { + final model = CreateEventViewModel(); + model.initialize(); + final mockQueryResult = QueryResult( + source: QueryResultSource.network, + data: null, + options: QueryOptions(document: gql(queries.venueListQuery())), + ); + + when( + databaseFunctions.gqlAuthQuery( + queries.venueListQuery(), + variables: { + "orgId": 'XYZ', + }, + ), + ).thenAnswer((_) async => mockQueryResult); + + model.fetchVenues(); + }); + test('check if fetchVenues method work properly', () { + final model = CreateEventViewModel(); + model.initialize(); + + final mockQueryResult = QueryResult( + source: QueryResultSource.network, + data: { + 'getVenueByOrgId': [ + { + 'id': '1', + 'name': 'Mock Venue 1', + 'capacity': 100, + 'imageUrl': '', + 'description': 'aaa', + }, + { + 'id': '2', + 'name': 'Mock Venue 2', + 'capacity': 150, + 'imageUrl': '', + 'description': 'aaa', + }, + ], + }, + options: QueryOptions(document: gql(queries.venueListQuery())), + ); + + when( + databaseFunctions.gqlAuthQuery( + queries.venueListQuery(), + variables: { + "orgId": 'XYZ', + }, + ), + ).thenAnswer((_) async => mockQueryResult); + + model.fetchVenues(); + }); }); } diff --git a/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/event_info_view_model_test.dart b/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/event_info_view_model_test.dart index d36af3eaa..979a7158e 100644 --- a/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/event_info_view_model_test.dart +++ b/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/event_info_view_model_test.dart @@ -15,16 +15,15 @@ import '../../../helpers/test_locator.dart'; class MockBuildContext extends Mock implements BuildContext {} void main() { - testSetupLocator(); - locator().test(); - locator().test(); - - setUp(() { - registerServices(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); locator().test(); + registerServices(); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); diff --git a/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/explore_events_view_model_test.dart b/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/explore_events_view_model_test.dart index 294e7e79a..510a7f829 100644 --- a/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/explore_events_view_model_test.dart +++ b/test/view_model_tests/after_auth_view_model_tests/event_view_model_tests/explore_events_view_model_test.dart @@ -54,12 +54,12 @@ class _MockNavigationService extends Mock implements NavigationService { } void main() { - testSetupLocator(); - locator().test(); - locator().test(); - late Event newEvent; - setUp(() async { + + setUpAll(() async { + testSetupLocator(); + locator().test(); + locator().test(); registerServices(); await locator.unregister(); locator.registerSingleton(_MockNavigationService()); @@ -83,7 +83,7 @@ void main() { ); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); diff --git a/test/view_model_tests/after_auth_view_model_tests/feed_view_models_test/organization_feed_view_model_test.dart b/test/view_model_tests/after_auth_view_model_tests/feed_view_models_test/organization_feed_view_model_test.dart index 19cfdf60e..c9cd1d3ff 100644 --- a/test/view_model_tests/after_auth_view_model_tests/feed_view_models_test/organization_feed_view_model_test.dart +++ b/test/view_model_tests/after_auth_view_model_tests/feed_view_models_test/organization_feed_view_model_test.dart @@ -21,7 +21,10 @@ class MockCallbackFunction extends Mock { } void main() { - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + }); late OrganizationFeedViewModel model; final notifyListenerCallback = MockCallbackFunction(); diff --git a/test/view_model_tests/after_auth_view_model_tests/profile_view_model_tests/edit_profile_view_model_test.dart b/test/view_model_tests/after_auth_view_model_tests/profile_view_model_tests/edit_profile_view_model_test.dart index f3230fe2a..31392d8bc 100644 --- a/test/view_model_tests/after_auth_view_model_tests/profile_view_model_tests/edit_profile_view_model_test.dart +++ b/test/view_model_tests/after_auth_view_model_tests/profile_view_model_tests/edit_profile_view_model_test.dart @@ -24,9 +24,9 @@ class MockCallbackFunction extends Mock { } void main() { - testSetupLocator(); - SizeConfig().test(); setUpAll(() { + testSetupLocator(); + SizeConfig().test(); registerServices(); graphqlConfig.test(); sizeConfig.test(); diff --git a/test/view_model_tests/after_auth_view_model_tests/profile_view_model_tests/profile_page_view_model_test.dart b/test/view_model_tests/after_auth_view_model_tests/profile_view_model_tests/profile_page_view_model_test.dart index 0b51b0f6f..a4f1219ab 100644 --- a/test/view_model_tests/after_auth_view_model_tests/profile_view_model_tests/profile_page_view_model_test.dart +++ b/test/view_model_tests/after_auth_view_model_tests/profile_view_model_tests/profile_page_view_model_test.dart @@ -33,7 +33,10 @@ void verifyInteraction(dynamic x, {required String mockName}) { } void main() async { - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + }); group('ProfilePageViewModel Tests -', () { setUpAll(() { diff --git a/test/view_model_tests/after_auth_view_model_tests/settings_view_models_test/app_setting_view_model_test.dart b/test/view_model_tests/after_auth_view_model_tests/settings_view_models_test/app_setting_view_model_test.dart index 3827b490f..7520d143b 100644 --- a/test/view_model_tests/after_auth_view_model_tests/settings_view_models_test/app_setting_view_model_test.dart +++ b/test/view_model_tests/after_auth_view_model_tests/settings_view_models_test/app_setting_view_model_test.dart @@ -26,8 +26,11 @@ class MockUrlLauncher extends Mock } void main() async { - SizeConfig().test(); - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + }); final Directory dir = Directory('test/fixtures/core1'); diff --git a/test/view_model_tests/connectivity_view_model_test.dart b/test/view_model_tests/connectivity_view_model_test.dart new file mode 100644 index 000000000..0c142bd8b --- /dev/null +++ b/test/view_model_tests/connectivity_view_model_test.dart @@ -0,0 +1,108 @@ +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:provider/provider.dart'; +import 'package:talawa/constants/custom_theme.dart'; +import 'package:talawa/router.dart' as router; +import 'package:talawa/services/navigation_service.dart'; +import 'package:talawa/utils/app_localization.dart'; +import 'package:talawa/view_model/connectivity_view_model.dart'; +import 'package:talawa/view_model/lang_view_model.dart'; +import 'package:talawa/view_model/main_screen_view_model.dart'; +import 'package:talawa/view_model/theme_view_model.dart'; +import 'package:talawa/views/base_view.dart'; + +import '../helpers/test_helpers.dart'; +import '../helpers/test_locator.dart'; +import '../service_tests/third_party_service_test.dart/connectivity_service_test.dart'; + +Widget createMainScreen({bool demoMode = true, bool? isOnline}) { + return BaseView( + onModelReady: (model) => model.initialize(), + builder: (context, model, child) { + return BaseView( + onModelReady: (model) => model.initialize(), + builder: (context, themeModel, child) { + return BaseView( + onModelReady: (connectivityModel) => connectivityModel.initialise(), + builder: (context, connectivityModel, child) { + return MaterialApp( + locale: const Locale('en'), + localizationsDelegates: [ + const AppLocalizationsDelegate(isTest: true), + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ], + key: const Key('Root'), + theme: Provider.of(context, listen: true).isdarkTheme + ? TalawaTheme.darkTheme + : TalawaTheme.lightTheme, + home: Scaffold( + body: TextButton( + child: const Text('click me'), + onPressed: () { + AppConnectivity.showSnackbar(isOnline: isOnline!); + }, + ), + ), + navigatorKey: locator().navigatorKey, + onGenerateRoute: router.generateRoute, + ); + }, + ); + }, + ); + }, + ); +} + +void main() { + late AppConnectivity model; + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + registerServices(); + connectivityService.initConnectivity(client: http.Client()); + + model = locator(); + model.initialise(); + }); + test('handleConnection when demoMode', () { + MainScreenViewModel.demoMode = true; + model.handleConnection(ConnectivityResult.mobile); + }); + + test('handleConnection when online', () { + MainScreenViewModel.demoMode = false; + model.handleConnection(ConnectivityResult.mobile); + }); + + test('handleConnection when offline', () { + internetAccessible = false; + model.handleConnection(ConnectivityResult.none); + }); + + testWidgets('showSnackbar when online', (tester) async { + await tester.pumpWidget(createMainScreen(isOnline: true)); + await tester.pumpAndSettle(const Duration(seconds: 1)); + + await tester.tap(find.text('click me')); + }); + + testWidgets('showSnackbar when offline', (tester) async { + await tester.pumpWidget(createMainScreen(isOnline: false)); + await tester.pumpAndSettle(const Duration(seconds: 1)); + + await tester.tap(find.text('click me')); + }); + + test('check enableSubscription body', () { + connectivityService.connectionStatusController.add(ConnectivityResult.none); + }); + + test('enableSubscirption exception', () async { + model.enableSubscription(); + }); +} diff --git a/test/view_model_tests/custom_drawer_view_model_test.dart b/test/view_model_tests/custom_drawer_view_model_test.dart index 3d5f92550..7c3ef3ce1 100644 --- a/test/view_model_tests/custom_drawer_view_model_test.dart +++ b/test/view_model_tests/custom_drawer_view_model_test.dart @@ -29,17 +29,17 @@ class MockBuildContext extends Mock implements BuildContext {} /// **returns**: /// None void main() { - testSetupLocator(); - locator().test(); - locator().test(); - locator(); - - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + locator().test(); + locator(); registerServices(); locator().test(); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); group('CustomDrawerViewModel Tests', () { diff --git a/test/view_model_tests/lang_view_model_test.dart b/test/view_model_tests/lang_view_model_test.dart index d1a9491ab..52c0978d8 100644 --- a/test/view_model_tests/lang_view_model_test.dart +++ b/test/view_model_tests/lang_view_model_test.dart @@ -125,7 +125,6 @@ void main() { ), ), ); - // consider if user is logged in. when(userConfig.currentUser).thenReturn(User(id: 'xyz1')); @@ -190,4 +189,48 @@ void main() { await model.dbLanguageUpdate(); }); }); + + group('Locale Resolution Tests', () { + final model = AppLanguage(isTest: true); + model.initialize(); + const supportedLocales = [ + Locale('en', 'US'), + Locale('es', 'ES'), + Locale('fr', 'FR'), + Locale('hi', 'IN'), + Locale('zh', 'CN'), + Locale('de', 'DE'), + Locale('ja', 'JP'), + Locale('pt', 'PT'), + ]; + + test('Returns first supported locale when locale is null', () { + final result = model.localeResoultion(null, supportedLocales); + expect(result, supportedLocales.first); + }); + + test('Returns matching language code locale', () { + const locale = Locale('es', 'MX'); + final result = model.localeResoultion(locale, supportedLocales); + expect(result, const Locale('es', 'ES')); + }); + + test('Returns matching country code locale', () { + const locale = Locale('fr', 'CA'); + final result = model.localeResoultion(locale, supportedLocales); + expect(result, const Locale('fr', 'FR')); + }); + + test('Returns first supported locale when no match is found', () { + const locale = Locale('it', 'IT'); + final result = model.localeResoultion(locale, supportedLocales); + expect(result, supportedLocales.first); + }); + + test('Returns correct locale when exact match is found', () { + const locale = Locale('en', 'US'); + final result = model.localeResoultion(locale, supportedLocales); + expect(result, locale); + }); + }); } diff --git a/test/view_model_tests/progress_dialog_view_model_test.dart b/test/view_model_tests/progress_dialog_view_model_test.dart index bb5de02fb..84dfa7340 100644 --- a/test/view_model_tests/progress_dialog_view_model_test.dart +++ b/test/view_model_tests/progress_dialog_view_model_test.dart @@ -7,20 +7,17 @@ import 'package:mockito/mockito.dart'; import 'package:talawa/view_model/widgets_view_models/progress_dialog_view_model.dart'; import '../helpers/test_helpers.dart'; +import '../service_tests/third_party_service_test.dart/connectivity_service_test.dart'; void main() { group('ProgressDialogViewModelTest -', () { group('initialise -', () { - final mockConnectivity = getAndRegisterConnectivityService(); + getAndRegisterConnectivity(); final model = ProgressDialogViewModel(); test( 'When called and connectivity is present, connectivityPresent must be set to true', () async { - when(mockConnectivity.checkConnectivity()).thenAnswer( - (_) async => ConnectivityResult.mobile, - ); - await model.initialise(); expect(model.connectivityPresent, true); @@ -31,8 +28,7 @@ void main() { () async { final mockNavigation = getAndRegisterNavigationService(); - when(mockConnectivity.checkConnectivity()) - .thenAnswer((_) async => ConnectivityResult.none); + connectivityStatus = ConnectivityResult.none; await model.initialise(); diff --git a/test/view_model_tests/signup_details_view_model_test.dart b/test/view_model_tests/signup_details_view_model_test.dart index 6ac5ee5f7..270e9db9d 100644 --- a/test/view_model_tests/signup_details_view_model_test.dart +++ b/test/view_model_tests/signup_details_view_model_test.dart @@ -15,9 +15,12 @@ import '../helpers/test_locator.dart'; class MockBuildContext extends Mock implements BuildContext {} void main() { - testSetupLocator(); - locator().test(); - locator().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + locator().test(); + }); setUp(() { registerServices(); diff --git a/test/view_model_tests/widgets_view_model_test/comments_view_model_test.dart b/test/view_model_tests/widgets_view_model_test/comments_view_model_test.dart index 9ffecac01..dbed958ff 100644 --- a/test/view_model_tests/widgets_view_model_test/comments_view_model_test.dart +++ b/test/view_model_tests/widgets_view_model_test/comments_view_model_test.dart @@ -19,28 +19,28 @@ class MockCallbackFunction extends Mock { } void main() { - testSetupLocator(); - locator().test(); - - setUp(() { + late Post mockPost; + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); registerServices(); + mockPost = Post( + sId: "1", + creator: userConfig.currentUser, + description: "mock post", + imageUrl: "mockImageUrl", + videoUrl: "mockVideoUrl", + organization: userConfig.currentOrg, + createdAt: DateTime.now(), + comments: [], + ); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); - final Post mockPost = Post( - sId: "1", - creator: userConfig.currentUser, - description: "mock post", - imageUrl: "mockImageUrl", - videoUrl: "mockVideoUrl", - organization: userConfig.currentOrg, - createdAt: DateTime.now(), - comments: [], - ); - group('Comments View Model Tests', () { test("Testing the functions", () async { /// first testing initialize function diff --git a/test/views/after_auth_screens/add_post_page_test.dart b/test/views/after_auth_screens/add_post_page_test.dart index 4f42e79f6..cfae2177d 100644 --- a/test/views/after_auth_screens/add_post_page_test.dart +++ b/test/views/after_auth_screens/add_post_page_test.dart @@ -116,14 +116,11 @@ final demoJson = { }; void main() { - // SizeConfig().test(); - setupLocator(); - // locator.registerSingleton(LikeButtonViewModel()); - sizeConfig.test(); - - setUp(() { + setUpAll(() { + setupLocator(); registerServices(); getAndRegisterImageService(); + sizeConfig.test(); }); group('createAddPostScreen Test', () { diff --git a/test/views/after_auth_screens/chat/chat_message_screen_test/chat_message_screen_test.dart b/test/views/after_auth_screens/chat/chat_message_screen_test/chat_message_screen_test.dart index 0026ffb01..ea821ad87 100644 --- a/test/views/after_auth_screens/chat/chat_message_screen_test/chat_message_screen_test.dart +++ b/test/views/after_auth_screens/chat/chat_message_screen_test/chat_message_screen_test.dart @@ -45,9 +45,12 @@ Future showChatMessageScreen(WidgetTester tester) async { } void main() { - SizeConfig().test(); - testSetupLocator(); - registerServices(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + registerServices(); + }); testWidgets('Check if Chat Message Screen page shows up', (tester) async { await showChatMessageScreen(tester); diff --git a/test/views/after_auth_screens/chat/widgets/chat_input_field_test.dart b/test/views/after_auth_screens/chat/widgets/chat_input_field_test.dart index ed2a80187..d6f3fe51a 100644 --- a/test/views/after_auth_screens/chat/widgets/chat_input_field_test.dart +++ b/test/views/after_auth_screens/chat/widgets/chat_input_field_test.dart @@ -52,9 +52,12 @@ Widget createChatInputField() { } void main() { - SizeConfig().test(); - testSetupLocator(); - registerServices(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + registerServices(); + }); testWidgets("Check if chat input field shows up", (tester) async { await tester.pumpWidget(createChatInputField()); await tester.pumpAndSettle(); diff --git a/test/views/after_auth_screens/events/create_custom_recurring_event_test.dart b/test/views/after_auth_screens/events/create_custom_recurring_event_test.dart index 9043883d4..fbf53eb88 100644 --- a/test/views/after_auth_screens/events/create_custom_recurring_event_test.dart +++ b/test/views/after_auth_screens/events/create_custom_recurring_event_test.dart @@ -55,9 +55,12 @@ Widget createCustomRecurrenceScreen({ ); void main() { - SizeConfig().test(); - testSetupLocator(); - getAndRegisterNavigationService(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + getAndRegisterNavigationService(); + }); // setUp(() { // registerServices(); diff --git a/test/views/after_auth_screens/events/create_event_page_test.dart b/test/views/after_auth_screens/events/create_event_page_test.dart index c947afb14..7af45acc4 100644 --- a/test/views/after_auth_screens/events/create_event_page_test.dart +++ b/test/views/after_auth_screens/events/create_event_page_test.dart @@ -2,9 +2,11 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:intl/intl.dart'; import 'package:mockito/mockito.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; +import 'package:network_image_mock/network_image_mock.dart'; import 'package:talawa/constants/custom_theme.dart'; import 'package:talawa/router.dart' as router; import 'package:talawa/services/size_config.dart'; @@ -13,6 +15,7 @@ import 'package:talawa/utils/app_localization.dart'; import 'package:talawa/view_model/after_auth_view_models/event_view_models/create_event_view_model.dart'; import 'package:talawa/view_model/lang_view_model.dart'; import 'package:talawa/views/after_auth_screens/events/create_event_page.dart'; +import 'package:talawa/views/after_auth_screens/events/venue_bottom_sheet.dart'; import 'package:talawa/views/base_view.dart'; import 'package:talawa/widgets/recurrence_dialog.dart'; @@ -75,21 +78,147 @@ Widget createEventScreen({ ); void main() { - SizeConfig().test(); - testSetupLocator(); - // locator.unregister(); - locator.unregister(); - // locator.registerSingleton(OrganizationService()); - // locator.registerSingleton(LikeButtonViewModel()); - - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); registerServices(); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); group('testing -> CreateEventPage', () { + testWidgets("Checking if add venue button shows up", (tester) async { + await tester.pumpWidget( + createEventScreen( + themeMode: ThemeMode.dark, + theme: TalawaTheme.darkTheme, + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Add Venue'), findsOneWidget); + }); + testWidgets("Checking if bottom sheet appears if no venue is selcted", + (tester) async { + final model = CreateEventViewModel(); + model.initialize(); + final mockQueryResult = QueryResult( + source: QueryResultSource.network, + data: { + 'getVenueByOrgId': [ + { + 'id': '1', + 'name': 'Mock Venue 1', + 'capacity': 100, + 'imageUrl': 'xyz', + 'description': 'aaa', + }, + { + 'id': '2', + 'name': 'Mock Venue 2', + 'capacity': 150, + 'imageUrl': '', + 'description': 'aaa', + }, + ], + }, + options: QueryOptions(document: gql(queries.venueListQuery())), + ); + + when( + databaseFunctions.gqlAuthQuery( + queries.venueListQuery(), + variables: { + "orgId": 'XYZ', + }, + ), + ).thenAnswer((_) async => mockQueryResult); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + createEventScreen( + themeMode: ThemeMode.dark, + theme: TalawaTheme.darkTheme, + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Add Venue'), findsOneWidget); + await tester.tap(find.text('Add Venue')); + await tester.pumpAndSettle(); + + expect(find.byType(VenueBottomSheet), findsOneWidget); + }); + }); + testWidgets("Checking if selected venue shows up", (tester) async { + final model = createEventViewModel; + model.initialize(); + final mockQueryResult = QueryResult( + source: QueryResultSource.network, + data: { + 'getVenueByOrgId': [ + { + 'id': '1', + 'name': 'Mock Venue 1', + 'capacity': 100, + 'imageUrl': '/image/test', + 'description': 'aaa', + }, + { + 'id': '2', + 'name': 'Mock Venue 2', + 'capacity': 150, + 'imageUrl': '', + 'description': 'aaa', + }, + ], + }, + options: QueryOptions(document: gql(queries.venueListQuery())), + ); + + when( + databaseFunctions.gqlAuthQuery( + queries.venueListQuery(), + variables: { + "orgId": 'XYZ', + }, + ), + ).thenAnswer((_) async => mockQueryResult); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + createEventScreen( + themeMode: ThemeMode.dark, + theme: TalawaTheme.darkTheme, + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Add Venue'), findsOneWidget); + await tester.tap(find.text('Add Venue')); + await tester.pumpAndSettle(); + + expect(find.byType(VenueBottomSheet), findsOneWidget); + expect(find.text('Mock Venue 1'), findsOneWidget); + + await tester.tap(find.text('Mock Venue 1')); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.check)); + await tester.pumpAndSettle(); + + expect(find.text('Mock Venue 1'), findsOneWidget); + expect(find.byIcon(Icons.edit), findsOneWidget); + + expect(find.byIcon(Icons.cancel), findsOneWidget); + await tester.tap(find.byIcon(Icons.cancel)); + await tester.pumpAndSettle(); + + expect(find.text('Mock Venue 1'), findsNothing); + }); + }); testWidgets("Checking tap Inkwell for setDate 1 datetime", (tester) async { await tester.pumpWidget( createEventScreen( @@ -434,53 +563,6 @@ void main() { expect((tester.widgetList(switches).toList()[2] as Switch).value, false); }); - // testWidgets("Checking tap Inkwell work for admin list", (tester) async { - // await tester.pumpWidget( - // createEventScreen( - // themeMode: ThemeMode.dark, - // theme: TalawaTheme.darkTheme, - // ), - // ); - // await tester.pump(); - // final inkwellFinder = find.byType(InkWell); - // expect(inkwellFinder, findsNWidgets(8)); - - // ///returning the file variable to the - // ///result of function multimediaPickerService.getPhotoFromGallery - // ///when this function is called in the - // ///view model of add_post_page. - // final file = File('fakePath'); - - // /// using the new instance of multimediaPickerService - // /// so that when statement can be used again, - // /// else it gives null point exception - // final multimediaPickerService = locator(); - - // /// when is function provided by mockito lib - // when(multimediaPickerService.getPhotoFromGallery(camera: false)) - // .thenAnswer((_) async { - // return file; - // }); - - // await tester.ensureVisible(find.byKey(const Key('inwell_cep1'))); - // await tester.pumpAndSettle(); - - // await tester.tap(find.byKey(const Key('inwell_cep1'))); - // await tester.pump(); - - // //TODO: implement Rest of the test when the _adminCheckedMap or _memberCheckedMap return true for some id - // //TODO: for not it return false for all the ordMember.id - // // - // // orgMembersList.forEach((orgMember) { - // // if (isAdmin) { - // // _adminCheckedMap.putIfAbsent(orgMember.id!, () => false); - // // } else { - // // _memberCheckedMap.putIfAbsent(orgMember.id!, () => false); - // // } - // // _memberCheckedMap.putIfAbsent(orgMember.id!, () => false); - // // }); - // }); - testWidgets("Checking tap Inkwell for second add to bottom sheet", (tester) async { await tester.pumpWidget( @@ -524,33 +606,6 @@ void main() { await tester.pump(); }); group('setState Coverage completion', () { - testWidgets('Tap on DateTimeTile date', (tester) async { - await tester.pumpWidget( - createEventScreen( - themeMode: ThemeMode.dark, - theme: TalawaTheme.darkTheme, - ), - ); - await tester.pump(); - - await tester.tap(find.byKey(const Key('EventDateTimeTileDate')).first); - await tester.pump(); - - await tester.ensureVisible(find.byKey(const Key('key for test cep'))); - await tester.pump(); - - expect(find.byType(DatePickerDialog), findsOneWidget); - expect(find.byType(CalendarDatePicker), findsOneWidget); - - await tester.tap(find.text('OK')); - await tester.pumpAndSettle(); - - expect( - find.text(DateTime.now().toString().split(' ').first), - findsNWidgets(2), - ); - }); - testWidgets('Test end date selection', (tester) async { await tester.pumpWidget( createEventScreen( @@ -580,44 +635,6 @@ void main() { expect(find.text('Does not repeat'), findsOneWidget); }); - testWidgets('Tap on DateTimeTile time', (tester) async { - final currentTime = DateTime.now(); - final futureTime = currentTime.add(const Duration(minutes: 30)); - await tester.pumpWidget( - createEventScreen( - themeMode: ThemeMode.dark, - theme: TalawaTheme.darkTheme, - ), - ); - await tester.pumpAndSettle(); - - final switches = find.descendant( - of: find.byType(Row), - matching: find.byType(Switch), - ); - expect(switches, findsNWidgets(3)); - expect((tester.widgetList(switches).toList()[0] as Switch).value, true); - await tester.ensureVisible(switches.at(0)); - await tester.tap(switches.at(1)); - - await tester.pump(); - await tester.tap(find.byKey(const Key('EventDateTimeTileTime')).first); - await tester.pump(); - - expect(find.byType(TimePickerDialog), findsOneWidget); - - await tester.tap(find.text('OK')); - await tester.pump(); - expect( - find.text(DateFormat.jm().format(currentTime)), - findsOneWidget, - ); - - expect( - find.text(DateFormat.jm().format(futureTime)), - findsOneWidget, - ); - }); testWidgets('Tap on DateTimeTile date', (tester) async { await tester.pumpWidget( createEventScreen( diff --git a/test/views/after_auth_screens/events/event_filter_bottomsheet_test.dart b/test/views/after_auth_screens/events/event_filter_bottomsheet_test.dart index bd75c3302..8d80f75f5 100644 --- a/test/views/after_auth_screens/events/event_filter_bottomsheet_test.dart +++ b/test/views/after_auth_screens/events/event_filter_bottomsheet_test.dart @@ -50,13 +50,14 @@ Widget createExploreEventsScreen(MainScreenViewModel model) => MaterialApp( onGenerateRoute: router.generateRoute, ); void main() { - SizeConfig().test(); - testSetupLocator(); - locator.unregister(); - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + locator.unregister(); registerServices(); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); group('testing filters bottomsheet', () { diff --git a/test/views/after_auth_screens/events/event_info_body_test.dart b/test/views/after_auth_screens/events/event_info_body_test.dart index b7b8b5bba..03d8c47af 100644 --- a/test/views/after_auth_screens/events/event_info_body_test.dart +++ b/test/views/after_auth_screens/events/event_info_body_test.dart @@ -109,16 +109,17 @@ Widget createEventInfoBody({ } void main() { - testSetupLocator(); // locator().test(); - TestWidgetsFlutterBinding.ensureInitialized(); - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + + testSetupLocator(); registerServices(); locator().test(); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); diff --git a/test/views/after_auth_screens/events/venue_bottom_sheet_test.dart b/test/views/after_auth_screens/events/venue_bottom_sheet_test.dart new file mode 100644 index 000000000..5e8faf613 --- /dev/null +++ b/test/views/after_auth_screens/events/venue_bottom_sheet_test.dart @@ -0,0 +1,159 @@ +// ignore_for_file: talawa_api_doc +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:network_image_mock/network_image_mock.dart'; +import 'package:talawa/models/events/event_venue.dart'; +import 'package:talawa/services/size_config.dart'; +import 'package:talawa/utils/app_localization.dart'; +import 'package:talawa/views/after_auth_screens/events/venue_bottom_sheet.dart'; +import 'package:talawa/widgets/venue_card.dart'; + +import '../../../helpers/test_helpers.dart'; +import '../../../helpers/test_locator.dart'; + +Widget createVenueBottomSheet(List venues) { + return MaterialApp( + locale: const Locale('en'), + supportedLocales: [ + const Locale('en', 'US'), + const Locale('es', 'ES'), + const Locale('fr', 'FR'), + const Locale('hi', 'IN'), + const Locale('zh', 'CN'), + const Locale('de', 'DE'), + const Locale('ja', 'JP'), + const Locale('pt', 'PT'), + ], + localizationsDelegates: [ + const AppLocalizationsDelegate(isTest: true), + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ], + home: Scaffold( + body: VenueBottomSheet(venues: venues), + ), + ); +} + +List venues = [ + Venue( + id: '1', + capacity: 100, + description: 'A beautiful venue for events.', + imageUrl: 'http://localhost:4000/images/venue1.jpg', + name: 'Main Hall', + organizationId: 'org1', + ), + Venue( + id: '2', + capacity: 50, + description: 'A small cozy venue.', + imageUrl: 'http://localhost:4000/images/venue2.jpg', + name: 'Conference Room', + organizationId: 'org2', + ), +]; + +void main() { + testSetupLocator(); + group('VenueBottomSheet Widget Tests', () { + setUp(() { + registerServices(); + locator().test(); + }); + + testWidgets('Displays venues correctly', (WidgetTester tester) async { + await mockNetworkImagesFor(() async { + await tester.pumpWidget(createVenueBottomSheet(venues)); + await tester.pumpAndSettle(); + + expect(find.text('Add Venue'), findsOneWidget); + expect(find.byType(VenueCard), findsNWidgets(venues.length)); + expect(find.text('Main Hall'), findsOneWidget); + expect(find.text('Conference Room'), findsOneWidget); + + expect(find.byKey(const Key('gestureDetector1')), findsOneWidget); + await tester.tap(find.byKey(const Key('gestureDetector1'))); + await tester.pumpAndSettle(); + }); + }); + + testWidgets('Searches venues correctly', (WidgetTester tester) async { + await mockNetworkImagesFor(() async { + await tester.pumpWidget(createVenueBottomSheet(venues)); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.search)); + await tester.pumpAndSettle(); + + expect(find.byType(TextField), findsOneWidget); + + await tester.enterText(find.byType(TextField), 'Main'); + await tester.pumpAndSettle(); + + expect(find.byType(VenueCard), findsOneWidget); + expect(find.text('Main Hall'), findsOneWidget); + expect(find.text('Conference Room'), findsNothing); + + await tester.tap(find.byIcon(Icons.close)); + await tester.pumpAndSettle(); + + expect(find.byType(VenueCard), findsNWidgets(venues.length)); + }); + }); + + testWidgets('Selects a venue correctly', (WidgetTester tester) async { + await mockNetworkImagesFor(() async { + await tester.pumpWidget(createVenueBottomSheet(venues)); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Main Hall')); + await tester.pumpAndSettle(); + + expect(find.byIcon(Icons.check), findsOneWidget); + + await tester.tap(find.byIcon(Icons.check)); + await tester.pumpAndSettle(); + + expect(find.byIcon(Icons.arrow_back), findsNothing); + }); + }); + + testWidgets('Shows no venues available when list is empty', + (WidgetTester tester) async { + await mockNetworkImagesFor(() async { + await tester.pumpWidget(createVenueBottomSheet([])); + await tester.pumpAndSettle(); + + expect(find.text('No Venues added yet'), findsOneWidget); + }); + }); + testWidgets( + 'Shows no venues available when search query doesnt match with any venue', + (WidgetTester tester) async { + await mockNetworkImagesFor(() async { + await tester.pumpWidget(createVenueBottomSheet(venues)); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.search)); + await tester.pumpAndSettle(); + + expect(find.byType(TextField), findsOneWidget); + + await tester.enterText(find.byType(TextField), 'abc'); + await tester.pumpAndSettle(); + + expect(find.byType(VenueCard), findsNothing); + expect(find.text('Main Hall'), findsNothing); + expect(find.text('Conference Room'), findsNothing); + expect(find.text('No venues available'), findsOneWidget); + + await tester.tap(find.byIcon(Icons.close)); + await tester.pumpAndSettle(); + + expect(find.byType(VenueCard), findsNWidgets(venues.length)); + }); + }); + }); +} diff --git a/test/views/after_auth_screens/feed/individual_post_test.dart b/test/views/after_auth_screens/feed/individual_post_test.dart index 19c8b6f2b..351be4fef 100644 --- a/test/views/after_auth_screens/feed/individual_post_test.dart +++ b/test/views/after_auth_screens/feed/individual_post_test.dart @@ -178,10 +178,9 @@ Widget createCommentTemplateWidget(Comment comment) { } void main() { - SizeConfig().test(); - testSetupLocator(); - - setUp(() { + setUpAll(() { + SizeConfig().test(); + testSetupLocator(); registerServices(); }); diff --git a/test/views/after_auth_screens/join_org_after_auth_test/access_request_screen_test.dart b/test/views/after_auth_screens/join_org_after_auth_test/access_request_screen_test.dart index f061229e0..8f9acc7fc 100644 --- a/test/views/after_auth_screens/join_org_after_auth_test/access_request_screen_test.dart +++ b/test/views/after_auth_screens/join_org_after_auth_test/access_request_screen_test.dart @@ -28,7 +28,10 @@ Widget accessRequestScreen() { } void main() { - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + }); setUp(() => registerServices()); tearDown(() => unregisterServices()); group("SendRequestAccess Screen test", () { diff --git a/test/views/after_auth_screens/join_org_after_auth_test/join_organisation_after_auth_test.dart b/test/views/after_auth_screens/join_org_after_auth_test/join_organisation_after_auth_test.dart index 448d301d8..c2ac42036 100644 --- a/test/views/after_auth_screens/join_org_after_auth_test/join_organisation_after_auth_test.dart +++ b/test/views/after_auth_screens/join_org_after_auth_test/join_organisation_after_auth_test.dart @@ -44,16 +44,16 @@ Widget createJoinOrgAfterAuth({ } void main() { - testSetupLocator(); - locator().test(); - TestWidgetsFlutterBinding.ensureInitialized(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); - setUp(() { + testSetupLocator(); + locator().test(); registerServices(); locator().test(); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); diff --git a/test/views/after_auth_screens/org_info_screen_test.dart b/test/views/after_auth_screens/org_info_screen_test.dart index d10e7e4b7..20c174631 100644 --- a/test/views/after_auth_screens/org_info_screen_test.dart +++ b/test/views/after_auth_screens/org_info_screen_test.dart @@ -176,10 +176,10 @@ Widget createOrgInfoScreen2() { } void main() { - testSetupLocator(); - SizeConfig().test(); - GraphqlConfig().test(); - setUp(() { + setUpAll(() { + testSetupLocator(); + SizeConfig().test(); + GraphqlConfig().test(); registerServices(); }); group('OrganisationInfoScreen Tests', () { diff --git a/test/views/after_auth_screens/profile/profile_page_test.dart b/test/views/after_auth_screens/profile/profile_page_test.dart index 93d11d001..19c276b5d 100644 --- a/test/views/after_auth_screens/profile/profile_page_test.dart +++ b/test/views/after_auth_screens/profile/profile_page_test.dart @@ -47,41 +47,46 @@ Widget createProfilePage({required MainScreenViewModel mainScreenViewModel}) { } void main() async { - testSetupLocator(); - locator().test(); - final Directory dir = Directory('test/fixtures/coree'); - group('build', () { - setUpAll(() async { - registerServices(); - getAndRegisterAppTheme(); - Hive - ..init(dir.path) - ..registerAdapter(UserAdapter()) - ..registerAdapter(OrgInfoAdapter()); - await Hive.openBox('currentUser'); - await Hive.openBox('currentOrg'); - await Hive.openBox('pluginBox'); - }); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + registerServices(); + getAndRegisterAppTheme(); + }); - tearDownAll(() async { - await Hive.close(); - Future safeDelete(String filePath) async { - final file = File(filePath); - if (await file.exists()) { - try { - await file.delete(); - } catch (e) { - print('Error deleting $filePath: $e'); - } + tearDownAll(() async { + await Hive.close(); + Future safeDelete(String filePath) async { + final file = File(filePath); + if (await file.exists()) { + try { + await file.delete(); + } catch (e) { + print('Error deleting $filePath: $e'); } } + } - await safeDelete('test/fixtures/coree/currentorg.hive'); - await safeDelete('test/fixtures/coree/currentorg.lock'); - await safeDelete('test/fixtures/coree/currentuser.hive'); - await safeDelete('test/fixtures/coree/currentuser.lock'); - await safeDelete('test/fixtures/coree/pluginbox.hive'); - }); + await safeDelete('test/fixtures/coree/currentorg.hive'); + await safeDelete('test/fixtures/coree/currentorg.lock'); + await safeDelete('test/fixtures/coree/currentuser.hive'); + await safeDelete('test/fixtures/coree/currentuser.lock'); + await safeDelete('test/fixtures/coree/pluginbox.hive'); + }); + + late final Directory dir; + + dir = Directory('test/fixtures/coree'); + Hive + ..init(dir.path) + ..registerAdapter(UserAdapter()) + ..registerAdapter(OrgInfoAdapter()); + await Hive.openBox('currentUser'); + await Hive.openBox('currentOrg'); + await Hive.openBox('pluginBox'); + + group('build', () { testWidgets('check if profilePage shows up and refreshIndicator work', (tester) async { await tester.pumpWidget( diff --git a/test/views/after_auth_screens/profile/user_event_test.dart b/test/views/after_auth_screens/profile/user_event_test.dart index c210b26eb..8a4bb1a94 100644 --- a/test/views/after_auth_screens/profile/user_event_test.dart +++ b/test/views/after_auth_screens/profile/user_event_test.dart @@ -57,16 +57,16 @@ Widget userEventsScreen({ } void main() { - SizeConfig().test(); - testSetupLocator(); late MockExploreEventsViewModel mockViewModel; - setUp(() { + setUpAll(() { + SizeConfig().test(); + testSetupLocator(); registerServices(); mockViewModel = MockExploreEventsViewModel(); locator.unregister(); locator.registerSingleton(mockViewModel); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); group('tests for UserEvents Screen', () { diff --git a/test/views/after_auth_screens/profile/user_feed_test.dart b/test/views/after_auth_screens/profile/user_feed_test.dart index dc9ee4659..6c8429910 100644 --- a/test/views/after_auth_screens/profile/user_feed_test.dart +++ b/test/views/after_auth_screens/profile/user_feed_test.dart @@ -105,21 +105,22 @@ final post = Post( ); void main() { - SizeConfig().test(); - testSetupLocator(); late MockOrganizationFeedViewModel mockViewModel; - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + + SizeConfig().test(); + testSetupLocator(); registerServices(); mockViewModel = MockOrganizationFeedViewModel(); locator.unregister(); locator.registerSingleton(mockViewModel); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); - TestWidgetsFlutterBinding.ensureInitialized(); group('tests for User feed Screen', () { testWidgets('check if UserFeedScreen shows up', (tester) async { when(mockViewModel.isFetchingPosts).thenReturn(true); diff --git a/test/views/demo_screens/organization_feed_demo_test.dart b/test/views/demo_screens/organization_feed_demo_test.dart index 0767d0bea..d86261c18 100644 --- a/test/views/demo_screens/organization_feed_demo_test.dart +++ b/test/views/demo_screens/organization_feed_demo_test.dart @@ -39,9 +39,9 @@ Widget createHomeScreen({required bool demoMode}) { } void main() async { - testSetupLocator(); - - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); registerServices(); locator().test(); locator().test(); diff --git a/test/views/demo_screens/profile_page_demo_test.dart b/test/views/demo_screens/profile_page_demo_test.dart index 7e9426c1b..b536a2445 100644 --- a/test/views/demo_screens/profile_page_demo_test.dart +++ b/test/views/demo_screens/profile_page_demo_test.dart @@ -6,6 +6,7 @@ import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:talawa/constants/custom_theme.dart'; +// import 'package:talawa/locator.dart'; import 'package:talawa/models/mainscreen_navigation_args.dart'; import 'package:talawa/services/graphql_config.dart'; import 'package:talawa/services/size_config.dart'; @@ -14,6 +15,7 @@ import 'package:talawa/views/main_screen.dart'; import '../../helpers/test_helpers.dart'; import '../../helpers/test_locator.dart'; +// import '../../helpers/test_locator.dart'; class MockBuildContext extends Mock implements BuildContext {} @@ -39,14 +41,24 @@ Widget createProfileScreen({required bool demoMode}) { } void main() async { - testSetupLocator(); + // setUpAll(() { + // TestWidgetsFlutterBinding.ensureInitialized(); + // testSetupLocator(); + // }); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + registerServices(); + locator().test(); + locator().test(); + getAndRegisterNavigationService(); + }); + + tearDownAll(() { + unregisterServices(); + }); group('Profile Page tests', () { - setUpAll(() { - registerServices(); - locator().test(); - locator().test(); - }); testWidgets('Test for donate button.', (tester) async { await tester.pumpWidget(createProfileScreen(demoMode: true)); diff --git a/test/views/main_screen_test.dart b/test/views/main_screen_test.dart index f9a5afc12..29a36b358 100644 --- a/test/views/main_screen_test.dart +++ b/test/views/main_screen_test.dart @@ -95,12 +95,7 @@ class Test extends StatelessWidget { } void main() async { - testSetupLocator(); - registerServices(); - - TestWidgetsFlutterBinding.ensureInitialized(); - locator().test(); - locator().test(); + late GraphQLClient graphQLClient; final Directory dir = Directory('temporaryPath'); Hive @@ -114,11 +109,14 @@ void main() async { await Hive.openBox('pluginBox'); await Hive.openBox('url'); - late GraphQLClient graphQLClient; + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); - setUp(() { + testSetupLocator(); registerServices(); + locator().test(); locator().test(); + locator.unregister(); locator .registerFactory(() => MockMainScreenViewModel()); @@ -143,12 +141,13 @@ void main() async { ); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); group("Test for main_screen.dart", () { testWidgets('Test join org banner.', (tester) async { + MainScreenViewModel.demoMode = true; await tester.pumpWidget(createMainScreen()); await tester.pumpAndSettle(const Duration(seconds: 1)); @@ -160,8 +159,10 @@ void main() async { }); testWidgets("Test if Join Org banner not visible.", (tester) async { - await tester.pumpWidget(createMainScreen(demoMode: false)); - await tester.pump(); + MainScreenViewModel.demoMode = false; + await tester + .pumpWidget(createMainScreen(demoMode: MainScreenViewModel.demoMode)); + await tester.pumpAndSettle(const Duration(seconds: 1)); }); // // // Don't call pumpAndSettle as the BottomNavigationBar diff --git a/test/widget_tests/after_auth_screens/app_settings/app_setting_page_test.dart b/test/widget_tests/after_auth_screens/app_settings/app_setting_page_test.dart index 9fb34de38..7dd3f2c6d 100644 --- a/test/widget_tests/after_auth_screens/app_settings/app_setting_page_test.dart +++ b/test/widget_tests/after_auth_screens/app_settings/app_setting_page_test.dart @@ -74,11 +74,13 @@ Widget createAppSettingScreen({ThemeMode themeMode = ThemeMode.light}) => ); Future main() async { - testSetupLocator(); - TestWidgetsFlutterBinding.ensureInitialized(); - locator().test(); - SizeConfig().test(); - registerServices(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + SizeConfig().test(); + registerServices(); + }); group('Setting Page Screen Widget Test in dark mode', () { testWidgets("Testing if Settings Screen shows up", (tester) async { diff --git a/test/widget_tests/after_auth_screens/events/create_event_page_test.dart b/test/widget_tests/after_auth_screens/events/create_event_page_test.dart index c3a33cbf5..1fd243c16 100644 --- a/test/widget_tests/after_auth_screens/events/create_event_page_test.dart +++ b/test/widget_tests/after_auth_screens/events/create_event_page_test.dart @@ -48,9 +48,11 @@ Widget createEventScreen({ ); void main() { - SizeConfig().test(); - setupLocator(); - graphqlConfig.test(); + setUpAll(() { + SizeConfig().test(); + setupLocator(); + graphqlConfig.test(); + }); group("Create Event Screen Widget Test in dark mode", () { group('Check if the validator of the create_event_form is working', () { testWidgets("Testing if text field validator are working", diff --git a/test/widget_tests/after_auth_screens/events/edit_event_page_test.dart b/test/widget_tests/after_auth_screens/events/edit_event_page_test.dart index 821cad531..2167de07e 100644 --- a/test/widget_tests/after_auth_screens/events/edit_event_page_test.dart +++ b/test/widget_tests/after_auth_screens/events/edit_event_page_test.dart @@ -3,14 +3,19 @@ // ignore_for_file: unused_import +import 'dart:io'; + import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; import 'package:intl/intl.dart'; import 'package:mockito/mockito.dart'; import 'package:talawa/constants/custom_theme.dart'; import 'package:talawa/locator.dart'; import 'package:talawa/models/events/event_model.dart'; +import 'package:talawa/models/organization/org_info.dart'; +import 'package:talawa/models/user/user_info.dart'; import 'package:talawa/router.dart' as router; import 'package:talawa/services/database_mutation_functions.dart'; import 'package:talawa/services/size_config.dart'; @@ -69,9 +74,19 @@ Widget editEventScreen({ ); void main() { - SizeConfig().test(); - setupLocator(); - graphqlConfig.test(); + setUpAll(() async { + final Directory dir = Directory('temporaryPath'); + Hive + ..init(dir.path) + ..registerAdapter(UserAdapter()) + ..registerAdapter(OrgInfoAdapter()); + await Hive.openBox('currentUser'); + await Hive.openBox('currentOrg'); + await Hive.openBox('url'); + SizeConfig().test(); + setupLocator(); + graphqlConfig.test(); + }); group("Edit Event Screen Widget Test in dark mode", () { testWidgets("Testing if dark mode is applied", (tester) async { diff --git a/test/widget_tests/after_auth_screens/feed/individual_post_test.dart b/test/widget_tests/after_auth_screens/feed/individual_post_test.dart index a70efc78e..e223fb682 100644 --- a/test/widget_tests/after_auth_screens/feed/individual_post_test.dart +++ b/test/widget_tests/after_auth_screens/feed/individual_post_test.dart @@ -247,11 +247,11 @@ Widget createIndividualPostViewWidget({ } void main() { - SizeConfig().test(); - testSetupLocator(); // locator.registerSingleton(LikeButtonViewModel()); - setUp(() { + setUpAll(() { + SizeConfig().test(); + testSetupLocator(); registerServices(); }); diff --git a/test/widget_tests/after_auth_screens/feed/organization_feed_test.dart b/test/widget_tests/after_auth_screens/feed/organization_feed_test.dart index 795cc445a..b7072707c 100644 --- a/test/widget_tests/after_auth_screens/feed/organization_feed_test.dart +++ b/test/widget_tests/after_auth_screens/feed/organization_feed_test.dart @@ -105,21 +105,22 @@ final post = Post( ); void main() { - SizeConfig().test(); - testSetupLocator(); late MockOrganizationFeedViewModel mockViewModel; - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); registerServices(); mockViewModel = MockOrganizationFeedViewModel(); locator.unregister(); locator.registerSingleton(mockViewModel); }); - tearDown(() { + + tearDownAll(() { unregisterServices(); }); - TestWidgetsFlutterBinding.ensureInitialized(); group('tests for Organizaiton feed Screen', () { testWidgets('check if orgname is displayed shows up', (tester) async { when(mockViewModel.currentOrgName).thenReturn('testOrg'); diff --git a/test/widget_tests/after_auth_screens/feed/pinned_post_screen_test.dart b/test/widget_tests/after_auth_screens/feed/pinned_post_screen_test.dart index cb4734321..c61cb973b 100644 --- a/test/widget_tests/after_auth_screens/feed/pinned_post_screen_test.dart +++ b/test/widget_tests/after_auth_screens/feed/pinned_post_screen_test.dart @@ -51,9 +51,12 @@ Widget createApp() { } void main() { - SizeConfig().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); - testSetupLocator(); + testSetupLocator(); + }); group('description', () { testWidgets('Check if SignUp screen shows up', (tester) async { diff --git a/test/widget_tests/after_auth_screens/profile/edit_profile_page_test.dart b/test/widget_tests/after_auth_screens/profile/edit_profile_page_test.dart index f14ce1800..349e01738 100644 --- a/test/widget_tests/after_auth_screens/profile/edit_profile_page_test.dart +++ b/test/widget_tests/after_auth_screens/profile/edit_profile_page_test.dart @@ -70,10 +70,12 @@ Widget createEditProfilePage({ThemeMode themeMode = ThemeMode.light}) => }, ); Future main() async { - TestWidgetsFlutterBinding.ensureInitialized(); - testSetupLocator(); - locator().test(); - locator().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + locator().test(); + }); final Directory dir = Directory('temporaryPath'); Hive diff --git a/test/widget_tests/pre_auth_screens/change_password_page_test.dart b/test/widget_tests/pre_auth_screens/change_password_page_test.dart index 7a6ad9f6b..d70a068f7 100644 --- a/test/widget_tests/pre_auth_screens/change_password_page_test.dart +++ b/test/widget_tests/pre_auth_screens/change_password_page_test.dart @@ -45,9 +45,12 @@ Widget createChangePassScreen({ThemeMode themeMode = ThemeMode.light}) => ); void main() { - testSetupLocator(); - locator().test(); - locator().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + locator().test(); + }); group('Change Password Screen Widget Test in light mode', () { testWidgets("Testing if Change Password Screen shows up", (tester) async { await tester diff --git a/test/widget_tests/pre_auth_screens/login_test.dart b/test/widget_tests/pre_auth_screens/login_test.dart index 75268cd74..cf250e32e 100644 --- a/test/widget_tests/pre_auth_screens/login_test.dart +++ b/test/widget_tests/pre_auth_screens/login_test.dart @@ -43,8 +43,11 @@ Future showLoginScreen(WidgetTester tester) async { } void main() { - SizeConfig().test(); - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + }); group('Test for Login screen', () { testWidgets('Check if Login screen shows up', (tester) async { await tester.pumpWidget(createApp()); diff --git a/test/widget_tests/pre_auth_screens/recover_page_test.dart b/test/widget_tests/pre_auth_screens/recover_page_test.dart index 7c3988a83..dbfc2a115 100644 --- a/test/widget_tests/pre_auth_screens/recover_page_test.dart +++ b/test/widget_tests/pre_auth_screens/recover_page_test.dart @@ -60,9 +60,12 @@ Widget createRecoverScreenDark({ThemeMode themeMode = ThemeMode.dark}) => ); void main() { - testSetupLocator(); - locator().test(); - locator().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + locator().test(); + }); group('Select Language Screen Widget Test in light mode', () { testWidgets("Testing if Select Language Screen shows up", (tester) async { await tester.pumpWidget(createRecoverScreenLight()); diff --git a/test/widget_tests/pre_auth_screens/select_language_page_test.dart b/test/widget_tests/pre_auth_screens/select_language_page_test.dart index cafd870c4..bde36d46c 100644 --- a/test/widget_tests/pre_auth_screens/select_language_page_test.dart +++ b/test/widget_tests/pre_auth_screens/select_language_page_test.dart @@ -68,7 +68,6 @@ Widget createSelectLanguageScreenDark({ThemeMode themeMode = ThemeMode.dark}) => ); Future main() async { - TestWidgetsFlutterBinding.ensureInitialized(); //initializing Hive const testMockStorage = 'test/fixtures/core'; Hive @@ -80,9 +79,13 @@ Future main() async { await Hive.openBox('currentOrg'); // await Hive.openBox('url'); - testSetupLocator(); - locator().test(); - locator().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + + testSetupLocator(); + locator().test(); + locator().test(); + }); group('Select Language Screen Widget Test in light mode', () { testWidgets("Testing if Select Language Screen shows up", (tester) async { diff --git a/test/widget_tests/pre_auth_screens/set_url_page_test.dart b/test/widget_tests/pre_auth_screens/set_url_page_test.dart index fc9b6d16f..8f136eee3 100644 --- a/test/widget_tests/pre_auth_screens/set_url_page_test.dart +++ b/test/widget_tests/pre_auth_screens/set_url_page_test.dart @@ -58,7 +58,6 @@ Widget createSetUrlScreen({ ); Future main() async { - TestWidgetsFlutterBinding.ensureInitialized(); const testMockStorage = 'test/fixtures/core'; Hive ..init(testMockStorage) @@ -69,12 +68,14 @@ Future main() async { // await Hive.openBox('currentOrg'); await Hive.openBox('url'); //setting up MVVM - setupLocator(); - //initializing test functions - locator().test(); - locator().test(); - setUp(() async { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + setupLocator(); registerServices(); + + //initializing test functions + locator().test(); + locator().test(); }); //Testing in light mode/normal mode diff --git a/test/widget_tests/pre_auth_screens/signup_details_test.dart b/test/widget_tests/pre_auth_screens/signup_details_test.dart index 032b4af28..820d5457b 100644 --- a/test/widget_tests/pre_auth_screens/signup_details_test.dart +++ b/test/widget_tests/pre_auth_screens/signup_details_test.dart @@ -48,9 +48,12 @@ Future showSignUpScreen(WidgetTester tester) async { } void main() { - SizeConfig().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); - testSetupLocator(); + testSetupLocator(); + }); group('Test For SignUp Screen', () { testWidgets('Check if SignUp screen shows up', (tester) async { diff --git a/test/widget_tests/pre_auth_screens/splash_screen_test.dart b/test/widget_tests/pre_auth_screens/splash_screen_test.dart index 855d49189..50f08eab4 100644 --- a/test/widget_tests/pre_auth_screens/splash_screen_test.dart +++ b/test/widget_tests/pre_auth_screens/splash_screen_test.dart @@ -64,8 +64,10 @@ Widget createSplashScreenDark({ThemeMode themeMode = ThemeMode.dark}) => ); Future main() async { - setupLocator(); - graphqlConfig.test(); + setUpAll(() { + setupLocator(); + graphqlConfig.test(); + }); group('Splash Screen Widget Test in light mode', () { testWidgets("Testing if Splash Screen shows up", (tester) async { diff --git a/test/widget_tests/widgets/custom_alert_dialog_test.dart b/test/widget_tests/widgets/custom_alert_dialog_test.dart index 754b15650..b05950d59 100644 --- a/test/widget_tests/widgets/custom_alert_dialog_test.dart +++ b/test/widget_tests/widgets/custom_alert_dialog_test.dart @@ -66,8 +66,11 @@ Widget createCustomAlertDialog({ } void main() { - SizeConfig().test(); - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + }); group('Test for CustomAlertDialog', () { testWidgets('Check if the AlertDialog shows up', (tester) async { await tester.pumpWidget(createCustomAlertDialog()); diff --git a/test/widget_tests/widgets/custom_drawer_test.dart b/test/widget_tests/widgets/custom_drawer_test.dart index 08e6f9e11..1b138f781 100644 --- a/test/widget_tests/widgets/custom_drawer_test.dart +++ b/test/widget_tests/widgets/custom_drawer_test.dart @@ -78,12 +78,13 @@ Widget createHomePageScreen({required bool demoMode}) { } void main() async { - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); - setUp(() { - registerServices(); locator().test(); locator().test(); + registerServices(); }); final Directory dir = Directory('test/fixtures/core'); @@ -99,6 +100,13 @@ void main() async { await Hive.openBox('pluginBox'); await Hive.openBox('url'); + // setUp(() { + // }); + + tearDownAll(() { + unregisterServices(); + }); + group('Exit Button', () { testWidgets("Tapping Tests for Exit", (tester) async { final customDrawerViewModel = CustomDrawerViewModel(); @@ -310,8 +318,4 @@ void main() async { // await tester.pumpAndSettle(); });*/ }); - - tearDown(() { - unregisterServices(); - }); } diff --git a/test/widget_tests/widgets/custom_progress_dialog_test.dart b/test/widget_tests/widgets/custom_progress_dialog_test.dart index fe337fb3f..e9ba62364 100644 --- a/test/widget_tests/widgets/custom_progress_dialog_test.dart +++ b/test/widget_tests/widgets/custom_progress_dialog_test.dart @@ -6,7 +6,6 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/mockito.dart'; import 'package:talawa/locator.dart'; import 'package:talawa/router.dart' as router; import 'package:talawa/services/navigation_service.dart'; @@ -15,6 +14,7 @@ import 'package:talawa/utils/app_localization.dart'; import 'package:talawa/widgets/custom_progress_dialog.dart'; import '../../helpers/test_helpers.dart'; +import '../../service_tests/third_party_service_test.dart/connectivity_service_test.dart'; Widget createCustomProgressDialog() { return MaterialApp( @@ -51,10 +51,6 @@ void main() { testWidgets( 'Check if CustomProgressDialog widget shows up when connection available', (tester) async { - // Setup connectivity for connection available - when(connectivity.checkConnectivity()) - .thenAnswer((_) async => ConnectivityResult.wifi); - // Build the widget await tester.pumpWidget(createCustomProgressDialog()); await tester.pump(); @@ -70,8 +66,7 @@ void main() { locator.registerSingleton(NavigationService()); // Setup connectivity for connection not available - when(connectivity.checkConnectivity()) - .thenAnswer((_) async => ConnectivityResult.none); + connectivityStatus = ConnectivityResult.none; // Build the widget await tester.pumpWidget(createCustomProgressDialog()); diff --git a/test/widget_tests/widgets/event_card_test.dart b/test/widget_tests/widgets/event_card_test.dart index 202d20e18..51fab396b 100644 --- a/test/widget_tests/widgets/event_card_test.dart +++ b/test/widget_tests/widgets/event_card_test.dart @@ -59,10 +59,11 @@ Widget createCustomEventCard( } void main() { - SizeConfig().test(); - testSetupLocator(); - - TestWidgetsFlutterBinding.ensureInitialized(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + }); group("Test for EventCard widget", () { testWidgets('Check if Event Card shows up', (tester) async { diff --git a/test/widget_tests/widgets/event_date_time_tile_test.dart b/test/widget_tests/widgets/event_date_time_tile_test.dart index 4fb0c6e0d..41f22175b 100644 --- a/test/widget_tests/widgets/event_date_time_tile_test.dart +++ b/test/widget_tests/widgets/event_date_time_tile_test.dart @@ -47,8 +47,11 @@ Widget createWidget() { } void main() { - testSetupLocator(); - locator().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + }); setUp(() { registerServices(); diff --git a/test/widget_tests/widgets/lang_switch_test.dart b/test/widget_tests/widgets/lang_switch_test.dart index 02b6be38f..6140030b4 100644 --- a/test/widget_tests/widgets/lang_switch_test.dart +++ b/test/widget_tests/widgets/lang_switch_test.dart @@ -33,8 +33,11 @@ Widget createLanguageTile() { } void main() { - testSetupLocator(); - sizeConfig.test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + sizeConfig.test(); + }); group('Test for LanguageTile', () { testWidgets('Check if LanguageTile widget shows up', (tester) async { await tester.pumpWidget(createLanguageTile()); diff --git a/test/widget_tests/widgets/pinned_carousel_widget_test.dart b/test/widget_tests/widgets/pinned_carousel_widget_test.dart index 2b68f2d43..0bef6213f 100644 --- a/test/widget_tests/widgets/pinned_carousel_widget_test.dart +++ b/test/widget_tests/widgets/pinned_carousel_widget_test.dart @@ -54,8 +54,11 @@ Widget createPinnedCarouselWidget() { } void main() { - testSetupLocator(); - SizeConfig().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + SizeConfig().test(); + }); group('Test for PinnedPostCarousel', () { testWidgets('Check if the widget shows up', (tester) async { await tester.pumpWidget(createPinnedCarouselWidget()); diff --git a/test/widget_tests/widgets/pinned_post_test.dart b/test/widget_tests/widgets/pinned_post_test.dart index 51a1533bf..96684df0a 100644 --- a/test/widget_tests/widgets/pinned_post_test.dart +++ b/test/widget_tests/widgets/pinned_post_test.dart @@ -73,14 +73,14 @@ List get pinnedPosts { /// **returns**: /// None void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - testSetupLocator(); - locator().test(); - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); registerServices(); locator().test(); }); - tearDown(() { + tearDownAll(() { unregisterServices(); }); diff --git a/test/widget_tests/widgets/post_modal_test.dart b/test/widget_tests/widgets/post_modal_test.dart index 0ee90eb12..609c7a623 100644 --- a/test/widget_tests/widgets/post_modal_test.dart +++ b/test/widget_tests/widgets/post_modal_test.dart @@ -115,14 +115,14 @@ Widget createPostBottomModal() { } void main() { - SizeConfig().test(); - testSetupLocator(); - - setUp(() { + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); registerServices(); }); - tearDown(() => unregisterServices()); + tearDownAll(() => unregisterServices()); group('PostBottomModalTest -', () { testWidgets('has a post widget', (tester) async { diff --git a/test/widget_tests/widgets/recurrence_dialog_test.dart b/test/widget_tests/widgets/recurrence_dialog_test.dart index 6909cf2bc..08b43ff58 100644 --- a/test/widget_tests/widgets/recurrence_dialog_test.dart +++ b/test/widget_tests/widgets/recurrence_dialog_test.dart @@ -10,11 +10,14 @@ import '../../helpers/test_helpers.dart'; import '../../helpers/test_locator.dart'; void main() { + late CreateEventViewModel model; + group('ShowRecurrenceDialog', () { - TestWidgetsFlutterBinding.ensureInitialized(); - testSetupLocator(); - locator().test(); - late CreateEventViewModel model; + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + }); setUp(() { locator().test(); diff --git a/test/widget_tests/widgets/talawa_error_dialog_test.dart b/test/widget_tests/widgets/talawa_error_dialog_test.dart index bcbe81e68..9ea0786de 100644 --- a/test/widget_tests/widgets/talawa_error_dialog_test.dart +++ b/test/widget_tests/widgets/talawa_error_dialog_test.dart @@ -166,8 +166,11 @@ Widget createTalawaErrorWidget4({ } void main() { - SizeConfig().test(); - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + }); group('Test for TalawaErrorWidget', () { testWidgets('Check if the Error Widget shows up(error)', (tester) async { await tester.pumpWidget(createTalawaErrorWidget1()); diff --git a/test/widget_tests/widgets/talawa_error_snackbar_test.dart b/test/widget_tests/widgets/talawa_error_snackbar_test.dart index 7469fe712..13e2c1108 100644 --- a/test/widget_tests/widgets/talawa_error_snackbar_test.dart +++ b/test/widget_tests/widgets/talawa_error_snackbar_test.dart @@ -127,8 +127,11 @@ Widget createTalawaErrorWidget3({ } void main() { - SizeConfig().test(); - testSetupLocator(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + SizeConfig().test(); + testSetupLocator(); + }); group('Test for TalawaErrorWidget', () { testWidgets('Check if the Snackbar shows up in warning form', (tester) async { diff --git a/test/widget_tests/widgets/theme_switch_test.dart b/test/widget_tests/widgets/theme_switch_test.dart index 0da53d784..b0496aeca 100644 --- a/test/widget_tests/widgets/theme_switch_test.dart +++ b/test/widget_tests/widgets/theme_switch_test.dart @@ -44,8 +44,11 @@ class LocalizationsInj extends StatelessWidget { } void main() { - testSetupLocator(); - locator().test(); + setUpAll(() { + TestWidgetsFlutterBinding.ensureInitialized(); + testSetupLocator(); + locator().test(); + }); setUp(() { registerServices(); diff --git a/test/widget_tests/widgets/venue_card_test.dart b/test/widget_tests/widgets/venue_card_test.dart new file mode 100644 index 000000000..90fc001bc --- /dev/null +++ b/test/widget_tests/widgets/venue_card_test.dart @@ -0,0 +1,107 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:network_image_mock/network_image_mock.dart'; +import 'package:talawa/models/events/event_venue.dart'; +import 'package:talawa/services/graphql_config.dart'; +import 'package:talawa/services/size_config.dart'; +import 'package:talawa/widgets/venue_card.dart'; + +import '../../helpers/test_helpers.dart'; +import '../../helpers/test_locator.dart'; + +void main() { + testSetupLocator(); + setUp(() { + GraphqlConfig.orgURI = 'http://example.com/graphql'; + registerServices(); + locator().test(); + }); + + group('VenueCard Widget Tests', () { + testWidgets('Displays venue details correctly', + (WidgetTester tester) async { + final venue = Venue( + id: '1', + capacity: 100, + description: 'A beautiful venue for events.', + imageUrl: 'http://localhost:4000/images/venue.jpg', + name: 'Main Hall', + organizationId: 'org1', + ); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: VenueCard( + venue: venue, + isSelected: false, + ), + ), + ), + ); + + expect(find.text('Main Hall'), findsOneWidget); + expect(find.text('Capacity: 100'), findsOneWidget); + expect(find.text('A beautiful venue for events.'), findsOneWidget); + expect(find.byIcon(Icons.check_circle), findsNothing); + }); + }); + + testWidgets('Displays selected state correctly', + (WidgetTester tester) async { + final venue = Venue( + id: '1', + capacity: 100, + description: 'A beautiful venue for events.', + imageUrl: 'http://localhost:4000/images/venue.jpg', + name: 'Main Hall', + organizationId: 'org1', + ); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: VenueCard( + venue: venue, + isSelected: true, + ), + ), + ), + ); + + expect(find.byIcon(Icons.check_circle), findsOneWidget); + }); + }); + + testWidgets('Displays default image when imageUrl is empty', + (WidgetTester tester) async { + final venue = Venue( + id: '1', + capacity: 100, + description: 'A beautiful venue for events.', + imageUrl: '', + name: 'Main Hall', + organizationId: 'org1', + ); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: VenueCard( + venue: venue, + isSelected: false, + ), + ), + ), + ); + expect( + find.byKey(const Key('image_container')), + findsWidgets, + ); + }); + }); + }); +}