From e269cffd4264157a3ad0d5d9f807fcc94face3c4 Mon Sep 17 00:00:00 2001 From: demola234 Date: Sun, 27 Aug 2023 05:23:08 +0100 Subject: [PATCH 1/2] unit tests --- lib/core/network/network_provider.dart | 55 +- lib/core/secure/secure_storage.dart | 9 +- .../authentication_local_datasource.dart | 2 +- .../authentication_remote_data_source.dart | 16 - .../authentication_repository.dart | 25 +- .../campaign_category_entities.dart | 37 - .../campaign_category_entities.freezed.dart | 380 ------- .../campaign_category_entities.g.dart | 39 - .../entities/campaigns/campaigns_entity.dart | 72 -- .../campaigns/campaigns_entity.freezed.dart | 930 ------------------ .../campaigns/campaigns_entity.g.dart | 88 -- .../repositories/campaign_repository.dart | 9 - .../usecases/campaign_catergory_usecase.dart | 16 - .../domain/usecases/get_campaigns.dart | 16 - .../presentation/view/campaigns_screen.dart | 6 +- .../presentation/view/donations_screen.dart | 6 +- .../campaign_remote_date_source.dart | 76 +- .../repositories/campaign_repository.dart | 1 + .../entities/campaigns/campaigns_entity.dart | 2 +- .../campaigns/campaigns_entity.freezed.dart | 32 +- .../campaigns/campaigns_entity.g.dart | 4 +- .../entities/donors_entity/donors_entity.dart | 2 +- .../donors_entity/donors_entity.freezed.dart | 32 +- .../donors_entity/donors_entity.g.dart | 4 +- .../view/category_campaign_screen.dart | 6 +- .../view/latest_funding_screen.dart | 22 +- .../view/view_donation_screen.dart | 4 +- test/core/network/network_provider_test.dart | 6 +- ...uthentication_remote_data_source_test.dart | 93 +- .../authentication_repository_test.dart | 100 ++ .../check_user_exist_usecase_test.dart | 72 ++ .../check_user_exist_usecase_test.mocks.dart | 291 ++++++ .../get_user_details_usecase_test.dart | 69 ++ .../get_user_details_usecase_test.mocks.dart | 291 ++++++ .../state/bloc/forget_password_bloc_test.dart | 144 +++ .../bloc/forget_password_bloc_test.mocks.dart | 124 +++ .../bloc/get_user_details_bloc_test.dart | 85 ++ .../get_user_details_bloc_test.mocks.dart | 87 ++ .../bloc/set_profile_avatar_bloc_test.dart | 88 ++ .../set_profile_avatar_bloc_test.mocks.dart | 86 ++ .../create_password_bloc_test.dart | 101 ++ .../create_password_bloc_test.mocks.dart | 85 ++ .../bloc/verify_otp_bloc_test.dart | 104 ++ .../bloc/verify_otp_bloc_test.mocks.dart | 84 ++ .../campaign_remote_data_source_test.dart | 379 +++++++ .../campaign_repository_test.dart | 261 +++++ .../campaign/campaigns_entity_test.dart | 73 ++ .../campaign_categories_entity_test.dart | 51 + .../donors_entity/donors_entity_test.dart | 51 + .../campaign_catergory_usecase_test.dart | 73 ++ ...campaign_catergory_usecase_test.mocks.dart | 242 +++++ .../create_donation_usecase_test.dart | 116 +++ .../current_eth_price_usecases_test.dart | 67 ++ ...get_campaign_by_category_usecase_test.dart | 106 ++ .../domain/usecases/get_campaigns_test.dart | 95 ++ .../usecases/get_donations_usecase_test.dart | 95 ++ .../usecases/get_donors_usecase_test.dart | 84 ++ .../usecases/make_donation_usecase_test.dart | 85 ++ .../fixture/campaign_categories_response.json | 12 + test/fixture/campaign_failed_response.json | 5 + test/fixture/campaign_reesponse.json | 34 + test/fixture/donors_response.json | 12 + 62 files changed, 3899 insertions(+), 1743 deletions(-) delete mode 100644 lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.dart delete mode 100644 lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.freezed.dart delete mode 100644 lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.g.dart delete mode 100644 lib/features/donation/domain/entities/campaigns/campaigns_entity.dart delete mode 100644 lib/features/donation/domain/entities/campaigns/campaigns_entity.freezed.dart delete mode 100644 lib/features/donation/domain/entities/campaigns/campaigns_entity.g.dart delete mode 100644 lib/features/donation/domain/repositories/campaign_repository.dart delete mode 100644 lib/features/donation/domain/usecases/campaign_catergory_usecase.dart delete mode 100644 lib/features/donation/domain/usecases/get_campaigns.dart create mode 100644 test/feature/authentication/domain/usecases/check_user_exist_usecase_test.dart create mode 100644 test/feature/authentication/domain/usecases/check_user_exist_usecase_test.mocks.dart create mode 100644 test/feature/authentication/domain/usecases/get_user_details_usecase_test.dart create mode 100644 test/feature/authentication/domain/usecases/get_user_details_usecase_test.mocks.dart create mode 100644 test/feature/authentication/presentation/forget_password/state/bloc/forget_password_bloc_test.dart create mode 100644 test/feature/authentication/presentation/forget_password/state/bloc/forget_password_bloc_test.mocks.dart create mode 100644 test/feature/authentication/presentation/login/state/get_user_details/bloc/get_user_details_bloc_test.dart create mode 100644 test/feature/authentication/presentation/login/state/get_user_details/bloc/get_user_details_bloc_test.mocks.dart create mode 100644 test/feature/authentication/presentation/login/state/set_profile_avatar/bloc/set_profile_avatar_bloc_test.dart create mode 100644 test/feature/authentication/presentation/login/state/set_profile_avatar/bloc/set_profile_avatar_bloc_test.mocks.dart create mode 100644 test/feature/authentication/presentation/signup/state/create_password_bloc/create_password_bloc_test.dart create mode 100644 test/feature/authentication/presentation/signup/state/create_password_bloc/create_password_bloc_test.mocks.dart create mode 100644 test/feature/authentication/presentation/signup/state/verify_bloc/bloc/verify_otp_bloc_test.dart create mode 100644 test/feature/authentication/presentation/signup/state/verify_bloc/bloc/verify_otp_bloc_test.mocks.dart create mode 100644 test/feature/home/data/data_source/campaign_remote_data_source_test.dart create mode 100644 test/feature/home/data/repositories/campaign_repository_test.dart create mode 100644 test/feature/home/domain/entities/campaign/campaigns_entity_test.dart create mode 100644 test/feature/home/domain/entities/campaign_categories_entity/campaign_categories_entity_test.dart create mode 100644 test/feature/home/domain/entities/donors_entity/donors_entity_test.dart create mode 100644 test/feature/home/domain/usecases/campaign_catergory_usecase_test.dart create mode 100644 test/feature/home/domain/usecases/campaign_catergory_usecase_test.mocks.dart create mode 100644 test/feature/home/domain/usecases/create_donation_usecase_test.dart create mode 100644 test/feature/home/domain/usecases/current_eth_price_usecases_test.dart create mode 100644 test/feature/home/domain/usecases/get_campaign_by_category_usecase_test.dart create mode 100644 test/feature/home/domain/usecases/get_campaigns_test.dart create mode 100644 test/feature/home/domain/usecases/get_donations_usecase_test.dart create mode 100644 test/feature/home/domain/usecases/get_donors_usecase_test.dart create mode 100644 test/feature/home/domain/usecases/make_donation_usecase_test.dart create mode 100644 test/fixture/campaign_categories_response.json create mode 100644 test/fixture/campaign_failed_response.json create mode 100644 test/fixture/campaign_reesponse.json create mode 100644 test/fixture/donors_response.json diff --git a/lib/core/network/network_provider.dart b/lib/core/network/network_provider.dart index da6ba20..1cefb46 100644 --- a/lib/core/network/network_provider.dart +++ b/lib/core/network/network_provider.dart @@ -4,9 +4,13 @@ import 'package:curl_logger_dio_interceptor/curl_logger_dio_interceptor.dart'; // 🌎 Project imports: import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/core/secure/secure_key.dart'; import 'package:dio/dio.dart'; import 'package:pretty_dio_logger/pretty_dio_logger.dart'; +import '../di/injector.dart'; +import '../secure/secure.dart'; + abstract class NetworkProvider { Future call({ required String path, @@ -63,28 +67,59 @@ class NetworkProviderImpl extends NetworkProvider { Options? options, Map queryParams = const {}, }) async { + final token = + await sl().getAccessToken(SecureStorageKey().token); Response? response; try { switch (method) { case RequestMethod.get: - response = await _getDioInstance() - .get(path, queryParameters: queryParams, options: options); + response = await _getDioInstance().get( + path, + queryParameters: queryParams, + options: Options(headers: { + 'Authorization': 'Bearer $token', + }), + ); break; case RequestMethod.post: - response = await _getDioInstance().post(path, - data: body, queryParameters: queryParams, options: options); + response = await _getDioInstance().post( + path, + data: body, + queryParameters: queryParams, + options: Options(headers: { + 'Authorization': 'Bearer $token', + }), + ); break; case RequestMethod.patch: - response = await _getDioInstance().patch(path, - data: body, queryParameters: queryParams, options: options); + response = await _getDioInstance().patch( + path, + data: body, + queryParameters: queryParams, + options: Options(headers: { + 'Authorization': 'Bearer $token', + }), + ); break; case RequestMethod.put: - response = await _getDioInstance().put(path, - data: body, queryParameters: queryParams, options: options); + response = await _getDioInstance().put( + path, + data: body, + queryParameters: queryParams, + options: Options(headers: { + 'Authorization': 'Bearer $token', + }), + ); break; case RequestMethod.delete: - response = await _getDioInstance().delete(path, - data: body, queryParameters: queryParams, options: options); + response = await _getDioInstance().delete( + path, + data: body, + queryParameters: queryParams, + options: Options(headers: { + 'Authorization': 'Bearer $token', + }), + ); break; } diff --git a/lib/core/secure/secure_storage.dart b/lib/core/secure/secure_storage.dart index 5b816c8..cceae63 100644 --- a/lib/core/secure/secure_storage.dart +++ b/lib/core/secure/secure_storage.dart @@ -27,14 +27,7 @@ class ISecureStorage implements SecureStorage { Future getHiveKey(String hiveKey) async { return await _flutterSecureStorage.read( key: hiveKey, - aOptions: AndroidOptions( - encryptedSharedPreferences: true, - keyCipherAlgorithm: - KeyCipherAlgorithm.RSA_ECB_OAEPwithSHA_256andMGF1Padding), - iOptions: IOSOptions( - synchronizable: true, - accessibility: KeychainAccessibility.first_unlock, - ), + ); } diff --git a/lib/features/authentication/data/data_source/authentication_local_datasource.dart b/lib/features/authentication/data/data_source/authentication_local_datasource.dart index 4dc7e8a..f3f5404 100644 --- a/lib/features/authentication/data/data_source/authentication_local_datasource.dart +++ b/lib/features/authentication/data/data_source/authentication_local_datasource.dart @@ -12,7 +12,7 @@ abstract class AuthLocalDataSource { required LastUserCachedDetails lastUserCachedDetails, }); - Future cacheUserDetails({ + cacheUserDetails({ required UserResponse user, }); diff --git a/lib/features/authentication/data/data_source/authentication_remote_data_source.dart b/lib/features/authentication/data/data_source/authentication_remote_data_source.dart index 09c80fe..d0b7a83 100644 --- a/lib/features/authentication/data/data_source/authentication_remote_data_source.dart +++ b/lib/features/authentication/data/data_source/authentication_remote_data_source.dart @@ -1,14 +1,10 @@ -import 'package:defiraiser_mobile/core/di/injector.dart'; import 'package:defiraiser_mobile/core/global/error/exceptions.dart'; import 'package:defiraiser_mobile/core/network/endpoint_manager.dart'; import 'package:defiraiser_mobile/core/network/network_provider.dart'; -import 'package:defiraiser_mobile/core/secure/secure.dart'; -import 'package:defiraiser_mobile/core/secure/secure_key.dart'; import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; import 'package:defiraiser_mobile/features/authentication/domain/entities/check_user_entity/check_user_entity.dart'; import 'package:defiraiser_mobile/features/authentication/domain/entities/login_entity/login_response_entity.dart'; import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart'; -import 'package:dio/dio.dart'; abstract class AuthenticationRemoteDataSource { Future createAccount(String username, String email); @@ -177,16 +173,10 @@ class IAuthenticationRemoteDataSource @override Future setProfile({required int imageId}) async { - final token = - await sl().getAccessToken(SecureStorageKey().token); - final response = await client.call( path: EndpointManager.setProfileAvatar, method: RequestMethod.post, body: {'image_id': imageId}, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), ); final res = response!.data['data']; if (response.statusCode == 200) { @@ -198,15 +188,9 @@ class IAuthenticationRemoteDataSource @override Future getUserDetails() async { - final token = - await sl().getAccessToken(SecureStorageKey().token); - final response = await client.call( path: EndpointManager.getUser, method: RequestMethod.get, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), ); final res = response!.data['data']; if (response.statusCode == 200) { diff --git a/lib/features/authentication/data/repositories/authentication_repository.dart b/lib/features/authentication/data/repositories/authentication_repository.dart index a565277..8808d84 100644 --- a/lib/features/authentication/data/repositories/authentication_repository.dart +++ b/lib/features/authentication/data/repositories/authentication_repository.dart @@ -37,17 +37,20 @@ class IAuthenticationRepository implements AuthenticationRepository { {required String username, required String password}) async { try { final remoteLogin = await remoteDataSource.login(username, password); - final lastCacheDetails = LastUserCachedDetails( - password: password, - username: username, - email: remoteLogin.data!.user.email, - isBiometric: remoteLogin.data!.user.biometrics, - ); - await authLocalDataSource.cacheUserLoginData( - lastUserCachedDetails: lastCacheDetails); - await authLocalDataSource.cacheUserDetails(user: remoteLogin.data!.user); - await authLocalDataSource.saveAccessToken( - token: remoteLogin.data!.accessToken); + if (remoteLogin.data != null) { + final lastCacheDetails = LastUserCachedDetails( + password: password, + username: username, + email: remoteLogin.data!.user.email, + isBiometric: remoteLogin.data!.user.biometrics, + ); + await authLocalDataSource.cacheUserLoginData( + lastUserCachedDetails: lastCacheDetails); + await authLocalDataSource.cacheUserDetails( + user: remoteLogin.data!.user); + await authLocalDataSource.saveAccessToken( + token: remoteLogin.data!.accessToken); + } return Right(remoteLogin); } on ApiError catch (error) { return Left(error); diff --git a/lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.dart b/lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.dart deleted file mode 100644 index 1640b2c..0000000 --- a/lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.dart +++ /dev/null @@ -1,37 +0,0 @@ -import 'dart:convert'; - -import 'package:freezed_annotation/freezed_annotation.dart'; - -part 'campaign_category_entities.freezed.dart'; -part 'campaign_category_entities.g.dart'; - -CampaignCategories campaignCategoriesFromJson(String str) => - CampaignCategories.fromJson(json.decode(str)); - -String campaignCategoriesToJson(CampaignCategories data) => - json.encode(data.toJson()); - -@freezed -class CampaignCategories with _$CampaignCategories { - const factory CampaignCategories({ - required List data, - @Default('') message, - required int status, - }) = _CampaignCategories; - - factory CampaignCategories.fromJson(Map json) => - _$CampaignCategoriesFromJson(json); -} - -@freezed -class Datum with _$Datum { - @JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake) - const factory Datum({ - @Default('') name, - @Default('') image, - @Default('') description, - @Default('') id, - }) = _Datum; - - factory Datum.fromJson(Map json) => _$DatumFromJson(json); -} diff --git a/lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.freezed.dart b/lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.freezed.dart deleted file mode 100644 index e17c10a..0000000 --- a/lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.freezed.dart +++ /dev/null @@ -1,380 +0,0 @@ -// coverage:ignore-file -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint -// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark - -part of 'campaign_category_entities.dart'; - -// ************************************************************************** -// FreezedGenerator -// ************************************************************************** - -T _$identity(T value) => value; - -final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); - -CampaignCategories _$CampaignCategoriesFromJson(Map json) { - return _CampaignCategories.fromJson(json); -} - -/// @nodoc -mixin _$CampaignCategories { - List get data => throw _privateConstructorUsedError; - dynamic get message => throw _privateConstructorUsedError; - int get status => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CampaignCategoriesCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CampaignCategoriesCopyWith<$Res> { - factory $CampaignCategoriesCopyWith( - CampaignCategories value, $Res Function(CampaignCategories) then) = - _$CampaignCategoriesCopyWithImpl<$Res, CampaignCategories>; - @useResult - $Res call({List data, dynamic message, int status}); -} - -/// @nodoc -class _$CampaignCategoriesCopyWithImpl<$Res, $Val extends CampaignCategories> - implements $CampaignCategoriesCopyWith<$Res> { - _$CampaignCategoriesCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? data = null, - Object? message = freezed, - Object? status = null, - }) { - return _then(_value.copyWith( - data: null == data - ? _value.data - : data // ignore: cast_nullable_to_non_nullable - as List, - message: freezed == message - ? _value.message - : message // ignore: cast_nullable_to_non_nullable - as dynamic, - status: null == status - ? _value.status - : status // ignore: cast_nullable_to_non_nullable - as int, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$_CampaignCategoriesCopyWith<$Res> - implements $CampaignCategoriesCopyWith<$Res> { - factory _$$_CampaignCategoriesCopyWith(_$_CampaignCategories value, - $Res Function(_$_CampaignCategories) then) = - __$$_CampaignCategoriesCopyWithImpl<$Res>; - @override - @useResult - $Res call({List data, dynamic message, int status}); -} - -/// @nodoc -class __$$_CampaignCategoriesCopyWithImpl<$Res> - extends _$CampaignCategoriesCopyWithImpl<$Res, _$_CampaignCategories> - implements _$$_CampaignCategoriesCopyWith<$Res> { - __$$_CampaignCategoriesCopyWithImpl( - _$_CampaignCategories _value, $Res Function(_$_CampaignCategories) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? data = null, - Object? message = freezed, - Object? status = null, - }) { - return _then(_$_CampaignCategories( - data: null == data - ? _value._data - : data // ignore: cast_nullable_to_non_nullable - as List, - message: freezed == message ? _value.message! : message, - status: null == status - ? _value.status - : status // ignore: cast_nullable_to_non_nullable - as int, - )); - } -} - -/// @nodoc -@JsonSerializable() -class _$_CampaignCategories implements _CampaignCategories { - const _$_CampaignCategories( - {required final List data, - this.message = '', - required this.status}) - : _data = data; - - factory _$_CampaignCategories.fromJson(Map json) => - _$$_CampaignCategoriesFromJson(json); - - final List _data; - @override - List get data { - if (_data is EqualUnmodifiableListView) return _data; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_data); - } - - @override - @JsonKey() - final dynamic message; - @override - final int status; - - @override - String toString() { - return 'CampaignCategories(data: $data, message: $message, status: $status)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$_CampaignCategories && - const DeepCollectionEquality().equals(other._data, _data) && - const DeepCollectionEquality().equals(other.message, message) && - (identical(other.status, status) || other.status == status)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - const DeepCollectionEquality().hash(_data), - const DeepCollectionEquality().hash(message), - status); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$_CampaignCategoriesCopyWith<_$_CampaignCategories> get copyWith => - __$$_CampaignCategoriesCopyWithImpl<_$_CampaignCategories>( - this, _$identity); - - @override - Map toJson() { - return _$$_CampaignCategoriesToJson( - this, - ); - } -} - -abstract class _CampaignCategories implements CampaignCategories { - const factory _CampaignCategories( - {required final List data, - final dynamic message, - required final int status}) = _$_CampaignCategories; - - factory _CampaignCategories.fromJson(Map json) = - _$_CampaignCategories.fromJson; - - @override - List get data; - @override - dynamic get message; - @override - int get status; - @override - @JsonKey(ignore: true) - _$$_CampaignCategoriesCopyWith<_$_CampaignCategories> get copyWith => - throw _privateConstructorUsedError; -} - -Datum _$DatumFromJson(Map json) { - return _Datum.fromJson(json); -} - -/// @nodoc -mixin _$Datum { - dynamic get name => throw _privateConstructorUsedError; - dynamic get image => throw _privateConstructorUsedError; - dynamic get description => throw _privateConstructorUsedError; - dynamic get id => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $DatumCopyWith get copyWith => throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $DatumCopyWith<$Res> { - factory $DatumCopyWith(Datum value, $Res Function(Datum) then) = - _$DatumCopyWithImpl<$Res, Datum>; - @useResult - $Res call({dynamic name, dynamic image, dynamic description, dynamic id}); -} - -/// @nodoc -class _$DatumCopyWithImpl<$Res, $Val extends Datum> - implements $DatumCopyWith<$Res> { - _$DatumCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? name = freezed, - Object? image = freezed, - Object? description = freezed, - Object? id = freezed, - }) { - return _then(_value.copyWith( - name: freezed == name - ? _value.name - : name // ignore: cast_nullable_to_non_nullable - as dynamic, - image: freezed == image - ? _value.image - : image // ignore: cast_nullable_to_non_nullable - as dynamic, - description: freezed == description - ? _value.description - : description // ignore: cast_nullable_to_non_nullable - as dynamic, - id: freezed == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as dynamic, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$_DatumCopyWith<$Res> implements $DatumCopyWith<$Res> { - factory _$$_DatumCopyWith(_$_Datum value, $Res Function(_$_Datum) then) = - __$$_DatumCopyWithImpl<$Res>; - @override - @useResult - $Res call({dynamic name, dynamic image, dynamic description, dynamic id}); -} - -/// @nodoc -class __$$_DatumCopyWithImpl<$Res> extends _$DatumCopyWithImpl<$Res, _$_Datum> - implements _$$_DatumCopyWith<$Res> { - __$$_DatumCopyWithImpl(_$_Datum _value, $Res Function(_$_Datum) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? name = freezed, - Object? image = freezed, - Object? description = freezed, - Object? id = freezed, - }) { - return _then(_$_Datum( - name: freezed == name ? _value.name! : name, - image: freezed == image ? _value.image! : image, - description: freezed == description ? _value.description! : description, - id: freezed == id ? _value.id! : id, - )); - } -} - -/// @nodoc - -@JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake) -class _$_Datum implements _Datum { - const _$_Datum( - {this.name = '', this.image = '', this.description = '', this.id = ''}); - - factory _$_Datum.fromJson(Map json) => - _$$_DatumFromJson(json); - - @override - @JsonKey() - final dynamic name; - @override - @JsonKey() - final dynamic image; - @override - @JsonKey() - final dynamic description; - @override - @JsonKey() - final dynamic id; - - @override - String toString() { - return 'Datum(name: $name, image: $image, description: $description, id: $id)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$_Datum && - const DeepCollectionEquality().equals(other.name, name) && - const DeepCollectionEquality().equals(other.image, image) && - const DeepCollectionEquality() - .equals(other.description, description) && - const DeepCollectionEquality().equals(other.id, id)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - const DeepCollectionEquality().hash(name), - const DeepCollectionEquality().hash(image), - const DeepCollectionEquality().hash(description), - const DeepCollectionEquality().hash(id)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$_DatumCopyWith<_$_Datum> get copyWith => - __$$_DatumCopyWithImpl<_$_Datum>(this, _$identity); - - @override - Map toJson() { - return _$$_DatumToJson( - this, - ); - } -} - -abstract class _Datum implements Datum { - const factory _Datum( - {final dynamic name, - final dynamic image, - final dynamic description, - final dynamic id}) = _$_Datum; - - factory _Datum.fromJson(Map json) = _$_Datum.fromJson; - - @override - dynamic get name; - @override - dynamic get image; - @override - dynamic get description; - @override - dynamic get id; - @override - @JsonKey(ignore: true) - _$$_DatumCopyWith<_$_Datum> get copyWith => - throw _privateConstructorUsedError; -} diff --git a/lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.g.dart b/lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.g.dart deleted file mode 100644 index 759e3d8..0000000 --- a/lib/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.g.dart +++ /dev/null @@ -1,39 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'campaign_category_entities.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -_$_CampaignCategories _$$_CampaignCategoriesFromJson( - Map json) => - _$_CampaignCategories( - data: (json['data'] as List) - .map((e) => Datum.fromJson(e as Map)) - .toList(), - message: json['message'] ?? '', - status: json['status'] as int, - ); - -Map _$$_CampaignCategoriesToJson( - _$_CampaignCategories instance) => - { - 'data': instance.data, - 'message': instance.message, - 'status': instance.status, - }; - -_$_Datum _$$_DatumFromJson(Map json) => _$_Datum( - name: json['name'] ?? '', - image: json['image'] ?? '', - description: json['description'] ?? '', - id: json['id'] ?? '', - ); - -Map _$$_DatumToJson(_$_Datum instance) => { - 'name': instance.name, - 'image': instance.image, - 'description': instance.description, - 'id': instance.id, - }; diff --git a/lib/features/donation/domain/entities/campaigns/campaigns_entity.dart b/lib/features/donation/domain/entities/campaigns/campaigns_entity.dart deleted file mode 100644 index ca967a2..0000000 --- a/lib/features/donation/domain/entities/campaigns/campaigns_entity.dart +++ /dev/null @@ -1,72 +0,0 @@ -import 'dart:convert'; - -import 'package:freezed_annotation/freezed_annotation.dart'; - -part 'campaigns_entity.freezed.dart'; -part 'campaigns_entity.g.dart'; - -CampaignResponse campaignCategoriesFromJson(String str) => - CampaignResponse.fromJson(json.decode(str)); - -String campaignCategoriesToJson(CampaignResponse data) => - json.encode(data.toJson()); - -@freezed -class CampaignResponse with _$CampaignResponse { - const factory CampaignResponse({ - required List data, - @Default('') message, - @Default(0) status, - }) = _CampaignCategories; - - factory CampaignResponse.fromJson(Map json) => - _$CampaignResponseFromJson(json); -} - -@freezed -class Datum with _$Datum { - @JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake) - const factory Datum({ - @Default('') campaignId, - @Default('') title, - @Default('') description, - @Default(0.0) goal, - @Default('') deadline, - @Default(0.0) totalAmountDonated, - @Default(0) id, - @Default('') image, - @Default('') owner, - @Default(0) totalNumber, - required List user, - required List donations, - }) = _Datum; - - factory Datum.fromJson(Map json) => _$DatumFromJson(json); -} - -@freezed -class Donation with _$Donation { - @JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake) - const factory Donation({ - @Default(0.0) amount, - @Default('') donor, - @Default('') image, - @Default('') username, - }) = _Donation; - - factory Donation.fromJson(Map json) => - _$DonationFromJson(json); -} - -@freezed -class User with _$User { - @JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake) - const factory User({ - @Default('') username, - @Default('') email, - @Default('') address, - @Default('') avatar, - }) = _User; - - factory User.fromJson(Map json) => _$UserFromJson(json); -} diff --git a/lib/features/donation/domain/entities/campaigns/campaigns_entity.freezed.dart b/lib/features/donation/domain/entities/campaigns/campaigns_entity.freezed.dart deleted file mode 100644 index 5e72843..0000000 --- a/lib/features/donation/domain/entities/campaigns/campaigns_entity.freezed.dart +++ /dev/null @@ -1,930 +0,0 @@ -// coverage:ignore-file -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint -// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark - -part of 'campaigns_entity.dart'; - -// ************************************************************************** -// FreezedGenerator -// ************************************************************************** - -T _$identity(T value) => value; - -final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); - -CampaignResponse _$CampaignResponseFromJson(Map json) { - return _CampaignCategories.fromJson(json); -} - -/// @nodoc -mixin _$CampaignResponse { - List get data => throw _privateConstructorUsedError; - dynamic get message => throw _privateConstructorUsedError; - dynamic get status => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $CampaignResponseCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $CampaignResponseCopyWith<$Res> { - factory $CampaignResponseCopyWith( - CampaignResponse value, $Res Function(CampaignResponse) then) = - _$CampaignResponseCopyWithImpl<$Res, CampaignResponse>; - @useResult - $Res call({List data, dynamic message, dynamic status}); -} - -/// @nodoc -class _$CampaignResponseCopyWithImpl<$Res, $Val extends CampaignResponse> - implements $CampaignResponseCopyWith<$Res> { - _$CampaignResponseCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? data = null, - Object? message = freezed, - Object? status = freezed, - }) { - return _then(_value.copyWith( - data: null == data - ? _value.data - : data // ignore: cast_nullable_to_non_nullable - as List, - message: freezed == message - ? _value.message - : message // ignore: cast_nullable_to_non_nullable - as dynamic, - status: freezed == status - ? _value.status - : status // ignore: cast_nullable_to_non_nullable - as dynamic, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$_CampaignCategoriesCopyWith<$Res> - implements $CampaignResponseCopyWith<$Res> { - factory _$$_CampaignCategoriesCopyWith(_$_CampaignCategories value, - $Res Function(_$_CampaignCategories) then) = - __$$_CampaignCategoriesCopyWithImpl<$Res>; - @override - @useResult - $Res call({List data, dynamic message, dynamic status}); -} - -/// @nodoc -class __$$_CampaignCategoriesCopyWithImpl<$Res> - extends _$CampaignResponseCopyWithImpl<$Res, _$_CampaignCategories> - implements _$$_CampaignCategoriesCopyWith<$Res> { - __$$_CampaignCategoriesCopyWithImpl( - _$_CampaignCategories _value, $Res Function(_$_CampaignCategories) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? data = null, - Object? message = freezed, - Object? status = freezed, - }) { - return _then(_$_CampaignCategories( - data: null == data - ? _value._data - : data // ignore: cast_nullable_to_non_nullable - as List, - message: freezed == message ? _value.message! : message, - status: freezed == status ? _value.status! : status, - )); - } -} - -/// @nodoc -@JsonSerializable() -class _$_CampaignCategories implements _CampaignCategories { - const _$_CampaignCategories( - {required final List data, this.message = '', this.status = 0}) - : _data = data; - - factory _$_CampaignCategories.fromJson(Map json) => - _$$_CampaignCategoriesFromJson(json); - - final List _data; - @override - List get data { - if (_data is EqualUnmodifiableListView) return _data; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_data); - } - - @override - @JsonKey() - final dynamic message; - @override - @JsonKey() - final dynamic status; - - @override - String toString() { - return 'CampaignResponse(data: $data, message: $message, status: $status)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$_CampaignCategories && - const DeepCollectionEquality().equals(other._data, _data) && - const DeepCollectionEquality().equals(other.message, message) && - const DeepCollectionEquality().equals(other.status, status)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - const DeepCollectionEquality().hash(_data), - const DeepCollectionEquality().hash(message), - const DeepCollectionEquality().hash(status)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$_CampaignCategoriesCopyWith<_$_CampaignCategories> get copyWith => - __$$_CampaignCategoriesCopyWithImpl<_$_CampaignCategories>( - this, _$identity); - - @override - Map toJson() { - return _$$_CampaignCategoriesToJson( - this, - ); - } -} - -abstract class _CampaignCategories implements CampaignResponse { - const factory _CampaignCategories( - {required final List data, - final dynamic message, - final dynamic status}) = _$_CampaignCategories; - - factory _CampaignCategories.fromJson(Map json) = - _$_CampaignCategories.fromJson; - - @override - List get data; - @override - dynamic get message; - @override - dynamic get status; - @override - @JsonKey(ignore: true) - _$$_CampaignCategoriesCopyWith<_$_CampaignCategories> get copyWith => - throw _privateConstructorUsedError; -} - -Datum _$DatumFromJson(Map json) { - return _Datum.fromJson(json); -} - -/// @nodoc -mixin _$Datum { - dynamic get campaignId => throw _privateConstructorUsedError; - dynamic get title => throw _privateConstructorUsedError; - dynamic get description => throw _privateConstructorUsedError; - dynamic get goal => throw _privateConstructorUsedError; - dynamic get deadline => throw _privateConstructorUsedError; - dynamic get totalAmountDonated => throw _privateConstructorUsedError; - dynamic get id => throw _privateConstructorUsedError; - dynamic get image => throw _privateConstructorUsedError; - dynamic get owner => throw _privateConstructorUsedError; - dynamic get totalNumber => throw _privateConstructorUsedError; - List get user => throw _privateConstructorUsedError; - List get donations => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $DatumCopyWith get copyWith => throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $DatumCopyWith<$Res> { - factory $DatumCopyWith(Datum value, $Res Function(Datum) then) = - _$DatumCopyWithImpl<$Res, Datum>; - @useResult - $Res call( - {dynamic campaignId, - dynamic title, - dynamic description, - dynamic goal, - dynamic deadline, - dynamic totalAmountDonated, - dynamic id, - dynamic image, - dynamic owner, - dynamic totalNumber, - List user, - List donations}); -} - -/// @nodoc -class _$DatumCopyWithImpl<$Res, $Val extends Datum> - implements $DatumCopyWith<$Res> { - _$DatumCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? campaignId = freezed, - Object? title = freezed, - Object? description = freezed, - Object? goal = freezed, - Object? deadline = freezed, - Object? totalAmountDonated = freezed, - Object? id = freezed, - Object? image = freezed, - Object? owner = freezed, - Object? totalNumber = freezed, - Object? user = null, - Object? donations = null, - }) { - return _then(_value.copyWith( - campaignId: freezed == campaignId - ? _value.campaignId - : campaignId // ignore: cast_nullable_to_non_nullable - as dynamic, - title: freezed == title - ? _value.title - : title // ignore: cast_nullable_to_non_nullable - as dynamic, - description: freezed == description - ? _value.description - : description // ignore: cast_nullable_to_non_nullable - as dynamic, - goal: freezed == goal - ? _value.goal - : goal // ignore: cast_nullable_to_non_nullable - as dynamic, - deadline: freezed == deadline - ? _value.deadline - : deadline // ignore: cast_nullable_to_non_nullable - as dynamic, - totalAmountDonated: freezed == totalAmountDonated - ? _value.totalAmountDonated - : totalAmountDonated // ignore: cast_nullable_to_non_nullable - as dynamic, - id: freezed == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as dynamic, - image: freezed == image - ? _value.image - : image // ignore: cast_nullable_to_non_nullable - as dynamic, - owner: freezed == owner - ? _value.owner - : owner // ignore: cast_nullable_to_non_nullable - as dynamic, - totalNumber: freezed == totalNumber - ? _value.totalNumber - : totalNumber // ignore: cast_nullable_to_non_nullable - as dynamic, - user: null == user - ? _value.user - : user // ignore: cast_nullable_to_non_nullable - as List, - donations: null == donations - ? _value.donations - : donations // ignore: cast_nullable_to_non_nullable - as List, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$_DatumCopyWith<$Res> implements $DatumCopyWith<$Res> { - factory _$$_DatumCopyWith(_$_Datum value, $Res Function(_$_Datum) then) = - __$$_DatumCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {dynamic campaignId, - dynamic title, - dynamic description, - dynamic goal, - dynamic deadline, - dynamic totalAmountDonated, - dynamic id, - dynamic image, - dynamic owner, - dynamic totalNumber, - List user, - List donations}); -} - -/// @nodoc -class __$$_DatumCopyWithImpl<$Res> extends _$DatumCopyWithImpl<$Res, _$_Datum> - implements _$$_DatumCopyWith<$Res> { - __$$_DatumCopyWithImpl(_$_Datum _value, $Res Function(_$_Datum) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? campaignId = freezed, - Object? title = freezed, - Object? description = freezed, - Object? goal = freezed, - Object? deadline = freezed, - Object? totalAmountDonated = freezed, - Object? id = freezed, - Object? image = freezed, - Object? owner = freezed, - Object? totalNumber = freezed, - Object? user = null, - Object? donations = null, - }) { - return _then(_$_Datum( - campaignId: freezed == campaignId ? _value.campaignId! : campaignId, - title: freezed == title ? _value.title! : title, - description: freezed == description ? _value.description! : description, - goal: freezed == goal ? _value.goal! : goal, - deadline: freezed == deadline ? _value.deadline! : deadline, - totalAmountDonated: freezed == totalAmountDonated - ? _value.totalAmountDonated! - : totalAmountDonated, - id: freezed == id ? _value.id! : id, - image: freezed == image ? _value.image! : image, - owner: freezed == owner ? _value.owner! : owner, - totalNumber: freezed == totalNumber ? _value.totalNumber! : totalNumber, - user: null == user - ? _value._user - : user // ignore: cast_nullable_to_non_nullable - as List, - donations: null == donations - ? _value._donations - : donations // ignore: cast_nullable_to_non_nullable - as List, - )); - } -} - -/// @nodoc - -@JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake) -class _$_Datum implements _Datum { - const _$_Datum( - {this.campaignId = '', - this.title = '', - this.description = '', - this.goal = 0.0, - this.deadline = '', - this.totalAmountDonated = 0.0, - this.id = 0, - this.image = '', - this.owner = '', - this.totalNumber = 0, - required final List user, - required final List donations}) - : _user = user, - _donations = donations; - - factory _$_Datum.fromJson(Map json) => - _$$_DatumFromJson(json); - - @override - @JsonKey() - final dynamic campaignId; - @override - @JsonKey() - final dynamic title; - @override - @JsonKey() - final dynamic description; - @override - @JsonKey() - final dynamic goal; - @override - @JsonKey() - final dynamic deadline; - @override - @JsonKey() - final dynamic totalAmountDonated; - @override - @JsonKey() - final dynamic id; - @override - @JsonKey() - final dynamic image; - @override - @JsonKey() - final dynamic owner; - @override - @JsonKey() - final dynamic totalNumber; - final List _user; - @override - List get user { - if (_user is EqualUnmodifiableListView) return _user; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_user); - } - - final List _donations; - @override - List get donations { - if (_donations is EqualUnmodifiableListView) return _donations; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_donations); - } - - @override - String toString() { - return 'Datum(campaignId: $campaignId, title: $title, description: $description, goal: $goal, deadline: $deadline, totalAmountDonated: $totalAmountDonated, id: $id, image: $image, owner: $owner, totalNumber: $totalNumber, user: $user, donations: $donations)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$_Datum && - const DeepCollectionEquality() - .equals(other.campaignId, campaignId) && - const DeepCollectionEquality().equals(other.title, title) && - const DeepCollectionEquality() - .equals(other.description, description) && - const DeepCollectionEquality().equals(other.goal, goal) && - const DeepCollectionEquality().equals(other.deadline, deadline) && - const DeepCollectionEquality() - .equals(other.totalAmountDonated, totalAmountDonated) && - const DeepCollectionEquality().equals(other.id, id) && - const DeepCollectionEquality().equals(other.image, image) && - const DeepCollectionEquality().equals(other.owner, owner) && - const DeepCollectionEquality() - .equals(other.totalNumber, totalNumber) && - const DeepCollectionEquality().equals(other._user, _user) && - const DeepCollectionEquality() - .equals(other._donations, _donations)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - const DeepCollectionEquality().hash(campaignId), - const DeepCollectionEquality().hash(title), - const DeepCollectionEquality().hash(description), - const DeepCollectionEquality().hash(goal), - const DeepCollectionEquality().hash(deadline), - const DeepCollectionEquality().hash(totalAmountDonated), - const DeepCollectionEquality().hash(id), - const DeepCollectionEquality().hash(image), - const DeepCollectionEquality().hash(owner), - const DeepCollectionEquality().hash(totalNumber), - const DeepCollectionEquality().hash(_user), - const DeepCollectionEquality().hash(_donations)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$_DatumCopyWith<_$_Datum> get copyWith => - __$$_DatumCopyWithImpl<_$_Datum>(this, _$identity); - - @override - Map toJson() { - return _$$_DatumToJson( - this, - ); - } -} - -abstract class _Datum implements Datum { - const factory _Datum( - {final dynamic campaignId, - final dynamic title, - final dynamic description, - final dynamic goal, - final dynamic deadline, - final dynamic totalAmountDonated, - final dynamic id, - final dynamic image, - final dynamic owner, - final dynamic totalNumber, - required final List user, - required final List donations}) = _$_Datum; - - factory _Datum.fromJson(Map json) = _$_Datum.fromJson; - - @override - dynamic get campaignId; - @override - dynamic get title; - @override - dynamic get description; - @override - dynamic get goal; - @override - dynamic get deadline; - @override - dynamic get totalAmountDonated; - @override - dynamic get id; - @override - dynamic get image; - @override - dynamic get owner; - @override - dynamic get totalNumber; - @override - List get user; - @override - List get donations; - @override - @JsonKey(ignore: true) - _$$_DatumCopyWith<_$_Datum> get copyWith => - throw _privateConstructorUsedError; -} - -Donation _$DonationFromJson(Map json) { - return _Donation.fromJson(json); -} - -/// @nodoc -mixin _$Donation { - dynamic get amount => throw _privateConstructorUsedError; - dynamic get donor => throw _privateConstructorUsedError; - dynamic get image => throw _privateConstructorUsedError; - dynamic get username => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $DonationCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $DonationCopyWith<$Res> { - factory $DonationCopyWith(Donation value, $Res Function(Donation) then) = - _$DonationCopyWithImpl<$Res, Donation>; - @useResult - $Res call({dynamic amount, dynamic donor, dynamic image, dynamic username}); -} - -/// @nodoc -class _$DonationCopyWithImpl<$Res, $Val extends Donation> - implements $DonationCopyWith<$Res> { - _$DonationCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? amount = freezed, - Object? donor = freezed, - Object? image = freezed, - Object? username = freezed, - }) { - return _then(_value.copyWith( - amount: freezed == amount - ? _value.amount - : amount // ignore: cast_nullable_to_non_nullable - as dynamic, - donor: freezed == donor - ? _value.donor - : donor // ignore: cast_nullable_to_non_nullable - as dynamic, - image: freezed == image - ? _value.image - : image // ignore: cast_nullable_to_non_nullable - as dynamic, - username: freezed == username - ? _value.username - : username // ignore: cast_nullable_to_non_nullable - as dynamic, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$_DonationCopyWith<$Res> implements $DonationCopyWith<$Res> { - factory _$$_DonationCopyWith( - _$_Donation value, $Res Function(_$_Donation) then) = - __$$_DonationCopyWithImpl<$Res>; - @override - @useResult - $Res call({dynamic amount, dynamic donor, dynamic image, dynamic username}); -} - -/// @nodoc -class __$$_DonationCopyWithImpl<$Res> - extends _$DonationCopyWithImpl<$Res, _$_Donation> - implements _$$_DonationCopyWith<$Res> { - __$$_DonationCopyWithImpl( - _$_Donation _value, $Res Function(_$_Donation) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? amount = freezed, - Object? donor = freezed, - Object? image = freezed, - Object? username = freezed, - }) { - return _then(_$_Donation( - amount: freezed == amount ? _value.amount! : amount, - donor: freezed == donor ? _value.donor! : donor, - image: freezed == image ? _value.image! : image, - username: freezed == username ? _value.username! : username, - )); - } -} - -/// @nodoc - -@JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake) -class _$_Donation implements _Donation { - const _$_Donation( - {this.amount = 0.0, - this.donor = '', - this.image = '', - this.username = ''}); - - factory _$_Donation.fromJson(Map json) => - _$$_DonationFromJson(json); - - @override - @JsonKey() - final dynamic amount; - @override - @JsonKey() - final dynamic donor; - @override - @JsonKey() - final dynamic image; - @override - @JsonKey() - final dynamic username; - - @override - String toString() { - return 'Donation(amount: $amount, donor: $donor, image: $image, username: $username)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$_Donation && - const DeepCollectionEquality().equals(other.amount, amount) && - const DeepCollectionEquality().equals(other.donor, donor) && - const DeepCollectionEquality().equals(other.image, image) && - const DeepCollectionEquality().equals(other.username, username)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - const DeepCollectionEquality().hash(amount), - const DeepCollectionEquality().hash(donor), - const DeepCollectionEquality().hash(image), - const DeepCollectionEquality().hash(username)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$_DonationCopyWith<_$_Donation> get copyWith => - __$$_DonationCopyWithImpl<_$_Donation>(this, _$identity); - - @override - Map toJson() { - return _$$_DonationToJson( - this, - ); - } -} - -abstract class _Donation implements Donation { - const factory _Donation( - {final dynamic amount, - final dynamic donor, - final dynamic image, - final dynamic username}) = _$_Donation; - - factory _Donation.fromJson(Map json) = _$_Donation.fromJson; - - @override - dynamic get amount; - @override - dynamic get donor; - @override - dynamic get image; - @override - dynamic get username; - @override - @JsonKey(ignore: true) - _$$_DonationCopyWith<_$_Donation> get copyWith => - throw _privateConstructorUsedError; -} - -User _$UserFromJson(Map json) { - return _User.fromJson(json); -} - -/// @nodoc -mixin _$User { - dynamic get username => throw _privateConstructorUsedError; - dynamic get email => throw _privateConstructorUsedError; - dynamic get address => throw _privateConstructorUsedError; - dynamic get avatar => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $UserCopyWith get copyWith => throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $UserCopyWith<$Res> { - factory $UserCopyWith(User value, $Res Function(User) then) = - _$UserCopyWithImpl<$Res, User>; - @useResult - $Res call({dynamic username, dynamic email, dynamic address, dynamic avatar}); -} - -/// @nodoc -class _$UserCopyWithImpl<$Res, $Val extends User> - implements $UserCopyWith<$Res> { - _$UserCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? username = freezed, - Object? email = freezed, - Object? address = freezed, - Object? avatar = freezed, - }) { - return _then(_value.copyWith( - username: freezed == username - ? _value.username - : username // ignore: cast_nullable_to_non_nullable - as dynamic, - email: freezed == email - ? _value.email - : email // ignore: cast_nullable_to_non_nullable - as dynamic, - address: freezed == address - ? _value.address - : address // ignore: cast_nullable_to_non_nullable - as dynamic, - avatar: freezed == avatar - ? _value.avatar - : avatar // ignore: cast_nullable_to_non_nullable - as dynamic, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$_UserCopyWith<$Res> implements $UserCopyWith<$Res> { - factory _$$_UserCopyWith(_$_User value, $Res Function(_$_User) then) = - __$$_UserCopyWithImpl<$Res>; - @override - @useResult - $Res call({dynamic username, dynamic email, dynamic address, dynamic avatar}); -} - -/// @nodoc -class __$$_UserCopyWithImpl<$Res> extends _$UserCopyWithImpl<$Res, _$_User> - implements _$$_UserCopyWith<$Res> { - __$$_UserCopyWithImpl(_$_User _value, $Res Function(_$_User) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? username = freezed, - Object? email = freezed, - Object? address = freezed, - Object? avatar = freezed, - }) { - return _then(_$_User( - username: freezed == username ? _value.username! : username, - email: freezed == email ? _value.email! : email, - address: freezed == address ? _value.address! : address, - avatar: freezed == avatar ? _value.avatar! : avatar, - )); - } -} - -/// @nodoc - -@JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake) -class _$_User implements _User { - const _$_User( - {this.username = '', - this.email = '', - this.address = '', - this.avatar = ''}); - - factory _$_User.fromJson(Map json) => _$$_UserFromJson(json); - - @override - @JsonKey() - final dynamic username; - @override - @JsonKey() - final dynamic email; - @override - @JsonKey() - final dynamic address; - @override - @JsonKey() - final dynamic avatar; - - @override - String toString() { - return 'User(username: $username, email: $email, address: $address, avatar: $avatar)'; - } - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$_User && - const DeepCollectionEquality().equals(other.username, username) && - const DeepCollectionEquality().equals(other.email, email) && - const DeepCollectionEquality().equals(other.address, address) && - const DeepCollectionEquality().equals(other.avatar, avatar)); - } - - @JsonKey(ignore: true) - @override - int get hashCode => Object.hash( - runtimeType, - const DeepCollectionEquality().hash(username), - const DeepCollectionEquality().hash(email), - const DeepCollectionEquality().hash(address), - const DeepCollectionEquality().hash(avatar)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$_UserCopyWith<_$_User> get copyWith => - __$$_UserCopyWithImpl<_$_User>(this, _$identity); - - @override - Map toJson() { - return _$$_UserToJson( - this, - ); - } -} - -abstract class _User implements User { - const factory _User( - {final dynamic username, - final dynamic email, - final dynamic address, - final dynamic avatar}) = _$_User; - - factory _User.fromJson(Map json) = _$_User.fromJson; - - @override - dynamic get username; - @override - dynamic get email; - @override - dynamic get address; - @override - dynamic get avatar; - @override - @JsonKey(ignore: true) - _$$_UserCopyWith<_$_User> get copyWith => throw _privateConstructorUsedError; -} diff --git a/lib/features/donation/domain/entities/campaigns/campaigns_entity.g.dart b/lib/features/donation/domain/entities/campaigns/campaigns_entity.g.dart deleted file mode 100644 index b5117b3..0000000 --- a/lib/features/donation/domain/entities/campaigns/campaigns_entity.g.dart +++ /dev/null @@ -1,88 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'campaigns_entity.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -_$_CampaignCategories _$$_CampaignCategoriesFromJson( - Map json) => - _$_CampaignCategories( - data: (json['data'] as List) - .map((e) => Datum.fromJson(e as Map)) - .toList(), - message: json['message'] ?? '', - status: json['status'] ?? 0, - ); - -Map _$$_CampaignCategoriesToJson( - _$_CampaignCategories instance) => - { - 'data': instance.data, - 'message': instance.message, - 'status': instance.status, - }; - -_$_Datum _$$_DatumFromJson(Map json) => _$_Datum( - campaignId: json['campaign_id'] ?? '', - title: json['title'] ?? '', - description: json['description'] ?? '', - goal: json['goal'] ?? 0.0, - deadline: json['deadline'] ?? '', - totalAmountDonated: json['total_amount_donated'] ?? 0.0, - id: json['id'] ?? 0, - image: json['image'] ?? '', - owner: json['owner'] ?? '', - totalNumber: json['total_number'] ?? 0, - user: (json['user'] as List) - .map((e) => User.fromJson(e as Map)) - .toList(), - donations: (json['donations'] as List) - .map((e) => Donation.fromJson(e as Map)) - .toList(), - ); - -Map _$$_DatumToJson(_$_Datum instance) => { - 'campaign_id': instance.campaignId, - 'title': instance.title, - 'description': instance.description, - 'goal': instance.goal, - 'deadline': instance.deadline, - 'total_amount_donated': instance.totalAmountDonated, - 'id': instance.id, - 'image': instance.image, - 'owner': instance.owner, - 'total_number': instance.totalNumber, - 'user': instance.user.map((e) => e.toJson()).toList(), - 'donations': instance.donations.map((e) => e.toJson()).toList(), - }; - -_$_Donation _$$_DonationFromJson(Map json) => _$_Donation( - amount: json['amount'] ?? 0.0, - donor: json['donor'] ?? '', - image: json['image'] ?? '', - username: json['username'] ?? '', - ); - -Map _$$_DonationToJson(_$_Donation instance) => - { - 'amount': instance.amount, - 'donor': instance.donor, - 'image': instance.image, - 'username': instance.username, - }; - -_$_User _$$_UserFromJson(Map json) => _$_User( - username: json['username'] ?? '', - email: json['email'] ?? '', - address: json['address'] ?? '', - avatar: json['avatar'] ?? '', - ); - -Map _$$_UserToJson(_$_User instance) => { - 'username': instance.username, - 'email': instance.email, - 'address': instance.address, - 'avatar': instance.avatar, - }; diff --git a/lib/features/donation/domain/repositories/campaign_repository.dart b/lib/features/donation/domain/repositories/campaign_repository.dart deleted file mode 100644 index 5f62c2d..0000000 --- a/lib/features/donation/domain/repositories/campaign_repository.dart +++ /dev/null @@ -1,9 +0,0 @@ -import 'package:dartz/dartz.dart'; -import 'package:defiraiser_mobile/core/network/api_error.dart'; -import 'package:defiraiser_mobile/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.dart'; -import 'package:defiraiser_mobile/features/donation/domain/entities/campaigns/campaigns_entity.dart'; - -abstract class CampaignRepository { - Future> getCategories(); - Future> getCampaigns(); -} diff --git a/lib/features/donation/domain/usecases/campaign_catergory_usecase.dart b/lib/features/donation/domain/usecases/campaign_catergory_usecase.dart deleted file mode 100644 index 7edd350..0000000 --- a/lib/features/donation/domain/usecases/campaign_catergory_usecase.dart +++ /dev/null @@ -1,16 +0,0 @@ -import 'package:dartz/dartz.dart'; -import 'package:defiraiser_mobile/core/network/api_error.dart'; -import 'package:defiraiser_mobile/core/usecases/usecases.dart'; -import 'package:defiraiser_mobile/features/donation/domain/entities/campaign_categories_entity/campaign_category_entities.dart'; -import 'package:defiraiser_mobile/features/donation/domain/repositories/campaign_repository.dart'; - -class CampaignCategoryUseCase implements UseCase { - final CampaignRepository campaignRepository; - - CampaignCategoryUseCase(this.campaignRepository); - - @override - Future> call(NoParams params) async { - return await campaignRepository.getCategories(); - } -} diff --git a/lib/features/donation/domain/usecases/get_campaigns.dart b/lib/features/donation/domain/usecases/get_campaigns.dart deleted file mode 100644 index 67a3446..0000000 --- a/lib/features/donation/domain/usecases/get_campaigns.dart +++ /dev/null @@ -1,16 +0,0 @@ -import 'package:dartz/dartz.dart'; -import 'package:defiraiser_mobile/core/network/api_error.dart'; -import 'package:defiraiser_mobile/core/usecases/usecases.dart'; -import 'package:defiraiser_mobile/features/donation/domain/entities/campaigns/campaigns_entity.dart'; -import 'package:defiraiser_mobile/features/donation/domain/repositories/campaign_repository.dart'; - -class GetCampaignsUseCase implements UseCase { - final CampaignRepository campaignRepository; - - GetCampaignsUseCase(this.campaignRepository); - - @override - Future> call(NoParams params) async { - return await campaignRepository.getCampaigns(); - } -} diff --git a/lib/features/donation/presentation/view/campaigns_screen.dart b/lib/features/donation/presentation/view/campaigns_screen.dart index f29f5be..2e19875 100644 --- a/lib/features/donation/presentation/view/campaigns_screen.dart +++ b/lib/features/donation/presentation/view/campaigns_screen.dart @@ -111,12 +111,12 @@ class _CampaignScreenViewState extends ConsumerState shrinkWrap: true, physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics()), - itemCount: success.data.length, + itemCount: success.data!.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { context.goNamed(RouteConstants.singleDonation, - extra: success.data[index]); + extra: success.data![index]); }, child: AnimationConfiguration.staggeredList( position: index, @@ -125,7 +125,7 @@ class _CampaignScreenViewState extends ConsumerState verticalOffset: 50.0, child: FadeInAnimation( child: BuildDonationWidget( - campaign: success.data[index], + campaign: success.data![index], controller: _controller, ), ), diff --git a/lib/features/donation/presentation/view/donations_screen.dart b/lib/features/donation/presentation/view/donations_screen.dart index 08747f3..536e11b 100644 --- a/lib/features/donation/presentation/view/donations_screen.dart +++ b/lib/features/donation/presentation/view/donations_screen.dart @@ -81,12 +81,12 @@ class _DonationScreenViewState extends ConsumerState shrinkWrap: true, physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics()), - itemCount: success.data.length, + itemCount: success.data!.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { context.goNamed(RouteConstants.singleDonation, - extra: success.data[index]); + extra: success.data![index]); }, child: AnimationConfiguration.staggeredList( position: index, @@ -95,7 +95,7 @@ class _DonationScreenViewState extends ConsumerState verticalOffset: 50.0, child: FadeInAnimation( child: BuildDonationWidget( - campaign: success.data[index], + campaign: success.data![index], controller: _controller, ), ), diff --git a/lib/features/home/data/data_source/campaign_remote_date_source.dart b/lib/features/home/data/data_source/campaign_remote_date_source.dart index f2a57e5..34fff85 100644 --- a/lib/features/home/data/data_source/campaign_remote_date_source.dart +++ b/lib/features/home/data/data_source/campaign_remote_date_source.dart @@ -43,15 +43,9 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { @override Future getCategories() async { - final token = - await sl().getAccessToken(SecureStorageKey().token); - final response = await client.call( path: EndpointManager.getCategories, method: RequestMethod.get, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), ); final res = response!.data; if (response.statusCode == 200) { @@ -63,15 +57,12 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { @override Future getCampaigns() async { - final token = - await sl().getAccessToken(SecureStorageKey().token); + // final token = + // await sl().getAccessToken(SecureStorageKey().token); final response = await client.call( path: EndpointManager.getCampaign, method: RequestMethod.get, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), ); final res = response!.data; if (response.statusCode == 200) { @@ -83,15 +74,10 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { @override Future getMyCampaigns() async { - final token = - await sl().getAccessToken(SecureStorageKey().token); final response = await client.call( path: EndpointManager.getMyCampaign, method: RequestMethod.get, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), ); final res = response!.data; if (response.statusCode == 200) { @@ -103,15 +89,13 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { @override Future getDonations() async { - final token = - await sl().getAccessToken(SecureStorageKey().token); final response = await client.call( path: EndpointManager.getDonation, method: RequestMethod.get, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), + // options: Options(headers: { + // 'Authorization': 'Bearer $token', + // }), ); final res = response!.data; if (response.statusCode == 200) { @@ -123,15 +107,15 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { @override Future getCampaignsByCategory({required String id}) async { - final token = - await sl().getAccessToken(SecureStorageKey().token); + // final token = + // await sl().getAccessToken(SecureStorageKey().token); final response = await client.call( path: EndpointManager.getCampaignsByCategory(id), method: RequestMethod.get, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), + // options: Options(headers: { + // 'Authorization': 'Bearer $token', + // }), ); final res = response!.data; if (response.statusCode == 200) { @@ -143,15 +127,15 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { @override Future getCurrentEthPrice() async { - final token = - await sl().getAccessToken(SecureStorageKey().token); + // final token = + // await sl().getAccessToken(SecureStorageKey().token); final response = await client.call( path: EndpointManager.getCurrentEthPrice, method: RequestMethod.get, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), + // options: Options(headers: { + // 'Authorization': 'Bearer $token', + // }), ); final res = response!.data; if (response.statusCode == 200) { @@ -164,8 +148,8 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { @override Future makeDonation( {required String campaignId, required String amount}) async { - final token = - await sl().getAccessToken(SecureStorageKey().token); + // final token = + // await sl().getAccessToken(SecureStorageKey().token); final response = await client.call( path: EndpointManager.makeDonation, @@ -174,9 +158,9 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { 'campaign_id': campaignId, 'amount': amount, }, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), + // options: Options(headers: { + // 'Authorization': 'Bearer $token', + // }), ); final res = response!.data; if (response.statusCode == 200) { @@ -188,15 +172,15 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { @override Future getDonors({required String campaignId}) async { - final token = - await sl().getAccessToken(SecureStorageKey().token); + // final token = + // await sl().getAccessToken(SecureStorageKey().token); final response = await client.call( path: EndpointManager.getDonors(campaignId), method: RequestMethod.get, - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), + // options: Options(headers: { + // 'Authorization': 'Bearer $token', + // }), ); final res = response!.data; if (response.statusCode == 200) { @@ -214,8 +198,8 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { required String category, required String deadline, required File images}) async { - final token = - await sl().getAccessToken(SecureStorageKey().token); + // final token = + // await sl().getAccessToken(SecureStorageKey().token); List multiPart = []; var data = {}; @@ -238,9 +222,9 @@ class CampaignRemoteDataSourceImpl implements CampaignRemoteDataSource { path: EndpointManager.createDonation, method: RequestMethod.post, body: FormData.fromMap(data), - options: Options(headers: { - 'Authorization': 'Bearer $token', - }), + // options: Options(headers: { + // 'Authorization': 'Bearer $token', + // }), ); final res = response!.data; if (response.statusCode == 200) { diff --git a/lib/features/home/data/repositories/campaign_repository.dart b/lib/features/home/data/repositories/campaign_repository.dart index 38b00ee..ea54fda 100644 --- a/lib/features/home/data/repositories/campaign_repository.dart +++ b/lib/features/home/data/repositories/campaign_repository.dart @@ -123,6 +123,7 @@ class ICampaignRepository implements CampaignRepository { deadline: deadline, images: images, ); + return Right(remoteCampaign); } on ApiError catch (error) { return Left(error); diff --git a/lib/features/home/domain/entities/campaigns/campaigns_entity.dart b/lib/features/home/domain/entities/campaigns/campaigns_entity.dart index 3d7c368..0e137d2 100644 --- a/lib/features/home/domain/entities/campaigns/campaigns_entity.dart +++ b/lib/features/home/domain/entities/campaigns/campaigns_entity.dart @@ -14,7 +14,7 @@ String campaignCategoriesToJson(CampaignResponse data) => @freezed class CampaignResponse with _$CampaignResponse { const factory CampaignResponse({ - required List data, + List? data, @Default('') message, @Default(0) status, }) = _CampaignCategories; diff --git a/lib/features/home/domain/entities/campaigns/campaigns_entity.freezed.dart b/lib/features/home/domain/entities/campaigns/campaigns_entity.freezed.dart index 115b140..0588b63 100644 --- a/lib/features/home/domain/entities/campaigns/campaigns_entity.freezed.dart +++ b/lib/features/home/domain/entities/campaigns/campaigns_entity.freezed.dart @@ -20,7 +20,7 @@ CampaignResponse _$CampaignResponseFromJson(Map json) { /// @nodoc mixin _$CampaignResponse { - List get data => throw _privateConstructorUsedError; + List? get data => throw _privateConstructorUsedError; dynamic get message => throw _privateConstructorUsedError; dynamic get status => throw _privateConstructorUsedError; @@ -36,7 +36,7 @@ abstract class $CampaignResponseCopyWith<$Res> { CampaignResponse value, $Res Function(CampaignResponse) then) = _$CampaignResponseCopyWithImpl<$Res, CampaignResponse>; @useResult - $Res call({List data, dynamic message, dynamic status}); + $Res call({List? data, dynamic message, dynamic status}); } /// @nodoc @@ -52,15 +52,15 @@ class _$CampaignResponseCopyWithImpl<$Res, $Val extends CampaignResponse> @pragma('vm:prefer-inline') @override $Res call({ - Object? data = null, + Object? data = freezed, Object? message = freezed, Object? status = freezed, }) { return _then(_value.copyWith( - data: null == data + data: freezed == data ? _value.data : data // ignore: cast_nullable_to_non_nullable - as List, + as List?, message: freezed == message ? _value.message : message // ignore: cast_nullable_to_non_nullable @@ -81,7 +81,7 @@ abstract class _$$_CampaignCategoriesCopyWith<$Res> __$$_CampaignCategoriesCopyWithImpl<$Res>; @override @useResult - $Res call({List data, dynamic message, dynamic status}); + $Res call({List? data, dynamic message, dynamic status}); } /// @nodoc @@ -95,15 +95,15 @@ class __$$_CampaignCategoriesCopyWithImpl<$Res> @pragma('vm:prefer-inline') @override $Res call({ - Object? data = null, + Object? data = freezed, Object? message = freezed, Object? status = freezed, }) { return _then(_$_CampaignCategories( - data: null == data + data: freezed == data ? _value._data : data // ignore: cast_nullable_to_non_nullable - as List, + as List?, message: freezed == message ? _value.message! : message, status: freezed == status ? _value.status! : status, )); @@ -114,18 +114,20 @@ class __$$_CampaignCategoriesCopyWithImpl<$Res> @JsonSerializable() class _$_CampaignCategories implements _CampaignCategories { const _$_CampaignCategories( - {required final List data, this.message = '', this.status = 0}) + {final List? data, this.message = '', this.status = 0}) : _data = data; factory _$_CampaignCategories.fromJson(Map json) => _$$_CampaignCategoriesFromJson(json); - final List _data; + final List? _data; @override - List get data { + List? get data { + final value = _data; + if (value == null) return null; if (_data is EqualUnmodifiableListView) return _data; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_data); + return EqualUnmodifiableListView(value); } @override @@ -175,7 +177,7 @@ class _$_CampaignCategories implements _CampaignCategories { abstract class _CampaignCategories implements CampaignResponse { const factory _CampaignCategories( - {required final List data, + {final List? data, final dynamic message, final dynamic status}) = _$_CampaignCategories; @@ -183,7 +185,7 @@ abstract class _CampaignCategories implements CampaignResponse { _$_CampaignCategories.fromJson; @override - List get data; + List? get data; @override dynamic get message; @override diff --git a/lib/features/home/domain/entities/campaigns/campaigns_entity.g.dart b/lib/features/home/domain/entities/campaigns/campaigns_entity.g.dart index 553bb46..bebc7cb 100644 --- a/lib/features/home/domain/entities/campaigns/campaigns_entity.g.dart +++ b/lib/features/home/domain/entities/campaigns/campaigns_entity.g.dart @@ -9,8 +9,8 @@ part of 'campaigns_entity.dart'; _$_CampaignCategories _$$_CampaignCategoriesFromJson( Map json) => _$_CampaignCategories( - data: (json['data'] as List) - .map((e) => Datum.fromJson(e as Map)) + data: (json['data'] as List?) + ?.map((e) => Datum.fromJson(e as Map)) .toList(), message: json['message'] ?? '', status: json['status'] ?? 0, diff --git a/lib/features/home/domain/entities/donors_entity/donors_entity.dart b/lib/features/home/domain/entities/donors_entity/donors_entity.dart index 1a4d39c..7d43793 100644 --- a/lib/features/home/domain/entities/donors_entity/donors_entity.dart +++ b/lib/features/home/domain/entities/donors_entity/donors_entity.dart @@ -13,7 +13,7 @@ String donorsEntityToJson(DonorsEntity data) => json.encode(data.toJson()); @freezed class DonorsEntity with _$DonorsEntity { const factory DonorsEntity({ - required List data, + List? data, @Default('') message, @Default(0) status, }) = _DonorsEntity; diff --git a/lib/features/home/domain/entities/donors_entity/donors_entity.freezed.dart b/lib/features/home/domain/entities/donors_entity/donors_entity.freezed.dart index 8ea3274..d21f09b 100644 --- a/lib/features/home/domain/entities/donors_entity/donors_entity.freezed.dart +++ b/lib/features/home/domain/entities/donors_entity/donors_entity.freezed.dart @@ -20,7 +20,7 @@ DonorsEntity _$DonorsEntityFromJson(Map json) { /// @nodoc mixin _$DonorsEntity { - List get data => throw _privateConstructorUsedError; + List? get data => throw _privateConstructorUsedError; dynamic get message => throw _privateConstructorUsedError; dynamic get status => throw _privateConstructorUsedError; @@ -36,7 +36,7 @@ abstract class $DonorsEntityCopyWith<$Res> { DonorsEntity value, $Res Function(DonorsEntity) then) = _$DonorsEntityCopyWithImpl<$Res, DonorsEntity>; @useResult - $Res call({List data, dynamic message, dynamic status}); + $Res call({List? data, dynamic message, dynamic status}); } /// @nodoc @@ -52,15 +52,15 @@ class _$DonorsEntityCopyWithImpl<$Res, $Val extends DonorsEntity> @pragma('vm:prefer-inline') @override $Res call({ - Object? data = null, + Object? data = freezed, Object? message = freezed, Object? status = freezed, }) { return _then(_value.copyWith( - data: null == data + data: freezed == data ? _value.data : data // ignore: cast_nullable_to_non_nullable - as List, + as List?, message: freezed == message ? _value.message : message // ignore: cast_nullable_to_non_nullable @@ -81,7 +81,7 @@ abstract class _$$_DonorsEntityCopyWith<$Res> __$$_DonorsEntityCopyWithImpl<$Res>; @override @useResult - $Res call({List data, dynamic message, dynamic status}); + $Res call({List? data, dynamic message, dynamic status}); } /// @nodoc @@ -95,15 +95,15 @@ class __$$_DonorsEntityCopyWithImpl<$Res> @pragma('vm:prefer-inline') @override $Res call({ - Object? data = null, + Object? data = freezed, Object? message = freezed, Object? status = freezed, }) { return _then(_$_DonorsEntity( - data: null == data + data: freezed == data ? _value._data : data // ignore: cast_nullable_to_non_nullable - as List, + as List?, message: freezed == message ? _value.message! : message, status: freezed == status ? _value.status! : status, )); @@ -114,18 +114,20 @@ class __$$_DonorsEntityCopyWithImpl<$Res> @JsonSerializable() class _$_DonorsEntity implements _DonorsEntity { const _$_DonorsEntity( - {required final List data, this.message = '', this.status = 0}) + {final List? data, this.message = '', this.status = 0}) : _data = data; factory _$_DonorsEntity.fromJson(Map json) => _$$_DonorsEntityFromJson(json); - final List _data; + final List? _data; @override - List get data { + List? get data { + final value = _data; + if (value == null) return null; if (_data is EqualUnmodifiableListView) return _data; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_data); + return EqualUnmodifiableListView(value); } @override @@ -174,7 +176,7 @@ class _$_DonorsEntity implements _DonorsEntity { abstract class _DonorsEntity implements DonorsEntity { const factory _DonorsEntity( - {required final List data, + {final List? data, final dynamic message, final dynamic status}) = _$_DonorsEntity; @@ -182,7 +184,7 @@ abstract class _DonorsEntity implements DonorsEntity { _$_DonorsEntity.fromJson; @override - List get data; + List? get data; @override dynamic get message; @override diff --git a/lib/features/home/domain/entities/donors_entity/donors_entity.g.dart b/lib/features/home/domain/entities/donors_entity/donors_entity.g.dart index 965528c..b19c296 100644 --- a/lib/features/home/domain/entities/donors_entity/donors_entity.g.dart +++ b/lib/features/home/domain/entities/donors_entity/donors_entity.g.dart @@ -8,8 +8,8 @@ part of 'donors_entity.dart'; _$_DonorsEntity _$$_DonorsEntityFromJson(Map json) => _$_DonorsEntity( - data: (json['data'] as List) - .map((e) => Donors.fromJson(e as Map)) + data: (json['data'] as List?) + ?.map((e) => Donors.fromJson(e as Map)) .toList(), message: json['message'] ?? '', status: json['status'] ?? 0, diff --git a/lib/features/home/presentation/view/category_campaign_screen.dart b/lib/features/home/presentation/view/category_campaign_screen.dart index 2911614..50bb296 100644 --- a/lib/features/home/presentation/view/category_campaign_screen.dart +++ b/lib/features/home/presentation/view/category_campaign_screen.dart @@ -87,12 +87,12 @@ class _DonationScreenViewState extends ConsumerState shrinkWrap: true, physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics()), - itemCount: success.data.length, + itemCount: success.data!.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { context.goNamed(RouteConstants.singleDonation, - extra: success.data[index]); + extra: success.data![index]); }, child: AnimationConfiguration.staggeredList( position: index, @@ -101,7 +101,7 @@ class _DonationScreenViewState extends ConsumerState verticalOffset: 50.0, child: FadeInAnimation( child: BuildDonationWidget( - campaign: success.data[index], + campaign: success.data![index], controller: _controller, ), ), diff --git a/lib/features/home/presentation/view/latest_funding_screen.dart b/lib/features/home/presentation/view/latest_funding_screen.dart index 49d04bf..7b1f9e4 100644 --- a/lib/features/home/presentation/view/latest_funding_screen.dart +++ b/lib/features/home/presentation/view/latest_funding_screen.dart @@ -55,7 +55,7 @@ class _LatestFundraiserWidgetState extends ConsumerState orElse: () => Container(), loaded: (success) => AnimationLimiter( child: ListView.builder( - itemCount: success.data.length, + itemCount: success.data!.length, shrinkWrap: true, physics: BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics()), @@ -65,7 +65,7 @@ class _LatestFundraiserWidgetState extends ConsumerState return GestureDetector( onTap: () { context.goNamed(RouteConstants.singleDonation, - extra: success.data[index]); + extra: success.data![index]); }, child: AnimationConfiguration.staggeredList( position: index, @@ -104,7 +104,7 @@ class _LatestFundraiserWidgetState extends ConsumerState 20), child: CachedNetworkImage( imageUrl: success - .data[index].image, + .data![index].image, fit: BoxFit.cover, height: 120, placeholder: (context, @@ -176,7 +176,7 @@ class _LatestFundraiserWidgetState extends ConsumerState HorizontalMargin(5), CachedNetworkImage( imageUrl: success - .data[index] + .data![index] .user![0] .avatar, fit: BoxFit.cover, @@ -198,11 +198,11 @@ class _LatestFundraiserWidgetState extends ConsumerState Flexible( child: Text( success - .data[index] + .data![index] .user![0] .username != "" - ? "${success.data[index].user![0].username}" + ? "${success.data![index].user![0].username}" : "Anonymous", maxLines: 1, overflow: TextOverflow @@ -230,7 +230,7 @@ class _LatestFundraiserWidgetState extends ConsumerState Flexible( child: Text( success - .data[index].title, + .data![index].title, maxLines: 1, overflow: TextOverflow .ellipsis, @@ -249,9 +249,9 @@ class _LatestFundraiserWidgetState extends ConsumerState ), VerticalMargin(10), linearPercentage( - success.data[index] + success.data![index] .totalAmountDonated, - success.data[index].goal, + success.data![index].goal, _controller, context, height: 10, @@ -273,7 +273,7 @@ class _LatestFundraiserWidgetState extends ConsumerState ), HorizontalMargin(5), Text( - (success.data[index] + (success.data![index] .goal / 1000000000000000000) .toString(), @@ -304,7 +304,7 @@ class _LatestFundraiserWidgetState extends ConsumerState ), Text( DateTime.tryParse(success - .data[index] + .data![index] .deadline!)! .endTime(), style: Config.b2(context) diff --git a/lib/features/home/presentation/view/view_donation_screen.dart b/lib/features/home/presentation/view/view_donation_screen.dart index 6e3cdd4..067e419 100644 --- a/lib/features/home/presentation/view/view_donation_screen.dart +++ b/lib/features/home/presentation/view/view_donation_screen.dart @@ -57,7 +57,7 @@ class _ViewDonorsScreensState extends ConsumerState { shrinkWrap: true, physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics()), - itemCount: donors.data.length, + itemCount: donors.data!.length, itemBuilder: (context, index) { return AnimationConfiguration.staggeredList( position: index, @@ -66,7 +66,7 @@ class _ViewDonorsScreensState extends ConsumerState { verticalOffset: 1.0, child: FadeInAnimation( child: _buildDonorItem( - donors: donors.data[index], + donors: donors.data![index], ), ), ), diff --git a/test/core/network/network_provider_test.dart b/test/core/network/network_provider_test.dart index 325ef9a..e40230f 100644 --- a/test/core/network/network_provider_test.dart +++ b/test/core/network/network_provider_test.dart @@ -1,3 +1,4 @@ +import 'package:defiraiser_mobile/core/di/injector.dart'; import 'package:defiraiser_mobile/core/network/network_provider.dart'; import 'package:dio/dio.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -13,6 +14,7 @@ void main() { late Response tResponse; setUp(() { + injector(); mockDio = MockDio(); networkProvider = NetworkProviderImpl(); }); @@ -22,7 +24,9 @@ void main() { test("should return a response", () async { // arrange tResponse = Response( - requestOptions: RequestOptions(path: tPath), + requestOptions: RequestOptions( + path: tPath, + ), data: {"data": "data"}, statusCode: 200, statusMessage: "OK", diff --git a/test/feature/authentication/data/data_source/authentication_remote_data_source_test.dart b/test/feature/authentication/data/data_source/authentication_remote_data_source_test.dart index c502f3b..92a5d3b 100644 --- a/test/feature/authentication/data/data_source/authentication_remote_data_source_test.dart +++ b/test/feature/authentication/data/data_source/authentication_remote_data_source_test.dart @@ -18,12 +18,15 @@ class MockNetworkProvider extends Mock implements NetworkProvider {} void main() { late MockNetworkProvider mockNetworkProvider; late AuthenticationRemoteDataSource authenticationRemoteDataSource; + late String tUsername = "test"; late String tEmail = "test@test.com"; late String tPassword = "test"; late String tOtpCode = "123456"; + late String tToken = "testToken"; + late int tImageId = 1; - setUp(() { + setUp(() async { mockNetworkProvider = MockNetworkProvider(); authenticationRemoteDataSource = IAuthenticationRemoteDataSource(mockNetworkProvider); @@ -104,6 +107,33 @@ void main() { }); } + void setUpMockProfileAvatar() { + when(() => mockNetworkProvider.call( + path: EndpointManager.setProfileAvatar, + method: RequestMethod.post, + body: { + "image_id": tImageId, + })).thenAnswer((_) async { + return Response( + requestOptions: + RequestOptions(path: EndpointManager.setProfileAvatar), + data: json.decode(fixture('create_account_response.json')), + statusCode: 200); + }); + } + + void setUpMockGetUserDetails() { + when(() => mockNetworkProvider.call( + path: EndpointManager.getUser, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getUser), + data: json.decode(fixture('create_account_response.json')), + statusCode: 200); + }); + } + void setUpMockVerifyPasswordResetCodeHttpManager() { when(() => mockNetworkProvider.call( path: EndpointManager.confirmReset, @@ -124,8 +154,8 @@ void main() { test("should return Create User Response when the call is successful", () async { setUpMockHttpManager(); - final result = await authenticationRemoteDataSource.createAccount( - tUsername, tEmail); + final result = + await authenticationRemoteDataSource.createAccount(tUsername, tEmail); expect(result, isA()); }); @@ -144,11 +174,12 @@ void main() { statusCode: 400); }); final call = authenticationRemoteDataSource.createAccount; - expect(() => call(tUsername, tEmail), - throwsA(isA())); + expect(() => call(tUsername, tEmail), throwsA(isA())); }); }); + + group("login user account", () { test("should return Login Response when the call is successful", () async { setUpMockLoginHttpManager(); @@ -295,4 +326,56 @@ void main() { throwsA(isA())); }); }); + + group("Set Profile ", () { + test("should return ResendOTP Response when the call is successful", + () async { + setUpMockProfileAvatar(); + final result = + await authenticationRemoteDataSource.setProfile(imageId: tImageId); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.setProfileAvatar, + method: RequestMethod.post, + body: {'image_id': tImageId}, + )).thenAnswer((_) async { + return Response( + requestOptions: + RequestOptions(path: EndpointManager.setProfileAvatar), + data: json.decode(fixture('base_response_failed.json')), + statusCode: 400); + }); + final call = authenticationRemoteDataSource.setProfile; + expect(() => call(imageId: tImageId), throwsA(isA())); + }); + }); + + // getUserDetails + group("Get User Details", () { + test("should return ResendOTP Response when the call is successful", + () async { + setUpMockGetUserDetails(); + final result = await authenticationRemoteDataSource.getUserDetails(); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.getUser, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getUser), + data: json.decode(fixture('base_response_failed.json')), + statusCode: 400); + }); + final call = authenticationRemoteDataSource.getUserDetails; + expect(() => call(), throwsA(isA())); + }); + }); } diff --git a/test/feature/authentication/data/repositories/authentication_repository_test.dart b/test/feature/authentication/data/repositories/authentication_repository_test.dart index 95b44a3..e5c449d 100644 --- a/test/feature/authentication/data/repositories/authentication_repository_test.dart +++ b/test/feature/authentication/data/repositories/authentication_repository_test.dart @@ -3,6 +3,8 @@ import 'package:defiraiser_mobile/features/authentication/data/data_source/authe import 'package:defiraiser_mobile/features/authentication/data/data_source/authentication_remote_data_source.dart'; import 'package:defiraiser_mobile/features/authentication/data/repositories/authentication_repository.dart'; import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/check_user_entity/check_user_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/last_user_cache_details/last_user_cache_details.dart'; import 'package:defiraiser_mobile/features/authentication/domain/entities/login_entity/login_response_entity.dart' as login; import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart'; @@ -19,15 +21,19 @@ class MockAuthLocalDataSource extends Mock implements AuthLocalDataSource {} void main() { late MockAuthenticationRemoteDataSource mockRemoteDataSource; late IAuthenticationRepository authenticationRepositoryImpl; + late MockAuthLocalDataSource mockAuthLocalDataSource; late String tUsername = "test"; late String tEmail = "test@test.com"; late String tPassword = "test"; late String tOtpCode = "123456"; + late int tImageId = 1; late CreateAccountResponse tCreateAccountResponse; late login.LoginResponse tLoginResponse; late BaseEntity tBaseResponse; + late CheckUserEntity tCheckUserEntity; + late login.UserResponse tUserResponse; setUpAll(() { mockRemoteDataSource = MockAuthenticationRemoteDataSource(); @@ -48,6 +54,21 @@ void main() { status: 200); }); + tUserResponse = const login.UserResponse( + username: "ademola1", + email: "", + passwordChangedAt: null, + createdAt: null, + address: "0x1C803Ba37C0494ecD088Fb878d687FAEb5a2EB5E", + balance: "0.1", + ); + + tCheckUserEntity = const CheckUserEntity( + data: true, + message: "success", + status: 200, + ); + tLoginResponse = const login.LoginResponse( data: login.Data( sessionId: "", @@ -98,9 +119,25 @@ void main() { // arrange when(() => mockRemoteDataSource.login(any(), any())) .thenAnswer((_) async => tLoginResponse); + // act final result = await authenticationRepositoryImpl.login( username: tUsername, password: tPassword); + if (tLoginResponse.data != null) { + final lastCacheDetails = LastUserCachedDetails( + password: tPassword, + username: tUsername, + email: tLoginResponse.data!.user.email, + isBiometric: tLoginResponse.data!.user.biometrics, + ); + await mockAuthLocalDataSource.cacheUserLoginData( + lastUserCachedDetails: lastCacheDetails); + await mockAuthLocalDataSource.cacheUserDetails( + user: tLoginResponse.data!.user); + await mockAuthLocalDataSource.saveAccessToken( + token: tLoginResponse.data!.accessToken); + } + // assert verify(() => mockRemoteDataSource.login(any(), any())); expect(result, equals(Right(tLoginResponse))); @@ -199,4 +236,67 @@ void main() { expect(result, equals(Right(tBaseResponse))); }); }); + + // checkUsernameExists + group("checkUsernameExists user account", () { + test( + "should return remote data when the call to remote data source is successful", + () async { + // arrange + when(() => mockRemoteDataSource.checkUsernameExists( + username: any( + named: "username", + ))).thenAnswer((_) async => tCheckUserEntity); + // act + final result = await authenticationRepositoryImpl.checkUsernameExists( + username: tUsername); + // assert + verify(() => mockRemoteDataSource.checkUsernameExists( + username: any( + named: "username", + ))); + expect(result, equals(Right(tCheckUserEntity))); + }); + }); + + // setProfileAvatar + group("setProfileAvatar user account", () { + test( + "should return remote data when the call to remote data source is successful", + () async { + // arrange + when(() => mockRemoteDataSource.setProfile( + imageId: any( + named: "imageId", + ), + )).thenAnswer((_) async => tUserResponse); + // act + final result = await authenticationRepositoryImpl.setProfileAvatar( + imageId: tImageId); + // assert + verify(() => mockRemoteDataSource.setProfile( + imageId: any( + named: "imageId", + ), + )); + expect(result, equals(Right(tUserResponse))); + }); + }); + + // getUserDetails + group("getUserDetails user account", () { + test( + "should return remote data when the call to remote data source is successful", + () async { + // arrange + when(() => mockRemoteDataSource.getUserDetails()) + .thenAnswer((_) async => tUserResponse); + // act + final result = await authenticationRepositoryImpl.getUserDetails(); + await mockAuthLocalDataSource.cacheUserDetails(user: tUserResponse); + // assert + verify(() => mockRemoteDataSource.getUserDetails()); + expect(result, equals(Right(tUserResponse))); + }); + }); } diff --git a/test/feature/authentication/domain/usecases/check_user_exist_usecase_test.dart b/test/feature/authentication/domain/usecases/check_user_exist_usecase_test.dart new file mode 100644 index 0000000..7948089 --- /dev/null +++ b/test/feature/authentication/domain/usecases/check_user_exist_usecase_test.dart @@ -0,0 +1,72 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/check_user_entity/check_user_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/repositories/authentication_repository.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/check_user_exist_usecase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'create_account_usecase_test.mocks.dart'; + +@GenerateMocks([AuthenticationRepository]) +void main() { + late CheckUsernameExistUsecase usecase; + late MockAuthenticationRepository mockAuthenticationRepository; + late String username; + late CheckUserEntity tResponse; + + setUp(() { + mockAuthenticationRepository = MockAuthenticationRepository(); + usecase = CheckUsernameExistUsecase(mockAuthenticationRepository); + username = "test"; + tResponse = + const CheckUserEntity(data: true, message: "success", status: 200); + }); + + final tFailedResponse = CreateAccountResponse( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + test("should get the user info after you create account", () async { + // arrange + when(mockAuthenticationRepository.checkUsernameExists(username: username)) + .thenAnswer((_) async => Right(tResponse)); + + // act + final result = + await usecase.call(CheckUsernameExistParams(username: username)); + + // assert + expect(result, Right(tResponse)); + verify(mockAuthenticationRepository.checkUsernameExists( + username: username, + )); + verifyNoMoreInteractions(mockAuthenticationRepository); + }); + + test('should not get the user info when create account fails', () async { + // arrange + when(mockAuthenticationRepository.checkUsernameExists( + username: username, + )).thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(CheckUsernameExistParams( + username: username, + )); + + // assert + expect(result, Left(failure)); + verify(mockAuthenticationRepository.checkUsernameExists( + username: username, + )); + verifyNoMoreInteractions(mockAuthenticationRepository); + }); +} diff --git a/test/feature/authentication/domain/usecases/check_user_exist_usecase_test.mocks.dart b/test/feature/authentication/domain/usecases/check_user_exist_usecase_test.mocks.dart new file mode 100644 index 0000000..c424dc7 --- /dev/null +++ b/test/feature/authentication/domain/usecases/check_user_exist_usecase_test.mocks.dart @@ -0,0 +1,291 @@ +// Mocks generated by Mockito 5.4.2 from annotations +// in defiraiser_mobile/test/feature/authentication/domain/usecases/check_user_exist_usecase_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i4; + +import 'package:dartz/dartz.dart' as _i2; +import 'package:defiraiser_mobile/core/network/api_error.dart' as _i5; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart' + as _i8; +import 'package:defiraiser_mobile/features/authentication/domain/entities/check_user_entity/check_user_entity.dart' + as _i9; +import 'package:defiraiser_mobile/features/authentication/domain/entities/login_entity/login_response_entity.dart' + as _i7; +import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart' + as _i6; +import 'package:defiraiser_mobile/features/authentication/domain/repositories/authentication_repository.dart' + as _i3; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class + +class _FakeEither_0 extends _i1.SmartFake implements _i2.Either { + _FakeEither_0( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +/// A class which mocks [AuthenticationRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockAuthenticationRepository extends _i1.Mock + implements _i3.AuthenticationRepository { + MockAuthenticationRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i4.Future<_i2.Either<_i5.ApiError, _i6.CreateAccountResponse>> + createAccount({ + required String? username, + required String? email, + }) => + (super.noSuchMethod( + Invocation.method( + #createAccount, + [], + { + #username: username, + #email: email, + }, + ), + returnValue: _i4.Future< + _i2.Either<_i5.ApiError, _i6.CreateAccountResponse>>.value( + _FakeEither_0<_i5.ApiError, _i6.CreateAccountResponse>( + this, + Invocation.method( + #createAccount, + [], + { + #username: username, + #email: email, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i6.CreateAccountResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.LoginResponse>> login({ + required String? username, + required String? password, + }) => + (super.noSuchMethod( + Invocation.method( + #login, + [], + { + #username: username, + #password: password, + }, + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i7.LoginResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.LoginResponse>( + this, + Invocation.method( + #login, + [], + { + #username: username, + #password: password, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.LoginResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> verifyOtp({ + required String? username, + required String? otpCode, + }) => + (super.noSuchMethod( + Invocation.method( + #verifyOtp, + [], + { + #username: username, + #otpCode: otpCode, + }, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #verifyOtp, + [], + { + #username: username, + #otpCode: otpCode, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> resendOTP( + {required String? userId}) => + (super.noSuchMethod( + Invocation.method( + #resendOTP, + [], + {#userId: userId}, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #resendOTP, + [], + {#userId: userId}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> resetPassword( + {required String? username}) => + (super.noSuchMethod( + Invocation.method( + #resetPassword, + [], + {#username: username}, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #resetPassword, + [], + {#username: username}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> verifyPasswordResetCode({ + required String? username, + required String? otpCode, + required String? password, + }) => + (super.noSuchMethod( + Invocation.method( + #verifyPasswordResetCode, + [], + { + #username: username, + #otpCode: otpCode, + #password: password, + }, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #verifyPasswordResetCode, + [], + { + #username: username, + #otpCode: otpCode, + #password: password, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> createUserPassword({ + required String? username, + required bool? biometrics, + required String? password, + }) => + (super.noSuchMethod( + Invocation.method( + #createUserPassword, + [], + { + #username: username, + #biometrics: biometrics, + #password: password, + }, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #createUserPassword, + [], + { + #username: username, + #biometrics: biometrics, + #password: password, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i9.CheckUserEntity>> checkUsernameExists( + {required String? username}) => + (super.noSuchMethod( + Invocation.method( + #checkUsernameExists, + [], + {#username: username}, + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i9.CheckUserEntity>>.value( + _FakeEither_0<_i5.ApiError, _i9.CheckUserEntity>( + this, + Invocation.method( + #checkUsernameExists, + [], + {#username: username}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i9.CheckUserEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>> setProfileAvatar( + {required int? imageId}) => + (super.noSuchMethod( + Invocation.method( + #setProfileAvatar, + [], + {#imageId: imageId}, + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.UserResponse>( + this, + Invocation.method( + #setProfileAvatar, + [], + {#imageId: imageId}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>> getUserDetails() => + (super.noSuchMethod( + Invocation.method( + #getUserDetails, + [], + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.UserResponse>( + this, + Invocation.method( + #getUserDetails, + [], + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>>); +} diff --git a/test/feature/authentication/domain/usecases/get_user_details_usecase_test.dart b/test/feature/authentication/domain/usecases/get_user_details_usecase_test.dart new file mode 100644 index 0000000..fcda914 --- /dev/null +++ b/test/feature/authentication/domain/usecases/get_user_details_usecase_test.dart @@ -0,0 +1,69 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/core/usecases/usecases.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/login_entity/login_response_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/repositories/authentication_repository.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/get_user_details_usecase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'login_usecase_test.mocks.dart'; + +@GenerateMocks([AuthenticationRepository]) +void main() { + late GetUserDetailsUsecase usecase; + late MockAuthenticationRepository mockAuthenticationRepository; + + late UserResponse tResponse; + + setUp(() { + mockAuthenticationRepository = MockAuthenticationRepository(); + usecase = GetUserDetailsUsecase(mockAuthenticationRepository); + tResponse = const UserResponse( + username: "ademola1", + email: "", + passwordChangedAt: null, + createdAt: null, + address: "0x1C803Ba37C0494ecD088Fb878d687FAEb5a2EB5E", + balance: "0.1", + ); + }); + + final tFailedResponse = LoginResponse( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + test("should get the user info after you create account", () async { + // arrange + when(mockAuthenticationRepository.getUserDetails()) + .thenAnswer((_) async => Right(tResponse)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Right(tResponse)); + verify(mockAuthenticationRepository.getUserDetails()); + verifyNoMoreInteractions(mockAuthenticationRepository); + }); + + test('should not get the user info when create account fails', () async { + // arrange + when(mockAuthenticationRepository.getUserDetails()) + .thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Left(failure)); + verify(mockAuthenticationRepository.getUserDetails()); + verifyNoMoreInteractions(mockAuthenticationRepository); + }); +} diff --git a/test/feature/authentication/domain/usecases/get_user_details_usecase_test.mocks.dart b/test/feature/authentication/domain/usecases/get_user_details_usecase_test.mocks.dart new file mode 100644 index 0000000..f597dd5 --- /dev/null +++ b/test/feature/authentication/domain/usecases/get_user_details_usecase_test.mocks.dart @@ -0,0 +1,291 @@ +// Mocks generated by Mockito 5.4.2 from annotations +// in defiraiser_mobile/test/feature/authentication/domain/usecases/get_user_details_usecase_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i4; + +import 'package:dartz/dartz.dart' as _i2; +import 'package:defiraiser_mobile/core/network/api_error.dart' as _i5; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart' + as _i8; +import 'package:defiraiser_mobile/features/authentication/domain/entities/check_user_entity/check_user_entity.dart' + as _i9; +import 'package:defiraiser_mobile/features/authentication/domain/entities/login_entity/login_response_entity.dart' + as _i7; +import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart' + as _i6; +import 'package:defiraiser_mobile/features/authentication/domain/repositories/authentication_repository.dart' + as _i3; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class + +class _FakeEither_0 extends _i1.SmartFake implements _i2.Either { + _FakeEither_0( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +/// A class which mocks [AuthenticationRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockAuthenticationRepository extends _i1.Mock + implements _i3.AuthenticationRepository { + MockAuthenticationRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i4.Future<_i2.Either<_i5.ApiError, _i6.CreateAccountResponse>> + createAccount({ + required String? username, + required String? email, + }) => + (super.noSuchMethod( + Invocation.method( + #createAccount, + [], + { + #username: username, + #email: email, + }, + ), + returnValue: _i4.Future< + _i2.Either<_i5.ApiError, _i6.CreateAccountResponse>>.value( + _FakeEither_0<_i5.ApiError, _i6.CreateAccountResponse>( + this, + Invocation.method( + #createAccount, + [], + { + #username: username, + #email: email, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i6.CreateAccountResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.LoginResponse>> login({ + required String? username, + required String? password, + }) => + (super.noSuchMethod( + Invocation.method( + #login, + [], + { + #username: username, + #password: password, + }, + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i7.LoginResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.LoginResponse>( + this, + Invocation.method( + #login, + [], + { + #username: username, + #password: password, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.LoginResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> verifyOtp({ + required String? username, + required String? otpCode, + }) => + (super.noSuchMethod( + Invocation.method( + #verifyOtp, + [], + { + #username: username, + #otpCode: otpCode, + }, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #verifyOtp, + [], + { + #username: username, + #otpCode: otpCode, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> resendOTP( + {required String? userId}) => + (super.noSuchMethod( + Invocation.method( + #resendOTP, + [], + {#userId: userId}, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #resendOTP, + [], + {#userId: userId}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> resetPassword( + {required String? username}) => + (super.noSuchMethod( + Invocation.method( + #resetPassword, + [], + {#username: username}, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #resetPassword, + [], + {#username: username}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> verifyPasswordResetCode({ + required String? username, + required String? otpCode, + required String? password, + }) => + (super.noSuchMethod( + Invocation.method( + #verifyPasswordResetCode, + [], + { + #username: username, + #otpCode: otpCode, + #password: password, + }, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #verifyPasswordResetCode, + [], + { + #username: username, + #otpCode: otpCode, + #password: password, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> createUserPassword({ + required String? username, + required bool? biometrics, + required String? password, + }) => + (super.noSuchMethod( + Invocation.method( + #createUserPassword, + [], + { + #username: username, + #biometrics: biometrics, + #password: password, + }, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #createUserPassword, + [], + { + #username: username, + #biometrics: biometrics, + #password: password, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i9.CheckUserEntity>> checkUsernameExists( + {required String? username}) => + (super.noSuchMethod( + Invocation.method( + #checkUsernameExists, + [], + {#username: username}, + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i9.CheckUserEntity>>.value( + _FakeEither_0<_i5.ApiError, _i9.CheckUserEntity>( + this, + Invocation.method( + #checkUsernameExists, + [], + {#username: username}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i9.CheckUserEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>> setProfileAvatar( + {required int? imageId}) => + (super.noSuchMethod( + Invocation.method( + #setProfileAvatar, + [], + {#imageId: imageId}, + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.UserResponse>( + this, + Invocation.method( + #setProfileAvatar, + [], + {#imageId: imageId}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>> getUserDetails() => + (super.noSuchMethod( + Invocation.method( + #getUserDetails, + [], + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.UserResponse>( + this, + Invocation.method( + #getUserDetails, + [], + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.UserResponse>>); +} diff --git a/test/feature/authentication/presentation/forget_password/state/bloc/forget_password_bloc_test.dart b/test/feature/authentication/presentation/forget_password/state/bloc/forget_password_bloc_test.dart new file mode 100644 index 0000000..decc695 --- /dev/null +++ b/test/feature/authentication/presentation/forget_password/state/bloc/forget_password_bloc_test.dart @@ -0,0 +1,144 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/reset_password_usecase.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/verify_password_reset.dart'; +import 'package:defiraiser_mobile/features/authentication/presentation/forget_password/state/bloc/forget_password_bloc.dart'; +import 'package:defiraiser_mobile/features/authentication/presentation/login/states/bloc/login_state_bloc.dart'; +import 'package:defiraiser_mobile/features/authentication/presentation/signup/states/bloc/sign_up_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'forget_password_bloc_test.mocks.dart'; + +@GenerateMocks([ResetPasswordUsecase]) +@GenerateMocks([VerifyPasswordResetUsecase]) +void main() { + late MockResetPasswordUsecase mockResetPasswordUsecase; + late MockVerifyPasswordResetUsecase mockVerifyPasswordResetUsecase; + late String tEmail; + late String tOtp; + late String tPassword; + late BaseEntity tResponse; + late ForgetPasswordBloc bloc; + + setUp(() { + mockResetPasswordUsecase = MockResetPasswordUsecase(); + mockVerifyPasswordResetUsecase = MockVerifyPasswordResetUsecase(); + tEmail = "test@test.com"; + tOtp = "123456"; + tPassword = "test"; + bloc = ForgetPasswordBloc( + resetPasswordUsecase: mockResetPasswordUsecase, + verifyPasswordResetUsecase: mockVerifyPasswordResetUsecase); + tResponse = BaseEntity( + data: "Verified", + message: "success", + status: 200, + ); + }); + + void setUpMockConverterToSuccess() => when(mockResetPasswordUsecase.call(any)) + .thenAnswer((_) async => Right(tResponse)); + + void setUpMockConverterToVerifyPasswordSuccess() => when(mockVerifyPasswordResetUsecase.call(any)) + .thenAnswer((_) async => Right(tResponse)); + + test('initialState should be Empty', () async { + //assert + expect(bloc.state, ForgetPasswordState.initial()); + }); + + group('Reset Password User Account', () { + test('should get the user info after you create account', () async { + // arrange + setUpMockConverterToSuccess(); + + // act + bloc.add(ResetPasswordEvent(email: tEmail)); + + // assert + await untilCalled(mockResetPasswordUsecase.call(any)); + verify(mockResetPasswordUsecase.call(Params(username: tEmail))); + }); + + test('should emit [Loading, Loaded] when data is gotten successfully', + () async* { + // arrange + setUpMockConverterToSuccess(); + + // assert later + final expected = [ + ForgetPasswordState.loading(), + ForgetPasswordState.resetPassword(), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(ResetPasswordEvent(email: tEmail)); + }); + + test('should emit [Loading, Error] when getting data fails', () async* { + // arrange + when(mockResetPasswordUsecase.call(any)).thenAnswer( + (_) async => Left(ApiError(errorMessage: "error", errorCode: "400"))); + + // assert later + final expected = [ + ForgetPasswordState.loading(), + ForgetPasswordState.resetPasswordError(tResponse.message), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(ResetPasswordEvent(email: tEmail)); + }); + }); + + group("Verify User Otp Code", () { + test('should get the user info after you create account', () async { + // arrange + setUpMockConverterToVerifyPasswordSuccess(); + + // act + bloc.add(ResetVerifyOtpEvent(username: tEmail, otp: tOtp, password: tPassword)); + + // assert + await untilCalled(mockVerifyPasswordResetUsecase.call(any)); + verify(mockVerifyPasswordResetUsecase.call(VerifyPasswordParams(username: tEmail, otpCode: tOtp, password: tPassword))); + }); + + test('should emit [Loading, Loaded] when data is gotten successfully', + () async* { + // arrange + setUpMockConverterToVerifyPasswordSuccess(); + + // assert later + final expected = [ + ForgetPasswordState.loading(), + ForgetPasswordState.registrationSuccessful(tResponse.message), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(ResetVerifyOtpEvent(username: tEmail, otp: tOtp, password: tPassword)); + }); + + test('should emit [Loading, Error] when getting data fails', () async* { + // arrange + when(mockVerifyPasswordResetUsecase.call(any)).thenAnswer( + (_) async => Left(ApiError(errorMessage: "error", errorCode: "400"))); + + // assert later + final expected = [ + ForgetPasswordState.loading(), + ForgetPasswordState.registrationError(tResponse.message), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(ResetVerifyOtpEvent(username: tEmail, otp: tOtp, password: tPassword)); + }); + }); +} diff --git a/test/feature/authentication/presentation/forget_password/state/bloc/forget_password_bloc_test.mocks.dart b/test/feature/authentication/presentation/forget_password/state/bloc/forget_password_bloc_test.mocks.dart new file mode 100644 index 0000000..3420b0e --- /dev/null +++ b/test/feature/authentication/presentation/forget_password/state/bloc/forget_password_bloc_test.mocks.dart @@ -0,0 +1,124 @@ +// Mocks generated by Mockito 5.4.2 from annotations +// in defiraiser_mobile/test/feature/authentication/presentation/forget_password/state/bloc/forget_password_bloc_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:dartz/dartz.dart' as _i3; +import 'package:defiraiser_mobile/core/network/api_error.dart' as _i6; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart' + as _i7; +import 'package:defiraiser_mobile/features/authentication/domain/repositories/authentication_repository.dart' + as _i2; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/reset_password_usecase.dart' + as _i4; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/verify_password_reset.dart' + as _i8; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class + +class _FakeAuthenticationRepository_0 extends _i1.SmartFake + implements _i2.AuthenticationRepository { + _FakeAuthenticationRepository_0( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +class _FakeEither_1 extends _i1.SmartFake implements _i3.Either { + _FakeEither_1( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +/// A class which mocks [ResetPasswordUsecase]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockResetPasswordUsecase extends _i1.Mock + implements _i4.ResetPasswordUsecase { + MockResetPasswordUsecase() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.AuthenticationRepository get authenticationRepository => + (super.noSuchMethod( + Invocation.getter(#authenticationRepository), + returnValue: _FakeAuthenticationRepository_0( + this, + Invocation.getter(#authenticationRepository), + ), + ) as _i2.AuthenticationRepository); + @override + _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>> call( + _i4.Params? params) => + (super.noSuchMethod( + Invocation.method( + #call, + [params], + ), + returnValue: _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>>.value( + _FakeEither_1<_i6.ApiError, _i7.BaseEntity>( + this, + Invocation.method( + #call, + [params], + ), + )), + ) as _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>>); +} + +/// A class which mocks [VerifyPasswordResetUsecase]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockVerifyPasswordResetUsecase extends _i1.Mock + implements _i8.VerifyPasswordResetUsecase { + MockVerifyPasswordResetUsecase() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.AuthenticationRepository get authenticationRepository => + (super.noSuchMethod( + Invocation.getter(#authenticationRepository), + returnValue: _FakeAuthenticationRepository_0( + this, + Invocation.getter(#authenticationRepository), + ), + ) as _i2.AuthenticationRepository); + @override + _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>> call( + _i8.VerifyPasswordParams? params) => + (super.noSuchMethod( + Invocation.method( + #call, + [params], + ), + returnValue: _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>>.value( + _FakeEither_1<_i6.ApiError, _i7.BaseEntity>( + this, + Invocation.method( + #call, + [params], + ), + )), + ) as _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>>); +} diff --git a/test/feature/authentication/presentation/login/state/get_user_details/bloc/get_user_details_bloc_test.dart b/test/feature/authentication/presentation/login/state/get_user_details/bloc/get_user_details_bloc_test.dart new file mode 100644 index 0000000..11d3f9b --- /dev/null +++ b/test/feature/authentication/presentation/login/state/get_user_details/bloc/get_user_details_bloc_test.dart @@ -0,0 +1,85 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/core/usecases/usecases.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/login_entity/login_response_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/get_user_details_usecase.dart'; +import 'package:defiraiser_mobile/features/authentication/presentation/login/states/get_user_details/bloc/get_user_details_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'get_user_details_bloc_test.mocks.dart'; + +@GenerateMocks([GetUserDetailsUsecase]) +void main() { + late MockGetUserDetailsUsecase mockGetUserDetailsUsecase; + late UserResponse tResponse; + late GetUserDetailsBloc bloc; + + setUp(() { + mockGetUserDetailsUsecase = MockGetUserDetailsUsecase(); + bloc = GetUserDetailsBloc(getUserDetailsUsecase: mockGetUserDetailsUsecase); + tResponse = const UserResponse( + username: "ademola1", + email: "", + passwordChangedAt: null, + createdAt: null, + address: "0x1C803Ba37C0494ecD088Fb878d687FAEb5a2EB5E", + balance: "0.1", + ); + }); + + void setUpMockConverterToSuccess() => + when(mockGetUserDetailsUsecase.call(any)) + .thenAnswer((_) async => Right(tResponse)); + test('initialState should be Empty', () async { + //assert + expect(bloc.state, GetUserDetailsState.initial()); + }); + + group('Create User Account', () { + test('should get the user info after you create account', () async { + // arrange + setUpMockConverterToSuccess(); + + // act + bloc.add(GetUserEventEq()); + + // assert + await untilCalled(mockGetUserDetailsUsecase.call(any)); + verify(mockGetUserDetailsUsecase.call(NoParams())); + }); + + test('should emit [Loading, Loaded] when data is gotten successfully', + () async* { + // arrange + setUpMockConverterToSuccess(); + + // assert later + final expected = [ + GetUserDetailsState.loading(), + GetUserDetailsState.loadDetails(tResponse), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(GetUserEventEq()); + }); + + test('should emit [Loading, Error] when getting data fails', () async* { + // arrange + when(mockGetUserDetailsUsecase.call(any)).thenAnswer( + (_) async => Left(ApiError(errorMessage: "error", errorCode: "400"))); + + // assert later + final expected = [ + GetUserDetailsState.loading(), + GetUserDetailsState.loadDetails(tResponse), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(GetUserEventEq()); + }); + }); +} diff --git a/test/feature/authentication/presentation/login/state/get_user_details/bloc/get_user_details_bloc_test.mocks.dart b/test/feature/authentication/presentation/login/state/get_user_details/bloc/get_user_details_bloc_test.mocks.dart new file mode 100644 index 0000000..b93a702 --- /dev/null +++ b/test/feature/authentication/presentation/login/state/get_user_details/bloc/get_user_details_bloc_test.mocks.dart @@ -0,0 +1,87 @@ +// Mocks generated by Mockito 5.4.2 from annotations +// in defiraiser_mobile/test/feature/authentication/presentation/login/state/get_user_details/bloc/get_user_details_bloc_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:dartz/dartz.dart' as _i3; +import 'package:defiraiser_mobile/core/network/api_error.dart' as _i6; +import 'package:defiraiser_mobile/core/usecases/usecases.dart' as _i8; +import 'package:defiraiser_mobile/features/authentication/domain/entities/login_entity/login_response_entity.dart' + as _i7; +import 'package:defiraiser_mobile/features/authentication/domain/repositories/authentication_repository.dart' + as _i2; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/get_user_details_usecase.dart' + as _i4; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class + +class _FakeAuthenticationRepository_0 extends _i1.SmartFake + implements _i2.AuthenticationRepository { + _FakeAuthenticationRepository_0( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +class _FakeEither_1 extends _i1.SmartFake implements _i3.Either { + _FakeEither_1( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +/// A class which mocks [GetUserDetailsUsecase]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockGetUserDetailsUsecase extends _i1.Mock + implements _i4.GetUserDetailsUsecase { + MockGetUserDetailsUsecase() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.AuthenticationRepository get authenticationRepository => + (super.noSuchMethod( + Invocation.getter(#authenticationRepository), + returnValue: _FakeAuthenticationRepository_0( + this, + Invocation.getter(#authenticationRepository), + ), + ) as _i2.AuthenticationRepository); + @override + _i5.Future<_i3.Either<_i6.ApiError, _i7.UserResponse>> call( + _i8.NoParams? params) => + (super.noSuchMethod( + Invocation.method( + #call, + [params], + ), + returnValue: + _i5.Future<_i3.Either<_i6.ApiError, _i7.UserResponse>>.value( + _FakeEither_1<_i6.ApiError, _i7.UserResponse>( + this, + Invocation.method( + #call, + [params], + ), + )), + ) as _i5.Future<_i3.Either<_i6.ApiError, _i7.UserResponse>>); +} diff --git a/test/feature/authentication/presentation/login/state/set_profile_avatar/bloc/set_profile_avatar_bloc_test.dart b/test/feature/authentication/presentation/login/state/set_profile_avatar/bloc/set_profile_avatar_bloc_test.dart new file mode 100644 index 0000000..a8e325e --- /dev/null +++ b/test/feature/authentication/presentation/login/state/set_profile_avatar/bloc/set_profile_avatar_bloc_test.dart @@ -0,0 +1,88 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/login_entity/login_response_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/set_profile_avatar_usecase.dart'; +import 'package:defiraiser_mobile/features/authentication/presentation/login/states/set_profile_avatar/bloc/set_profile_avatar_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'set_profile_avatar_bloc_test.mocks.dart'; + +@GenerateMocks([ProfileAvatarUsecase]) +void main() { + late MockProfileAvatarUsecase mockProfileAvatarUsecase; + late UserResponse tResponse; + late SetProfileAvatarBloc bloc; + late String tMessage; + late int tImageId; + + setUp(() { + mockProfileAvatarUsecase = MockProfileAvatarUsecase(); + bloc = SetProfileAvatarBloc(profileAvatarUsecase: mockProfileAvatarUsecase); + tResponse = const UserResponse( + username: "ademola1", + email: "", + passwordChangedAt: null, + createdAt: null, + address: "0x1C803Ba37C0494ecD088Fb878d687FAEb5a2EB5E", + balance: "0.1", + ); + tImageId = 1; + tMessage = "Error"; + }); + + void setUpMockConverterToSuccess() => when(mockProfileAvatarUsecase.call(any)) + .thenAnswer((_) async => Right(tResponse)); + test('initialState should be Empty', () async { + //assert + expect(bloc.state, SetProfileAvatarState.initial()); + }); + + group('Create User Account', () { + test('should get the user info after you create account', () async { + // arrange + setUpMockConverterToSuccess(); + + // act + bloc.add(SetProfileAvatarEq(imageId: tImageId)); + + // assert + await untilCalled(mockProfileAvatarUsecase.call(any)); + verify(mockProfileAvatarUsecase + .call((SetProfileAvatarParams(imageId: tImageId)))); + }); + + test('should emit [Loading, Loaded] when data is gotten successfully', + () async* { + // arrange + setUpMockConverterToSuccess(); + + // assert later + final expected = [ + SetProfileAvatarState.loading(), + SetProfileAvatarState.profileSet(tResponse.avatar), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(SetProfileAvatarEq(imageId: tImageId)); + }); + + test('should emit [Loading, Error] when getting data fails', () async* { + // arrange + when(mockProfileAvatarUsecase.call(any)).thenAnswer( + (_) async => Left(ApiError(errorMessage: "error", errorCode: "400"))); + + // assert later + final expected = [ + SetProfileAvatarState.loading(), + SetProfileAvatarState.profileError(tMessage), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(SetProfileAvatarEq(imageId: tImageId)); + }); + }); +} diff --git a/test/feature/authentication/presentation/login/state/set_profile_avatar/bloc/set_profile_avatar_bloc_test.mocks.dart b/test/feature/authentication/presentation/login/state/set_profile_avatar/bloc/set_profile_avatar_bloc_test.mocks.dart new file mode 100644 index 0000000..fc3990f --- /dev/null +++ b/test/feature/authentication/presentation/login/state/set_profile_avatar/bloc/set_profile_avatar_bloc_test.mocks.dart @@ -0,0 +1,86 @@ +// Mocks generated by Mockito 5.4.2 from annotations +// in defiraiser_mobile/test/feature/authentication/presentation/login/state/set_profile_avatar/bloc/set_profile_avatar_bloc_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:dartz/dartz.dart' as _i3; +import 'package:defiraiser_mobile/core/network/api_error.dart' as _i6; +import 'package:defiraiser_mobile/features/authentication/domain/entities/login_entity/login_response_entity.dart' + as _i7; +import 'package:defiraiser_mobile/features/authentication/domain/repositories/authentication_repository.dart' + as _i2; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/set_profile_avatar_usecase.dart' + as _i4; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class + +class _FakeAuthenticationRepository_0 extends _i1.SmartFake + implements _i2.AuthenticationRepository { + _FakeAuthenticationRepository_0( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +class _FakeEither_1 extends _i1.SmartFake implements _i3.Either { + _FakeEither_1( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +/// A class which mocks [ProfileAvatarUsecase]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockProfileAvatarUsecase extends _i1.Mock + implements _i4.ProfileAvatarUsecase { + MockProfileAvatarUsecase() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.AuthenticationRepository get authenticationRepository => + (super.noSuchMethod( + Invocation.getter(#authenticationRepository), + returnValue: _FakeAuthenticationRepository_0( + this, + Invocation.getter(#authenticationRepository), + ), + ) as _i2.AuthenticationRepository); + @override + _i5.Future<_i3.Either<_i6.ApiError, _i7.UserResponse>> call( + _i4.SetProfileAvatarParams? params) => + (super.noSuchMethod( + Invocation.method( + #call, + [params], + ), + returnValue: + _i5.Future<_i3.Either<_i6.ApiError, _i7.UserResponse>>.value( + _FakeEither_1<_i6.ApiError, _i7.UserResponse>( + this, + Invocation.method( + #call, + [params], + ), + )), + ) as _i5.Future<_i3.Either<_i6.ApiError, _i7.UserResponse>>); +} diff --git a/test/feature/authentication/presentation/signup/state/create_password_bloc/create_password_bloc_test.dart b/test/feature/authentication/presentation/signup/state/create_password_bloc/create_password_bloc_test.dart new file mode 100644 index 0000000..8ac958e --- /dev/null +++ b/test/feature/authentication/presentation/signup/state/create_password_bloc/create_password_bloc_test.dart @@ -0,0 +1,101 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/create_user_password_usecase.dart'; +import 'package:defiraiser_mobile/features/authentication/presentation/signup/states/create_password_bloc/bloc/create_password_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'create_password_bloc_test.mocks.dart'; + +@GenerateMocks([CreateUserPasswordUsecase]) +void main() { + late MockCreateUserPasswordUsecase mockCreateUserPasswordUsecase; + + late CreatePasswordBloc bloc; + late BaseEntity tBaseResponse; + late String tUsername; + late String tPassword; + late bool tBiometrics; + late String tMessage; + + setUp(() { + mockCreateUserPasswordUsecase = MockCreateUserPasswordUsecase(); + bloc = CreatePasswordBloc( + createUserPasswordUsecase: mockCreateUserPasswordUsecase, + ); + }); + + tBaseResponse = const BaseEntity( + message: "success", + data: "Passed", + status: 200, + ); + + tUsername = "test"; + tPassword = "test"; + tBiometrics = true; + tMessage = "success"; + + void setUpMockConverterToSuccess() => + when(mockCreateUserPasswordUsecase.call(any)) + .thenAnswer((_) async => Right(tBaseResponse)); + + test('initialState should be Empty', () async { + //assert + expect(bloc.state, CreatePasswordState.initial()); + }); + + group("should create password", () { + test('should get the user info after you create account', () async { + // arrange + setUpMockConverterToSuccess(); + + // act + bloc.add(CreatePasswordEq( + password: tPassword, username: tUsername, biometrics: tBiometrics)); + + // assert + await untilCalled(mockCreateUserPasswordUsecase.call(any)); + verify(mockCreateUserPasswordUsecase.call(CreatePasswordParams( + password: tPassword, username: tUsername, biometrics: tBiometrics))); + }); + + test( + 'should emit [Loading, Loaded] when data is gotten successfully from the server', + () async { + // arrange + setUpMockConverterToSuccess(); + + // assert later + final expected = [ + CreatePasswordState.creatingPassword(), + CreatePasswordState.createPasswordSuccess(tMessage), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(CreatePasswordEq( + password: tPassword, username: tUsername, biometrics: tBiometrics)); + }); + + test('should emit [Loading, Error] when getting data fails from the server', + () async* { + // arrange + when(mockCreateUserPasswordUsecase.call(any)).thenAnswer( + (_) async => Left(ApiError(errorMessage: "error", errorCode: "400"))); + + // assert later + final expected = [ + CreatePasswordState.creatingPassword(), + CreatePasswordState.createPasswordError(tBaseResponse.message), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(CreatePasswordEq( + password: tPassword, username: tUsername, biometrics: tBiometrics)); + }); + }); +} diff --git a/test/feature/authentication/presentation/signup/state/create_password_bloc/create_password_bloc_test.mocks.dart b/test/feature/authentication/presentation/signup/state/create_password_bloc/create_password_bloc_test.mocks.dart new file mode 100644 index 0000000..7268366 --- /dev/null +++ b/test/feature/authentication/presentation/signup/state/create_password_bloc/create_password_bloc_test.mocks.dart @@ -0,0 +1,85 @@ +// Mocks generated by Mockito 5.4.2 from annotations +// in defiraiser_mobile/test/feature/authentication/presentation/signup/state/create_password_bloc/create_password_bloc_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:dartz/dartz.dart' as _i3; +import 'package:defiraiser_mobile/core/network/api_error.dart' as _i6; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart' + as _i7; +import 'package:defiraiser_mobile/features/authentication/domain/repositories/authentication_repository.dart' + as _i2; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/create_user_password_usecase.dart' + as _i4; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class + +class _FakeAuthenticationRepository_0 extends _i1.SmartFake + implements _i2.AuthenticationRepository { + _FakeAuthenticationRepository_0( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +class _FakeEither_1 extends _i1.SmartFake implements _i3.Either { + _FakeEither_1( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +/// A class which mocks [CreateUserPasswordUsecase]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCreateUserPasswordUsecase extends _i1.Mock + implements _i4.CreateUserPasswordUsecase { + MockCreateUserPasswordUsecase() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.AuthenticationRepository get authenticationRepository => + (super.noSuchMethod( + Invocation.getter(#authenticationRepository), + returnValue: _FakeAuthenticationRepository_0( + this, + Invocation.getter(#authenticationRepository), + ), + ) as _i2.AuthenticationRepository); + @override + _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>> call( + _i4.CreatePasswordParams? params) => + (super.noSuchMethod( + Invocation.method( + #call, + [params], + ), + returnValue: _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>>.value( + _FakeEither_1<_i6.ApiError, _i7.BaseEntity>( + this, + Invocation.method( + #call, + [params], + ), + )), + ) as _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>>); +} diff --git a/test/feature/authentication/presentation/signup/state/verify_bloc/bloc/verify_otp_bloc_test.dart b/test/feature/authentication/presentation/signup/state/verify_bloc/bloc/verify_otp_bloc_test.dart new file mode 100644 index 0000000..d0f3210 --- /dev/null +++ b/test/feature/authentication/presentation/signup/state/verify_bloc/bloc/verify_otp_bloc_test.dart @@ -0,0 +1,104 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/verify_otp_usecase.dart'; +import 'package:defiraiser_mobile/features/authentication/presentation/signup/states/verify_bloc/bloc/verify_otp_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'verify_otp_bloc_test.mocks.dart'; + +@GenerateMocks([VerifyOtpUseCase]) +void main() { + late MockVerifyOtpUseCase mockVerifyOtpUseCase; + + late VerifyOtpBloc bloc; + late BaseEntity tBaseResponse; + late String tUsername; + late String tOtp; + late String tMessage; + + setUp(() { + mockVerifyOtpUseCase = MockVerifyOtpUseCase(); + bloc = VerifyOtpBloc( + verifyOtpUseCase: mockVerifyOtpUseCase, + ); + }); + + tBaseResponse = const BaseEntity( + message: "success", + data: "Passed", + status: 200, + ); + + tUsername = "test"; + tOtp = "123456"; + tMessage = "success"; + + void setUpMockConverterToSuccess() => when(mockVerifyOtpUseCase.call(any)) + .thenAnswer((_) async => Right(tBaseResponse)); + + test('initialState should be Empty', () async { + //assert + expect(bloc.state, VerifyOtpState.initial()); + }); + + group("should create password", () { + test('should get the user info after you create account', () async { + // arrange + setUpMockConverterToSuccess(); + + // act + bloc.add(VerifyOtpEq( + otp: tOtp, + username: tUsername, + )); + + // assert + await untilCalled(mockVerifyOtpUseCase.call(any)); + verify(mockVerifyOtpUseCase + .call(VerifyParams(username: tUsername, otpCode: tOtp))); + }); + + test( + 'should emit [Loading, Loaded] when data is gotten successfully from the server', + () async { + // arrange + setUpMockConverterToSuccess(); + + // assert later + final expected = [ + VerifyOtpState.verifyingOtp(), + VerifyOtpState.otpVerificationSuccessful(tMessage), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(VerifyOtpEq( + otp: tOtp, + username: tUsername, + )); + }); + + test('should emit [Loading, Error] when getting data fails from the server', + () async* { + // arrange + when(mockVerifyOtpUseCase.call(any)).thenAnswer( + (_) async => Left(ApiError(errorMessage: "error", errorCode: "400"))); + + // assert later + final expected = [ + VerifyOtpState.verifyingOtp(), + VerifyOtpState.otpVerificationError(tBaseResponse.message), + ]; + expectLater(bloc.stream, emitsInOrder(expected)); + + // act + bloc.add(VerifyOtpEq( + otp: tOtp, + username: tUsername, + )); + }); + }); +} diff --git a/test/feature/authentication/presentation/signup/state/verify_bloc/bloc/verify_otp_bloc_test.mocks.dart b/test/feature/authentication/presentation/signup/state/verify_bloc/bloc/verify_otp_bloc_test.mocks.dart new file mode 100644 index 0000000..6616a1f --- /dev/null +++ b/test/feature/authentication/presentation/signup/state/verify_bloc/bloc/verify_otp_bloc_test.mocks.dart @@ -0,0 +1,84 @@ +// Mocks generated by Mockito 5.4.2 from annotations +// in defiraiser_mobile/test/feature/authentication/presentation/signup/state/verify_bloc/bloc/verify_otp_bloc_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:dartz/dartz.dart' as _i3; +import 'package:defiraiser_mobile/core/network/api_error.dart' as _i6; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart' + as _i7; +import 'package:defiraiser_mobile/features/authentication/domain/repositories/authentication_repository.dart' + as _i2; +import 'package:defiraiser_mobile/features/authentication/domain/usecases/verify_otp_usecase.dart' + as _i4; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class + +class _FakeAuthenticationRepository_0 extends _i1.SmartFake + implements _i2.AuthenticationRepository { + _FakeAuthenticationRepository_0( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +class _FakeEither_1 extends _i1.SmartFake implements _i3.Either { + _FakeEither_1( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +/// A class which mocks [VerifyOtpUseCase]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockVerifyOtpUseCase extends _i1.Mock implements _i4.VerifyOtpUseCase { + MockVerifyOtpUseCase() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.AuthenticationRepository get authenticationRepository => + (super.noSuchMethod( + Invocation.getter(#authenticationRepository), + returnValue: _FakeAuthenticationRepository_0( + this, + Invocation.getter(#authenticationRepository), + ), + ) as _i2.AuthenticationRepository); + @override + _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>> call( + _i4.VerifyParams? params) => + (super.noSuchMethod( + Invocation.method( + #call, + [params], + ), + returnValue: _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>>.value( + _FakeEither_1<_i6.ApiError, _i7.BaseEntity>( + this, + Invocation.method( + #call, + [params], + ), + )), + ) as _i5.Future<_i3.Either<_i6.ApiError, _i7.BaseEntity>>); +} diff --git a/test/feature/home/data/data_source/campaign_remote_data_source_test.dart b/test/feature/home/data/data_source/campaign_remote_data_source_test.dart new file mode 100644 index 0000000..c0c7d93 --- /dev/null +++ b/test/feature/home/data/data_source/campaign_remote_data_source_test.dart @@ -0,0 +1,379 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:defiraiser_mobile/core/global/error/exceptions.dart'; +import 'package:defiraiser_mobile/core/network/endpoint_manager.dart'; +import 'package:defiraiser_mobile/core/network/network_provider.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/home/data/data_source/campaign_remote_date_source.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/campaign_categories_entity/campaign_category_entities.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/campaigns/campaigns_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/donors_entity/donors_entity.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +import '../../../../fixture/fixture_reader.dart'; + +class MockNetworkProvider extends Mock implements NetworkProvider {} + +void main() { + late MockNetworkProvider mockNetworkProvider; + late CampaignRemoteDataSourceImpl campaignRemoteDataSourceImpl; + + setUp(() async { + mockNetworkProvider = MockNetworkProvider(); + campaignRemoteDataSourceImpl = + CampaignRemoteDataSourceImpl(mockNetworkProvider); + }); + + // getCampaigns + void setUpMockHttpGetCampaigns() { + when(() => mockNetworkProvider.call( + path: EndpointManager.getCampaign, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getCampaign), + data: json.decode(fixture('campaign_reesponse.json')), + statusCode: 200); + }); + } + + // getMyCampaigns + void setUpMockHttpGetMyCampaigns() { + when(() => mockNetworkProvider.call( + path: EndpointManager.getMyCampaign, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getMyCampaign), + data: json.decode(fixture('campaign_reesponse.json')), + statusCode: 200); + }); + } + + // getCategories + void setUpMockHttpGetCategories() { + when(() => mockNetworkProvider.call( + path: EndpointManager.getCategories, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getCategories), + data: json.decode(fixture('campaign_categories_response.json')), + statusCode: 200); + }); + } + + // getDonations + void setUpMockHttpGetDonations() { + when(() => mockNetworkProvider.call( + path: EndpointManager.getDonation, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getDonation), + data: json.decode(fixture('campaign_reesponse.json')), + statusCode: 200); + }); + } + + // getCampaignsByCategory + void setUpMockHttpGetCampaignsByCategory() { + when(() => mockNetworkProvider.call( + path: EndpointManager.getCampaignsByCategory("1"), + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: + RequestOptions(path: EndpointManager.getCampaignsByCategory("1")), + data: json.decode(fixture('campaign_reesponse.json')), + statusCode: 200); + }); + } + + // getCurrentEthPrice + void setUpMockHttpGetCurrentEthPrice() { + when(() => mockNetworkProvider.call( + path: EndpointManager.getCurrentEthPrice, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions( + path: EndpointManager.getCurrentEthPrice,), + data: json.decode(fixture('base_response.json')), + statusCode: 200); + }); + } + + // getDonors + void setUpMockHttpGetDonors() { + when(() => mockNetworkProvider.call( + path: EndpointManager.getDonors("1"), + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getDonors("1")), + data: json.decode(fixture('donors_response.json')), + statusCode: 200); + }); + } + // makeDonation + void setUpMockHttpMakeDonation() { + when(() => mockNetworkProvider.call( + path: EndpointManager.makeDonation, + method: RequestMethod.post, + body: { + "campaign_id": "1", + "amount": "1", + }, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.makeDonation), + data: json.decode(fixture('base_response.json')), + statusCode: 200); + }); + } + + // createDonation + void setUpMockHttpCreateDonation() async { + var data = {}; + var multiPart = await MultipartFile.fromFile( + "assets/images/appLogo.png", + filename: "appLogo.png", + ); + + data["image"] = multiPart; + data['title'] = "title"; + data['description'] = "description"; + data['goal'] = "amount"; + data['category'] = "category"; + data['deadline'] = "deadline"; + + + when(() => mockNetworkProvider.call( + path: EndpointManager.createDonation, + method: RequestMethod.post, + body: FormData.fromMap(data), + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.createDonation), + data: json.decode(fixture('base_response.json')), + statusCode: 200); + }); + } + + group("Get Campaigns", () { + test("should return Create User Response when the call is successful", + () async { + setUpMockHttpGetCampaigns(); + final result = await campaignRemoteDataSourceImpl.getCampaigns(); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.getCampaign, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getCampaign), + data: json.decode(fixture('campaign_failed_response.json')), + statusCode: 400); + }); + final call = campaignRemoteDataSourceImpl.getCampaigns; + expect(() => call(), throwsA(isA())); + }); + }); + + // getMyCampaigns + group("Get My Campaigns", () { + test("should return Create User Response when the call is successful", + () async { + setUpMockHttpGetMyCampaigns(); + final result = await campaignRemoteDataSourceImpl.getMyCampaigns(); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.getMyCampaign, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getMyCampaign), + data: json.decode(fixture('campaign_failed_response.json')), + statusCode: 400); + }); + final call = campaignRemoteDataSourceImpl.getMyCampaigns; + expect(() => call(), throwsA(isA())); + }); + }); + + // getCategories + group("Get Categories", () { + test("should return Create User Response when the call is successful", + () async { + setUpMockHttpGetCategories(); + final result = await campaignRemoteDataSourceImpl.getCategories(); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.getCategories, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getCategories), + data: json.decode(fixture('campaign_failed_response.json')), + statusCode: 400); + }); + final call = campaignRemoteDataSourceImpl.getCategories; + expect(() => call(), throwsA(isA())); + }); + }); + + // getDonations + group("Get Donations", () { + test("should return Create User Response when the call is successful", + () async { + setUpMockHttpGetDonations(); + final result = await campaignRemoteDataSourceImpl.getDonations(); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.getDonation, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getDonation), + data: json.decode(fixture('campaign_failed_response.json')), + statusCode: 400); + }); + final call = campaignRemoteDataSourceImpl.getDonations; + expect(() => call(), throwsA(isA())); + }); + }); + + // getCampaignsByCategory + group("Get Campaigns By Category", () { + test("should return Create User Response when the call is successful", + () async { + setUpMockHttpGetCampaignsByCategory(); + final result = + await campaignRemoteDataSourceImpl.getCampaignsByCategory(id: "1"); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.getCampaignsByCategory("1"), + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions( + path: EndpointManager.getCampaignsByCategory("1")), + data: json.decode(fixture('campaign_failed_response.json')), + statusCode: 400); + }); + final call = campaignRemoteDataSourceImpl.getCampaignsByCategory; + expect(() => call(id: "1"), throwsA(isA())); + }); + }); + + // getCurrentEthPrice + group("Get Current Eth Price", () { + test("should return Create User Response when the call is successful", + () async { + setUpMockHttpGetCurrentEthPrice(); + final result = + await campaignRemoteDataSourceImpl.getCurrentEthPrice(); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.getCurrentEthPrice, + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions( + path: EndpointManager.getCurrentEthPrice), + data: json.decode(fixture('campaign_failed_response.json')), + statusCode: 400); + }); + final call = campaignRemoteDataSourceImpl.getCurrentEthPrice; + expect(() => call(), throwsA(isA())); + }); + }); + + // getDonors + group("Get Donors", () { + test("should return Create User Response when the call is successful", + () async { + setUpMockHttpGetDonors(); + final result = await campaignRemoteDataSourceImpl.getDonors(campaignId: "1"); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.getDonors("1"), + method: RequestMethod.get, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.getDonors("1")), + data: json.decode(fixture('campaign_failed_response.json')), + statusCode: 400); + }); + final call = campaignRemoteDataSourceImpl.getDonors; + expect(() => call(campaignId: "1"), throwsA(isA())); + }); + }); + + // makeDonation + group("Make Donation", () { + test("should return Create User Response when the call is successful", + () async { + setUpMockHttpMakeDonation(); + final result = await campaignRemoteDataSourceImpl.makeDonation( + campaignId: "1", + amount: "1", + ); + expect(result, isA()); + }); + + test("should throw ServerException when the call is unsuccessful", + () async { + when(() => mockNetworkProvider.call( + path: EndpointManager.makeDonation, + method: RequestMethod.post, + body: { + "campaign_id": "1", + "amount": "1", + }, + )).thenAnswer((_) async { + return Response( + requestOptions: RequestOptions(path: EndpointManager.makeDonation), + data: json.decode(fixture('campaign_failed_response.json')), + statusCode: 400); + }); + final call = campaignRemoteDataSourceImpl.makeDonation; + expect(() => call(campaignId: "1", amount: "1"), + throwsA(isA())); + }); + }); + + // createDonation +} diff --git a/test/feature/home/data/repositories/campaign_repository_test.dart b/test/feature/home/data/repositories/campaign_repository_test.dart new file mode 100644 index 0000000..b229647 --- /dev/null +++ b/test/feature/home/data/repositories/campaign_repository_test.dart @@ -0,0 +1,261 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/home/data/data_source/campaign_remote_date_source.dart'; +import 'package:defiraiser_mobile/features/home/data/repositories/campaign_repository.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/campaign_categories_entity/campaign_category_entities.dart' + as campaign_categories; +import 'package:defiraiser_mobile/features/home/domain/entities/campaigns/campaigns_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/donors_entity/donors_entity.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class MockCampaignRemoteDataSource extends Mock + implements CampaignRemoteDataSource {} + +void main() { + late MockCampaignRemoteDataSource mockRemoteDataSource; + late ICampaignRepository campaignRepositoryImpl; + late BaseEntity tBaseResponse; + late DonorsEntity tDonorsResponse; + late CampaignResponse tCampaignResponse; + late campaign_categories.CampaignCategories tCampaignCategoriesResponse; + + setUpAll(() { + mockRemoteDataSource = MockCampaignRemoteDataSource(); + campaignRepositoryImpl = ICampaignRepository( + remoteDataSource: mockRemoteDataSource, + ); + + tBaseResponse = const BaseEntity( + message: "success", + data: "Passed", + status: 200, + ); + + tDonorsResponse = const DonorsEntity( + data: [ + Donors( + amount: 0, + donor: "test", + image: "test", + username: "test", + ), + ], + message: "success", + status: 200, + ); + + tCampaignCategoriesResponse = campaign_categories.CampaignCategories( + data: [ + campaign_categories.Datum( + id: "1", + name: "test", + description: "test", + image: "test", + ) + ], + message: "success", + status: 200, + ); + + tCampaignResponse = const CampaignResponse( + data: [ + Datum( + campaignId: "test", + title: "test", + description: "test", + deadline: "test", + goal: 0, + image: "test", + id: 0, + owner: "test", + totalAmountDonated: 0, + totalNumber: 0, + user: [ + User( + address: "test", + username: "test", + avatar: "test", + email: "test", + ), + ], + donations: [ + Donation( + amount: 0, + donor: "test", + image: "test", + username: "test", + ), + ], + ) + ], + message: "success", + status: 200, + ); + }); + + group("should get campaigns", () { + test('should get the user info after you create account', () async { + // arrange + when(() => mockRemoteDataSource.getCampaigns()) + .thenAnswer((_) async => tCampaignResponse); + + // act + final result = await campaignRepositoryImpl.getCampaigns(); + + // assert + expect(result, Right(tCampaignResponse)); + verify(() => mockRemoteDataSource.getCampaigns()); + verifyNoMoreInteractions(mockRemoteDataSource); + }); + }); + + // getCategories test + group("should get categories", () { + test('should get the user info after you create account', () async { + // arrange + when(() => mockRemoteDataSource.getCategories()) + .thenAnswer((_) async => tCampaignCategoriesResponse); + + // act + final result = await campaignRepositoryImpl.getCategories(); + + // assert + expect(result, Right(tCampaignCategoriesResponse)); + verify(() => mockRemoteDataSource.getCategories()); + verifyNoMoreInteractions(mockRemoteDataSource); + }); + }); + + // getMyCampaigns test + group("should get my campaigns", () { + test('should get the user info after you create account', () async { + // arrange + when(() => mockRemoteDataSource.getMyCampaigns()) + .thenAnswer((_) async => tCampaignResponse); + + // act + final result = await campaignRepositoryImpl.getMyCampaigns(); + + // assert + expect(result, Right(tCampaignResponse)); + verify(() => mockRemoteDataSource.getMyCampaigns()); + verifyNoMoreInteractions(mockRemoteDataSource); + }); + }); + + // getCampaignsByCategory test + group("should get campaigns by category", () { + test('should get the user info after you create account', () async { + // arrange + when(() => mockRemoteDataSource.getCampaignsByCategory(id: "1")) + .thenAnswer((_) async => tCampaignResponse); + + // act + final result = + await campaignRepositoryImpl.getCampaignsByCategory(id: "1"); + + // assert + expect(result, Right(tCampaignResponse)); + verify(() => mockRemoteDataSource.getCampaignsByCategory(id: "1")); + verifyNoMoreInteractions(mockRemoteDataSource); + }); + }); + + // getCurrentEthPrice test + group("should get current eth price", () { + test('should get the user info after you create account', () async { + // arrange + when(() => mockRemoteDataSource.getCurrentEthPrice()) + .thenAnswer((_) async => tBaseResponse); + + // act + final result = await campaignRepositoryImpl.getCurrentEthPrice(); + + // assert + expect(result, Right(tBaseResponse)); + verify(() => mockRemoteDataSource.getCurrentEthPrice()); + verifyNoMoreInteractions(mockRemoteDataSource); + }); + }); + + // makeDonation test + group("should make donation", () { + test('should get the user info after you create account', () async { + // arrange + when(() => mockRemoteDataSource.makeDonation( + campaignId: "1", + amount: "1", + )).thenAnswer((_) async => tBaseResponse); + + // act + final result = await campaignRepositoryImpl.makeDonation( + campaignId: "1", + amount: "1", + ); + + // assert + expect(result, Right(tBaseResponse)); + verify(() => mockRemoteDataSource.makeDonation( + campaignId: "1", + amount: "1", + )); + verifyNoMoreInteractions(mockRemoteDataSource); + }); + }); + + // getDonors test + group("should get donors", () { + test('should get the user info after you create account', () async { + // arrange + when(() => mockRemoteDataSource.getDonors(campaignId: "1")) + .thenAnswer((_) async => tDonorsResponse); + + // act + final result = await campaignRepositoryImpl.getDonors(campaignId: "1"); + + // assert + expect(result, Right(tDonorsResponse)); + verify(() => mockRemoteDataSource.getDonors(campaignId: "1")); + verifyNoMoreInteractions(mockRemoteDataSource); + }); + }); + + // createDonation test + // group("should create donation", () { + // test('should get the user info after you create account', () async { + // // arrange + // when(() => mockRemoteDataSource.createDonation( + // category: "test", + // deadline: "test", + // description: "test", + // images: File("test"), + // title: "test", + // amount: "1", + // )).thenAnswer((_) async => tBaseResponse); + + // // act + // final result = await campaignRepositoryImpl.createDonation( + // category: "test", + // deadline: "test", + // description: "test", + // images: File("test"), + // title: "test", + // amount: "1", + // ); + + // // assert + // expect(result, Right(tBaseResponse)); + // verify(() => mockRemoteDataSource.createDonation( + // category: "test", + // deadline: "test", + // description: "test", + // images: File("test"), + // title: "test", + // amount: "1", + // )); + + // verifyNoMoreInteractions(mockRemoteDataSource); + // }); + // }); +} diff --git a/test/feature/home/domain/entities/campaign/campaigns_entity_test.dart b/test/feature/home/domain/entities/campaign/campaigns_entity_test.dart new file mode 100644 index 0000000..fb89dad --- /dev/null +++ b/test/feature/home/domain/entities/campaign/campaigns_entity_test.dart @@ -0,0 +1,73 @@ +import 'dart:convert'; + +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/campaigns/campaigns_entity.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../../../../fixture/fixture_reader.dart'; + +void main() { + final tResponse = CampaignResponse( + data: [ + Datum( + campaignId: "test", + title: "test", + description: "test", + deadline: "test", + goal: 0, + image: "test", + id: 0, + owner: "test", + totalAmountDonated: 0, + totalNumber: 0, + user: [ + User( + address: "test", + username: "test", + avatar: "test", + email: "test", + ), + ], + donations: [ + Donation( + amount: 0, + donor: "test", + image: "test", + username: "test", + ), + ], + ) + ], + message: "success", + status: 200, + ); + + final tFailedResponse = CampaignResponse( + message: "failed", + status: 400, + ); + + group("test response on successful user verified", () { + test("should return a valid model", () { + // arrange + final Map jsonMap = + json.decode(fixture("campaign_reesponse.json")); + // act + final result = CampaignResponse.fromJson(jsonMap); + // assert + expect(result, tResponse); + }); + }); + + group("test response on failed verify user account", () { + test("should return a valid model", () { + // arrange + final Map jsonMap = + json.decode(fixture("campaign_failed_response.json")); + // act + final result = CampaignResponse.fromJson(jsonMap); + // assert + expect(result, tFailedResponse); + }); + }); +} diff --git a/test/feature/home/domain/entities/campaign_categories_entity/campaign_categories_entity_test.dart b/test/feature/home/domain/entities/campaign_categories_entity/campaign_categories_entity_test.dart new file mode 100644 index 0000000..cba14a6 --- /dev/null +++ b/test/feature/home/domain/entities/campaign_categories_entity/campaign_categories_entity_test.dart @@ -0,0 +1,51 @@ +import 'dart:convert'; + +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/campaign_categories_entity/campaign_category_entities.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../../../../fixture/fixture_reader.dart'; + +void main() { + final tResponse = CampaignCategories( + data: [ + Datum( + id: "1", + name: "test", + description: "test", + image: "test", + ) + ], + message: "success", + status: 200, + ); + + final tFailedResponse = BaseEntity( + message: "failed", + status: 400, + ); + + group("test response on successful user verified", () { + test("should return a valid model", () { + // arrange + final Map jsonMap = + json.decode(fixture("campaign_categories_response.json")); + // act + final result = CampaignCategories.fromJson(jsonMap); + // assert + expect(result, tResponse); + }); + }); + + group("test response on failed verify user account", () { + test("should return a valid model", () { + // arrange + final Map jsonMap = + json.decode(fixture("base_response_failed.json")); + // act + final result = BaseEntity.fromJson(jsonMap); + // assert + expect(result, tFailedResponse); + }); + }); +} diff --git a/test/feature/home/domain/entities/donors_entity/donors_entity_test.dart b/test/feature/home/domain/entities/donors_entity/donors_entity_test.dart new file mode 100644 index 0000000..3d8f63d --- /dev/null +++ b/test/feature/home/domain/entities/donors_entity/donors_entity_test.dart @@ -0,0 +1,51 @@ +import 'dart:convert'; + +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/donors_entity/donors_entity.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../../../../fixture/fixture_reader.dart'; + +void main() { + final tResponse = DonorsEntity( + data: [ + Donors( + amount: 0, + donor: "test", + image: "test", + username: "test", + ), + ], + message: "success", + status: 200, + ); + + final tFailedResponse = DonorsEntity( + message: "failed", + status: 400, + ); + + group("test response on successful user verified", () { + test("should return a valid model", () { + // arrange + final Map jsonMap = + json.decode(fixture("donors_response.json")); + // act + final result = DonorsEntity.fromJson(jsonMap); + // assert + expect(result, tResponse); + }); + }); + + group("test response on failed verify user account", () { + test("should return a valid model", () { + // arrange + final Map jsonMap = + json.decode(fixture("campaign_failed_response.json")); + // act + final result = DonorsEntity.fromJson(jsonMap); + // assert + expect(result, tFailedResponse); + }); + }); +} diff --git a/test/feature/home/domain/usecases/campaign_catergory_usecase_test.dart b/test/feature/home/domain/usecases/campaign_catergory_usecase_test.dart new file mode 100644 index 0000000..857d240 --- /dev/null +++ b/test/feature/home/domain/usecases/campaign_catergory_usecase_test.dart @@ -0,0 +1,73 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/core/usecases/usecases.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/campaign_categories_entity/campaign_category_entities.dart'; +import 'package:defiraiser_mobile/features/home/domain/repositories/campaign_repository.dart'; +import 'package:defiraiser_mobile/features/home/domain/usecases/campaign_catergory_usecase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'campaign_catergory_usecase_test.mocks.dart'; + +@GenerateMocks([CampaignRepository]) +void main() { + late CampaignCategoryUseCase usecase; + late MockCampaignRepository mockCampaignRepository; + late CampaignCategories tResponse; + + setUp(() { + mockCampaignRepository = MockCampaignRepository(); + usecase = CampaignCategoryUseCase(mockCampaignRepository); + tResponse = CampaignCategories( + data: [ + Datum( + id: "1", + name: "test", + description: "test", + image: "test", + ) + ], + message: "success", + status: 200, + ); + }); + + final tFailedResponse = CreateAccountResponse( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + test("should get the user info after you create account", () async { + // arrange + when(mockCampaignRepository.getCategories()) + .thenAnswer((_) async => Right(tResponse)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Right(tResponse)); + verify(mockCampaignRepository.getCategories()); + verifyNoMoreInteractions(mockCampaignRepository); + }); + + test('should not get the user info when create account fails', () async { + // getCategories + when(mockCampaignRepository.getCategories()) + .thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Left(failure)); + verify(mockCampaignRepository.getCategories()); + verifyNoMoreInteractions(mockCampaignRepository); + }); +} diff --git a/test/feature/home/domain/usecases/campaign_catergory_usecase_test.mocks.dart b/test/feature/home/domain/usecases/campaign_catergory_usecase_test.mocks.dart new file mode 100644 index 0000000..387eb7e --- /dev/null +++ b/test/feature/home/domain/usecases/campaign_catergory_usecase_test.mocks.dart @@ -0,0 +1,242 @@ +// Mocks generated by Mockito 5.4.2 from annotations +// in defiraiser_mobile/test/feature/home/domain/usecases/campaign_catergory_usecase_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i4; +import 'dart:io' as _i10; + +import 'package:dartz/dartz.dart' as _i2; +import 'package:defiraiser_mobile/core/network/api_error.dart' as _i5; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart' + as _i8; +import 'package:defiraiser_mobile/features/home/domain/entities/campaign_categories_entity/campaign_category_entities.dart' + as _i6; +import 'package:defiraiser_mobile/features/home/domain/entities/campaigns/campaigns_entity.dart' + as _i7; +import 'package:defiraiser_mobile/features/home/domain/entities/donors_entity/donors_entity.dart' + as _i9; +import 'package:defiraiser_mobile/features/home/domain/repositories/campaign_repository.dart' + as _i3; +import 'package:mockito/mockito.dart' as _i1; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class + +class _FakeEither_0 extends _i1.SmartFake implements _i2.Either { + _FakeEither_0( + Object parent, + Invocation parentInvocation, + ) : super( + parent, + parentInvocation, + ); +} + +/// A class which mocks [CampaignRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCampaignRepository extends _i1.Mock + implements _i3.CampaignRepository { + MockCampaignRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i4.Future<_i2.Either<_i5.ApiError, _i6.CampaignCategories>> + getCategories() => (super.noSuchMethod( + Invocation.method( + #getCategories, + [], + ), + returnValue: _i4 + .Future<_i2.Either<_i5.ApiError, _i6.CampaignCategories>>.value( + _FakeEither_0<_i5.ApiError, _i6.CampaignCategories>( + this, + Invocation.method( + #getCategories, + [], + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i6.CampaignCategories>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>> getCampaigns() => + (super.noSuchMethod( + Invocation.method( + #getCampaigns, + [], + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.CampaignResponse>( + this, + Invocation.method( + #getCampaigns, + [], + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>> getMyCampaigns() => + (super.noSuchMethod( + Invocation.method( + #getMyCampaigns, + [], + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.CampaignResponse>( + this, + Invocation.method( + #getMyCampaigns, + [], + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>> getDonations() => + (super.noSuchMethod( + Invocation.method( + #getDonations, + [], + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.CampaignResponse>( + this, + Invocation.method( + #getDonations, + [], + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>> + getCampaignsByCategory({required String? id}) => (super.noSuchMethod( + Invocation.method( + #getCampaignsByCategory, + [], + {#id: id}, + ), + returnValue: _i4 + .Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>>.value( + _FakeEither_0<_i5.ApiError, _i7.CampaignResponse>( + this, + Invocation.method( + #getCampaignsByCategory, + [], + {#id: id}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i7.CampaignResponse>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> getCurrentEthPrice() => + (super.noSuchMethod( + Invocation.method( + #getCurrentEthPrice, + [], + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #getCurrentEthPrice, + [], + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> makeDonation({ + required String? campaignId, + required String? amount, + }) => + (super.noSuchMethod( + Invocation.method( + #makeDonation, + [], + { + #campaignId: campaignId, + #amount: amount, + }, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #makeDonation, + [], + { + #campaignId: campaignId, + #amount: amount, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i9.DonorsEntity>> getDonors( + {required String? campaignId}) => + (super.noSuchMethod( + Invocation.method( + #getDonors, + [], + {#campaignId: campaignId}, + ), + returnValue: + _i4.Future<_i2.Either<_i5.ApiError, _i9.DonorsEntity>>.value( + _FakeEither_0<_i5.ApiError, _i9.DonorsEntity>( + this, + Invocation.method( + #getDonors, + [], + {#campaignId: campaignId}, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i9.DonorsEntity>>); + @override + _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>> createDonation({ + required String? title, + required String? description, + required String? amount, + required String? category, + required String? deadline, + required _i10.File? images, + }) => + (super.noSuchMethod( + Invocation.method( + #createDonation, + [], + { + #title: title, + #description: description, + #amount: amount, + #category: category, + #deadline: deadline, + #images: images, + }, + ), + returnValue: _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>.value( + _FakeEither_0<_i5.ApiError, _i8.BaseEntity>( + this, + Invocation.method( + #createDonation, + [], + { + #title: title, + #description: description, + #amount: amount, + #category: category, + #deadline: deadline, + #images: images, + }, + ), + )), + ) as _i4.Future<_i2.Either<_i5.ApiError, _i8.BaseEntity>>); +} diff --git a/test/feature/home/domain/usecases/create_donation_usecase_test.dart b/test/feature/home/domain/usecases/create_donation_usecase_test.dart new file mode 100644 index 0000000..509577f --- /dev/null +++ b/test/feature/home/domain/usecases/create_donation_usecase_test.dart @@ -0,0 +1,116 @@ +import 'dart:io'; + +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart'; +import 'package:defiraiser_mobile/features/home/domain/repositories/campaign_repository.dart'; +import 'package:defiraiser_mobile/features/home/domain/usecases/create_donation_usecase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'campaign_catergory_usecase_test.mocks.dart'; + +@GenerateMocks([CampaignRepository]) +void main() { + late CreateDonationUsecase usecase; + late MockCampaignRepository mockCampaignRepository; + late String tAmount; + late String tCategory; + late String tDescription; + late String tTitle; + late String tDeadline; + late File tImages; + late BaseEntity tResponse; + + setUp(() { + mockCampaignRepository = MockCampaignRepository(); + usecase = CreateDonationUsecase(mockCampaignRepository); + tAmount = "0.1"; + tCategory = "test"; + tDescription = "test"; + tTitle = "test"; + tDeadline = "2023-09-20T14:08:19+01:00"; + tImages = File("test"); + + tResponse = const BaseEntity(data: "test", message: "success", status: 200); + }); + + final tFailedResponse = CreateAccountResponse( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + test("should get the user info after you create account", () async { + // arrange + when(mockCampaignRepository.createDonation( + amount: tAmount, + category: tCategory, + description: tDescription, + title: tTitle, + deadline: tDeadline, + images: tImages, + )).thenAnswer((_) async => Right(tResponse)); + + // act + final result = await usecase.call(CreateDonationParams( + amount: tAmount, + category: tCategory, + description: tDescription, + title: tTitle, + deadline: tDeadline, + images: tImages, + )); + + // assert + expect(result, Right(tResponse)); + verify(mockCampaignRepository.createDonation( + amount: tAmount, + category: tCategory, + description: tDescription, + title: tTitle, + deadline: tDeadline, + images: tImages, + )); + verifyNoMoreInteractions(mockCampaignRepository); + }); + + test('should not get the user info when create account fails', () async { + // arrange + when(mockCampaignRepository.createDonation( + amount: tAmount, + category: tCategory, + description: tDescription, + title: tTitle, + deadline: tDeadline, + images: tImages, + )).thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(CreateDonationParams( + amount: tAmount, + category: tCategory, + description: tDescription, + title: tTitle, + deadline: tDeadline, + images: tImages, + )); + + // assert + expect(result, Left(failure)); + verify(mockCampaignRepository.createDonation( + amount: tAmount, + category: tCategory, + description: tDescription, + title: tTitle, + deadline: tDeadline, + images: tImages, + )); + verifyNoMoreInteractions(mockCampaignRepository); + }); +} diff --git a/test/feature/home/domain/usecases/current_eth_price_usecases_test.dart b/test/feature/home/domain/usecases/current_eth_price_usecases_test.dart new file mode 100644 index 0000000..35a0b6e --- /dev/null +++ b/test/feature/home/domain/usecases/current_eth_price_usecases_test.dart @@ -0,0 +1,67 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/core/usecases/usecases.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart'; +import 'package:defiraiser_mobile/features/home/domain/repositories/campaign_repository.dart'; +import 'package:defiraiser_mobile/features/home/domain/usecases/current_eth_price_usecases.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'campaign_catergory_usecase_test.mocks.dart'; + +@GenerateMocks([CampaignRepository]) +void main() { + late CurrentEthPriceUsecase usecase; + late MockCampaignRepository mockCampaignRepository; + late BaseEntity tResponse; + + setUp(() { + mockCampaignRepository = MockCampaignRepository(); + usecase = CurrentEthPriceUsecase(mockCampaignRepository); + tResponse = BaseEntity( + data: "2000", + message: "success", + status: 200, + ); + }); + + final tFailedResponse = CreateAccountResponse( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + + test("should get the user info after you create account", () async { + // arrange + when(mockCampaignRepository.getCurrentEthPrice()) + .thenAnswer((_) async => Right(tResponse)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Right(tResponse)); + verify(mockCampaignRepository.getCurrentEthPrice()); + verifyNoMoreInteractions(mockCampaignRepository); + }); + + test('should not get the user info when create account fails', () async { + // getCurrentEthPrice + when(mockCampaignRepository.getCurrentEthPrice()) + .thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Left(failure)); + verify(mockCampaignRepository.getCurrentEthPrice()); + verifyNoMoreInteractions(mockCampaignRepository); + }); +} diff --git a/test/feature/home/domain/usecases/get_campaign_by_category_usecase_test.dart b/test/feature/home/domain/usecases/get_campaign_by_category_usecase_test.dart new file mode 100644 index 0000000..9a227d6 --- /dev/null +++ b/test/feature/home/domain/usecases/get_campaign_by_category_usecase_test.dart @@ -0,0 +1,106 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/campaigns/campaigns_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/repositories/campaign_repository.dart'; +import 'package:defiraiser_mobile/features/home/domain/usecases/get_campaign_by_category_usecase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'campaign_catergory_usecase_test.mocks.dart'; + +@GenerateMocks([CampaignRepository]) +void main() { + late GetCampaignByCategoryUseCase usecase; + late MockCampaignRepository mockCampaignRepository; + late String tId; + late CampaignResponse tResponse; + + setUp(() { + mockCampaignRepository = MockCampaignRepository(); + usecase = GetCampaignByCategoryUseCase(mockCampaignRepository); + tId = "1"; + + tResponse = const CampaignResponse( + data: [ + Datum( + campaignId: "test", + title: "test", + description: "test", + deadline: "test", + goal: 0, + image: "test", + id: 0, + owner: "test", + totalAmountDonated: 0, + totalNumber: 0, + user: [ + User( + address: "test", + username: "test", + avatar: "test", + email: "test", + ), + ], + donations: [ + Donation( + amount: 0, + donor: "test", + image: "test", + username: "test", + ), + ], + ) + ], + message: "success", + status: 200, + ); + }); + + final tFailedResponse = CampaignResponse( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + test("should get the user info after you create account", () async { + // arrange + when(mockCampaignRepository.getCampaignsByCategory( + id: tId, + )).thenAnswer((_) async => Right(tResponse)); + + // act + final result = await usecase.call(CampaignByCategoryParams( + id: tId, + )); + + // assert + expect(result, Right(tResponse)); + verify(mockCampaignRepository.getCampaignsByCategory( + id: tId, + )); + verifyNoMoreInteractions(mockCampaignRepository); + }); + + test('should not get the user info when create account fails', () async { + // arrange + when(mockCampaignRepository.getCampaignsByCategory( + id: tId, + )).thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(CampaignByCategoryParams( + id: tId, + )); + + // assert + expect(result, Left(failure)); + verify(mockCampaignRepository.getCampaignsByCategory( + id: tId, + )); + verifyNoMoreInteractions(mockCampaignRepository); + }); +} diff --git a/test/feature/home/domain/usecases/get_campaigns_test.dart b/test/feature/home/domain/usecases/get_campaigns_test.dart new file mode 100644 index 0000000..a61a5b0 --- /dev/null +++ b/test/feature/home/domain/usecases/get_campaigns_test.dart @@ -0,0 +1,95 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/core/usecases/usecases.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/campaigns/campaigns_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/repositories/campaign_repository.dart'; +import 'package:defiraiser_mobile/features/home/domain/usecases/get_campaigns.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'campaign_catergory_usecase_test.mocks.dart'; + +@GenerateMocks([CampaignRepository]) +void main() { + late GetCampaignsUseCase usecase; + late MockCampaignRepository mockCampaignRepository; + late CampaignResponse tResponse; + + setUp(() { + mockCampaignRepository = MockCampaignRepository(); + usecase = GetCampaignsUseCase(mockCampaignRepository); + tResponse = const CampaignResponse( + data: [ + Datum( + campaignId: "test", + title: "test", + description: "test", + deadline: "test", + goal: 0, + image: "test", + id: 0, + owner: "test", + totalAmountDonated: 0, + totalNumber: 0, + user: [ + User( + address: "test", + username: "test", + avatar: "test", + email: "test", + ), + ], + donations: [ + Donation( + amount: 0, + donor: "test", + image: "test", + username: "test", + ), + ], + ) + ], + message: "success", + status: 200, + ); + }); + + final tFailedResponse = CreateAccountResponse( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + test("should get the user info after you create account", () async { + // arrange + when(mockCampaignRepository.getCampaigns()) + .thenAnswer((_) async => Right(tResponse)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Right(tResponse)); + verify(mockCampaignRepository.getCampaigns()); + verifyNoMoreInteractions(mockCampaignRepository); + }); + + test('should not get the user info when create account fails', () async { + // getCampaigns + when(mockCampaignRepository.getCampaigns()) + .thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Left(failure)); + verify(mockCampaignRepository.getCampaigns()); + verifyNoMoreInteractions(mockCampaignRepository); + }); +} diff --git a/test/feature/home/domain/usecases/get_donations_usecase_test.dart b/test/feature/home/domain/usecases/get_donations_usecase_test.dart new file mode 100644 index 0000000..261c2c9 --- /dev/null +++ b/test/feature/home/domain/usecases/get_donations_usecase_test.dart @@ -0,0 +1,95 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/core/usecases/usecases.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/register_entity/create_account_response.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/campaigns/campaigns_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/repositories/campaign_repository.dart'; +import 'package:defiraiser_mobile/features/home/domain/usecases/get_donations_usecase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'campaign_catergory_usecase_test.mocks.dart'; + +@GenerateMocks([CampaignRepository]) +void main() { + late GetDonationsUseCase usecase; + late MockCampaignRepository mockCampaignRepository; + late CampaignResponse tResponse; + + setUp(() { + mockCampaignRepository = MockCampaignRepository(); + usecase = GetDonationsUseCase(mockCampaignRepository); + tResponse = const CampaignResponse( + data: [ + Datum( + campaignId: "test", + title: "test", + description: "test", + deadline: "test", + goal: 0, + image: "test", + id: 0, + owner: "test", + totalAmountDonated: 0, + totalNumber: 0, + user: [ + User( + address: "test", + username: "test", + avatar: "test", + email: "test", + ), + ], + donations: [ + Donation( + amount: 0, + donor: "test", + image: "test", + username: "test", + ), + ], + ) + ], + message: "success", + status: 200, + ); + }); + + final tFailedResponse = CreateAccountResponse( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + test("should get the user info after you create account", () async { + // arrange + when(mockCampaignRepository.getDonations()) + .thenAnswer((_) async => Right(tResponse)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Right(tResponse)); + verify(mockCampaignRepository.getDonations()); + verifyNoMoreInteractions(mockCampaignRepository); + }); + + test('should not get the user info when create account fails', () async { + // getDonations + when(mockCampaignRepository.getDonations()) + .thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(NoParams()); + + // assert + expect(result, Left(failure)); + verify(mockCampaignRepository.getDonations()); + verifyNoMoreInteractions(mockCampaignRepository); + }); +} diff --git a/test/feature/home/domain/usecases/get_donors_usecase_test.dart b/test/feature/home/domain/usecases/get_donors_usecase_test.dart new file mode 100644 index 0000000..b0be52a --- /dev/null +++ b/test/feature/home/domain/usecases/get_donors_usecase_test.dart @@ -0,0 +1,84 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/features/home/domain/entities/donors_entity/donors_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/repositories/campaign_repository.dart'; +import 'package:defiraiser_mobile/features/home/domain/usecases/get_donors_usecase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'campaign_catergory_usecase_test.mocks.dart'; + +@GenerateMocks([CampaignRepository]) +void main() { + late GetDonorsUsecase usecase; + late MockCampaignRepository mockCampaignRepository; + late String tId; + late DonorsEntity tResponse; + + setUp(() { + mockCampaignRepository = MockCampaignRepository(); + usecase = GetDonorsUsecase(mockCampaignRepository); + tId = "1"; + + tResponse = const DonorsEntity( + data: [ + Donors( + amount: 0, + donor: "test", + image: "test", + username: "test", + ), + ], + message: "success", + status: 200, + ); + }); + + final tFailedResponse = DonorsEntity( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + test("should get the user info after you create account", () async { + // arrange + when(mockCampaignRepository.getDonors( + campaignId: tId, + )).thenAnswer((_) async => Right(tResponse)); + + // act + final result = await usecase.call(DonorsParams( + id: tId, + )); + + // assert + expect(result, Right(tResponse)); + verify(mockCampaignRepository.getDonors( + campaignId: tId, + )); + verifyNoMoreInteractions(mockCampaignRepository); + }); + + test('should not get the user info when create account fails', () async { + // arrange + when(mockCampaignRepository.getDonors( + campaignId: tId, + )).thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(DonorsParams( + id: tId, + )); + + // assert + expect(result, Left(failure)); + verify(mockCampaignRepository.getDonors( + campaignId: tId, + )); + verifyNoMoreInteractions(mockCampaignRepository); + }); +} diff --git a/test/feature/home/domain/usecases/make_donation_usecase_test.dart b/test/feature/home/domain/usecases/make_donation_usecase_test.dart new file mode 100644 index 0000000..aeedece --- /dev/null +++ b/test/feature/home/domain/usecases/make_donation_usecase_test.dart @@ -0,0 +1,85 @@ +import 'package:dartz/dartz.dart'; +import 'package:defiraiser_mobile/core/network/api_error.dart'; +import 'package:defiraiser_mobile/features/authentication/domain/entities/base_entity/base_entity.dart'; +import 'package:defiraiser_mobile/features/home/domain/repositories/campaign_repository.dart'; +import 'package:defiraiser_mobile/features/home/domain/usecases/make_donation_usecase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; + +import 'campaign_catergory_usecase_test.mocks.dart'; + +@GenerateMocks([CampaignRepository]) +void main() { + late MakeDonationUsecase usecase; + late MockCampaignRepository mockCampaignRepository; + late String tId; + late String tAmount; + late BaseEntity tResponse; + + setUp(() { + mockCampaignRepository = MockCampaignRepository(); + usecase = MakeDonationUsecase(mockCampaignRepository); + tId = "1"; + tAmount = "1000"; + + tResponse = const BaseEntity( + data: "2000", + message: "success", + status: 200, + ); + }); + + final tFailedResponse = BaseEntity( + message: "error message", + status: 400, + ); + + final failure = ApiError( + errorCode: tFailedResponse.status.toString(), + errorMessage: tFailedResponse.message); + + test("should get the user info after you create account", () async { + // arrange + when(mockCampaignRepository.makeDonation( + campaignId: tId, + amount: tAmount, + )).thenAnswer((_) async => Right(tResponse)); + + // act + final result = await usecase.call(MakeDonationParams( + campaignId: tId, + amount: tAmount, + )); + + // assert + expect(result, Right(tResponse)); + verify(mockCampaignRepository.makeDonation( + campaignId: tId, + amount: tAmount, + )); + verifyNoMoreInteractions(mockCampaignRepository); + }); + + test('should not get the user info when create account fails', () async { + // arrange + when(mockCampaignRepository.makeDonation( + campaignId: tId, + amount: tAmount, + )).thenAnswer((_) async => Left(failure)); + + // act + final result = await usecase.call(MakeDonationParams( + campaignId: tId, + amount: tAmount, + )); + + // assert + expect(result, Left(failure)); + verify(mockCampaignRepository.makeDonation( + campaignId: tId, + amount: tAmount, + )); + verifyNoMoreInteractions(mockCampaignRepository); + }); +} diff --git a/test/fixture/campaign_categories_response.json b/test/fixture/campaign_categories_response.json new file mode 100644 index 0000000..8530d6b --- /dev/null +++ b/test/fixture/campaign_categories_response.json @@ -0,0 +1,12 @@ +{ + "data": [ + { + "description": "test", + "id": "1", + "image": "test", + "name": "test" + } + ], + "message": "success", + "status": 200 +} diff --git a/test/fixture/campaign_failed_response.json b/test/fixture/campaign_failed_response.json new file mode 100644 index 0000000..5092deb --- /dev/null +++ b/test/fixture/campaign_failed_response.json @@ -0,0 +1,5 @@ +{ + "message": "failed", + "data": null, + "status": 400 +} diff --git a/test/fixture/campaign_reesponse.json b/test/fixture/campaign_reesponse.json new file mode 100644 index 0000000..553f052 --- /dev/null +++ b/test/fixture/campaign_reesponse.json @@ -0,0 +1,34 @@ +{ + "data": [ + { + "campaign_id": "test", + "deadline": "test", + "description": "test", + "donations": [ + { + "amount": 0, + "donor": "test", + "image": "test", + "username": "test" + } + ], + "goal": 0, + "id": 0, + "image": "test", + "owner": "test", + "title": "test", + "total_amount_donated": 0, + "total_number": 0, + "user": [ + { + "address": "test", + "avatar": "test", + "email": "test", + "username": "test" + } + ] + } + ], + "message": "success", + "status": 200 +} diff --git a/test/fixture/donors_response.json b/test/fixture/donors_response.json new file mode 100644 index 0000000..7d485e4 --- /dev/null +++ b/test/fixture/donors_response.json @@ -0,0 +1,12 @@ +{ + "data": [ + { + "amount": 0, + "donor": "test", + "image": "test", + "username": "test" + } + ], + "message": "success", + "status": 200 + } \ No newline at end of file From faaf551d891e1a533c4c00c27d61b8e4fd3cb086 Mon Sep 17 00:00:00 2001 From: demola234 Date: Sun, 27 Aug 2023 05:28:35 +0100 Subject: [PATCH 2/2] ci cd implementation --- .github/workflows/main.yml | 34 ++++++++++++++++++++++++++++++++++ README.md | 18 +++--------------- 2 files changed, 37 insertions(+), 15 deletions(-) create mode 100644 .github/workflows/main.yml diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..8ead5bb --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,34 @@ +name: Main + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + name: unit-test + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v1 + with: + java-version: "12.x" + - uses: subosito/flutter-action@v1.5.3 + with: + flutter_channel: stable + flutter_version: 3.0.0 + - name: Install dependencies + run: flutter pub get + - name: Build APK + run: flutter build apk --split-per-abi + - name: Run unit tests + run: flutter test --coverage + - name: Upload to code coverage + uses: codecov/codecov-action@v1.2.2 + with: + token: ${{secrets.CODECOV_TOKEN}} + file: coverage/lcov.info diff --git a/README.md b/README.md index 6e82c7b..9b9fca6 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,4 @@ -# defiraiser_mobile +# DefiFundr -A new Flutter project. - -## Getting Started - -This project is a starting point for a Flutter application. - -A few resources to get you started if this is your first Flutter project: - -- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) -- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) - -For help getting started with Flutter development, view the -[online documentation](https://docs.flutter.dev/), which offers tutorials, -samples, guidance on mobile development, and a full API reference. +[![CI](https://github.com/demola234/tdd_weather/actions/workflows/cl.yml/badge.svg)](https://github.com/demola234/tdd_weather/actions/workflows/cl.yml) +[![codecov](https://codecov.io/gh/demola234/tdd_weather/branch/main/graph/badge.svg?token=IPGEQHNLN2)](https://codecov.io/gh/demola234/tdd_weather)